问:
Some videos fail to chromecast with error MEDIA_UNKNOWN
Using mkchromecast to cast local mp4 files, some videos work, and some don't (as in: the screen hangs on the blue chromecast logo, suggesting that the initial connection worked). I can reproduce exactly the issue described here.

So I decided to go one level lower, with pychromecast, and try to see what actually happens when it hangs on the blue logo. I converted two videos to HLS format, and exposed them through an http server. The video that works with mkchromecast also works with my setup, but the one that fails, well... fails on both. With pychromecast, I don't get much more information than:

ERROR, code 100: MEDIA_UNKNOWN.

From the Cast documentation, this error means:

The media element encountered an unknown error fired from platform. The media element encountered an error that did not indicate it's one of MediaError.MEDIA_ERR_*. This should be rare.

It is not rare for me at all, though. I thought that maybe the failing video was in an unsupported format, as described in the documentation. So I tried to compare both videos with the following command:

```<code>ffprobe -v quiet -print_format json -show_streams <video.mp4>
</code>```

Video that works:

```<code>{
    "streams": [
        {
            "index": 0,
            "codec_name": "h264",
            "codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10",
            "profile": "High",
            "codec_type": "video",
            "codec_time_base": "1001/48000",
            "codec_tag_string": "avc1",
            "codec_tag": "0x31637661",
            "width": 1920,
            "height": 1080,
            "coded_width": 1920,
            "coded_height": 1088,
            "has_b_frames": 2,
            "sample_aspect_ratio": "1:1",
            "display_aspect_ratio": "16:9",
            "pix_fmt": "yuv420p",
            "level": 50,
            "chroma_location": "left",
            "refs": 1,
            "is_avc": "true",
            "nal_length_size": "4",
            "r_frame_rate": "24000/1001",
            "avg_frame_rate": "24000/1001",
            "time_base": "1/24000",
            "start_pts": 0,
            "start_time": "0.000000",
            "duration_ts": 47127080,
            "duration": "1963.628333",
            "bit_rate": "5527977",
            "bits_per_raw_sample": "8",
            "nb_frames": "47080",
            "disposition": {
                "default": 1,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0,
                "timed_thumbnails": 0
            },
            "tags": {
                "language": "und",
                "handler_name": "VideoHandler"
            }
        },
        {
            "index": 1,
            "codec_name": "aac",
            "codec_long_name": "AAC (Advanced Audio Coding)",
            "profile": "LC",
            "codec_type": "audio",
            "codec_time_base": "1/48000",
            "codec_tag_string": "mp4a",
            "codec_tag": "0x6134706d",
            "sample_fmt": "fltp",
            "sample_rate": "48000",
            "channels": 2,
            "channel_layout": "stereo",
            "bits_per_sample": 0,
            "r_frame_rate": "0/0",
            "avg_frame_rate": "0/0",
            "time_base": "1/48000",
            "start_pts": 0,
            "start_time": "0.000000",
            "duration_ts": 94254528,
            "duration": "1963.636000",
            "bit_rate": "125776",
            "max_bit_rate": "125776",
            "nb_frames": "92048",
            "disposition": {
                "default": 1,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0,
                "timed_thumbnails": 0
            },
            "tags": {
                "language": "und",
                "handler_name": "SoundHandler"
            }
        }
    ]
}
</code>```

Video that does NOT work:

```<code>{
    "streams": [
        {
            "index": 0,
            "codec_name": "h264",
            "codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10",
            "profile": "High",
            "codec_type": "video",
            "codec_time_base": "125/5994",
            "codec_tag_string": "avc1",
            "codec_tag": "0x31637661",
            "width": 1920,
            "height": 1040,
            "coded_width": 1920,
            "coded_height": 1040,
            "has_b_frames": 2,
            "sample_aspect_ratio": "1:1",
            "display_aspect_ratio": "24:13",
            "pix_fmt": "yuv420p",
            "level": 41,
            "chroma_location": "left",
            "refs": 1,
            "is_avc": "true",
            "nal_length_size": "4",
            "r_frame_rate": "2997/125",
            "avg_frame_rate": "2997/125",
            "time_base": "1/11988",
            "start_pts": 0,
            "start_time": "0.000000",
            "duration_ts": 97032000,
            "duration": "8094.094094",
            "bit_rate": "2499644",
            "bits_per_raw_sample": "8",
            "nb_frames": "194064",
            "disposition": {
                "default": 1,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0,
                "timed_thumbnails": 0
            },
            "tags": {
                "creation_time": "2020-03-27T09:56:39.000000Z",
                "language": "und",
                "handler_name": "L-SMASH Video Media Handler"
            }
        },
        {
            "index": 1,
            "codec_name": "aac",
            "codec_long_name": "AAC (Advanced Audio Coding)",
            "profile": "LC",
            "codec_type": "audio",
            "codec_time_base": "1/48000",
            "codec_tag_string": "mp4a",
            "codec_tag": "0x6134706d",
            "sample_fmt": "fltp",
            "sample_rate": "48000",
            "channels": 6,
            "channel_layout": "5.1",
            "bits_per_sample": 0,
            "r_frame_rate": "0/0",
            "avg_frame_rate": "0/0",
            "time_base": "1/48000",
            "start_pts": 0,
            "start_time": "0.000000",
            "duration_ts": 388516320,
            "duration": "8094.090000",
            "bit_rate": "224000",
            "max_bit_rate": "224000",
            "nb_frames": "379413",
            "disposition": {
                "default": 1,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0,
                "timed_thumbnails": 0
            },
            "tags": {
                "creation_time": "2020-03-27T09:56:39.000000Z",
                "language": "eng",
                "handler_name": "SoundHandler"
            }
        }
    ]
}
</code>```

For what I can see, the codecs are the same, and the only difference I can make is in the aspect ratio.

What could be the reason for this "MEDIA_UNKNOWN" error on the chromecast side? Is there something more I could compare between those two videos? Could it be that the chromecast fails because of the aspect ratio?

答:
It does not like 5.1 channel layout. Try downmixing it to stereo:</p>

```<code>ffmpeg -i not_working.mp4 -c copy -c:a aac -ac 2 -movflags +faststart fixed.mp4
</code>```

Body:
Using mkchromecast to cast local mp4 files, some videos work, and some don't (as in: the screen hangs on the blue chromecast logo, suggesting that the initial connection worked). I can reproduce exactly the issue described here.

So I decided to go one level lower, with pychromecast, and try to see what actually happens when it hangs on the blue logo. I converted two videos to HLS format, and exposed them through an http server. The video that works with mkchromecast also works with my setup, but the one that fails, well... fails on both. With pychromecast, I don't get much more information than:

ERROR, code 100: MEDIA_UNKNOWN.

From the Cast documentation, this error means:

The media element encountered an unknown error fired from platform. The media element encountered an error that did not indicate it's one of MediaError.MEDIA_ERR_*. This should be rare.

It is not rare for me at all, though. I thought that maybe the failing video was in an unsupported format, as described in the documentation. So I tried to compare both videos with the following command:

ffprobe -v quiet -print_format json -show_streams <video.mp4>

Video that works:

{
    "streams": [
        {
            "index": 0,
            "codec_name": "h264",
            "codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10",
            "profile": "High",
            "codec_type": "video",
            "codec_time_base": "1001/48000",
            "codec_tag_string": "avc1",
            "codec_tag": "0x31637661",
            "width": 1920,
            "height": 1080,
            "coded_width": 1920,
            "coded_height": 1088,
            "has_b_frames": 2,
            "sample_aspect_ratio": "1:1",
            "display_aspect_ratio": "16:9",
            "pix_fmt": "yuv420p",
            "level": 50,
            "chroma_location": "left",
            "refs": 1,
            "is_avc": "true",
            "nal_length_size": "4",
            "r_frame_rate": "24000/1001",
            "avg_frame_rate": "24000/1001",
            "time_base": "1/24000",
            "start_pts": 0,
            "start_time": "0.000000",
            "duration_ts": 47127080,
            "duration": "1963.628333",
            "bit_rate": "5527977",
            "bits_per_raw_sample": "8",
            "nb_frames": "47080",
            "disposition": {
                "default": 1,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0,
                "timed_thumbnails": 0
            },
            "tags": {
                "language": "und",
                "handler_name": "VideoHandler"
            }
        },
        {
            "index": 1,
            "codec_name": "aac",
            "codec_long_name": "AAC (Advanced Audio Coding)",
            "profile": "LC",
            "codec_type": "audio",
            "codec_time_base": "1/48000",
            "codec_tag_string": "mp4a",
            "codec_tag": "0x6134706d",
            "sample_fmt": "fltp",
            "sample_rate": "48000",
            "channels": 2,
            "channel_layout": "stereo",
            "bits_per_sample": 0,
            "r_frame_rate": "0/0",
            "avg_frame_rate": "0/0",
            "time_base": "1/48000",
            "start_pts": 0,
            "start_time": "0.000000",
            "duration_ts": 94254528,
            "duration": "1963.636000",
            "bit_rate": "125776",
            "max_bit_rate": "125776",
            "nb_frames": "92048",
            "disposition": {
                "default": 1,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0,
                "timed_thumbnails": 0
            },
            "tags": {
                "language": "und",
                "handler_name": "SoundHandler"
            }
        }
    ]
}

Video that does NOT work:

{
    "streams": [
        {
            "index": 0,
            "codec_name": "h264",
            "codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10",
            "profile": "High",
            "codec_type": "video",
            "codec_time_base": "125/5994",
            "codec_tag_string": "avc1",
            "codec_tag": "0x31637661",
            "width": 1920,
            "height": 1040,
            "coded_width": 1920,
            "coded_height": 1040,
            "has_b_frames": 2,
            "sample_aspect_ratio": "1:1",
            "display_aspect_ratio": "24:13",
            "pix_fmt": "yuv420p",
            "level": 41,
            "chroma_location": "left",
            "refs": 1,
            "is_avc": "true",
            "nal_length_size": "4",
            "r_frame_rate": "2997/125",
            "avg_frame_rate": "2997/125",
            "time_base": "1/11988",
            "start_pts": 0,
            "start_time": "0.000000",
            "duration_ts": 97032000,
            "duration": "8094.094094",
            "bit_rate": "2499644",
            "bits_per_raw_sample": "8",
            "nb_frames": "194064",
            "disposition": {
                "default": 1,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0,
                "timed_thumbnails": 0
            },
            "tags": {
                "creation_time": "2020-03-27T09:56:39.000000Z",
                "language": "und",
                "handler_name": "L-SMASH Video Media Handler"
            }
        },
        {
            "index": 1,
            "codec_name": "aac",
            "codec_long_name": "AAC (Advanced Audio Coding)",
            "profile": "LC",
            "codec_type": "audio",
            "codec_time_base": "1/48000",
            "codec_tag_string": "mp4a",
            "codec_tag": "0x6134706d",
            "sample_fmt": "fltp",
            "sample_rate": "48000",
            "channels": 6,
            "channel_layout": "5.1",
            "bits_per_sample": 0,
            "r_frame_rate": "0/0",
            "avg_frame_rate": "0/0",
            "time_base": "1/48000",
            "start_pts": 0,
            "start_time": "0.000000",
            "duration_ts": 388516320,
            "duration": "8094.090000",
            "bit_rate": "224000",
            "max_bit_rate": "224000",
            "nb_frames": "379413",
            "disposition": {
                "default": 1,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0,
                "timed_thumbnails": 0
            },
            "tags": {
                "creation_time": "2020-03-27T09:56:39.000000Z",
                "language": "eng",
                "handler_name": "SoundHandler"
            }
        }
    ]
}

For what I can see, the codecs are the same, and the only difference I can make is in the aspect ratio.

What could be the reason for this "MEDIA_UNKNOWN" error on the chromecast side? Is there something more I could compare between those two videos? Could it be that the chromecast fails because of the aspect ratio?

Body:
It does not like 5.1 channel layout. Try downmixing it to stereo:

ffmpeg -i not_working.mp4 -c copy -c:a aac -ac 2 -movflags +faststart fixed.mp4


来源: stackexchange

问:
How to convert List of Double to List of String?
This just might be too easy for all of you, but I am just learning and implementing Java in a project and am stuck with this.

How to convert List of Double  to List String?

答:
```<code>List<Double> doubleList = new ArrayList<Double>();
doubleList.add(1.1d);
doubleList.add(2.2d);
doubleList.add(3.3d);

List<String> listOfStrings = new ArrayList<String>();
for (Double d:doubleList)
     listOfStrings.add(d.toString());
</code>```

ContentLicense: CC BY-SA 3.0


问:
Save the video while making a video call using AWS Kinesis Video stream with WebRTC
Im using aws kinesis video stream webRTC for making a video chat in reactjs .Everything is working fine.But i want to store the video in s3 bucket.How should i implement this video storage?</p>

答:
I think you can do the following:

Get the video stream from WebRTC

Use KVS Producer's PutMedia, https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_PutMedia.html.

Retrieve them the frames with GetMedia, https://docs.aws.amazon.com/kinesisvideostreams/latest/dg/API_dataplane_GetMedia.html.

Note: under the hood, KVS Producer uses S3

ContentLicense: CC BY-SA 4.0


问:
How can I use a loop to get clockwise spiral output in matrix as an independent output?
This image explains the problem I'm trying to solve.

And here is my attempted solution:

```<code>matrix = [[1, 2, 3, 4, 5],
      [6, 7, 8, 9, 10],
      [11, 12, 13, 14, 15],
      [16, 17, 18, 19, 20]]
i = 0
y = (len(matrix)-1)
while i < len(matrix):
    if i == 0:
        # print 1st row.
        for rows in matrix[i]:
            print(rows)

    # print all the last element of every rows, except 1st and last row.
    elif i != 0 and i != y:
        print(matrix[i][-1])

    # print the last row in reverse.
    elif i == y and i != 0:
        matrix[i].sort(reverse=True)
        for row in matrix[i]:
            print(row)

        print(matrix[i-1][0])       # print the 1st element of 3rd row.

        # print the 1st four elements of 2nd row.
        for r in matrix[1][0:4]:
            print(r)

        # finally print the rest of the elements in reverse.
        matrix[2].sort(reverse=True)
        for r_remain in matrix[2][1:4]:
            print(r_remain)

    i += 1
</code>```

My question is, is this algorithm right or wrong?

Secondly, my algorithm depends on the size and contents of the input matrix. How can I make it work for any input?

答:
Here is a completely general solution working for any number of rows:

```<code>matrix = [[ 1,  2,  3,  4,  5],
          [12, 13, 14, 15,  6],
          [11, 10,  9,  8,  7]]

# print rows between lo_x..hi_x and columns between lo_y..hi_y (inclusive)
lo_x = lo_y = 0
hi_x = len(matrix[0]) - 1
hi_y = len(matrix) - 1

while lo_x <= hi_x and lo_y <= hi_y:
    for x in range(lo_x, hi_x+1): print(matrix[lo_y][x])
    lo_y += 1
    for y in range(lo_y, hi_y+1): print(matrix[y][hi_x])
    hi_x -= 1
    if not (lo_x <= hi_x and lo_y <= hi_y): break
    for x in reversed(range(lo_x, hi_x+1)): print(matrix[hi_y][x])
    hi_y -= 1
    for y in reversed(range(lo_y, hi_y+1)): print(matrix[y][lo_x])
    lo_x += 1
</code>```

In each iteration we do one spiral (right, down, left, up). The break in the middle is needed because we might still have an x-range left even when our y-range is used up. I added the matrix as an example of why break is needed (it will produce false output if one deletes the break).

Body:
This image explains the problem I'm trying to solve.

And here is my attempted solution:

matrix = [[1, 2, 3, 4, 5],
      [6, 7, 8, 9, 10],
      [11, 12, 13, 14, 15],
      [16, 17, 18, 19, 20]]
i = 0
y = (len(matrix)-1)
while i < len(matrix):
    if i == 0:
        # print 1st row.
        for rows in matrix[i]:
            print(rows)

    # print all the last element of every rows, except 1st and last row.
    elif i != 0 and i != y:
        print(matrix[i][-1])

    # print the last row in reverse.
    elif i == y and i != 0:
        matrix[i].sort(reverse=True)
        for row in matrix[i]:
            print(row)

        print(matrix[i-1][0])       # print the 1st element of 3rd row.

        # print the 1st four elements of 2nd row.
        for r in matrix[1][0:4]:
            print(r)

        # finally print the rest of the elements in reverse.
        matrix[2].sort(reverse=True)
        for r_remain in matrix[2][1:4]:
            print(r_remain)

    i += 1

My question is, is this algorithm right or wrong?

Secondly, my algorithm depends on the size and contents of the input matrix. How can I make it work for any input?

Body:
Here is a completely general solution working for any number of rows:

matrix = [[ 1,  2,  3,  4,  5],
          [12, 13, 14, 15,  6],
          [11, 10,  9,  8,  7]]

# print rows between lo_x..hi_x and columns between lo_y..hi_y (inclusive)
lo_x = lo_y = 0
hi_x = len(matrix[0]) - 1
hi_y = len(matrix) - 1

while lo_x <= hi_x and lo_y <= hi_y:
    for x in range(lo_x, hi_x+1): print(matrix[lo_y][x])
    lo_y += 1
    for y in range(lo_y, hi_y+1): print(matrix[y][hi_x])
    hi_x -= 1
    if not (lo_x <= hi_x and lo_y <= hi_y): break
    for x in reversed(range(lo_x, hi_x+1)): print(matrix[hi_y][x])
    hi_y -= 1
    for y in reversed(range(lo_y, hi_y+1)): print(matrix[y][lo_x])
    lo_x += 1

In each iteration we do one spiral (right, down, left, up). The break in the middle is needed because we might still have an x-range left even when our y-range is used up. I added the matrix as an example of why break is needed (it will produce false output if one deletes the break).


问:
Why time.mktime returns different result on windows and linux for same input?
time.mktime behaves differently on windows and linux.
For a datetime value '0001-01-01 00:00:00' , on windows it throws exception "OverflowError: mktime argument out of range" while on Linux it does not throw any exception and returns an incorrect (-ve) value.

on windows -

```<code>>>> from dateutil.parser import parse
>>> dt = parse('0001-01-01 00:00:00')
>>> dt
datetime.datetime(1, 1, 1, 0, 0)
>>> time.mktime(dt.timetuple())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: mktime argument out of range
</code>```

On Linux

```<code>>>> from dateutil.parser import parse
>>> dt = parse('0001-01-01 00:00:00')
>>> dt
datetime.datetime(1, 1, 1, 0, 0)
>>> time.mktime(dt.timetuple())
-62135596800.0
</code>```

any pointer as to why same function is behaving differently on windows and Linux is appreciated.

答:
The underlying C libraries for mktime used by the Python implementations for Windows and Linux are different.

As the documentation points out:

The earliest date for which it (mktime) can generate a time is
  platform-dependent.

Body:
time.mktime behaves differently on windows and linux.
For a datetime value '0001-01-01 00:00:00' , on windows it throws exception "OverflowError: mktime argument out of range" while on Linux it does not throw any exception and returns an incorrect (-ve) value.

on windows -

>>> from dateutil.parser import parse
>>> dt = parse('0001-01-01 00:00:00')
>>> dt
datetime.datetime(1, 1, 1, 0, 0)
>>> time.mktime(dt.timetuple())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: mktime argument out of range

On Linux

>>> from dateutil.parser import parse
>>> dt = parse('0001-01-01 00:00:00')
>>> dt
datetime.datetime(1, 1, 1, 0, 0)
>>> time.mktime(dt.timetuple())
-62135596800.0

any pointer as to why same function is behaving differently on windows and Linux is appreciated.


问:
What are the units of measure/ dimensions of given edge attributes in Osmnx
my question is rather simple: osmnx allows you to get the length of the edges of a given place. What are the units of measure of the length attribute? (km or meters).

Also this operation osmnx.speed.add_edge_travel_times(G) gives me the time it takes to go through an edge at a given speed (which has to be set as km/h). Again, what are the units of measure of these time intervals?

Thank you in advance.

答:
The distance unit used internally are meters. You can check for instance with the function that adds the edge lengths,osmnx.utils_graph.add_edge_lengths(G), which as mentioned considers the specified lengths to be in meters.

And osmnx.speed.add_edge_travel_times is used to add edge travel times in seconds. This, as mentioned in the docs, is based on length and speed_kph attributes, which must be set prior to setting the edge travel times. So even though the speeds are set in km/h the base time unit that is used are seconds.


问:
Having Trouble Executing While Loop
I am attempting to create a coronavirus temp scan compare program. I want to open an excel file and create a small database each day of scanned employees. When I execute I am just getting the first input prompt and my excel spreadsheet is not opening. My goal was to have each line of code under the while statement nested and would continue to loop until the program operator ended the loop. My code is below. Any help is appreciated.</p>

```<code>from datetime import date
from xlwt import Workbook

# Workbook is created
wb = Workbook()

# add sheet
sheet1 = wb.add_sheet('Temperature Scans')

sheet1.write(0, 0, 'First Name')
sheet1.write(0, 1, 'Last Name')
sheet1.write(0, 2, 'Date')
sheet1.write(0, 3, 'Temperature')

Normal = 98.6

Recording = input("Are you Recording Temperature Today? 1 if yes; 0 if no: ")

while Recording == 1:
    Employee_First = input("Enter First Name: ")
    Employee_Last = input("Enter Last Name: ")
    Temp = float(input("Input Scanned Temperature (Example if 99 degrees enter 99): "))
    if Temp > Normal:
            print("Elevated Temperature Detected! Entrance Not Permitted")
    else:
            print("Temperature Within Acceptable Limits. Entrance Permitted")
    Date = today.strftime("%m/%d/%y")
    for i in range(0, 15000):
            sheet1.write(i+1, 0, Employee_First)
            sheet1.write(i+1, 1, Employee_Last)
            sheet1.write(i+1, 2, Date)
            sheet1.write(i+1, 3, Temp)

            Day = today.strftime("%d")
            Month = today.strftime("%m")
            Year = today.strftime("%y")

            wb.save(Month, _ , Day, _ , Year, 'Temp Scans.xlsx')

    break

    continue
</code>```

答:
The input statement will only take input as a string, it is up to you to convert it into different formats:</p>

```<code>Recording = input("Are you Recording Temperature Today? 1 if yes; 0 if no: ")

while Recording == '1':
    # do something
</code>```

Title: Having Trouble Executing While Loop

Body:
I am attempting to create a coronavirus temp scan compare program. I want to open an excel file and create a small database each day of scanned employees. When I execute I am just getting the first input prompt and my excel spreadsheet is not opening. My goal was to have each line of code under the while statement nested and would continue to loop until the program operator ended the loop. My code is below. Any help is appreciated.

from datetime import date
from xlwt import Workbook

# Workbook is created
wb = Workbook()

# add sheet
sheet1 = wb.add_sheet('Temperature Scans')

sheet1.write(0, 0, 'First Name')
sheet1.write(0, 1, 'Last Name')
sheet1.write(0, 2, 'Date')
sheet1.write(0, 3, 'Temperature')

Normal = 98.6

Recording = input("Are you Recording Temperature Today? 1 if yes; 0 if no: ")

while Recording == 1:
    Employee_First = input("Enter First Name: ")
    Employee_Last = input("Enter Last Name: ")
    Temp = float(input("Input Scanned Temperature (Example if 99 degrees enter 99): "))
    if Temp > Normal:
            print("Elevated Temperature Detected! Entrance Not Permitted")
    else:
            print("Temperature Within Acceptable Limits. Entrance Permitted")
    Date = today.strftime("%m/%d/%y")
    for i in range(0, 15000):
            sheet1.write(i+1, 0, Employee_First)
            sheet1.write(i+1, 1, Employee_Last)
            sheet1.write(i+1, 2, Date)
            sheet1.write(i+1, 3, Temp)

            Day = today.strftime("%d")
            Month = today.strftime("%m")
            Year = today.strftime("%y")

            wb.save(Month, _ , Day, _ , Year, 'Temp Scans.xlsx')

    break

    continue

Body:
The input statement will only take input as a string, it is up to you to convert it into different formats:

Recording = input("Are you Recording Temperature Today? 1 if yes; 0 if no: ")

while Recording == '1':
    # do something


问:
Assigning values Python 2D Array
I am just not getting this.  I want to create a simple 2D array.   I do not know the size, but it will be N number of rows of 3 columns.   I have tried several things:

```<code>data_list[v_row][v_trade_date, v_buy_text, v_ticker]
data_list.append[v_trade_date, v_buy_text, v_ticker]
data_list[v_row].append(v_trade_date)
data_list[v_row].append(v_sell_text)
data_list[v_row].append(v_ticker)
</code>```

Just not getting it.  I do not need to use any FOR loop to assign the values, as each time through the outer loop, I'll be getting 3 items, and I'll assign them explicitly into different cells of that row.   Maybe my thinking is wrong, and I'm thinking of 2D arrays from other languages, but any help would be great.

答:
For appending a row:

```<code>data_list.append([v_trade_date, v_buy_text, v_ticker])
</code>```

And for assigning:

```<code>data_list[v_row] = [v_trade_date, v_buy_text, v_ticker]
</code>```

Title: Assigning values Python 2D Array

Body:
I am just not getting this.  I want to create a simple 2D array.   I do not know the size, but it will be N number of rows of 3 columns.   I have tried several things:

data_list[v_row][v_trade_date, v_buy_text, v_ticker]
data_list.append[v_trade_date, v_buy_text, v_ticker]
data_list[v_row].append(v_trade_date)
data_list[v_row].append(v_sell_text)
data_list[v_row].append(v_ticker)

Just not getting it.  I do not need to use any FOR loop to assign the values, as each time through the outer loop, I'll be getting 3 items, and I'll assign them explicitly into different cells of that row.   Maybe my thinking is wrong, and I'm thinking of 2D arrays from other languages, but any help would be great.

Body:
For appending a row:

data_list.append([v_trade_date, v_buy_text, v_ticker])

And for assigning:

data_list[v_row] = [v_trade_date, v_buy_text, v_ticker]


问:
Can't Transfer Amount to Connect Stripe Account
BackGround:

What i'm trying to do is set-up a marketplace where the customer can acquire services of a seller,The Project is a MERN Stack Travel Application to be exact. What i would like is for the customer to Pay the Platform(My Website connected with Stripe) when he wishes to acquire a service e.g a hotel Room. The Customer stays at the hotel for the allotted time and when he checksout the platform keeps some of the customers amount as application fee and transfers the rest to the service provider,in this case the hotel.

Current Effort:

I Used STRIPE CONNECT to acheive the required functionality.

(Note: you guys don't need to see all of the code below just the heading and description would give you an idea of what i have done and what i'm trying to ask,but please do read the issue section)

i create a Connect account for the seller when he signs up on my Website

Create Connect Account

```<code>const express = require("express");
const router = express.Router();
  router.post("/createAccount", async (req, res) => {
  const { name, email } = req.body; //Data Passed from the FrontEnd
  stripe.accounts.create(
    {
      type: "custom",
      country: "US",
      email: email,
      requested_capabilities: ["card_payments", "transfers"],
    },
    function (err, account) {
      res.json({ account: account });
    }
  );
});
</code>```

When the Seller Provides the rest of the required details(including bank Account) after logging-in to the Seller Portal i create a bank_account,update the already created Connect Account and link the bank_account with the Connect Account (Hopefully, that somehow makes sense)

Create Bank Account

```<code>  router.post("/createBankAccount", async (req, res) => {
  const { account_holder_name, routing_number, account_number } = req.body;
  stripe.tokens.create(
    {
      bank_account: {
        country: "US",
        currency: "USD",
        account_holder_name,
        account_holder_type: "individual",
        routing_number,
        account_number,
      },
    },
    function (err, token) {
      res.send(token);
    }
  );
});
</code>```

Update Account:

```<code>  router.post("/updateAccount", async (req, res) => {
      const {
        AccountID,
        Day,
        Month,
        Year,
        first_name,
        last_name,
        email,
        BankAccountID,
      } = req.body;

      const FrontFilePath = fs.readFileSync("PathToFileHere");
      const FrontPhotoIDUpload = await stripe.files.create({
        file: {
          data: FrontFilePath,
          name: "FrontPhotoID.jpg",
          type: "application.octet-stream",
        },
        purpose: "identity_document",
      });

      const BackFilePath = fs.readFileSync("PathToFileHere");
      const BackPhotoIDUpload = await stripe.files.create({
        file: {
          data: BackFilePath,
          name: "BackPhotoID.jpg",
          type: "application.octet-stream",
        },
        purpose: "identity_document",
      });

      stripe.accounts.update(
        AccountID,
        {
          business_type: "individual",
          individual: {
            dob: { day: Day, month: Month, year: Year },
            first_name: first_name,
            last_name: last_name,
            id_number: "006-20-8311",
            phone: "605-628-6049",
            address: {
              city: "Half Way",
              line1: "2467  Twin House Lane",
              postal_code: "65663",
              state: "MO",
            },
            email,
            ssn_last_4: "8311",
            verification: {
              document: {
                front: FrontPhotoIDUpload.id,
                back: BackPhotoIDUpload.id,
              },
            },
          },
          business_profile: {
            mcc: "4722",
            url: "http://www.baoisne.com",
          },
          tos_acceptance: {
            date: Math.floor(Date.now() / 1000),
            ip: req.connection.remoteAddress,
          },
        },
        function (err, account) {
          console.log(err);
          console.log(account);
        }
      );
     //Connect External Account
      stripe.accounts.createExternalAccount(
        AccountID,
        {
          external_account: BankAccountID,
        },
        function (err, bankAccount) {
          console.log(err);
          res.send(bankAccount);
        }
      );
    });
</code>```

Then when the customers provides his account details i charge the customer,keep some money as application fee and move the rest to the Service Providers Connect account.

Charge Customer

```<code>  router.post("/charge", async (req, res) => {
  const { TokenID, CustomerID, Amount, AccountID } = req.body;
  let PaymentAmount = Amount * 100;
  let application_fee_amount = 400;
  try {
    const payment = await stripe.paymentIntents.create({
      amount: PaymentAmount,
      currency: "USD",
      description: "We did it boss",
      payment_method_data: {
        type: "card",
        card: {
          token: TokenID,
        },
      },
      receipt_email: "abdullahabid427@gmail.com",
      customer: CustomerID,
      application_fee_amount,
      transfer_data: {
      destination: AccountID,
      },
      confirm: true,
    });
    return res.status(200).json({
      confirm: "Payment Succeeded",
    });
  } catch (error) {
    console.log(error);
    return res.status(400).json({
      message: error.message,
    });
  }
});
</code>```

By doing the above procedure a connect account is created and the amount is moved into the connected account.

Issue

The Above procedure although works correctly, it moves the amount into the Connected Service Provider Account directly after the customer is charged, what i would like is for the customer to pay the platform and after the Service Provider has provided his services , the Platform pays the Service Provider, i thought about removing

```<code>  application_fee_amount,
  transfer_data: {
  destination: AccountID,
  }
</code>```

the above parameters in the Charge or Stripe.paymentIntents.create endpoint, and after Service Provider has completed his services i transfer the amount using the Stripe Transfer API

```<code>router.post("/transfer", async (req, res) => {
  try {
    console.log("TRANSFER=");
    const { AccountID, amount } = req.body;
    const transfer = await stripe.transfers.create({
      amount,
      currency: "USD",
      destination: AccountID,
    });
    res.send(transfer);
  } catch (error) {
    res.send(error);
  }
});
</code>```

the issue here is that transfer endpoint returns "Your destination account needs to have at least one of the following capabilities enabled: transfers, legacy_payments" , i have checked the Connected Account in Stripe Dashboard and in the Capabilities section Card_Payment and Transfers are both set to Active, plus Payments and Payouts are both Enabled and the status of the connect account is "Complete"

So if anyone could point in the right direction i would really Appreciate it,Cheers :)

答:
Ok - we'll agree that Stripe works as intended. You get the error message that you get because you remove the destination account ID from the payment intent creating function. That's where the problem lies, under your heading Charge Customer.

Let's look at it: (a shortened version)

```<code>const payment = await stripe.paymentIntents.create({
  amount: PaymentAmount,
  currency: "USD",
  ...
  customer: CustomerID,
  application_fee_amount,
  transfer_data: {
    destination: AccountID,
  },
  confirm: true,
});
</code>```

The last property confirm: true is equivalent to creating and confirming the payment intent in the same call. The default value is false -- using that the status of the newly created payment intent will be requires_confirmation. And when you're ready, you confirm the payment intent along these lines:

```<code>const confirmedPayment = await stripe.paymentIntents.confirm(
    'payment_intent_id',
    {payment_method: 'card'},
    function(err, paymentIntent) {

    }
});
</code>```

A few general comments on things going wrong

When a payer pays money for some goods online, it is the responsibility of the app developer to implement the logic, according to which the money and goods are sent and received: it can be prepaid, postpaid, or partially both. No logic is foolproof. In general, if we worry about customers taking advantage of our payment policy, we can require everything to be prepaid by all paying parties and include a fair refund policy. In this case, Stripe supports refunds of payment intents but what's more important: it keeps track of the status of the payment.

When the payment intent is created but not confirmed, the status is requires_confirmation. Not much can go wrong there. But after the payment intent has been confirmed, the status will be processing - this may take days. You may decide to cancel the payment at any time. But if things go fine, the status will change to succeeded which means that the funds are in the destination account. But if the payment fails for whatever reason, the status will return to requires_payment_method. Even in this case, there's no need to create a new payment or transfer object. You can retrieve the payment intent any time by calling stripe.retrievePaymentIntent(clientSecret) and check the status. But in my opinion, it's much easier to monitor the status changes with a webhook that is configured to receive the status changing events. Even if no action takes place immediately when the status changes, we can store the status in the DB where it's available.

From experience, I've seen how common it is for payments to fail. It doesn't mean that there's any fraud going on on either side but it does mean that the app should be prepared to handle both cases. The events to add to the webhook config are payment_intent.succeeded and payment_intent.payment_failed. How these events are handled is specific to each and every application.

Body:
BackGround:

What i'm trying to do is set-up a marketplace where the customer can acquire services of a seller,The Project is a MERN Stack Travel Application to be exact. What i would like is for the customer to Pay the Platform(My Website connected with Stripe) when he wishes to acquire a service e.g a hotel Room. The Customer stays at the hotel for the allotted time and when he checksout the platform keeps some of the customers amount as application fee and transfers the rest to the service provider,in this case the hotel.

Current Effort:

I Used STRIPE CONNECT to acheive the required functionality.

(Note: you guys don't need to see all of the code below just the heading and description would give you an idea of what i have done and what i'm trying to ask,but please do read the issue section)

i create a Connect account for the seller when he signs up on my Website

Create Connect Account

const express = require("express");
const router = express.Router();
  router.post("/createAccount", async (req, res) => {
  const { name, email } = req.body; //Data Passed from the FrontEnd
  stripe.accounts.create(
    {
      type: "custom",
      country: "US",
      email: email,
      requested_capabilities: ["card_payments", "transfers"],
    },
    function (err, account) {
      res.json({ account: account });
    }
  );
});

When the Seller Provides the rest of the required details(including bank Account) after logging-in to the Seller Portal i create a bank_account,update the already created Connect Account and link the bank_account with the Connect Account (Hopefully, that somehow makes sense)

Create Bank Account

  router.post("/createBankAccount", async (req, res) => {
  const { account_holder_name, routing_number, account_number } = req.body;
  stripe.tokens.create(
    {
      bank_account: {
        country: "US",
        currency: "USD",
        account_holder_name,
        account_holder_type: "individual",
        routing_number,
        account_number,
      },
    },
    function (err, token) {
      res.send(token);
    }
  );
});

Update Account:

  router.post("/updateAccount", async (req, res) => {
      const {
        AccountID,
        Day,
        Month,
        Year,
        first_name,
        last_name,
        email,
        BankAccountID,
      } = req.body;

      const FrontFilePath = fs.readFileSync("PathToFileHere");
      const FrontPhotoIDUpload = await stripe.files.create({
        file: {
          data: FrontFilePath,
          name: "FrontPhotoID.jpg",
          type: "application.octet-stream",
        },
        purpose: "identity_document",
      });

      const BackFilePath = fs.readFileSync("PathToFileHere");
      const BackPhotoIDUpload = await stripe.files.create({
        file: {
          data: BackFilePath,
          name: "BackPhotoID.jpg",
          type: "application.octet-stream",
        },
        purpose: "identity_document",
      });

      stripe.accounts.update(
        AccountID,
        {
          business_type: "individual",
          individual: {
            dob: { day: Day, month: Month, year: Year },
            first_name: first_name,
            last_name: last_name,
            id_number: "006-20-8311",
            phone: "605-628-6049",
            address: {
              city: "Half Way",
              line1: "2467  Twin House Lane",
              postal_code: "65663",
              state: "MO",
            },
            email,
            ssn_last_4: "8311",
            verification: {
              document: {
                front: FrontPhotoIDUpload.id,
                back: BackPhotoIDUpload.id,
              },
            },
          },
          business_profile: {
            mcc: "4722",
            url: "http://www.baoisne.com",
          },
          tos_acceptance: {
            date: Math.floor(Date.now() / 1000),
            ip: req.connection.remoteAddress,
          },
        },
        function (err, account) {
          console.log(err);
          console.log(account);
        }
      );
     //Connect External Account
      stripe.accounts.createExternalAccount(
        AccountID,
        {
          external_account: BankAccountID,
        },
        function (err, bankAccount) {
          console.log(err);
          res.send(bankAccount);
        }
      );
    });

Then when the customers provides his account details i charge the customer,keep some money as application fee and move the rest to the Service Providers Connect account.

Charge Customer

  router.post("/charge", async (req, res) => {
  const { TokenID, CustomerID, Amount, AccountID } = req.body;
  let PaymentAmount = Amount * 100;
  let application_fee_amount = 400;
  try {
    const payment = await stripe.paymentIntents.create({
      amount: PaymentAmount,
      currency: "USD",
      description: "We did it boss",
      payment_method_data: {
        type: "card",
        card: {
          token: TokenID,
        },
      },
      receipt_email: "abdullahabid427@gmail.com",
      customer: CustomerID,
      application_fee_amount,
      transfer_data: {
      destination: AccountID,
      },
      confirm: true,
    });
    return res.status(200).json({
      confirm: "Payment Succeeded",
    });
  } catch (error) {
    console.log(error);
    return res.status(400).json({
      message: error.message,
    });
  }
});

By doing the above procedure a connect account is created and the amount is moved into the connected account.

Issue

The Above procedure although works correctly, it moves the amount into the Connected Service Provider Account directly after the customer is charged, what i would like is for the customer to pay the platform and after the Service Provider has provided his services , the Platform pays the Service Provider, i thought about removing

  application_fee_amount,
  transfer_data: {
  destination: AccountID,
  }

the above parameters in the Charge or Stripe.paymentIntents.create endpoint, and after Service Provider has completed his services i transfer the amount using the Stripe Transfer API

router.post("/transfer", async (req, res) => {
  try {
    console.log("TRANSFER=");
    const { AccountID, amount } = req.body;
    const transfer = await stripe.transfers.create({
      amount,
      currency: "USD",
      destination: AccountID,
    });
    res.send(transfer);
  } catch (error) {
    res.send(error);
  }
});

the issue here is that transfer endpoint returns "Your destination account needs to have at least one of the following capabilities enabled: transfers, legacy_payments" , i have checked the Connected Account in Stripe Dashboard and in the Capabilities section Card_Payment and Transfers are both set to Active, plus Payments and Payouts are both Enabled and the status of the connect account is "Complete"

So if anyone could point in the right direction i would really Appreciate it,Cheers :)

Body:
Ok - we'll agree that Stripe works as intended. You get the error message that you get because you remove the destination account ID from the payment intent creating function. That's where the problem lies, under your heading Charge Customer.

Let's look at it: (a shortened version)

const payment = await stripe.paymentIntents.create({
  amount: PaymentAmount,
  currency: "USD",
  ...
  customer: CustomerID,
  application_fee_amount,
  transfer_data: {
    destination: AccountID,
  },
  confirm: true,
});

The last property confirm: true is equivalent to creating and confirming the payment intent in the same call. The default value is false -- using that the status of the newly created payment intent will be requires_confirmation. And when you're ready, you confirm the payment intent along these lines:

const confirmedPayment = await stripe.paymentIntents.confirm(
    'payment_intent_id',
    {payment_method: 'card'},
    function(err, paymentIntent) {

    }
});

A few general comments on things going wrong

When a payer pays money for some goods online, it is the responsibility of the app developer to implement the logic, according to which the money and goods are sent and received: it can be prepaid, postpaid, or partially both. No logic is foolproof. In general, if we worry about customers taking advantage of our payment policy, we can require everything to be prepaid by all paying parties and include a fair refund policy. In this case, Stripe supports refunds of payment intents but what's more important: it keeps track of the status of the payment.

When the payment intent is created but not confirmed, the status is requires_confirmation. Not much can go wrong there. But after the payment intent has been confirmed, the status will be processing - this may take days. You may decide to cancel the payment at any time. But if things go fine, the status will change to succeeded which means that the funds are in the destination account. But if the payment fails for whatever reason, the status will return to requires_payment_method. Even in this case, there's no need to create a new payment or transfer object. You can retrieve the payment intent any time by calling stripe.retrievePaymentIntent(clientSecret) and check the status. But in my opinion, it's much easier to monitor the status changes with a webhook that is configured to receive the status changing events. Even if no action takes place immediately when the status changes, we can store the status in the DB where it's available.

From experience, I've seen how common it is for payments to fail. It doesn't mean that there's any fraud going on on either side but it does mean that the app should be prepared to handle both cases. The events to add to the webhook config are payment_intent.succeeded and payment_intent.payment_failed. How these events are handled is specific to each and every application.


问:
How to use the useState hook to handle multiple textInputs that are dynamic from a FlatList in React Native?

I have a functional component that is a screen and I need to handle some state. I do not want to refactor my code to make it a class component and I would like to make use of hooks. I have a component within the screen that renders a flatlist (from JSON) of a product description, quantity and a box for a user input quantity. Currently my state for all the input quantities is tied together, so when I enter a number into 1 box, that same number is displayed in all boxes. How can I seperate and store the input state using hooks?

There is a lot of examples online with using hooks to store 1 peice of data but not multiple and as I do not know how many 'products' there will be a head of time I cannot create different useState's for them. Am I best having 1 useState for all the input boxes and stored in an array?

```<code>import { Text, View, StyleSheet, SafeAreaView, FlatList } from "react-native";

function InstallScreen({ navigation, route }) {
  // State for the number installed component
  const [quantityInstalled, setQuantityInstalled] = useState([]);

  const { item } = route.params;

  // pulling just the product arrays from the job data and storing separately
  const productData = item.products;

  return (
    <View style={styles.containerNine}>
      <View style={styles.descriptionBoxContainer}>
        <View style={styles.descriptionBox}>
          <FlatList
            data={productData}
            keyExtractor={(item) => item.id.toString()}
            renderItem={({ item }) => (
              <DescriptionBox
                productDescription={item.description}
                dueQuantity={item.quantity}
                value={quantityInstalled}
                onChangeText={(value) => setQuantityInstalled(value)}
              />
            )}
          />

          <Text>Number installed is {quantityInstalled} </Text>
        </View>
      </View>
    </View>
  );
};
</code>```

Description Component

```<code>import { View, Text, StyleSheet, TextInput } from "react-native";

const DescriptionBox = (props) => {
  return (
    <View style={styles.productsAllContainer}>
      <View style={styles.descriptionBoxStyle}>
        <Text style={styles.textStyle}>{props.productDescription}</Text>
      </View>

      <View style={styles.qtyBoxStyle}>
        <Text style={styles.qtyTextStyle}>{props.dueQuantity}</Text>
      </View>

      <View>
        <TextInput
          style={styles.installedBoxStyle}
          textAlign="center"
          fontSize="18"
          fontWeight="bold"
          autoCapitalize="none"
          autoCorrect={false}
          keyboardType={"numeric"}
          maxLength={5}
          value={props.value}
          onChangeText={props.onChangeText}
        />
      </View>
    </View>
  );
};
</code>```

答:
Disclaimer: I have not used react native, but what I usually do is make the name, the id of the item in the list then pass that name up when changing the state

```<code><input name={id} onChange={onChange} />
</code>```

then having one call to use state but make the on change function get the name from the event handler

```<code>  const [productQuantity, setProductQuantity] = React.useState('')
  const onChange = (e) => {
    const {name, value} = e.target;
    setProductQuantity({...productQuantity,[name]:value})
  };
</code>```

however for your specific case you'd also probably need a function to get the installed quantity from the state, you could also pass down a function to the child to do this along the lines, of

```<code>  const getProductQuantity = (id) => (
    productQuantity[id] && productQuantity[id] || 0
  )
</code>```

Body:
I have a functional component that is a screen and I need to handle some state. I do not want to refactor my code to make it a class component and I would like to make use of hooks. I have a component within the screen that renders a flatlist (from JSON) of a product description, quantity and a box for a user input quantity. Currently my state for all the input quantities is tied together, so when I enter a number into 1 box, that same number is displayed in all boxes. How can I seperate and store the input state using hooks?

There is a lot of examples online with using hooks to store 1 peice of data but not multiple and as I do not know how many 'products' there will be a head of time I cannot create different useState's for them. Am I best having 1 useState for all the input boxes and stored in an array?

import { Text, View, StyleSheet, SafeAreaView, FlatList } from "react-native";

function InstallScreen({ navigation, route }) {
  // State for the number installed component
  const [quantityInstalled, setQuantityInstalled] = useState([]);

  const { item } = route.params;

  // pulling just the product arrays from the job data and storing separately
  const productData = item.products;

  return (
    <View style={styles.containerNine}>
      <View style={styles.descriptionBoxContainer}>
        <View style={styles.descriptionBox}>
          <FlatList
            data={productData}
            keyExtractor={(item) => item.id.toString()}
            renderItem={({ item }) => (
              <DescriptionBox
                productDescription={item.description}
                dueQuantity={item.quantity}
                value={quantityInstalled}
                onChangeText={(value) => setQuantityInstalled(value)}
              />
            )}
          />

          <Text>Number installed is {quantityInstalled} </Text>
        </View>
      </View>
    </View>
  );
};

Description Component

import { View, Text, StyleSheet, TextInput } from "react-native";

const DescriptionBox = (props) => {
  return (
    <View style={styles.productsAllContainer}>
      <View style={styles.descriptionBoxStyle}>
        <Text style={styles.textStyle}>{props.productDescription}</Text>
      </View>

      <View style={styles.qtyBoxStyle}>
        <Text style={styles.qtyTextStyle}>{props.dueQuantity}</Text>
      </View>

      <View>
        <TextInput
          style={styles.installedBoxStyle}
          textAlign="center"
          fontSize="18"
          fontWeight="bold"
          autoCapitalize="none"
          autoCorrect={false}
          keyboardType={"numeric"}
          maxLength={5}
          value={props.value}
          onChangeText={props.onChangeText}
        />
      </View>
    </View>
  );
};

Body:
Disclaimer: I have not used react native, but what I usually do is make the name, the id of the item in the list then pass that name up when changing the state

<input name={id} onChange={onChange} />

then having one call to use state but make the on change function get the name from the event handler

  const [productQuantity, setProductQuantity] = React.useState('')
  const onChange = (e) => {
    const {name, value} = e.target;
    setProductQuantity({...productQuantity,[name]:value})
  };

however for your specific case you'd also probably need a function to get the installed quantity from the state, you could also pass down a function to the child to do this along the lines, of

  const getProductQuantity = (id) => (
    productQuantity[id] && productQuantity[id] || 0
  )


问:
Read-only (visually) CheckBox
I need to have 2 groups of controls on the screen: inputs and outputs (so they have 2 states: On or Off). Thus CheckBox seems to be a good choice. Checking any output will set it.

However, when displaying inputs there will be no user interaction with it. User is only allowed to see its value, not to change it.

Question: how to make checkbos visually appears as read-only ?

Could think about possible solutions:

Make CheckBox disabled. Bad: there will be no tooltip (possible to solve it? by fake panel on top?) and visually disabled CheckBox is not nice (and I don't want to make user think it is disabled).

Use different control. Which one? Label doesn't have nice placeholder for the On/Off value. RadioButton look differently, but they usually means there is a single choice out of many, while values of inputs are independent.

Making own component. Drawing the whole CheckBox is a bit overkill (and honestly, I don't know how to do it to have Win7 appearance). Would it be possible to add only ReadOnly appearance to the box part easily?

What do you guys think?

答:
This is an old post but still can be usefull so here is my solution.

In order to make a read-only behavior:

Disable highlight when the cursor is over the CheckBox

Disable reacting (logically or visibly) to a mouse click

Have tooltips enabled

We can inherit the CheckBox class and disable mouse and keyboard interaction:

```<code>public class ReadOnlyCheckBox : CheckBox
{
    [System.ComponentModel.Category("Behavior")]
    [System.ComponentModel.DefaultValue(false)]
    public bool ReadOnly { get; set; } = false;

    protected override void OnMouseEnter(EventArgs e)
    {
        // Disable highlight when the cursor is over the CheckBox
        if (!ReadOnly) base.OnMouseEnter(e);
    }

    protected override void OnMouseDown(MouseEventArgs e)
    {
        // Disable reacting (logically or visibly) to a mouse click
        if (!ReadOnly) base.OnMouseDown(e);
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        // Suppress space key to disable checking/unchecking
        if (!ReadOnly || e.KeyData != Keys.Space) base.OnKeyDown(e);
    }
}
</code>```

In order to make it visually apparent that the CheckBox is read-only, we can change the ForColor according to the ReadOnly property.

Note: changing the ForColor only changes the text color, the colors of the checkmark can only be changed by overriding the OnPaint method and repainting the CheckBox (as far as I know).

Here is an extended version of the previous code that changes the ForColor according to the ReadOnly property:

```<code>public class ReadOnlyCheckBox : CheckBox
{
    private bool _readOnly = false;
    private Color _readOnlyForeColor = Color.Gray;
    private Color _normalForeColor = Color.Black;

    [System.ComponentModel.Category("Behavior")]
    [System.ComponentModel.DefaultValue(false)]
    public bool ReadOnly
    {
        get => _readOnly;
        set
        {
            if (_readOnly != value)
            {
                _readOnly = value;
                UpdateForColor();
            }
        }
    }

    [System.ComponentModel.Category("Appearance")]
    [System.ComponentModel.DefaultValue(typeof(Color), "Black")]
    public Color NormalForeColor
    {
        get => _normalForeColor;
        set
        {
            if (_normalForeColor != value)
            {
                _normalForeColor = value;
                UpdateForColor();
            }
        }
    }

    [System.ComponentModel.Category("Appearance")]
    [System.ComponentModel.DefaultValue(typeof(Color), "Gray")]
    public Color ReadOnlyForeColor
    {
        get => _readOnlyForeColor;
        set
        {
            if (_readOnlyForeColor != value)
            {
                _readOnlyForeColor = value;
                UpdateForColor();
            }
        }
    }

    // Hide ForeColor from the editor
    [System.ComponentModel.Browsable(false)]
    [System.ComponentModel.EditorBrowsable(
        System.ComponentModel.EditorBrowsableState.Never)]
    public override Color ForeColor
    {
        get => base.ForeColor;
        set => base.ForeColor = value;
    }

    public ReadOnlyCheckBox()
    {
        UpdateForColor();
    }

    private void UpdateForColor()
    {
        ForeColor = ReadOnly ? ReadOnlyForeColor : NormalForeColor;
    }

    protected override void OnMouseEnter(EventArgs e)
    {
        // Disable highlight when the cursor is over the CheckBox
        if (!ReadOnly) base.OnMouseEnter(e);
    }

    protected override void OnMouseDown(MouseEventArgs e)
    {
        // Disable reacting (logically or visibly) to a mouse click
        if (!ReadOnly) base.OnMouseDown(e);
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        // Suppress space key to disable checking/unchecking
        if (!ReadOnly || e.KeyData != Keys.Space) base.OnKeyDown(e);
    }
}
</code>```

Title: Read-only (visually) CheckBox

Body:
This is an old post but still can be usefull so here is my solution.

In order to make a read-only behavior:

Disable highlight when the cursor is over the CheckBox

Disable reacting (logically or visibly) to a mouse click

Have tooltips enabled

We can inherit the CheckBox class and disable mouse and keyboard interaction:

public class ReadOnlyCheckBox : CheckBox
{
    [System.ComponentModel.Category("Behavior")]
    [System.ComponentModel.DefaultValue(false)]
    public bool ReadOnly { get; set; } = false;

    protected override void OnMouseEnter(EventArgs e)
    {
        // Disable highlight when the cursor is over the CheckBox
        if (!ReadOnly) base.OnMouseEnter(e);
    }

    protected override void OnMouseDown(MouseEventArgs e)
    {
        // Disable reacting (logically or visibly) to a mouse click
        if (!ReadOnly) base.OnMouseDown(e);
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        // Suppress space key to disable checking/unchecking
        if (!ReadOnly || e.KeyData != Keys.Space) base.OnKeyDown(e);
    }
}

In order to make it visually apparent that the CheckBox is read-only, we can change the ForColor according to the ReadOnly property.

Note: changing the ForColor only changes the text color, the colors of the checkmark can only be changed by overriding the OnPaint method and repainting the CheckBox (as far as I know).

Here is an extended version of the previous code that changes the ForColor according to the ReadOnly property:

public class ReadOnlyCheckBox : CheckBox
{
    private bool _readOnly = false;
    private Color _readOnlyForeColor = Color.Gray;
    private Color _normalForeColor = Color.Black;

    [System.ComponentModel.Category("Behavior")]
    [System.ComponentModel.DefaultValue(false)]
    public bool ReadOnly
    {
        get => _readOnly;
        set
        {
            if (_readOnly != value)
            {
                _readOnly = value;
                UpdateForColor();
            }
        }
    }

    [System.ComponentModel.Category("Appearance")]
    [System.ComponentModel.DefaultValue(typeof(Color), "Black")]
    public Color NormalForeColor
    {
        get => _normalForeColor;
        set
        {
            if (_normalForeColor != value)
            {
                _normalForeColor = value;
                UpdateForColor();
            }
        }
    }

    [System.ComponentModel.Category("Appearance")]
    [System.ComponentModel.DefaultValue(typeof(Color), "Gray")]
    public Color ReadOnlyForeColor
    {
        get => _readOnlyForeColor;
        set
        {
            if (_readOnlyForeColor != value)
            {
                _readOnlyForeColor = value;
                UpdateForColor();
            }
        }
    }

    // Hide ForeColor from the editor
    [System.ComponentModel.Browsable(false)]
    [System.ComponentModel.EditorBrowsable(
        System.ComponentModel.EditorBrowsableState.Never)]
    public override Color ForeColor
    {
        get => base.ForeColor;
        set => base.ForeColor = value;
    }

    public ReadOnlyCheckBox()
    {
        UpdateForColor();
    }

    private void UpdateForColor()
    {
        ForeColor = ReadOnly ? ReadOnlyForeColor : NormalForeColor;
    }

    protected override void OnMouseEnter(EventArgs e)
    {
        // Disable highlight when the cursor is over the CheckBox
        if (!ReadOnly) base.OnMouseEnter(e);
    }

    protected override void OnMouseDown(MouseEventArgs e)
    {
        // Disable reacting (logically or visibly) to a mouse click
        if (!ReadOnly) base.OnMouseDown(e);
    }

    protected override void OnKeyDown(KeyEventArgs e)
    {
        // Suppress space key to disable checking/unchecking
        if (!ReadOnly || e.KeyData != Keys.Space) base.OnKeyDown(e);
    }
}


问:
Add list to Pandas Dateframe, but keep NaNs at the top
I think this has probably been answered, but I cant find the answer anywhere. It is pretty trivial. How can I add a list to a pandas dataframe as a column, but keep the NaNs at the top?

This is the code i have:

```<code>df = pd.DataFrame()
a = [1,2,3,4,5,6,7]
b = [2,3,5,6,4,3,2]
c = [2,3,5,6,4,3]
d = [1,2,3,4]
df["a"] = a
df["b"] = b
df.loc[range(len(c)),'c'] = c
df.loc[range(len(d)),'d'] = d
print(df)
</code>```

which returns this:

```<code>   a  b    c    d
0  1  2  2.0  1.0
1  2  3  3.0  2.0
2  3  5  5.0  3.0
3  4  6  6.0  4.0
4  5  4  4.0  NaN
5  6  3  3.0  NaN
6  7  2  NaN  NaN
</code>```

However, I would like it to return this instead:

```<code>  a  b    c    d
0  1  2  NaN  NaN
1  2  3  2.0  NaN
2  3  5  3.0  NaN
3  4  6  5.0  1.0
4  5  4  6.0  2.0
5  6  3  4.0  3.0
6  7  2  3.0  4.0
</code>```

答:
If the problem is with assignment instead of transformation, you can also try with iloc with get_loc after creating a dictionary (d):

```<code>d = {'c':c,'d':d}
df = df.reindex(columns=df.columns.union(d.keys(),sort=False))

for k,v in d.items():
    df.iloc[-len(v):,df.columns.get_loc(k)] = v
</code>```

```<code>print(df)

   a  b    c    d
0  1  2  NaN  NaN
1  2  3  2.0  NaN
2  3  5  3.0  NaN
3  4  6  5.0  1.0
4  5  4  6.0  2.0
5  6  3  4.0  3.0
6  7  2  3.0  4.0
</code>```

Body:
I think this has probably been answered, but I cant find the answer anywhere. It is pretty trivial. How can I add a list to a pandas dataframe as a column, but keep the NaNs at the top?

This is the code i have:

df = pd.DataFrame()
a = [1,2,3,4,5,6,7]
b = [2,3,5,6,4,3,2]
c = [2,3,5,6,4,3]
d = [1,2,3,4]
df["a"] = a
df["b"] = b
df.loc[range(len(c)),'c'] = c
df.loc[range(len(d)),'d'] = d
print(df)

which returns this:

   a  b    c    d
0  1  2  2.0  1.0
1  2  3  3.0  2.0
2  3  5  5.0  3.0
3  4  6  6.0  4.0
4  5  4  4.0  NaN
5  6  3  3.0  NaN
6  7  2  NaN  NaN

However, I would like it to return this instead:

  a  b    c    d
0  1  2  NaN  NaN
1  2  3  2.0  NaN
2  3  5  3.0  NaN
3  4  6  5.0  1.0
4  5  4  6.0  2.0
5  6  3  4.0  3.0
6  7  2  3.0  4.0

Body:
If the problem is with assignment instead of transformation, you can also try with iloc with get_loc after creating a dictionary (d):

d = {'c':c,'d':d}
df = df.reindex(columns=df.columns.union(d.keys(),sort=False))

for k,v in d.items():
    df.iloc[-len(v):,df.columns.get_loc(k)] = v

print(df)

   a  b    c    d
0  1  2  NaN  NaN
1  2  3  2.0  NaN
2  3  5  3.0  NaN
3  4  6  5.0  1.0
4  5  4  6.0  2.0
5  6  3  4.0  3.0
6  7  2  3.0  4.0


问:
I am getting error while running this part of the code. tried some of the existing solutions, none of them helped
```<code>for face_location in face_locations:
top , right, bottom , left = face_location
print("A face is located at the pixel locations Top: {} , Right:{} , Left: {} , Bottom: {}.")

   **** I always get this error:****

 File "<ipython-input-55-23558b69803e>", line 1
for face_location in face_locations:
</code>```

<p>^SyntaxError: unexpected EOF while parsing</p>

答:
Could it be that you forgot to use a tab after the for loop?
instead of

```<code>for face_location in face_locations:
top , right, bottom , left = face_location
</code>```

do

```<code>for face_location in face_locations:
    top , right, bottom , left = face_location
</code>```

Body:
for face_location in face_locations:
top , right, bottom , left = face_location
print("A face is located at the pixel locations Top: {} , Right:{} , Left: {} , Bottom: {}.")

   **** I always get this error:****

 File "<ipython-input-55-23558b69803e>", line 1
for face_location in face_locations:

^SyntaxError: unexpected EOF while parsing

Body:
Could it be that you forgot to use a tab after the for loop?
instead of

for face_location in face_locations:
top , right, bottom , left = face_location

do

for face_location in face_locations:
    top , right, bottom , left = face_location


问:
How to ignore certain script files / lines when debugging?
I'm trying to debug some JavaScript, I want to find out what code gets executed when I hover over a certain div element (I've got no idea which bit of code, because there's no direct 'onmouseover' - I think there's a jQuery selector in place somewhere?).

Usually I'd use the "Break All" / "Break On Next" facility provided by Developer Tools / Firebug, but my problem is that other code (tickers, mouse movement listeners etc.) immediately gets caught instead.

What I'd like to do is tell the debugger to ignore certain JavaScript files or individual lines, so that it won't stop on code I'm not interested in or have ruled out. Is there any way to achieve that in IE (spit, spit!) - or could you suggest a better approach?

答:
If using are using IE 7.0 onwards, you should have developer toolbar from where you can debug. Just use breakpoint where you need, rest of the code will not stop.
  Alternatavely you  can define other applications like Interdev/ Visual Studio.net for debugging purpose too.</p>


问:
simple pandas merge has unexpected results - get data structure but not expected data
So I'm getting unexpected results - my merge includes 2 columns in 1 table, 3 columns in another with a common column between them. Merge returns the expected 3 column data structure, but only the results from one side of the merge (basically a copy of one side of the data), so one field has no values unless I do an outer join. If I do an inner join, I get no values - even though I can clearly see values in common.
Have used on_left and on_right with same results. No columns are indexed.

I am using Pandas v 1.0.3

DFA.merge(DFB, on=['queue'],  how='left').fillna('').drop_duplicates() results in

```<code>(illustrative - not actual results)
queue  group   app
Q1        G1
Q2        G2
Q3        G2
Q4
Q5        G4
Q5        G6
</code>```

DFA.merge(DFB, on=['queue'],  how='right').fillna('').drop_duplicates() results in

```<code>
(illustrative - not actual results)
app queue   group
10  Q1
20  Q3
30  Q3
40  Q4
10
</code>```

DFA.merge(DFB, on=['queue'],  how='inner').fillna('').drop_duplicates() results in

```<code>(actual results)
</code>```

yeah, no results

This seems pretty simple - what am I missing here? The values in the queue file are verified to be exactly the same in excel. data types are all objects (strings)

答:
The user striped the spaces off the data and then showed me that the data matched, then sent me the file w/o saving it so the data still had spaces.

never trust any inputs

The code was fine.

Body:
So I'm getting unexpected results - my merge includes 2 columns in 1 table, 3 columns in another with a common column between them. Merge returns the expected 3 column data structure, but only the results from one side of the merge (basically a copy of one side of the data), so one field has no values unless I do an outer join. If I do an inner join, I get no values - even though I can clearly see values in common.
Have used on_left and on_right with same results. No columns are indexed.

I am using Pandas v 1.0.3

DFA.merge(DFB, on=['queue'],  how='left').fillna('').drop_duplicates() results in

(illustrative - not actual results)
queue  group   app
Q1        G1
Q2        G2
Q3        G2
Q4
Q5        G4
Q5        G6

DFA.merge(DFB, on=['queue'],  how='right').fillna('').drop_duplicates() results in

(illustrative - not actual results)
app queue   group
10  Q1
20  Q3
30  Q3
40  Q4
10

DFA.merge(DFB, on=['queue'],  how='inner').fillna('').drop_duplicates() results in

(actual results)

yeah, no results

This seems pretty simple - what am I missing here? The values in the queue file are verified to be exactly the same in excel. data types are all objects (strings)


问:
Error when creating file opening window by using tkinter library
I am referring to this post: Tkinter not creating a window?. And the code published there as answer returns me the same error on my code: TclError: no display name and no $DISPLAY environment variable
This is my code:

```<code>import tkinter
root = tkinter.Tk()
root.title = ('Project planner')
open_button = tkinter.Button(root, text='Open project...', command=open_project)
open_button.pack(side='top')
canvas = tkinter.Canvas(root, width=800, height=400, bg='white')
canvas.pack(side='bottom')
tkinter.mainloop()
</code>```

What is wrong?

答: I should be running my code locally, then it works, it does not work on server.</p>

Body:
I am referring to this post: Tkinter not creating a window?. And the code published there as answer returns me the same error on my code: TclError: no display name and no $DISPLAY environment variable
This is my code:

import tkinter
root = tkinter.Tk()
root.title = ('Project planner')
open_button = tkinter.Button(root, text='Open project...', command=open_project)
open_button.pack(side='top')
canvas = tkinter.Canvas(root, width=800, height=400, bg='white')
canvas.pack(side='bottom')
tkinter.mainloop()

What is wrong?