问:
How does shared_ptr call the right destructor when make_shared is used to construct it?
```<code>struct Base{};
struct Derived : Base {};

std::shared_ptr<Base> sp(new Derived);
</code>```

So the explanation is that sp knows that it needs to call the destructor of Derived because Derived argument was passed in the constructor. However in this case of creating a shared pointer with make_shared you don't supply the pointer, and so it can't know the Derived type. Does this mean that the correct behaviour of having a shared_ptr pointing to a Derived can only work in the case of supplying your own pointer to the constructor, not in make_shared?

答:
shared_ptr "knows" which destructor to call because the type of the originally owned object is recorded at the point of shared_ptr construction.

In the case of constructing shared_ptr from a raw pointer:

```<code>std::shared_ptr<Base> sp(new Derived);
</code>```

shared_ptr constructor internally creates an object that, among other things, stores the original pointer to Derived and an associated deleter that will be called on the pointer when the last shared_ptr referencing that object is destroyed. This internal pointer to Derived is separate from the pointer that is exposed through shared_ptr interface methods, such as get or operator->, and it stays intact for the whole lifetime of the referenced Derived object. The exposed pointer may change by constructing different shared_ptr instances, and in some cases may not even point to the Derived object at all. This is why although std::shared_ptr<Base> exposes the pointer to Base, it is still able to destroy the original Derived in the end.

The case with make_shared is similar:

```<code>std::shared_ptr<Base> sp = std::make_shared<Derived>();
</code>```

Here, Derived object creation and shared_ptr initialization happens within make_shared. Simplistically, you could think of make_shared like this:

```<code>template< typename T >
std::shared_ptr<T> make_shared()
{
    std::shared_ptr<T> internal_sp(new T());
    return internal_sp;
}
</code>```

(I'm intentionally simplifying make_shared implementation here.)

So, in make_shared, when internal_sp is initialized, it records the object type with the associated deleter just as explained above. When sp is initialized from the result of make_shared, it simply inherits the deleter and the original pointer, and converts the exposed pointer from Derived* to Base*.

This feature of shared_ptr is key to its many other useful capabilities, such as:

Hiding the deleter type from the shared_ptr type. For example, shared_ptr<FILE> spf(fopen("foo.txt", "r"), &fclose).

Flexibility in pointer conversions. For example, as noted in the comments, shared_ptr<void> spv = sp is valid, and spv will still be able to destroy Derived object as expected.

Pointer aliasing, when the exposed pointer is pointing to a different object than the one that was originally allocated. Usually, this is used when the lifetime of the pointed object is limited by the lifetime of the allocated object (e.g. the pointed object is a data member of the allocated object).

Partly, the fact that the allocated pointer and deleter are stored in a separate object, is useful for supporting weak_ptr, as it allows to store reference counters in that object as well.

Body:
struct Base{};
struct Derived : Base {};

std::shared_ptr<Base> sp(new Derived);

So the explanation is that sp knows that it needs to call the destructor of Derived because Derived argument was passed in the constructor. However in this case of creating a shared pointer with make_shared you don't supply the pointer, and so it can't know the Derived type. Does this mean that the correct behaviour of having a shared_ptr pointing to a Derived can only work in the case of supplying your own pointer to the constructor, not in make_shared?

Body:
shared_ptr "knows" which destructor to call because the type of the originally owned object is recorded at the point of shared_ptr construction.

In the case of constructing shared_ptr from a raw pointer:

std::shared_ptr<Base> sp(new Derived);

shared_ptr constructor internally creates an object that, among other things, stores the original pointer to Derived and an associated deleter that will be called on the pointer when the last shared_ptr referencing that object is destroyed. This internal pointer to Derived is separate from the pointer that is exposed through shared_ptr interface methods, such as get or operator->, and it stays intact for the whole lifetime of the referenced Derived object. The exposed pointer may change by constructing different shared_ptr instances, and in some cases may not even point to the Derived object at all. This is why although std::shared_ptr<Base> exposes the pointer to Base, it is still able to destroy the original Derived in the end.

The case with make_shared is similar:

std::shared_ptr<Base> sp = std::make_shared<Derived>();

Here, Derived object creation and shared_ptr initialization happens within make_shared. Simplistically, you could think of make_shared like this:

template< typename T >
std::shared_ptr<T> make_shared()
{
    std::shared_ptr<T> internal_sp(new T());
    return internal_sp;
}

(I'm intentionally simplifying make_shared implementation here.)

So, in make_shared, when internal_sp is initialized, it records the object type with the associated deleter just as explained above. When sp is initialized from the result of make_shared, it simply inherits the deleter and the original pointer, and converts the exposed pointer from Derived* to Base*.

This feature of shared_ptr is key to its many other useful capabilities, such as:

Hiding the deleter type from the shared_ptr type. For example, shared_ptr<FILE> spf(fopen("foo.txt", "r"), &fclose).

Flexibility in pointer conversions. For example, as noted in the comments, shared_ptr<void> spv = sp is valid, and spv will still be able to destroy Derived object as expected.

Pointer aliasing, when the exposed pointer is pointing to a different object than the one that was originally allocated. Usually, this is used when the lifetime of the pointed object is limited by the lifetime of the allocated object (e.g. the pointed object is a data member of the allocated object).

Partly, the fact that the allocated pointer and deleter are stored in a separate object, is useful for supporting weak_ptr, as it allows to store reference counters in that object as well.


来源: stackexchange

问:
Pinescript : How to get previous EMAs cross values
We have inbuilt functions for crossover and crossunder boolean results. However I would like to know the value of the script during those cross and then calculate the price difference between the latest value and crossover values. How can I achieve that?

Thank you,
Prateek

答:
In order to get the value when a condition is met (in your case, the value of Close when EMA is crossed) you can use the ta.valuewhen() function.

From the documentation:

Source series value when the condition was true on the n-th most recent occurrence.

For example, you can use it to return the Close price when EMA is crossed:

```<code>//@version=5
indicator("My script", overlay=true)

slow = ta.ema(close, 7)
fast = ta.ema(close, 14)

// get value of close
closePriceOnCrossEma = ta.valuewhen(ta.cross(slow, fast), close, 0)

plot(closePriceOnCrossEma)
</code>```

You can now use this value to compare it with any other value you wish.

ContentLicense: CC BY-SA 4.0

Body:
In order to get the value when a condition is met (in your case, the value of Close when EMA is crossed) you can use the ta.valuewhen() function.

From the documentation:

Source series value when the condition was true on the n-th most recent occurrence.

For example, you can use it to return the Close price when EMA is crossed:

//@version=5
indicator("My script", overlay=true)

slow = ta.ema(close, 7)
fast = ta.ema(close, 14)

// get value of close
closePriceOnCrossEma = ta.valuewhen(ta.cross(slow, fast), close, 0)

plot(closePriceOnCrossEma)

You can now use this value to compare it with any other value you wish.


问:
how can i extract a 6 digit alphanumeric part of txt from a string (i want them kept together not pulled apart)
How can I extract a 6 digit alphanumeric part of txt from a string (I want them kept together not pulled apart).

ie I want to extract 3B3520 from 'Media Hold Vessel 3B3520, Vessel drawing'

Can extract the text or numbers alone but not both.

答:
What have you tried?

First 6 characters in the 4th word

```<code>= Table.AddColumn(#"PriorStep", "Custom", each Text.Start(Text.Split([Column1]," "){3},6))
</code>```

6 characters starting in position #19

```<code>= Table.AddColumn(#"PriorStep", "Custom", each Text.Middle([Column1],18,6))
</code>```

6 characters preceding the comma, version 1

```<code>= Table.AddColumn(#"PriorStep", "Custom", each Text.Middle([Column1],Text.PositionOf([Column1],",")-6,6))
</code>```

6 characters preceding the comma, version 2

```<code>= Table.AddColumn(#"PriorStep", "Custom", each Text.End(Text.Split([Column1],","){0},6))
</code>```

Regex looking for a number followed by a letter followed by 4 numbers

```<code>let fx=(text,regex)=> Web.Page("<script>var x='"&text&"';var y=new RegExp('"&regex&"','g');var b=x.match(y);document.write(b);</script>")[Data]{0}[Children]{0}[Children]{1}[Text]{0}
in let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Added Custom" = Table.AddColumn(Source , "Custom", each fx([Column1], "[0-9][a-zA-Z][0-9]{3,}"))
in  #"Added Custom"
</code>```

First 6 characters after the word "Vessel "

```<code>= Table.AddColumn(#"PriorStep", "Custom", each Text.Start(Text.Split([Column1],"Vessel "){1},6))
</code>```

Body:
What have you tried?

First 6 characters in the 4th word

= Table.AddColumn(#"PriorStep", "Custom", each Text.Start(Text.Split([Column1]," "){3},6))

6 characters starting in position #19

= Table.AddColumn(#"PriorStep", "Custom", each Text.Middle([Column1],18,6))

6 characters preceding the comma, version 1

= Table.AddColumn(#"PriorStep", "Custom", each Text.Middle([Column1],Text.PositionOf([Column1],",")-6,6))

6 characters preceding the comma, version 2

= Table.AddColumn(#"PriorStep", "Custom", each Text.End(Text.Split([Column1],","){0},6))

Regex looking for a number followed by a letter followed by 4 numbers

let fx=(text,regex)=> Web.Page("<script>var x='"&text&"';var y=new RegExp('"&regex&"','g');var b=x.match(y);document.write(b);</script>")[Data]{0}[Children]{0}[Children]{1}[Text]{0}
in let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Added Custom" = Table.AddColumn(Source , "Custom", each fx([Column1], "[0-9][a-zA-Z][0-9]{3,}"))
in  #"Added Custom"

First 6 characters after the word "Vessel "

= Table.AddColumn(#"PriorStep", "Custom", each Text.Start(Text.Split([Column1],"Vessel "){1},6))


问:
How can I tell if a date is before a certain time in Java?
For example given a java.util.Date how could I test if the time was before 12.30 PM that day?</p>

答: You can create a Date with the current date and 12:30PM as the time and do a compareTo with the other date.</p>

ContentLicense: CC BY-SA 3.0


问:
request.get_json() return 400 bad request
So I am testing POST to add new stuff to my database in postman and it keeps returning 400 error with no other info

```<code>127.0.0.1 - - [23/Feb/2021 00:46:04] "[1m[31mPOST /drinks HTTP/1.1[0m" 400 -
</code>```

I tried to use request.is_json and it returns True. The code just returns error as long as it runs to

new_drink = request.get_json()

I have no idea where did I mess up.

```<code>@app.route('/drinks',methods=['POST'])
@requires_auth('post:drinks')
def add_drinks(payload):
    new_drink = request.get_json()
    title = new_drink.get('title')
    recipe = new_drink.get('recipe')
    drink = Drink(title=title,recipe=json.dumps(recipe))
    drink.insert()
    result = {
        "success": True,
        "drinks": drink.long()
    }
    return jsonify(result), 200
</code>```

Here is a link to my project

https://github.com/TYL1026/coffee_shop/blob/main/backend/src/api.py

答: As mentioned in the comments, in my case the problem was a header. I was setting "Content-Type": "application/json" but I was sending form-data. I removed the header and the problem was solved.

Body:
So I am testing POST to add new stuff to my database in postman and it keeps returning 400 error with no other info

127.0.0.1 - - [23/Feb/2021 00:46:04] "[1m[31mPOST /drinks HTTP/1.1[0m" 400 -

I tried to use request.is_json and it returns True. The code just returns error as long as it runs to

new_drink = request.get_json()

I have no idea where did I mess up.

@app.route('/drinks',methods=['POST'])
@requires_auth('post:drinks')
def add_drinks(payload):
    new_drink = request.get_json()
    title = new_drink.get('title')
    recipe = new_drink.get('recipe')
    drink = Drink(title=title,recipe=json.dumps(recipe))
    drink.insert()
    result = {
        "success": True,
        "drinks": drink.long()
    }
    return jsonify(result), 200

Here is a link to my project

https://github.com/TYL1026/coffee_shop/blob/main/backend/src/api.py


问:
How to parse specific strings from an attribute inside xml using etree and xpath
I have an XML with two of the same tags and same attribute but different value.

```<code><testsuite>
 <testcase>
  <GenericItem html="Name: Epsilon<br/>ID: ID-032<br/>Owner: Infinitie <a
   href="mailto: infinitie@company.com
   ">infinitie@company.com</a><br/>Revision ID: ataaaa">
   Algorithm:
  </GenericItem>
  <GenericItem html="No numerical differences between 'Model AB' and 'Baseline A'
   found.</font>">
   Results for 'Epsilon Model-01':
  </GenericItem>
 </testcase>
 <testcase>
   <GenericItem html="Name: ZeroG<br/>ID: ID-033<br/>Owner: Lite <a
   href="mailto: lite@company.com
   ">lite@company.com</a><br/>Revision ID: ataaab">
   Algorithm:
  </GenericItem>
  <GenericItem html="No numerical differences between 'Model A' and 'Baseline B' found.</font><br/><font color="green">No performance difficulties found.</font><br/><font color="red">Target memory footprint more than 1.4 of baseline.</font><br/>Applied tolerance from model configuration: 2e-13<br/><font color="green">No numerical differences between 'Baseline B' and 'Target - Model A' found.</font>">
   Results for 'Lite Model':
  </GenericItem>
 </testcase>
</testSuite>
</code>```

The data that I want to get are :

Results for '#### Model'

Numerical Differences (if not listed then print ("NULL")

Performance Difficulties (if not listed then print ("NULL")

Memory footprint (if not listed then print ("NULL")

Tolerance Model applied (if not listed then print ("NULL")

The other numerical differences (if not listed then print ("NULL")

The code for now are :

```<code>from lxml import etree as ET

html_parser = ET.HTMLParser()
tree = ET.parse('NewestReport.xml')

test = tree.findall('testcase')
root = tree.getroot()
count = 0
count1 = 0
i = 0
for person in tree.xpath('./testcase'):
    a = person.xpath('//text()[contains(.,"Results")]')[i]
    print(a.strip())
    b = person.xpath('.//@html/text()[contains(., "tolerance")]')[i]
    if b:
        print(b.strip())
    else:
        print("None")
    i = i + 1
</code>```

I manage to get the Results for '#### Model' but for the Tolerance Model applied (if not listed then print ("NULL") it outputs the error:

```<code> Traceback (most recent call last):
IndexError: list index out of range
</code>```

I think it is because the no 'tolerance' is found on the first . But I can't seem to fix the error. Can someone help enlighten me on this problem ?

答:
The main problem is that you forgot . to create relative path to - and then you don't need [i] but always [0]

```<code>a = person.xpath('.//text()[contains(.,"Results")]')[0]
</code>```

And in second part you should search in @html instead of text()

And you should also use [0] but after checking if

```<code>b = person.xpath('.//@html[contains(., "tolerance")]')

if b:
    print(b[0].strip().split('<br/>'))
else:
    print("None")
</code>```

Minimal working example with data directly in code

```<code>text = '''<testsuite>
 <testcase>
  <GenericItem html="Name: Epsilon<br/>ID: ID-032<br/>Owner: Infinitie <a
   href="mailto: infinitie@company.com
   ">infinitie@company.com</a><br/>Revision ID: ataaaa">
   Algorithm:
  </GenericItem>
  <GenericItem html="No numerical differences between 'Model AB' and 'Baseline A'
   found.</font>">
   Results for 'Epsilon Model-01':
  </GenericItem>
 </testcase>
 <testcase>
   <GenericItem html="Name: ZeroG<br/>ID: ID-033<br/>Owner: Lite <a
   href="mailto: lite@company.com
   ">lite@company.com</a><br/>Revision ID: ataaab">
   Algorithm:
  </GenericItem>
  <GenericItem html="No numerical differences between 'Model A' and 'Baseline B' found.</font><br/><font color="green">No performance difficulties found.</font><br/><font color="red">Target memory footprint more than 1.4 of baseline.</font><br/>Applied tolerance from model configuration: 2e-13<br/><font color="green">No numerical differences between 'Baseline B' and 'Target - Model A' found.</font>">
   Results for 'Lite Model':
  </GenericItem>
 </testcase>
</testsuite>
'''

from lxml import etree as ET

html_parser = ET.HTMLParser()
#tree = ET.parse('NewestReport.xml')
tree = ET.fromstring(text)

for person in tree.xpath('./testcase'):
    a = person.xpath('.//text()[contains(.,"Results")]')[0]
    print(a.strip())
    print('---')

    b = person.xpath('.//@html[contains(., "tolerance")]')
    if b:
        print(b[0].strip().split('<br/>'))
    else:
        print("None")
    print('----------------')
</code>```

Result:

```<code>Results for 'Epsilon Model-01':
---
None
----------------
Results for 'Lite Model':
---
No numerical differences between 'Model A' and 'Baseline B' found.</font>
<font color="green">No performance difficulties found.</font>
<font color="red">Target memory footprint more than 1.4 of baseline.</font>
Applied tolerance from model configuration: 2e-13
<font color="green">No numerical differences between 'Baseline B' and 'Target - Model A' found.</font>
----------------
</code>```

For getting Numerical Differences, Performance Difficulties,
etc. I would use normal string functions or regex.

Body:
I have an XML with two of the same tags and same attribute but different value.

<testsuite>
 <testcase>
  <GenericItem html="Name: Epsilon
ID: ID-032
Owner: Infinitie infinitie@company.com
Revision ID: ataaaa">
   Algorithm:
  </GenericItem>
  <GenericItem html="No numerical differences between 'Model AB' and 'Baseline A'
   found.">
   Results for 'Epsilon Model-01':
  </GenericItem>
 </testcase>
 <testcase>
   <GenericItem html="Name: ZeroG
ID: ID-033
Owner: Lite lite@company.com
Revision ID: ataaab">
   Algorithm:
  </GenericItem>
  <GenericItem html="No numerical differences between 'Model A' and 'Baseline B' found.
No performance difficulties found.
Target memory footprint more than 1.4 of baseline.
Applied tolerance from model configuration: 2e-13
No numerical differences between 'Baseline B' and 'Target - Model A' found.">
   Results for 'Lite Model':
  </GenericItem>
 </testcase>
</testSuite>

The data that I want to get are :

Results for '#### Model'

Numerical Differences (if not listed then print ("NULL")

Performance Difficulties (if not listed then print ("NULL")

Memory footprint (if not listed then print ("NULL")

Tolerance Model applied (if not listed then print ("NULL")

The other numerical differences (if not listed then print ("NULL")

The code for now are :

from lxml import etree as ET

html_parser = ET.HTMLParser()
tree = ET.parse('NewestReport.xml')

test = tree.findall('testcase')
root = tree.getroot()
count = 0
count1 = 0
i = 0
for person in tree.xpath('./testcase'):
    a = person.xpath('//text()[contains(.,"Results")]')[i]
    print(a.strip())
    b = person.xpath('.//@html/text()[contains(., "tolerance")]')[i]
    if b:
        print(b.strip())
    else:
        print("None")
    i = i + 1

I manage to get the Results for '#### Model' but for the Tolerance Model applied (if not listed then print ("NULL") it outputs the error:

 Traceback (most recent call last):
IndexError: list index out of range

I think it is because the no 'tolerance' is found on the first . But I can't seem to fix the error. Can someone help enlighten me on this problem ?

Body:
The main problem is that you forgot . to create relative path to - and then you don't need [i] but always [0]

a = person.xpath('.//text()[contains(.,"Results")]')[0]

And in second part you should search in @html instead of text()

And you should also use [0] but after checking if

b = person.xpath('.//@html[contains(., "tolerance")]')

if b:
    print(b[0].strip().split('<br/>'))
else:
    print("None")

Minimal working example with data directly in code

text = '''<testsuite>
 <testcase>
  <GenericItem html="Name: Epsilon&lt;br/&gt;ID: ID-032&lt;br/&gt;Owner: Infinitie &lt;a
   href=&quot;mailto: infinitie@company.com
   &quot;&gt;infinitie@company.com&lt;/a&gt;&lt;br/&gt;Revision ID: ataaaa">
   Algorithm:
  </GenericItem>
  <GenericItem html="No numerical differences between 'Model AB' and 'Baseline A'
   found.&lt;/font&gt;">
   Results for 'Epsilon Model-01':
  </GenericItem>
 </testcase>
 <testcase>
   <GenericItem html="Name: ZeroG&lt;br/&gt;ID: ID-033&lt;br/&gt;Owner: Lite &lt;a
   href=&quot;mailto: lite@company.com
   &quot;&gt;lite@company.com&lt;/a&gt;&lt;br/&gt;Revision ID: ataaab">
   Algorithm:
  </GenericItem>
  <GenericItem html="No numerical differences between 'Model A' and 'Baseline B' found.&lt;/font&gt;&lt;br/&gt;&lt;font color=&quot;green&quot;&gt;No performance difficulties found.&lt;/font&gt;&lt;br/&gt;&lt;font color=&quot;red&quot;&gt;Target memory footprint more than 1.4 of baseline.&lt;/font&gt;&lt;br/&gt;Applied tolerance from model configuration: 2e-13&lt;br/&gt;&lt;font color=&quot;green&quot;&gt;No numerical differences between 'Baseline B' and 'Target - Model A' found.&lt;/font&gt;">
   Results for 'Lite Model':
  </GenericItem>
 </testcase>
</testsuite>
'''

from lxml import etree as ET

html_parser = ET.HTMLParser()
#tree = ET.parse('NewestReport.xml')
tree = ET.fromstring(text)

for person in tree.xpath('./testcase'):
    a = person.xpath('.//text()[contains(.,"Results")]')[0]
    print(a.strip())
    print('---')

    b = person.xpath('.//@html[contains(., "tolerance")]')
    if b:
        print(b[0].strip().split('<br/>'))
    else:
        print("None")
    print('----------------')

Result:

Results for 'Epsilon Model-01':
---
None
----------------
Results for 'Lite Model':
---
No numerical differences between 'Model A' and 'Baseline B' found.</font>
<font color="green">No performance difficulties found.</font>
<font color="red">Target memory footprint more than 1.4 of baseline.</font>
Applied tolerance from model configuration: 2e-13
<font color="green">No numerical differences between 'Baseline B' and 'Target - Model A' found.</font>
----------------

For getting Numerical Differences, Performance Difficulties,
etc. I would use normal string functions or regex.


问:
Selenium web driver assert webelement contains text and display actual vs expected
I have a demo selenium cucumber project that just runs some maths expressions in google search box and validates the results.

I want the reports to show the actual value vs expected when it fails.

I'm storing the returned text as string with ..

```<code>String resultText = driver.findElement(By.cssSelector("div[class='dDoNo vrBOv vk_bk']")).getText();
</code>```

and then asserting against expected which gets passed from my feature files with ...

```<code>assertTrue(resultText.equals(expectedResult));
</code>```

but the reports show ...

```<code>java.lang.AssertionError: expected [true] but found [false]
</code>```

I want it to display the actual expected result vs actual i.e.

```<code>java.lang.AssertionError: expected [200] but found [201]
</code>```

I've also tried ...

```<code>Assert.assertEquals(expectedResult, resultText);
</code>```

I'm using ... org.testng.Assert

Thanks

答:
With the assertion you can use your customized error text. Something like this:

Assert.assertEquals(resultText, expectedResult, "Expected: " + expectedResult + " but found " + resultText);
```
<p>Or this</p>
<pre class="lang-java prettyprint-override"><code>Assert.assertTrue(expectedResult.equals(resultText), "Expected: " + expectedResult + " but found " + resultText);
</code>```

In case of non-equal parameters it will present you output like this for the first case:

java.lang.AssertionError: Expected: expectedResult but found resultText

Expected :expectedResult

Actual   :resultText

And for the second case:

java.lang.AssertionError: Expected: expectedResult but found resultText

Expected :true

Actual   :false

Body:
I have a demo selenium cucumber project that just runs some maths expressions in google search box and validates the results.

I want the reports to show the actual value vs expected when it fails.

I'm storing the returned text as string with ..

String resultText = driver.findElement(By.cssSelector("div[class='dDoNo vrBOv vk_bk']")).getText();

and then asserting against expected which gets passed from my feature files with ...

assertTrue(resultText.equals(expectedResult));

but the reports show ...

java.lang.AssertionError: expected [true] but found [false]

I want it to display the actual expected result vs actual i.e.

java.lang.AssertionError: expected [200] but found [201]

I've also tried ...

Assert.assertEquals(expectedResult, resultText);

I'm using ... org.testng.Assert

Thanks

Body:
With the assertion you can use your customized error text. Something like this:

Assert.assertEquals(resultText, expectedResult, "Expected: " + expectedResult + " but found " + resultText);

Or this

Assert.assertTrue(expectedResult.equals(resultText), "Expected: " + expectedResult + " but found " + resultText);

In case of non-equal parameters it will present you output like this for the first case:

java.lang.AssertionError: Expected: expectedResult but found resultText

Expected :expectedResult

Actual   :resultText

And for the second case:

java.lang.AssertionError: Expected: expectedResult but found resultText

Expected :true

Actual   :false


问:
How to "PERFORM" a CTE query returning multiple rows/columns?
As a follow-up to this question:

How to "PERFORM" CTE queries in PL/pgSQL?

I try:

```<code>perform (with test_as_cte as(select * from myTable) select * from test_as_cte);
</code>```

But get the following error:

```<code>SQL Error [42601]: ERROR: subquery must return only one column
Where: PL/pgSQL function inline_code_block line 9 at PERFORM
</code>```

If I replace * with myCol in the above code there is no error.

However, I need to do realistic performance testing with the CTE and return multiple columns.

答:
The WITH query enclosed in parentheses is treated like a sub-select. It works fine the way you have it as long as it returns a single value (one column of one row). Else you must treat it as subquery and call it like this (inside a PL/pgSQL code block!):

```<code>PERFORM * FROM (with test_as_cte as (select * from b2) select * from test_as_cte t) sub;
</code>```

Or just:

```<code>PERFORM FROM (<any SELECT query>) sub;
</code>```

The manual:

PERFORM query;

This executes query and discards the result. Write the query
the same way you would write an SQL SELECT command, but replace the
initial keyword SELECT with PERFORM. For WITH queries, use
PERFORM and then place the query in parentheses. (In this case, the
query can only return one row.)

I think this could be clearer. I'll suggest a fix for the documentation.

Body:
As a follow-up to this question:

How to "PERFORM" CTE queries in PL/pgSQL?

I try:

perform (with test_as_cte as(select * from myTable) select * from test_as_cte);

But get the following error:

SQL Error [42601]: ERROR: subquery must return only one column
Where: PL/pgSQL function inline_code_block line 9 at PERFORM

If I replace * with myCol in the above code there is no error.

However, I need to do realistic performance testing with the CTE and return multiple columns.

Body:
The WITH query enclosed in parentheses is treated like a sub-select. It works fine the way you have it as long as it returns a single value (one column of one row). Else you must treat it as subquery and call it like this (inside a PL/pgSQL code block!):

PERFORM * FROM (with test_as_cte as (select * from b2) select * from test_as_cte t) sub;

Or just:

PERFORM FROM (<any SELECT query>) sub;

The manual:

PERFORM query;

This executes query and discards the result. Write the query
the same way you would write an SQL SELECT command, but replace the
initial keyword SELECT with PERFORM. For WITH queries, use
PERFORM and then place the query in parentheses. (In this case, the
query can only return one row.)

I think this could be clearer. I'll suggest a fix for the documentation.


问:
How to position 2 divs? CSS
I would like to achieve this:

But I currently have this:

I would like the ">" vertically centre to the right.I am currently using a table to do so but i am unable to make the text float to the right on centre the icon.

My Html (I am using react):

```<code><div className="biy">
            <table>
              <tr className=""></tr>
              <tr className=""></tr>
              <td className="biy-td-content">
                <p className="biy-title">{"Bible in a year :"}</p>
                <a className="biy-a" href={Data.bible_in_a_year_url}>
                  <p className="biy-p">{Data.bible_in_a_year_references}</p>
                </a>
              </td>
              <td className="biy-td-icon">
                <div className="biy-span-center">
                  <div className="biy-span">
                    <GrFormNext></GrFormNext>
                  </div>
                </div>
              </td>
            </table>
          </div>
</code>```

My CSS:

```<code>.biy {
  background-color: var(--light);
  border-radius: 5px;
  margin-top: 16px;
  padding: 16px;
}

.biy-title {
  font-size: 1.1rem;
  margin: 0px;
  font-weight: 500;
}

.biy-p {
  font-size: 1.1rem;
  margin: 0px;
  color: var(--blue);
  font-weight: 550;
  margin-top: 8px;
}
.biy-a {
  text-decoration: none;
}

.biy-td-content {
  width: 96%;
}
.biy-td-icon {
  width: 4%;
}
.biy-span {
  margin: 0px;
  font-weight: 1000;
  font-size: 2rem;
  float: right;
}

.biy-span-center {
  position: fixed;
}
</code>```

Please help me

答:
you should go for CSS grid instead of a table. When using grid-area you can position the 3 elements without any extra markup.

Matt

body {
  font-family: sans-serif;
  background: #F1F7FE;
}

.biy {
  display: grid;
  grid-template-columns: auto 24px;
  grid-template-areas:
    "label icon"
    "value icon";
  gap: 4px;
  width: 300px;
  padding: 16px;
  border-radius: 4px;
  background: #FFF;
}

.biy-label {
  grid-area: label;
}

.biy-link {
  grid-area: value;
  color: #56A4DC;
  text-decoration: none;
}

.biy-icon {
  grid-area: icon;
  align-self: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="biy">
  <div class="biy-label">Bible in a year:</div>
  Exodus 34–35; Matthew 22:23–46
  <svg class="biy-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentcolor">
    <path d="M8 3L17 12L8 21" stroke-width="3" />
  </svg>
</div></code>```

Title: How to position 2 divs? CSS

Body:
I would like to achieve this:

But I currently have this:

I would like the ">" vertically centre to the right.I am currently using a table to do so but i am unable to make the text float to the right on centre the icon.

My Html (I am using react):

{"Bible in a year :"}

{Data.bible_in_a_year_references}

                    <GrFormNext></GrFormNext>

My CSS:

.biy {
  background-color: var(--light);
  border-radius: 5px;
  margin-top: 16px;
  padding: 16px;
}

.biy-title {
  font-size: 1.1rem;
  margin: 0px;
  font-weight: 500;
}

.biy-p {
  font-size: 1.1rem;
  margin: 0px;
  color: var(--blue);
  font-weight: 550;
  margin-top: 8px;
}
.biy-a {
  text-decoration: none;
}

.biy-td-content {
  width: 96%;
}
.biy-td-icon {
  width: 4%;
}
.biy-span {
  margin: 0px;
  font-weight: 1000;
  font-size: 2rem;
  float: right;
}

.biy-span-center {
  position: fixed;
}

Please help me

Body:
you should go for CSS grid instead of a table. When using grid-area you can position the 3 elements without any extra markup.

Matt

body {
  font-family: sans-serif;
  background: #F1F7FE;
}

.biy {
  display: grid;
  grid-template-columns: auto 24px;
  grid-template-areas:
    "label icon"
    "value icon";
  gap: 4px;
  width: 300px;
  padding: 16px;
  border-radius: 4px;
  background: #FFF;
}

.biy-label {
  grid-area: label;
}

.biy-link {
  grid-area: value;
  color: #56A4DC;
  text-decoration: none;
}

.biy-icon {
  grid-area: icon;
  align-self: center;
}

<div class="biy">
  <div class="biy-label">Bible in a year:</div>
  <a class="biy-link" href="">Exodus 34–35; Matthew 22:23–46</a>
  <svg class="biy-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentcolor">
    <path d="M8 3L17 12L8 21" stroke-width="3" />
  </svg>
</div>


问:
What is the difference between ValueError and IndexError?
I am learning about arrays and linked lists. When I wanted to take look at the implementation of a singly linked list, I found this on GitHub. If you take a look a the implementation, you will probably notice that people used IndexError and ValueError interchangeably for the same purpose: for telling the user that the index they have provided doesn't have a valid value. So this is the source of confusion. Could someone please shed some light on the difference and when to use them?

Furthermore, I would appreciate it if someone explained the following sentence from Python docs

... and the situation is not described by a more precise exception such as IndexError.

答: Index Error is for wrong indexs, while Value Errors are for when a string might be empty, etc.</p>


问:
Is it possible to define function that creates an N-dimensional list of lists easily?
I have searched and found these questions: How to create a multi-dimensional list and N dimensional array in python which hint toward what I am looking for, but they seem to only make 2D arrays and not ND arrays.

Problem:

My problem is that I am able to create an n-dimensional list of lists for a known n, but I am not sure how it can be generalized to work with all values of n.

Consider this example:

```<code>def makeList(n):
    return [[[n for _ in range(n)]
                for _ in range(n)]
                for _ in range(n)]
print(makeList(3))
</code>```

Output:

```<code>[[[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]],
 [[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]],
 [[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]]]
</code>```

This will create a list of lists that is a 3x3x3 array of 3's which is the intended result, but if we use a different n:

```<code>print(makeList(2))
</code>```

Output:

```<code>[[[2, 2],
  [2, 2]],
 [[2, 2],
  [2, 2]]]
</code>```

This will create a list of lists that is a 2x2x0 array of 2's and this is not the intended result. Instead the results should be a list of lists that is a 2x2 array of 2's.

Likewise if we set n = 4:

```<code>print(makeList(4))
</code>```

This will give a list of lists that is 4x4x4 when it should give a 4x4x4x4 list of lists.

The main issue is that the number of for loops must change depending on the input, but obviously the code can't "come to life" and recode itself magically, hence my issue.

I am looking for a way to get this result that is simple. I am sure I could continue developing ideas for solutions, but I have not been able to think of anything that is concise.

What I have tried:

The first idea I thought of was to use recursion, and this my simple approach:

```<code>def makeList(n, output = []):
    if not output:
        output = [n for _ in range(n)]
    else:
        output = [output for _ in range(n)]
    if len(output) == n:
        return output
    else:
        return makeList(n, output)
</code>```

This obviously will not work because if len(output) == n: will execute the first iteration since the length of the inner loops is equal to the length of the outermost loop. However, even if there was a condition that properly terminated the function, this solution would still not be ideal because I could run into maximum recursion errors with large values of n. Furthermore, even if these issues were resolved this code is still quite long as well as time consuming.

The other potential perspective I considered (and the solution that I found that works) is using a dict. My solution saves the intermediate lists of lists in a dict so it can be used for the next iteration:

```<code>def makeList(n):
    d = {str(i): None for i in range(n)}
    for i in range(n):
        if i == 0:
            d[str(i)] = [n for _ in range(n)]
        else:
            d[str(i)] = [d[str(i-1)] for _ in range(n)]
    return d[str(n-1)]
</code>```

But again, this is very long and doesn't seem very pythonic.

Solution requirements:

The ideal solution would be much more concise than mine with an efficient time complexity that only uses built-in functions.

Other options that are close to these requirements would also be helpful as long as the spirit of the answer is trying to best meet the requirements.

Being concise is the most important aspect, however, which is why I am not fully happy with my current attempts.

答: Your BEST plan is to use numpy for this.  You can create an arbitrary array of all zeros with np.zeros( (4,4,4) ), or an array of 1s with np.ones( (4,4,4) ).  If you're going to be working with arrays very much at all, you will certainly want to use numpy.

Body:
I have searched and found these questions: How to create a multi-dimensional list and N dimensional array in python which hint toward what I am looking for, but they seem to only make 2D arrays and not ND arrays.

Problem:

My problem is that I am able to create an n-dimensional list of lists for a known n, but I am not sure how it can be generalized to work with all values of n.

Consider this example:

def makeList(n):
    return [[[n for _ in range(n)]
                for _ in range(n)]
                for _ in range(n)]
print(makeList(3))

Output:

[[[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]],
 [[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]],
 [[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]]]

This will create a list of lists that is a 3x3x3 array of 3's which is the intended result, but if we use a different n:

print(makeList(2))

Output:

[[[2, 2],
  [2, 2]],
 [[2, 2],
  [2, 2]]]

This will create a list of lists that is a 2x2x0 array of 2's and this is not the intended result. Instead the results should be a list of lists that is a 2x2 array of 2's.

Likewise if we set n = 4:

print(makeList(4))

This will give a list of lists that is 4x4x4 when it should give a 4x4x4x4 list of lists.

The main issue is that the number of for loops must change depending on the input, but obviously the code can't "come to life" and recode itself magically, hence my issue.

I am looking for a way to get this result that is simple. I am sure I could continue developing ideas for solutions, but I have not been able to think of anything that is concise.

What I have tried:

The first idea I thought of was to use recursion, and this my simple approach:

def makeList(n, output = []):
    if not output:
        output = [n for _ in range(n)]
    else:
        output = [output for _ in range(n)]
    if len(output) == n:
        return output
    else:
        return makeList(n, output)

This obviously will not work because if len(output) == n: will execute the first iteration since the length of the inner loops is equal to the length of the outermost loop. However, even if there was a condition that properly terminated the function, this solution would still not be ideal because I could run into maximum recursion errors with large values of n. Furthermore, even if these issues were resolved this code is still quite long as well as time consuming.

The other potential perspective I considered (and the solution that I found that works) is using a dict. My solution saves the intermediate lists of lists in a dict so it can be used for the next iteration:

def makeList(n):
    d = {str(i): None for i in range(n)}
    for i in range(n):
        if i == 0:
            d[str(i)] = [n for _ in range(n)]
        else:
            d[str(i)] = [d[str(i-1)] for _ in range(n)]
    return d[str(n-1)]

But again, this is very long and doesn't seem very pythonic.

Solution requirements:

The ideal solution would be much more concise than mine with an efficient time complexity that only uses built-in functions.

Other options that are close to these requirements would also be helpful as long as the spirit of the answer is trying to best meet the requirements.

Being concise is the most important aspect, however, which is why I am not fully happy with my current attempts.


问:
Adding UITextView to SwiftUI
i tried to add UITextView to swiftUI because there are things that TextEditor isn't capable of doing. Here's how I built it

```<code>struct TextViewSwift : UIViewRepresentable {
    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        textView.text = "Testing UITextView"
        return textView
    }

    func updateUIView(_ uiView: UITextView, context: Context) {

    }

    typealias UIViewType = UITextView

}
</code>```

So I test it out with UILabel (because I want to make sure that the code is working when doing with other UIkit component)

and turns out when I debug the view, not even the UITextView appear, is it a bug within the SwiftUI it self or am I missing something? Thank you

Only UILabel appear

答:
Just need a Text view? Try this.</p>
```<code>import SwiftUI

struct TextArea: View {
    @Binding var text: String
    let placeholder: String

    init(_ placeholder: String, text: Binding<String>) {
        self._text = text
        self.placeholder = placeholder
        UITextView.appearance().backgroundColor = .clear
    }

    var body: some View {
        ZStack(alignment: .topLeading) {
            if text.isEmpty {
                Text(placeholder)
                    .foregroundColor(Color(.placeholderText))
                    .padding(.horizontal, 8)
                    .padding(.vertical, 12)
            }

            TextEditor(text: $text)
                .padding(4)
        }.font(.body)
    }
}
</code>```

Title: Adding UITextView to SwiftUI

Body:
i tried to add UITextView to swiftUI because there are things that TextEditor isn't capable of doing. Here's how I built it

struct TextViewSwift : UIViewRepresentable {
    func makeUIView(context: Context) -> UITextView {
        let textView = UITextView()
        textView.text = "Testing UITextView"
        return textView
    }

    func updateUIView(_ uiView: UITextView, context: Context) {

    }

    typealias UIViewType = UITextView

}

So I test it out with UILabel (because I want to make sure that the code is working when doing with other UIkit component)

and turns out when I debug the view, not even the UITextView appear, is it a bug within the SwiftUI it self or am I missing something? Thank you

Only UILabel appear

Body:
Just need a Text view? Try this.

import SwiftUI

struct TextArea: View {
    @Binding var text: String
    let placeholder: String

    init(_ placeholder: String, text: Binding<String>) {
        self._text = text
        self.placeholder = placeholder
        UITextView.appearance().backgroundColor = .clear
    }

    var body: some View {
        ZStack(alignment: .topLeading) {
            if text.isEmpty {
                Text(placeholder)
                    .foregroundColor(Color(.placeholderText))
                    .padding(.horizontal, 8)
                    .padding(.vertical, 12)
            }

            TextEditor(text: $text)
                .padding(4)
        }.font(.body)
    }
}


问:
Python program, list not printing
I have the following program which seeks to check the similarity between two lists. However, the originalword (list) prints correctly the first time but not the second therefore the code doesn't work to check equivalence.

https://trinket.io/python3/b3b7827717

Can anyone spot the error? If so, could a solution be posted
a) using lists
b) Not introducing any new skills (e.g. string slicing)

```<code>def palindromechecker():
  print("----Palindrome Checker---")

  word=input("Enter word:")

  #empty list for reversed word
  originalword=[]
  reversedword=[]

  #put each letter in word in the list originallist
  for i in range(len(word)):
    originalword.append(word[i])
  print("Print original word in order:",originalword)

  #reverse the word
  for i in range(len(word)):
    reversedword.append(originalword.pop())
  print("Reversed word:",reversedword)
  print("Original word:",originalword)

  #are original word and reversed word the same?

  if originalword==reversedword:
    print("--Palindrome Found--")
  else:
    print("--Not a Palindrome---")

palindromechecker()
</code>```

答:
You make originalword list empty by doing that originalword.pop() in the second loop. Better way to do that is just reverse list like that

reversedword = originalword[::-1]

It will work without loop

Or you can do something like that:

for i in range(len(word)):
    reversedword.append(originalword[-1-i])
```

Title: Python program, list not printing

Body:
I have the following program which seeks to check the similarity between two lists. However, the originalword (list) prints correctly the first time but not the second therefore the code doesn't work to check equivalence.

https://trinket.io/python3/b3b7827717

Can anyone spot the error? If so, could a solution be posted
a) using lists
b) Not introducing any new skills (e.g. string slicing)

def palindromechecker():
  print("----Palindrome Checker---")

  word=input("Enter word:")

  #empty list for reversed word
  originalword=[]
  reversedword=[]

  #put each letter in word in the list originallist
  for i in range(len(word)):
    originalword.append(word[i])
  print("Print original word in order:",originalword)

  #reverse the word
  for i in range(len(word)):
    reversedword.append(originalword.pop())
  print("Reversed word:",reversedword)
  print("Original word:",originalword)

  #are original word and reversed word the same?

  if originalword==reversedword:
    print("--Palindrome Found--")
  else:
    print("--Not a Palindrome---")

palindromechecker()


问:
Is there's a way to validate unknown keys with JOI on nested payloads?
I have a middleware that validates a incoming request using Joi.

```<code>export default (schema: any) => async (req: Request, res: Response, next: NextFunction) => {
  try {
    const validation = schema.validate(req, { abortEarly: false })

    if (validation.error) throw validation.error

    return next()
  } catch (error) {
    return res.status(400).json({ error: error.details })
  }
}
</code>```

For testing, propouse, my schema is as follow

```<code>const schema = Joi.object({
  headers: Joi.object()
    .keys({
      page: Joi.string().required()
    })
    .unknown(true)
    .label('headers'),
  body: Joi.object({
    page: Joi.string().required()
  })
})
</code>```

I'm testing this function with Postman. When I do not send the header it fails but show this following errors:

'user-agent': 'PostmanRuntime/7.29.0'

accept: '/',

'accept-encoding': 'gzip, deflate, br',

connection: 'keep-alive'

I want to be able to validate only the 'page' field on the schema, and ignore the anyn other field above.

答:
Change your validation and add stripUnknown option to true:</p>
```<code>const validation = schema.validate(req, { abortEarly: false, stripUnknown:true })
</code>```

Body:
I have a middleware that validates a incoming request using Joi.

export default (schema: any) => async (req: Request, res: Response, next: NextFunction) => {
  try {
    const validation = schema.validate(req, { abortEarly: false })

    if (validation.error) throw validation.error

    return next()
  } catch (error) {
    return res.status(400).json({ error: error.details })
  }
}

For testing, propouse, my schema is as follow

const schema = Joi.object({
  headers: Joi.object()
    .keys({
      page: Joi.string().required()
    })
    .unknown(true)
    .label('headers'),
  body: Joi.object({
    page: Joi.string().required()
  })
})

I'm testing this function with Postman. When I do not send the header it fails but show this following errors:

'user-agent': 'PostmanRuntime/7.29.0'

accept: '/',

'accept-encoding': 'gzip, deflate, br',

connection: 'keep-alive'

I want to be able to validate only the 'page' field on the schema, and ignore the anyn other field above.

Body:
Change your validation and add stripUnknown option to true:

const validation = schema.validate(req, { abortEarly: false, stripUnknown:true })


问:
Install shell extension conditionally
Reference: Integrate a packaged desktop app with File Explorer
https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/integrate-packaged-app-with-file-explorer

I now know how to install a shell extension custom menu item in the File Explorer for my win32 packaged desktop app. But I want to give a choice to the user whether he really wants the shell extension. Is there a way to do that in Appx manifest?

答:
You can work around that issue if you implement the IExplorerCommandState interface which has the IExplorerCommandState::GetState method

Implement this interface when you need to determine the command state
dynamically (for instance, based on an item's properties). This
interface provides the same functionality as
IExplorerCommand::GetState, without the overhead of that interface's
additional methods. Implement IExplorerCommandState when you only need
to compute the command state

Title: Install shell extension conditionally


问:
Why are my selectors not working inside this flexbox?
I am just starting out in html and css and am not sure why my selector is not shrinking my image, can you help me out?

I created a flex-box to put both the image and the caption in, and I plan on adding a paragraph of text on the left side of the screen also in the flex-box which I will also include in the flex-box, but the problem is i can't shrink the image while it's in the flex-box without using a selector for all images instead of for this specific one, what am I doing wrong?

Edit: Made the code reproducible as per requested

#img-container {
    display: flex;
    flex-direction: column;
    align-items: end;
}
#selfie {
    flex-basis: 10%;
    min-height: auto;
}
#selfie-caption {
    justify-content: flex-start;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
    <link rel="stylesheet" href="resume.css">
    <main id="main">
        <title>My Name</title>
        <div id="img-container">
            <figure>
                <img id="selfie" src="https://upload.wikimedia.org/wikipedia/commons/thumb/7/71/2010-kodiak-bear-1.jpg/220px-2010-kodiak-bear-1.jpg">
                <figcaption id="selfie-caption">An Image Of Me</figcaption>
            </figure>
        </div>
    </main>
</html></code>```

答:
flex-basis not works, because you set display: flex to #img-container. So your flex item is figure and not #selfie and #selfie-caption. So flex-basis: 10% not give a meaning for that. So should:

```<code>figure{
display: flex;
flex-direction: column;
}
#selfie {
flex-basis: 10%;
min-height: auto;
}
</code>```

Body:
I am just starting out in html and css and am not sure why my selector is not shrinking my image, can you help me out?

I created a flex-box to put both the image and the caption in, and I plan on adding a paragraph of text on the left side of the screen also in the flex-box which I will also include in the flex-box, but the problem is i can't shrink the image while it's in the flex-box without using a selector for all images instead of for this specific one, what am I doing wrong?

Edit: Made the code reproducible as per requested

#img-container {
    display: flex;
    flex-direction: column;
    align-items: end;
}
#selfie {
    flex-basis: 10%;
    min-height: auto;
}
#selfie-caption {
    justify-content: flex-start;
}

    <link rel="stylesheet" href="resume.css">

        <title>My Name</title>

An Image Of Me

Body:
flex-basis not works, because you set display: flex to #img-container. So your flex item is figure and not #selfie and #selfie-caption. So flex-basis: 10% not give a meaning for that. So should:

figure{
display: flex;
flex-direction: column;
}
#selfie {
flex-basis: 10%;
min-height: auto;
}


问:
Prevent Android Boxed TextInputLayout scroll to bottom suddenly on cursor positioning
I hava a long TextInputEditText in a TextInputLayout in a ScrollView, When I click at the start of the text to set the cursor position on the first line, but suddenly screen scrolls to bottom. see GIF below:

Now if I remove Material box style from TextInputLayout, everything is ok. No sudden scroll on first line click.

```<code><com.google.android.material.textfield.TextInputLayout
            android:id="@+id/tilDescription"
            <!--style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.Dense"-->
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dp"
            android:hint="Product Description"
            app:counterEnabled="true"
</code>```

see this GIF, when I remove style attribute:

What's wrong with outlined Box style?

Caution: I don't want to change windowSoftInputMode in AndroidManifest to adjustPan, I should use adjustResize because I have some other stuff which keyboard shouldn't appear on top of them.

答:
For multi-line TextInputEditTexts that might be taller than the screen (especially after the soft keyboard is shown), you need to add the following to your TextInputEditText

```<code>app:textInputLayoutFocusedRectEnabled="false"
</code>```

as described here: Android TextInputLayout writing focus issue when height is bigger than the screen

Body:
I hava a long TextInputEditText in a TextInputLayout in a ScrollView, When I click at the start of the text to set the cursor position on the first line, but suddenly screen scrolls to bottom. see GIF below:

Now if I remove Material box style from TextInputLayout, everything is ok. No sudden scroll on first line click.

<com.google.android.material.textfield.TextInputLayout
            android:id="@+id/tilDescription"

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dp"
            android:hint="Product Description"
            app:counterEnabled="true"

see this GIF, when I remove style attribute:

What's wrong with outlined Box style?

Caution: I don't want to change windowSoftInputMode in AndroidManifest to adjustPan, I should use adjustResize because I have some other stuff which keyboard shouldn't appear on top of them.

Body:
For multi-line TextInputEditTexts that might be taller than the screen (especially after the soft keyboard is shown), you need to add the following to your TextInputEditText

app:textInputLayoutFocusedRectEnabled="false"

as described here: Android TextInputLayout writing focus issue when height is bigger than the screen


问:
What’s the difference between AbstractMessageSource and MessageProducerSupport in Spring Integration?
When developing inbound channel adapters, I couldn’t find any place that mentions the differences between AbstractMessageSource and MessageProducerSupport in Spring Integration. I’m asking this question in the context of reactive streams, so I’m actually looking at AbstractReactiveMessageSource, but I guess it doesn’t matter for my question. I also wonder whether MessageProducerSupport supports project reactor and doesn’t have an equivalent to AbstractReactiveMessageSource.

答:
There is some documentation about these types of components: https://docs.spring.io/spring-integration/docs/current/reference/html/overview.html#finding-class-names-for-java-and-dsl-configuration

The inbound message flow side has its own components, which are divided into polling and listening behaviors.

So, the MessageProducerSupport is for those protocols which provide a listening callback for us. So, we can hook up into that, build message and produce it into a channel provided by the MessageProducer. So, it is  self-eventing component which really has everything to listen to the source system and produce messages from the callback. This type of channel adapters called event-driven and samples of them are JMS, AMQP, HTTP, IMAP,  Kinesis etc.

From here it is wrong to try to compare the MessageProducerSupport with an AbstractMessageSource because the are not relevant. The one you should look into is a SourcePollingChannelAdapter. Exactly this one is that kind of flow beginning endpoint which is similar to MessageProducerSupport. With only the problem that it is based on a periodic scheduled task to request for messages in the provided MessageSource. This type of component is for those protocols which don't provide listening callback, e.g. local file system, (S)FTP, JDBC, MongoDb, POP3, S3 etc.

You probable would expect something similar to MessageSource for the MessageProducer level, but there is not that kind of layer because everything single event-driven protocol has its own specifics, therefore we cannot extract some common abstraction like in case of polling protocols.

If your source system provides for you a reactive Publisher, you don't need to look into a SourcePollingChannelAdapter and MessageSource. You just need a MessageProducerSupport and call its subscribeToPublisher(Publisher<? extends Message<?>> publisher) from the start() implementation.

There is no need in the reactive implementation for the polling since Publisher is not pollable by itself it is event-driven. Although it has its own back-pressure specifics which is out of MessageProducerSupport scope.

There is also some explanation in  this section of the doc: https://docs.spring.io/spring-integration/docs/current/reference/html/reactive-streams.html#source-polling-channel-adapter. And see a couple next paragraphs.


问:
How do I append a text after an element has faded out completely?
I want to append a class .Appear only after ensuring the element has been removed completely..How can I achieve this?

```<code><html>
 <body>
     <div id="Append"></div>
 </body>
</html>

$(function(){
$(".Appear").stop().fadeOut("fast",function(){
    $(this).remove();
    alert(123);
    })

   $("#Append").append("<span class='Appear'>Appear</span>"); alert(8);
})
</code>```

http://jsfiddle.net/uyPJB/

答:
You could do this:

```<code>    var $appear = $("<span class='Appear'>Appear</span>")
    $("#Append").append($appear)
    $appear.fadeOut("fast",function(){$(this).remove();});
</code>```

Live example: http://jsfiddle.net/VGp2U/

Body:
I want to append a class .Appear only after ensuring the element has been removed completely..How can I achieve this?

$(function(){
$(".Appear").stop().fadeOut("fast",function(){
    $(this).remove();
    alert(123);
    })

   $("#Append").append("Appear"); alert(8);
})

http://jsfiddle.net/uyPJB/

Body:
You could do this:

    var $appear = $("<span class='Appear'>Appear</span>")
    $("#Append").append($appear)
    $appear.fadeOut("fast",function(){$(this).remove();});

Live example: http://jsfiddle.net/VGp2U/


问:
How to get the indexes of all minimum values in pandas dataframe?
I have a dataframe:

```<code>df = pd.DataFrame({'A': [0, 0, 1], 'B': [1, 0, 0]}, index=['x', 'y', 'z'])

   A  B
x  0  1
y  0  0
z  1  0
</code>```

For each row, I want the names of all the columns with the lowest value (edit: per row), something like:

```<code>x  A
y  A
y  B
z  B

# or

x  [A]
y  [A, B]
z  [B]
</code>```

I know idxmin() gives the first instance of the lowest value:

```<code>df.idxmin(axis=1)

x    A
y    A
z    B
</code>```

But what is an efficient way to get all of them?

This question gives all of the rows with the minimum value in a specific column, but that's not quite what I want.

Edit: Here's a better toy df to play with for getting the column names with the minimum value in each row:

```<code>df2 = pd.DataFrame({'A': [1, 0, 6], 'B': [3, 0, 2]}, index=['x', 'y', 'z'])

   A  B
x  1  3
y  0  0
z  6  2
</code>```

答:
You can use groupby+transform('min'):

```<code>s = df.stack()
s[s.eq(s.groupby(level=0).transform('min'))]
</code>```

Output:

```<code>x  A    0
y  A    0
   B    0
z  B    0
</code>```

Alternative format:

```<code>s = df.stack()
(s[s.eq(s.groupby(level=0).transform('min'))]
  .reset_index()
  .groupby('level_0')['level_1'].apply(list)
 )
</code>```

Output:

```<code>level_0
x       [A]
y    [A, B]
z       [B]
Name: level_1, dtype: object
</code>```

Body:
I have a dataframe:

df = pd.DataFrame({'A': [0, 0, 1], 'B': [1, 0, 0]}, index=['x', 'y', 'z'])

   A  B
x  0  1
y  0  0
z  1  0

For each row, I want the names of all the columns with the lowest value (edit: per row), something like:

x  A
y  A
y  B
z  B

# or

x  [A]
y  [A, B]
z  [B]

I know idxmin() gives the first instance of the lowest value:

df.idxmin(axis=1)

x    A
y    A
z    B

But what is an efficient way to get all of them?

This question gives all of the rows with the minimum value in a specific column, but that's not quite what I want.

Edit: Here's a better toy df to play with for getting the column names with the minimum value in each row:

df2 = pd.DataFrame({'A': [1, 0, 6], 'B': [3, 0, 2]}, index=['x', 'y', 'z'])

   A  B
x  1  3
y  0  0
z  6  2

Body:
You can use groupby+transform('min'):

s = df.stack()
s[s.eq(s.groupby(level=0).transform('min'))]

Output:

x  A    0
y  A    0
   B    0
z  B    0

Alternative format:

s = df.stack()
(s[s.eq(s.groupby(level=0).transform('min'))]
  .reset_index()
  .groupby('level_0')['level_1'].apply(list)
 )

Output:

level_0
x       [A]
y    [A, B]
z       [B]
Name: level_1, dtype: object


问:
Create a Dataframe of Difference scores between users for multiple variables
I have a large dataframe with users scores on a number of language dimensions, with a simplified version looking like the code below (I have included a dput replication data at the bottom of the post)

```<code>    user             Authentic   Analytic    Clout       Tone
2   Adams_Alma       0.05738848  0.7511374  0.3675847   0.95387755
3   Aguilar_Pete     0.24302974  0.7725205  0.3873588   0.79183673
4   Allred_Colin     0.11245353  0.7770701  0.7482345   0.58346939
5   Auchincloss_Jake 0.96119888  0.8020928  0.2673023   0.49765306
6   Axne_Cynthia     0.12500000  0.8644222  0.4918785   0.97112245
</code>```

Using this data, I want to create a dataframe in which each row is the difference score of between a pair of users in the dataset, as seen below (though the actual dataframe is much larger).

```<code>    from        to                 diff_Authentic   diff_Analytic  diff_Clout  diff_Tone
1   Adams_Alma  Aguilar_Pete       0.9802260        0.123456       0.123456    0.123456
2   Adams_Alma  Allred_Colin       0.6193503        0.123456       0.123456    0.123456
3   Adams_Alma  Auchincloss_Jake   0.8997175        0.123456       0.123456    0.123456
4   Adams_Alma  Axne_Cynthia       0.8757062        0.123456       0.123456    0.123456
5   Adams_Alma  Baldwin_Tammy      0.9406780        0.123456       0.123456    0.123456
6   Adams_Alma  Barragán_Nanette   0.8495763        0.123456       0.123456    0.123456
7   Adams_Alma  Bass_Karen         0.8234463        0.123456       0.123456    0.123456
8   Adams_Alma  Beatty_Joyce       0.9014831        0.123456       0.123456    0.123456
9   Adams_Alma  Bennet_Michael     0.5183616        0.123456       0.123456    0.123456
10  Adams_Alma  Bera_Ami           0.8223870        0.123456       0.123456    0.123456
</code>```

Using the code below, I am able to create a difference edgelist for one variable at a time, but my full dataframe has 90 variables I want differences for.

```<code>out <- with(norm_data, as.matrix(dist(setNames(norm_data$Authentic, norm_data$user))))
dif_g <- graph_from_adjacency_matrix (out, mode = 'undirected', weighted = TRUE)
dif_edge_list <- as_data_frame(dif_g, 'edges')
dif_edge_list$weight <- 1 - dif_edge_list$weight
</code>```

I would like to have a single dataframe that has the difference scores for each pair of users across all variables. I'm assuming a loop might be the solution, but I can't figure out how to do this. Any help would be greatly appreciated. Let me know if you need any more info.

Dput Data:

```<code>Show in New WindowClear OutputExpand/Collapse Output
structure(list(user = structure(1:50, .Label = c("Adams_Alma",
"Aguilar_Pete", "Allred_Colin", "Auchincloss_Jake", "Axne_Cynthia",
"Baldwin_Tammy", "Barragán_Nanette", "Bass_Karen", "Beatty_Joyce",
"Bennet_Michael", "Bera_Ami", "Beyer_Donald", "Bishop_Sanford",
"Blumenthal_Richard", "Blunt_Rochester_Lisa", "Bonamici_Suzanne",
"Booker_Cory", "Bourdeaux_Carolyn", "Bowman_Jamaal", "Boyle_Brendan",
"Brown_Anthony", "Brown_Sherrod", "Brownley_Julia", "Bush_Cori",
"Bustos_Cheri", "Butterfield_George", "Cantwell_Maria", "Carbajal_Salud",
"Cárdenas_Tony", "Cardin_Benjamin", "Carper_Thomas", "Carson_André",
"Cartwright_Matthew", "Case_Ed", "Casey_Robert", "Casten_Sean",
"Castor_Kathy", "Castro_Joaquin", "Chu_Judy", "Cicilline_David",
"Clark_Katherine", "Clarke_Yvette", "Cleaver_Emanuel", "Clyburn_James",
"Cohen_Steve", "Connolly_Gerald", "Coons_Christopher", "Cooper_Jim",
"Correa_J", "Cortez_Masto_Catherine", "Costa_Jim", "Courtney_Joe",
"Craig_Angie", "Crist_Charlie", "Crow_Jason", "Cuellar_Henry",
"Davids_Sharice", "Davis_Danny", "Dean_Madeleine", "DeFazio_Peter",
"DeGette_Diana", "DeLauro_Rosa", "DelBene_Suzan", "Delgado_Antonio",
"Demings_Val", "DeSaulnier_Mark", "Deutch_Theodore", "Dingell_Debbie",
"Doggett_Lloyd", "Doyle_Michael", "Duckworth_Tammy", "Durbin_Richard",
"Escobar_Veronica", "Eshoo_Anna", "Espaillat_Adriano", "Evans_Dwight",
"Feinstein_Dianne", "Fletcher_Lizzie", "Foster_Bill", "Frankel_Lois",
"Gallego_Ruben", "Garamendi_John", "García_Jesús", "Garcia_Sylvia",
"Golden_Jared", "Gomez_Jimmy", "Gonzalez_Vicente", "Gottheimer_Josh",
"Green_Al", "Grijalva_Raúl", "Harder_Josh", "Hassan_Margaret",
"Hayes_Jahana", "Heinrich_Martin", "Higgins_Brian", "Himes_James",
"Hirono_Mazie", "Horsford_Steven", "Houlahan_Chrissy", "Hoyer_Steny",
"Huffman_Jared", "Jackson_Lee_Sheila", "Jacobs_Sara", "Jayapal_Pramila",
"Jeffries_Hakeem", "Johnson_Eddie", "Johnson_Henry", "Kaptur_Marcy",
"Keating_William", "Kelly_Mark", "Kelly_Robin", "Khanna_Ro",
"Kildee_Daniel", "Kilmer_Derek", "Kim_Andy", "Kind_Ron", "Kirkpatrick_Ann",
"Klobuchar_Amy", "Krishnamoorthi_Raja", "Kuster_Ann", "Lamb_Conor",
"Langevin_James", "Larsen_Rick", "Larson_John", "Lawrence_Brenda",
"Lawson_Al", "Leahy_Patrick", "Lee_Barbara", "Lee_Susie", "Leger_Fernandez_Teresa",
"Levin_Andy", "Levin_Mike", "Lieu_Ted", "Lofgren_Zoe", "Lowenthal_Alan",
"Luján_Ben", "Luria_Elaine", "Lynch_Stephen", "Malinowski_Tom",
"Maloney_Carolyn", "Maloney_Sean", "Manchin_Joe", "Manning_Kathy",
"Markey_Edward", "Matsui_Doris", "McBath_Lucy", "McCollum_Betty",
"McEachin_A", "McGovern_James", "McNerney_Jerry", "Meeks_Gregory",
"Menendez_Robert", "Meng_Grace", "Merkley_Jeff", "Mfume_Kweisi",
"Moore_Gwen", "Morelle_Joseph", "Moulton_Seth", "Mrvan_Frank",
"Murphy_Stephanie", "Murray_Patty", "Nadler_Jerrold", "Napolitano_Grace",
"Neal_Richard", "Neguse_Joe", "Newman_Marie", "Norcross_Donald",
"Norton_Eleanor", "O_Halleran_Tom", "Ocasio_Cortez_Alexandria",
"Omar_Ilhan", "Ossoff_Jon", "Padilla_Alejandro", "Pallone_Frank",
"Panetta_Jimmy", "Pappas_Chris", "Pascrell_Bill", "Payne_Donald",
"Pelosi_Nancy", "Perlmutter_Ed", "Peters_Gary", "Peters_Scott",
"Phillips_Dean", "Pingree_Chellie", "Plaskett_Stacey", "Pocan_Mark",
"Porter_Katie", "Pressley_Ayanna", "Price_David", "Quigley_Mike",
"Raskin_Jamie", "Reed_John", "Rice_Kathleen", "Rosen_Jacky",
"Ross_Deborah", "Roybal_Allard_Lucille", "Ruiz_Raul", "Ruppersberger_C",
"Rush_Bobby", "Ryan_Tim", "Sablan_Gregorio", "Sánchez_Linda",
"Sarbanes_John", "Scanlon_Mary", "Schakowsky_Janice", "Schatz_Brian",
"Schiff_Adam", "Schneider_Bradley", "Schrader_Kurt", "Schrier_Kim",
"Schumer_Charles", "Scott_David", "Scott_Robert", "Sewell_Terri",
"Shaheen_Jeanne", "Shelby_Richard", "Sherman_Brad", "Sherrill_Mikie",
"Sinema_Kyrsten", "Sires_Albio", "Slotkin_Elissa", "Smith_Adam",
"Smith_Tina", "Soto_Darren", "Spanberger_Abigail", "Speier_Jackie",
"Stabenow_Debbie", "Stanton_Greg", "Stevens_Haley", "Strickland_Marilyn",
"Suozzi_Thomas", "Swalwell_Eric", "Takano_Mark", "Tester_Jon",
"Thompson_Bennie", "Thompson_Mike", "Titus_Dina", "Tlaib_Rashida",
"Tonko_Paul", "Torres_Norma", "Torres_Ritchie", "Trahan_Lori",
"Trone_David", "Underwood_Lauren", "user", "Van_Hollen_Chris",
"Vargas_Juan", "Veasey_Marc", "Vela_Filemon", "Velázquez_Nydia",
"Warner_Mark", "Warnock_Raphael", "Warren_Elizabeth", "Wasserman_Schultz_Debbie",
"Waters_Maxine", "Watson_Coleman_Bonnie", "Welch_Peter", "Wexton_Jennifer",
"Whitehouse_Sheldon", "Wild_Susan", "Williams_Nikema", "Wilson_Frederica",
"Wyden_Ron", "Yarmuth_John"), class = "factor"), Authentic = c(0.0573884758364312,
0.243029739776952, 0.112453531598513, 0.961198884758364, 0.125,
0.139869888475836, 0.131737918215613, 0.174024163568773, 0.115706319702602,
0.325046468401487, 0.223048327137546, 0.087592936802974, 0.133364312267658,
0.190985130111524, 0.21003717472119, 0.0422862453531598, 0.153113382899628,
0.263708178438662, 0.157295539033457, 0.328996282527881, 0.139637546468401,
0.48025092936803, 0.26974907063197, 0.378020446096654, 0.153113382899628,
0.454693308550186, 0.0820167286245353, 0.130576208178439, 0.33317843866171,
0.263243494423792, 0.197490706319703, 0.295074349442379, 0.251626394052045,
0.303671003717472, 0.180065055762082, 0.155204460966543, 0.10246282527881,
0.237453531598513, 0.132434944237918, 0.151022304832714, 0.10339219330855,
0.991635687732342, 0.185176579925651, 0.263475836431227, 0.0669144981412639,
0.143587360594796, 0.127788104089219, 0.212360594795539, 0.45817843866171,
0.054135687732342), Analytic = c(0.751137397634213, 0.772520473157416,
0.777070063694267, 0.802092811646951, 0.86442220200182, 0.75796178343949,
0.847133757961783, 0.873976342129208, 0.816196542311192, 0.801182893539581,
0.809827115559599, 0.695177434030937, 0.803457688808007, 0.726569608735214,
0.774795268425842, 0.843039126478617, 0.788898999090082, 0.773885350318471,
0.79936305732484, 0.78434940855323, 0.939945404913557, 0.772520473157416,
0.741128298453139, 0.736123748862602, 0.927206551410373, 0.673794358507734,
0.859872611464968, 0.763421292083712, 0.810282074613285, 0.871701546860782,
0.834849863512284, 0.786624203821656, 0.782984531392174, 1, 0.872611464968152,
0.748862602365787, 0.804367606915377, 0.79936305732484, 0.682893539581438,
0.761601455868971, 0.722929936305732, 0.767970882620564, 0.845313921747043,
0.79663330300273, 0.74294813466788, 0.840764331210191, 0.894904458598726,
0.787534121929026, 0.800272975432211, 0.883530482256597), Clout = c(0.367584745762712,
0.387358757062147, 0.748234463276836, 0.267302259887006, 0.491878531073446,
0.426906779661017, 0.518008474576271, 0.191031073446328, 0.466101694915254,
0.849223163841808, 0.545197740112994, 0.475988700564972, 0.548728813559322,
0.711511299435028, 0.538841807909604, 0.792372881355932, 0.49364406779661,
0.487641242937853, 0.64795197740113, 0.370409604519774, 0.771186440677966,
0.288488700564972, 0.211158192090395, 0.273658192090395, 0.420197740112994,
1, 0.531779661016949, 0.629237288135593, 0.646539548022599, 0.208686440677966,
0.189618644067797, 0.92090395480226, 0.632415254237288, 0.965042372881356,
0.34180790960452, 0.392302259887005, 0.604166666666666, 0.548375706214689,
0.401836158192091, 0.415254237288136, 0.364759887005649, 0.332980225988701,
0.354519774011299, 0.346398305084746, 0.52295197740113, 0.453389830508474,
0.777189265536723, 0.332980225988701, 0.436087570621469, 0.387358757062147
), Tone = c(0.953877551020408, 0.791836734693877, 0.583469387755102,
0.49765306122449, 0.971122448979592, 0.994183673469388, 0.626836734693878,
0.893061224489796, 0.34469387755102, 0.68530612244898, 0.970204081632653,
0.698265306122449, 0.959795918367347, 0.379183673469388, 0.988469387755102,
0.930408163265306, 0.0593877551020408, 0.744897959183674, 0.884387755102041,
0.803367346938776, 0.659285714285714, 0.422244897959184, 0.283571428571429,
0.252755102040816, 0.926530612244898, 0.988265306122449, 0.76469387755102,
0.525408163265306, 0.817040816326531, 0.891428571428571, 0.81265306122449,
0.451632653061224, 0.654285714285714, 0.727244897959184, 0.974591836734694,
0.467448979591837, 0.798775510204082, 0.501122448979592, 0.919795918367347,
0.744897959183674, 0.83234693877551, 0.931224489795918, 0.866326530612245,
0.448673469387755, 0.766530612244898, 0.326734693877551, 0.847959183673469,
0.685204081632653, 0.78765306122449, 0.847755102040816)), row.names = 2:51, class = "data.frame")
</code>```

答:
Here is a solution:</p>
```<code>library(tidyverse)
crossing(data, user2 = data$user) %>%
  filter(user != user2) %>%
  left_join(data, by = c("user2" = "user")) %>%
  transmute(
    from = user,
    to = user2,
    Authentic_diff = Authentic.y - Authentic.x,
    Analytic_diff =  Analytic.y - Analytic.x,
    Clout_diff = Clout.y - Clout.x,
    Tone_diff = Tone.y - Tone.x

  )

</code>```

Body:
I have a large dataframe with users scores on a number of language dimensions, with a simplified version looking like the code below (I have included a dput replication data at the bottom of the post)

    user             Authentic   Analytic    Clout       Tone
2   Adams_Alma       0.05738848  0.7511374  0.3675847   0.95387755
3   Aguilar_Pete     0.24302974  0.7725205  0.3873588   0.79183673
4   Allred_Colin     0.11245353  0.7770701  0.7482345   0.58346939
5   Auchincloss_Jake 0.96119888  0.8020928  0.2673023   0.49765306
6   Axne_Cynthia     0.12500000  0.8644222  0.4918785   0.97112245

Using this data, I want to create a dataframe in which each row is the difference score of between a pair of users in the dataset, as seen below (though the actual dataframe is much larger).

    from        to                 diff_Authentic   diff_Analytic  diff_Clout  diff_Tone
1   Adams_Alma  Aguilar_Pete       0.9802260        0.123456       0.123456    0.123456
2   Adams_Alma  Allred_Colin       0.6193503        0.123456       0.123456    0.123456
3   Adams_Alma  Auchincloss_Jake   0.8997175        0.123456       0.123456    0.123456
4   Adams_Alma  Axne_Cynthia       0.8757062        0.123456       0.123456    0.123456
5   Adams_Alma  Baldwin_Tammy      0.9406780        0.123456       0.123456    0.123456
6   Adams_Alma  Barragán_Nanette   0.8495763        0.123456       0.123456    0.123456
7   Adams_Alma  Bass_Karen         0.8234463        0.123456       0.123456    0.123456
8   Adams_Alma  Beatty_Joyce       0.9014831        0.123456       0.123456    0.123456
9   Adams_Alma  Bennet_Michael     0.5183616        0.123456       0.123456    0.123456
10  Adams_Alma  Bera_Ami           0.8223870        0.123456       0.123456    0.123456

Using the code below, I am able to create a difference edgelist for one variable at a time, but my full dataframe has 90 variables I want differences for.

out <- with(norm_data, as.matrix(dist(setNames(norm_data$Authentic, norm_data$user))))
dif_g <- graph_from_adjacency_matrix (out, mode = 'undirected', weighted = TRUE)
dif_edge_list <- as_data_frame(dif_g, 'edges')
dif_edge_list$weight <- 1 - dif_edge_list$weight

I would like to have a single dataframe that has the difference scores for each pair of users across all variables. I'm assuming a loop might be the solution, but I can't figure out how to do this. Any help would be greatly appreciated. Let me know if you need any more info.

Dput Data:

Show in New WindowClear OutputExpand/Collapse Output
structure(list(user = structure(1:50, .Label = c("Adams_Alma",
"Aguilar_Pete", "Allred_Colin", "Auchincloss_Jake", "Axne_Cynthia",
"Baldwin_Tammy", "Barragán_Nanette", "Bass_Karen", "Beatty_Joyce",
"Bennet_Michael", "Bera_Ami", "Beyer_Donald", "Bishop_Sanford",
"Blumenthal_Richard", "Blunt_Rochester_Lisa", "Bonamici_Suzanne",
"Booker_Cory", "Bourdeaux_Carolyn", "Bowman_Jamaal", "Boyle_Brendan",
"Brown_Anthony", "Brown_Sherrod", "Brownley_Julia", "Bush_Cori",
"Bustos_Cheri", "Butterfield_George", "Cantwell_Maria", "Carbajal_Salud",
"Cárdenas_Tony", "Cardin_Benjamin", "Carper_Thomas", "Carson_André",
"Cartwright_Matthew", "Case_Ed", "Casey_Robert", "Casten_Sean",
"Castor_Kathy", "Castro_Joaquin", "Chu_Judy", "Cicilline_David",
"Clark_Katherine", "Clarke_Yvette", "Cleaver_Emanuel", "Clyburn_James",
"Cohen_Steve", "Connolly_Gerald", "Coons_Christopher", "Cooper_Jim",
"Correa_J", "Cortez_Masto_Catherine", "Costa_Jim", "Courtney_Joe",
"Craig_Angie", "Crist_Charlie", "Crow_Jason", "Cuellar_Henry",
"Davids_Sharice", "Davis_Danny", "Dean_Madeleine", "DeFazio_Peter",
"DeGette_Diana", "DeLauro_Rosa", "DelBene_Suzan", "Delgado_Antonio",
"Demings_Val", "DeSaulnier_Mark", "Deutch_Theodore", "Dingell_Debbie",
"Doggett_Lloyd", "Doyle_Michael", "Duckworth_Tammy", "Durbin_Richard",
"Escobar_Veronica", "Eshoo_Anna", "Espaillat_Adriano", "Evans_Dwight",
"Feinstein_Dianne", "Fletcher_Lizzie", "Foster_Bill", "Frankel_Lois",
"Gallego_Ruben", "Garamendi_John", "García_Jesús", "Garcia_Sylvia",
"Golden_Jared", "Gomez_Jimmy", "Gonzalez_Vicente", "Gottheimer_Josh",
"Green_Al", "Grijalva_Raúl", "Harder_Josh", "Hassan_Margaret",
"Hayes_Jahana", "Heinrich_Martin", "Higgins_Brian", "Himes_James",
"Hirono_Mazie", "Horsford_Steven", "Houlahan_Chrissy", "Hoyer_Steny",
"Huffman_Jared", "Jackson_Lee_Sheila", "Jacobs_Sara", "Jayapal_Pramila",
"Jeffries_Hakeem", "Johnson_Eddie", "Johnson_Henry", "Kaptur_Marcy",
"Keating_William", "Kelly_Mark", "Kelly_Robin", "Khanna_Ro",
"Kildee_Daniel", "Kilmer_Derek", "Kim_Andy", "Kind_Ron", "Kirkpatrick_Ann",
"Klobuchar_Amy", "Krishnamoorthi_Raja", "Kuster_Ann", "Lamb_Conor",
"Langevin_James", "Larsen_Rick", "Larson_John", "Lawrence_Brenda",
"Lawson_Al", "Leahy_Patrick", "Lee_Barbara", "Lee_Susie", "Leger_Fernandez_Teresa",
"Levin_Andy", "Levin_Mike", "Lieu_Ted", "Lofgren_Zoe", "Lowenthal_Alan",
"Luján_Ben", "Luria_Elaine", "Lynch_Stephen", "Malinowski_Tom",
"Maloney_Carolyn", "Maloney_Sean", "Manchin_Joe", "Manning_Kathy",
"Markey_Edward", "Matsui_Doris", "McBath_Lucy", "McCollum_Betty",
"McEachin_A", "McGovern_James", "McNerney_Jerry", "Meeks_Gregory",
"Menendez_Robert", "Meng_Grace", "Merkley_Jeff", "Mfume_Kweisi",
"Moore_Gwen", "Morelle_Joseph", "Moulton_Seth", "Mrvan_Frank",
"Murphy_Stephanie", "Murray_Patty", "Nadler_Jerrold", "Napolitano_Grace",
"Neal_Richard", "Neguse_Joe", "Newman_Marie", "Norcross_Donald",
"Norton_Eleanor", "O_Halleran_Tom", "Ocasio_Cortez_Alexandria",
"Omar_Ilhan", "Ossoff_Jon", "Padilla_Alejandro", "Pallone_Frank",
"Panetta_Jimmy", "Pappas_Chris", "Pascrell_Bill", "Payne_Donald",
"Pelosi_Nancy", "Perlmutter_Ed", "Peters_Gary", "Peters_Scott",
"Phillips_Dean", "Pingree_Chellie", "Plaskett_Stacey", "Pocan_Mark",
"Porter_Katie", "Pressley_Ayanna", "Price_David", "Quigley_Mike",
"Raskin_Jamie", "Reed_John", "Rice_Kathleen", "Rosen_Jacky",
"Ross_Deborah", "Roybal_Allard_Lucille", "Ruiz_Raul", "Ruppersberger_C",
"Rush_Bobby", "Ryan_Tim", "Sablan_Gregorio", "Sánchez_Linda",
"Sarbanes_John", "Scanlon_Mary", "Schakowsky_Janice", "Schatz_Brian",
"Schiff_Adam", "Schneider_Bradley", "Schrader_Kurt", "Schrier_Kim",
"Schumer_Charles", "Scott_David", "Scott_Robert", "Sewell_Terri",
"Shaheen_Jeanne", "Shelby_Richard", "Sherman_Brad", "Sherrill_Mikie",
"Sinema_Kyrsten", "Sires_Albio", "Slotkin_Elissa", "Smith_Adam",
"Smith_Tina", "Soto_Darren", "Spanberger_Abigail", "Speier_Jackie",
"Stabenow_Debbie", "Stanton_Greg", "Stevens_Haley", "Strickland_Marilyn",
"Suozzi_Thomas", "Swalwell_Eric", "Takano_Mark", "Tester_Jon",
"Thompson_Bennie", "Thompson_Mike", "Titus_Dina", "Tlaib_Rashida",
"Tonko_Paul", "Torres_Norma", "Torres_Ritchie", "Trahan_Lori",
"Trone_David", "Underwood_Lauren", "user", "Van_Hollen_Chris",
"Vargas_Juan", "Veasey_Marc", "Vela_Filemon", "Velázquez_Nydia",
"Warner_Mark", "Warnock_Raphael", "Warren_Elizabeth", "Wasserman_Schultz_Debbie",
"Waters_Maxine", "Watson_Coleman_Bonnie", "Welch_Peter", "Wexton_Jennifer",
"Whitehouse_Sheldon", "Wild_Susan", "Williams_Nikema", "Wilson_Frederica",
"Wyden_Ron", "Yarmuth_John"), class = "factor"), Authentic = c(0.0573884758364312,
0.243029739776952, 0.112453531598513, 0.961198884758364, 0.125,
0.139869888475836, 0.131737918215613, 0.174024163568773, 0.115706319702602,
0.325046468401487, 0.223048327137546, 0.087592936802974, 0.133364312267658,
0.190985130111524, 0.21003717472119, 0.0422862453531598, 0.153113382899628,
0.263708178438662, 0.157295539033457, 0.328996282527881, 0.139637546468401,
0.48025092936803, 0.26974907063197, 0.378020446096654, 0.153113382899628,
0.454693308550186, 0.0820167286245353, 0.130576208178439, 0.33317843866171,
0.263243494423792, 0.197490706319703, 0.295074349442379, 0.251626394052045,
0.303671003717472, 0.180065055762082, 0.155204460966543, 0.10246282527881,
0.237453531598513, 0.132434944237918, 0.151022304832714, 0.10339219330855,
0.991635687732342, 0.185176579925651, 0.263475836431227, 0.0669144981412639,
0.143587360594796, 0.127788104089219, 0.212360594795539, 0.45817843866171,
0.054135687732342), Analytic = c(0.751137397634213, 0.772520473157416,
0.777070063694267, 0.802092811646951, 0.86442220200182, 0.75796178343949,
0.847133757961783, 0.873976342129208, 0.816196542311192, 0.801182893539581,
0.809827115559599, 0.695177434030937, 0.803457688808007, 0.726569608735214,
0.774795268425842, 0.843039126478617, 0.788898999090082, 0.773885350318471,
0.79936305732484, 0.78434940855323, 0.939945404913557, 0.772520473157416,
0.741128298453139, 0.736123748862602, 0.927206551410373, 0.673794358507734,
0.859872611464968, 0.763421292083712, 0.810282074613285, 0.871701546860782,
0.834849863512284, 0.786624203821656, 0.782984531392174, 1, 0.872611464968152,
0.748862602365787, 0.804367606915377, 0.79936305732484, 0.682893539581438,
0.761601455868971, 0.722929936305732, 0.767970882620564, 0.845313921747043,
0.79663330300273, 0.74294813466788, 0.840764331210191, 0.894904458598726,
0.787534121929026, 0.800272975432211, 0.883530482256597), Clout = c(0.367584745762712,
0.387358757062147, 0.748234463276836, 0.267302259887006, 0.491878531073446,
0.426906779661017, 0.518008474576271, 0.191031073446328, 0.466101694915254,
0.849223163841808, 0.545197740112994, 0.475988700564972, 0.548728813559322,
0.711511299435028, 0.538841807909604, 0.792372881355932, 0.49364406779661,
0.487641242937853, 0.64795197740113, 0.370409604519774, 0.771186440677966,
0.288488700564972, 0.211158192090395, 0.273658192090395, 0.420197740112994,
1, 0.531779661016949, 0.629237288135593, 0.646539548022599, 0.208686440677966,
0.189618644067797, 0.92090395480226, 0.632415254237288, 0.965042372881356,
0.34180790960452, 0.392302259887005, 0.604166666666666, 0.548375706214689,
0.401836158192091, 0.415254237288136, 0.364759887005649, 0.332980225988701,
0.354519774011299, 0.346398305084746, 0.52295197740113, 0.453389830508474,
0.777189265536723, 0.332980225988701, 0.436087570621469, 0.387358757062147
), Tone = c(0.953877551020408, 0.791836734693877, 0.583469387755102,
0.49765306122449, 0.971122448979592, 0.994183673469388, 0.626836734693878,
0.893061224489796, 0.34469387755102, 0.68530612244898, 0.970204081632653,
0.698265306122449, 0.959795918367347, 0.379183673469388, 0.988469387755102,
0.930408163265306, 0.0593877551020408, 0.744897959183674, 0.884387755102041,
0.803367346938776, 0.659285714285714, 0.422244897959184, 0.283571428571429,
0.252755102040816, 0.926530612244898, 0.988265306122449, 0.76469387755102,
0.525408163265306, 0.817040816326531, 0.891428571428571, 0.81265306122449,
0.451632653061224, 0.654285714285714, 0.727244897959184, 0.974591836734694,
0.467448979591837, 0.798775510204082, 0.501122448979592, 0.919795918367347,
0.744897959183674, 0.83234693877551, 0.931224489795918, 0.866326530612245,
0.448673469387755, 0.766530612244898, 0.326734693877551, 0.847959183673469,
0.685204081632653, 0.78765306122449, 0.847755102040816)), row.names = 2:51, class = "data.frame")

Body:
Here is a solution:

library(tidyverse)
crossing(data, user2 = data$user) %>%
  filter(user != user2) %>%
  left_join(data, by = c("user2" = "user")) %>%
  transmute(
    from = user,
    to = user2,
    Authentic_diff = Authentic.y - Authentic.x,
    Analytic_diff =  Analytic.y - Analytic.x,
    Clout_diff = Clout.y - Clout.x,
    Tone_diff = Tone.y - Tone.x

  )


问:
Docker: The framework 'Microsoft.WindowsDesktop.App', version '3.1.0' (x64) was not found
I have an existing dotnet core 3.1 web app that builds and deploys to an azure app service.  it works fine.   I am trying to containerize the app.

the build is fine, but when the container runs it gives me

```<code>It was not possible to find any compatible framework version
The framework 'Microsoft.WindowsDesktop.App', version '3.1.0' (x64) was not found.
  - No frameworks were found.
You can resolve the problem by installing the specified framework and/or SDK.
</code>```

my docker

```<code>FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /source

# copy csproj and restore as distinct layers
COPY myreports/*.csproj .

RUN dotnet restore

# copy and publish app and libraries
COPY . .
RUN dotnet publish -c release -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/runtime:6.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "myreports.dll"]
</code>```

I've tried a variety of docker images(inc dotnet/core) and its the same.
my csproj

```<code><Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>myreports</RootNamespace>
    <UserSecretsId>ed68b972-ed89-4115-8e6c-5f0d032efa4d</UserSecretsId>
    <DockerDefaultTargetOS>Windows</DockerDefaultTargetOS>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Azure.Storage.Blobs" Version="12.8.0" />
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.PerfCounterCollector" Version="2.16.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.9" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.9">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <!--PackageReference Include="Microsoft.Extensions.Logging.ApplicationInsights" Version="2.14.0" /-->
    <PackageReference Include="Microsoft.AspNetCore.AzureAppServices.HostingStartup" Version="3.1.9" />
    <PackageReference Include="Microsoft.Azure.EventGrid" Version="3.0.0" />
    <PackageReference Include="Microsoft.Azure.Management.ResourceManager" Version="1.6.0-preview" />
    <PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="4.5.0" />
    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.14.0" />
  </ItemGroup>
</Project>
</code>```

I suspect its this
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />

But its required as its core to the project.   What gets me is that my config in the (working) app settings is:

答:
Your project is targeting .NET Core 3.1 but your Dockerfile is referencing 6.0 tags, which refers to .NET 6. A .NET Core 3.1 app won't be able to run in a 6.0 runtime container. You should update your Dockerfile to reference 3.1 instead of 6.0.

Update

Since there's also a dependency on the Microsoft.WindowsDesktop.App framework, you'll need to manually add that framework into the runtime. By default, the runtime image only contains the Microsoft.NETCore.App.

However, the sdk image does contain the Microsoft.WindowsDesktop.App framework. This allows you to use an sdk container to build a project that has a Microsoft.WindowsDesktop.App framework dependency. You just can't run, by default, in the runtime container because it's very atypical to run an app in a container that has such a dependency.

What this all means is that you can copy the Microsoft.WindowsDesktop.App framework from the sdk to the runtime container which should resolve your issue. I've updated your Dockerfile to include COPY instruction which does this:

```<code>FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
WORKDIR /source

# copy csproj and restore as distinct layers
COPY myreports/*.csproj .

RUN dotnet restore

# copy and publish app and libraries
COPY . .
RUN dotnet publish -c release -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/runtime:3.1
COPY --from=build ["C:/Program Files/dotnet/shared/Microsoft.WindowsDesktop.App", "C:/Program Files/dotnet/shared/Microsoft.WindowsDesktop.App/"]
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "myreports.dll"]
</code>```

Body:
I have an existing dotnet core 3.1 web app that builds and deploys to an azure app service.  it works fine.   I am trying to containerize the app.

the build is fine, but when the container runs it gives me

It was not possible to find any compatible framework version
The framework 'Microsoft.WindowsDesktop.App', version '3.1.0' (x64) was not found.
  - No frameworks were found.
You can resolve the problem by installing the specified framework and/or SDK.

my docker

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /source

# copy csproj and restore as distinct layers
COPY myreports/*.csproj .

RUN dotnet restore

# copy and publish app and libraries
COPY . .
RUN dotnet publish -c release -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/runtime:6.0
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "myreports.dll"]

I've tried a variety of docker images(inc dotnet/core) and its the same.
my csproj

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <RootNamespace>myreports</RootNamespace>
    <UserSecretsId>ed68b972-ed89-4115-8e6c-5f0d032efa4d</UserSecretsId>
    <DockerDefaultTargetOS>Windows</DockerDefaultTargetOS>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Azure.Storage.Blobs" Version="12.8.0" />
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />
    <PackageReference Include="Microsoft.ApplicationInsights" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.16.0" />
    <PackageReference Include="Microsoft.ApplicationInsights.PerfCounterCollector" Version="2.16.0" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.9" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="3.1.9" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="3.1.9">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>

    <PackageReference Include="Microsoft.AspNetCore.AzureAppServices.HostingStartup" Version="3.1.9" />
    <PackageReference Include="Microsoft.Azure.EventGrid" Version="3.0.0" />
    <PackageReference Include="Microsoft.Azure.Management.ResourceManager" Version="1.6.0-preview" />
    <PackageReference Include="Microsoft.IdentityModel.Clients.ActiveDirectory" Version="4.5.0" />
    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.14.0" />
  </ItemGroup>
</Project>

I suspect its this
    <PackageReference Include="FastReport.Core3.Web" Version="2021.3.0" />

But its required as its core to the project.   What gets me is that my config in the (working) app settings is:

Body:
Your project is targeting .NET Core 3.1 but your Dockerfile is referencing 6.0 tags, which refers to .NET 6. A .NET Core 3.1 app won't be able to run in a 6.0 runtime container. You should update your Dockerfile to reference 3.1 instead of 6.0.

Update

Since there's also a dependency on the Microsoft.WindowsDesktop.App framework, you'll need to manually add that framework into the runtime. By default, the runtime image only contains the Microsoft.NETCore.App.

However, the sdk image does contain the Microsoft.WindowsDesktop.App framework. This allows you to use an sdk container to build a project that has a Microsoft.WindowsDesktop.App framework dependency. You just can't run, by default, in the runtime container because it's very atypical to run an app in a container that has such a dependency.

What this all means is that you can copy the Microsoft.WindowsDesktop.App framework from the sdk to the runtime container which should resolve your issue. I've updated your Dockerfile to include COPY instruction which does this:

FROM mcr.microsoft.com/dotnet/sdk:3.1 AS build
WORKDIR /source

# copy csproj and restore as distinct layers
COPY myreports/*.csproj .

RUN dotnet restore

# copy and publish app and libraries
COPY . .
RUN dotnet publish -c release -o /app

# final stage/image
FROM mcr.microsoft.com/dotnet/runtime:3.1
COPY --from=build ["C:/Program Files/dotnet/shared/Microsoft.WindowsDesktop.App", "C:/Program Files/dotnet/shared/Microsoft.WindowsDesktop.App/"]
WORKDIR /app
COPY --from=build /app .
ENTRYPOINT ["dotnet", "myreports.dll"]


答:
I've sketched out a recursive function that might suit:

def nd_list(n, x=None):
    if x is None:
        x = n
    if x == 1:
        return [n] * n
    return [nd_list(n, x-1)] * n
```
<hr />
<p>In two lines using no external libraries!</p>
<pre class="lang-py prettyprint-override"><code>def nd_list(x, z):
    return [z] * z if x == 1 else [nd_list(x-1, z)] * z
</code>```

In two lines (just) and without the list of lists surprising behaviour:

def nd_list(x, z):
    return [0 for _ in range(z)] if x == 1 else [nd_list(x-1, z) for _ in range(z)]
```

Title: Is it possible to define function that creates an N-dimensional list of lists easily?

Body:
I have searched and found these questions: How to create a multi-dimensional list and N dimensional array in python which hint toward what I am looking for, but they seem to only make 2D arrays and not ND arrays.

Problem:

My problem is that I am able to create an n-dimensional list of lists for a known n, but I am not sure how it can be generalized to work with all values of n.

Consider this example:

def makeList(n):
    return [[[n for _ in range(n)]
                for _ in range(n)]
                for _ in range(n)]
print(makeList(3))

Output:

[[[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]],
 [[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]],
 [[3, 3, 3],
  [3, 3, 3],
  [3, 3, 3]]]

This will create a list of lists that is a 3x3x3 array of 3's which is the intended result, but if we use a different n:

print(makeList(2))

Output:

[[[2, 2],
  [2, 2]],
 [[2, 2],
  [2, 2]]]

This will create a list of lists that is a 2x2x0 array of 2's and this is not the intended result. Instead the results should be a list of lists that is a 2x2 array of 2's.

Likewise if we set n = 4:

print(makeList(4))

This will give a list of lists that is 4x4x4 when it should give a 4x4x4x4 list of lists.

The main issue is that the number of for loops must change depending on the input, but obviously the code can't "come to life" and recode itself magically, hence my issue.

I am looking for a way to get this result that is simple. I am sure I could continue developing ideas for solutions, but I have not been able to think of anything that is concise.

What I have tried:

The first idea I thought of was to use recursion, and this my simple approach:

def makeList(n, output = []):
    if not output:
        output = [n for _ in range(n)]
    else:
        output = [output for _ in range(n)]
    if len(output) == n:
        return output
    else:
        return makeList(n, output)

This obviously will not work because if len(output) == n: will execute the first iteration since the length of the inner loops is equal to the length of the outermost loop. However, even if there was a condition that properly terminated the function, this solution would still not be ideal because I could run into maximum recursion errors with large values of n. Furthermore, even if these issues were resolved this code is still quite long as well as time consuming.

The other potential perspective I considered (and the solution that I found that works) is using a dict. My solution saves the intermediate lists of lists in a dict so it can be used for the next iteration:

def makeList(n):
    d = {str(i): None for i in range(n)}
    for i in range(n):
        if i == 0:
            d[str(i)] = [n for _ in range(n)]
        else:
            d[str(i)] = [d[str(i-1)] for _ in range(n)]
    return d[str(n-1)]

But again, this is very long and doesn't seem very pythonic.

Solution requirements:

The ideal solution would be much more concise than mine with an efficient time complexity that only uses built-in functions.

Other options that are close to these requirements would also be helpful as long as the spirit of the answer is trying to best meet the requirements.

Being concise is the most important aspect, however, which is why I am not fully happy with my current attempts.

Body:
I've sketched out a recursive function that might suit:

def nd_list(n, x=None):
    if x is None:
        x = n
    if x == 1:
        return [n] * n
    return [nd_list(n, x-1)] * n

In two lines using no external libraries!

def nd_list(x, z):
    return [z] * z if x == 1 else [nd_list(x-1, z)] * z

In two lines (just) and without the list of lists surprising behaviour:

def nd_list(x, z):
    return [0 for _ in range(z)] if x == 1 else [nd_list(x-1, z) for _ in range(z)]