问:
Procedure in if loop not working even though condition is met
I have made this code to emulate a rock paper scissors game. I have a procedure which has the main game, and when I run this by itself without the if loop at the end, it works. However, when I try to validate whether or not the user entry is numerical, it does not print the correct message. Here is the full code:

```<code>import random
def game(choice):
    number = random.randint(1,3)
    if choice == 1 and number == 2:
        print("You lose.")
    if choice == 1 and number ==3:
        print("You win.")
    if choice == 1 and number == 1:
        print("It is a draw")
    if choice == 2 and number == 3:
        print("You lose.")
    if choice == 2 and number ==1:
        print("You win.")
    if choice == 2 and number == 2:
        print("It is a draw")
    if choice == 3 and number == 1:
        print("You lose.")
    if choice == 3 and number ==2:
        print("You win.")
    if choice == 3 and number == 3:
        print("It is a draw")
x = input("Choose 1 (rock), 2 (paper) or 3 (scissors).")
digit = x.isdigit()
if digit == True:
    game(x)
</code>```

By the way, there is no error message, the procedure just does not work!

答:
First of all, there are a few issues with your code. If you wish to ignore, skip to Error Handling for answer to your question. You will find it in there.

Naming Variables

Your variables do not tell a person reading your code what they are. If you showed someone the word number, they would not know that it is what the computer chooses in rock paper scissors. Same with choice (who's choice?) and even more so x. So why don't we name them computer_choice, user_choice and choice respectively. I know these are a bit longer to type, but it is worth sacrificing a few extra keystrokes for a bit more clarity. Also notice that I used snake_case name formatting as per usual Python standards.

Repetitiveness/ game()

Your game function could do with a bit of re-doing. All you need is a general 'formula' for winning and losing. In this case, losing is when (thanks to @Brett Beatty) if computer_choice == (user_choice + 1) % 3, drawing is when computer_choice == user_choice and winning is everything else. Also, when your code is being played, the user only knows if they have won or lost, and not what the computer chose, so to add a bit more clarity, I added a list and another print() line. This feature is also useful to test code. Additionally, use zero-based variable values, such as in the computer_choice and user_choice variables. This is useful when converting values to list indexes. Below is a revised version of your code that i have made which includes all points above (I have also made it a function, as you will see below - I just think it looks better):

```<code>import random

def game(user_choice):
    user_choice -= 1
    rps = ["Rock", "Paper", "Scissors"]
    computer_choice = random.randint(0, 2)
    print("You: {} Computer: {}".format(rps[user_choice], rps[computer_choice]))
    if user_choice == computer_choice:
        return 0
    elif computer_choice == (user_choice + 1) % 3:
        return -1
    else:
        return 1
</code>```

Error Handling

To make sure the user enters an integer, you would have to add int() around the input statement. However, this alone would return ValueError if the value entered by the user is not an integer, and this is a problem. However, there is a way to fix this using try: except: else: blocks, as you will see below. This is what you would need to decide if the value is an integer, it also prints the correct message when it is not. I also think this is what you wanted for if digit == True(FYI you would only need if digit if you were to do it that way).

```<code>def main():
    while True:
        try:
            value = int(input("Choose 1 (rock), 2 (paper) or 3 (scissors):"))
        except ValueError: # If any part of the code in the try block raises a ValueError
            print("Not an integer")
        else:  # If error is not raised
            if not 1 <= value <= 3: # If value is not between 1 and 3
                print("Must be between 1 and 3")
            else:
                result = game(value) # sets result to return value from game()
                break
    if result == 1:
        print("You Win")
    elif result == -1:
        print("You Lose")
    else:
        print("It's a Draw")
</code>```

And Finally, the 'if loop'?

Let me just make this clear. There is no such thing as an if loop!!! An if statement runs code **ONCE** if a certain condition is True. I think what you want is a while loop. This runs code **REPEATEDLY** as long as a certain condition is True. In the code below, I created a while True loop, which runs the code each time the user types in "y", and breaks from the loop if not.

Also, use if __name__ == '__main__'. It exists in Python so that Python files can act as either reusable modules, or as standalone programs. It also looks more complex, if you want to look smart.

```<code>if __name__ == '__main__':
    while True:
        main()
        if input("Again? Yes(y) No(Anything else): ").lower() != 'y':
            break
</code>```

Example Output (ignore colours):

```<code>Choose 1 (rock), 2 (paper) or 3 (scissors):1
You: Rock Computer: Scissors
You Win
Again? Yes(y) No(Anything else): y
Choose 1 (rock), 2 (paper) or 3 (scissors):3
You: Scissors Computer: Scissors
It's a Draw
Again? Yes(y) No(Anything else): y
Choose 1 (rock), 2 (paper) or 3 (scissors):2
You: Paper Computer: Paper
It's a Draw
Again? Yes(y) No(Anything else): n

Process finished with exit code 0
</code>```

Also, for the OP, if you haven't already, I would recommend downloading Pycharm. It is completely free, and makes coding a lot easier. It also improves presentation too. It picks up on some of the things mentioned above, as well as keeping your code in line with PEP guidelines.

Body:
I have made this code to emulate a rock paper scissors game. I have a procedure which has the main game, and when I run this by itself without the if loop at the end, it works. However, when I try to validate whether or not the user entry is numerical, it does not print the correct message. Here is the full code:

import random
def game(choice):
    number = random.randint(1,3)
    if choice == 1 and number == 2:
        print("You lose.")
    if choice == 1 and number ==3:
        print("You win.")
    if choice == 1 and number == 1:
        print("It is a draw")
    if choice == 2 and number == 3:
        print("You lose.")
    if choice == 2 and number ==1:
        print("You win.")
    if choice == 2 and number == 2:
        print("It is a draw")
    if choice == 3 and number == 1:
        print("You lose.")
    if choice == 3 and number ==2:
        print("You win.")
    if choice == 3 and number == 3:
        print("It is a draw")
x = input("Choose 1 (rock), 2 (paper) or 3 (scissors).")
digit = x.isdigit()
if digit == True:
    game(x)

By the way, there is no error message, the procedure just does not work!

Body:
First of all, there are a few issues with your code. If you wish to ignore, skip to Error Handling for answer to your question. You will find it in there.

Naming Variables

Your variables do not tell a person reading your code what they are. If you showed someone the word number, they would not know that it is what the computer chooses in rock paper scissors. Same with choice (who's choice?) and even more so x. So why don't we name them computer_choice, user_choice and choice respectively. I know these are a bit longer to type, but it is worth sacrificing a few extra keystrokes for a bit more clarity. Also notice that I used snake_case name formatting as per usual Python standards.

Repetitiveness/ game()

Your game function could do with a bit of re-doing. All you need is a general 'formula' for winning and losing. In this case, losing is when (thanks to @Brett Beatty) if computer_choice == (user_choice + 1) % 3, drawing is when computer_choice == user_choice and winning is everything else. Also, when your code is being played, the user only knows if they have won or lost, and not what the computer chose, so to add a bit more clarity, I added a list and another print() line. This feature is also useful to test code. Additionally, use zero-based variable values, such as in the computer_choice and user_choice variables. This is useful when converting values to list indexes. Below is a revised version of your code that i have made which includes all points above (I have also made it a function, as you will see below - I just think it looks better):

import random

def game(user_choice):
    user_choice -= 1
    rps = ["Rock", "Paper", "Scissors"]
    computer_choice = random.randint(0, 2)
    print("You: {} Computer: {}".format(rps[user_choice], rps[computer_choice]))
    if user_choice == computer_choice:
        return 0
    elif computer_choice == (user_choice + 1) % 3:
        return -1
    else:
        return 1

Error Handling

To make sure the user enters an integer, you would have to add int() around the input statement. However, this alone would return ValueError if the value entered by the user is not an integer, and this is a problem. However, there is a way to fix this using try: except: else: blocks, as you will see below. This is what you would need to decide if the value is an integer, it also prints the correct message when it is not. I also think this is what you wanted for if digit == True(FYI you would only need if digit if you were to do it that way).

def main():
    while True:
        try:
            value = int(input("Choose 1 (rock), 2 (paper) or 3 (scissors):"))
        except ValueError: # If any part of the code in the try block raises a ValueError
            print("Not an integer")
        else:  # If error is not raised
            if not 1 <= value <= 3: # If value is not between 1 and 3
                print("Must be between 1 and 3")
            else:
                result = game(value) # sets result to return value from game()
                break
    if result == 1:
        print("You Win")
    elif result == -1:
        print("You Lose")
    else:
        print("It's a Draw")

And Finally, the 'if loop'?

Let me just make this clear. There is no such thing as an if loop!!! An if statement runs code **ONCE** if a certain condition is True. I think what you want is a while loop. This runs code **REPEATEDLY** as long as a certain condition is True. In the code below, I created a while True loop, which runs the code each time the user types in "y", and breaks from the loop if not.

Also, use if __name__ == '__main__'. It exists in Python so that Python files can act as either reusable modules, or as standalone programs. It also looks more complex, if you want to look smart.

if __name__ == '__main__':
    while True:
        main()
        if input("Again? Yes(y) No(Anything else): ").lower() != 'y':
            break

Example Output (ignore colours):

Choose 1 (rock), 2 (paper) or 3 (scissors):1
You: Rock Computer: Scissors
You Win
Again? Yes(y) No(Anything else): y
Choose 1 (rock), 2 (paper) or 3 (scissors):3
You: Scissors Computer: Scissors
It's a Draw
Again? Yes(y) No(Anything else): y
Choose 1 (rock), 2 (paper) or 3 (scissors):2
You: Paper Computer: Paper
It's a Draw
Again? Yes(y) No(Anything else): n

Process finished with exit code 0

Also, for the OP, if you haven't already, I would recommend downloading Pycharm. It is completely free, and makes coding a lot easier. It also improves presentation too. It picks up on some of the things mentioned above, as well as keeping your code in line with PEP guidelines.


来源: stackexchange

问:
How can I keep my database updating itself while no one is online (firebase)?
Imagine a browser game that users have their resources to build an army/walls etc., and those resources should be updated based on their buildings even when they're offline. How can I update this data when they're off (I'm using Firebase)? </p>

答:
Consider Firebase as strictly a storage medium - not a service which is running all the time.

That being said, have your app "calculate" the state changes which would have theoretically transpired while the user was "offline" when the user connects.

Besides, if you did have your app continually update the Firebase backend while the user was offline, you would likely incur some surprising costs: Firebase Pricing.

ContentLicense: CC BY-SA 3.0


问:
Best Solution For the Train Composition
Recently I answered My Online Interview test Wherein I was asked Following question

A TrainComposition is built by attaching and detaching wagons from the left and the right sides.

For example, if we start by attaching wagon 7 from the left followed by attaching wagon 13, again from the left, we get a composition of two wagons (13 and 7 from left to right). Now the first wagon that can be detached from the right is 7 and the first that can be detached from the left is 13. Implement a TrainComposition that models this problem.

I used doubly linked list to solve the issue

```<code>class Node

{
    protected int data;
    protected Node next, prev;
    /* Constructor */
    public Node()
    {
        next = null;
        prev = null;
        data = 0;
    }

    /* Constructor */

    public Node(int d, Node n, Node p)
    {
        data = d;
        next = n;
        prev = p;
    }

    /* Function to set link to next node */
    public void setLinkNext(Node n) {
        next = n;
    }
    /* Function to set link to previous node */
    public void setLinkPrev(Node p) {
        prev = p;
    }

    /* Funtion to get link to next node */

    public Node getLinkNext() {
        return next;
    }

    /* Function to get link to previous node */

    public Node getLinkPrev() {
        return prev;
    }

    /* Function to set data to node */
    public void setData(int d) {
        data = d;
    }

    /* Function to get data from node */

    public int getData() {
        return data;
    }
}

public class SortedSearch {
    protected Node start;
    protected Node end;
    public int size;
    /* Constructor */
    public SortedSearch()
    {
        start = null;
        end = null;
        size = 0;
    }
    public boolean isEmpty()
    {
        return start == null;
    }

    public int getSize()
    {
        return size;
    }

    public void attachWagonFromLeft(int wagonId) {
        Node nptr = new Node(wagonId, null, null);
        if (start == null)
        {
            start = nptr;
            end = start;
        }
        else
        {
            start.setLinkPrev(nptr);
            nptr.setLinkNext(start);
            start = nptr;
        }
        size++;
    }
    public void attachWagonFromRight(int wagonId) {
        Node nptr = new Node(wagonId, null, null);
        if (start == null)
        {
            start = nptr;
            end = start;
        }
        else
        {
            nptr.setLinkPrev(end);
            end.setLinkNext(nptr);
            end = nptr;
        }
        size++;
    }
    public int detachWagonFromLeft() {
        int value=0;
        if (size == 1)
        {
            value = start.getData();
            start = null;
            end = null;
            size = 0;
            return value;

        }
        value = start.getData();
        start = start.getLinkNext();
        start.setLinkPrev(null);
        size--;
        return value;
    }

    public int detachWagonFromRight() {
        int value=0;
            value = end.getData();
            end = end.getLinkPrev();
            end.setLinkNext(null);
            size-- ;
            return value;
    }

    public static void main(String[] args) {
        SortedSearch tree = new SortedSearch();
        tree.attachWagonFromLeft(7);
        tree.attachWagonFromLeft(13);
        tree.attachWagonFromLeft(12);
        tree.attachWagonFromLeft(10);
        tree.attachWagonFromLeft(6);
        tree.attachWagonFromLeft(4);
        tree.attachWagonFromLeft(3);
        tree.attachWagonFromLeft(2);
        System.out.println(tree.detachWagonFromRight()); // 7
        System.out.println(tree.detachWagonFromRight()); // 13
        System.out.println(tree.detachWagonFromRight()); // 7
        System.out.println(tree.detachWagonFromRight()); // 13
        System.out.println(tree.detachWagonFromRight()); // 7
        System.out.println(tree.detachWagonFromRight()); // 13

    }
}
</code>```

And tested it accordingly. But when submitted it said failed internal test cases, and the answer was marked wrong.
Can you please tell which is the best solution for this problem.

答:
```<code>import java.util.*;
public class TrainComposition {
    LinkedList<Integer> wagons = new LinkedList<Integer>();
  public static void main(String[] args) {

    TrainComposition tree = new TrainComposition();
    tree.attachWagonFromLeft(7);
    tree.attachWagonFromLeft(13);
    System.out.println(tree.detachWagonFromRight()); // 7
    System.out.println(tree.detachWagonFromLeft()); // 13
}

public void attachWagonFromLeft(int wagonId) {
    wagons.addFirst(wagonId);
   // throw new UnsupportedOperationException("Waiting to be implemented.");
}

public void attachWagonFromRight(int wagonId) {
    wagons.addLast(wagonId);
   // throw new UnsupportedOperationException("Waiting to be implemented.");
}

public int detachWagonFromLeft() {
    if (!wagons.isEmpty()) {
  return wagons.removeFirst();

   } else {
  throw new IndexOutOfBoundsException("No wagons available");
}
}
 public int detachWagonFromRight() {
    if (!wagons.isEmpty()) {
  return wagons.removeLast();

   } else {
  throw new IndexOutOfBoundsException("No wagons available");
}

}
</code>```

Title: Best Solution For the Train Composition

Body:
Recently I answered My Online Interview test Wherein I was asked Following question

A TrainComposition is built by attaching and detaching wagons from the left and the right sides.

For example, if we start by attaching wagon 7 from the left followed by attaching wagon 13, again from the left, we get a composition of two wagons (13 and 7 from left to right). Now the first wagon that can be detached from the right is 7 and the first that can be detached from the left is 13. Implement a TrainComposition that models this problem.

I used doubly linked list to solve the issue

class Node

{
    protected int data;
    protected Node next, prev;
    /* Constructor */
    public Node()
    {
        next = null;
        prev = null;
        data = 0;
    }

    /* Constructor */

    public Node(int d, Node n, Node p)
    {
        data = d;
        next = n;
        prev = p;
    }

    /* Function to set link to next node */
    public void setLinkNext(Node n) {
        next = n;
    }
    /* Function to set link to previous node */
    public void setLinkPrev(Node p) {
        prev = p;
    }

    /* Funtion to get link to next node */

    public Node getLinkNext() {
        return next;
    }

    /* Function to get link to previous node */

    public Node getLinkPrev() {
        return prev;
    }

    /* Function to set data to node */
    public void setData(int d) {
        data = d;
    }

    /* Function to get data from node */

    public int getData() {
        return data;
    }
}

public class SortedSearch {
    protected Node start;
    protected Node end;
    public int size;
    /* Constructor */
    public SortedSearch()
    {
        start = null;
        end = null;
        size = 0;
    }
    public boolean isEmpty()
    {
        return start == null;
    }

    public int getSize()
    {
        return size;
    }

    public void attachWagonFromLeft(int wagonId) {
        Node nptr = new Node(wagonId, null, null);
        if (start == null)
        {
            start = nptr;
            end = start;
        }
        else
        {
            start.setLinkPrev(nptr);
            nptr.setLinkNext(start);
            start = nptr;
        }
        size++;
    }
    public void attachWagonFromRight(int wagonId) {
        Node nptr = new Node(wagonId, null, null);
        if (start == null)
        {
            start = nptr;
            end = start;
        }
        else
        {
            nptr.setLinkPrev(end);
            end.setLinkNext(nptr);
            end = nptr;
        }
        size++;
    }
    public int detachWagonFromLeft() {
        int value=0;
        if (size == 1)
        {
            value = start.getData();
            start = null;
            end = null;
            size = 0;
            return value;

        }
        value = start.getData();
        start = start.getLinkNext();
        start.setLinkPrev(null);
        size--;
        return value;
    }

    public int detachWagonFromRight() {
        int value=0;
            value = end.getData();
            end = end.getLinkPrev();
            end.setLinkNext(null);
            size-- ;
            return value;
    }

    public static void main(String[] args) {
        SortedSearch tree = new SortedSearch();
        tree.attachWagonFromLeft(7);
        tree.attachWagonFromLeft(13);
        tree.attachWagonFromLeft(12);
        tree.attachWagonFromLeft(10);
        tree.attachWagonFromLeft(6);
        tree.attachWagonFromLeft(4);
        tree.attachWagonFromLeft(3);
        tree.attachWagonFromLeft(2);
        System.out.println(tree.detachWagonFromRight()); // 7
        System.out.println(tree.detachWagonFromRight()); // 13
        System.out.println(tree.detachWagonFromRight()); // 7
        System.out.println(tree.detachWagonFromRight()); // 13
        System.out.println(tree.detachWagonFromRight()); // 7
        System.out.println(tree.detachWagonFromRight()); // 13

    }
}

And tested it accordingly. But when submitted it said failed internal test cases, and the answer was marked wrong.
Can you please tell which is the best solution for this problem.


问:
Laravel phpunit drops database tables

I'm trying to test my app using phpunit with laravel but each time I run

unit test

```<code>vendor\bin\phpunit
</code>```

All tables in my database drop so I have to migrate each time I run a test

Have you encountered with similar issue  & how can I fix it ?

答:
Use a separate connection for tests. Add this connection to config/database.php config file:

```<code>'connections' => [

    'testing' => [
        'driver' => 'sqlite',
        'database' => ':memory:',
        'prefix' => '',
    ],
</code>```

Title: Laravel phpunit drops database tables

Body:
I'm trying to test my app using phpunit with laravel but each time I run

unit test

vendor\bin\phpunit

All tables in my database drop so I have to migrate each time I run a test

Have you encountered with similar issue  & how can I fix it ?

Body:
Use a separate connection for tests. Add this connection to config/database.php config file:

'connections' => [

    'testing' => [
        'driver' => 'sqlite',
        'database' => ':memory:',
        'prefix' => '',
    ],


问:
Good uses for Apache CollectionUtils
I found the CollectionUtils class a year or so ago and a few of the methods like, collect, and transform seem really cool, however, I have yet to find a use where it would not by syntactically cleaner and\or easier to just write the logic with a simple loop.

Has any found a unique\useful use for these methods (transform, predicatedCollection, collect, etc) e.g. the methods that take a transformer or predicate as an argument?

答:
I'm not sure I agree with your statement...

A simple loop adds complexity, and is less "readable and obvious" than a call with a sensible name.

Refactoring evangelists would claim that your goal should generally be to create flat and short functions that call other operations. While addAll, find, and such methods are easy to implement yourself, avoiding them would require the reader to grasp something more complex than a single word, and may cause code replication.

IMHO, CollectionUtils actually presents cleaner operations than the standard Java collection library.

ContentLicense: CC BY-SA 2.5

Title: Good uses for Apache CollectionUtils

OwnerDisplayName: Uri


问:
Tampermonkey - Right click menu
With Tampermonkey is there any way to create a right click menu option in Chrome?

I found GM_registerMenuCommand but it does not seem to show any new items in the right click menu.

Another problem is I use GM_openInTab in the test script but it seems to loop infinitely for some reason. It should only trigger after the menu is clicked, why would this happen?

Also I am wondering is there a way to do this in a more advanced way with custom right click icons etc?

There was a GM script for Firefox that worked for menus but in Chrome nothing seems to show so it would be good to have a way to have this working.

```<code>// ==UserScript==
// @name            Context Menu
// @namespace       http://tampermonkey.net/
// @description     Test
// @version         0.1
// @author          author
// @include         *
// @exclude         file://*
// @grant           GM_openInTab
// @grant           GM_registerMenuCommand
// ==/UserScript==]

(function() {
    'use strict';

function test() {
    GM_openInTab("https://website.net");
}

GM_registerMenuCommand("hello", test(), "h");

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

答:
Instead of GM_registerMenuCommand("hello", test(), "h") you should have GM_registerMenuCommand("hello", test, "h")

The first version calls the test function immediately, and then passes its result to GM_registerMenuCommand function. The second passes the function itself instead of its result.

Title: Tampermonkey - Right click menu

Body:
With Tampermonkey is there any way to create a right click menu option in Chrome?

I found GM_registerMenuCommand but it does not seem to show any new items in the right click menu.

Another problem is I use GM_openInTab in the test script but it seems to loop infinitely for some reason. It should only trigger after the menu is clicked, why would this happen?

Also I am wondering is there a way to do this in a more advanced way with custom right click icons etc?

There was a GM script for Firefox that worked for menus but in Chrome nothing seems to show so it would be good to have a way to have this working.

// ==UserScript==
// @name            Context Menu
// @namespace       http://tampermonkey.net/
// @description     Test
// @version         0.1
// @author          author
// @include         *
// @exclude         file://*
// @grant           GM_openInTab
// @grant           GM_registerMenuCommand
// ==/UserScript==]

(function() {
    'use strict';

function test() {
    GM_openInTab("https://website.net");
}

GM_registerMenuCommand("hello", test(), "h");

})();


问:
Google Assistant SDK refusing authenticated channel as "UNAUTHENTICATED"
I am trying to create a Google Assistant for my Raspberry Pi in Kotlin. I implemented a OAuth flow using the so called "device flow" proposed in this IETF draft, since my Raspberry shall later just expose a web interface and does not have any input devices or graphical interfaces.

Google does support this flow (of course) and I obtain a valid access token with user consent in the end. For testing purpose I also tried a default authorization flow that will just forward the user to localhost, as it is normally done but it did not solve the problem.

I tested the access token using this tool and it confirmed validity of scope and token. So the token itself should work.

Scope is: https://www.googleapis.com/auth/assistant-sdk-prototype as documented here
This actually does not point to any valid web resource but is referenced in every documentation.

Then I tried to stream audio data to the assistant SDK endpoint using the gRPC provided java stubs. As took a third party reference implementation as a guide how to authenticate the rpc stub. But neither the reference implementation nor my own one works. They both report

```<code>io.grpc.StatusRuntimeException: UNAUTHENTICATED: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
</code>```

The stub is authenticated this way:

```<code>embeddedAssistantStub.withCallCredentials(
            MoreCallCredentials.from(OAuth2Credentials
                    .newBuilder()
                    .setAccessToken(
                            myAccessToken,
                            myAccessTokenExpirationDate))
                    .build()))
</code>```

and the authenticated request is performed like this:

```<code>val observer = authenticatedEmbeddedAssistantStub.converse(myStreamObserverImplementation)
observer.onNext(myConfigConverseRequest)
while(more audio data frames available) {
    observer.onNext(myAudioFrameConverseRequest)
}
observer.onCompleted()
</code>```

(I prefixed pseudo variables with "my" for clarity, they can consist of more code in the actual implementation.)

I even contacted the author of this demo implementation. He told me, last time he checked (several months ago) it was working perfectly fine. So I finally ran out of options.
Since the client implementation I took as reference used to work and I do actually authenticate the stub (although the error message suggests the opposite) Probably, either my valid access token with correct scope is not suitable chosen for the assistant API (though I followed the suggestions of google) or the API servers had a change not properly documented in the getting started articles by google.

So: Did anyone ran in the same problem and know how to fix it? I have the project on github. So if anyone needs the broken source code, I can do a temporary commit that produces the error.

Note, to save some works for mods: This issue referres to this and this question, both unresolved and using different languages but describing a similar problem.

答:
Well, seems I was right about my second assumption: The error is server side. Here is the github issue, let's just wait for the fix.

https://github.com/googlesamples/assistant-sdk-python/issues/138

Body:
I am trying to create a Google Assistant for my Raspberry Pi in Kotlin. I implemented a OAuth flow using the so called "device flow" proposed in this IETF draft, since my Raspberry shall later just expose a web interface and does not have any input devices or graphical interfaces.

Google does support this flow (of course) and I obtain a valid access token with user consent in the end. For testing purpose I also tried a default authorization flow that will just forward the user to localhost, as it is normally done but it did not solve the problem.

I tested the access token using this tool and it confirmed validity of scope and token. So the token itself should work.

Scope is: https://www.googleapis.com/auth/assistant-sdk-prototype as documented here
This actually does not point to any valid web resource but is referenced in every documentation.

Then I tried to stream audio data to the assistant SDK endpoint using the gRPC provided java stubs. As took a third party reference implementation as a guide how to authenticate the rpc stub. But neither the reference implementation nor my own one works. They both report

io.grpc.StatusRuntimeException: UNAUTHENTICATED: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.

The stub is authenticated this way:

embeddedAssistantStub.withCallCredentials(
            MoreCallCredentials.from(OAuth2Credentials
                    .newBuilder()
                    .setAccessToken(
                            myAccessToken,
                            myAccessTokenExpirationDate))
                    .build()))

and the authenticated request is performed like this:

val observer = authenticatedEmbeddedAssistantStub.converse(myStreamObserverImplementation)
observer.onNext(myConfigConverseRequest)
while(more audio data frames available) {
    observer.onNext(myAudioFrameConverseRequest)
}
observer.onCompleted()

(I prefixed pseudo variables with "my" for clarity, they can consist of more code in the actual implementation.)

I even contacted the author of this demo implementation. He told me, last time he checked (several months ago) it was working perfectly fine. So I finally ran out of options.
Since the client implementation I took as reference used to work and I do actually authenticate the stub (although the error message suggests the opposite) Probably, either my valid access token with correct scope is not suitable chosen for the assistant API (though I followed the suggestions of google) or the API servers had a change not properly documented in the getting started articles by google.

So: Did anyone ran in the same problem and know how to fix it? I have the project on github. So if anyone needs the broken source code, I can do a temporary commit that produces the error.

Note, to save some works for mods: This issue referres to this and this question, both unresolved and using different languages but describing a similar problem.


问:
JQuery Autocomplete: make ajax call to collect more details of the selected item from autocomplete
What I am trying to do is once a user selects a result from the autocomplete, an ajax call is made to a php file to collect more details about the selected item and then the details coming within response are displayed in a textarea box.

```<code>$(document).ready(function() {
    $("#bookSearch").autocomplete({
        source: "getBooks.php",
        minLength: 3,
        select: function() {
            $.ajax({
                method: "get",
                url: "getBooks2.php"
            })
            .done(function(event, ui){
                $('#bookResults').val(ui.item.value + "\n");
            })
        }
    });
});
</code>```

This is my javascript at the moment. I get an error

"Cannot read property 'value' of undefined" in reference to "$('#bookResults').val(ui.item.value + "\n");".

How can I implement the ajax call into the autocomplete function?

```<code><div id="autoComplete">
    <h2 id="searchTitle">Book search</h2>
    <input type="text" id="bookSearch" placeholder="Type in a book name"/>
    <br>
    <textarea rows="10" cols="40" id="bookResults" readonly></textarea>
</div>
</code>```

答:
After some tinkering I have managed to find a solution:</p>

```<code>$(document).ready(function() {
    $("#bookSearch").autocomplete({
        source: "getBooks.php",
        minLength: 3,
        select: function(event, ui) {
            $.ajax({
                method: "get",
                url: "getBooks2.php",
                data: {bookTitle: ui.item.value}
            })
                .done(function(data) {
                    $('#bookResults').val(data);
                })
        }
    });
});
</code>```

Body:
What I am trying to do is once a user selects a result from the autocomplete, an ajax call is made to a php file to collect more details about the selected item and then the details coming within response are displayed in a textarea box.

$(document).ready(function() {
    $("#bookSearch").autocomplete({
        source: "getBooks.php",
        minLength: 3,
        select: function() {
            $.ajax({
                method: "get",
                url: "getBooks2.php"
            })
            .done(function(event, ui){
                $('#bookResults').val(ui.item.value + "\n");
            })
        }
    });
});

This is my javascript at the moment. I get an error

"Cannot read property 'value' of undefined" in reference to "$('#bookResults').val(ui.item.value + "\n");".

How can I implement the ajax call into the autocomplete function?

Book search

    <input type="text" id="bookSearch" placeholder="Type in a book name"/>

    <textarea rows="10" cols="40" id="bookResults" readonly></textarea>

Body:
After some tinkering I have managed to find a solution:

$(document).ready(function() {
    $("#bookSearch").autocomplete({
        source: "getBooks.php",
        minLength: 3,
        select: function(event, ui) {
            $.ajax({
                method: "get",
                url: "getBooks2.php",
                data: {bookTitle: ui.item.value}
            })
                .done(function(data) {
                    $('#bookResults').val(data);
                })
        }
    });
});


问:
angular4 page changes dynamiclly according to some attribute
HTML file:

```<code><div [hidden]="isshow">
  <h1>this is a</h1>
</div>
<div [hidden]="!isshow">
 <h1>this is b</h1>
</div>
</code>```

component.ts:

```<code>  public get isshow() {
    return (this._state === 'ready');
  }
</code>```

The state value is changed by an EventListener, and will change from "connecting" to "ready".

What I want is to show "this is a" at the beginning then change to "this is b"
 when state is "ready", but looks it doesn't work.
What should I do? Thanks in advance.

答:
Just a piece of advice here. Due to some internal shenanigans angular does with it's change detection system it's better not to use getter for binding.
Your

```<code> public get isshow() {
    return (this._state === 'ready');
  }
</code>```

will be called everytime your component checks for changes (just put console.log there before return (this._state === 'ready'); and you'll see)

it's better to use a pipe or just put the condtion this._state === 'ready' in your binding and this way it'll be called only when this._state actually changes

The same is also true for functions bound to your fields i.e you shouldn't use them in bindings

Body:
HTML file:

this is a

this is b

component.ts:

  public get isshow() {
    return (this._state === 'ready');
  }

The state value is changed by an EventListener, and will change from "connecting" to "ready".

What I want is to show "this is a" at the beginning then change to "this is b"
 when state is "ready", but looks it doesn't work.
What should I do? Thanks in advance.

Body:
Just a piece of advice here. Due to some internal shenanigans angular does with it's change detection system it's better not to use getter for binding.
Your

 public get isshow() {
    return (this._state === 'ready');
  }

will be called everytime your component checks for changes (just put console.log there before return (this._state === 'ready'); and you'll see)

it's better to use a pipe or just put the condtion this._state === 'ready' in your binding and this way it'll be called only when this._state actually changes

The same is also true for functions bound to your fields i.e you shouldn't use them in bindings


答: Maybe there is a better way - I havent used Firebase for a while, but simplest way could be just as in Javascript - check the current day and calculate needed changes accordingly when some user access some resource. Say UserA builds an army and it reaches 100% in 10 days, so if UserB attacks UserA army after 5 days, just calculate UserA army strength and update its database. Maybe its even more efficient than doing some background jobs - do it when its needed and server will cost less.  </p>

Title: How can I keep my database updating itself while no one is online (firebase)?

Body: Imagine a browser game that users have their resources to build an army/walls etc., and those resources should be updated based on their buildings even when they're offline. How can I update this data when they're off (I'm using Firebase)?


问:
Can dockerfile be put in .dockerignore?
The documentation says that yes it can.

https://docs.docker.com/engine/reference/builder/

You can even use the .dockerignore file to exclude the Dockerfile and .dockerignore files. These files are still sent to the daemon because it needs them to do its job. But the ADD and COPY instructions do not copy them to the image.

But when I put dockerfile in the .dockerignore I get

```<code>Sending build context to Docker daemon  1.646MB
Error response from daemon: Cannot locate specified Dockerfile: Dockerfile
</code>```

答:
The question was edited a while back which I didn't notice. The original question more accurately reflects the knowledge that I was missing and the issue that I was having and I have reverted to that version.

Docker treats the names 'dockerfile' and 'Dockerfile' equally up to a point. i.e. you can call it 'dockerfile' and docker will still automatically use it if you do something like docker build -t blah .. However if you then put dockerfile in the .dockerignore file it doesn't know how to build your image automatically anymore and you will get

Error response from daemon: Cannot locate specified Dockerfile: Dockerfile

Title: Can dockerfile be put in .dockerignore?

Body:
The documentation says that yes it can.

https://docs.docker.com/engine/reference/builder/

You can even use the .dockerignore file to exclude the Dockerfile and .dockerignore files. These files are still sent to the daemon because it needs them to do its job. But the ADD and COPY instructions do not copy them to the image.

But when I put dockerfile in the .dockerignore I get

Sending build context to Docker daemon  1.646MB
Error response from daemon: Cannot locate specified Dockerfile: Dockerfile


问:
Removing string from string where part of the string can be a number in javascript
I want to remove part of a string from another string where the part I want to remove has a number in it.

The string is my url and the part I want to remove is the page and page number
ex.

```<code>var url = www.mysite.com/?someparam=someparam&someparam=somparam&page=3
</code>```

I want to remove the

```<code>&page=3
</code>```

but the page can be 1,2,3,4,etc

I know I can do this by string replace like

```<code>var str = "mystring&page=1";
var res = str.replace("&page=1", "");
</code>```

but this only works with a static number like 1, and I want it to work with any number

答:
Use a regular expressions with \d+ to match any number of one or more digits:

function removePage(url) {
  return url.replace(/([?&])page=\d+(&?)/, function(p1, p2, p3) {
    return p2 === '?' ? '?' : p3;
  });
}

console.log(removePage('www.mysite.com/?someparam=someparam&someparam=somparam&page=6'));

console.log(removePage('www.mysite.com/?someparam=someparam&someparam=somparam&page=3&cats'));

console.log(removePage('www.mysite.com/?page=59&someparam=someparam&someparam=somparam'));```

Body:
I want to remove part of a string from another string where the part I want to remove has a number in it.

The string is my url and the part I want to remove is the page and page number
ex.

var url = www.mysite.com/?someparam=someparam&someparam=somparam&page=3

I want to remove the

&page=3

but the page can be 1,2,3,4,etc

I know I can do this by string replace like

var str = "mystring&page=1";
var res = str.replace("&page=1", "");

but this only works with a static number like 1, and I want it to work with any number


问:
Conditional query of sort key in DynamoDB not working?
I am building a trivial API using API Gateway through to DynamoDB.  I am trying to do a conditional query against a sort key and I keep getting the message "Query key conditional not supported."  However, everything I've read in the documents said this should indeed work.

I'm trying to do something like:

```<code>{
    "TableName": "testTable",
    "KeyConditionExpression": "requestTimeEpoch > :since",
    "ExpressionAttributeValues": {
        ":since": {
            #if($input.params('since') != "")
                "S": "$input.params('since')"
            #else
                "S": "1"
            #end
        }
    }
}
</code>```

I read somewhere that someone had this issue when using a Number, so I tried switching it to a String instead.  Either way, shouldn't this work?

(requestTimeEpoch is the sort/range key for the hash key)

答:
You can't use the sort key on its own. Data is only sorted within its partition. So you need to specify a partition key (this has to be an equals operator) on your query.

If you don't want to use your partition key, you need to switch to a scan operation. A scan doesn't require any key conditions.

EDIT: So with a partition (hash) key it might be something like

```<code>{
    "TableName": "testTable",
    "KeyConditionExpression": "YourHash = :hash and requestTimeEpoch > :since",
    "ExpressionAttributeValues": {
        ":since": {
            #if($input.params('since') != "")
                "S": "$input.params('since')"
            #else
                "S": "1"
            #end
        ":hash" : {S: 'yourHashId'}
        }
    }
}
</code>```

and a scan

```<code>var params = {
    TableName: "testTable",
    FilterExpression: "#since > :time",
    ExpressionAttributeNames: {
        "#since": "time",
    },
    ExpressionAttributeValues: {
         ":time": 2017,
    }
};
</code>```

Body:
I am building a trivial API using API Gateway through to DynamoDB.  I am trying to do a conditional query against a sort key and I keep getting the message "Query key conditional not supported."  However, everything I've read in the documents said this should indeed work.

I'm trying to do something like:

{
    "TableName": "testTable",
    "KeyConditionExpression": "requestTimeEpoch > :since",
    "ExpressionAttributeValues": {
        ":since": {
            #if($input.params('since') != "")
                "S": "$input.params('since')"
            #else
                "S": "1"
            #end
        }
    }
}

I read somewhere that someone had this issue when using a Number, so I tried switching it to a String instead.  Either way, shouldn't this work?

(requestTimeEpoch is the sort/range key for the hash key)

Body:
You can't use the sort key on its own. Data is only sorted within its partition. So you need to specify a partition key (this has to be an equals operator) on your query.

If you don't want to use your partition key, you need to switch to a scan operation. A scan doesn't require any key conditions.

EDIT: So with a partition (hash) key it might be something like

{
    "TableName": "testTable",
    "KeyConditionExpression": "YourHash = :hash and requestTimeEpoch > :since",
    "ExpressionAttributeValues": {
        ":since": {
            #if($input.params('since') != "")
                "S": "$input.params('since')"
            #else
                "S": "1"
            #end
        ":hash" : {S: 'yourHashId'}
        }
    }
}

and a scan

var params = {
    TableName: "testTable",
    FilterExpression: "#since > :time",
    ExpressionAttributeNames: {
        "#since": "time",
    },
    ExpressionAttributeValues: {
         ":time": 2017,
    }
};


问:
Sending two AJAX requests at the same time
I am probably missing something very simple here, but what I am trying to do is update two divs on my page with AJAX requests that are called at the same time when an item is clicked.

I have looked at here
but unfortunately I am still missing something in the code.

I have the following JavaScript code:

```<code>$(document.body).on('click', '.details', function(event) {
    //  $(this) = your current element that clicked.
    // additional code
    var id = event.target.id;
    //alert(id);
    //alert($(this));
    _formurl = "home_stocktake_locations_list_group.php";
    _formdata = {
        'store_id': id
    };
    _formurl2 = "home_stocktake_list.php";
    $.ajax({
            type: "GET",
            url: _formurl,
            data: _formdata,
            success: function(xhrResponse) {
                $('#current').html(xhrResponse);
                var rowCount = $('#locations').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        }),
        $.ajax({

            type: "GET",
            url: _formurl2,
            data: _formdata,
            success: function(xhrResponse) {
                $('#previous').html(xhrResponse);
                var rowCount = $('#dd_home_stocktake').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        });

});
</code>```

When I look at what happens in the console, only home_stocktake_locations_list_group.php file gets called, the second AJAX call is completely ignored. What is causing this?

In the console I can only see the following:

答:
After the first $.ajax you have a , (comma), replace by a ; (semicolon). Othen than that, it worked fine for me.

Also, if you are sending data on the request, consider using $.post instead of the lower level $.ajax. Also, you have the same error routine, so isolate it:

```<code>function handleError(xhr, status, error) {
  $('#alert_msg').html(error);
  $('#alert_msg').fadeIn('slow');
}

$.post(_formurl, _formdata)
  .done(function(data) {
    $('#current').html(data);
    var rowCount = $('#locations').length;
    row_count = parseInt(rowCount);
  })
  .fail(handleError);

$.post(_formurl2, _formdata)
  .done(function(data) {
    $('#previous').html(data);
    var rowCount = $('#dd_home_stocktake').length;
    row_count = parseInt(rowCount);
  })
  .fail(handleError);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am probably missing something very simple here, but what I am trying to do is update two divs on my page with AJAX requests that are called at the same time when an item is clicked.

I have looked at here
but unfortunately I am still missing something in the code.

I have the following JavaScript code:

$(document.body).on('click', '.details', function(event) {
    //  $(this) = your current element that clicked.
    // additional code
    var id = event.target.id;
    //alert(id);
    //alert($(this));
    _formurl = "home_stocktake_locations_list_group.php";
    _formdata = {
        'store_id': id
    };
    _formurl2 = "home_stocktake_list.php";
    $.ajax({
            type: "GET",
            url: _formurl,
            data: _formdata,
            success: function(xhrResponse) {
                $('#current').html(xhrResponse);
                var rowCount = $('#locations').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        }),
        $.ajax({

            type: "GET",
            url: _formurl2,
            data: _formdata,
            success: function(xhrResponse) {
                $('#previous').html(xhrResponse);
                var rowCount = $('#dd_home_stocktake').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        });

});

When I look at what happens in the console, only home_stocktake_locations_list_group.php file gets called, the second AJAX call is completely ignored. What is causing this?

In the console I can only see the following:

Body:
After the first $.ajax you have a , (comma), replace by a ; (semicolon). Othen than that, it worked fine for me.

Also, if you are sending data on the request, consider using $.post instead of the lower level $.ajax. Also, you have the same error routine, so isolate it:

function handleError(xhr, status, error) {
  $('#alert_msg').html(error);
  $('#alert_msg').fadeIn('slow');
}

$.post(_formurl, _formdata)
  .done(function(data) {
    $('#current').html(data);
    var rowCount = $('#locations').length;
    row_count = parseInt(rowCount);
  })
  .fail(handleError);

$.post(_formurl2, _formdata)
  .done(function(data) {
    $('#previous').html(data);
    var rowCount = $('#dd_home_stocktake').length;
    row_count = parseInt(rowCount);
  })
  .fail(handleError);


问:
Is it possible to have the "IF" on a "select" statement or using "Case"?
I have an IF statement that basically gives me concatenation of addresses if value for them is not null. as see below :

```<code>IF @Address1 IS NOT NULL
BEGIN
    IF @Address2 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+@Address2
        ELSE SET @TotalAddress=@Address1;
    IF @Address3 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+ISNULL(@Address2, '')+CHAR(13)+ISNULL(@Address3, '')
    IF @Address4 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+ISNULL(@Address2, '')+CHAR(13)+ISNULL(@Address3, '')+CHAR(13)+ISNULL(@Address4, '')
END
</code>```

I was wondering if I can have my code in select statement directly and grab address1,2 and 3 without creating a variable.

答:
Try this using CONCAT ,NULLIF , IIF and ISNULL

```<code>declare @address1 varchar(10)= NULL
declare @address2 varchar(10)= '39 Cox Street'
declare @address3 varchar(10)= NULL
declare @address4 varchar(10)= 'Chicago'

select
   iif(isnull(@address1,'') = '','',
   concat(@address1 + char(13),
   nullif(@address2,'') + char(13) ,
   nullif(@address3,'') + char(13),
   nullif(@address4,'') + char(13)))
</code>```

demo found here http://rextester.com/live/OMP74388

Body:
I have an IF statement that basically gives me concatenation of addresses if value for them is not null. as see below :

IF @Address1 IS NOT NULL
BEGIN
    IF @Address2 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+@Address2
        ELSE SET @TotalAddress=@Address1;
    IF @Address3 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+ISNULL(@Address2, '')+CHAR(13)+ISNULL(@Address3, '')
    IF @Address4 IS NOT NULL SET @TotalAddress=ISNULL(@Address1, '')+CHAR(13)+ISNULL(@Address2, '')+CHAR(13)+ISNULL(@Address3, '')+CHAR(13)+ISNULL(@Address4, '')
END

I was wondering if I can have my code in select statement directly and grab address1,2 and 3 without creating a variable.

Body:
Try this using CONCAT ,NULLIF , IIF and ISNULL

declare @address1 varchar(10)= NULL
declare @address2 varchar(10)= '39 Cox Street'
declare @address3 varchar(10)= NULL
declare @address4 varchar(10)= 'Chicago'

select
   iif(isnull(@address1,'') = '','',
   concat(@address1 + char(13),
   nullif(@address2,'') + char(13) ,
   nullif(@address3,'') + char(13),
   nullif(@address4,'') + char(13)))

demo found here http://rextester.com/live/OMP74388


问:
How to do an atomic custom update of a mongodb document?
I am aware that MongoDB can do atomic updates using findOneAndModify but this only permits basic operations like set or increment.

What I need is to apply a custom function to transform my document:

```<code>const updateDoc = async (event) => {
  const oldState = await db.collection(collectionName).findOne({ name });
  const newState = customFunction(oldState, event);
  await db.collection(collectionName).replaceOne({ name }, newState);
}
</code>```

This function will be called by a system that won't wait for a resolved promise to continue working: there can be multiple synchronous calls.

Is there a way to rewrite updateDoc to make it atomic, so that when we do:

```<code>updateDoc(event1); // note the absence of await
updateDoc(event2);
</code>```

We can be sure that the stored doc will be customFunction(customFunction(initState, event1), event2)?

Thanks

答:
A possible solution would be a task queue, that shedules one update after another:

```<code>class Scheduler {
  constructor(){
    this.running = false;
    this.queue = [];
  }

  add(el){
     this.queue.push(el);
     if(!this.running) this.run();
  }

  async run(){
    this.running = true;
    while(this.queue.length) await this.queue.shift();
    this.running = false;
 }
}
</code>```

Usable like this:

```<code> const dbTasks = new Sheduler();

 const updateDoc = async (event) => dbTasks.add( _ => {
   const oldState = await db.collection(collectionName).findOne({ name });
   const newState = customFunction(oldState, event);
   await db.collection(collectionName).replaceOne({ name }, newState);
});

updateDoc(evt1);
updateDoc(evt2);
</code>```

Body:
I am aware that MongoDB can do atomic updates using findOneAndModify but this only permits basic operations like set or increment.

What I need is to apply a custom function to transform my document:

const updateDoc = async (event) => {
  const oldState = await db.collection(collectionName).findOne({ name });
  const newState = customFunction(oldState, event);
  await db.collection(collectionName).replaceOne({ name }, newState);
}

This function will be called by a system that won't wait for a resolved promise to continue working: there can be multiple synchronous calls.

Is there a way to rewrite updateDoc to make it atomic, so that when we do:

updateDoc(event1); // note the absence of await
updateDoc(event2);

We can be sure that the stored doc will be customFunction(customFunction(initState, event1), event2)?

Thanks

Body:
A possible solution would be a task queue, that shedules one update after another:

class Scheduler {
  constructor(){
    this.running = false;
    this.queue = [];
  }

  add(el){
     this.queue.push(el);
     if(!this.running) this.run();
  }

  async run(){
    this.running = true;
    while(this.queue.length) await this.queue.shift();
    this.running = false;
 }
}

Usable like this:

 const dbTasks = new Sheduler();

 const updateDoc = async (event) => dbTasks.add( _ => {
   const oldState = await db.collection(collectionName).findOne({ name });
   const newState = customFunction(oldState, event);
   await db.collection(collectionName).replaceOne({ name }, newState);
});

updateDoc(evt1);
updateDoc(evt2);


问:
Indexing array in php pdo insert while loop
I'm trying to insert a row into a table for each fetch from another table using a while loop. The code I currently have inserts the first users data into the database. </p>

<p>If the insert query is outside of the loop it will enter the last users data. It must be an issue iterating through the array. Is there a way I can index the array values for each pass of the loop? </p>

```<code>$query = "SELECT * FROM users_table" ;
$statement = $db->prepare($query);
$rows = $statement->fetchAll();
$statement->execute();

while($rows = $statement->fetch()){

    $salted = $sso_key . $companyId;
    $hash = hash('sha1',$salted,true);
    $saltedHash = substr($hash,0,16);

    $iv = substr(md5(microtime()),rand(0,16),16); //Generate random 16 bit string

    $user_data = array(
      "user_id" => $rows['id'],
      "first_name" => $rows['first_name'],
      "last_name" => $rows['last_name'],
      "email" => $rows['email'],
      "position" => $rows['type']);

    $data = json_encode($user_data);
    $data = $iv . $data;

    $pad = 16 - (strlen($data) % 16);
    $data = $data . str_repeat(chr($pad), $pad);

    $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128,'','cbc','');
    mcrypt_generic_init($cipher, $saltedHash, $iv);
    $encryptedData = mcrypt_generic($cipher,$data);
    mcrypt_generic_deinit($cipher);

    $encryptedData = base64_encode($encryptedData);

    $token = array(
        "token" => $encryptedData
    );

    $token_data = json_encode($token);

    echo "
    <br>Here is the token for ".$user_data['first_name'].", ".$user_data['last_name']."
    ".$user_data['email'] ." :
    " . $token['token'];

    $query = "INSERT INTO another_table
            (token ,first_name,last_name,email,position)
            VALUES (:token, :first_name,
            :last_name, :email, :position)";

    $statement = $db->prepare($query);
    $statement->bindValue(':token', $token['token']);
    $statement->bindValue(':first_name', $user_data['first_name']);
    $statement->bindValue(':last_name', $user_data['last_name']);
    $statement->bindValue(':email', $user_data['email']);
    $statement->bindValue(':position', $user_data['position']);

    $statement->execute();

}
?>
</code>```

答:
Reducing that code to the basics, you have this:

```<code>$query = "SELECT * FROM users_table" ;
$statement = $db->prepare($query);
$rows = $statement->fetchAll();
$statement->execute();
while($rows = $statement->fetch()){
    // .. stuff ..
    $query = "INSERT INTO another_table
            (token ,first_name,last_name,email,position)
            VALUES (:token, :first_name,
            :last_name, :email, :position)";
    $statement = $db->prepare($query);
    $statement->bindValue(':token', $token['token']);
    $statement->bindValue(':first_name', $user_data['first_name']);
    $statement->bindValue(':last_name', $user_data['last_name']);
    $statement->bindValue(':email', $user_data['email']);
    $statement->bindValue(':position', $user_data['position']);
    $statement->execute();
}
</code>```

See the problem yet? Ok, here is a hint to fix it:

```<code>$query = "SELECT * FROM users_table" ;
$statement = $db->prepare($query);
$statement->execute();
$query = ".. prepared query here .."; // your second query used in the loop
$SECOND_statement = $db->prepare($query); // set it up
while($row = $statement->fetch()){
    // .. bindValue lines here ..
    $SECOND_statement->execute();
}
</code>```

Inside your while loop, you were overwriting the variable $statement with the insert sql. This effectively ended your while loop prematurely. Can also cause some serious unwanted and unexpected issues if that second sql was another SELECT.

Body:
I'm trying to insert a row into a table for each fetch from another table using a while loop. The code I currently have inserts the first users data into the database.

If the insert query is outside of the loop it will enter the last users data. It must be an issue iterating through the array. Is there a way I can index the array values for each pass of the loop?

$query = "SELECT * FROM users_table" ;
$statement = $db->prepare($query);
$rows = $statement->fetchAll();
$statement->execute();

while($rows = $statement->fetch()){

    $salted = $sso_key . $companyId;
    $hash = hash('sha1',$salted,true);
    $saltedHash = substr($hash,0,16);

    $iv = substr(md5(microtime()),rand(0,16),16); //Generate random 16 bit string

    $user_data = array(
      "user_id" => $rows['id'],
      "first_name" => $rows['first_name'],
      "last_name" => $rows['last_name'],
      "email" => $rows['email'],
      "position" => $rows['type']);

    $data = json_encode($user_data);
    $data = $iv . $data;

    $pad = 16 - (strlen($data) % 16);
    $data = $data . str_repeat(chr($pad), $pad);

    $cipher = mcrypt_module_open(MCRYPT_RIJNDAEL_128,'','cbc','');
    mcrypt_generic_init($cipher, $saltedHash, $iv);
    $encryptedData = mcrypt_generic($cipher,$data);
    mcrypt_generic_deinit($cipher);

    $encryptedData = base64_encode($encryptedData);

    $token = array(
        "token" => $encryptedData
    );

    $token_data = json_encode($token);

    echo "

Here is the token for ".$user_data['first_name'].", ".$user_data['last_name']."
    ".$user_data['email'] ." :
    " . $token['token'];

    $query = "INSERT INTO another_table
            (token ,first_name,last_name,email,position)
            VALUES (:token, :first_name,
            :last_name, :email, :position)";

    $statement = $db->prepare($query);
    $statement->bindValue(':token', $token['token']);
    $statement->bindValue(':first_name', $user_data['first_name']);
    $statement->bindValue(':last_name', $user_data['last_name']);
    $statement->bindValue(':email', $user_data['email']);
    $statement->bindValue(':position', $user_data['position']);

    $statement->execute();

}
?>

Body:
Reducing that code to the basics, you have this:

$query = "SELECT * FROM users_table" ;
$statement = $db->prepare($query);
$rows = $statement->fetchAll();
$statement->execute();
while($rows = $statement->fetch()){
    // .. stuff ..
    $query = "INSERT INTO another_table
            (token ,first_name,last_name,email,position)
            VALUES (:token, :first_name,
            :last_name, :email, :position)";
    $statement = $db->prepare($query);
    $statement->bindValue(':token', $token['token']);
    $statement->bindValue(':first_name', $user_data['first_name']);
    $statement->bindValue(':last_name', $user_data['last_name']);
    $statement->bindValue(':email', $user_data['email']);
    $statement->bindValue(':position', $user_data['position']);
    $statement->execute();
}

See the problem yet? Ok, here is a hint to fix it:

$query = "SELECT * FROM users_table" ;
$statement = $db->prepare($query);
$statement->execute();
$query = ".. prepared query here .."; // your second query used in the loop
$SECOND_statement = $db->prepare($query); // set it up
while($row = $statement->fetch()){
    // .. bindValue lines here ..
    $SECOND_statement->execute();
}

Inside your while loop, you were overwriting the variable $statement with the insert sql. This effectively ended your while loop prematurely. Can also cause some serious unwanted and unexpected issues if that second sql was another SELECT.


问:
Using $document.querySelectorAll in angularjs
As $document is wrapper for angular.element(window.document), ideally
$document.querySelectorAll() should work, but I am getting an error saying it is not a function. Can somebody explain?

答:
You will have to use angular.element(document.querySelector().jqLiteMethods());

For example

```<code>angular.element(document.querySelector('#dis-caret-drop')).find('.caret').css({'opacity' : 0.4});
</code>```

This would select the element with id 'dis-caret-drop' and search for the child element with class 'caret' and change the opacity of the child element to 0.4

Body:
You will have to use angular.element(document.querySelector().jqLiteMethods());

For example

angular.element(document.querySelector('#dis-caret-drop')).find('.caret').css({'opacity' : 0.4});

This would select the element with id 'dis-caret-drop' and search for the child element with class 'caret' and change the opacity of the child element to 0.4


问:
Name convention on Java Swing components(prefix)
An question that was brought to my mind when programming with Swing in Java was, is it a recommendation or an "official"/most used naming convention(prefix) on Swing components.

Such as(even though other may prefer other naming conventions this is what I am currently using):

txt for JTextField

btn for JButton

lbl for JLabel

pnl for JPanel

But then my list ends..

I think such prefixes enhance the readability in my code so, but I do not have any names for components such as JComboBox, JList, JRadioButton, JCheckButton and so the list goes on.

Thanks in advance.

答:
Why not just call JTextField textField, JButton button, JLabel label, and JPanel panel. Is it so bad to spend a few extra characters to make the variable read like an English word?

Furthermore, when I do put the type in the variable name, I put it on the end. So a JLabel that displays a name is nameLabel (which IMO is more readable than lblName).

And even furthermore, following duffymo's advice, it's bad practice to put the type in the variable name. A better approach is to describe what the variable is. In the case of a name label, it's a UI component that displays name. So a better name might be nameComponent. The fact that nameComponent is a JLabel or some other type is secondary and shouldn't clutter the variable name.


问:
How/When does the server get to know that a connection got staled?
As per IBM documentation:
Purge Policy
Specifies how to purge connections when a stale connection or fatal connection error is detected.
Valid values are EntirePool and FailingConnectionOnly.

Question:
How/When does the server get to know that a connection got staled? Does it purge the pool as soon as (immediately?) any connection goes stale or it happens as per the reap time?

Say if the reap time is 180 seconds. Let's say the reap thread last ran at 3:05 PM and a connection goes stale at 3:06 PM, will the server purge the pool at 3:06 PM itself or the purge will happen only at 3:08 PM ? Is there a risk of clients getting staled connection objects between 3:06 and 3:08 ?

The IBM document i'm referring to is:
https://www.ibm.com/support/knowledgecenter/en/ssw_i5_54/rzamy/50/admin/help/udat_conpoolset.html

答:
Stale connections are identified in the following ways:

JDBC operation is performed that raises SQLRecoverableException or SQLNonTransientConnectionException, or a general SQLException with a SQL State or error code that the application server has built-in knowledge of. For specific lists of SQL states and error codes, refer to the SQLState mappings in DatabaseHelper and its various subclasses per database.

JDBC driver's ConnectionEventListener.connectionErrorOccurred signals the application server that a connection has gone bad.

When the application server learns that a connection has gone bad, it does not return that connection to the pool. Subsequent requests outside of the sharing scope would never get that same connection.

Purge Policy determines what the application server does with the other connections that are in the pool at the time that a stale connection occurred.  The application server can aggressively purge all connections from the pool (EntirePool option), or it can leave the others there (FailingConnectionOnly option), or it can check all connections in the pool before allowing them to be handed out (ValidateAllConnections option).

Note that the property values above are for WebSphere Application Server Liberty.  If using traditional, ValidateAllConnections is done as the combination of FailingConectionOnly plus defaultPretestOptimizationOverride=true.


问:
SonarQube unable to understand Java inline expression for null check
We are doing static code analysis using SonarQube.
We are facing following Bug found by SonarQube

```<code>NullPointerException might be thrown as 'evt' is nullable here
</code>```

in following code

```<code>try {
//business logic

}(Exception e){
    throw new MyException("Found issue for event " + evt.getDeatil());
}
</code>```

So to remove this bug we have introduced small inline code for null check

```<code>try {
//business logic

 }(Exception e){
     throw new MyException("Found issue for event " + evt != null ?
       evt.getDeatil() : null);
}
</code>```

Still SonarQube showing same violation bug after code change.

Could anyone please help us to find what we are missing here?

答:
You have an error in line:

```<code>throw new MyException("Found issue for event " + evt != null ? evt.getDeatil() : null);
</code>```

The problem is operators precedence. + is evaluated before ?: so your code is equal to:

```<code>String message = "Found issue for event " + evt;
throw new MyException(message != null ? evt.getDeatil() : null);
</code>```

NullPointerException still can occur. Additional you've introduced a new problem - expression:

```<code>message != null
</code>```

always evaluates to true.

To fix it you have to add curly brackets:

```<code>throw new MyException("Found issue for event " + (evt != null ? evt.getDeatil() : null));
</code>```

Body:
We are doing static code analysis using SonarQube.
We are facing following Bug found by SonarQube

NullPointerException might be thrown as 'evt' is nullable here

in following code

try {
//business logic

}(Exception e){
    throw new MyException("Found issue for event " + evt.getDeatil());
}

So to remove this bug we have introduced small inline code for null check

try {
//business logic

 }(Exception e){
     throw new MyException("Found issue for event " + evt != null ?
       evt.getDeatil() : null);
}

Still SonarQube showing same violation bug after code change.

Could anyone please help us to find what we are missing here?

Body:
You have an error in line:

throw new MyException("Found issue for event " + evt != null ? evt.getDeatil() : null);

The problem is operators precedence. + is evaluated before ?: so your code is equal to:

String message = "Found issue for event " + evt;
throw new MyException(message != null ? evt.getDeatil() : null);

NullPointerException still can occur. Additional you've introduced a new problem - expression:

message != null

always evaluates to true.

To fix it you have to add curly brackets:

throw new MyException("Found issue for event " + (evt != null ? evt.getDeatil() : null));


问:
RFID using Python Socket ( Low Level Commands)
SAAT-520Wireless-Communication-Programming-Development-ProtocolI've been trying to send Lowlevel commands to my RFID to get device information. I'm using wireshark to tap the connection and it seams to be fine as packets seem to go and come from my PC to RFID device and vice versa.

But I'm unable to see any response or output on my program. On the device note I have response command, I'm not sure should I and/or where I can use command response.

```<code>Import socket

TCP_IP = '192.168.0.238'
TCP_PORT = 7086
BUFFER_SIZE = 20
MESSAGE = '0x55, 0x00~0xFF, 0x01, 0x00, 0x00~0xFF'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.connect((TCP_IP, TCP_PORT))
except:
    print ('failed' + TCP_IP, 'down')
s.sendall(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print 'received', repr(data)
</code>```

I don't understand why there is no response from my program. No error nor program is successful. Just process never ends.

Also please find the notes for commands in the attachment.

System Information Query Command (0x01H)

Command Response

答:
(From your question)

```<code>s.sendall(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
</code>```

You are sending data via send, immediately asking for the response data, then closing the socket. Enough time will not have passed for you to get a response. For testing, try placing a time delay between.

```<code>import time
s.sendall(MESSAGE)
time.sleep(5)
data = s.recv(BUFFER_SIZE)
print(data)
s.close()
</code>```

You can also wait for the incoming data;

```<code>import time
s.sendall(MESSAGE)
while data is None:
    data = s.recv(BUFFER_SIZE)
    print "No data, waiting...."
    time.sleep(0.5)

print "Data arrived"
incoming = data.decode('utf-8')
print incoming
# Process Data
</code>```

I did personally have an issue if my buffer size was too small -- I had to catch the timeout exception to deal with it. Perhaps try increasing your buffer size.

Below is something close to the actual code I use for my application; It python 3.x, and you will have to condition it a bit -- but it works for me.

```<code>            try:
                data = s.recv(buf_len)
                if data is not None and len(data) > 0:
                    while True:
                        new_data = s.recv(buf_len)
                        if new_data is None or len(new_data) == 0:
                            break
                        data = data + new_data

            except socket.timeout:
                if data is not None and self.callback is not None:
                    logger.debug(f"Received packet: {data}")

incoming = data.decode('utf-8')
print incoming
# Process Data
</code>```

Body:
SAAT-520Wireless-Communication-Programming-Development-ProtocolI've been trying to send Lowlevel commands to my RFID to get device information. I'm using wireshark to tap the connection and it seams to be fine as packets seem to go and come from my PC to RFID device and vice versa.

But I'm unable to see any response or output on my program. On the device note I have response command, I'm not sure should I and/or where I can use command response.

Import socket

TCP_IP = '192.168.0.238'
TCP_PORT = 7086
BUFFER_SIZE = 20
MESSAGE = '0x55, 0x00~0xFF, 0x01, 0x00, 0x00~0xFF'

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
    s.connect((TCP_IP, TCP_PORT))
except:
    print ('failed' + TCP_IP, 'down')
s.sendall(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()
print 'received', repr(data)

I don't understand why there is no response from my program. No error nor program is successful. Just process never ends.

Also please find the notes for commands in the attachment.

System Information Query Command (0x01H)

Command Response

Body:
(From your question)

s.sendall(MESSAGE)
data = s.recv(BUFFER_SIZE)
s.close()

You are sending data via send, immediately asking for the response data, then closing the socket. Enough time will not have passed for you to get a response. For testing, try placing a time delay between.

import time
s.sendall(MESSAGE)
time.sleep(5)
data = s.recv(BUFFER_SIZE)
print(data)
s.close()

You can also wait for the incoming data;

import time
s.sendall(MESSAGE)
while data is None:
    data = s.recv(BUFFER_SIZE)
    print "No data, waiting...."
    time.sleep(0.5)

print "Data arrived"
incoming = data.decode('utf-8')
print incoming
# Process Data

I did personally have an issue if my buffer size was too small -- I had to catch the timeout exception to deal with it. Perhaps try increasing your buffer size.

Below is something close to the actual code I use for my application; It python 3.x, and you will have to condition it a bit -- but it works for me.

            try:
                data = s.recv(buf_len)
                if data is not None and len(data) > 0:
                    while True:
                        new_data = s.recv(buf_len)
                        if new_data is None or len(new_data) == 0:
                            break
                        data = data + new_data

            except socket.timeout:
                if data is not None and self.callback is not None:
                    logger.debug(f"Received packet: {data}")

incoming = data.decode('utf-8')
print incoming
# Process Data


问:
Push Commit origin:master with git (android studio)
I've inserted an image in drawable and tried to push. Got a IDE error. Tried to push again and I got this next time when I'm trying to push.
Can you please help? I'm new to VCS.

答:
better try in your studio terminal

1- git add .

2- git commit -m "your message here"

3- git push origin master

done.

check git status


问:
How to use List type with Codable? (RealmSwift)
Problem is List type does not conform to Codable, the below class cannot be insert to Realm.

for example,

```<code>class Book: Codable {
    var name: String = ""
    var author: String = ""
    var tags = [String]()
}
</code>```

Consider the above class conforms to Codable, if store this class to Realm, it needs to use List<Object> type instead of [String]

```<code>class Book: Object, Codable {
    @objc dynamic var name: String = ""
    @objc dynamic var author: String = ""
    var tags = List<Tag>()

    required convenience init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        author = try container.decode(String.self, forKey: .author)
        tags = try container.decode(List<Tag>.self, forKey: .tags)   // this is problem.
    }
}

class Tag: Object, Codable {
    @objc dynamic var string: String = ""

    required convenience init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: CodingKeys.self)
        string = try container.decode(String.self, forKey: .string)
    }
}
</code>```

To conform to Codable, it should be implement Decodable protocol. (required convenience init(from decoder: Decoder) throws)

But, List type does not conform to Codable(Decodable), it is impossible to use Codable if the class has List type.

How to resolve this issue?

Thanks,

答:
There is only one problem with the accepted answer. Realm specifies that lists should be let(Constants) So to modify the solution to follow best practices you just have to make your list a let and then loop through appending the results to your array.

```<code>// Change this Line in [Your Code]
// to a let (Constant)
</code>```

var tags = List<Tag>() to let tags = List<Tag>()

Then change

```<code>tags = try container.decode(List<Tag>.self, forKey: .tags)
</code>```

to

```<code>let tagsArray = try container.decode([Tag].self, forKey: .tags)
tagsArray.forEach{ tags.append($0) }
</code>```

Body:
Problem is List type does not conform to Codable, the below class cannot be insert to Realm.

for example,

class Book: Codable {
    var name: String = ""
    var author: String = ""
    var tags = [String]()
}

Consider the above class conforms to Codable, if store this class to Realm, it needs to use List<Object> type instead of [String]

class Book: Object, Codable {
    @objc dynamic var name: String = ""
    @objc dynamic var author: String = ""
    var tags = List<Tag>()

    required convenience init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: CodingKeys.self)
        name = try container.decode(String.self, forKey: .name)
        author = try container.decode(String.self, forKey: .author)
        tags = try container.decode(List<Tag>.self, forKey: .tags)   // this is problem.
    }
}

class Tag: Object, Codable {
    @objc dynamic var string: String = ""

    required convenience init(from decoder: Decoder) throws {
        self.init()
        let container = try decoder.container(keyedBy: CodingKeys.self)
        string = try container.decode(String.self, forKey: .string)
    }
}

To conform to Codable, it should be implement Decodable protocol. (required convenience init(from decoder: Decoder) throws)

But, List type does not conform to Codable(Decodable), it is impossible to use Codable if the class has List type.

How to resolve this issue?

Thanks,

Body:
There is only one problem with the accepted answer. Realm specifies that lists should be let(Constants) So to modify the solution to follow best practices you just have to make your list a let and then loop through appending the results to your array.

// Change this Line in [Your Code]
// to a let (Constant)

var tags = List<Tag>() to let tags = List<Tag>()

Then change

tags = try container.decode(List<Tag>.self, forKey: .tags)

to

let tagsArray = try container.decode([Tag].self, forKey: .tags)
tagsArray.forEach{ tags.append($0) }


问:
Django Forms Showing No Input Fields
instead of the whole form i am just seeing the submit button not the form fields

Goal: get form fields to load and be able to submit form.

views.py file

```<code>from django.shortcuts import render
from django.template.response import TemplateResponse
from django.views import generic
from friendsbook.models import Status,User
from django.views.generic.edit import CreateView
from .forms import CreatePost

class IndexView(generic.ListView):
    template_name='uposts/home.html'
    context_object_name='status_object'

    def get_queryset(self):
        return Status.objects.all()

class  post_detail(generic.DetailView):
    model=Status
    context_object_name='user_profile'
    template_name='uposts/detail.html'

    def get_queryset(self):
        abc=Status.objects.all()
        return abc;

def create_post(request):
    form=CreatePost()
    return render(request,"uposts/createpost.html",{'form':form})
</code>```

forms.py file

```<code>from django import forms
from friendsbook.models import Status

class CreatePost(forms.Form):

    class meta:
        model=Status
        fields = ("title","username" )
</code>```

createpost.html file inside designated folder

```<code>{% extends "friendsbook/structure.html" %}
{% block content %}
<form action="" method="post">{%csrf_token %}
    {{ form.as_table }}
    <input type="submit" value="Save">
</form>

{% endblock %}
</code>```

i also try by python shell but it's of no use.
look at this it's giving me empty string instead of form fields.

please help me.

答:
Since you're not using a ModelForm, you need to define the fields. And you can get rid of the model = Status declaration.

Try this:

```<code>from django import forms

class CreatePost(forms.Form):
    title = forms.CharField()
    username = forms.CharField()

    class meta:
        fields = ("title","username" )
</code>```

Since it's not a ModelForm, the form has no idea what fields there are in the Status model. And it has no way to instantiate the fields (since they are not defined).

I think you probably want to use a ModelForm though, unless there's some compelling reason not to.

Title: Django Forms Showing No Input Fields

Body:
instead of the whole form i am just seeing the submit button not the form fields

Goal: get form fields to load and be able to submit form.

views.py file

from django.shortcuts import render
from django.template.response import TemplateResponse
from django.views import generic
from friendsbook.models import Status,User
from django.views.generic.edit import CreateView
from .forms import CreatePost

class IndexView(generic.ListView):
    template_name='uposts/home.html'
    context_object_name='status_object'

    def get_queryset(self):
        return Status.objects.all()

class  post_detail(generic.DetailView):
    model=Status
    context_object_name='user_profile'
    template_name='uposts/detail.html'

    def get_queryset(self):
        abc=Status.objects.all()
        return abc;

def create_post(request):
    form=CreatePost()
    return render(request,"uposts/createpost.html",{'form':form})

forms.py file

from django import forms
from friendsbook.models import Status

class CreatePost(forms.Form):

    class meta:
        model=Status
        fields = ("title","username" )

createpost.html file inside designated folder

{% extends "friendsbook/structure.html" %}
{% block content %}
<form action="" method="post">{%csrf_token %}
    {{ form.as_table }}
    <input type="submit" value="Save">
</form>

{% endblock %}

i also try by python shell but it's of no use.
look at this it's giving me empty string instead of form fields.

please help me.

Body:
Since you're not using a ModelForm, you need to define the fields. And you can get rid of the model = Status declaration.

Try this:

from django import forms

class CreatePost(forms.Form):
    title = forms.CharField()
    username = forms.CharField()

    class meta:
        fields = ("title","username" )

Since it's not a ModelForm, the form has no idea what fields there are in the Status model. And it has no way to instantiate the fields (since they are not defined).

I think you probably want to use a ModelForm though, unless there's some compelling reason not to.


问:
Task return type with and without Async
I little bit confused on the behavior of the async keyword.

Lets say I have 2 methods,

```<code>public async Task DoSomething1()
{
    await Task.Run(() =>
    {
        for(int i = 0; i<3; i++)
        {
            Console.WriteLine("I m doing something:" + i);
        }
    });
}
</code>```

And

```<code>public Task DoSomething2()
{
    return Task.Run(() =>
    {
        for(int i = 0; i<3; i++)
        {
            Console.WriteLine("I m doing something:" + i);
        }
    });
}
</code>```

From my understanding both methods are awaitable. But when I write a method that has a Task return type without the async keyword I need to return a Task otherwise the compiler generates an error. Its a common thing that a method should return its type. But when I use it with the async keyword the compiler generates another error that you can't return a Task. So what does it mean? I am totally confused here.

答:
General Async Info

If you use await in your code, you are required to use the async keyword on the method.

If you use async and want to return an actual type, you can declare that your method returns the type as a generic Task like this Task<int>.

Here are the valid return types for an async method:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/async-return-types

Task<TResult>, for an async method that returns a value.

Task, for an async method that performs an operation but returns no value.

void, for an event handler.

A new answer August 2022

TL;DR - The return type is automatically wrapped in a Task.

I was receiving downvotes on this so I re-read the question in more detail and got to the root of it.  It's not about the return type in the signature of the method.  Its about the return value.  Also it is not a duplicate question!

Anyway, let's look at this method:

```<code>public Task TaskMethod()
{
    return Task.CompletedTask;
}
</code>```

This seems pretty normal and what we are used to in C#.  You declare the return type and return an object of that type.  Easy.  (In fact the "lowered" code is the exact same.)

Now for the async case.

```<code>public async Task MethodAsync()
{
    return Task.CompletedTask;
}
</code>```

This generates a compile error: error CS1997: Since 'C.MethodAsync()' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'?

OK, then we can't return a task directly, let's do the right thing.  It is easier to see this example if we return something so, let's return int.

```<code>public async Task<int> MethodAsync()
{
    return 1;
}
</code>```

(This method gives a warning that we are using async without await, but ignore this for now.)

The lowered code is complicated, but you can see that a state machine will be generated.  The MethodAsync looks like this:

```<code>[CompilerGenerated]
private sealed class <MethodAsync>d__0 : IAsyncStateMachine
{
    public int <>1__state;

    public AsyncTaskMethodBuilder<int> <>t__builder;

    public C <>4__this;

    private void MoveNext()
    {
        int num = <>1__state;
        int result;
        try
        {
            result = 1;
        }
        catch (Exception exception)
        {
            <>1__state = -2;
            <>t__builder.SetException(exception);
            return;
        }
        <>1__state = -2;
        <>t__builder.SetResult(result);
    }

    void IAsyncStateMachine.MoveNext()
    {
        //ILSpy generated this explicit interface implementation from .override directive in MoveNext
        this.MoveNext();
    }

    [DebuggerHidden]
    private void SetStateMachine(IAsyncStateMachine stateMachine)
    {
    }

    void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
    {
        //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
        this.SetStateMachine(stateMachine);
    }
}

[AsyncStateMachine(typeof(<MethodAsync>d__0))]
[DebuggerStepThrough]
public Task<int> MethodAsync()
{
    <MethodAsync>d__0 stateMachine = new <MethodAsync>d__0();
    stateMachine.<>t__builder = AsyncTaskMethodBuilder<int>.Create();
    stateMachine.<>4__this = this;
    stateMachine.<>1__state = -1;
    stateMachine.<>t__builder.Start(ref stateMachine);
    return stateMachine.<>t__builder.Task;
}
</code>```

And you can see the Task here is automatically returned in the public method.  The state machine implements the method body.

You can see that the actual value returned is the int from <>t__builder wrapped in a Task.

To see the lowered code yourself, you can try it in https://sharplab.io.

Also after writing all this I found another answer that explains it in a different way.  Guess who wrote that answer?
https://stackoverflow.com/a/37647093/1804678

Title: Task return type with and without Async

Body:
I little bit confused on the behavior of the async keyword.

Lets say I have 2 methods,

public async Task DoSomething1()
{
    await Task.Run(() =>
    {
        for(int i = 0; i<3; i++)
        {
            Console.WriteLine("I m doing something:" + i);
        }
    });
}

And

public Task DoSomething2()
{
    return Task.Run(() =>
    {
        for(int i = 0; i<3; i++)
        {
            Console.WriteLine("I m doing something:" + i);
        }
    });
}

From my understanding both methods are awaitable. But when I write a method that has a Task return type without the async keyword I need to return a Task otherwise the compiler generates an error. Its a common thing that a method should return its type. But when I use it with the async keyword the compiler generates another error that you can't return a Task. So what does it mean? I am totally confused here.

Body:
General Async Info

If you use await in your code, you are required to use the async keyword on the method.

If you use async and want to return an actual type, you can declare that your method returns the type as a generic Task like this Task<int>.

Here are the valid return types for an async method:

https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/async-return-types

Task<TResult>, for an async method that returns a value.

Task, for an async method that performs an operation but returns no value.

void, for an event handler.

A new answer August 2022

TL;DR - The return type is automatically wrapped in a Task.

I was receiving downvotes on this so I re-read the question in more detail and got to the root of it.  It's not about the return type in the signature of the method.  Its about the return value.  Also it is not a duplicate question!

Anyway, let's look at this method:

public Task TaskMethod()
{
    return Task.CompletedTask;
}

This seems pretty normal and what we are used to in C#.  You declare the return type and return an object of that type.  Easy.  (In fact the "lowered" code is the exact same.)

Now for the async case.

public async Task MethodAsync()
{
    return Task.CompletedTask;
}

This generates a compile error: error CS1997: Since 'C.MethodAsync()' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'?

OK, then we can't return a task directly, let's do the right thing.  It is easier to see this example if we return something so, let's return int.

public async Task<int> MethodAsync()
{
    return 1;
}

(This method gives a warning that we are using async without await, but ignore this for now.)

The lowered code is complicated, but you can see that a state machine will be generated.  The MethodAsync looks like this:

[CompilerGenerated]
private sealed class <MethodAsync>d__0 : IAsyncStateMachine
{
    public int <>1__state;

    public AsyncTaskMethodBuilder<int> <>t__builder;

    public C <>4__this;

    private void MoveNext()
    {
        int num = <>1__state;
        int result;
        try
        {
            result = 1;
        }
        catch (Exception exception)
        {
            <>1__state = -2;
            <>t__builder.SetException(exception);
            return;
        }
        <>1__state = -2;
        <>t__builder.SetResult(result);
    }

    void IAsyncStateMachine.MoveNext()
    {
        //ILSpy generated this explicit interface implementation from .override directive in MoveNext
        this.MoveNext();
    }

    [DebuggerHidden]
    private void SetStateMachine(IAsyncStateMachine stateMachine)
    {
    }

    void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
    {
        //ILSpy generated this explicit interface implementation from .override directive in SetStateMachine
        this.SetStateMachine(stateMachine);
    }
}

[AsyncStateMachine(typeof(<MethodAsync>d__0))]
[DebuggerStepThrough]
public Task<int> MethodAsync()
{
    <MethodAsync>d__0 stateMachine = new <MethodAsync>d__0();
    stateMachine.<>t__builder = AsyncTaskMethodBuilder<int>.Create();
    stateMachine.<>4__this = this;
    stateMachine.<>1__state = -1;
    stateMachine.<>t__builder.Start(ref stateMachine);
    return stateMachine.<>t__builder.Task;
}

And you can see the Task here is automatically returned in the public method.  The state machine implements the method body.

You can see that the actual value returned is the int from <>t__builder wrapped in a Task.

To see the lowered code yourself, you can try it in https://sharplab.io.

Also after writing all this I found another answer that explains it in a different way.  Guess who wrote that answer?
https://stackoverflow.com/a/37647093/1804678


问:
Aerospike server crashed with error "__setDR: Assertion `!”setDR ERROR”’ failed"
I am running aerospike server on ubuntu 16.04 on aarch64 device. Server is crashing with below error when I test with aerospike_test running on the same device

```<code>asd: bt_code.c:345: __setDR: Assertion `!“setDR ERROR”’ failed.
Dec 04 2017 17:09:00 GMT: WARNING (as): (signal.c:96) SIGABRT received, aborting Aerospike Community Edition build 3.15.0.0 os ubuntu16.04
Dec 04 2017 17:09:00 GMT: WARNING (as): (signal.c:100) stacktrace: found 1 frames
Dec 04 2017 17:09:00 GMT: WARNING (as): (signal.c:100) stacktrace: frame 0: ./target/Linux-aarch64/bin/asd(as_sig_handle_abort+0x58) [0x483e88]
Makefile:70: recipe for target ‘start’ failed
make: *** [start] Aborted
</code>```

Could you please help me to resolve this issue?

答:
You're using Aerospike Community Edition, which is an open source project. The repo for it is on GitHub at aerospike/aerospike-server.

As a community (as-in free) user, you should contribute to the project by opening a good bug report, or adding information to an existing, similar bug. On GitHub you do this by going to the issues page of the project. You can hit the New Issue button to open a new issue.

Please add information about your OS, kernel, the version of the server, and any other pertinent information.

Body:
I am running aerospike server on ubuntu 16.04 on aarch64 device. Server is crashing with below error when I test with aerospike_test running on the same device

asd: bt_code.c:345: __setDR: Assertion `!“setDR ERROR”’ failed.
Dec 04 2017 17:09:00 GMT: WARNING (as): (signal.c:96) SIGABRT received, aborting Aerospike Community Edition build 3.15.0.0 os ubuntu16.04
Dec 04 2017 17:09:00 GMT: WARNING (as): (signal.c:100) stacktrace: found 1 frames
Dec 04 2017 17:09:00 GMT: WARNING (as): (signal.c:100) stacktrace: frame 0: ./target/Linux-aarch64/bin/asd(as_sig_handle_abort+0x58) [0x483e88]
Makefile:70: recipe for target ‘start’ failed
make: *** [start] Aborted

Could you please help me to resolve this issue?