问:
I need assistance with creating a program
I'm having a tough time with creating a program that will print a triangle pattern based on the number value entered by the user while using nested while loop.

Here's my code.

```<code>import java.util.Scanner;

public class MyClass {
    public static void main(String args[]) {
        Scanner sc = new Scanner (System.in);
        int i, j;

        System.out.print("Enter a number: ");
        i = sc.nextInt();

        j = i - 1;

        while(i>0)
        {
            while(j<i)
            {
                System.out.print(" "+i+" ");
                --j;
            }
            System.out.println();
            --i;
        }
    }
}
</code>```

This should be the expected output

But when I execute the code, it just keeps typing the number I entered indefinitely.

答:
Your code is printing in an infinite loop because you did "while j is less than i".

j is only being subtracted in that loop, therefore will never be greater than i until j overflows at -2147483649.

I probably would have used for loops to code this, but because you used whiles in the question I will also use them here.

```<code>//...

//runs the amount of times you input
while(i > 0){

  /*
  j is being set to the same value as i, which means the following loop will print out the value of i.
  it will do this j number of times.
  A different variable is used so that we can iterate and count down while still printing the original value of i on that line
  */
  int j = i;
  while(j > 0){
    System.out.print(i + " ");
    j--;
  }

  System.out.println(); //goes to the next line after the current one is finished

  i--; //decreases the number being printed for each level in the triangle
}

//...
</code>```

Body:
I'm having a tough time with creating a program that will print a triangle pattern based on the number value entered by the user while using nested while loop.

Here's my code.

import java.util.Scanner;

public class MyClass {
    public static void main(String args[]) {
        Scanner sc = new Scanner (System.in);
        int i, j;

        System.out.print("Enter a number: ");
        i = sc.nextInt();

        j = i - 1;

        while(i>0)
        {
            while(j<i)
            {
                System.out.print(" "+i+" ");
                --j;
            }
            System.out.println();
            --i;
        }
    }
}

This should be the expected output

But when I execute the code, it just keeps typing the number I entered indefinitely.

Body:
Your code is printing in an infinite loop because you did "while j is less than i".

j is only being subtracted in that loop, therefore will never be greater than i until j overflows at -2147483649.

I probably would have used for loops to code this, but because you used whiles in the question I will also use them here.

//...

//runs the amount of times you input
while(i > 0){

  /*
  j is being set to the same value as i, which means the following loop will print out the value of i.
  it will do this j number of times.
  A different variable is used so that we can iterate and count down while still printing the original value of i on that line
  */
  int j = i;
  while(j > 0){
    System.out.print(i + " ");
    j--;
  }

  System.out.println(); //goes to the next line after the current one is finished

  i--; //decreases the number being printed for each level in the triangle
}

//...


来源: stackexchange

问:
Netezza, how to RAISE NOTICE with current time
Im trying to debug Netezza procedure using RAISE NOTICE after UPDATE AND INSERT queries. Im trying to show the current time after each query is finished.
I tried something like this:

```<code>RAISE NOTICE 'UPDATE time=%', now();
</code>```

But that doesn't work. Only way I have had it working is to define a timestamp variable at the beginning of procedure and then just before raising notice I define this variablie like this:

```<code>timevar:=now();
RAISE NOTICE 'UPDATE time=%', timevar;
</code>```

Is there a way where I can combine it just in one line and not have to define a new variable at beginning of procedure and assining it  now() each time I whant to RAISE NOTICE ?

答:
When you want to track progress through several steps in the same transaction, you can't use now() as that won't change.

It's a feature of transaction management within Postgres, that all statements within the same transaction get the same value for now()

However timeofday() DOES change, so you can use that.

And you can use a function in the place of identifier:

```<code>RAISE NOTICE 'UPDATE time=%', timeofday();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Im trying to debug Netezza procedure using RAISE NOTICE after UPDATE AND INSERT queries. Im trying to show the current time after each query is finished.
I tried something like this:

RAISE NOTICE 'UPDATE time=%', now();

But that doesn't work. Only way I have had it working is to define a timestamp variable at the beginning of procedure and then just before raising notice I define this variablie like this:

timevar:=now();
RAISE NOTICE 'UPDATE time=%', timevar;

Is there a way where I can combine it just in one line and not have to define a new variable at beginning of procedure and assining it  now() each time I whant to RAISE NOTICE ?

Body:
When you want to track progress through several steps in the same transaction, you can't use now() as that won't change.

It's a feature of transaction management within Postgres, that all statements within the same transaction get the same value for now()

However timeofday() DOES change, so you can use that.

And you can use a function in the place of identifier:

RAISE NOTICE 'UPDATE time=%', timeofday();

ContentLicense: CC BY-SA 4.0


问:
Parse a json data out from a tag
The text below is part of a string I parsed from html (pre). Since I can not place tags <> in this box I have replace the beginning and end tags as (pre) (/pre).

```<code>(pre)(b)Below are the details for server SomeServerName from NetSystem.(Data Length - 1)(/b)
[
    {
        "askId": "Value1",
        "billingCode": "99999999",
        "clusterId": null,
        "createdBy": "Mike",
        "createdFromLegacy": null,
        "createdOn": "2021-08-06T17:54:28.220Z",
        "description": "Windows 2019",
        "environment": "devops",
        "hostId": null,
        "id": "acd16582-b009-4667-aa95-5977603772sa",
        "infrastructure": {
            "apiId": "App2019_SA_1_v8-w2019_mike3_cc8f7e02-d426-423d-addb-b29bc7e163be",
            "capacityId": "ODI",
            "catalogManagementGroup": "Sales Marketing"
        },
        "legacyId": "XL143036181",
        "location": {
            "availabilityZone": "ny",
            "code": "mx31",
            "description": "uhg : mn053",
            "region": "west",
            "vendor": "apple"
        },
        "maintenance": {
            "group": "3",
            "status": "steady_state",
            "window": {
                "days": "Sunday",
                "endTime": "06:00:00.000Z",
                "startTime": "02:00:00.000Z"
            }
        },
        "name": "SomeServer",
        "network": {
            "fqdn": "SomeServer.dom.tes.contoso.com",
            "ipAddress": "xx.xx.xx.xx"
        },
        "os": {
            "description": "Microsoft windows 2019",
            "type": "windows",
            "vendor": "Microsoft",
            "version": "2019"
        },
        "owner": {
            "id": "000111111",
            "msid": "jtest"
        },
        "provision": {
            "id": "ba424e42-a925-49a5-a4b7-5dcf41b69d4e",
            "requestingApi": "mars Hub",
            "system": "vRealize"
        },
        "specs": {
            "cpuCount": 4,
            "description": "Virtual Hardware",
            "ram": 64384,
            "serialNumber": null
        },
        "status": "ACTIVE",
        "support": {
            "group": "Support group"
        },
        "tags": {
            "appTag": "minitab"
        },
        "updatedBy": "snir_agent",
        "updatedOn": "2021-08-06T17:54:31.525Z"
    }
](/pre)
</code>```

As you can see this is almost json data but I can not parse it as such because of the (b) (/b) tag that exists inside my (pre) (/pre) tag. How can I parse out this (b) tag with its content so I am left with the json data and can treat it as such enabling me to more easily select values with json functions.

答:
You can do this either by using re as indicated here or using split:

```<code>cleaned = data.split("(b)")[0] + data.split("(/b)")[1]
</code>```

Above line will concatenate the content before (b) and after (/b) cleaning the b tag and its content.

Title: Parse a json data out from a tag

Body:
The text below is part of a string I parsed from html (pre). Since I can not place tags <> in this box I have replace the beginning and end tags as (pre) (/pre).

(pre)(b)Below are the details for server SomeServerName from NetSystem.(Data Length - 1)(/b)
[
    {
        "askId": "Value1",
        "billingCode": "99999999",
        "clusterId": null,
        "createdBy": "Mike",
        "createdFromLegacy": null,
        "createdOn": "2021-08-06T17:54:28.220Z",
        "description": "Windows 2019",
        "environment": "devops",
        "hostId": null,
        "id": "acd16582-b009-4667-aa95-5977603772sa",
        "infrastructure": {
            "apiId": "App2019_SA_1_v8-w2019_mike3_cc8f7e02-d426-423d-addb-b29bc7e163be",
            "capacityId": "ODI",
            "catalogManagementGroup": "Sales Marketing"
        },
        "legacyId": "XL143036181",
        "location": {
            "availabilityZone": "ny",
            "code": "mx31",
            "description": "uhg : mn053",
            "region": "west",
            "vendor": "apple"
        },
        "maintenance": {
            "group": "3",
            "status": "steady_state",
            "window": {
                "days": "Sunday",
                "endTime": "06:00:00.000Z",
                "startTime": "02:00:00.000Z"
            }
        },
        "name": "SomeServer",
        "network": {
            "fqdn": "SomeServer.dom.tes.contoso.com",
            "ipAddress": "xx.xx.xx.xx"
        },
        "os": {
            "description": "Microsoft windows 2019",
            "type": "windows",
            "vendor": "Microsoft",
            "version": "2019"
        },
        "owner": {
            "id": "000111111",
            "msid": "jtest"
        },
        "provision": {
            "id": "ba424e42-a925-49a5-a4b7-5dcf41b69d4e",
            "requestingApi": "mars Hub",
            "system": "vRealize"
        },
        "specs": {
            "cpuCount": 4,
            "description": "Virtual Hardware",
            "ram": 64384,
            "serialNumber": null
        },
        "status": "ACTIVE",
        "support": {
            "group": "Support group"
        },
        "tags": {
            "appTag": "minitab"
        },
        "updatedBy": "snir_agent",
        "updatedOn": "2021-08-06T17:54:31.525Z"
    }
](/pre)

As you can see this is almost json data but I can not parse it as such because of the (b) (/b) tag that exists inside my (pre) (/pre) tag. How can I parse out this (b) tag with its content so I am left with the json data and can treat it as such enabling me to more easily select values with json functions.

Body:
You can do this either by using re as indicated here or using split:

cleaned = data.split("(b)")[0] + data.split("(/b)")[1]

Above line will concatenate the content before (b) and after (/b) cleaning the b tag and its content.


问:
Writing to a file with mode "w" versus "a" - I can't get "w" to work properly
Let me start out by saying I am very new to Python.  I'm taking a Udemy bootcamp, so I am not by any means condoning my solution as the best solution, but for the life of me, I cannot figure out why, when I write to the output files, I have to use mode "a" instead of "w".  If I use "w", it only writes the last line of the starting_letter.txt.

invited_names.txt is a .txt file attached to the project with the following records.  There is no new line \n after the last name in the file:

```<code>Aang
Zuko
Appa
Katara
Sokka
Momo
Uncle Iroh
Toph
</code>```

The starting_letter.txt file is also attached to my project.

```<code>Dear [name],

You are invited to my birthday this Saturday.

Hope you can make it!

Joel
</code>```

The function of the program is to replace [name] from the first record in the starting_letter.txt file with a name from the invited_names.txt file and create an output file for each name in invited_names.txt. I would prefer to use mode "w" so the files get overlaid each time the file runs because mode "a" obviously will append to an existing file if it already exists. I compared my code to the instructor's solution, and I can't see why hers works with "w", but mine doesn't.

```<code>invited_names = open("./Input/Names/invited_names.txt")
invited_names_list = invited_names.readlines()

for i in range(len(invited_names_list)):
    invited_names_list[i] = invited_names_list[i].strip()

starting_letter = open("./Input/Letters/starting_letter.txt")
starting_letter_list = starting_letter.readlines()

for name in invited_names_list:
    for line in starting_letter_list:
        new_line = line.replace("[name]", name)
        with open(f"./Output/ReadyToSend/letter_for_{name}.txt", mode="a") as file:
            file.write(new_line)
</code>```

答:
Updated functional code, please note the line of code that opens the file. In w mode it opens a new file and it should be outside of the for loop. In your code it opens a new file inside the second for loop and gets overwritten in each iteration of second for loop.

```<code>invited_names = open("tmp_data/invited.txt")
invited_names_list = invited_names.readlines()

for i in range(len(invited_names_list)):
    invited_names_list[i] = invited_names_list[i].strip()

starting_letter = open("tmp_data/starting_letter.txt")
starting_letter_list = starting_letter.readlines()

for name in invited_names_list:
    with open(f"tmp_data/letter_for_{name}.txt", mode="w") as file:
        for line in starting_letter_list:
            new_line = line.replace("[name]", name)
            file.write(new_line)
</code>```

Body:
Let me start out by saying I am very new to Python.  I'm taking a Udemy bootcamp, so I am not by any means condoning my solution as the best solution, but for the life of me, I cannot figure out why, when I write to the output files, I have to use mode "a" instead of "w".  If I use "w", it only writes the last line of the starting_letter.txt.

invited_names.txt is a .txt file attached to the project with the following records.  There is no new line \n after the last name in the file:

Aang
Zuko
Appa
Katara
Sokka
Momo
Uncle Iroh
Toph

The starting_letter.txt file is also attached to my project.

Dear [name],

You are invited to my birthday this Saturday.

Hope you can make it!

Joel

The function of the program is to replace [name] from the first record in the starting_letter.txt file with a name from the invited_names.txt file and create an output file for each name in invited_names.txt. I would prefer to use mode "w" so the files get overlaid each time the file runs because mode "a" obviously will append to an existing file if it already exists. I compared my code to the instructor's solution, and I can't see why hers works with "w", but mine doesn't.

invited_names = open("./Input/Names/invited_names.txt")
invited_names_list = invited_names.readlines()

for i in range(len(invited_names_list)):
    invited_names_list[i] = invited_names_list[i].strip()

starting_letter = open("./Input/Letters/starting_letter.txt")
starting_letter_list = starting_letter.readlines()

for name in invited_names_list:
    for line in starting_letter_list:
        new_line = line.replace("[name]", name)
        with open(f"./Output/ReadyToSend/letter_for_{name}.txt", mode="a") as file:
            file.write(new_line)

Body:
Updated functional code, please note the line of code that opens the file. In w mode it opens a new file and it should be outside of the for loop. In your code it opens a new file inside the second for loop and gets overwritten in each iteration of second for loop.

invited_names = open("tmp_data/invited.txt")
invited_names_list = invited_names.readlines()

for i in range(len(invited_names_list)):
    invited_names_list[i] = invited_names_list[i].strip()

starting_letter = open("tmp_data/starting_letter.txt")
starting_letter_list = starting_letter.readlines()

for name in invited_names_list:
    with open(f"tmp_data/letter_for_{name}.txt", mode="w") as file:
        for line in starting_letter_list:
            new_line = line.replace("[name]", name)
            file.write(new_line)


问:
How do I replace if statements with ? operator for making a shader work on mobile?
I'm porting a custom shader to make it work on mobile phones since shaders inside mobiles can not have if statements.

I tried replacing the if statements of my code with the ? operator but I can not compile in Unity without errors. I'm pretty new to c# so it is obvious to myself I am missing something here to complete this.
Any advice from more experienced programmers here? Many thanks to you all.

// The original code is commented.

I also tried to store the result inside a variable and return it but also didn't work.

/*
if (charCol.r > .8f)
{
    if(_monochromatic == 1)
        return float4(0, gray, 0, 1);
    else
        return col;
}
else
{
    return col * _brightness;
}
*/

charCol.r > .8f ? (_monochromatic == 1) ? return float4(0, gray, 0, 1) : return col : return col * _brightness;
```

Error message:

Shader error in 'Custom/Shader': syntax error: unexpected token 'return'

答:
You should return as below:

return charCol.r > .8f
    ? ((_monochromatic == 1) ? float4(0, gray, 0, 1) : col)
    : col * _brightness;
```

Small opinion:

Even you can return value with the ternary operator, you may get a headache if the logic is complex and difficult to maintain.

Body:
I'm porting a custom shader to make it work on mobile phones since shaders inside mobiles can not have if statements.

I tried replacing the if statements of my code with the ? operator but I can not compile in Unity without errors. I'm pretty new to c# so it is obvious to myself I am missing something here to complete this.
Any advice from more experienced programmers here? Many thanks to you all.

// The original code is commented.

I also tried to store the result inside a variable and return it but also didn't work.

/*
if (charCol.r > .8f)
{
    if(_monochromatic == 1)
        return float4(0, gray, 0, 1);
    else
        return col;
}
else
{
    return col * _brightness;
}
*/

charCol.r > .8f ? (_monochromatic == 1) ? return float4(0, gray, 0, 1) : return col : return col * _brightness;

Error message:

Shader error in 'Custom/Shader': syntax error: unexpected token 'return'

Body:
You should return as below:

return charCol.r > .8f
    ? ((_monochromatic == 1) ? float4(0, gray, 0, 1) : col)
    : col * _brightness;

Small opinion:

Even you can return value with the ternary operator, you may get a headache if the logic is complex and difficult to maintain.


问:
android emulator error:[2011-08-02 11:14:01 - Emulator] PANIC: Could not open: C:\Users\hallo\.android/avd/myemu.ini
I am beginner android application developer. I have done lot of apps in eclipse on emulator and device also. But now it is giving error at the time of running project on emulator. It is working on device phone but on emulator it is giving following error:

```<code>[2011-08-02 11:14:00 - hello1] ------------------------------

[2011-08-02 11:14:00 - hello1] Android Launch!

[2011-08-02 11:14:00 - hello1] adb is running normally.

[2011-08-02 11:14:00 - hello1] Performing com.mahiways.Hello1.Hello1Activity activity launch

[2011-08-02 11:14:00 - hello1] Automatic Target Mode: launching new emulator with compatible AVD 'myemu'

[2011-08-02 11:14:00 - hello1] Launching a new emulator with Virtual Device 'myemu'

[2011-08-02 11:14:01 - Emulator] PANIC: Could not open: C:\Users\hallo\.android/avd/myemu.ini
</code>```

How can I solve this problem?

答:
I was having this problem also but finally found a solution.

What you need to do is:

1. Create a new Windows system variable called ANDROID_SDK_HOME and set it to the directory of your Android SDK installation

2. In your "eclipse\configuration.settings\org.eclipse.ui.ide.prefs" file, also add a definition for ANDROID_SDK_Home

Then, all of your AVD files will be created in your "android-sdk/.android/avd" folder

Body:
I am beginner android application developer. I have done lot of apps in eclipse on emulator and device also. But now it is giving error at the time of running project on emulator. It is working on device phone but on emulator it is giving following error:

[2011-08-02 11:14:00 - hello1] ------------------------------

[2011-08-02 11:14:00 - hello1] Android Launch!

[2011-08-02 11:14:00 - hello1] adb is running normally.

[2011-08-02 11:14:00 - hello1] Performing com.mahiways.Hello1.Hello1Activity activity launch

[2011-08-02 11:14:00 - hello1] Automatic Target Mode: launching new emulator with compatible AVD 'myemu'

[2011-08-02 11:14:00 - hello1] Launching a new emulator with Virtual Device 'myemu'

[2011-08-02 11:14:01 - Emulator] PANIC: Could not open: C:\Users\hallo\.android/avd/myemu.ini

How can I solve this problem?


问:
how character pointer could be used to point a string in c++?
First of all I am beginner in C++. I was trying to learn about type casting in C++ with strings and character pointer. Is it possible to point a string with a character pointer?

```<code>int main() {
    string data="LetsTry";
    cout<<(&data)<<"\n";
    cout<<data<<"\n"<<"size "<<sizeof(data)<<"\n";
    //char *ptr = static_cast<char*>(data);
    //char *ptr=(char*)data;
    char *ptr = reinterpret_cast<char*>(&data);
    cout<<(ptr)<<"\n";
    cout<<*ptr;
}
</code>```

The above code yields outcome as below:

```<code>0x7ffea4a06150
LetsTry
size 32
`a���
`
</code>```

I understand as ptr should output the address 0x7ffea4a06150

答:
In C++, string is class and what you doing is creating a string object. So, to use are char * you need to convert it using c_str()

You can refer below code:

```<code>std::string data = "LetsTry";

// declaring character array
char * cstr = new char [data.length()+1];

// copying the contents of the
// string to char array
std::strcpy (cstr, data.c_str());
</code>```

Now, you can get use char * to point your data.

Body:
First of all I am beginner in C++. I was trying to learn about type casting in C++ with strings and character pointer. Is it possible to point a string with a character pointer?

int main() {
    string data="LetsTry";
    cout<<(&data)<<"\n";
    cout<<data<<"\n"<<"size "<<sizeof(data)<<"\n";
    //char *ptr = static_cast<char*>(data);
    //char *ptr=(char*)data;
    char *ptr = reinterpret_cast<char*>(&data);
    cout<<(ptr)<<"\n";
    cout<<*ptr;
}

The above code yields outcome as below:

0x7ffea4a06150
LetsTry
size 32
`a���
`

I understand as ptr should output the address 0x7ffea4a06150

Body:
In C++, string is class and what you doing is creating a string object. So, to use are char * you need to convert it using c_str()

You can refer below code:

std::string data = "LetsTry";

// declaring character array
char * cstr = new char [data.length()+1];

// copying the contents of the
// string to char array
std::strcpy (cstr, data.c_str());

Now, you can get use char * to point your data.


问:
How can i install pygame on my internet not connected computer?
i'm trying to install pygame package on my computer which one is not connected to internet.

(env : windows10, python 3.9(anaconda))

so i downloaded a "pygame-2.1.2.tar" file from www.pypi.org and then tried to install it

from cmd with "python setup.py install" commend.

then it shows error message like below

```<code>    ===============================================================================

    (base) C:\pythonpackage\pygame-2.1.2>python setup.py install

    WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
    Using WINDOWS configuration...

    Making dir :prebuilt_downloads:
    Downloading... https://www.libsdl.org/release/SDL2-devel-2.0.18-VC.zip
    d561079ec622b0bab5a9e02976f5d540b0622da

    ---
    For help with compilation see:
        https://www.pygame.org/wiki/CompileWindows
    To contribute to pygame development see:
        https://www.pygame.org/contribute.html
    ---

    Traceback (most recent call last):
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py", line 174, in
    _new_conn
        conn = connection.create_connection(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\util\connection.py", line 73,
    in create_connection
        for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
      File "C:\ProgramData\Anaconda3\lib\socket.py", line 954, in getaddrinfo
        for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
    socket.gaierror: [Errno 11002] getaddrinfo failed

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 699,
    in urlopen
        httplib_response = self._make_request(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 382,
    in _make_request
        self._validate_conn(conn)
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 1010,
    in _validate_conn
        conn.connect()
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py", line 358, in
    connect
        conn = self._new_conn()
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py", line 186, in
    _new_conn
        raise NewConnectionError(
    urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at
    0x00000237AF075250>: Failed to establish a new connection: [Errno 11002] getaddrinfo
    failed

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py", line 439, in
    send
        resp = conn.urlopen(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 755,
    in urlopen
        retries = retries.increment(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\util\retry.py", line 574, in
    increment
        raise MaxRetryError(_pool, url, error or ResponseError(cause))
    urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='www.libsdl.org', port=443):
    Max retries exceeded with url: /release/SDL2-devel-2.0.18-VC.zip (Caused by
    NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000237AF075250>:
    Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\pythonpackage\pygame-2.1.2\setup.py", line 359, in <module>
        buildconfig.config.main(AUTO_CONFIG)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\config.py", line 225, in main
        deps = CFG.main(**kwds)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\config_win.py", line 497, in main
        and download_win_prebuilt.ask(**download_kwargs):
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 290, in
    ask
        update(x86=x86, x64=x64)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 273, in
    update
        download_prebuilts(download_dir, x86=x86, x64=x64)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 124, in
    download_prebuilts
        download_sha1_unzip(url, checksum, temp_dir, 1)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 47, in
    download_sha1_unzip
        response = requests.get(url)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py", line 75, in get
        return request('get', url, params=params, **kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py", line 61, in request
        return session.request(method=method, url=url, **kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py", line 542, in
    request
        resp = self.send(prep, **send_kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py", line 655, in
    send
        r = adapter.send(request, **kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py", line 516, in
    send
        raise ConnectionError(e, request=request)
    requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.libsdl.org', port=443):
    Max retries exceeded with url: /release/SDL2-devel-2.0.18-VC.zip (Caused by
    NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000237AF075250>:
    Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))

    ===============================================================================
</code>```

please let me know how to install pygame on offline environment.

i need your help!! please~~

答: you can run command: pip install pygame</p>

Body:
i'm trying to install pygame package on my computer which one is not connected to internet.

(env : windows10, python 3.9(anaconda))

so i downloaded a "pygame-2.1.2.tar" file from www.pypi.org and then tried to install it

from cmd with "python setup.py install" commend.

then it shows error message like below

    ===============================================================================

    (base) C:\pythonpackage\pygame-2.1.2>python setup.py install

    WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
    Using WINDOWS configuration...

    Making dir :prebuilt_downloads:
    Downloading... https://www.libsdl.org/release/SDL2-devel-2.0.18-VC.zip
    d561079ec622b0bab5a9e02976f5d540b0622da

    ---
    For help with compilation see:
        https://www.pygame.org/wiki/CompileWindows
    To contribute to pygame development see:
        https://www.pygame.org/contribute.html
    ---

    Traceback (most recent call last):
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py", line 174, in
    _new_conn
        conn = connection.create_connection(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\util\connection.py", line 73,
    in create_connection
        for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
      File "C:\ProgramData\Anaconda3\lib\socket.py", line 954, in getaddrinfo
        for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
    socket.gaierror: [Errno 11002] getaddrinfo failed

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 699,
    in urlopen
        httplib_response = self._make_request(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 382,
    in _make_request
        self._validate_conn(conn)
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 1010,
    in _validate_conn
        conn.connect()
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py", line 358, in
    connect
        conn = self._new_conn()
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connection.py", line 186, in
    _new_conn
        raise NewConnectionError(
    urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPSConnection object at
    0x00000237AF075250>: Failed to establish a new connection: [Errno 11002] getaddrinfo
    failed

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py", line 439, in
    send
        resp = conn.urlopen(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\connectionpool.py", line 755,
    in urlopen
        retries = retries.increment(
      File "C:\ProgramData\Anaconda3\lib\site-packages\urllib3\util\retry.py", line 574, in
    increment
        raise MaxRetryError(_pool, url, error or ResponseError(cause))
    urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='www.libsdl.org', port=443):
    Max retries exceeded with url: /release/SDL2-devel-2.0.18-VC.zip (Caused by
    NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000237AF075250>:
    Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "C:\pythonpackage\pygame-2.1.2\setup.py", line 359, in <module>
        buildconfig.config.main(AUTO_CONFIG)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\config.py", line 225, in main
        deps = CFG.main(**kwds)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\config_win.py", line 497, in main
        and download_win_prebuilt.ask(**download_kwargs):
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 290, in
    ask
        update(x86=x86, x64=x64)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 273, in
    update
        download_prebuilts(download_dir, x86=x86, x64=x64)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 124, in
    download_prebuilts
        download_sha1_unzip(url, checksum, temp_dir, 1)
      File "C:\pythonpackage\pygame-2.1.2\buildconfig\download_win_prebuilt.py", line 47, in
    download_sha1_unzip
        response = requests.get(url)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py", line 75, in get
        return request('get', url, params=params, **kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\api.py", line 61, in request
        return session.request(method=method, url=url, **kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py", line 542, in
    request
        resp = self.send(prep, **send_kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\sessions.py", line 655, in
    send
        r = adapter.send(request, **kwargs)
      File "C:\ProgramData\Anaconda3\lib\site-packages\requests\adapters.py", line 516, in
    send
        raise ConnectionError(e, request=request)
    requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.libsdl.org', port=443):
    Max retries exceeded with url: /release/SDL2-devel-2.0.18-VC.zip (Caused by
    NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000237AF075250>:
    Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))

    ===============================================================================

please let me know how to install pygame on offline environment.

i need your help!! please~~

Body: you can run command: pip install pygame


问:
Get value from pseudo element with python
I would like to get the price value from the pseudo element you see on the picture below. If I hover over the mouse only then I can see some value like the price it costs( that is what I need). I found the "move_to_element" so now I can hover over the mouse with the program but I still cant get the price out of the element.
The problem is that even if I hover over my mouse I cant see the element opening in the inspector tab.

Thank you!

This is the code I would like to get out the :before element from:

```<code><div onclick="Game.UpgradesById[503].click(event);" class="crate upgrade enabled" onmouseout="Game.setOnCrate(0);Game.tooltip.shouldHide=1;" onmouseover="if (!Game.mouseDown) {Game.setOnCrate(this);Game.tooltip.dynamic=1;Game.tooltip.draw(this,function(){return function(){return Game.crateTooltip(Game.UpgradesById[503],'store');}();},'store');Game.tooltip.wobble();}" id="upgrade0" style="background-position:-1056px -1296px;"></div>
</code>```

After this there is an en element ::before and end of the div

答:
When I visited the website manually, I get somewhat like what you showed, but when I run through automation, it does not show any Upgrades. Hence, I had to stick to checking the identities (like Grandma, Cursor, etc); but they didn't show in automated version. Only the users ??? are seen. Snapshot

Eventually, I tried it with ??? only. I tried a different approach, instead of using ::before or ::after, I tried to see if any tooltip exists somewhere, and it does exist. The only caveat is that I was able to fetch all the text from the hover (from which again we have to extract what is required through code). On this context, here is the code:

```<code>driver.get("https://orteil.dashnet.org/cookieclicker/")
time.sleep(10)
ActionChains(driver).move_to_element(driver.find_element(By.ID, 'product0')).perform()
time.sleep(1)
x = driver.find_element(By.ID, 'tooltip').text
print(x)
</code>```

Here is the output:

```<code>15
???
[owned : 0]

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

Please change the element to the element that you want and you should get the result.

Body:
I would like to get the price value from the pseudo element you see on the picture below. If I hover over the mouse only then I can see some value like the price it costs( that is what I need). I found the "move_to_element" so now I can hover over the mouse with the program but I still cant get the price out of the element.
The problem is that even if I hover over my mouse I cant see the element opening in the inspector tab.

Thank you!

This is the code I would like to get out the :before element from:

After this there is an en element ::before and end of the div

Body:
When I visited the website manually, I get somewhat like what you showed, but when I run through automation, it does not show any Upgrades. Hence, I had to stick to checking the identities (like Grandma, Cursor, etc); but they didn't show in automated version. Only the users ??? are seen. Snapshot

Eventually, I tried it with ??? only. I tried a different approach, instead of using ::before or ::after, I tried to see if any tooltip exists somewhere, and it does exist. The only caveat is that I was able to fetch all the text from the hover (from which again we have to extract what is required through code). On this context, here is the code:

driver.get("https://orteil.dashnet.org/cookieclicker/")
time.sleep(10)
ActionChains(driver).move_to_element(driver.find_element(By.ID, 'product0')).perform()
time.sleep(1)
x = driver.find_element(By.ID, 'tooltip').text
print(x)

Here is the output:

15
???
[owned : 0]

Process finished with exit code 0

Please change the element to the element that you want and you should get the result.


问:
Is there anyway to shorten the amount of lines used for having multiple turtles?
So I'm trying to make a program where I want to have many turtles. But I was wondering if instead of writing every single name to instate a new turtle being made, I could make it as short as one line if it's possible on Python turtle. I just want to do this to make the program shorter and easier to understand because looking at say 20 lines of 20 different turtles would not look good. Also, I don't want to use clones as each turtle needs to have something specific to it and will have different variables set to it.</p>
```<code>import turtle

a1 = turtle.Turtle()
b1 = turtle.Turtle()
c1 = turtle.Turtle()
d1 = turtle.Turtle()
a2 = turtle.Turtle()
b2 = turtle.Turtle()
c2 = turtle.Turtle()
d2 = turtle.Turtle()
a3 = turtle.Turtle()
b3 = turtle.Turtle()
c3 = turtle.Turtle()
d3 = turtle.Turtle()
</code>```

答:
I just want to do this to make the program shorter and easier to
understand

Given that you already have a sense of name for your turtles, I think using numeric indexes to access them would make your program harder to understand so contrary to the other answer and comment, I'll suggest that instead of a list you go with a dict:

```<code>from turtle import Screen, Turtle
from itertools import product

screen = Screen()

turtles = {a + str(n): Turtle() for a, n in product("abcd", range(1, 4))}

turtles['b3'].circle(100)
turtles['d1'].circle(-50, steps=5)

screen.exitonclick()
</code>```

Body:
So I'm trying to make a program where I want to have many turtles. But I was wondering if instead of writing every single name to instate a new turtle being made, I could make it as short as one line if it's possible on Python turtle. I just want to do this to make the program shorter and easier to understand because looking at say 20 lines of 20 different turtles would not look good. Also, I don't want to use clones as each turtle needs to have something specific to it and will have different variables set to it.

import turtle

a1 = turtle.Turtle()
b1 = turtle.Turtle()
c1 = turtle.Turtle()
d1 = turtle.Turtle()
a2 = turtle.Turtle()
b2 = turtle.Turtle()
c2 = turtle.Turtle()
d2 = turtle.Turtle()
a3 = turtle.Turtle()
b3 = turtle.Turtle()
c3 = turtle.Turtle()
d3 = turtle.Turtle()

Body:
I just want to do this to make the program shorter and easier to
understand

Given that you already have a sense of name for your turtles, I think using numeric indexes to access them would make your program harder to understand so contrary to the other answer and comment, I'll suggest that instead of a list you go with a dict:

from turtle import Screen, Turtle
from itertools import product

screen = Screen()

turtles = {a + str(n): Turtle() for a, n in product("abcd", range(1, 4))}

turtles['b3'].circle(100)
turtles['d1'].circle(-50, steps=5)

screen.exitonclick()


问:
Consistent updating of validation state in a custom reactive form control?
I'm trying to create a material username reactive form control using the approach outlined in this tutorial.

The end result should work in a form like this ( the fs-username-form is the custom reactive form component ):

```<code><mat-card class="UsernameFormTestCard">
  <form class="UsernameForm" [formGroup]="form" (ngSubmit)="submit()">
    <mat-form-field>
      <input
        matInput
        placeholder="First name"
        type="text"
        formControlName="firstName"
      />
      <mat-hint *ngIf="!username">Example Monica</mat-hint>
      <mat-error>Please enter your first name</mat-error>
    </mat-form-field>

    <fs-username-form formControlName="username"></fs-username-form>

    <button mat-button type="submit" [disabled]="!form.valid">Submit</button>
  </form>
</mat-card>

</code>```

If the form is valid then the Submit button enables.

And it works ... sort of ... It enables reactively ... but not consistently.  The minimum number of characters is set to 4.  And the submit button enables when the length is 4.  However if we start removing characters from the username the submit button only disables after the length of the username is 2.

This is the Stackblitz demo showing this.

The username-form.component.ts is implemented like this:

```<code>import { Component } from '@angular/core';
import {
  AbstractControl,
  ControlValueAccessor,
  FormControl,
  FormGroup,
  NG_VALIDATORS,
  NG_VALUE_ACCESSOR,
  ValidationErrors,
  Validator,
  Validators,
} from '@angular/forms';

@Component({
  selector: 'fs-username-form',
  templateUrl: './username-form.component.html',
  styleUrls: ['./username-form.component.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      multi: true,
      useExisting: UsernameFormComponent,
    },
    {
      provide: NG_VALIDATORS,
      multi: true,
      useExisting: UsernameFormComponent,
    },
  ],
})
export class UsernameFormComponent implements ControlValueAccessor, Validator {
  //=============================================
  // ControlValueAccessor API Methods
  //=============================================
  disabled: boolean = false;
  // Dummy initialization.
  //The implementation is passed in
  // with registerOnChange.
  onChange = (username: string) => {};
  onTouched = () => {};
  touched = false;
  usernameValue = '';

  writeValue(username: any): void {
    this.usernameValue = username;
  }

  //=============================================
  // Registration API Methods
  //=============================================

  registerOnChange(onChange: any): void {
    this.onChange = onChange;
  }

  registerOnTouched(onTouched: any): void {
    this.onTouched = onTouched;
  }

  markAsTouched() {
    if (!this.touched) {
      this.onTouched();
      this.touched = true;
    }
  }

  setDisabledState(disabled: boolean) {
    this.disabled = disabled;
    if (disabled) {
      this.usernameControl?.disable();
    } else {
      this.usernameControl?.enable();
    }
  }

  //=============================================
  // Validator API Methods
  //=============================================
  validate(control: AbstractControl): ValidationErrors | null {
    console.log('VALIDATE IS GETTING CALLED');
    console.log('Is the form valid: ', this.usernameForm.valid);

    if (this.usernameForm.valid) {
      return null;
    }

    let errors: any = {};

    errors = this.addControlErrors(errors, 'username');

    return errors;
  }

  addControlErrors(allErrors: any, controlName: string) {
    const errors = { ...allErrors };
    const controlErrors = this.usernameForm.controls[controlName].errors;

    if (controlErrors) {
      errors[controlName] = controlErrors;
    }
    return errors;
  }

  /**
   * Registers a call to onChange to inform
   * parent forms of valueChanges events.
   */
  constructor() {
    this.usernameControl?.valueChanges.subscribe((u) => {
      this.onChange(u);
    });
  }

  public usernameForm: FormGroup = new FormGroup({
    username: new FormControl('', [
      Validators.required,
      Validators.minLength(4),
    ]),
  });

  get username() {
    return this.usernameForm.get('username')?.value;
  }

  get usernameControl() {
    return this.usernameForm.get('username');
  }
}

</code>```

The username-form.component.html template looks like this:

```<code><form class="UsernameForm" [formGroup]="usernameForm">
  <mat-form-field>
    <input
      matInput
      placeholder="username"
      type="text"
      formControlName="username"
    />
    <mat-hint *ngIf="!username">Example Monica</mat-hint>
    <mat-error>Please enter your username</mat-error>
  </mat-form-field>
</form>

</code>```

As can be seen it implements the ControlValueAccessor and  Validator interfaces.

Call on onChange are made when the user types in the username field and, if I understand correctly, this in turn should cause the parent form to call validate on the username control.

Why does the submit button in the demo form not update consistently or why the username-form component does not?

答:
Got it working.  Instead of checking whether the form containing the control is valid in the validate method, I switched it to check whether the control itself is valid like this:

```<code>  //=============================================
  // Validator API Methods
  //=============================================
  validate(control: AbstractControl): ValidationErrors | null {

    if (this.usernameControl.valid) {
      return null;
    }

    let errors: any = {};

    errors = this.addControlErrors(errors, 'username');

    return errors;
  }
</code>```

And now it works.  This is a new working demo.

Body:
I'm trying to create a material username reactive form control using the approach outlined in this tutorial.

The end result should work in a form like this ( the fs-username-form is the custom reactive form component ):

<mat-card class="UsernameFormTestCard">
  <form class="UsernameForm" [formGroup]="form" (ngSubmit)="submit()">
    <mat-form-field>
      <input
        matInput
        placeholder="First name"
        type="text"
        formControlName="firstName"
      />
      <mat-hint *ngIf="!username">Example Monica</mat-hint>
      <mat-error>Please enter your first name</mat-error>
    </mat-form-field>

    <fs-username-form formControlName="username"></fs-username-form>

    <button mat-button type="submit" [disabled]="!form.valid">Submit</button>
  </form>
</mat-card>

If the form is valid then the Submit button enables.

And it works ... sort of ... It enables reactively ... but not consistently.  The minimum number of characters is set to 4.  And the submit button enables when the length is 4.  However if we start removing characters from the username the submit button only disables after the length of the username is 2.

This is the Stackblitz demo showing this.

The username-form.component.ts is implemented like this:

import { Component } from '@angular/core';
import {
  AbstractControl,
  ControlValueAccessor,
  FormControl,
  FormGroup,
  NG_VALIDATORS,
  NG_VALUE_ACCESSOR,
  ValidationErrors,
  Validator,
  Validators,
} from '@angular/forms';

@Component({
  selector: 'fs-username-form',
  templateUrl: './username-form.component.html',
  styleUrls: ['./username-form.component.css'],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      multi: true,
      useExisting: UsernameFormComponent,
    },
    {
      provide: NG_VALIDATORS,
      multi: true,
      useExisting: UsernameFormComponent,
    },
  ],
})
export class UsernameFormComponent implements ControlValueAccessor, Validator {
  //=============================================
  // ControlValueAccessor API Methods
  //=============================================
  disabled: boolean = false;
  // Dummy initialization.
  //The implementation is passed in
  // with registerOnChange.
  onChange = (username: string) => {};
  onTouched = () => {};
  touched = false;
  usernameValue = '';

  writeValue(username: any): void {
    this.usernameValue = username;
  }

  //=============================================
  // Registration API Methods
  //=============================================

  registerOnChange(onChange: any): void {
    this.onChange = onChange;
  }

  registerOnTouched(onTouched: any): void {
    this.onTouched = onTouched;
  }

  markAsTouched() {
    if (!this.touched) {
      this.onTouched();
      this.touched = true;
    }
  }

  setDisabledState(disabled: boolean) {
    this.disabled = disabled;
    if (disabled) {
      this.usernameControl?.disable();
    } else {
      this.usernameControl?.enable();
    }
  }

  //=============================================
  // Validator API Methods
  //=============================================
  validate(control: AbstractControl): ValidationErrors | null {
    console.log('VALIDATE IS GETTING CALLED');
    console.log('Is the form valid: ', this.usernameForm.valid);

    if (this.usernameForm.valid) {
      return null;
    }

    let errors: any = {};

    errors = this.addControlErrors(errors, 'username');

    return errors;
  }

  addControlErrors(allErrors: any, controlName: string) {
    const errors = { ...allErrors };
    const controlErrors = this.usernameForm.controls[controlName].errors;

    if (controlErrors) {
      errors[controlName] = controlErrors;
    }
    return errors;
  }

  /**
   * Registers a call to onChange to inform
   * parent forms of valueChanges events.
   */
  constructor() {
    this.usernameControl?.valueChanges.subscribe((u) => {
      this.onChange(u);
    });
  }

  public usernameForm: FormGroup = new FormGroup({
    username: new FormControl('', [
      Validators.required,
      Validators.minLength(4),
    ]),
  });

  get username() {
    return this.usernameForm.get('username')?.value;
  }

  get usernameControl() {
    return this.usernameForm.get('username');
  }
}

The username-form.component.html template looks like this:

<form class="UsernameForm" [formGroup]="usernameForm">
  <mat-form-field>
    <input
      matInput
      placeholder="username"
      type="text"
      formControlName="username"
    />
    <mat-hint *ngIf="!username">Example Monica</mat-hint>
    <mat-error>Please enter your username</mat-error>
  </mat-form-field>
</form>

As can be seen it implements the ControlValueAccessor and  Validator interfaces.

Call on onChange are made when the user types in the username field and, if I understand correctly, this in turn should cause the parent form to call validate on the username control.

Why does the submit button in the demo form not update consistently or why the username-form component does not?

Body:
Got it working.  Instead of checking whether the form containing the control is valid in the validate method, I switched it to check whether the control itself is valid like this:

  //=============================================
  // Validator API Methods
  //=============================================
  validate(control: AbstractControl): ValidationErrors | null {

    if (this.usernameControl.valid) {
      return null;
    }

    let errors: any = {};

    errors = this.addControlErrors(errors, 'username');

    return errors;
  }

And now it works.  This is a new working demo.


问:
Capturing stdout result of `flutter test integration_test`
For CI, I need to write a program that runs flutter test integration_test and captures the stdout result. In python the code would be:

import subprocess

process = subprocess.Popen(
    f'flutter test integration_test',
    shell=True,
    universal_newlines=True,
    stderr=subprocess.PIPE,
    stdout=subprocess.PIPE)

print('starting')

for line in process.stdout:
    print(f'[from python]: {line}')
```
<p>If you run the above code in the example directory of a plugin package(for example path_provider) with an emulator, every output line will be prefixed with <code>[from python]</code> as expected:</p>
```...

[from python]: 00:17 +0: getTemporaryDirectory

[from python]: 00:17 +1: getTemporaryDirectory

[from python]: 00:17 +1: getApplicationDocumentsDirectory

[from python]: 00:18 +1: getApplicationDocumentsDirectory

[from python]: 00:18 +2: getApplicationDocumentsDirectory

...
```
<p>However I need to write the program in dart, the code I wrote is:</p>
<pre class="lang-dart prettyprint-override"><code>import 'dart:io';

Future<void> main() async {
  print('starting');

  final process = await Process.start(
      'flutter', <String>['test', 'integration_test'],
      runInShell: true);
  await for (final line in process.stdout) {
    print('[from dart]: ${String.fromCharCodes(line)}');
  }
}
</code>```

When I run the above code in the same example directory, some lines are not prefixed with [from dart], which means some stdout results were not captured by the dart program but are directly written to console.

```<code>[from dart]: â  Built build/app/outputs/flutter-apk/app-debug.apk.

00:15 +0: loading /home/hakkyu/mydir/project/flutter/flutter_plugins/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart
[from dart]: Installing build/app/outputs/flutter-apk/app.apk...
00:16 +0: loading /home/hakkyu/mydir/project/flutter/flutter_plugins/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart
[from dart]:    492ms

00:17 +0: loading /home/hakkyu/mydir/project/flutter/flutter_plugins/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart
00:17 +0: getTemporaryDirectory
00:17 +1: getTemporaryDirectory
00:17 +1: getApplicationDocumentsDirectory
00:17 +2: getApplicationDocumentsDirectory
00:17 +2: getApplicationSupportDirectory
00:17 +3: getApplicationSupportDirectory
00:17 +3: getLibraryDirectory
00:17 +4: getLibraryDirectory
00:17 +4: getExternalStorageDirectory
</code>```

If I haven't made any mistakes in the code, I can only assume that there are implementation differences in "process" between python and dart. I have no clue what to look into at this point. What could be causing this issue?

答:
Give this a try:

import 'dart:convert';
import 'dart:io';

Future<void> main() async {
  print('starting');

  final process = await Process.start(
      'flutter', <String>['test', 'integration_test'],
      runInShell: true);
  await for (final line
      in process.stdout.transform(Utf8Decoder()).transform(LineSplitter())) {
    print('[from dart]: $line');
  }
}
```

.transform(Utf8Decoder()) will convert bytes into Strings. .transform(LineSplitter()) will split the strings up if there are newlines, I am not too familiar with python, but I am guessing this is what the universal_newlines=True option does.

Body:
For CI, I need to write a program that runs flutter test integration_test and captures the stdout result. In python the code would be:

import subprocess

process = subprocess.Popen(
    f'flutter test integration_test',
    shell=True,
    universal_newlines=True,
    stderr=subprocess.PIPE,
    stdout=subprocess.PIPE)

print('starting')

for line in process.stdout:
    print(f'[from python]: {line}')

If you run the above code in the example directory of a plugin package(for example path_provider) with an emulator, every output line will be prefixed with [from python] as expected:

...

[from python]: 00:17 +0: getTemporaryDirectory

[from python]: 00:17 +1: getTemporaryDirectory

[from python]: 00:17 +1: getApplicationDocumentsDirectory

[from python]: 00:18 +1: getApplicationDocumentsDirectory

[from python]: 00:18 +2: getApplicationDocumentsDirectory

...

However I need to write the program in dart, the code I wrote is:

import 'dart:io';

Future<void> main() async {
  print('starting');

  final process = await Process.start(
      'flutter', <String>['test', 'integration_test'],
      runInShell: true);
  await for (final line in process.stdout) {
    print('[from dart]: ${String.fromCharCodes(line)}');
  }
}

When I run the above code in the same example directory, some lines are not prefixed with [from dart], which means some stdout results were not captured by the dart program but are directly written to console.

[from dart]: â  Built build/app/outputs/flutter-apk/app-debug.apk.

00:15 +0: loading /home/hakkyu/mydir/project/flutter/flutter_plugins/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart
[from dart]: Installing build/app/outputs/flutter-apk/app.apk...
00:16 +0: loading /home/hakkyu/mydir/project/flutter/flutter_plugins/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart
[from dart]:    492ms

00:17 +0: loading /home/hakkyu/mydir/project/flutter/flutter_plugins/packages/path_provider/path_provider/example/integration_test/path_provider_test.dart
00:17 +0: getTemporaryDirectory
00:17 +1: getTemporaryDirectory
00:17 +1: getApplicationDocumentsDirectory
00:17 +2: getApplicationDocumentsDirectory
00:17 +2: getApplicationSupportDirectory
00:17 +3: getApplicationSupportDirectory
00:17 +3: getLibraryDirectory
00:17 +4: getLibraryDirectory
00:17 +4: getExternalStorageDirectory

If I haven't made any mistakes in the code, I can only assume that there are implementation differences in "process" between python and dart. I have no clue what to look into at this point. What could be causing this issue?

Body:
Give this a try:

import 'dart:convert';
import 'dart:io';

Future<void> main() async {
  print('starting');

  final process = await Process.start(
      'flutter', <String>['test', 'integration_test'],
      runInShell: true);
  await for (final line
      in process.stdout.transform(Utf8Decoder()).transform(LineSplitter())) {
    print('[from dart]: $line');
  }
}

.transform(Utf8Decoder()) will convert bytes into Strings. .transform(LineSplitter()) will split the strings up if there are newlines, I am not too familiar with python, but I am guessing this is what the universal_newlines=True option does.


问:
Parameters order with and @XmlType(propOrder) and Resteasy jackson
I produce json using resteasy.
Everything works fine but... I can't order the parameters of my generated json:

In my serialized class, I have the following anotations:

```<code>@XmlRootElement
@XmlType(propOrder={"foo1", "foo2", "foo3"})
</code>```

in my generated json, i get:

```<code>{"foo2":"bar2","foo1":"bar1","foo3":""}
</code>```

There is the following dependency in my pom.xml

```<code>    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson-provider</artifactId>
        <version>2.2.0.GA</version>
    </dependency>
</code>```

any idea?

答:
A simple answer is that "it does not matter" -- ordering of properties in JSON Object has no significance, so libraries and frameworks are free to output them in whatever order they want to.

But more complex answer would be along lines of trying to maybe use Jackson's own @JsonPropertyOrder annotation, which should work. Unless you absolutely must use JAXB annotations, that might solve your problem.

Even so, this JAXB annotation should be supported by Jackson, when JAXB annotation mode is enabled. So if you need to use JAXB annotations, you need to try to figure out why support is not enabled. It may or may not be enabled with RESTeasy, since Jackson itself does not use them by default (i.e. framework has to explicitly enable then).

Body:
I produce json using resteasy.
Everything works fine but... I can't order the parameters of my generated json:

In my serialized class, I have the following anotations:

@XmlRootElement
@XmlType(propOrder={"foo1", "foo2", "foo3"})

in my generated json, i get:

{"foo2":"bar2","foo1":"bar1","foo3":""}

There is the following dependency in my pom.xml

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson-provider</artifactId>
        <version>2.2.0.GA</version>
    </dependency>

any idea?


问:
Using unordered_map to store key-value pairs in STL
I have to store some data in my program as described below.

The data is high dimensional coordinates and the number of points in those coordinates. Following would be a simple example (with coordinate dimension 5):

```<code>  coordinate        # of points
(3, 5, 3, 5, 7)          6
(6, 8, 5, 8, 9)          4
(4, 8, 6, 7, 9)          3
</code>```

Please note that even if I use 5 dimensions as an example, the actual problem is of 20 dimensions. The coordinates are always integers.

I want to store this information in some kind of data structure. The first thing that comes to my mind is a hash table. I tried unordered_map in STL. But cannot figure out how to use the coordinates as the key in unordered_map. Defining it as:

```<code>unordered_map<int[5], int> umap;
</code>```

or,

```<code>unordered_map<int[], int> umap;
</code>```

gives me a compilation error. What am I doing wrong?

答:
Hacky way

I've seen this being used in programming competitions for ease of use. You can convert the set of points to a string(concatenate each coordinate and separate them with a space or any other special character) and then use unordered_map<string, int>

```<code>unordered_map<string, int> map; int p[5] = {3, 5, 3, 5, 7};

string point = to_string(p[0]) + " " + to_string(p[1]) + " " to_string(p[2]) + " " to_string(p[3]) + " " to_string(p[4]);

map[point] = 6;
</code>```

Body:
I have to store some data in my program as described below.

The data is high dimensional coordinates and the number of points in those coordinates. Following would be a simple example (with coordinate dimension 5):

  coordinate        # of points
(3, 5, 3, 5, 7)          6
(6, 8, 5, 8, 9)          4
(4, 8, 6, 7, 9)          3

Please note that even if I use 5 dimensions as an example, the actual problem is of 20 dimensions. The coordinates are always integers.

I want to store this information in some kind of data structure. The first thing that comes to my mind is a hash table. I tried unordered_map in STL. But cannot figure out how to use the coordinates as the key in unordered_map. Defining it as:

unordered_map<int[5], int> umap;

or,

unordered_map<int[], int> umap;

gives me a compilation error. What am I doing wrong?

Body:
Hacky way

I've seen this being used in programming competitions for ease of use. You can convert the set of points to a string(concatenate each coordinate and separate them with a space or any other special character) and then use unordered_map<string, int>

unordered_map<string, int> map; int p[5] = {3, 5, 3, 5, 7};

string point = to_string(p[0]) + " " + to_string(p[1]) + " " to_string(p[2]) + " " to_string(p[3]) + " " to_string(p[4]);

map[point] = 6;


问:
What is the equivalent of TestName rule in JUnit 5?
How can I get name of the test method in JUnit 5?</p>

答:
An alternative for having the test name globally available as was possible in JUnit 4 is to shim the functionality yourself in a setup method using the TestInfo interface.

From the JUnit documentation on "Dependency Injection for Constructors and Methods":

The TestInfo can then be used to retrieve information about the current container or test such as the display name, the test class, the test method, and associated tags.

Here we leverage the fact that the built-in resolvers will supply an instance of TestInfo corresponding to the current container or test as the value for parameters of type TestInfo to methods annotated as lifecycle hooks (here we use @BeforeEach).

import org.junit.jupiter.api.TestInfo;

public class MyTestClass {
  String displayName;

  @BeforeEach
  void setUp(TestInfo testInfo) {
    displayName = testInfo.getDisplayName();
    // ... the rest of your setup
  }
}
```
<p>This for example enables you to reference the current test name in other non-test methods (such as various utility methods) without having to include the test name as a parameter to each function call from the initial test method to that utility method.</p>
<p>You can do the same for other information about the current container or test.</p>
<p>Seems like the only disadvantages are:</p>
<ul>
<li>the instance variable cannot be made <code>final</code>, as it is set dynamically</li>
<li>may pollute your setup code</li>
</ul>
<hr />
<p>For reference, here is how the TestName-Rule might be implemented in JUnit 4:</p>
```public class MyTestClass {
  @Rule
  public final TestName name = new TestName();
}
```

Body:
An alternative for having the test name globally available as was possible in JUnit 4 is to shim the functionality yourself in a setup method using the TestInfo interface.

From the JUnit documentation on "Dependency Injection for Constructors and Methods":

The TestInfo can then be used to retrieve information about the current container or test such as the display name, the test class, the test method, and associated tags.

Here we leverage the fact that the built-in resolvers will supply an instance of TestInfo corresponding to the current container or test as the value for parameters of type TestInfo to methods annotated as lifecycle hooks (here we use @BeforeEach).

import org.junit.jupiter.api.TestInfo;

public class MyTestClass {
  String displayName;

  @BeforeEach
  void setUp(TestInfo testInfo) {
    displayName = testInfo.getDisplayName();
    // ... the rest of your setup
  }
}

This for example enables you to reference the current test name in other non-test methods (such as various utility methods) without having to include the test name as a parameter to each function call from the initial test method to that utility method.

You can do the same for other information about the current container or test.

Seems like the only disadvantages are:

the instance variable cannot be made final, as it is set dynamically

may pollute your setup code

For reference, here is how the TestName-Rule might be implemented in JUnit 4:

public class MyTestClass {
  @Rule
  public final TestName name = new TestName();
}


问:
Hadoop HDFS active NameNode is not becoming active after upgrade
I'm upgrading hadoop from version 3.0.0 to version 3.2.2. Following are the steps I followed:

Get active namenode:

```<code>$ hdfs haadmin -getServiceState nn1
standby

$ hdfs haadmin -getServiceState nn2
active
</code>```

Turn safemode on and save namespace(commands ran on nn2):

```<code>$ hdfs dfsadmin -safemode enter
$ hdfs dfsadmin -saveNamespace
</code>```

Stop all hadoop services and upgrade binaries on all nodes

Start zookeeper-failover-controller and journalnode on required nodes

Start nn2(last active namenode) with -upgrade -renameReserved flags

```<code>$ hdfs --daemon start namenode -upgrade -renameReserved
</code>```

from logs:

```<code>STARTUP_MSG: Starting NameNode
STARTUP_MSG:   host = <hostname2>/<IP2>
STARTUP_MSG:   args = [-upgrade, -renameReserved]
STARTUP_MSG:   version = 3.2.2

org.apache.hadoop.hdfs.server.namenode.NameNode: createNameNode [-upgrade, -renameReserved]

org.apache.hadoop.hdfs.server.namenode.FSImage: Starting upgrade of local storage directories.
   old LV = -64; old CTime = 1636096354752.
   new LV = -65; new CTime = 1642257088033
org.apache.hadoop.hdfs.server.namenode.NNUpgradeUtil: Starting upgrade of storage directory

org.apache.hadoop.hdfs.server.namenode.NNUpgradeUtil: Performing upgrade of storage directory

org.apache.hadoop.hdfs.StateChange: STATE* Safe mode ON
org.apache.hadoop.hdfs.server.namenode.FSNamesystem: Starting services required for active state
</code>```

stop nn2 and start normally and turn safemode off(We have defined these as services, hence starting nn2 as service):

```<code>$ hdfs --daemon stop namenode
$ sudo service hadoop-hdfs-namenode start
</code>```

from logs:

```<code>STARTUP_MSG: Starting NameNode
STARTUP_MSG:   host = <hostname2>/<IP2>
STARTUP_MSG:   args = []
STARTUP_MSG:   version = 3.2.2

org.apache.hadoop.hdfs.StateChange: STATE* Safe mode ON.
The reported blocks 0 needs additional 2537 blocks to reach the threshold 0.9990 of total blocks 2540.
The minimum number of live datanodes is not required. Safe mode will be turned off automatically once the thresholds have been reached.

org.apache.hadoop.hdfs.server.namenode.FSNamesystem: Starting services required for standby state
org.apache.hadoop.hdfs.server.namenode.ha.EditLogTailer: Will roll logs on active node every 120 seconds.

org.apache.hadoop.hdfs.server.namenode.ha.StandbyCheckpointer: Starting standby checkpoint thread...
Checkpointing active NN to possible NNs: [http://<hostname1>:<port>]
Serving checkpoints at http://<hostname2>:<port>

org.apache.hadoop.hdfs.server.namenode.ha.EditLogTailer: Triggering log roll on remote NameNode
org.apache.hadoop.ipc.Client: Retrying connect to server: <hostname1>/<ip1>:<port>
</code>```

Turn safemode off on active nn(nn2 in this case)

```<code>$ hdfs dfsadmin -safemode leave
safemode: Call From <hostname2>/<IP2> to <hostname1>:<port> failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
</code>```

Wait until safemode is turned off:

```<code>$ hdfs dfsadmin -safemode get
safemode: Call From <hostname2>/<IP2> to <hostname1>:<port> failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
</code>```

I expect the safemode to be turned off on nn2, and getting exception for nn1 as it is not running, but this is not happening. I do not see anything in the logs after this point other than it trying to connect to <hostname1>/<IP1>:<port>

After step 8, I start standby namenode and issue hdfs namenode -bootstrapStandby and restart both namenodes and finalize the upgrade.

I've tested these upgrade steps atleast 20-25 times, But this time I'm stuck at step 7.

Since nn2(hostname2) was the active namenode before upgrade, I expect it to come up and be the active namenode again(and turn safemode off), but that is not happening in this case.
I could not find anything related to it, can someone please help with this?

答:
Looks like some problem with get safemode command, if nn1 is not running, it does not check for nn2 and return error.
In order to get around this, I've changed the steps to following:

Bootstrap standby namenode using hdfs namenode -bootstrapStandby
fs image will be copied to nn2 and it will shutdown.
Start namenode service on nn2 host using sudo service hadoop-hdfs-namenode start

Turn HDFS safemode off: hdfs dfsadmin -safemode leave

Wait for safemode to be turned off: hdfs dfsadmin -safemode get

Body:
I'm upgrading hadoop from version 3.0.0 to version 3.2.2. Following are the steps I followed:

Get active namenode:

$ hdfs haadmin -getServiceState nn1
standby

$ hdfs haadmin -getServiceState nn2
active

Turn safemode on and save namespace(commands ran on nn2):

$ hdfs dfsadmin -safemode enter
$ hdfs dfsadmin -saveNamespace

Stop all hadoop services and upgrade binaries on all nodes

Start zookeeper-failover-controller and journalnode on required nodes

Start nn2(last active namenode) with -upgrade -renameReserved flags

$ hdfs --daemon start namenode -upgrade -renameReserved

from logs:

STARTUP_MSG: Starting NameNode
STARTUP_MSG:   host = <hostname2>/<IP2>
STARTUP_MSG:   args = [-upgrade, -renameReserved]
STARTUP_MSG:   version = 3.2.2

org.apache.hadoop.hdfs.server.namenode.NameNode: createNameNode [-upgrade, -renameReserved]

org.apache.hadoop.hdfs.server.namenode.FSImage: Starting upgrade of local storage directories.
   old LV = -64; old CTime = 1636096354752.
   new LV = -65; new CTime = 1642257088033
org.apache.hadoop.hdfs.server.namenode.NNUpgradeUtil: Starting upgrade of storage directory

org.apache.hadoop.hdfs.server.namenode.NNUpgradeUtil: Performing upgrade of storage directory

org.apache.hadoop.hdfs.StateChange: STATE* Safe mode ON
org.apache.hadoop.hdfs.server.namenode.FSNamesystem: Starting services required for active state

stop nn2 and start normally and turn safemode off(We have defined these as services, hence starting nn2 as service):

$ hdfs --daemon stop namenode
$ sudo service hadoop-hdfs-namenode start

from logs:

STARTUP_MSG: Starting NameNode
STARTUP_MSG:   host = <hostname2>/<IP2>
STARTUP_MSG:   args = []
STARTUP_MSG:   version = 3.2.2

org.apache.hadoop.hdfs.StateChange: STATE* Safe mode ON.
The reported blocks 0 needs additional 2537 blocks to reach the threshold 0.9990 of total blocks 2540.
The minimum number of live datanodes is not required. Safe mode will be turned off automatically once the thresholds have been reached.

org.apache.hadoop.hdfs.server.namenode.FSNamesystem: Starting services required for standby state
org.apache.hadoop.hdfs.server.namenode.ha.EditLogTailer: Will roll logs on active node every 120 seconds.

org.apache.hadoop.hdfs.server.namenode.ha.StandbyCheckpointer: Starting standby checkpoint thread...
Checkpointing active NN to possible NNs: [http://<hostname1>:<port>]
Serving checkpoints at http://<hostname2>:<port>

org.apache.hadoop.hdfs.server.namenode.ha.EditLogTailer: Triggering log roll on remote NameNode
org.apache.hadoop.ipc.Client: Retrying connect to server: <hostname1>/<ip1>:<port>

Turn safemode off on active nn(nn2 in this case)

$ hdfs dfsadmin -safemode leave
safemode: Call From <hostname2>/<IP2> to <hostname1>:<port> failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused

Wait until safemode is turned off:

$ hdfs dfsadmin -safemode get
safemode: Call From <hostname2>/<IP2> to <hostname1>:<port> failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused

I expect the safemode to be turned off on nn2, and getting exception for nn1 as it is not running, but this is not happening. I do not see anything in the logs after this point other than it trying to connect to <hostname1>/<IP1>:<port>

After step 8, I start standby namenode and issue hdfs namenode -bootstrapStandby and restart both namenodes and finalize the upgrade.

I've tested these upgrade steps atleast 20-25 times, But this time I'm stuck at step 7.

Since nn2(hostname2) was the active namenode before upgrade, I expect it to come up and be the active namenode again(and turn safemode off), but that is not happening in this case.
I could not find anything related to it, can someone please help with this?


问:
Flutter: Unhandled Exception: Bad state: field does not exist within the DocumentSnapshotPlatform
I am new to flutter and i am building a social media App through tutorial which i am now customizing.
Now I tried to add more input fields to a users profile page then i started getting the error below. When i could login my timeline page turned red with warning Bad state: field does not exist within the DocumentSnapshotPlatform

I ran Flutter clean and now my user cannot log into the app

I am getting this error:

```<code>E/flutter ( 3971): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Bad state: field does not exist within the DocumentSnapshotPlatform
E/flutter ( 3971): #0      DocumentSnapshotPlatform.get._findKeyValueInMap
package:cloud_firestore_platform_interface/…/platform_interface/platform_interface_document_snapshot.dart:82
E/flutter ( 3971): #1      DocumentSnapshotPlatform.get._findComponent
package:cloud_firestore_platform_interface/…/platform_interface/platform_interface_document_snapshot.dart:98
E/flutter ( 3971): #2      DocumentSnapshotPlatform.get
package:cloud_firestore_platform_interface/…/platform_interface/platform_interface_document_snapshot.dart:113
E/flutter ( 3971): #3      DocumentSnapshot.get
package:cloud_firestore/src/document_snapshot.dart:49
E/flutter ( 3971): #4      DocumentSnapshot.[]
package:cloud_firestore/src/document_snapshot.dart:56
E/flutter ( 3971): #5      new User.fromDocument
package:findemed/models/user.dart:46
E/flutter ( 3971): #6      _HomeState.createUserInFirestore
package:findemed/pages/home.dart:152
E/flutter ( 3971): <asynchronous suspension>
E/flutter ( 3971): #7      _HomeState.handleSignIn
package:findemed/pages/home.dart:60
E/flutter ( 3971): #8      _HomeState.initState.<anonymous closure>
package:findemed/pages/home.dart:46
E/flutter ( 3971): #9      _rootRunUnary (dart:async/zone.dart:1198:47)

</code>```

The initial was pointing to this dart section of my home file

```<code>buildUsersToFollow() {
  return StreamBuilder(
    stream: usersRef.orderBy('timestamp', descending: true)
    .limit(0)
    .snapshots(),
    builder: (context, snapshot) {
      if (!snapshot.hasData) {
        return circularProgress(context);
      }
      List<UserResult> userResults = [];
      snapshot.data.docs.forEach((doc) {
        User user = User.fromDocument(doc);
        final bool isAuthUser = currentUser.id == user.id;
        final bool isFollowingUser = followingList.contains(user.id);
        // remove auth user from recommended list
        if (isAuthUser) {
          return;
        } else if (isFollowingUser) {
          return;
        } else {
          UserResult userResult = UserResult(user);
          userResults.add(userResult);
        }
        });

</code>```

Now its pointing to this snippet:

```<code>factory User.fromDocument(DocumentSnapshot doc) {
    return User(
      id: doc['id'],
      email: doc['email'],
      username: doc['username'],
      photoUrl: doc['photoUrl'],
      displayName: doc['displayName'],
      bio: doc['bio'],
      fullNames: doc['fullNames'],
      practice: doc['practice'],
      speciality: doc['speciality'],
      phone: doc['phone'],
      mobile: doc['mobile'],
      emergency: doc['emergency'],
      address: doc['address'],
      city: doc['city'],
      location: doc['location'],
    );
  }
</code>```

and this is the other bit of code pointed out in the stack

```<code>currentUser = User.fromDocument(doc);
    print(currentUser);
    print(currentUser.username);
</code>```

答:
This error occurs when any parameter key is missing or has a typo in it as compared to firebase declared fields.

For Example: inside the firebase document, we have a key/value username.

```<code>username: "Ali Murtaza"
</code>```

Now if inside the model if we miss it or write it like this:

```<code>username: doc["usernameeeeee"] as String
</code>```

then bad state: field does not exception will occur.

To handle this case, we have to check whether the document we are fetching contains the particular field or not? To check this:

```<code>username: doc.data()!.containsKey("username")
              ? doc["username"] as String
              : "Username Key Does Not Exist inside Firebase Document",
</code>```

Body:
I am new to flutter and i am building a social media App through tutorial which i am now customizing.
Now I tried to add more input fields to a users profile page then i started getting the error below. When i could login my timeline page turned red with warning Bad state: field does not exist within the DocumentSnapshotPlatform

I ran Flutter clean and now my user cannot log into the app

I am getting this error:

E/flutter ( 3971): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: Bad state: field does not exist within the DocumentSnapshotPlatform
E/flutter ( 3971): #0      DocumentSnapshotPlatform.get._findKeyValueInMap
package:cloud_firestore_platform_interface/…/platform_interface/platform_interface_document_snapshot.dart:82
E/flutter ( 3971): #1      DocumentSnapshotPlatform.get._findComponent
package:cloud_firestore_platform_interface/…/platform_interface/platform_interface_document_snapshot.dart:98
E/flutter ( 3971): #2      DocumentSnapshotPlatform.get
package:cloud_firestore_platform_interface/…/platform_interface/platform_interface_document_snapshot.dart:113
E/flutter ( 3971): #3      DocumentSnapshot.get
package:cloud_firestore/src/document_snapshot.dart:49
E/flutter ( 3971): #4      DocumentSnapshot.[]
package:cloud_firestore/src/document_snapshot.dart:56
E/flutter ( 3971): #5      new User.fromDocument
package:findemed/models/user.dart:46
E/flutter ( 3971): #6      _HomeState.createUserInFirestore
package:findemed/pages/home.dart:152
E/flutter ( 3971): <asynchronous suspension>
E/flutter ( 3971): #7      _HomeState.handleSignIn
package:findemed/pages/home.dart:60
E/flutter ( 3971): #8      _HomeState.initState.<anonymous closure>
package:findemed/pages/home.dart:46
E/flutter ( 3971): #9      _rootRunUnary (dart:async/zone.dart:1198:47)

The initial was pointing to this dart section of my home file

buildUsersToFollow() {
  return StreamBuilder(
    stream: usersRef.orderBy('timestamp', descending: true)
    .limit(0)
    .snapshots(),
    builder: (context, snapshot) {
      if (!snapshot.hasData) {
        return circularProgress(context);
      }
      List<UserResult> userResults = [];
      snapshot.data.docs.forEach((doc) {
        User user = User.fromDocument(doc);
        final bool isAuthUser = currentUser.id == user.id;
        final bool isFollowingUser = followingList.contains(user.id);
        // remove auth user from recommended list
        if (isAuthUser) {
          return;
        } else if (isFollowingUser) {
          return;
        } else {
          UserResult userResult = UserResult(user);
          userResults.add(userResult);
        }
        });

Now its pointing to this snippet:

factory User.fromDocument(DocumentSnapshot doc) {
    return User(
      id: doc['id'],
      email: doc['email'],
      username: doc['username'],
      photoUrl: doc['photoUrl'],
      displayName: doc['displayName'],
      bio: doc['bio'],
      fullNames: doc['fullNames'],
      practice: doc['practice'],
      speciality: doc['speciality'],
      phone: doc['phone'],
      mobile: doc['mobile'],
      emergency: doc['emergency'],
      address: doc['address'],
      city: doc['city'],
      location: doc['location'],
    );
  }

and this is the other bit of code pointed out in the stack

currentUser = User.fromDocument(doc);
    print(currentUser);
    print(currentUser.username);

Body:
This error occurs when any parameter key is missing or has a typo in it as compared to firebase declared fields.

For Example: inside the firebase document, we have a key/value username.

username: "Ali Murtaza"

Now if inside the model if we miss it or write it like this:

username: doc["usernameeeeee"] as String

then bad state: field does not exception will occur.

To handle this case, we have to check whether the document we are fetching contains the particular field or not? To check this:

username: doc.data()!.containsKey("username")
              ? doc["username"] as String
              : "Username Key Does Not Exist inside Firebase Document",


问:
Microsoft Visual J#® 2.0 Redistributable Package for x64 and x86
Is there a version of Microsoft Visual J#® 2.0 Redistributable Package which will support both x86 and x64 platforms?

In the download center, i found only different dlls for both platforms!!!

答:
Using Microsoft Visual J#® 2.0 Redistributable Package – Second Edition (x64), we will be able to build dlls with platform target any platform on a 64 bit machine.

It can be downloaded from: http://www.microsoft.com/download/en/details.aspx?id=15468


问:
How to return string from interface to setonclicklistener
I'm trying to learn android development and i was learning about the  recyclerView. I want to send a string via an interface when a list item is clicked but I dont know how to do that.Can anyone please tell me what to do to achieve this.
This is my java code of the custom recyclerview adapter that I've created.

```<code>import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private String[] localDataSet;
    private newsOnCkicked k;

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView;

        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            textView = (TextView) view.findViewById(R.id.textView2);
        }

        public TextView getTextView() {
            return textView;
        }
    }

    /**
     * Initialize the dataset of the Adapter.
     *
     * @param dataSet String[] containing the data to populate views to be used
     * by RecyclerView.
     */
    public CustomAdapter(String[] dataSet,newsOnCkicked k) {
        localDataSet = dataSet;
        this.k=k;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view, which defines the UI of the list item
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.mylayout, viewGroup, false);
        RecyclerView.ViewHolder v=new ViewHolder(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                k.onItemClicked(localDataSet[v.getAdapterPosition()]);
            }
        });
        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // Get element from your dataset at this position and replace the
        // contents of the view with that element
        viewHolder.getTextView().setText(localDataSet[viewHolder.getAdapterPosition()]);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return localDataSet.length;
    }
}
interface newsOnCkicked extends View.OnClickListener {
    String onItemClicked(String s);
}
</code>```

Kindly help me to figure this out!!

答:
This code seems fine except for these parts i noted you had to do
1)Extending onclick listener
2)The function and position of your interface.

First place your interface in a separate file or inside the adapter class,remove the extends and replace the string to return void:

```<code>   interface newsOnCkicked {
        void onItemClicked(String s);
    }
</code>```

Then call it like this from your activity

```<code> new RecyclerView(this)/* <- your recyclerview*/.setAdapter(new CustomAdapter(new String[20]/*your array*/, new CustomAdapter.newsOnCkicked() {
        @Override
        public void onItemClicked(String s) {
            //here s is your clicked string
        }
    }));
</code>```

The code should look more or less like below:

```<code>public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private String[] localDataSet;
    private newsOnCkicked k;

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView;

        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            textView = (TextView) view.findViewById(R.id.textView2);
        }

        public TextView getTextView() {
            return textView;
        }
    }

    /**
     * Initialize the dataset of the Adapter.
     *
     * @param dataSet String[] containing the data to populate views to be used
     * by RecyclerView.
     */
    public CustomAdapter(String[] dataSet,newsOnCkicked k) {
        localDataSet = dataSet;
        this.k=k;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view, which defines the UI of the list item
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.mylayout, viewGroup, false);
        RecyclerView.ViewHolder v=new ViewHolder(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                k.onItemClicked(localDataSet[v.getAdapterPosition()]);
            }
        });
        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // Get element from your dataset at this position and replace the
        // contents of the view with that element
        viewHolder.getTextView().setText(localDataSet[viewHolder.getAdapterPosition()]);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return localDataSet.length;
    }

    interface newsOnCkicked {
        void onItemClicked(String s);
    }

}
</code>```

Body:
I'm trying to learn android development and i was learning about the  recyclerView. I want to send a string via an interface when a list item is clicked but I dont know how to do that.Can anyone please tell me what to do to achieve this.
This is my java code of the custom recyclerview adapter that I've created.

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private String[] localDataSet;
    private newsOnCkicked k;

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView;

        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            textView = (TextView) view.findViewById(R.id.textView2);
        }

        public TextView getTextView() {
            return textView;
        }
    }

    /**
     * Initialize the dataset of the Adapter.
     *
     * @param dataSet String[] containing the data to populate views to be used
     * by RecyclerView.
     */
    public CustomAdapter(String[] dataSet,newsOnCkicked k) {
        localDataSet = dataSet;
        this.k=k;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view, which defines the UI of the list item
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.mylayout, viewGroup, false);
        RecyclerView.ViewHolder v=new ViewHolder(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                k.onItemClicked(localDataSet[v.getAdapterPosition()]);
            }
        });
        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // Get element from your dataset at this position and replace the
        // contents of the view with that element
        viewHolder.getTextView().setText(localDataSet[viewHolder.getAdapterPosition()]);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return localDataSet.length;
    }
}
interface newsOnCkicked extends View.OnClickListener {
    String onItemClicked(String s);
}

Kindly help me to figure this out!!

Body:
This code seems fine except for these parts i noted you had to do
1)Extending onclick listener
2)The function and position of your interface.

First place your interface in a separate file or inside the adapter class,remove the extends and replace the string to return void:

   interface newsOnCkicked {
        void onItemClicked(String s);
    }

Then call it like this from your activity

 new RecyclerView(this)/* <- your recyclerview*/.setAdapter(new CustomAdapter(new String[20]/*your array*/, new CustomAdapter.newsOnCkicked() {
        @Override
        public void onItemClicked(String s) {
            //here s is your clicked string
        }
    }));

The code should look more or less like below:

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

    private String[] localDataSet;
    private newsOnCkicked k;

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView;

        public ViewHolder(View view) {
            super(view);
            // Define click listener for the ViewHolder's View

            textView = (TextView) view.findViewById(R.id.textView2);
        }

        public TextView getTextView() {
            return textView;
        }
    }

    /**
     * Initialize the dataset of the Adapter.
     *
     * @param dataSet String[] containing the data to populate views to be used
     * by RecyclerView.
     */
    public CustomAdapter(String[] dataSet,newsOnCkicked k) {
        localDataSet = dataSet;
        this.k=k;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view, which defines the UI of the list item
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.mylayout, viewGroup, false);
        RecyclerView.ViewHolder v=new ViewHolder(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                k.onItemClicked(localDataSet[v.getAdapterPosition()]);
            }
        });
        return new ViewHolder(view);
    }

    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {

        // Get element from your dataset at this position and replace the
        // contents of the view with that element
        viewHolder.getTextView().setText(localDataSet[viewHolder.getAdapterPosition()]);
    }

    // Return the size of your dataset (invoked by the layout manager)
    @Override
    public int getItemCount() {
        return localDataSet.length;
    }

    interface newsOnCkicked {
        void onItemClicked(String s);
    }

}


问:
laravel create symlink in custom public path
I have deployed my laravel application on shared hosting. I have  moved all my filed and folders from public directory to public_html.

This is my directory structure

```<code>my-laravel-folder
public_html
  index.php
</code>```

Now i am trying to create symlink in public_html using command php artisan storage:link. but this command create symlink in public directory.

what should i do to create symlink in public_html using command php artisan storage:link ?

答:
You can follow below steps to create a symlink

First go to root directory of file system by running this command

```<code>cd /
</code>```

Then run this command

```<code>ln -s /path-to/my-laravel-folder/storage/app/public /path-to/public_html/storage
</code>```

I faced the same problem on Hostinger and I was able to fix this by running the following command in the root directory.

```<code>ln -s /home/MY_USERNAME/domains/MY-DOMAIN.COM/my-laravel-folder/storage/app/public /home/MY_USERNAME/domains/MY-DOMAIN.COM/public_html/storage
</code>```

Body:
I have deployed my laravel application on shared hosting. I have  moved all my filed and folders from public directory to public_html.

This is my directory structure

my-laravel-folder
public_html
  index.php

Now i am trying to create symlink in public_html using command php artisan storage:link. but this command create symlink in public directory.

what should i do to create symlink in public_html using command php artisan storage:link ?

Body:
You can follow below steps to create a symlink

First go to root directory of file system by running this command

cd /

Then run this command

ln -s /path-to/my-laravel-folder/storage/app/public /path-to/public_html/storage

I faced the same problem on Hostinger and I was able to fix this by running the following command in the root directory.

ln -s /home/MY_USERNAME/domains/MY-DOMAIN.COM/my-laravel-folder/storage/app/public /home/MY_USERNAME/domains/MY-DOMAIN.COM/public_html/storage