问:
why can i place the location of this button
the button wont go to postion i set it to when i run it could i get a little help please?</p>

```<code>import tkinter
newbw=tkinter.Tk()

def hub():
    newbw.destroy()
    newbw=tkinter.Tk()
    newbw.attributes('-fullscreen', True)
    a=tkinter.Button(newbw, text="demonfight", command=dfpre)
    b=tkinter.Button(newbw, text="shop", command=shop)
    c=tkinter.Button(newbw, text="train", command=trainhub)
    d=tkinter.Button(newbw, text="quit", command=end)
    d.place(x=20, y=20)
    a.pack()
    b.pack()
    c.pack()
    d.pack()
</code>```

答:
There are three geometry managers: pack, grid, and place.  Using one of them is known as mapping a widget.

Pack and grid cannot be mixed. It's one or the other.
Place can be mixed with pack or grid, but it's really (in my opinion) the last choice because placed widgets are not detected by the outer frame when it autosizes.
So, because of the above, you were able to mix pack with place and not get an error.

Once you map something with a geometry manager, can you unmap and remap it. So, your first call to d.place() places the d widget. But then your second call to d.pack() overrides the place() and then packs the widget.

Because the default for pack() is side='top', you'll see your four widgets stacked, with  a on top, down to d on the bottom.

Also, your app doesn't work right because you create a function hub(), but you never call it.  Add:

```<code>if __name__ == '__main__':
    hub()
</code>```

to the bottom of your program.

So, although your posted code is incomplete, try something more like this:

```<code>import tkinter

def hub():
    newbw=tkinter.Tk()
    newbw.attributes('-fullscreen', True)
    a=tkinter.Button(newbw, text="demonfight", command=dfpre)
    b=tkinter.Button(newbw, text="shop", command=shop)
    c=tkinter.Button(newbw, text="train", command=trainhub)
    d=tkinter.Button(newbw, text="quit", command=end)
    #  d.place(x=20, y=20)
    a.pack()
    b.pack()
    c.pack()
    d.pack()

if __name__ == '__main__':
    hub()
</code>```

Body:
the button wont go to postion i set it to when i run it could i get a little help please?

import tkinter
newbw=tkinter.Tk()

def hub():
    newbw.destroy()
    newbw=tkinter.Tk()
    newbw.attributes('-fullscreen', True)
    a=tkinter.Button(newbw, text="demonfight", command=dfpre)
    b=tkinter.Button(newbw, text="shop", command=shop)
    c=tkinter.Button(newbw, text="train", command=trainhub)
    d=tkinter.Button(newbw, text="quit", command=end)
    d.place(x=20, y=20)
    a.pack()
    b.pack()
    c.pack()
    d.pack()

Body:
There are three geometry managers: pack, grid, and place.  Using one of them is known as mapping a widget.

Pack and grid cannot be mixed. It's one or the other.
Place can be mixed with pack or grid, but it's really (in my opinion) the last choice because placed widgets are not detected by the outer frame when it autosizes.
So, because of the above, you were able to mix pack with place and not get an error.

Once you map something with a geometry manager, can you unmap and remap it. So, your first call to d.place() places the d widget. But then your second call to d.pack() overrides the place() and then packs the widget.

Because the default for pack() is side='top', you'll see your four widgets stacked, with  a on top, down to d on the bottom.

Also, your app doesn't work right because you create a function hub(), but you never call it.  Add:

if __name__ == '__main__':
    hub()

to the bottom of your program.

So, although your posted code is incomplete, try something more like this:

import tkinter

def hub():
    newbw=tkinter.Tk()
    newbw.attributes('-fullscreen', True)
    a=tkinter.Button(newbw, text="demonfight", command=dfpre)
    b=tkinter.Button(newbw, text="shop", command=shop)
    c=tkinter.Button(newbw, text="train", command=trainhub)
    d=tkinter.Button(newbw, text="quit", command=end)
    #  d.place(x=20, y=20)
    a.pack()
    b.pack()
    c.pack()
    d.pack()

if __name__ == '__main__':
    hub()


来源: stackexchange

问:
Generating waveforms with ChiselTest framework
I have a ChiselTest tester written as follows:

```<code>class EccTester extends FlatSpec with ChiselScalatestTester with Matchers {
    behavior of "Testers2"
  it should "send data without errors" in {
    test(new EccPair(width=8)) {
      c => {
        val rnd = new Random()
        for (i <- 0 to 20) {
          val testVal = rnd.nextInt(1 << c.getWidthParam)

          c.io.dataIn.poke(testVal.U)
          c.io.errorLocation.poke(0.U)
          c.io.injectError.poke(false.B)
          c.io.injectSecondError.poke(false.B)
          c.clock.step(1)
          c.io.dataOut.expect(testVal.U)
          c.io.outputNotEqual.expect(false.B)
        }
      }
    }
  }
}
</code>```

I am able to run the test in the shell with

testOnly chisel.lib.ecc.EccTester

But when I try to generate waveforms per the ChiselTest documentation,

testOnly chisel.lib.ecc.EccTester -- -DvwriteVcd=1

The test executes OK but does not dump a waveform.

Documentation I referenced is https://github.com/ucb-bar/chisel-testers2, and the full source code is at https://github.com/hutch31/ip-contributions/blob/ecc/src/test/scala/chisel/lib/ecc/EccTester.scala

答:
I don’t think there is a formal answer to this yet, but here’s what I do. First I add the two following imports.

```<code>import chiseltest.experimental.TestOptionBuilder._
import chiseltest.internal.WriteVcdAnnotation
</code>```

then add the annotation to the test like this

```<code>  it should "send data without errors" in {
    test(new EccPair(width=8)).withAnnotations(Seq(WriteVcdAnnotation)) {
      c => {
</code>```

Note: there are two definitions of WriteVcdAnnotation, one is in package treadle
and the other is in package chiseltest.internal. Use the latter, as it will work
for both treadle and verilator backends.

ContentLicense: CC BY-SA 4.0

Body:
I have a ChiselTest tester written as follows:

class EccTester extends FlatSpec with ChiselScalatestTester with Matchers {
    behavior of "Testers2"
  it should "send data without errors" in {
    test(new EccPair(width=8)) {
      c => {
        val rnd = new Random()
        for (i <- 0 to 20) {
          val testVal = rnd.nextInt(1 << c.getWidthParam)

          c.io.dataIn.poke(testVal.U)
          c.io.errorLocation.poke(0.U)
          c.io.injectError.poke(false.B)
          c.io.injectSecondError.poke(false.B)
          c.clock.step(1)
          c.io.dataOut.expect(testVal.U)
          c.io.outputNotEqual.expect(false.B)
        }
      }
    }
  }
}

I am able to run the test in the shell with

testOnly chisel.lib.ecc.EccTester

But when I try to generate waveforms per the ChiselTest documentation,

testOnly chisel.lib.ecc.EccTester -- -DvwriteVcd=1

The test executes OK but does not dump a waveform.

Documentation I referenced is https://github.com/ucb-bar/chisel-testers2, and the full source code is at https://github.com/hutch31/ip-contributions/blob/ecc/src/test/scala/chisel/lib/ecc/EccTester.scala

Body:
I don’t think there is a formal answer to this yet, but here’s what I do. First I add the two following imports.

import chiseltest.experimental.TestOptionBuilder._
import chiseltest.internal.WriteVcdAnnotation

then add the annotation to the test like this

  it should "send data without errors" in {
    test(new EccPair(width=8)).withAnnotations(Seq(WriteVcdAnnotation)) {
      c => {

Note: there are two definitions of WriteVcdAnnotation, one is in package treadle
and the other is in package chiseltest.internal. Use the latter, as it will work
for both treadle and verilator backends.


问:
loop over table to set the background css
My HTML table has some classes and table tag is used

Want to retain the classes as is, but all my table and tr , th or td are using td bgcolor which is an old technique.

I want to loop over the table and find if that bgcolor is defined, use the same color and convert it to a css based background color so i can print it in IE

```<code>function setBackground() {

var table = document.getElementById("table1");

//i found this in a previous stack overflow answer and tried it

for (var i = 0, row; row = table.rows[i]; i++) {

   for (var j = 0, col; col = row.cells[j]; j++) {

  //this is for debugging purposes... I can't even get this to work
   alert(table.rows[i].cells[j]);

   table.rows[i].cells[j].style.background = "orange"; //just an example

    }
 }
}
</code>```

because IE is not able to print the background lines and colors for some reason using the webkit property

答:
I cleaned up the for loops a little. You can read the attribute with getAttribute and set the style.

var table = document.getElementById("table1");
for (var i = 0; i < table.rows.length; i++) {
  var row = table.rows[i]
  for (var j = 0; j < row.cells.length; j++) {
    var cell = row.cells[j]
    var bgc = cell.getAttribute('bgcolor')
    if (bgc) {
      cell.style.background = bgc
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>td {
  width: 30px; height: 30px;
}</code>```

```
</div>
</div>
</p>

<p>You can just do it with one loop with getElementsByTagName</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var tds = document.getElementById("table1").getElementsByTagName("td");
for (var i = 0; i < tds.length; i++) {
  var cell = tds[i]
  var bgc = cell.getAttribute('bgcolor')
  if (bgc) {
    cell.style.background = bgc
  }
}</code>```

td {
  width: 30px; height: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="table1">
  <tr>
    <td bgcolor="red"></td>
    <td></td>
    <td bgcolor="blue"></td>
  </tr>
  <tr>
    <td></td>
    <td bgcolor="green"></td>
    <td></td>
  </tr>
  <tr>
    <td bgcolor="yellow"></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td bgcolor="silver"></td>
    <td></td>
    <td></td>
  </tr>
</table></code>```

Body:
My HTML table has some classes and table tag is used

Want to retain the classes as is, but all my table and tr , th or td are using td bgcolor which is an old technique.

I want to loop over the table and find if that bgcolor is defined, use the same color and convert it to a css based background color so i can print it in IE

function setBackground() {

var table = document.getElementById("table1");

//i found this in a previous stack overflow answer and tried it

for (var i = 0, row; row = table.rows[i]; i++) {

   for (var j = 0, col; col = row.cells[j]; j++) {

  //this is for debugging purposes... I can't even get this to work
   alert(table.rows[i].cells[j]);

   table.rows[i].cells[j].style.background = "orange"; //just an example

    }
 }
}

because IE is not able to print the background lines and colors for some reason using the webkit property

Body:
I cleaned up the for loops a little. You can read the attribute with getAttribute and set the style.

var table = document.getElementById("table1");
for (var i = 0; i < table.rows.length; i++) {
  var row = table.rows[i]
  for (var j = 0; j < row.cells.length; j++) {
    var cell = row.cells[j]
    var bgc = cell.getAttribute('bgcolor')
    if (bgc) {
      cell.style.background = bgc
    }
  }
}

td {
  width: 30px; height: 30px;
}

<table id="table1">
  <tr>
    <td bgcolor="red"></td>
    <td></td>
    <td bgcolor="blue"></td>
  </tr>
  <tr>
    <td></td>
    <td bgcolor="green"></td>
    <td></td>
  </tr>
  <tr>
    <td bgcolor="yellow"></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td bgcolor="silver"></td>
    <td></td>
    <td></td>
  </tr>
</table>

You can just do it with one loop with getElementsByTagName

var tds = document.getElementById("table1").getElementsByTagName("td");
for (var i = 0; i < tds.length; i++) {
  var cell = tds[i]
  var bgc = cell.getAttribute('bgcolor')
  if (bgc) {
    cell.style.background = bgc
  }
}

td {
  width: 30px; height: 30px;
}

<table id="table1">
  <tr>
    <td bgcolor="red"></td>
    <td></td>
    <td bgcolor="blue"></td>
  </tr>
  <tr>
    <td></td>
    <td bgcolor="green"></td>
    <td></td>
  </tr>
  <tr>
    <td bgcolor="yellow"></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td bgcolor="silver"></td>
    <td></td>
    <td></td>
  </tr>
</table>


问:
Powershell: Progress Bar for folders being created
I'm trying to see if I can get a progress bar going based off either the duration of my script or for the folders it is creating.

The script in question is building a framework of a big folder structure. I'd like to incorporate a progress bar into the script. What I have so far is the following:

```<code>$Progress = @{
    Activity = 'Building Source Folders'
    CurrentOperation = "Verifying/Building"
    PercentComplete = 0
}

Write-Progress @Progress
$u = 0

ForEach ($f in $folders) {
$folders = Get-ChildItem C:\Source -Recurse
$u++
[int]$percentage = ($u / $folders.count)*100
$progress.CurrentOperation = "$f"
$progress.PercentComplete = $percentage

Write-Progress @Progress
}

rest of the script
</code>```

Any help is super appreciated as I don't know if having it as a loop is the only way to do a progress bar or if it's better to do it as a function.

答:
I ended up getting what I was looking for with this code from https://adamtheautomator.com/building-progress-bar-powershell-scripts/:</p>

```<code>$steps = ([System.Management.Automation.PsParser]::Tokenize($MyInvocation.MyCommand.Definition, [ref]$null) | where { $_.Type -eq 'Command' -and $_.Content -eq 'Progress-Bar' }).Count
$StepCounter = 0

function Progress-Bar {
    param(
        [int]$StepNumber,
        [string]$Message,
        [string]$Percent = "$(([math]::Round((($StepCounter)/$steps * 100)))) %"
    )

    Write-Progress -Activity 'Building TDC Source Folder Structure' -Status $Message -CurrentOperation $Percent -PercentComplete (($StepNumber / $steps) * 100)
}```

</code>```

Body:
I'm trying to see if I can get a progress bar going based off either the duration of my script or for the folders it is creating.

The script in question is building a framework of a big folder structure. I'd like to incorporate a progress bar into the script. What I have so far is the following:

$Progress = @{
    Activity = 'Building Source Folders'
    CurrentOperation = "Verifying/Building"
    PercentComplete = 0
}

Write-Progress @Progress
$u = 0

ForEach ($f in $folders) {
$folders = Get-ChildItem C:\Source -Recurse
$u++
[int]$percentage = ($u / $folders.count)*100
$progress.CurrentOperation = "$f"
$progress.PercentComplete = $percentage

Write-Progress @Progress
}

rest of the script

Any help is super appreciated as I don't know if having it as a loop is the only way to do a progress bar or if it's better to do it as a function.

Body:
I ended up getting what I was looking for with this code from https://adamtheautomator.com/building-progress-bar-powershell-scripts/:

$steps = ([System.Management.Automation.PsParser]::Tokenize($MyInvocation.MyCommand.Definition, [ref]$null) | where { $_.Type -eq 'Command' -and $_.Content -eq 'Progress-Bar' }).Count
$StepCounter = 0

function Progress-Bar {
    param(
        [int]$StepNumber,
        [string]$Message,
        [string]$Percent = "$(([math]::Round((($StepCounter)/$steps * 100)))) %"
    )

    Write-Progress -Activity 'Building TDC Source Folder Structure' -Status $Message -CurrentOperation $Percent -PercentComplete (($StepNumber / $steps) * 100)
}```


问:
How to read an image stored in Android application's folder in Internal Shared Storage using html?
My app is saving camera photos into Internal shared storage\my app\photos

It is also saving a XML file and one of the pieces inside that file is the name of the photo file.

I'm using XSLT to transform the XML into HTML for printing purposes.

I can successfully render an image from src\main\res\drawable using HTML in my WebView by using

How can I render the image in Internal shared storage?

答:
Ok I got to it with </p>

```<code><img src="file:///storage/emulated/0/myapp/photos/myphoto.jpg"/>
</code>```

Body:
Ok I got to it with

<img src="file:///storage/emulated/0/myapp/photos/myphoto.jpg"/>


问:
Maven: How to split an existing maven project into different projects?
So I have this big spring boot project with hundreds of APIs and corresponding models. I was asked to seperate it into three different modules. Storefront, Order Management System and Utilities. As per my basic, plan I sorted, filtered and moved Storefront and OMS APIs to their corresponding projects. I moved all the model classes into Utilities, created a package, added this package to the local repository and included it as dependencies of Storefront and OMS. Further Iexported these two projects as a runnable jar with copying required libraries into a sub folder next to the generated jar. And I did this because the sub folder will include the package for Utilities, and if in future, I have to update something from Utilities, I could just replace this package and restart the server.

Everything is working fine, the problem is with the size of the final package. The jar size of the original project is 175 MBs. All three projects have similar .pom files. So all three project export to a size which is almost 175 MBs. And as I said, I included the package for Utilities in other two projects. So the size of the sub folder for Storefront and OMS became around 350 MBs.

Finally, my question is, is there any way to split a maven project into 3 different sub projects which can be built and deployed independently and, is there any way these 3 projects share a set of libraries which can be stored remotely and accessed by them independently so to decrese the size of the final runnable jar?

答:
I think there are some deeper issues involved. If your artifact has 175MB and most of this are dependencies, than you have very very many dependencies.

So first of all, you should ask yourself, if all of those dependencies are really necessary. It is not unusual that people add a dependency just to use one simple class from that dependency. And this dependency than has a transitive burden. 175MB really calls for a deeper analysis of this fact.

Next, if you see you cannot really reduce the dependencies any more, you can split the project into several ones (like you started to do). But, then most of the dependencies should be in just one of the resulting projects. If all of your resulting projects use all of the dependencies, then these projects are all doing similar, probably overlapping things, which is not good.


问:
can truncate(7^sqrt(8)-8^sqrt(7)) be solved via CLP(FD)?
CLP(FD) is a great Prolog tool. It extends the big nums of Prolog to constraints and labeling. But is it versatile? Can we for example figure out this integer value:

```<code> truncate(7^sqrt(8)-8^sqrt(7)) = ?
</code>```

What would a Prolog CLP(FD) solution look like? Or are there other recommended ways to determine an answer like CLP(?) or something else?

答:
Using float arithmetic, we might not be 100% sure what the truncate result will be. Via floats we get an approximation x~ which might be off from the true x:

```<code>SWI-Prolog (threaded, 64 bits, version 8.1.21)

?- X is 7, Y is 8, Z is X**sqrt(Y)-Y^sqrt(X).
X = 7,
Y = 8,
Z = 0.5348772168447056.
</code>```

By using interval arithmetic we can get more confidence. If an interval arithmetic result points to an interval [x1,x2] then we know for sure that the true x is inside this interval:

```<code>ECLiPSe Version 7.0 #52 (x86_64_nt)

?- X is breal(7), Y is breal(8), Z is X^sqrt(Y)-Y^sqrt(X).
X = 7.0__7.0
Y = 8.0__8.0
Z = 0.534877216844194__0.53487721684518874
</code>```

Since the interval is completely inside [0,1) truncate will be zero.

Body:
CLP(FD) is a great Prolog tool. It extends the big nums of Prolog to constraints and labeling. But is it versatile? Can we for example figure out this integer value:

 truncate(7^sqrt(8)-8^sqrt(7)) = ?

What would a Prolog CLP(FD) solution look like? Or are there other recommended ways to determine an answer like CLP(?) or something else?

Body:
Using float arithmetic, we might not be 100% sure what the truncate result will be. Via floats we get an approximation x~ which might be off from the true x:

SWI-Prolog (threaded, 64 bits, version 8.1.21)

?- X is 7, Y is 8, Z is X**sqrt(Y)-Y^sqrt(X).
X = 7,
Y = 8,
Z = 0.5348772168447056.

By using interval arithmetic we can get more confidence. If an interval arithmetic result points to an interval [x1,x2] then we know for sure that the true x is inside this interval:

ECLiPSe Version 7.0 #52 (x86_64_nt)

?- X is breal(7), Y is breal(8), Z is X^sqrt(Y)-Y^sqrt(X).
X = 7.0__7.0
Y = 8.0__8.0
Z = 0.534877216844194__0.53487721684518874

Since the interval is completely inside [0,1) truncate will be zero.


问:
How can I set single child element in center align using css?
I have multiple child element in parent that divided with 3 columns and from 4 element goes to second row with left align:

ul {
  list-style: none;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-flow: wrap;
}

li {
  width: 33.33%;
  flex: 0 0 33.33%;
  padding: 15px 0;
  background: #000;
  color: #fff;
  font-size: 1rem;
  text-align: center;
  margin-bottom: 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Four</li>
</ul></code>```

But, when I have only a single child in my
 list, I want single child column into center.

答:
Since the maximum number per row is 3 you can handle each case alone. You have only 2:

ul {
  list-style: none;
  display: flex;
  align-items: center;
  flex-flow: wrap;
  padding:0;
  margin:5px;
}

li {
  flex: 0 0 33.33%;
  padding: 15px 0;
  background: #000;
  color: #fff;
  font-size: 1rem;
  text-align: center;
  margin-bottom: 15px;
}

/*1 item */
li:only-child {
  margin:auto;
}
/*2 item */
li:nth-child(1):nth-last-child(2) {
  margin-left:auto;
}
li:nth-child(2):nth-last-child(1) {
  margin-right:auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>One</li>
</ul>

<ul>
  <li>One</li>
  <li>Two</li>
</ul>

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Four</li>
</ul></code>```

Body:
I have multiple child element in parent that divided with 3 columns and from 4 element goes to second row with left align:

ul {
  list-style: none;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-flow: wrap;
}

li {
  width: 33.33%;
  flex: 0 0 33.33%;
  padding: 15px 0;
  background: #000;
  color: #fff;
  font-size: 1rem;
  text-align: center;
  margin-bottom: 15px;
}

One

Two

Three

Four

Four

But, when I have only a single child in my
 list, I want single child column into center.

Body:
Since the maximum number per row is 3 you can handle each case alone. You have only 2:

ul {
  list-style: none;
  display: flex;
  align-items: center;
  flex-flow: wrap;
  padding:0;
  margin:5px;
}

li {
  flex: 0 0 33.33%;
  padding: 15px 0;
  background: #000;
  color: #fff;
  font-size: 1rem;
  text-align: center;
  margin-bottom: 15px;
}

/*1 item */
li:only-child {
  margin:auto;
}
/*2 item */
li:nth-child(1):nth-last-child(2) {
  margin-left:auto;
}
li:nth-child(2):nth-last-child(1) {
  margin-right:auto;
}

<ul>
  <li>One</li>
</ul>

<ul>
  <li>One</li>
  <li>Two</li>
</ul>

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
  <li>Four</li>
</ul>


问:
Innosetup - reference a file from [Code] before the installation starts
This is sort of a continuation of this question.  I have a file that I want to include with my installation package (a .CHM help file) that I need to access during installation from code.  It doesn't need to be installed to the user's machine.  So I want to

- include the file in the installation package, probably uncompressed (so I guess I will do that with a [Files] ... external flag).

- reference the file during installation with code like:

```<code>procedure HelpButtonOnClick (Sender: TObject) ;
var
    ErrorCode : Integer ;

begin
ShellExecAsOriginalUser ('open', ExpandConstant ('{???}') +  '\MyHelp.chm', '', '', SW_SHOWNORMAL, ewNoWait, ErrorCode);
end ;
</code>```

So can I reference the file before installation starts - i.e. before any files are copied to the user machine?  How do I specify the path ExpandConstant ('{???}') to the file?  I have a help button on the wizard form that calls the above handler.

答:
This is easy. Just do</p>

```<code>[Files]
Source: "MyHelp.chm"; Flags: dontcopy

[Code]

procedure HelpButtonOnClick(Sender: TObject);
var
  ErrorCode: integer;
begin
  ExtractTemporaryFile('MyHelp.chm');
  ShellExecAsOriginalUser('', ExpandConstant('{tmp}\MyHelp.chm'), '', '',
    SW_SHOWNORMAL, ewNoWait, ErrorCode);
end;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is sort of a continuation of this question.  I have a file that I want to include with my installation package (a .CHM help file) that I need to access during installation from code.  It doesn't need to be installed to the user's machine.  So I want to

- include the file in the installation package, probably uncompressed (so I guess I will do that with a [Files] ... external flag).

- reference the file during installation with code like:

procedure HelpButtonOnClick (Sender: TObject) ;
var
    ErrorCode : Integer ;

begin
ShellExecAsOriginalUser ('open', ExpandConstant ('{???}') +  '\MyHelp.chm', '', '', SW_SHOWNORMAL, ewNoWait, ErrorCode);
end ;

So can I reference the file before installation starts - i.e. before any files are copied to the user machine?  How do I specify the path ExpandConstant ('{???}') to the file?  I have a help button on the wizard form that calls the above handler.

Body:
This is easy. Just do

[Files]
Source: "MyHelp.chm"; Flags: dontcopy

[Code]

procedure HelpButtonOnClick(Sender: TObject);
var
  ErrorCode: integer;
begin
  ExtractTemporaryFile('MyHelp.chm');
  ShellExecAsOriginalUser('', ExpandConstant('{tmp}\MyHelp.chm'), '', '',
    SW_SHOWNORMAL, ewNoWait, ErrorCode);
end;


问:
Pass username and other data to socket.io connection
I'm wondering if it's possible to pass any data to socket client?
What I want to archieve?
I have nodejs + Angular app where I need socket.io functionality. I configured connection and it's working. I'm able to retrieve clientId but I want to pass also username and maybe avatar of logged user so when user is connecting it will show his name nad photo. And behavior should be reversed when user is disconnected.

Does anybody know the way to do it or it's not possible?

Thanks.

答:
You can pass the required data as an object on emit and use it in frontend. Create an object with required key values.</p>

```<code>var obj= { username:'xyz',avatar:imageUrl };
Socket.on('userConnected',(data)=>{
//do something with data
Socket.emit('userDetails',obj);

}
</code>```

Body:
You can pass the required data as an object on emit and use it in frontend. Create an object with required key values.

var obj= { username:'xyz',avatar:imageUrl };
Socket.on('userConnected',(data)=>{
//do something with data
Socket.emit('userDetails',obj);

}


问:
How can I remove a heading/trailing processing instruction with lxml
How can I remove a processing instruction which is a sibling of the root element in a XML tree?

I can't find any function to do that, and the classic way doesn't work because a head/tail processing instruction has no parent:

from lxml import etree

root = etree.XML("<ROOT/><?foo?>")
tail = root.getnext()
parent = tail.getparent()  # parent is None
parent.remove(tail)
```

<p>I get:</p>

```Traceback (most recent call last):
  File "/path/to/demo_remove_tail_pi.py", line 6, in <module>
    parent.remove(tail)
AttributeError: 'NoneType' object has no attribute 'remove'
```

答:
This is due the Processing Instructions being generated outside of the root XML tree. This was brought up as a bug many years ago on the LXML's website, but unfortunately it does not look like an appropriate fix was ever implemented.

One of the users on the thread provided a (hackyish) way to remove Processing Instructions that were generated in this manner. Simply take the tag, append it to the root element, and then remove it.

Unlike some other XML libraries, lxml allows an element to occur in one place. That is, you can not copy an element to another place; attempting that moves it to the new location, removing it from the old.

```<code>from lxml.etree import XML, tounicode

root = XML("<ROOT/><?foo?>")

print(tounicode(root.getroottree()))
>>> <ROOT/><?foo?>
tail = root.getnext()
root.append(tail)
root.remove(tail)
print(tounicode(root.getroottree()))
>>> <ROOT/>
</code>```

Body:
How can I remove a processing instruction which is a sibling of the root element in a XML tree?

I can't find any function to do that, and the classic way doesn't work because a head/tail processing instruction has no parent:

from lxml import etree

root = etree.XML("<ROOT/><?foo?>")
tail = root.getnext()
parent = tail.getparent()  # parent is None
parent.remove(tail)

I get:

Traceback (most recent call last):
  File "/path/to/demo_remove_tail_pi.py", line 6, in <module>
    parent.remove(tail)
AttributeError: 'NoneType' object has no attribute 'remove'

Body:
This is due the Processing Instructions being generated outside of the root XML tree. This was brought up as a bug many years ago on the LXML's website, but unfortunately it does not look like an appropriate fix was ever implemented.

One of the users on the thread provided a (hackyish) way to remove Processing Instructions that were generated in this manner. Simply take the tag, append it to the root element, and then remove it.

Unlike some other XML libraries, lxml allows an element to occur in one place. That is, you can not copy an element to another place; attempting that moves it to the new location, removing it from the old.

from lxml.etree import XML, tounicode

root = XML("<ROOT/><?foo?>")

print(tounicode(root.getroottree()))
>>> <ROOT/><?foo?>
tail = root.getnext()
root.append(tail)
root.remove(tail)
print(tounicode(root.getroottree()))
>>> <ROOT/>


问:
How do we sort a tables content using update based on some other table value
I have two tables both have some values in them,

```<code>CREATE TABLE one (ID not null, Col1 char, Col2 char, Col3 char, Col4 char, Col5 char);
Insert into one (ID, Col1, Col2, Col3, Col4, Col5) VALUES (1, 'S', 'D', 'X', 'Y', 'M', 'K');

</code>```

The other table contains what number each alphabet refers to (ex: S= 13, D = 1, X = 7, Y = 3, M = 2, k = 30)

I need to use the two tables with join and update the cols to be ordered from largest to smallest.

Expected result: 1, k, s, x, y, m, d

This is what I tired so far:

```<code>UPDATE one
INNER JOIN two a on (one.Col1 = a.Colname)
INNER JOIN two b on (one.Col2 = b.Colname)
INNER JOIN two c on (one.Col3 = c.Colname)
INNER JOIN two d on (one.Col4 = d.Colname)
INNER JOIN two e on (one.Col5 = e.Colname)
SET
one.Col1 = (@temp:=one.Col1), one.Col1 = if ((b.ColValue > (a.ColValue and c.ColValue and d.ColValue and e.ColValue)),one.Col2,@temp),
one.Col2 = if (one.Col1 = b.Col2, a.CardName, one.Col2);
</code>```

In the above I am also swapping the values based on if the previous value was swapped or not.

I am stuck in trying to swap the rest, I am sure there is an easier way but I really can not think of anything else at the moment. Help will be greatly appreciated!

答:
Look - does it is what you need?

```<code>UPDATE one
SET col1 = SUBSTRING_INDEX(SUBSTRING_INDEX((SELECT GROUP_CONCAT(letter ORDER BY weight DESC) FROM two LIMIT 1), ',', 1), ',', -1),
    col2 = SUBSTRING_INDEX(SUBSTRING_INDEX((SELECT GROUP_CONCAT(letter ORDER BY weight DESC) FROM two LIMIT 1), ',', 2), ',', -1),
    col3 = SUBSTRING_INDEX(SUBSTRING_INDEX((SELECT GROUP_CONCAT(letter ORDER BY weight DESC) FROM two LIMIT 1), ',', 3), ',', -1),
    col4 = SUBSTRING_INDEX(SUBSTRING_INDEX((SELECT GROUP_CONCAT(letter ORDER BY weight DESC) FROM two LIMIT 1), ',', 4), ',', -1),
    col5 = SUBSTRING_INDEX(SUBSTRING_INDEX((SELECT GROUP_CONCAT(letter ORDER BY weight DESC) FROM two LIMIT 1), ',', 5), ',', -1),
    col6 = SUBSTRING_INDEX(SUBSTRING_INDEX((SELECT GROUP_CONCAT(letter ORDER BY weight DESC) FROM two LIMIT 1), ',', 6), ',', -1);
</code>```

fiddle

Body:
I have two tables both have some values in them,

CREATE TABLE one (ID not null, Col1 char, Col2 char, Col3 char, Col4 char, Col5 char);
Insert into one (ID, Col1, Col2, Col3, Col4, Col5) VALUES (1, 'S', 'D', 'X', 'Y', 'M', 'K');

The other table contains what number each alphabet refers to (ex: S= 13, D = 1, X = 7, Y = 3, M = 2, k = 30)

I need to use the two tables with join and update the cols to be ordered from largest to smallest.

Expected result: 1, k, s, x, y, m, d

This is what I tired so far:

UPDATE one
INNER JOIN two a on (one.Col1 = a.Colname)
INNER JOIN two b on (one.Col2 = b.Colname)
INNER JOIN two c on (one.Col3 = c.Colname)
INNER JOIN two d on (one.Col4 = d.Colname)
INNER JOIN two e on (one.Col5 = e.Colname)
SET
one.Col1 = (@temp:=one.Col1), one.Col1 = if ((b.ColValue > (a.ColValue and c.ColValue and d.ColValue and e.ColValue)),one.Col2,@temp),
one.Col2 = if (one.Col1 = b.Col2, a.CardName, one.Col2);

In the above I am also swapping the values based on if the previous value was swapped or not.

I am stuck in trying to swap the rest, I am sure there is an easier way but I really can not think of anything else at the moment. Help will be greatly appreciated!

Body:
Look - does it is what you need?

UPDATE one
SET col1 = SUBSTRING_INDEX(SUBSTRING_INDEX((SELECT GROUP_CONCAT(letter ORDER BY weight DESC) FROM two LIMIT 1), ',', 1), ',', -1),
    col2 = SUBSTRING_INDEX(SUBSTRING_INDEX((SELECT GROUP_CONCAT(letter ORDER BY weight DESC) FROM two LIMIT 1), ',', 2), ',', -1),
    col3 = SUBSTRING_INDEX(SUBSTRING_INDEX((SELECT GROUP_CONCAT(letter ORDER BY weight DESC) FROM two LIMIT 1), ',', 3), ',', -1),
    col4 = SUBSTRING_INDEX(SUBSTRING_INDEX((SELECT GROUP_CONCAT(letter ORDER BY weight DESC) FROM two LIMIT 1), ',', 4), ',', -1),
    col5 = SUBSTRING_INDEX(SUBSTRING_INDEX((SELECT GROUP_CONCAT(letter ORDER BY weight DESC) FROM two LIMIT 1), ',', 5), ',', -1),
    col6 = SUBSTRING_INDEX(SUBSTRING_INDEX((SELECT GROUP_CONCAT(letter ORDER BY weight DESC) FROM two LIMIT 1), ',', 6), ',', -1);

fiddle


问:
How to disambiguate a foreach loop in Xcode with SwiftUI
I am trying to create a hexagon grid using swiftUI on Xcode. To loop over the creation of the individual hexagons I am using a foreach loop. However I came Across an error when creating a function that creates a column of hexagons:

```<code>private func makeCol(C: Int, Bump:Int) -> some View {
        return ZStack {
            ForEach(-5...5, id: \.self) {Ynumber in
                self.hexagon(
                    x: (ThreeRooted * self.L * Double(C)) + self.centerWidth,
                    y: (ThreeRooted * self.L * Double(Ynumber)) + self.centerHeight + (ThreeRootedOverTwo * self.L * Bump))
                    .stroke(Color.red, lineWidth: CGFloat(self.L/4.0))
            }
        }
    }
</code>```

Error:
The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions.

To get around this I extracted my location fields in separate variables. However, this gave another error:

```<code>private func makeCol(C: Int, Bump:Int) -> some View {
        return ZStack {
            ForEach(-5...5, id: \.self) {Ynumber in
                let xPlot = (ThreeRooted * self.L * Double(C)) + self.centerWidth
                let yPlot = (ThreeRooted * self.L * Double(Ynumber)) + self.centerHeight + (ThreeRootedOverTwo * self.L * Bump)

                self.hexagon(
                    x: xPlot,
                    y: yPlot)
                    .stroke(Color.red, lineWidth: CGFloat(self.L/4.0))
            }
        }
    }
</code>```

Error: Unable to infer complex closure return type; add explicit type to disambiguate.

How do I give this loop an explicit type?

答:
ForEach is a structure that computes views on demand from an underlying collection of identified data, NOT a loop.

How to create hexagonal grid? Below is one possible approach where I tried to show you how to use ForEach and SwiftUI declarative syntax.

```<code>import SwiftUI

struct Hexagon: Shape {
    func path(in rect: CGRect) -> Path {
        Path { (path) in
            path.move(to: .init(x: rect.midX, y: rect.minY))
            path.addLine(to: .init(x: rect.maxX, y: (rect.minY + rect.midY) / 2 ))
            path.addLine(to: .init(x: rect.maxX, y: (rect.maxY + rect.midY) / 2 ))
            path.addLine(to: .init(x: rect.midX, y: rect.maxY))
            path.addLine(to: .init(x: rect.minX, y: (rect.maxY + rect.midY) / 2 ))
            path.addLine(to: .init(x: rect.minX, y: (rect.minY + rect.midY) / 2 ))
            path.closeSubpath()
        }
    }
}

struct ContentView: View {
    var body: some View {
        VStack(spacing: -10) {
            ForEach(0 ..< 3) { j in
                HStack(spacing: 5) {
                    ForEach(0 ..< 4) { i in
                        Hexagon()
                            .fill(Color.yellow)
                            .overlay(
                                Hexagon()
                                .stroke(Color.red, lineWidth: 5)
                            )
                            .frame(width: 50, height: 60)
                    }
                }
                HStack(spacing: 5) {
                    ForEach(0 ..< 3) { i in
                        Hexagon()
                            .stroke(Color.blue, lineWidth: 5)
                            .frame(width: 50, height: 60)
                    }
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

and here is the result

Spacing and frame parameters are fixed here for simplicity, you are better to calculate proper numbers.

```<code>init(Range<Int>, content: (Int) -> Content)
</code>```

Available when Data is Range, ID is Int, and Content conforms to
  View.

You tried to use

```<code>init(Data, id: KeyPath<Data.Element, ID>, content: (Data.Element) -> Content)
</code>```

Available when Content conforms to View.

and finally we don't have any idea what type returns your hexagon function, it could be Shape, but Shape is protocol, and that could make your trouble. If it is Shape, try define return type as some Shape.

Yes, compiler error reporting is still not very usable with SwiftUI

Body:
I am trying to create a hexagon grid using swiftUI on Xcode. To loop over the creation of the individual hexagons I am using a foreach loop. However I came Across an error when creating a function that creates a column of hexagons:

private func makeCol(C: Int, Bump:Int) -> some View {
        return ZStack {
            ForEach(-5...5, id: \.self) {Ynumber in
                self.hexagon(
                    x: (ThreeRooted * self.L * Double(C)) + self.centerWidth,
                    y: (ThreeRooted * self.L * Double(Ynumber)) + self.centerHeight + (ThreeRootedOverTwo * self.L * Bump))
                    .stroke(Color.red, lineWidth: CGFloat(self.L/4.0))
            }
        }
    }

Error:
The compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions.

To get around this I extracted my location fields in separate variables. However, this gave another error:

private func makeCol(C: Int, Bump:Int) -> some View {
        return ZStack {
            ForEach(-5...5, id: \.self) {Ynumber in
                let xPlot = (ThreeRooted * self.L * Double(C)) + self.centerWidth
                let yPlot = (ThreeRooted * self.L * Double(Ynumber)) + self.centerHeight + (ThreeRootedOverTwo * self.L * Bump)

                self.hexagon(
                    x: xPlot,
                    y: yPlot)
                    .stroke(Color.red, lineWidth: CGFloat(self.L/4.0))
            }
        }
    }

Error: Unable to infer complex closure return type; add explicit type to disambiguate.

How do I give this loop an explicit type?

Body:
ForEach is a structure that computes views on demand from an underlying collection of identified data, NOT a loop.

How to create hexagonal grid? Below is one possible approach where I tried to show you how to use ForEach and SwiftUI declarative syntax.

import SwiftUI

struct Hexagon: Shape {
    func path(in rect: CGRect) -> Path {
        Path { (path) in
            path.move(to: .init(x: rect.midX, y: rect.minY))
            path.addLine(to: .init(x: rect.maxX, y: (rect.minY + rect.midY) / 2 ))
            path.addLine(to: .init(x: rect.maxX, y: (rect.maxY + rect.midY) / 2 ))
            path.addLine(to: .init(x: rect.midX, y: rect.maxY))
            path.addLine(to: .init(x: rect.minX, y: (rect.maxY + rect.midY) / 2 ))
            path.addLine(to: .init(x: rect.minX, y: (rect.minY + rect.midY) / 2 ))
            path.closeSubpath()
        }
    }
}

struct ContentView: View {
    var body: some View {
        VStack(spacing: -10) {
            ForEach(0 ..< 3) { j in
                HStack(spacing: 5) {
                    ForEach(0 ..< 4) { i in
                        Hexagon()
                            .fill(Color.yellow)
                            .overlay(
                                Hexagon()
                                .stroke(Color.red, lineWidth: 5)
                            )
                            .frame(width: 50, height: 60)
                    }
                }
                HStack(spacing: 5) {
                    ForEach(0 ..< 3) { i in
                        Hexagon()
                            .stroke(Color.blue, lineWidth: 5)
                            .frame(width: 50, height: 60)
                    }
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

and here is the result

Spacing and frame parameters are fixed here for simplicity, you are better to calculate proper numbers.

init(Range<Int>, content: (Int) -> Content)

Available when Data is Range, ID is Int, and Content conforms to
  View.

You tried to use

init(Data, id: KeyPath<Data.Element, ID>, content: (Data.Element) -> Content)

Available when Content conforms to View.

and finally we don't have any idea what type returns your hexagon function, it could be Shape, but Shape is protocol, and that could make your trouble. If it is Shape, try define return type as some Shape.

Yes, compiler error reporting is still not very usable with SwiftUI


问:
Import Error DLL load failed, sklearn linear_model
```<code>from sklearn import linear_model

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-35-070c84f8cd4b> in <module>
      1 import numpy as np
      2 import matplotlib.pyplot as plt
----> 3 from sklearn import linear_model

~\Anaconda3\lib\site-packages\sklearn\__init__.py in <module>
     74 else:
     75     from . import __check_build
---> 76     from .base import clone
     77     from .utils._show_versions import show_versions
     78

~\Anaconda3\lib\site-packages\sklearn\base.py in <module>
     14
     15 from . import __version__
---> 16 from .utils import _IS_32BIT
     17
     18 _DEFAULT_TAGS = {

~\Anaconda3\lib\site-packages\sklearn\utils\__init__.py in <module>
     18 from ..exceptions import DataConversionWarning
     19 from .deprecation import deprecated
---> 20 from .validation import (as_float_array,
     21                          assert_all_finite,
     22                          check_random_state, column_or_1d, check_array,

~\Anaconda3\lib\site-packages\sklearn\utils\validation.py in <module>
     19 from numpy.core.numeric import ComplexWarning
     20
---> 21 from .fixes import _object_dtype_isnan
     22 from .. import get_config as _get_config
     23 from ..exceptions import NonBLASDotWarning

~\Anaconda3\lib\site-packages\sklearn\utils\fixes.py in <module>
     16 import scipy.sparse as sp
     17 import scipy
---> 18 from scipy.sparse.linalg import lsqr as sparse_lsqr  # noqa
     19
     20

~\Anaconda3\lib\site-packages\scipy\sparse\linalg\__init__.py in <module>
    114 from .dsolve import *
    115 from .interface import *
--> 116 from .eigen import *
    117 from .matfuncs import *
    118 from ._onenormest import *

~\Anaconda3\lib\site-packages\scipy\sparse\linalg\eigen\__init__.py in <module>
      9 from __future__ import division, print_function, absolute_import
     10
---> 11 from .arpack import *
     12 from .lobpcg import *
     13

~\Anaconda3\lib\site-packages\scipy\sparse\linalg\eigen\arpack\__init__.py in <module>
     20 from __future__ import division, print_function, absolute_import
     21
---> 22 from .arpack import *

~\Anaconda3\lib\site-packages\scipy\sparse\linalg\eigen\arpack\arpack.py in <module>
     43 __all__ = ['eigs', 'eigsh', 'svds', 'ArpackError', 'ArpackNoConvergence']
     44
---> 45 from . import _arpack
     46 import numpy as np
     47 import warnings

ImportError: DLL load failed: The specified procedure could not be found.
</code>```

答:
I had the same problem and this helped:

I uninstall conda versions and use pip versions it works ok.

```<code>$> conda remove --force numpy, scipy
$> pip install numpy, scipy
</code>```

Body:
I had the same problem and this helped:

I uninstall conda versions and use pip versions it works ok.

$> conda remove --force numpy, scipy
$> pip install numpy, scipy


问:
Where to find TensorFlow 1.x Documentation
Where is the original TensorFlow 1 documentation? Not just of the API, but also guides and tutorials?</p>

答: It can be found here on GitHub.</p>

Body: It can be found here on GitHub.


问:
How can I delay document.ready until a variable is set?
I am doing QUnit testing in an IFRAME and have a recursive JavaScript function that loads all of the scripts from the parent page into the IFRAME before starting QUnit.  This works great.  My problem is that some of our scripts use document.ready to make stuff start.

Something such as:

```<code>$(document).ready(function () {
    // blah
});
</code>```

to do do their work.  I'd prefer to not change production code just to account for tests and I don't want these production scripts to think the IFRAME document is "ready" until every scripts is loaded.

How I can delay "document.ready" itself?

Here is my pseudocode to give you an example to work from:

```<code>scripts[0] = "/foo/bar.js";
scripts[1] = "/blah/blah.js";

function RecursiveScriptStart(){
    // I want to set document.ready = false right here!
    if(scripts.length == 0) {
        QUnitStart();
        return;
    }
    RecursiveScriptLoader(0, scripts);
}

function RecursiveScriptLoader(currentScriptID, scripts) {
    $.getScript(scripts[currentScriptID], function () {
        if (currentScriptID == (scripts.length - 1)) {
            QUnitStart();
        }
        else {
            RecursiveScriptLoader(currentScriptID + 1, scripts);
        }
    });
}

function QUnitStart() {
        // I want to set document.ready = true right here!
        QUnit.stop();
        QUnit.start();
}
</code>```

The actual code is similar, but involves a jquery selector populating the array "scripts[]" with JavaScript tag "src" properties.

Thanks!

答:
If your using jQuery 1.6 or higher you can use holdReady to delay the ready event being fired.

For 1.4.3 or higher you can use $.readyWait property to delay the ready event, Demo Here (not my code)

if your interested in figuring out how jquery handles the ready event search for the line

```<code>jQuery( document ).trigger( "ready" ).unbind( "ready" );
</code>```

in your developer copy of jquery.js

Body:
I am doing QUnit testing in an IFRAME and have a recursive JavaScript function that loads all of the scripts from the parent page into the IFRAME before starting QUnit.  This works great.  My problem is that some of our scripts use document.ready to make stuff start.

Something such as:

$(document).ready(function () {
    // blah
});

to do do their work.  I'd prefer to not change production code just to account for tests and I don't want these production scripts to think the IFRAME document is "ready" until every scripts is loaded.

How I can delay "document.ready" itself?

Here is my pseudocode to give you an example to work from:

scripts[0] = "/foo/bar.js";
scripts[1] = "/blah/blah.js";

function RecursiveScriptStart(){
    // I want to set document.ready = false right here!
    if(scripts.length == 0) {
        QUnitStart();
        return;
    }
    RecursiveScriptLoader(0, scripts);
}

function RecursiveScriptLoader(currentScriptID, scripts) {
    $.getScript(scripts[currentScriptID], function () {
        if (currentScriptID == (scripts.length - 1)) {
            QUnitStart();
        }
        else {
            RecursiveScriptLoader(currentScriptID + 1, scripts);
        }
    });
}

function QUnitStart() {
        // I want to set document.ready = true right here!
        QUnit.stop();
        QUnit.start();
}

The actual code is similar, but involves a jquery selector populating the array "scripts[]" with JavaScript tag "src" properties.

Thanks!

Body:
If your using jQuery 1.6 or higher you can use holdReady to delay the ready event being fired.

For 1.4.3 or higher you can use $.readyWait property to delay the ready event, Demo Here (not my code)

if your interested in figuring out how jquery handles the ready event search for the line

jQuery( document ).trigger( "ready" ).unbind( "ready" );

in your developer copy of jquery.js


问:
In PHP: what is the difference between "return", "yield", "yield from" and mixing both yield and return in same function?
The difference between return and yield seemed clear until I figured out there was also yield from and the possibility to combine both return and yield in the very same function!

My understanding of return was that everything after was not executed, right?

However:

```<code>function generate(): iterable {
    return [1, 2, 3];
}

foreach (generate() as $value) {
    echo $value;
}
</code>```

Produces: "123"

But the following:

```<code>function generate(): iterable {
    return [1, 2, 3];
    yield;
}

foreach (generate() as $value) {
    echo $value;
}
</code>```

Produces nothing! So that means yield is executed?

Is this a bug?

答:
From the documentation:

Any function containing yield is a generator function.

So it doesn't matter whether the yield is executed, the parser sees it somewhere in the function definition and turns it into a generator.

If the function never executes the yield statement, then the generator doesn't produce any values. The value returned by return is ignored when you try to use the result. The documentation says:

Note:

  In PHP 5, a generator could not return a value: doing so would result in a compile error. An empty return statement was valid syntax within a generator and it would terminate the generator. Since PHP 7.0, a generator can return values, which can be retrieved using Generator::getReturn().

So you could do:

```<code>$gen = generate();
foreach ($gen as $value) {
    echo $value;
}
print_r($gen->getReturn());
</code>```

Body:
The difference between return and yield seemed clear until I figured out there was also yield from and the possibility to combine both return and yield in the very same function!

My understanding of return was that everything after was not executed, right?

However:

function generate(): iterable {
    return [1, 2, 3];
}

foreach (generate() as $value) {
    echo $value;
}

Produces: "123"

But the following:

function generate(): iterable {
    return [1, 2, 3];
    yield;
}

foreach (generate() as $value) {
    echo $value;
}

Produces nothing! So that means yield is executed?

Is this a bug?

Body:
From the documentation:

Any function containing yield is a generator function.

So it doesn't matter whether the yield is executed, the parser sees it somewhere in the function definition and turns it into a generator.

If the function never executes the yield statement, then the generator doesn't produce any values. The value returned by return is ignored when you try to use the result. The documentation says:

Note:

  In PHP 5, a generator could not return a value: doing so would result in a compile error. An empty return statement was valid syntax within a generator and it would terminate the generator. Since PHP 7.0, a generator can return values, which can be retrieved using Generator::getReturn().

So you could do:

$gen = generate();
foreach ($gen as $value) {
    echo $value;
}
print_r($gen->getReturn());


问:
Android ListView can't loop invisible item in ScrollBar
I have a very bad error

I have list view with a custom Adapter

If I put 15 row in list win I make for loop

the loop in visible item on the screen only

If the screen take 10 item it will loop in 10 item only
and can't loop on other 5 item

This image
https://ibb.co/Zgnx67T

https://ibb.co/f0wLFS6

This is custom adapter

```<code>package com.bella_system.mostafasalama.bellasystem;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import static com.bella_system.mostafasalama.bellasystem.Constant.Add_Units_Count;
import static com.bella_system.mostafasalama.bellasystem.Constant.ItemID;
import static com.bella_system.mostafasalama.bellasystem.Constant.ItemName;
import static com.bella_system.mostafasalama.bellasystem.Constant.TextLineID;
import static com.bella_system.mostafasalama.bellasystem.Constant.TextLineM;
import static com.bella_system.mostafasalama.bellasystem.Constant.SUintID;
import static com.bella_system.mostafasalama.bellasystem.Constant.TextPrice;
import static com.bella_system.mostafasalama.bellasystem.Constant.TextQty;
import static com.bella_system.mostafasalama.bellasystem.Constant.TextSubQty;
import static com.bella_system.mostafasalama.bellasystem.Constant.Total_COLUMN;
import static com.bella_system.mostafasalama.bellasystem.Constant.UintTwoID;
import static com.bella_system.mostafasalama.bellasystem.Constant.UintTwoPrice;
public class ListViewAdapter extends BaseAdapter{
public ArrayList<HashMap<String, String>> list;
Activity activity;
public ListViewAdapter(Activity activity,ArrayList<HashMap<String, String>> list){
        super();
        this.activity = activity;
        this.list = list;
    }

    @Override public int getCount() { return list.size(); }
    @Override public Object getItem(int position) { return list.get(position); }
    @Override public long getItemId(int position) { return 0; }

    private class ViewHolder{
        TextView TextLineID;
        TextView TextItemID;
        TextView textLineM;
        TextView TextItemName;
        TextView TextTextQty;
        TextView TextPrice;
        TextView TextSubQty;
        TextView UintTwoPrice;
        TextView TextItemTotal;
        TextView TextUintID;
        TextView UintTwoID;
        TextView Add_Units_Count;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
     ViewHolder holder;
        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView=inflater.inflate(R.layout.datagridviewinv, parent,false);
            holder=new ViewHolder();
            holder.TextLineID = (TextView) convertView.findViewById(R.id.TextLineID);
            holder.TextItemID=(TextView) convertView.findViewById(R.id.TextItemID);
            holder.textLineM=(TextView) convertView.findViewById(R.id.TextLineM);
            holder.TextItemName=(TextView) convertView.findViewById(R.id.ItemName);
            holder.TextTextQty=(TextView) convertView.findViewById(R.id.TextQty);
            holder.TextPrice=(TextView) convertView.findViewById(R.id.TextPrice);
            holder.TextSubQty=(TextView) convertView.findViewById(R.id.TextSubQty);
            holder.UintTwoPrice=(TextView) convertView.findViewById(R.id.UintTwoPrice);
            holder.TextItemTotal=(TextView) convertView.findViewById(R.id.TextItemTotal);
            holder.TextUintID=(TextView) convertView.findViewById(R.id.TextUintID);
            holder.UintTwoID=(TextView) convertView.findViewById(R.id.UintTwoID);
            holder.Add_Units_Count=(TextView) convertView.findViewById(R.id.Add_Units_Count);
            convertView.setTag(holder);
        } else{ holder=(ViewHolder) convertView.getTag(); }

        HashMap<String, String> map = list.get(position);
     if (map != null) {
      holder.TextLineID.setText(map.get(TextLineID));
      holder.TextItemID.setText(map.get(ItemID));
      holder.textLineM.setText(map.get(TextLineM));
      holder.TextItemName.setText(map.get(ItemName));
      holder.TextTextQty.setText(map.get(TextQty));
      holder.TextPrice.setText(map.get(TextPrice));
      holder.TextSubQty.setText(map.get(TextSubQty));
      holder.UintTwoPrice.setText(map.get(UintTwoPrice));
      holder.TextItemTotal.setText(map.get(Total_COLUMN));
      holder.TextUintID.setText(map.get(SUintID));
      holder.UintTwoID.setText(map.get(UintTwoID));
      holder.Add_Units_Count.setText(map.get(Add_Units_Count));
     }
        return convertView;
    }
}
</code>```

And this my for loop

```<code>    for (int i = 0; i < listView.getAdapter().getCount(); i++) {
    if (listView.getChildAt(i) != null) {
    TextView LineID = (TextView) listView.getChildAt(i).findViewById(R.id.TextLineID);
    TextView ItemIDV = (TextView) listView.getChildAt(i).findViewById(R.id.TextItemID);
    TextView LineNumber = (TextView) listView.getChildAt(i).findViewById(R.id.TextLineM);
    TextView ItemName = (TextView) listView.getChildAt(i).findViewById(R.id.ItemName);
    TextView Qty = (TextView) listView.getChildAt(i).findViewById(R.id.TextQty);
    TextView SubQty = (TextView) listView.getChildAt(i).findViewById(R.id.TextSubQty);
    TextView Price = (TextView) listView.getChildAt(i).findViewById(R.id.TextPrice);
    TextView ItemTotal = (TextView) listView.getChildAt(i).findViewById(R.id.TextItemTotal);
    TextView SUintID = (TextView) listView.getChildAt(i).findViewById(R.id.TextUintID);
    TextView TUintTwoID = (TextView) listView.getChildAt(i).findViewById(R.id.UintTwoID);
    TextView UintTwoPriceV = (TextView) listView.getChildAt(i).findViewById(R.id.UintTwoPrice);
    TextView Add_Units_CountASDV = (TextView) listView.getChildAt(i).findViewById(R.id.Add_Units_Count);

}```
```

答:
You're almost there. You're trying to extract the values of the ListView data in order to persist it locally which means in your loop you'd need to point to the list data passed into the adapter that you've configured.

```<code>for (int i = 0; i < listView.getAdapter().getCount(); i++) {
    // if you have direct access to the list
    HashMap<String, String> itemMap = list.get(i);
    // if you don't have direct access you can do something like instead:
    // HashMap<String, String> itemMap = ((ListViewAdapter)listView.getAdapter()).list.get(i);
    if (itemMap != null) {
      String txtLineId = itemMap.get(TextLineID)
    }
}

</code>```

This is pretty much the same approach used when handling onClicks, see first code block here: https://stackoverflow.com/a/38919205/2340813

Body:
I have a very bad error

I have list view with a custom Adapter

If I put 15 row in list win I make for loop

the loop in visible item on the screen only

If the screen take 10 item it will loop in 10 item only
and can't loop on other 5 item

This image
https://ibb.co/Zgnx67T

https://ibb.co/f0wLFS6

This is custom adapter

package com.bella_system.mostafasalama.bellasystem;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import static com.bella_system.mostafasalama.bellasystem.Constant.Add_Units_Count;
import static com.bella_system.mostafasalama.bellasystem.Constant.ItemID;
import static com.bella_system.mostafasalama.bellasystem.Constant.ItemName;
import static com.bella_system.mostafasalama.bellasystem.Constant.TextLineID;
import static com.bella_system.mostafasalama.bellasystem.Constant.TextLineM;
import static com.bella_system.mostafasalama.bellasystem.Constant.SUintID;
import static com.bella_system.mostafasalama.bellasystem.Constant.TextPrice;
import static com.bella_system.mostafasalama.bellasystem.Constant.TextQty;
import static com.bella_system.mostafasalama.bellasystem.Constant.TextSubQty;
import static com.bella_system.mostafasalama.bellasystem.Constant.Total_COLUMN;
import static com.bella_system.mostafasalama.bellasystem.Constant.UintTwoID;
import static com.bella_system.mostafasalama.bellasystem.Constant.UintTwoPrice;
public class ListViewAdapter extends BaseAdapter{
public ArrayList<HashMap<String, String>> list;
Activity activity;
public ListViewAdapter(Activity activity,ArrayList<HashMap<String, String>> list){
        super();
        this.activity = activity;
        this.list = list;
    }

    @Override public int getCount() { return list.size(); }
    @Override public Object getItem(int position) { return list.get(position); }
    @Override public long getItemId(int position) { return 0; }

    private class ViewHolder{
        TextView TextLineID;
        TextView TextItemID;
        TextView textLineM;
        TextView TextItemName;
        TextView TextTextQty;
        TextView TextPrice;
        TextView TextSubQty;
        TextView UintTwoPrice;
        TextView TextItemTotal;
        TextView TextUintID;
        TextView UintTwoID;
        TextView Add_Units_Count;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
     ViewHolder holder;
        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView=inflater.inflate(R.layout.datagridviewinv, parent,false);
            holder=new ViewHolder();
            holder.TextLineID = (TextView) convertView.findViewById(R.id.TextLineID);
            holder.TextItemID=(TextView) convertView.findViewById(R.id.TextItemID);
            holder.textLineM=(TextView) convertView.findViewById(R.id.TextLineM);
            holder.TextItemName=(TextView) convertView.findViewById(R.id.ItemName);
            holder.TextTextQty=(TextView) convertView.findViewById(R.id.TextQty);
            holder.TextPrice=(TextView) convertView.findViewById(R.id.TextPrice);
            holder.TextSubQty=(TextView) convertView.findViewById(R.id.TextSubQty);
            holder.UintTwoPrice=(TextView) convertView.findViewById(R.id.UintTwoPrice);
            holder.TextItemTotal=(TextView) convertView.findViewById(R.id.TextItemTotal);
            holder.TextUintID=(TextView) convertView.findViewById(R.id.TextUintID);
            holder.UintTwoID=(TextView) convertView.findViewById(R.id.UintTwoID);
            holder.Add_Units_Count=(TextView) convertView.findViewById(R.id.Add_Units_Count);
            convertView.setTag(holder);
        } else{ holder=(ViewHolder) convertView.getTag(); }

        HashMap<String, String> map = list.get(position);
     if (map != null) {
      holder.TextLineID.setText(map.get(TextLineID));
      holder.TextItemID.setText(map.get(ItemID));
      holder.textLineM.setText(map.get(TextLineM));
      holder.TextItemName.setText(map.get(ItemName));
      holder.TextTextQty.setText(map.get(TextQty));
      holder.TextPrice.setText(map.get(TextPrice));
      holder.TextSubQty.setText(map.get(TextSubQty));
      holder.UintTwoPrice.setText(map.get(UintTwoPrice));
      holder.TextItemTotal.setText(map.get(Total_COLUMN));
      holder.TextUintID.setText(map.get(SUintID));
      holder.UintTwoID.setText(map.get(UintTwoID));
      holder.Add_Units_Count.setText(map.get(Add_Units_Count));
     }
        return convertView;
    }
}

And this my for loop

    for (int i = 0; i < listView.getAdapter().getCount(); i++) {
    if (listView.getChildAt(i) != null) {
    TextView LineID = (TextView) listView.getChildAt(i).findViewById(R.id.TextLineID);
    TextView ItemIDV = (TextView) listView.getChildAt(i).findViewById(R.id.TextItemID);
    TextView LineNumber = (TextView) listView.getChildAt(i).findViewById(R.id.TextLineM);
    TextView ItemName = (TextView) listView.getChildAt(i).findViewById(R.id.ItemName);
    TextView Qty = (TextView) listView.getChildAt(i).findViewById(R.id.TextQty);
    TextView SubQty = (TextView) listView.getChildAt(i).findViewById(R.id.TextSubQty);
    TextView Price = (TextView) listView.getChildAt(i).findViewById(R.id.TextPrice);
    TextView ItemTotal = (TextView) listView.getChildAt(i).findViewById(R.id.TextItemTotal);
    TextView SUintID = (TextView) listView.getChildAt(i).findViewById(R.id.TextUintID);
    TextView TUintTwoID = (TextView) listView.getChildAt(i).findViewById(R.id.UintTwoID);
    TextView UintTwoPriceV = (TextView) listView.getChildAt(i).findViewById(R.id.UintTwoPrice);
    TextView Add_Units_CountASDV = (TextView) listView.getChildAt(i).findViewById(R.id.Add_Units_Count);

}```

Body:
You're almost there. You're trying to extract the values of the ListView data in order to persist it locally which means in your loop you'd need to point to the list data passed into the adapter that you've configured.

for (int i = 0; i < listView.getAdapter().getCount(); i++) {
    // if you have direct access to the list
    HashMap<String, String> itemMap = list.get(i);
    // if you don't have direct access you can do something like instead:
    // HashMap<String, String> itemMap = ((ListViewAdapter)listView.getAdapter()).list.get(i);
    if (itemMap != null) {
      String txtLineId = itemMap.get(TextLineID)
    }
}

This is pretty much the same approach used when handling onClicks, see first code block here: https://stackoverflow.com/a/38919205/2340813


问:
How to define logging in one place in Python?
I am new Python and I want to define the following logging code in python in one place so that it can be used in other python files(class or non-class). In case of Java, we use log4j or slf4j as part of jar files and we simply define as Logger logger = Logger.getLogger("class name"), I want achieve exactly like this so that I can use loger in any python module/s. Currently I define the config in all the classes.

import logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler("debug.log"),
        logging.StreamHandler()
    ]
)
```

I have also gone through this SO link Using logging in multiple modules

Also please suggest the most recommended approach for medium to large project having more number of python files.

答:
One option to make your logging handler available everywhere, is to make it a built-in identifier:

a.py:

```<code>import logging
import builtins
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(filename)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler("/tmp/debug.log"),
        logging.StreamHandler()
    ]
)

builtins.logger = logging.getLogger(__name__)
logger.info("module a!")
import b
</code>```

b.py:

```<code>logger.info(msg='This is from module b.py')

def foo():
    logger.info('Log message from b.foo()')

foo()
</code>```

Output:

```<code>2020-02-14 20:18:17,549 a.py [INFO] module a!
2020-02-14 20:18:17,550 b.py [INFO] This is from module b.py
2020-02-14 20:18:17,550 b.py [INFO] Log message from b.foo()
</code>```

Body:
I am new Python and I want to define the following logging code in python in one place so that it can be used in other python files(class or non-class). In case of Java, we use log4j or slf4j as part of jar files and we simply define as Logger logger = Logger.getLogger("class name"), I want achieve exactly like this so that I can use loger in any python module/s. Currently I define the config in all the classes.

import logging
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler("debug.log"),
        logging.StreamHandler()
    ]
)

I have also gone through this SO link Using logging in multiple modules

Also please suggest the most recommended approach for medium to large project having more number of python files.

Body:
One option to make your logging handler available everywhere, is to make it a built-in identifier:

a.py:

import logging
import builtins
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s %(filename)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler("/tmp/debug.log"),
        logging.StreamHandler()
    ]
)

builtins.logger = logging.getLogger(__name__)
logger.info("module a!")
import b

b.py:

logger.info(msg='This is from module b.py')

def foo():
    logger.info('Log message from b.foo()')

foo()

Output:

2020-02-14 20:18:17,549 a.py [INFO] module a!
2020-02-14 20:18:17,550 b.py [INFO] This is from module b.py
2020-02-14 20:18:17,550 b.py [INFO] Log message from b.foo()