问:
Pass and store optional delegate in variable
I'm trying to pass an optional callback parameter to my class when I instantiate it. I need a callback method to format some value that may or may not need formatting.

Here is my simplified code of what I am trying to do:

```<code>Public Class ColumnSpec
    Property Title As String
    Property Name As String
    Property Value As String

    Delegate Function CallBack(aValue As String) As String
    Property HasCallBack As Boolean

    Public Sub New(aTitle As String, aName As String, Optional aCallBack As CallBack = Nothing)
        _Title = aTitle
        _Name = aName
        ' How do I assign aCallBack to the delegate function here?
        _HasCallBack = aCallBack IsNot Nothing
    End Sub
End Class
</code>```

I may or may not pass a callback function when instantiating ColumnSpec.

In another class, I need to check and call the delegate.

```<code>Public Class MyClass

   Public Function FormatText(Value as String) As String
       Return Value + "01234"  ' Return value after modifying
   End Function

   Public Function RenderValue() As String
       Dim lNewCol1 as ColumnSpec("Title1", "Name2", AddressOf FormatText)
       Dim lNewCol2 as ColumnSpec("Title2", "Name2")

       ' How do I check if there is a delegate and call it?
       If lNewCol1.HasCallBack Then lNewCol1.Value =  lNewCol1.CallBack(lNewCol1.HasCallBack)
       If lNewCol2.HasCallBack Then lNewCol2.Value =  lNewCol1.CallBack(lNewCol2.HasCallBack)
   End Function
End Class
</code>```

I am completely new to delegates. Any ideas on how I can solve this?

答:
Your line Delegate Function CallBack(aValue As String) As String only declares the type of the callback.  You need a separate property or field to hold the reference.

So, you would modify the class slightly:

Delegate Function CallbackFunction(aValue As String) As String

Public ReadOnly Property Callback As CallbackFunction

Public ReadOnly Property HasCallback As Boolean
    Get
        'Alternatively, you could assign the value in the ctor as in your code...
        Return Callback IsNot Nothing
    End Get
End Property

Public Sub New(Optional aCallback As CallbackFunction = Nothing)
    Me.Callback = aCallback
End Sub
```
<p>Your client code is fine as-is and doesn't need to be changed.</p>
<p>If you don't care about having a named type for the callback function, you could also use newer syntax, e.g.</p>
<pre class="lang-vb prettyprint-override"><code>Public ReadOnly Property Callback As Func(Of String, String)
</code>```

Also modifying the constructor accordingly.

The client code would still work fine as-is with this modification.

(Action is to Sub as Func is to Function.)

Body:
I'm trying to pass an optional callback parameter to my class when I instantiate it. I need a callback method to format some value that may or may not need formatting.

Here is my simplified code of what I am trying to do:

Public Class ColumnSpec
    Property Title As String
    Property Name As String
    Property Value As String

    Delegate Function CallBack(aValue As String) As String
    Property HasCallBack As Boolean

    Public Sub New(aTitle As String, aName As String, Optional aCallBack As CallBack = Nothing)
        _Title = aTitle
        _Name = aName
        ' How do I assign aCallBack to the delegate function here?
        _HasCallBack = aCallBack IsNot Nothing
    End Sub
End Class

I may or may not pass a callback function when instantiating ColumnSpec.

In another class, I need to check and call the delegate.

Public Class MyClass

   Public Function FormatText(Value as String) As String
       Return Value + "01234"  ' Return value after modifying
   End Function

   Public Function RenderValue() As String
       Dim lNewCol1 as ColumnSpec("Title1", "Name2", AddressOf FormatText)
       Dim lNewCol2 as ColumnSpec("Title2", "Name2")

       ' How do I check if there is a delegate and call it?
       If lNewCol1.HasCallBack Then lNewCol1.Value =  lNewCol1.CallBack(lNewCol1.HasCallBack)
       If lNewCol2.HasCallBack Then lNewCol2.Value =  lNewCol1.CallBack(lNewCol2.HasCallBack)
   End Function
End Class

I am completely new to delegates. Any ideas on how I can solve this?

Body:
Your line Delegate Function CallBack(aValue As String) As String only declares the type of the callback.  You need a separate property or field to hold the reference.

So, you would modify the class slightly:

Delegate Function CallbackFunction(aValue As String) As String

Public ReadOnly Property Callback As CallbackFunction

Public ReadOnly Property HasCallback As Boolean
    Get
        'Alternatively, you could assign the value in the ctor as in your code...
        Return Callback IsNot Nothing
    End Get
End Property

Public Sub New(Optional aCallback As CallbackFunction = Nothing)
    Me.Callback = aCallback
End Sub

Your client code is fine as-is and doesn't need to be changed.

If you don't care about having a named type for the callback function, you could also use newer syntax, e.g.

Public ReadOnly Property Callback As Func(Of String, String)

Also modifying the constructor accordingly.

The client code would still work fine as-is with this modification.

(Action is to Sub as Func is to Function.)


来源: stackexchange

问:
Trying to record from microphone and playback in real time
I'm trying to record data from my microphone and then play it back through the speakers in real time, and with some delays, but I'm having some problems with it. I chose to use python and alsaaudio, and my current script I'm having problems with can be found  here. This works with what I have this far(not the delay part), but produces some clicking. alsaaudio docs has this to say:

The most common reason for problems with playback of PCM audio is that writes to PCM devices must exactly match the data rate of the device.

If too little data is written to the device, it will underrun, and ugly clicking sounds will occur. Conversely, of too much data is written to the device, the write function will either block (PCM_NORMAL mode) or return zero (PCM_NONBLOCK mode).

I seem to be misunderstanding the docs, it says this about write():

PCM.write(data)

Writes (plays) the sound in data. The length of data must be a multiple of the frame size, and should be exactly the size of a period

a period in my script is 160.

it says this about read():

In PCM_NORMAL mode, this function blocks until a full period is available, and then returns a tuple (length,data) where length is the number of frames of captured data, and data is the captured sound frames as a string. The length of the returned data will be periodsize*framesize bytes.

in my script, period_size*frame_size should also be equal to 160, but when I print the length(part of tuple read() returns) i'm getting 940. Obviously I seem to not be passing the right amount of data to out.write(), but I'm not sure where to go. I put this code together mostly through examples I found, and I just started working with alsaaudio / sound, trying to put together some interesting projects, so I don't know a whole lot yet.

I also wanted to record live from the microphone, then playback with a 100ms delay, hence the commented time.sleep(). If I uncomment it, the length seems to go from 940 to -32 repeatedly, eventually causing out.write() to throw an exception (not enough data).

Could someone tell me how (or what's wrong with my script) I'd go about recording and playing back sound data in real time, and with a 100ms delay?

答:
you can't use sleep(0.1) to delay the output by 100ms. you need to create a buffer which hold the 100ms audio data:

```<code>buf = []
while True:
    l, data = inp.read()
    buf.append(data)
    if len(buffer)>=10:
        out.write(buf[0])
        del buf[0]
</code>```

change 10 to some number that will cause 100ms delay.

ContentLicense: CC BY-SA 3.0

Body:
you can't use sleep(0.1) to delay the output by 100ms. you need to create a buffer which hold the 100ms audio data:

buf = []
while True:
    l, data = inp.read()
    buf.append(data)
    if len(buffer)>=10:
        out.write(buf[0])
        del buf[0]

change 10 to some number that will cause 100ms delay.


问:
How to override log4j.properties during testing?
I'm trying to log all DEBUG messages to console during testing in maven. For this purpose I created a file src/test/resources/log4j.properties, which is going to override the configuration I already have in src/main/resources/log4j.properties. Unfortunately such an overriding is not happening. Why and how to fix it?

答:
Beware of changed version for that, with 2.17.1 of log4j at least, you'll have to change it from log4j.configuration to log4j.configurationFile to avoid having

ERROR StatusLogger Reconfiguration failed: No configuration found for '18b4aac2' at 'null' in 'null'

Here an example

```<code>        <plugin>
            <!--            DOC http://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html -->
            <artifactId>maven-surefire-plugin</artifactId>
            <version>${maven.surefire.version}</version>
            <!-- enables java assertions for tests -->
            <configuration>
                <enableAssertions>true</enableAssertions>
                <systemPropertyVariables>
                    <log4j.configurationFile>src/test/resources/log4j2_for_surefire.xml</log4j.configurationFile>
                </systemPropertyVariables>
            </configuration>
        </plugin>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Beware of changed version for that, with 2.17.1 of log4j at least, you'll have to change it from log4j.configuration to log4j.configurationFile to avoid having

ERROR StatusLogger Reconfiguration failed: No configuration found for '18b4aac2' at 'null' in 'null'

Here an example

        <plugin>
            <!--            DOC http://maven.apache.org/surefire/maven-surefire-plugin/test-mojo.html -->
            <artifactId>maven-surefire-plugin</artifactId>
            <version>${maven.surefire.version}</version>
            <!-- enables java assertions for tests -->
            <configuration>
                <enableAssertions>true</enableAssertions>
                <systemPropertyVariables>
                    <log4j.configurationFile>src/test/resources/log4j2_for_surefire.xml</log4j.configurationFile>
                </systemPropertyVariables>
            </configuration>
        </plugin>

ContentLicense: CC BY-SA 4.0


问:
How to create a TailwindCSS grid with a dynamic amount of grid columns?
I'm using Vue3 with TailwindCSS and want to create a grid with a dynamic grid-cols-{n} class. I know that TailwindCSS supports up to 12 columns by default but I can't customize the theme because the amount of columns is completely dynamic.

Given the following plain HTML / Js example

const amountOfItemsPerRow = 16;

const container = document.getElementById("container");

for (let i = 0; i < amountOfItemsPerRow; i++) {
  const item = document.createElement("div");
  item.innerText = i;
  container.appendChild(item);
}

container.classList.add(`grid-cols-${amountOfItemsPerRow}`); // this doesn't work if the value is greater than 12```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.tailwindcss.com"></script>

<div id="container" class="grid"></div></code>```

This code works fine if amountOfItemsPerRow is smaller or equal than 12, otherwise the CSS is broken.

Do I have to write code to setup plain CSS solving this or is there a dynamic Tailwind solution?

Another approach:

Based on the docs I tried to replace the line

```<code>container.classList.add(`grid-cols-${amountOfItemsPerRow}`);
</code>```

with

```<code>container.classList.add(`grid-template-columns:repeat(${amountOfItemsPerRow},minmax(0,1fr))`);
</code>```

to come up with a "native" approach but that didn't help.

答:
Create Dynamic Class Name with Tailwindcss is easy.
Inside [ and ], You can add Dynamic Class with TailwindCSS

```<code>const amountOfRows = 16;
const amountOfCellsPerRow = 16;

const container = document.getElementById("container");

for (let rowIndex = 0; rowIndex < amountOfRows; rowIndex++) {
  for (let columnIndex = 0; columnIndex < amountOfCellsPerRow; columnIndex++) {
    const cell = document.createElement("div");
    cell.innerText = rowIndex + "|" + columnIndex;
    container.appendChild(cell);
  }
}

container.classList.add(`grid-cols-[${amountOfCellsPerRow}]`)
</code>```

For more details here

Body:
I'm using Vue3 with TailwindCSS and want to create a grid with a dynamic grid-cols-{n} class. I know that TailwindCSS supports up to 12 columns by default but I can't customize the theme because the amount of columns is completely dynamic.

Given the following plain HTML / Js example

const amountOfItemsPerRow = 16;

const container = document.getElementById("container");

for (let i = 0; i < amountOfItemsPerRow; i++) {
  const item = document.createElement("div");
  item.innerText = i;
  container.appendChild(item);
}

container.classList.add(`grid-cols-${amountOfItemsPerRow}`); // this doesn't work if the value is greater than 12

This code works fine if amountOfItemsPerRow is smaller or equal than 12, otherwise the CSS is broken.

Do I have to write code to setup plain CSS solving this or is there a dynamic Tailwind solution?

Another approach:

Based on the docs I tried to replace the line

container.classList.add(`grid-cols-${amountOfItemsPerRow}`);

with

container.classList.add(`grid-template-columns:repeat(${amountOfItemsPerRow},minmax(0,1fr))`);

to come up with a "native" approach but that didn't help.

Body:
Create Dynamic Class Name with Tailwindcss is easy.
Inside [ and ], You can add Dynamic Class with TailwindCSS

const amountOfRows = 16;
const amountOfCellsPerRow = 16;

const container = document.getElementById("container");

for (let rowIndex = 0; rowIndex < amountOfRows; rowIndex++) {
  for (let columnIndex = 0; columnIndex < amountOfCellsPerRow; columnIndex++) {
    const cell = document.createElement("div");
    cell.innerText = rowIndex + "|" + columnIndex;
    container.appendChild(cell);
  }
}

container.classList.add(`grid-cols-[${amountOfCellsPerRow}]`)

For more details here


问:
json string format done differently
I have 2 lists - dates and weekdays

```<code>>>> dates
['2022-02-08', '2022-02-09', '2022-02-10', '2022-02-11', '2022-02-12', '2022-02-13', '2022-02-14', '2022-02-15']
>>> weekdays
['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
</code>```

I want to create a json object that looks like this (for eg) for each element in dates.

```<code>myjson = {"label": "Tuesday-2022-02-08", "value": "/inform_date{\"date_list\": \"2022-02-08\"}"}
</code>```

Basically I want to run a loop where myjson looks like what is given above.

```<code>data = []
for i in range(len(dates)):
  myjson = {"label": "{0}-{1}".format(weekdays[i], dates[i]), "value": "/inform_date{\"date_list\": \"{}\"}".format(dates[i])}
  data.append(myjson)
</code>```

but I get an error when I run the above for loop.

What is the correct way to build myjson so that it looks just like shown in the example above?

Title: json string format done differently

Body:
I have 2 lists - dates and weekdays

>>> dates
['2022-02-08', '2022-02-09', '2022-02-10', '2022-02-11', '2022-02-12', '2022-02-13', '2022-02-14', '2022-02-15']
>>> weekdays
['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']

I want to create a json object that looks like this (for eg) for each element in dates.

myjson = {"label": "Tuesday-2022-02-08", "value": "/inform_date{\"date_list\": \"2022-02-08\"}"}

Basically I want to run a loop where myjson looks like what is given above.

data = []
for i in range(len(dates)):
  myjson = {"label": "{0}-{1}".format(weekdays[i], dates[i]), "value": "/inform_date{\"date_list\": \"{}\"}".format(dates[i])}
  data.append(myjson)

but I get an error when I run the above for loop.

What is the correct way to build myjson so that it looks just like shown in the example above?

Body:
Use a comprehension and f-strings:

import json

data = [{'label': f"{w}-{d}", 'value': f'/inform_date{{"date_list": "{d}"}}'}
            for d, w in zip(dates, weekdays)]
print(json.dumps(data, indent=4))

[
    {
        "label": "Tuesday-2022-02-08",
        "value": "/inform_date{\"date_list\": \"2022-02-08\"}"
    },
    {
        "label": "Wednesday-2022-02-09",
        "value": "/inform_date{\"date_list\": \"2022-02-09\"}"
    },
    {
        "label": "Thursday-2022-02-10",
        "value": "/inform_date{\"date_list\": \"2022-02-10\"}"
    },
    {
        "label": "Friday-2022-02-11",
        "value": "/inform_date{\"date_list\": \"2022-02-11\"}"
    },
    {
        "label": "Saturday-2022-02-12",
        "value": "/inform_date{\"date_list\": \"2022-02-12\"}"
    },
    {
        "label": "Sunday-2022-02-13",
        "value": "/inform_date{\"date_list\": \"2022-02-13\"}"
    },
    {
        "label": "Monday-2022-02-14",
        "value": "/inform_date{\"date_list\": \"2022-02-14\"}"
    },
    {
        "label": "Tuesday-2022-02-15",
        "value": "/inform_date{\"date_list\": \"2022-02-15\"}"
    }
]


问:
Delphi: how to identify which panel called Form2
I have 16 TPanels on Form1 and OnDblClick event they call Form2  ( form2.Show; ). working with Form2, I want to know, which of panel(TPanel name) have called Form2

PS: using Tag property can identify tag number, but I need edit1.text  to show the name of panel

答:
Several possible solutions.

One of then is to add a string property to Form2 and set the value of the panel OnDblClick event before calling Form2.Show.

Another one is the create a new function in Form2 that takes a string argument which is the panel name, save that value to a form's field and call Show. From the panel's OnDblClick, call the function instead of Show, passing the panel's name.


问:
Calculating the mean by name of a named numeric returing another named numeric as a result
I am working on a code which has a for loop. At the end of each iteration, a named numeric vector is concatenated to the one of the previous loop.

```<code>all_obj <- c()
for (i in 1:3){
  obj <- 1:3*i
  names(obj) <- c('foo', 'baz', 'bar')
  all_obj <- c(all_obj, obj)
}
</code>```

At the end, all_obj looks like this:

```<code>foo baz bar foo baz bar foo baz bar
  1   2   3   2   4   6   3   6   9
</code>```

What I would need now is to have a result which is the mean by name of this vector, and it is a named numeric itself.

Expected result

```<code>foo baz bar
  2   4   6
</code>```

I know I can get the values with name foo (for example) with all_obj[names(all_obj) == "foo"]. But I am bit stuck as to how would I reach my desired result from here without having to convert the data too much (e.g. avoiding doing as.data.frame for instance). Not that there is anything wrong with this, it's just a matter of preference and curiosity.

This was my best attempt so far.

```<code>lapply(unique(names(all_obj)), function(x) mean(all_obj[names(all_obj) == x]))
#[[1]]
#[1] 2
#
#[[2]]
#[1] 4
#
#[[3]]
#[1] 6
</code>```

答:
Sorry, this was very easy....

I am posting the solution here so that it hopefully help anyone with my same requirement.

```<code>sapply(unique(names(all_obj)), function(x) mean(all_obj[names(all_obj) == x]))
</code>```

Result

```<code>foo baz bar
  2   4   6
</code>```

Body:
I am working on a code which has a for loop. At the end of each iteration, a named numeric vector is concatenated to the one of the previous loop.

all_obj <- c()
for (i in 1:3){
  obj <- 1:3*i
  names(obj) <- c('foo', 'baz', 'bar')
  all_obj <- c(all_obj, obj)
}

At the end, all_obj looks like this:

foo baz bar foo baz bar foo baz bar
  1   2   3   2   4   6   3   6   9

What I would need now is to have a result which is the mean by name of this vector, and it is a named numeric itself.

Expected result

foo baz bar
  2   4   6

I know I can get the values with name foo (for example) with all_obj[names(all_obj) == "foo"]. But I am bit stuck as to how would I reach my desired result from here without having to convert the data too much (e.g. avoiding doing as.data.frame for instance). Not that there is anything wrong with this, it's just a matter of preference and curiosity.

This was my best attempt so far.

lapply(unique(names(all_obj)), function(x) mean(all_obj[names(all_obj) == x]))
#[[1]]
#[1] 2
#
#[[2]]
#[1] 4
#
#[[3]]
#[1] 6

Body:
Sorry, this was very easy....

I am posting the solution here so that it hopefully help anyone with my same requirement.

sapply(unique(names(all_obj)), function(x) mean(all_obj[names(all_obj) == x]))

Result

foo baz bar
  2   4   6


问:
How to filter some urls from python list?
I wrote this code for extract images urls from a web page as I given. And it shows all images urls. But I need to filter "https://images.unsplash.com/profile" urls and print them.

```<code>from bs4 import BeautifulSoup
import urllib.request
import re

url= "https://unsplash.com/t/nature"

html_page= urllib.request.urlopen(url)
soup= BeautifulSoup(html_page)
images= []
for img in soup.findAll('img'):
    images.append(img.get('src'))

print(images)
</code>```

I tried;

```<code>from bs4 import BeautifulSoup
import urllib.request
import re

url= "https://unsplash.com/t/nature"

html_page= urllib.request.urlopen(url)
soup= BeautifulSoup(html_page)
images= []
for img in soup.findAll('img'):
    images.append(img.get('src'))

if "https://images.unsplash.com/profile" in images:
    print(images)
</code>```

And didn't worked!

答:
You need to iterate through the images and then look if each of the image within images contains the required string or not.

```<code>from bs4 import BeautifulSoup
import urllib.request
import re

url= "https://unsplash.com/t/nature"

html_page= urllib.request.urlopen(url)
soup= BeautifulSoup(html_page)
images=[]
for img in soup. find_all('img'):
    images.append(img.get('src'))

for image in images:
    if "https://images.unsplash.com/profile" in image:
        print(image)

</code>```

output -

```<code>https://images.unsplash.com/profile-1544707963613-16baf868f301?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1604758536753-68fd6f23aaf7image?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1516997253075-2a25da8007e7?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1628142977790-d9f66dcbc498image?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1593541755358-41ff2a4e41efimage?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1635425197470-04119ef8fe14image?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1578469980049-1a3edf161dd6image?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1634467404821-bfebba1c1fa0image?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1604529169445-f6fb0ce4419bimage?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1557995124272-d62d831ec026?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1629238389240-a728c73e5f2e?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1557995124272-d62d831ec026?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1639922696359-2aa9a8957e24image?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1604529169445-f6fb0ce4419bimage?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1638495379168-a1d47187bac3?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1618382084065-fc61a6f289a5image?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1604529169445-f6fb0ce4419bimage?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1638257899437-e27df4493c8a?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1613909172589-d6917d507f51image?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1643893364520-052a85760bbeimage?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1613830526692-e8a5006d9b70image?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1620741299521-03deb22f2a20image?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1557995124272-d62d831ec026?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1641356925987-40e732340cc4?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1641356925987-40e732340cc4?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1582127823399-8b7c96db846eimage?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
</code>```

Body:
I wrote this code for extract images urls from a web page as I given. And it shows all images urls. But I need to filter "https://images.unsplash.com/profile" urls and print them.

from bs4 import BeautifulSoup
import urllib.request
import re

url= "https://unsplash.com/t/nature"

html_page= urllib.request.urlopen(url)
soup= BeautifulSoup(html_page)
images= []
for img in soup.findAll('img'):
    images.append(img.get('src'))

print(images)

I tried;

from bs4 import BeautifulSoup
import urllib.request
import re

url= "https://unsplash.com/t/nature"

html_page= urllib.request.urlopen(url)
soup= BeautifulSoup(html_page)
images= []
for img in soup.findAll('img'):
    images.append(img.get('src'))

if "https://images.unsplash.com/profile" in images:
    print(images)

And didn't worked!

Body:
You need to iterate through the images and then look if each of the image within images contains the required string or not.

from bs4 import BeautifulSoup
import urllib.request
import re

url= "https://unsplash.com/t/nature"

html_page= urllib.request.urlopen(url)
soup= BeautifulSoup(html_page)
images=[]
for img in soup. find_all('img'):
    images.append(img.get('src'))

for image in images:
    if "https://images.unsplash.com/profile" in image:
        print(image)

output -

https://images.unsplash.com/profile-1544707963613-16baf868f301?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1604758536753-68fd6f23aaf7image?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1516997253075-2a25da8007e7?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1628142977790-d9f66dcbc498image?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1593541755358-41ff2a4e41efimage?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1635425197470-04119ef8fe14image?auto=format&fit=crop&w=16&h=16&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1578469980049-1a3edf161dd6image?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1634467404821-bfebba1c1fa0image?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1604529169445-f6fb0ce4419bimage?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1557995124272-d62d831ec026?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1629238389240-a728c73e5f2e?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1557995124272-d62d831ec026?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1639922696359-2aa9a8957e24image?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1604529169445-f6fb0ce4419bimage?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1638495379168-a1d47187bac3?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1618382084065-fc61a6f289a5image?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1604529169445-f6fb0ce4419bimage?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1638257899437-e27df4493c8a?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1613909172589-d6917d507f51image?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1643893364520-052a85760bbeimage?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1613830526692-e8a5006d9b70image?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1620741299521-03deb22f2a20image?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1557995124272-d62d831ec026?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1641356925987-40e732340cc4?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1641356925987-40e732340cc4?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff
https://images.unsplash.com/profile-1582127823399-8b7c96db846eimage?auto=format&fit=crop&w=32&h=32&q=60&crop=faces&bg=fff


问:
Django-Debug-Toolbar is not showing
I am building BlogApp and I am trying to run Django-Debug-Toolbar BUT it is not showing. I have seen many answers BUT nothing worked for me.

I have installed it correctly according to the Documentation

I have added in installed apps , middlewares and urls and also collecstatic. BUT still not showing when i go to Browser.

settings.py

```<code>if DEBUG:
    MIDDLEWARE += [
        'debug_toolbar.middleware.DebugToolbarMiddleware',
    ]
    INSTALLED_APPS += [
        'debug_toolbar',
    ]
    INTERNAL_IPS = ['127.0.0.1', ]

    # this is the main reason for not showing up the toolbar
    import mimetypes
    mimetypes.add_type("application/javascript", ".js", True)

    DEBUG_TOOLBAR_CONFIG = {
        'INTERCEPT_REDIRECTS': False,
    }
</code>```

urls.py

```<code>if settings.DEBUG:
    import debug_toolbar
    urlpatterns += [
        path('__debug__/', include(debug_toolbar.urls)),
    ]
</code>```

Any help would be Appreciated.

Thank You in Advance

答:
I had the same issue with application django debug toolbar
In settings.py, everything is correctly, but the application did not showing in the browser.
If you look by the inspect mode, you could see a javascript error because he sees it as text and not as js code.

Solution:
In the registry Editor ("Ctrl+r" "regedit") find HKEY_CLASSES_ROOT.js
then dubble click on the "Content Type" the "Value data" should be "text/javascript"

Then restart server "python manage.py runserver", remove cookies of your browser and that's all.
At the worst restart your machine.

Title: Django-Debug-Toolbar is not showing

Body:
I am building BlogApp and I am trying to run Django-Debug-Toolbar BUT it is not showing. I have seen many answers BUT nothing worked for me.

I have installed it correctly according to the Documentation

I have added in installed apps , middlewares and urls and also collecstatic. BUT still not showing when i go to Browser.

settings.py

if DEBUG:
    MIDDLEWARE += [
        'debug_toolbar.middleware.DebugToolbarMiddleware',
    ]
    INSTALLED_APPS += [
        'debug_toolbar',
    ]
    INTERNAL_IPS = ['127.0.0.1', ]

    # this is the main reason for not showing up the toolbar
    import mimetypes
    mimetypes.add_type("application/javascript", ".js", True)

    DEBUG_TOOLBAR_CONFIG = {
        'INTERCEPT_REDIRECTS': False,
    }

urls.py

if settings.DEBUG:
    import debug_toolbar
    urlpatterns += [
        path('__debug__/', include(debug_toolbar.urls)),
    ]

Any help would be Appreciated.

Thank You in Advance


问:
Add/remove textbox value when checkbox change
I have the following jquery code where i want to remove the value from the textfield if the checkbox is unchecked and add if it is checked.

initially all the values comes in the textbox as the ^ seperator. and all checkboxes checked

here is y piece of code:

```<code>$(document).on('change','._invoice',function() {
    var mystr = $(this).attr('data-id').is(":checked");
    if(mystr) {
        var returnVal = confirm("Are you sure?");
        $(this).attr("checked", returnVal);
    }
    });
});
</code>```

Text field values and i also want to remove the separator and add the name at the last with ^ as separator.

```<code>Robert Berenson^Nancy Foster^Richard Gourhan^LORI HEDMAN^Pui Hoang^Linda Lee^Kristen McDonald^Matthew Miller^Tricia Roland^Terry West
</code>```

答:
var txt = document.getElementById( 'droptxt' ),
            content = document.getElementById( 'content' ),
            list = document.querySelectorAll( '.content input[type="checkbox"]' ),
            quantity = document.querySelectorAll( '.quantity' );
        txt.addEventListener( 'click', function() {
            content.classList.toggle( 'show' )
        } )

        window.onclick = function( e ) {
            if ( !e.target.matches( '.list' ) ) {
                if ( content.classList.contains( 'show' ) ) content.classList.remove( 'show' )
            }
        }

        list.forEach( function( item, index ) {
            item.addEventListener( 'click', function() {
                calc()
            } )
        } )

        function calc() {
            for ( var i = 0, arr = []; i < list.length; i++ ) {
            let spanArray = [];
            document.querySelectorAll('span').forEach(element => {
                spanArray.push(element.innerHTML);
            });

                if ( list[ i ].checked ) arr.push( list[ i ].value + " "+ spanArray)
            }
            txt.value = arr.join(', ')
        }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h1 {
            color: #0000ff;
        }
        #droptxt {
            padding: 8px;
            width: 300px;
            cursor: pointer;
            box-sizing: border-box
        }
        .dropdown {
            position: relative;
            display: inline-block
        }
        .content {
            display: none;
            position: absolute;
            background-color: #f1f1f1;
            min-width: 200px;
            overflow: auto;
            box-shadow: 0 8px 16px 0 rgba(0, 0, 0, .2);
            z-index: 1
        }
        .content div {
            padding: 10px 15px
        }
        .content div:hover {
            background-color: #ddd
        }
        .show {
            display: block
        }</code>```

KIAAT

    Adding/Removing Checkbox Values into TextArea

    <input type="text" id="droptxt" class="list" placeholder="Select the values" readonly>

            <input type="checkbox" id="market" class="list" value="apple" /> Apple

            <input type="checkbox" id="banana" class="list" value="Banana" /> Banana

            <input type="checkbox" id="pineapple" class="list" value="Pineapple" /> Pineapple

```

Body:
I have the following jquery code where i want to remove the value from the textfield if the checkbox is unchecked and add if it is checked.

initially all the values comes in the textbox as the ^ seperator. and all checkboxes checked

here is y piece of code:

$(document).on('change','._invoice',function() {
    var mystr = $(this).attr('data-id').is(":checked");
    if(mystr) {
        var returnVal = confirm("Are you sure?");
        $(this).attr("checked", returnVal);
    }
    });
});

Text field values and i also want to remove the separator and add the name at the last with ^ as separator.

Robert Berenson^Nancy Foster^Richard Gourhan^LORI HEDMAN^Pui Hoang^Linda Lee^Kristen McDonald^Matthew Miller^Tricia Roland^Terry West

Body:
var txt = document.getElementById( 'droptxt' ),
            content = document.getElementById( 'content' ),
            list = document.querySelectorAll( '.content input[type="checkbox"]' ),
            quantity = document.querySelectorAll( '.quantity' );
        txt.addEventListener( 'click', function() {
            content.classList.toggle( 'show' )
        } )

        window.onclick = function( e ) {
            if ( !e.target.matches( '.list' ) ) {
                if ( content.classList.contains( 'show' ) ) content.classList.remove( 'show' )
            }
        }

        list.forEach( function( item, index ) {
            item.addEventListener( 'click', function() {
                calc()
            } )
        } )

        function calc() {
            for ( var i = 0, arr = []; i < list.length; i++ ) {
            let spanArray = [];
            document.querySelectorAll('span').forEach(element => {
                spanArray.push(element.innerHTML);
            });

                if ( list[ i ].checked ) arr.push( list[ i ].value + " "+ spanArray)
            }
            txt.value = arr.join(', ')
        }

h1 {
            color: #0000ff;
        }
        #droptxt {
            padding: 8px;
            width: 300px;
            cursor: pointer;
            box-sizing: border-box
        }
        .dropdown {
            position: relative;
            display: inline-block
        }
        .content {
            display: none;
            position: absolute;
            background-color: #f1f1f1;
            min-width: 200px;
            overflow: auto;
            box-shadow: 0 8px 16px 0 rgba(0, 0, 0, .2);
            z-index: 1
        }
        .content div {
            padding: 10px 15px
        }
        .content div:hover {
            background-color: #ddd
        }
        .show {
            display: block
        }

<h1>KIAAT</h1>
    <b>Adding/Removing Checkbox Values into TextArea</b>
    <br><br>
    <input type="text" id="droptxt" class="list" placeholder="Select the values" readonly>
        <div id="content" class="content">
            <div id="market" class="list">
            <label><input type="checkbox" id="market" class="list" value="apple" /> Apple</label>
            </div>

            <div class="list">
            <label><input type="checkbox" id="banana" class="list" value="Banana" /> Banana</label>
            </div>

            <div class="list">
            <label><input type="checkbox" id="pineapple" class="list" value="Pineapple" /> Pineapple</label>
            </div>
        </div>


问:
How to avoid many database round trips and a lot of irrelevant data?
I have worked with various applications and encountered this situation many times. Until now I have not figured out what is the best approach.

Here's the scenario:

I have an application either desktop or web

I need to retrieve simple documents from the database. The document has a general details and item details so the database:

GeneralDetails table:

```<code>| DocumentID | DateCreated | Owner     |
| 1          | 07/07/07    | Naruto    |
| 2          | 08/08/08    | Goku      |
| 3          | 09/09/09    | Taguro    |
</code>```

ItemDetails table

```<code>| DocumentID | Item        | Quantity  |
| 1          | Marbles     | 20        |
| 1          | Cards       | 56        |
| 2          | Yo-yo       | 1         |
| 2          | Chess board | 3         |
| 2          | GI Joe      | 12        |
| 3          | Rubber Duck | 1         |
</code>```

As you can see, the tables have a one-to-many relationship. Now, in order to retrieve all the documents and their respective items, I always do either of the two:

Method 1 - Many round trips (pseudo-code):

```<code> Documents = GetFromDB("select DocumentID, Owner " +
                       "from GeneralDetails")
 For Each Document in Documents
{
    Display(Document["CreatedBy"])
    DocumentItems = GetFromDB("select Item, Quantity " +
                              "from ItemDetails " +
                              "where DocumentID = " + Document["DocumentID"] + "")
    For Each DocumentItem in DocumentItems
    {
        Display(DocumentItem["Item"] + " " + DocumentItem["Quantity"])
    }
}
</code>```

Method 2 - Much irrelevant data (pseudo-code):

```<code>DocumentsAndItems = GetFromDB("select g.DocumentID, g.Owner, i.Item, i.Quantity " +
                              "from GeneralDetails as g " +
                              "inner join ItemDetails as i " +
                              "on g.DocumentID = i.DocumentID")
//Display...
</code>```

I used the first method when I was in college for desktop applications, the performance was not bad so I realized it was okay.

Until one day, I saw an article "Make the web faster", it says that many round trips to the database is bad; so ever since then I have used the second method.

On the second method, I avoided round trips by using inner join to retrieve the first and the second table at once, but it produces unecessary or redundant data. See the result set.

```<code>| DocumentID | Owner     | Item        | Quantity  |
| 1          | Naruto    | Marbles     | 20        |
| 1          | Naruto    | Cards       | 56        |
| 2          | Goku      | Yo-yo       | 1         |
| 2          | Goku      | Chess board | 3         |
| 2          | Goku      | GI Joe      | 12        |
| 3          | Taguro    | Rubber Duck | 1         |
</code>```

The result set has redundant DocumentID and Owner. It looks like an unnormalized database.

Now, the question is, how do I avoid round trips and at the same time avoid redundant data?

答:
The method used by ActiveRecord and other ORMs is to select the first table, batch together the IDs and then use those IDs in an IN clause for the second select.

SELECT * FROM ItemDetails WHERE DocumentId IN ( [Comma Separated List of IDs here] )

Advantages:

No redundant data

Disadvantages:

Two queries

Generally speaking, the first method is referred to as the "N+1 query problem" and the solutions are referred to as "eager loading". I tend to see your "Method 2" as preferable as the latency to the database generally trumps the size of the redundant data over the data transfer rate, but YRMV. As with almost everything in software, it's a tradeoff.

Body:
I have worked with various applications and encountered this situation many times. Until now I have not figured out what is the best approach.

Here's the scenario:

I have an application either desktop or web

I need to retrieve simple documents from the database. The document has a general details and item details so the database:

GeneralDetails table:

| DocumentID | DateCreated | Owner     |
| 1          | 07/07/07    | Naruto    |
| 2          | 08/08/08    | Goku      |
| 3          | 09/09/09    | Taguro    |

ItemDetails table

| DocumentID | Item        | Quantity  |
| 1          | Marbles     | 20        |
| 1          | Cards       | 56        |
| 2          | Yo-yo       | 1         |
| 2          | Chess board | 3         |
| 2          | GI Joe      | 12        |
| 3          | Rubber Duck | 1         |

As you can see, the tables have a one-to-many relationship. Now, in order to retrieve all the documents and their respective items, I always do either of the two:

Method 1 - Many round trips (pseudo-code):

 Documents = GetFromDB("select DocumentID, Owner " +
                       "from GeneralDetails")
 For Each Document in Documents
{
    Display(Document["CreatedBy"])
    DocumentItems = GetFromDB("select Item, Quantity " +
                              "from ItemDetails " +
                              "where DocumentID = " + Document["DocumentID"] + "")
    For Each DocumentItem in DocumentItems
    {
        Display(DocumentItem["Item"] + " " + DocumentItem["Quantity"])
    }
}

Method 2 - Much irrelevant data (pseudo-code):

DocumentsAndItems = GetFromDB("select g.DocumentID, g.Owner, i.Item, i.Quantity " +
                              "from GeneralDetails as g " +
                              "inner join ItemDetails as i " +
                              "on g.DocumentID = i.DocumentID")
//Display...

I used the first method when I was in college for desktop applications, the performance was not bad so I realized it was okay.

Until one day, I saw an article "Make the web faster", it says that many round trips to the database is bad; so ever since then I have used the second method.

On the second method, I avoided round trips by using inner join to retrieve the first and the second table at once, but it produces unecessary or redundant data. See the result set.

| DocumentID | Owner     | Item        | Quantity  |
| 1          | Naruto    | Marbles     | 20        |
| 1          | Naruto    | Cards       | 56        |
| 2          | Goku      | Yo-yo       | 1         |
| 2          | Goku      | Chess board | 3         |
| 2          | Goku      | GI Joe      | 12        |
| 3          | Taguro    | Rubber Duck | 1         |

The result set has redundant DocumentID and Owner. It looks like an unnormalized database.

Now, the question is, how do I avoid round trips and at the same time avoid redundant data?


问:
H2 Database result set is readonly
I'm getting the SQLNonTransientException error when trying to update one of my rows in a H2 database.

```<code>public static void setNewServiceInformationsToShown() {
    try (Connection conn = DriverManager.getConnection("jdbc:h2:" + Main.config_db_location,
            Main.config_db_username, Main.config_db_password)) {
        //read data from database
        PreparedStatement stmt = conn.prepareStatement("SELECT * FROM BCSTASKS_SERVICE");

        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            if(rs.getString("Status").equals("Neu") && rs.getBoolean("wasShown") == false) {
                rs.updateBoolean("WASSHOWN", true);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
</code>```

The error message already suggests that I should use conn.createStatement and set the ResultSet to CONCUR_UPDATABLE. The error occurs at the line with rs.updateBoolean(...);

Error Message:

The result set is readonly. You may need to use conn.createStatement(.., ResultSet.CONCUR_UPDATABLE). [90140-210]

The problem is I don't know where and how I should use this method. In the same function or at the start of the program?

答:
Most DB code I see doesn't attempt to use the fact that resultsets are updatable, and will instead fire off an additional UPDATE query, which works fine.

However, sure, H2 supports updateable resultsets too. However, some of the features that ResultSets have actually have quite a cost; the DB engine needs to do a boatload of additional bookkeeping to enable such features which have a performance cost. Lots of database queries are extremely performance sensitive, so by default you do not get the bookkeeping and therefore these features do not work. You need to enable them explicitly, that's what the error is telling you.

You're currently calling the 'wrong' preparedStatement method. You want the more extended one, where you pick and choose which additional bookkeeping you want H2 to do for you, in order to enable these things. You want this one.

conn.prepareStatement(
  "SELECT * FROM BCSTASKS_SERVICE",
  ResultSet.TYPE_SCROLL_INSENSITIVE, // [edited]
  ResultSet.CONCUR_UPDATABLE);
```

That CONCUR_UPDATABLE thing is just a flag you pass to say: Please do the bookkeeping so that I can call .update.

[edited] This used to read 0 before, but as @MarkRotteveel pointed out, that's not valid according to the documentation.

Title: H2 Database result set is readonly

Body:
I'm getting the SQLNonTransientException error when trying to update one of my rows in a H2 database.

public static void setNewServiceInformationsToShown() {
    try (Connection conn = DriverManager.getConnection("jdbc:h2:" + Main.config_db_location,
            Main.config_db_username, Main.config_db_password)) {
        //read data from database
        PreparedStatement stmt = conn.prepareStatement("SELECT * FROM BCSTASKS_SERVICE");

        ResultSet rs = stmt.executeQuery();
        while (rs.next()) {
            if(rs.getString("Status").equals("Neu") && rs.getBoolean("wasShown") == false) {
                rs.updateBoolean("WASSHOWN", true);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

The error message already suggests that I should use conn.createStatement and set the ResultSet to CONCUR_UPDATABLE. The error occurs at the line with rs.updateBoolean(...);

Error Message:

The result set is readonly. You may need to use conn.createStatement(.., ResultSet.CONCUR_UPDATABLE). [90140-210]

The problem is I don't know where and how I should use this method. In the same function or at the start of the program?

Body:
Most DB code I see doesn't attempt to use the fact that resultsets are updatable, and will instead fire off an additional UPDATE query, which works fine.

However, sure, H2 supports updateable resultsets too. However, some of the features that ResultSets have actually have quite a cost; the DB engine needs to do a boatload of additional bookkeeping to enable such features which have a performance cost. Lots of database queries are extremely performance sensitive, so by default you do not get the bookkeeping and therefore these features do not work. You need to enable them explicitly, that's what the error is telling you.

You're currently calling the 'wrong' preparedStatement method. You want the more extended one, where you pick and choose which additional bookkeeping you want H2 to do for you, in order to enable these things. You want this one.

conn.prepareStatement(
  "SELECT * FROM BCSTASKS_SERVICE",
  ResultSet.TYPE_SCROLL_INSENSITIVE, // [edited]
  ResultSet.CONCUR_UPDATABLE);

That CONCUR_UPDATABLE thing is just a flag you pass to say: Please do the bookkeeping so that I can call .update.

[edited] This used to read 0 before, but as @MarkRotteveel pointed out, that's not valid according to the documentation.


问:
colab keeps on crashing after using the 'GLOBAL' keyword
I copied this program from stackoverflow and added the global keyword to know the length of the list and it crashed because the ram is full.Why?If I removed the Global key word it works fine.I just wanted to know why it keeps on crashing</p>
```<code>def permutation(s):
    if len(s) == 1:
        return [s]
    global per_list
    per_list = []
    for i in s:
        rm = [x for x in s if x != i]
        ff = permutation(rm)
        for j in ff:
            per_list.append([i] + j)
    return per_list

s = [3,4,5]
permutation(s)
print(len(per_list))
</code>```

答:
Declare it as empty list outside the function first and try again.</p>
```<code>// like this
per_list = []

def permutation(s):
    //body

s = [3,4,5]
permutation(s)
print(len(per_list))
</code>```

Body:
I copied this program from stackoverflow and added the global keyword to know the length of the list and it crashed because the ram is full.Why?If I removed the Global key word it works fine.I just wanted to know why it keeps on crashing

def permutation(s):
    if len(s) == 1:
        return [s]
    global per_list
    per_list = []
    for i in s:
        rm = [x for x in s if x != i]
        ff = permutation(rm)
        for j in ff:
            per_list.append([i] + j)
    return per_list

s = [3,4,5]
permutation(s)
print(len(per_list))

Body:
Declare it as empty list outside the function first and try again.

// like this
per_list = []

def permutation(s):
    //body

s = [3,4,5]
permutation(s)
print(len(per_list))


问:
Getting some erros when building GridView
I have been recently getting this errors in my GridView, but only when running it on Real Devices(Happens with Android and iPhone devices).

Errors:

```<code>════════ Exception caught by rendering library ═════════════════════════════════
The following assertion was thrown during performLayout():
Leading widget consumes entire tile width. Please use a sized widget, or consider replacing ListTile with a custom widget (see https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4)
'package:flutter/src/material/list_tile.dart':
Failed assertion: line 1722 pos 7: 'tileWidth != leadingSize.width || tileWidth == 0.0'

Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
  https://github.com/flutter/flutter/issues/new?template=2_bug.md

The relevant error-causing widget was
ListTile
When the exception was thrown, this was the stack
#2      _RenderListTile.performLayout
#3      RenderObject.layout
#4      RenderPadding.performLayout
#5      RenderObject.layout
#6      RenderPadding.performLayout
...
The following RenderObject was being processed when the exception was fired: _RenderListTile#3da4d NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
RenderObject: _RenderListTile#3da4d NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    parentData: offset=Offset(0.0, 0.0) (can use size)
    constraints: BoxConstraints(w=68.0, h=54.7)
    size: MISSING
    leading: RenderParagraph#bed81 relayoutBoundary=up1 NEEDS-PAINT
        parentData: offset=Offset(0.0, 0.0) (can use size)
        constraints: BoxConstraints(0.0<=w<=68.0, 0.0<=h<=54.7)
        size: Size(68.0, 32.0)
        textAlign: center
        textDirection: ltr
        softWrap: wrapping at box width
        overflow: clip
        locale: en_US
        maxLines: unlimited
        text: TextSpan
            debugLabel: ((englishLike body1 2014).merge(blackMountainView bodyText2)).copyWith
            inherit: false
            color: Color(0xdd000000)
            family: Roboto
            size: 14.0
            weight: 400
            baseline: alphabetic
            decoration: TextDecoration.none
            "No parking spot"
    title: RenderConstrainedBox#fbbdc NEEDS-LAYOUT NEEDS-PAINT
        parentData: offset=Offset(0.0, 0.0)
        constraints: MISSING
        size: MISSING
        additionalConstraints: BoxConstraints(unconstrained)
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: _RenderListTile#3da4d NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPadding#0b1e1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPadding#0be47 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#459a2 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPointerListener#91e94 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#c896d NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderMouseRegion#0b93c NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#16727 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'No parking spot'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#55a96 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'No parking spot'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: _RenderInkFeatures#3a146 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'No parking spot'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderCustomPaint#0921c NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'No parking spot'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPhysicalShape#377a7 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'No parking spot'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPadding#4b4f6 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'No parking spot'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#00a52 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
GridView
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderRepaintBoundary#b4962 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
GridView
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
Leading widget consumes entire tile width. Please use a sized widget, or consider replacing ListTile with a custom widget (see https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4)
'package:flutter/src/material/list_tile.dart':
Failed assertion: line 1722 pos 7: 'tileWidth != leadingSize.width || tileWidth == 0.0'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: _RenderListTile#d708a NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPadding#b33e9 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPadding#a83e1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#96675 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPointerListener#d189c NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#1e85d NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderMouseRegion#ec538 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#31b1d NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'More Than 5 Totes'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#d4c29 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'More Than 5 Totes'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: _RenderInkFeatures#d2bdf NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'More Than 5 Totes'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderCustomPaint#c0642 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'More Than 5 Totes'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPhysicalShape#c75f1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'More Than 5 Totes'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPadding#44309 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'More Than 5 Totes'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#0cbe8 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
GridView
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderRepaintBoundary#e40ed NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
GridView
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 544 pos 12: 'child.hasSize': is not true.
The relevant error-causing widget was
GridView
════════════════════════════════════════════════════════════════════════════════
</code>```

This the code where I am building this GridView.

```<code>Widget build(BuildContext context) {
return Column(children: [
  Expanded(
    child: GridView.builder(
      //physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      //scrollDirection: Axis.vertical,
      itemCount: 6,
      gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        childAspectRatio: MediaQuery.of(context).size.width /
            (MediaQuery.of(context).size.height / 3),
      ),
      itemBuilder: (BuildContext context, int index) {
        return Card(
            key: ValueKey(options[index].description),
            margin: const EdgeInsets.all(10),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10)),

            // The color depends on this is selected or not
            color: options[index].isSelected == true
                ? Colors.amber
                : Colors.white,
            child: ListTile(
              onTap: () {
                // if this item isn't selected yet, "isSelected": false -> true
                // If this item already is selected: "isSelected": true -> false
                setState(() {
                  options[index].isSelected = !options[index].isSelected;
                  //selectedItems[index] = options[index].description;
                  selectedItems[index] = options[index].description;
                });
              },
              leading: Text(
                options[index].description.toString(),
                textAlign: TextAlign.center,
              ),
              /*title: Text(
            options[index].description,
                        ),*/
            ));
      },
    ),
  ),
  ElevatedButton(
    //onPressed: () => insertText('Drop \n', textController),
    //onPressed: () => showModalOptions(context),
    onPressed: () => {
      InsertText().insertText(
          'Drop Number: ' + widget.dropsController.text + '\n',
          widget.textController),
      for (var i = 0; i < selectedItems.length; i++)
        {
          if (selectedItems[i].isNotEmpty)
            if (i == 0)
              {
                InsertText().insertText(
                    selectedItems[i] + ' + ', widget.textController),
              }
            else if (i != selectedItems.length)
              {
                InsertText().insertText(
                    selectedItems[i] + ' ', widget.textController)
              }
        },
      setState(() {
        for (var i = 0; i < options.length; i++) {
          options[i].isSelected = false;
          selectedItems[i] = '';
        }
      })
    },
    child: Text('Add Drop'),
  ),
]);
</code>```

This is where I am calling on Main.dart

```<code>  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 2,
        child: Scaffold(
          appBar: AppBar(
            title: Text('Driver Notes'),
            bottom: TabBar(
              tabs: [
                Icon(Icons.notes),
                Icon(Icons.ac_unit),
              ],
            ),
          ),
          body: TabBarView(children: [
            // Action Tab
            Column(
              children: [
                Row(children: [
                  Container(
                    child: SizedBox(
                      width: 150,
                      child: TextField(
                        decoration: InputDecoration(labelText: 'Starting Date'),
                        controller: startDate,
                        onTap: _startDatePicker,
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 150,
                    child: TextField(
                      decoration: InputDecoration(labelText: 'Starting Time'),
                      controller: startTime,
                      onTap: _startTimePicker,
                    ),
                  ),
                ]),
                Row(children: [
                  SizedBox(
                    width: 150,
                    child: TextField(
                      decoration: InputDecoration(labelText: 'Finising Date'),
                      controller: finishDate,
                      onTap: _finishDatePicker,
                    ),
                  ),
                  SizedBox(
                    width: 150,
                    child: TextField(
                      decoration: InputDecoration(labelText: 'Finising Time'),
                      controller: finishTime,
                      onTap: _finishTimePicker,
                    ),
                  ),
                ]),
                TextField(
                  decoration: InputDecoration(labelText: 'Drop Number'),
                  keyboardType: TextInputType.number,
                  controller: dropController,
                ),
                Expanded(
                  child: ReasonSelection(textController, dropController),
                ),

              ],
            ),
            // Result Tab
            NotesTab(
                textController, startDate, startTime, finishDate, finishTime),
          ]),
        ),
      ),
    );
  }
}
</code>```

Running on Android emulator:

I have tried some solutions like using Expanded, SizedBox, setting shrinkWrap to true, no sucess until now.
Any idea of what is happening or how to fix it?

Thanks.

答: I think you can use CustomScrollView and add slivers for this case

Body:
I have been recently getting this errors in my GridView, but only when running it on Real Devices(Happens with Android and iPhone devices).

Errors:

════════ Exception caught by rendering library ═════════════════════════════════
The following assertion was thrown during performLayout():
Leading widget consumes entire tile width. Please use a sized widget, or consider replacing ListTile with a custom widget (see https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4)
'package:flutter/src/material/list_tile.dart':
Failed assertion: line 1722 pos 7: 'tileWidth != leadingSize.width || tileWidth == 0.0'

Either the assertion indicates an error in the framework itself, or we should provide substantially more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
  https://github.com/flutter/flutter/issues/new?template=2_bug.md

The relevant error-causing widget was
ListTile
When the exception was thrown, this was the stack
#2      _RenderListTile.performLayout
#3      RenderObject.layout
#4      RenderPadding.performLayout
#5      RenderObject.layout
#6      RenderPadding.performLayout
...
The following RenderObject was being processed when the exception was fired: _RenderListTile#3da4d NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
RenderObject: _RenderListTile#3da4d NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
    parentData: offset=Offset(0.0, 0.0) (can use size)
    constraints: BoxConstraints(w=68.0, h=54.7)
    size: MISSING
    leading: RenderParagraph#bed81 relayoutBoundary=up1 NEEDS-PAINT
        parentData: offset=Offset(0.0, 0.0) (can use size)
        constraints: BoxConstraints(0.0<=w<=68.0, 0.0<=h<=54.7)
        size: Size(68.0, 32.0)
        textAlign: center
        textDirection: ltr
        softWrap: wrapping at box width
        overflow: clip
        locale: en_US
        maxLines: unlimited
        text: TextSpan
            debugLabel: ((englishLike body1 2014).merge(blackMountainView bodyText2)).copyWith
            inherit: false
            color: Color(0xdd000000)
            family: Roboto
            size: 14.0
            weight: 400
            baseline: alphabetic
            decoration: TextDecoration.none
            "No parking spot"
    title: RenderConstrainedBox#fbbdc NEEDS-LAYOUT NEEDS-PAINT
        parentData: offset=Offset(0.0, 0.0)
        constraints: MISSING
        size: MISSING
        additionalConstraints: BoxConstraints(unconstrained)
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: _RenderListTile#3da4d NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPadding#0b1e1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPadding#0be47 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#459a2 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPointerListener#91e94 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#c896d NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderMouseRegion#0b93c NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#16727 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'No parking spot'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#55a96 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'No parking spot'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: _RenderInkFeatures#3a146 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'No parking spot'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderCustomPaint#0921c NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'No parking spot'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPhysicalShape#377a7 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'No parking spot'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPadding#4b4f6 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'No parking spot'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#00a52 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
GridView
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderRepaintBoundary#b4962 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
GridView
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
Leading widget consumes entire tile width. Please use a sized widget, or consider replacing ListTile with a custom widget (see https://api.flutter.dev/flutter/material/ListTile-class.html#material.ListTile.4)
'package:flutter/src/material/list_tile.dart':
Failed assertion: line 1722 pos 7: 'tileWidth != leadingSize.width || tileWidth == 0.0'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: _RenderListTile#d708a NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPadding#b33e9 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPadding#a83e1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#96675 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPointerListener#d189c NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#1e85d NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderMouseRegion#ec538 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
ListTile
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#31b1d NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'More Than 5 Totes'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#d4c29 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'More Than 5 Totes'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: _RenderInkFeatures#d2bdf NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'More Than 5 Totes'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderCustomPaint#c0642 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'More Than 5 Totes'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPhysicalShape#c75f1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'More Than 5 Totes'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderPadding#44309 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
Card-[<'More Than 5 Totes'>]
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderSemanticsAnnotations#0cbe8 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
GridView
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderRepaintBoundary#e40ed NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1930 pos 12: 'hasSize'

The relevant error-causing widget was
GridView
════════════════════════════════════════════════════════════════════════════════

════════ Exception caught by rendering library ═════════════════════════════════
'package:flutter/src/rendering/sliver_multi_box_adaptor.dart': Failed assertion: line 544 pos 12: 'child.hasSize': is not true.
The relevant error-causing widget was
GridView
════════════════════════════════════════════════════════════════════════════════

This the code where I am building this GridView.

Widget build(BuildContext context) {
return Column(children: [
  Expanded(
    child: GridView.builder(
      //physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      //scrollDirection: Axis.vertical,
      itemCount: 6,
      gridDelegate: new SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        childAspectRatio: MediaQuery.of(context).size.width /
            (MediaQuery.of(context).size.height / 3),
      ),
      itemBuilder: (BuildContext context, int index) {
        return Card(
            key: ValueKey(options[index].description),
            margin: const EdgeInsets.all(10),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10)),

            // The color depends on this is selected or not
            color: options[index].isSelected == true
                ? Colors.amber
                : Colors.white,
            child: ListTile(
              onTap: () {
                // if this item isn't selected yet, "isSelected": false -> true
                // If this item already is selected: "isSelected": true -> false
                setState(() {
                  options[index].isSelected = !options[index].isSelected;
                  //selectedItems[index] = options[index].description;
                  selectedItems[index] = options[index].description;
                });
              },
              leading: Text(
                options[index].description.toString(),
                textAlign: TextAlign.center,
              ),
              /*title: Text(
            options[index].description,
                        ),*/
            ));
      },
    ),
  ),
  ElevatedButton(
    //onPressed: () => insertText('Drop \n', textController),
    //onPressed: () => showModalOptions(context),
    onPressed: () => {
      InsertText().insertText(
          'Drop Number: ' + widget.dropsController.text + '\n',
          widget.textController),
      for (var i = 0; i < selectedItems.length; i++)
        {
          if (selectedItems[i].isNotEmpty)
            if (i == 0)
              {
                InsertText().insertText(
                    selectedItems[i] + ' + ', widget.textController),
              }
            else if (i != selectedItems.length)
              {
                InsertText().insertText(
                    selectedItems[i] + ' ', widget.textController)
              }
        },
      setState(() {
        for (var i = 0; i < options.length; i++) {
          options[i].isSelected = false;
          selectedItems[i] = '';
        }
      })
    },
    child: Text('Add Drop'),
  ),
]);

This is where I am calling on Main.dart

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 2,
        child: Scaffold(
          appBar: AppBar(
            title: Text('Driver Notes'),
            bottom: TabBar(
              tabs: [
                Icon(Icons.notes),
                Icon(Icons.ac_unit),
              ],
            ),
          ),
          body: TabBarView(children: [
            // Action Tab
            Column(
              children: [
                Row(children: [
                  Container(
                    child: SizedBox(
                      width: 150,
                      child: TextField(
                        decoration: InputDecoration(labelText: 'Starting Date'),
                        controller: startDate,
                        onTap: _startDatePicker,
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 150,
                    child: TextField(
                      decoration: InputDecoration(labelText: 'Starting Time'),
                      controller: startTime,
                      onTap: _startTimePicker,
                    ),
                  ),
                ]),
                Row(children: [
                  SizedBox(
                    width: 150,
                    child: TextField(
                      decoration: InputDecoration(labelText: 'Finising Date'),
                      controller: finishDate,
                      onTap: _finishDatePicker,
                    ),
                  ),
                  SizedBox(
                    width: 150,
                    child: TextField(
                      decoration: InputDecoration(labelText: 'Finising Time'),
                      controller: finishTime,
                      onTap: _finishTimePicker,
                    ),
                  ),
                ]),
                TextField(
                  decoration: InputDecoration(labelText: 'Drop Number'),
                  keyboardType: TextInputType.number,
                  controller: dropController,
                ),
                Expanded(
                  child: ReasonSelection(textController, dropController),
                ),

              ],
            ),
            // Result Tab
            NotesTab(
                textController, startDate, startTime, finishDate, finishTime),
          ]),
        ),
      ),
    );
  }
}

Running on Android emulator:

I have tried some solutions like using Expanded, SizedBox, setting shrinkWrap to true, no sucess until now.
Any idea of what is happening or how to fix it?

Thanks.