问:
Pivot some rows to new columns in DataFrame
I'm after a pythonic and pandemic (from pandas, pun not intended =) way to pivot some rows in a dataframe into new columns.

My data has this format:

```<code>           dof  foo  bar  qux
idxA idxB
100  101     1   10   30   50
     101     2   11   31   51
     101     3   12   32   52
     102     1   13   33   53
     102     2   14   34   54
     102     3   15   35   55
200  101     1   16   36   56
     101     2   17   37   57
     101     3   18   38   58
     102     1   19   39   59
     102     2   20   40   60
     102     3   21   41   61
</code>```

The variables foo, bar and qux actually have 3 dimensional coordinates, which I would like to call foo1, foo2, foo3, bar1, ..., qux3. These are identified by the column dof. Each row represents one axis in 3D, dof == 1 is the x axis, dof == 2 the y axis and dof == 3 is the z axis.

So, here is the final dataframe I want:

```<code>           foo1  bar1  qux1  foo2  bar2  qux2  foo3  bar3  qux3
idxA idxB
100  101     10    30    50    11    31    51    12    32    52
     102     13    33    53    14    34    54    15    35    55
200  101     16    36    56    17    37    57    18    38    58
     102     19    39    59    20    40    60    21    41    61
</code>```

Question is: what is the best way to do that?

Here is what I have done.

A code to re-create my dataset in a dataframe:

```<code>import pandas as pd

data = [[100, 101, 1, 10, 30, 50],
        [100, 101, 2, 11, 31, 51],
        [100, 101, 3, 12, 32, 52],
        [100, 102, 1, 13, 33, 53],
        [100, 102, 2, 14, 34, 54],
        [100, 102, 3, 15, 35, 55],
        [200, 101, 1, 16, 36, 56],
        [200, 101, 2, 17, 37, 57],
        [200, 101, 3, 18, 38, 58],
        [200, 102, 1, 19, 39, 59],
        [200, 102, 2, 20, 40, 60],
        [200, 102, 3, 21, 41, 61],
        ]

df = pd.DataFrame(data=data, columns=['idxA', 'idxB', 'dof', 'foo', 'bar', 'qux'])
df.set_index(['idxA', 'idxB'], inplace=True)
</code>```

Code to do what I would like to do:

```<code>df2 = df[df.dof == 1].reset_index()[['idxA', 'idxB']]
df2.set_index(['idxA', 'idxB'], inplace=True)
for pivot in [1, 2, 3]:
    df2.loc[:, 'foo%d' % pivot] = df[df.dof == pivot]['foo']
    df2.loc[:, 'bar%d' % pivot] = df[df.dof == pivot]['bar']
    df2.loc[:, 'qux%d' % pivot] = df[df.dof == pivot]['qux']
</code>```

However I'm not too happy with these .loc calls and incremental column additions to the dataframe. I thought that pandas being awesome as it is would have a neater way of doing that. A one-liner would be super cool.

答:
You can add dof to index and do a unstack:

```<code>new_df = df.set_index('dof',append=True).unstack('dof')
new_df.columns = [f'{x}{y}' for x,y in new_df.columns]
</code>```

Output:

```<code>           foo1  foo2  foo3  bar1  bar2  bar3  qux1  qux2  qux3
idxA idxB
100  101     10    11    12    30    31    32    50    51    52
     102     13    14    15    33    34    35    53    54    55
200  101     16    17    18    36    37    38    56    57    58
     102     19    20    21    39    40    41    59    60    61
</code>```

Body:
I'm after a pythonic and pandemic (from pandas, pun not intended =) way to pivot some rows in a dataframe into new columns.

My data has this format:

           dof  foo  bar  qux
idxA idxB
100  101     1   10   30   50
     101     2   11   31   51
     101     3   12   32   52
     102     1   13   33   53
     102     2   14   34   54
     102     3   15   35   55
200  101     1   16   36   56
     101     2   17   37   57
     101     3   18   38   58
     102     1   19   39   59
     102     2   20   40   60
     102     3   21   41   61

The variables foo, bar and qux actually have 3 dimensional coordinates, which I would like to call foo1, foo2, foo3, bar1, ..., qux3. These are identified by the column dof. Each row represents one axis in 3D, dof == 1 is the x axis, dof == 2 the y axis and dof == 3 is the z axis.

So, here is the final dataframe I want:

           foo1  bar1  qux1  foo2  bar2  qux2  foo3  bar3  qux3
idxA idxB
100  101     10    30    50    11    31    51    12    32    52
     102     13    33    53    14    34    54    15    35    55
200  101     16    36    56    17    37    57    18    38    58
     102     19    39    59    20    40    60    21    41    61

Question is: what is the best way to do that?

Here is what I have done.

A code to re-create my dataset in a dataframe:

import pandas as pd

data = [[100, 101, 1, 10, 30, 50],
        [100, 101, 2, 11, 31, 51],
        [100, 101, 3, 12, 32, 52],
        [100, 102, 1, 13, 33, 53],
        [100, 102, 2, 14, 34, 54],
        [100, 102, 3, 15, 35, 55],
        [200, 101, 1, 16, 36, 56],
        [200, 101, 2, 17, 37, 57],
        [200, 101, 3, 18, 38, 58],
        [200, 102, 1, 19, 39, 59],
        [200, 102, 2, 20, 40, 60],
        [200, 102, 3, 21, 41, 61],
        ]

df = pd.DataFrame(data=data, columns=['idxA', 'idxB', 'dof', 'foo', 'bar', 'qux'])
df.set_index(['idxA', 'idxB'], inplace=True)

Code to do what I would like to do:

df2 = df[df.dof == 1].reset_index()[['idxA', 'idxB']]
df2.set_index(['idxA', 'idxB'], inplace=True)
for pivot in [1, 2, 3]:
    df2.loc[:, 'foo%d' % pivot] = df[df.dof == pivot]['foo']
    df2.loc[:, 'bar%d' % pivot] = df[df.dof == pivot]['bar']
    df2.loc[:, 'qux%d' % pivot] = df[df.dof == pivot]['qux']

However I'm not too happy with these .loc calls and incremental column additions to the dataframe. I thought that pandas being awesome as it is would have a neater way of doing that. A one-liner would be super cool.

Body:
You can add dof to index and do a unstack:

new_df = df.set_index('dof',append=True).unstack('dof')
new_df.columns = [f'{x}{y}' for x,y in new_df.columns]

Output:

           foo1  foo2  foo3  bar1  bar2  bar3  qux1  qux2  qux3
idxA idxB
100  101     10    11    12    30    31    32    50    51    52
     102     13    14    15    33    34    35    53    54    55
200  101     16    17    18    36    37    38    56    57    58
     102     19    20    21    39    40    41    59    60    61


来源: stackexchange

问:
Print value of mapped data
I have a question I'm sure it's something easy but I don't find solution.
I'm mapping an array of objects with objects looking like this:

```<code>{
   categoryFr: "Commande",
   categoryEn: "Order"
}
</code>```

Now I want to to print this data in a div so if I do this, it works I get Commande:

```<code>   <div>{categoryFr}</div>
</code>```

But I want to dynamically render accordingly to the language I tried :

```<code>  <div>`c.name${lang}`</div>
  <div>`${c.name}${lang}`</div>
</code>```

But the string categoryFr is printed instead of the value Commande.

答:
you can access it with something like:

```<code><div>{c[name + lang]}</div>
</code>```

since obj.property (obj.categoryFr) is the equivalent with obj[property] (obj["category" + "Fr"])

ContentLicense: CC BY-SA 4.0

Title: Print value of mapped data

Body:
I have a question I'm sure it's something easy but I don't find solution.
I'm mapping an array of objects with objects looking like this:

{
   categoryFr: "Commande",
   categoryEn: "Order"
}

Now I want to to print this data in a div so if I do this, it works I get Commande:

{categoryFr}

But I want to dynamically render accordingly to the language I tried :

`c.name${lang}`

`${c.name}${lang}`

But the string categoryFr is printed instead of the value Commande.

Body:
you can access it with something like:

<div>{c[name + lang]}</div>

since obj.property (obj.categoryFr) is the equivalent with obj[property] (obj["category" + "Fr"])


问:
PowerBI Embedded - Formatting disappears on render
I have a PowerBI report built in PowerBI desktop and displaying in a .net app using javascript.  We have basic cards with decimal values formatted as currencies or percentages (in the formatting ribbon in PowerBI desktop).  When the embedded report first displays in the web app, the formatting symbols ($, %) show for a split second and then disappear.  I've removed layout and any extra style sheets and javascripts from the page, but still get the behavior.  Have also set the localSettings in the JS config.  Any ideas?</p>

答:
It's not a great solution, but a potential workaround would be to format the values using the FORMAT function which changes them to be text strings in the format you define rather than numeric values that get formatted however it decides.

For example, if you have a [measure] you can define another one like this:

```<code>measure_formatted = FORMAT ( [measure], "$ #,0.00")
</code>```

Body:
It's not a great solution, but a potential workaround would be to format the values using the FORMAT function which changes them to be text strings in the format you define rather than numeric values that get formatted however it decides.

For example, if you have a [measure] you can define another one like this:

measure_formatted = FORMAT ( [measure], "$ #,0.00")


问:
Add Social Login (FB/Google) to Cordova Typescript project
I've tried to convert my angular app to cordova follows this tutorial.
I done it but now i'm facing the problem to convert my social login (Facebook Login and Google) to cordova. Currently i'm using angular-6-social-login on web, but on cordova i can't get any dialog when i click "Sign In with" buttons. I get some errors in Console (when simulating iOS in browser):

```<code>The method FB.login can no longer be called from http pages. https://developers.facebook.com/blog/post/2018/06/08/enforce-https-facebook-login/
sdk.js?hash=3160dd80d8bcaa25ffc3fc1ccc6adb00:259
ERROR
</code>```

And in IOS:
facebook error

because of http://localhost.
For google login i get this.
My question is: Is there any way to fix it?
Cordova plugins is in JS(cordova-plugin-googleplus) and i can't see docs for Typescript.
Should i use cordova plugins (JS) or angular-6-social-login ?
Thanks for help.

答:
There is some plugins for this in cordova with types folder.
This is for Facebook and this is for google.
Enjoy.</p>

Body:
I've tried to convert my angular app to cordova follows this tutorial.
I done it but now i'm facing the problem to convert my social login (Facebook Login and Google) to cordova. Currently i'm using angular-6-social-login on web, but on cordova i can't get any dialog when i click "Sign In with" buttons. I get some errors in Console (when simulating iOS in browser):

The method FB.login can no longer be called from http pages. https://developers.facebook.com/blog/post/2018/06/08/enforce-https-facebook-login/
sdk.js?hash=3160dd80d8bcaa25ffc3fc1ccc6adb00:259
ERROR

And in IOS:
facebook error

because of http://localhost.
For google login i get this.
My question is: Is there any way to fix it?
Cordova plugins is in JS(cordova-plugin-googleplus) and i can't see docs for Typescript.
Should i use cordova plugins (JS) or angular-6-social-login ?
Thanks for help.


问:
Mismatched libraries in Debian Buster?
Note: all this work is being done on a closed network (i.e. no internet access).

I am being bitten by the GCC 5.0+ STL changes that occurred. It has been stated is other posts that starting in GCC 5.0 the Standard Template Libraries went through an update where there is now legacy stl and strict compliance stl. Code built with _GLIBCXX_USE_CXX11_ABI 1 does not link with code built with _GLIBCXX_USE_CXX11_ABI 0. A setting of 0 denotes legacy stl (i.e. std::string), whereas set to 1 constructs std::__cxx11::string.

OK fine that can be worked with if all user code is rebuilt to match the new libraries, but what if the debian packages are not built the same??? Now what?

Case in point, upgraded a Debian 8.11 (Jessie) system to 10.3 (Buster), included in the upgrade was Boost and Protobuf.
Now build my software using the default _GLIBCXX_USE_CXX11_ABI 1 and get link errors with Protobuf because it appears Protobuf was built with either pre-gcc 5.0 or ABI set to 0. Boost has other issues that it cannot find some std::__cxx1112::string (saw this once) or just std::string.

Downloaded the source for Boost, transferred to closed network, and built using ABI 1, my code now links to boost but still fails the link to protobuf.
Built Boost and my code with ABI 0, now link is successful with both.

Still in the process of getting a new mirror of Buster to determine if that will resolve, however the version I do have has mismatched libraries (incompatible)

This is just a warning that not all may be as it seems.

Boost went from 1_55 to 1_67, protobuf 9 to 17, gcc 4.8 to 8. Furthermore as of the writing of this post Glassfish is not compatible with the Buster version of JDK.

答:
I was also at the question leading up to this one.

I'll pick a few points to address:

OK fine that can be worked with if all user code is rebuilt to match the new libraries

Indeed

but what if the debian packages are not built the same??? Now what?

That's not typically what happens. Debian's QA and build servers are very highly controlled, and situations like this cannot arise unless someone slips up really badly - and even then it would immediately be noticed in testing unless the package has no users.

[...] get link errors with Protobuf because it appears Protobuf was built with either pre-gcc 5.0 or ABI set to 0 [...]

If you seem to be in this situation still, we can do some analysis like in my former answer, but this time for libprotobufX. What could be happening is

you have rogue (non-distro) shared libraries in your library path(s) (check ldconfig, LD_LIBRARY_PATH, -L flags)

Alternatively on a succesful link (so with the workaround) check with ldd on your linked binaries that it loads libprotobufXXX.so from the expected location. If there's an unexpected location, there may be

an ldconfig location as mentioned above

there may be RPATH/RUNPATH entries baked into the ELF image by the linker (look for -Wl,rpath or similar in your build scripts). To inspect the binary to confirm this:

```<code>  objdump -x binary-or-library |grep RPATH
  objdump -x binary-or-library |grep RUNPATH
</code>```

your upgrade might not have successfully updated that package (check the upgrade process for errors, the status of your repo-mirror)

you have a non-Debian (or non-supported) apt sources list (check /etc/apt/sources.list, /etc/apt/sources.list.d/*.list) - those builds may not uphold the same level of distro consistency

Sideline, usually canonical launchpad PPAs tend to reuse the distro build infrastructure so I think they're usually fine as long as the distro/component entries match your installation

Alternatively, you can inspect the contents of the APT caches after a full apt-get update using e.g.

```<code> apt-cache show libprotobuf.*
</code>```

Incidentally this will also give you the maintainers and contact addresses in case you do find a problem with the package. (There might be bug trackers better suited for this, I'm not known in this territory)

Hope this helps you find a lead

Still in the process of getting a new mirror of Buster to determine if that will resolve

That sounds like a good step

however the version I do have has mismatched libraries (incompatible)

I'm not sure what that means

Boost went from 1_55 to 1_67, protobuf 9 to 17, gcc 4.8 to 8. Furthermore as of the writing of this post Glassfish is not compatible with the Buster version of JDK.

Whoa, these are big jumps. If JDK is an issue, IME it helps to install a Java 8 or 9 JDK/JRE and make it the default, e.g.

```<code>$ update-alternatives --config java
There are 2 choices for the alternative java (providing /usr/bin/java).
  Selection    Path                                            Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-11-openjdk-amd64/bin/java      1111      auto mode
  1            /usr/lib/jvm/java-11-openjdk-amd64/bin/java      1111      manual mode
* 2            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1081      manual mode
</code>```

Title: Mismatched libraries in Debian Buster?

Body:
I was also at the question leading up to this one.

I'll pick a few points to address:

OK fine that can be worked with if all user code is rebuilt to match the new libraries

Indeed

but what if the debian packages are not built the same??? Now what?

That's not typically what happens. Debian's QA and build servers are very highly controlled, and situations like this cannot arise unless someone slips up really badly - and even then it would immediately be noticed in testing unless the package has no users.

[...] get link errors with Protobuf because it appears Protobuf was built with either pre-gcc 5.0 or ABI set to 0 [...]

If you seem to be in this situation still, we can do some analysis like in my former answer, but this time for libprotobufX. What could be happening is

you have rogue (non-distro) shared libraries in your library path(s) (check ldconfig, LD_LIBRARY_PATH, -L flags)

Alternatively on a succesful link (so with the workaround) check with ldd on your linked binaries that it loads libprotobufXXX.so from the expected location. If there's an unexpected location, there may be

an ldconfig location as mentioned above

there may be RPATH/RUNPATH entries baked into the ELF image by the linker (look for -Wl,rpath or similar in your build scripts). To inspect the binary to confirm this:

  objdump -x binary-or-library |grep RPATH
  objdump -x binary-or-library |grep RUNPATH

your upgrade might not have successfully updated that package (check the upgrade process for errors, the status of your repo-mirror)

you have a non-Debian (or non-supported) apt sources list (check /etc/apt/sources.list, /etc/apt/sources.list.d/*.list) - those builds may not uphold the same level of distro consistency

Sideline, usually canonical launchpad PPAs tend to reuse the distro build infrastructure so I think they're usually fine as long as the distro/component entries match your installation

Alternatively, you can inspect the contents of the APT caches after a full apt-get update using e.g.

 apt-cache show libprotobuf.*

Incidentally this will also give you the maintainers and contact addresses in case you do find a problem with the package. (There might be bug trackers better suited for this, I'm not known in this territory)

Hope this helps you find a lead

Still in the process of getting a new mirror of Buster to determine if that will resolve

That sounds like a good step

however the version I do have has mismatched libraries (incompatible)

I'm not sure what that means

Boost went from 1_55 to 1_67, protobuf 9 to 17, gcc 4.8 to 8. Furthermore as of the writing of this post Glassfish is not compatible with the Buster version of JDK.

Whoa, these are big jumps. If JDK is an issue, IME it helps to install a Java 8 or 9 JDK/JRE and make it the default, e.g.

$ update-alternatives --config java
There are 2 choices for the alternative java (providing /usr/bin/java).
  Selection    Path                                            Priority   Status
------------------------------------------------------------
  0            /usr/lib/jvm/java-11-openjdk-amd64/bin/java      1111      auto mode
  1            /usr/lib/jvm/java-11-openjdk-amd64/bin/java      1111      manual mode
* 2            /usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java   1081      manual mode


问:
Which observables do Angular complete automatically?
Which observables produced by Angular are also completed by Angular?

For example:

HttpClient completes any observables as the request finishes

observables from the Router (parammap, queryparammap, etc) automatically complete when the route changes.

What other observables from Angular does Angular complete for you automatically and under what circumstances?

答:
The async pipe subscribes to an Observable or Promise and returns the
  latest value it has emitted. When a new value is emitted, the async
  pipe marks the component to be checked for changes. When the component
  gets destroyed, the async pipe unsubscribes automatically to avoid
  potential memory leaks.

(from https://angular.io/api/common/AsyncPipe)


问:
curl file upload with semicolons in filename
I'm implementing an automated, command line file uploader using curl to a servlet.

The problem is, I've got tens of thousands of files with semicolons (;) in the filenames. I'm well aware of the annoyance of this but it is a legacy app that continues to produce new files each day. Renaming is not really an option for compatibility reasons downstream.

I've tried quoting, escaping, converting to "%3b", fully qualifying the path... the obvious stuff... but nothing seems to work, and it fails to send from the client side. I'm on my mac (bundled curl version 7.21.3) but that shouldn't make a difference?

Any ideas?

```<code>macbookpro:~$ curl -F upload=@"my file.txt" http://localhost:8080/data/upload
ok
macbookpro:~$ curl -F upload=@"my;file.txt" http://localhost:8080/data/upload
curl: (26) failed creating formpost data
macbookpro:~$ curl -F upload=@"my\;file.txt" http://localhost:8080/data/upload
curl: (26) failed creating formpost data
macbookpro:~$ curl -F upload=@"my\\;file.txt" http://localhost:8080/data/upload
curl: (26) failed creating formpost data
macbookpro:~$
</code>```

答:
According to CURL man pages, when you have ; or , in your form data(file or raw) you should always enclose it in double quotes.
CURL MAN

So just enclose the filename in double quotes and it should work

ContentLicense: CC BY-SA 3.0

Body:
I'm implementing an automated, command line file uploader using curl to a servlet.

The problem is, I've got tens of thousands of files with semicolons (;) in the filenames. I'm well aware of the annoyance of this but it is a legacy app that continues to produce new files each day. Renaming is not really an option for compatibility reasons downstream.

I've tried quoting, escaping, converting to "%3b", fully qualifying the path... the obvious stuff... but nothing seems to work, and it fails to send from the client side. I'm on my mac (bundled curl version 7.21.3) but that shouldn't make a difference?

Any ideas?

macbookpro:~$ curl -F upload=@"my file.txt" http://localhost:8080/data/upload
ok
macbookpro:~$ curl -F upload=@"my;file.txt" http://localhost:8080/data/upload
curl: (26) failed creating formpost data
macbookpro:~$ curl -F upload=@"my\;file.txt" http://localhost:8080/data/upload
curl: (26) failed creating formpost data
macbookpro:~$ curl -F upload=@"my\\;file.txt" http://localhost:8080/data/upload
curl: (26) failed creating formpost data
macbookpro:~$


问:
Sonar + Jacoco + Junit 5 : No information about coverage per test
I am trying to get coverage per test feature working with Sonarqube 7.

I am using jacoco-maven-plugin and my tests are running with JUnit 5.

I successfully managed to get global Coverage on Sonarqube dashboard, but I would like to go deeper by being able to see which tests covered which lines of my classes.

I've tried with the given configuration here but without success : I get the following message in the logs 'No information about coverage per test'. I see that this can be obtained by adding a listener org.sonar.java.jacoco.JUnitListener, but it is a JUnit 4 listener, so I guess it is not working because of that.

How can I manage to make the Coverage per test feature work with JUnit 5 ?

答:
I have some problem and solved change version of surefire-plugin:</p>

```<code><plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.22.2</version>
</plugin>
</code>```

Body:
I have some problem and solved change version of surefire-plugin:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>2.22.2</version>
</plugin>


问:
Javascript Add a mouseup event to the chart and use that instead of '3' key
I would like to modify the example below to add a mouseup event to the chart and use that instead of '3' key. So, when the user clicks mouse button while on the chart, server code will send new data.</p>

```<code>// Now, setup the keyboard event function
window.onload = function(){
 document.addEventListener("keypress", mKey);
}

function mKey(e) {

     if (e.key == "1") // transform chart
     {
       my_bar = !my_bar; //change the state, then transform
       if (my_bar ==true)
         chart.transform('bar');
       else
         chart.transform('line');
     }
     else if (e.key == "2") // transform chart
     {
       my_spline = !my_spline; //change the state, then transform
       if (my_spline==true)
         chart.transform('spline');
       else
         chart.transform('line');
     }
     else if (e.key == "3") // send message to Shiny
    {
       Shiny.onInputChange("clickedkey", [e.key, Math.random()]);
    }
}
</code>```

答:
Is this what you are looking for?

```<code>function mouseup(){
    Shiny.onInputChange("mouseup", [Math.random()]);
}

window.onload = function(){
     document.addEventListener("mouseup", mouseup);
     document.addEventListener("keypress", mKey);
}
</code>```

Then get rid of the 3 key else if statement

Body:
I would like to modify the example below to add a mouseup event to the chart and use that instead of '3' key. So, when the user clicks mouse button while on the chart, server code will send new data.

// Now, setup the keyboard event function
window.onload = function(){
 document.addEventListener("keypress", mKey);
}

function mKey(e) {

     if (e.key == "1") // transform chart
     {
       my_bar = !my_bar; //change the state, then transform
       if (my_bar ==true)
         chart.transform('bar');
       else
         chart.transform('line');
     }
     else if (e.key == "2") // transform chart
     {
       my_spline = !my_spline; //change the state, then transform
       if (my_spline==true)
         chart.transform('spline');
       else
         chart.transform('line');
     }
     else if (e.key == "3") // send message to Shiny
    {
       Shiny.onInputChange("clickedkey", [e.key, Math.random()]);
    }
}

Body:
Is this what you are looking for?

function mouseup(){
    Shiny.onInputChange("mouseup", [Math.random()]);
}

window.onload = function(){
     document.addEventListener("mouseup", mouseup);
     document.addEventListener("keypress", mKey);
}

Then get rid of the 3 key else if statement


问:
BigInteger modPow with BigDecimal exponent
I need a calculation of a BigInteger modPow, but with a BigDecimal as exponent.

Converting to double or using BigDecimal.pow and then mod is not possible in this case, since the full result without the mod will not fit into memory.
(and double lacks precision)
So converting to BigInteger with proper scale is out of question too.

I have found no library or similar for that.

Is it even mathematically possible to do an efficient modPow with a fractioned exponent without calculating the full exponentiation before?

EDIT:
Example

```<code>BigInteger base = BigInteger.valueOf("101");
BigDecimal exp = BigDecimal.valueOf("24.387207613444534);
BigInteger mod = BigInteger.valueOf("10403");

BigInteger result = base.modPow(exp, mod)
</code>```

These sample numbers are very small, the intended use needs much bigger ones.
Its supposed to deliver the mod of a number that itself is too large to hold in RAM, but is log and an integer divisor are known.

答:
So i found a way in the meantime.
base ^ (floor(exp - 1)) as regular modPow
multiplied with
base ^ (1+ (exp - floor(exp))
Then floor and mod.
The last exponentiation with factor 1.x is still small enough to fit into RAM.</p>

Body:
I need a calculation of a BigInteger modPow, but with a BigDecimal as exponent.

Converting to double or using BigDecimal.pow and then mod is not possible in this case, since the full result without the mod will not fit into memory.
(and double lacks precision)
So converting to BigInteger with proper scale is out of question too.

I have found no library or similar for that.

Is it even mathematically possible to do an efficient modPow with a fractioned exponent without calculating the full exponentiation before?

EDIT:
Example

BigInteger base = BigInteger.valueOf("101");
BigDecimal exp = BigDecimal.valueOf("24.387207613444534);
BigInteger mod = BigInteger.valueOf("10403");

BigInteger result = base.modPow(exp, mod)

These sample numbers are very small, the intended use needs much bigger ones.
Its supposed to deliver the mod of a number that itself is too large to hold in RAM, but is log and an integer divisor are known.


问:
Spring: How to start the logic after initializing the app
I have implemented this logic

```<code>@Component
public class SomeUpdater {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    private ExecutorService executorService;

    @PostConstruct
    public void init(){
        executorService = Executors.newSingleThreadExecutor();
        executorService.execute(()->{
            //some logic
            applicationEventPublisher.publishEvent(new PurposeEvent(this, 5));
        });
    }

}

@Component
public class SomeClass {

    @EventListener
    public void update(PurposeEvent purposeEvent){
        //update
    }
}
</code>```

But I can see from the logs that listener for update (PurposeEvent purposeEvent) is initialized later than the method applicationEventPublisher.publishEvent(new PurposeEvent(this, 5)); is called. How can I call logic after initialization? I tried using @EventListener for ContextRefreshedEvent, but as far as I understand, it can be called multiple times

答:
You can you annotation @DependsOn which can force the Spring container to initialize one or more beans before the bean annotated with @DependsOn annotation.
Then you'll be sure that SomeClass will be initialized before SomeUpdater.

The long term solution would be:

Spring Boot startup hooks

Spring Event types, like ApplicationStartedEvent, ApplicationReadyEvent.

Useful links:
http://dolszewski.com/spring/running-code-on-spring-boot-startup/
http://javainfinite.com/spring-boot/springboot-applicationreadyevent-applicationfailedevent-contextrefreshedevent/

Body:
I have implemented this logic

@Component
public class SomeUpdater {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    private ExecutorService executorService;

    @PostConstruct
    public void init(){
        executorService = Executors.newSingleThreadExecutor();
        executorService.execute(()->{
            //some logic
            applicationEventPublisher.publishEvent(new PurposeEvent(this, 5));
        });
    }

}

@Component
public class SomeClass {

    @EventListener
    public void update(PurposeEvent purposeEvent){
        //update
    }
}

But I can see from the logs that listener for update (PurposeEvent purposeEvent) is initialized later than the method applicationEventPublisher.publishEvent(new PurposeEvent(this, 5)); is called. How can I call logic after initialization? I tried using @EventListener for ContextRefreshedEvent, but as far as I understand, it can be called multiple times


问:
Can I set a element of my mongoose model to be strictly of some particular other models?
My subsection model should strictly be a type of lecture or quiz model only.
I want something like this. Any idea how to implement it properly?

```<code>const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;

const subSectionSchema = new mongoose.Schema({
  subSection:{
      type:ObjectId,
      enum:["Lecture","Quiz"]
  }
});
module.exports = mongoose.model("SubSection", subSectionSchema);

</code>```

Although I can always do this way...check which type it is and set that value.

```<code>const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;

const subSectionSchema = new mongoose.Schema({
  lecture: {
    type: ObjectId,
    ref: "Lecture",
  },
  quiz: {
    type: ObjectId,
    ref: "Quiz",
  },
});
module.exports = mongoose.model("SubSection", subSectionSchema);
</code>```

But I am looking for something simple.

答:
I'm not sure if I understood your question, but I think what you're looking for are dynamic references. This feature allow us to have dynamic properties on our MongoDB collection.

You'll basically need two properties for it, one for the ObjectID, other for the reference. Whenever you need to populate the reference, it will automatically detects which entity/collection to use.

Here's a quick example from Mongoose docs:

const commentSchema = new Schema({
  body: { type: String, required: true },
  on: {
    type: Schema.Types.ObjectId,
    required: true,
    // Instead of a hardcoded model name in `ref`, `refPath` means Mongoose
    // will look at the `onModel` property to find the right model.
    refPath: 'onModel'
  },
  onModel: {
    type: String,
    required: true,
    enum: ['BlogPost', 'Product']
  }
});

const Product = mongoose.model('Product', new Schema({ name: String }));
const BlogPost = mongoose.model('BlogPost', new Schema({ title: String }));
const Comment = mongoose.model('Comment', commentSchema);
```

Body:
My subsection model should strictly be a type of lecture or quiz model only.
I want something like this. Any idea how to implement it properly?

const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;

const subSectionSchema = new mongoose.Schema({
  subSection:{
      type:ObjectId,
      enum:["Lecture","Quiz"]
  }
});
module.exports = mongoose.model("SubSection", subSectionSchema);

Although I can always do this way...check which type it is and set that value.

const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;

const subSectionSchema = new mongoose.Schema({
  lecture: {
    type: ObjectId,
    ref: "Lecture",
  },
  quiz: {
    type: ObjectId,
    ref: "Quiz",
  },
});
module.exports = mongoose.model("SubSection", subSectionSchema);

But I am looking for something simple.


问:
Checking Duplicate Records in Table Where Id is Identity
In my table, ID is primary key field and identity column.
I want to check duplicate records.
(Certainly duplicate records do not have same ID)

And do not have date fields same.

How do I check this.

Extra Detail: I have 10 columns with 1 ID, 2 Date, and other 3 string, 3 Int, 1 bit.

Thansk in Advance.

答:
You can use GROUP BY to group similar records to count them, and then add a HAVING clause to filter out only those that occur more than once:

```<code>select StringCol1, StringCol2, StringCol3, IntCol1, IntCol2, IntCol3, BitCol1, count(*) as Count
from MyTable
group by StringCol1, StringCol2, StringCol3, IntCol1, IntCol2, IntCol3, BitCol1
having count(*) > 1
</code>```

Body:
You can use GROUP BY to group similar records to count them, and then add a HAVING clause to filter out only those that occur more than once:

select StringCol1, StringCol2, StringCol3, IntCol1, IntCol2, IntCol3, BitCol1, count(*) as Count
from MyTable
group by StringCol1, StringCol2, StringCol3, IntCol1, IntCol2, IntCol3, BitCol1
having count(*) > 1


问:
How to not use pylint-django in non Django file?
I'm new to the Django. I am currently use VS code as my code editor.

In order to work on the Django project, in the user settings of the VS code, I include the following code to use pylint_django as the default linter.

```<code>    "python.linting.pylintArgs": [
        "--load-plugins=pylint_django", "--errors-only"
    ],
</code>```

However, in another python file, which is just a regular python file, I got an error, saying "Django is not available on the PYTHONPATHpylint(django-not-available)"

If I comment the above code in the user setting, the error goes away. I think the problem is pylint-django is used as default linter, even for non-Django python file.

My question is I didn't find the solution to solve this problem. Could you please help me on this? Thank you so much. I really appreciate it.

答: The problem is solved when I uninstall the globally installed pylint_django.</p>

Body:
I'm new to the Django. I am currently use VS code as my code editor.

In order to work on the Django project, in the user settings of the VS code, I include the following code to use pylint_django as the default linter.

    "python.linting.pylintArgs": [
        "--load-plugins=pylint_django", "--errors-only"
    ],

However, in another python file, which is just a regular python file, I got an error, saying "Django is not available on the PYTHONPATHpylint(django-not-available)"

If I comment the above code in the user setting, the error goes away. I think the problem is pylint-django is used as default linter, even for non-Django python file.

My question is I didn't find the solution to solve this problem. Could you please help me on this? Thank you so much. I really appreciate it.


问:
SQL - Removing Row Groups
I have a table with the following information:

Is there a way to remove all groups which have multiple IDs? For example group 3 would be removed because it consists of ID 1 and 2.

Thank you!

答:
select * from temp where group in (
select groups from temp group by id,group having count(1)<3)

delete from temp where group in (
select groups from temp group by id,group having count(1)<3)

Title: SQL - Removing Row Groups


问:
IF Else with Jquery and input box
I am very very green with jquery.  I know the logic but am missing how to get this to work properly.

Basically this checks if the input box has the @ sign in it and if it does returns a message.  This is probably very simple but im lost at the moment.

```<code><script>
               $("input[name='email']").keyup(function () {
                 if($("#emailaddress").val().indexOf("@")){
                    $(".dynamic").html('Do Not include @domain.net');
                 }else{
                 $(".dynamic").html(this.value + '@domain.net');
                      }
             });
             </script>
</code>```

I also tried to make it so it just changes the background using this

```<code><script>
               $("input[name='email']").keyup(function () {
                 $(".dynamic").html(this.value + '@domain.net');

                 $("input[name='email']:contains(@)").css("background-color", "yellow");
             });
             </script>
</code>```

Neither work

Here is the part of my form i am looking at

```<code>    <div class="form-row">

          <div class="form-group col-md-auto ">
              <small id="emailHelp" class="form-text text-muted">Your Email Username Only <b>Do not include your FULL Email</b></small>
            <input type="text" class="form-control email" id="emailaddress" name="email" placeholder="Your E-mail username ONLY IE: johns" required >
          </div>
          <div class="form-group col-md-auto ">
            <small id="emailHelp" class="form-text text-muted"><br /></small>
            <div> <span class="dynamic" style="font-size: 26px"></span>
             <span class="static" style="font-size: 26px"></span>
             <script>
               $("input[name='email']").keyup(function () {
                 if($("#emailaddress").val().indexOf("@")){
                    $(".dynamic").html('Do NOt include @domain.net')
                 }
                 $(".dynamic").html(this.value + '@domain.net') <-----This works

             });
             </script>

            </div>
          </div>

    </div>
</code>```

答:
Just replace condition to $("#emailaddress").val().indexOf("@")>=0. The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.

```<code>$("input[name='email']").keyup(function () {
  if($("#emailaddress").val().indexOf("@")>=0){
    $(".dynamic").html('Do Not include @domain.net');
  }else{
    $(".dynamic").html(this.value + '@domain.net');
  }
});
</code>```

See in playground: https://jsfiddle.net/denisstukalov/exw78vfp/3/#&togetherjs=Io1neFKzQu

Title: IF Else with Jquery and input box

Body:
I am very very green with jquery.  I know the logic but am missing how to get this to work properly.

Basically this checks if the input box has the @ sign in it and if it does returns a message.  This is probably very simple but im lost at the moment.

I also tried to make it so it just changes the background using this

Neither work

Here is the part of my form i am looking at

              Your Email Username Only Do not include your FULL Email
            <input type="text" class="form-control email" id="emailaddress" name="email" placeholder="Your E-mail username ONLY IE: johns" required >

Body:
Just replace condition to $("#emailaddress").val().indexOf("@")>=0. The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found.

$("input[name='email']").keyup(function () {
  if($("#emailaddress").val().indexOf("@")>=0){
    $(".dynamic").html('Do Not include @domain.net');
  }else{
    $(".dynamic").html(this.value + '@domain.net');
  }
});

See in playground: https://jsfiddle.net/denisstukalov/exw78vfp/3/#&togetherjs=Io1neFKzQu


问:
C++: initialize vs assignment?
I'm reading Stroustrups C++ 4th Ed. Page 153 and have questions about initialization vs assignment.  It's my understanding that initialization is occurs in the constructor and assignment in operator= overloaded function.  Is this correct?

Also, I don't recall seeing the brackets i.e. int count {1} in his 1998 3rd Ed. book.  Should I be defining variables like counters using int count {1} or int count = 1?  Seems like an awkward difference from C if using the brackets.

Thanks for your guidance

```<code>void f() {
   int count {1}; // initialize count to 1
   const char∗ name {"Bjarne"}; // name is a    variable that points to a constant (§7.5)
   count = 2; // assign 2 to count
   name = "Marian";
}
</code>```

答:
The curly braces is part of uniform initialization which was added with the C++11 standard.

Using

```<code>int value {1};
</code>```

is equivalent to

```<code>int value = 1;
</code>```

There's some differences between using curly braces and "assignment" syntax for initialization of variables, but in this simple case they're equal.

Title: C++: initialize vs assignment?

Body:
I'm reading Stroustrups C++ 4th Ed. Page 153 and have questions about initialization vs assignment.  It's my understanding that initialization is occurs in the constructor and assignment in operator= overloaded function.  Is this correct?

Also, I don't recall seeing the brackets i.e. int count {1} in his 1998 3rd Ed. book.  Should I be defining variables like counters using int count {1} or int count = 1?  Seems like an awkward difference from C if using the brackets.

Thanks for your guidance

void f() {
   int count {1}; // initialize count to 1
   const char∗ name {"Bjarne"}; // name is a    variable that points to a constant (§7.5)
   count = 2; // assign 2 to count
   name = "Marian";
}

Body:
The curly braces is part of uniform initialization which was added with the C++11 standard.

Using

int value {1};

is equivalent to

int value = 1;

There's some differences between using curly braces and "assignment" syntax for initialization of variables, but in this simple case they're equal.


问:
MVC- Retrieve the original value of an EditorFor
On the edit page of my website I want users to be able to edit qty's and then have it change the model. This is why I am using 'editorFor'. The problem is that I still want to return the value of the model before it was edited to the controller post method.

For example, if a user edited a qty from 7 to 10, I would want the model to change to 10 but I would also want the view to return 7 to the controller. How can I do this?

Here is my editorFor code

```<code>  <div class="form-group">
            @Html.LabelFor(model => model.item_qty, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.item_qty, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.item_qty, "", new { @class = "text-danger" })
            </div>
  </div>
</code>```

Here is my edit post method

```<code>[RestrictAccess(restriction = AccessRestrictions.ModifyWorkOrder)]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Audit]
        public ActionResult Edit([Bind(Include = "ID,JobOrderID,StartDate,CompleteDate,jobSection,ItemID,item_qty,actual_item_qty,ComponentID,comp_qty,actual_comp_qty,PartID,part_qty,actual_part_qty,Notes,subDetail")] JODetails jODetails)
        {
            if (ModelState.IsValid)
            {
                JobOrder jo = db.JobOrders.Find(jODetails.JobOrderID);

                    db.Entry(jODetails).State = EntityState.Modified;

                    JODetails currentData = db.JODetails.Find(jODetails.ID);
                    Component comp = db.Components.Find(jODetails.ComponentID);
                    Item i = db.Items.Find(jODetails.ItemID);

                    int newItemCount = jODetails.item_qty != null ? (int)jODetails.item_qty : 0;
                    int oldItemCount = 0;
                    int itemDiff = newItemCount - oldItemCount;

           }
</code>```

答:
If I understand well enough, you don't need to return the value from the view. When the model is passed to the controller the value in the database has not been changed, you can read it again. Something like this:

// First. Grab the previous quantity...
// This approach won't work because of EF is already TRACKING the entity
// JODetails currentData = db.JODetails.Find(jODetails.ID);
// So, you have to access data like this...
var currentData = db.JODetails.AsNoTracking().FirstOrDefault(j => j.ID == jODetails.ID);

int previousQuantity = currentData?.item_qty;

//... do whatever with previousQuantity prop & new JODetails model. Don't forget to check if currentData is null

// Just NOW. Mutate the object via EF...
db.Entry(jODetails).State = EntityState.Modified;

// THEN. Commit changes...
db.SaveChanges();
```

It's not until you SaveChanges() that the record in the database it's really changed. Read some docs about how EF tracks, modifies & save objects.

This could be very helpful to understand this...

https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/examining-the-edit-methods-and-edit-view

Of course if you NEED to retrieve the Quantity data from the view (can't see why) there are some alternatives such as a ViewModel but I think this would do the trick. Yes, with this approach there's one more trip to the database, but it's minimal.

Body:
On the edit page of my website I want users to be able to edit qty's and then have it change the model. This is why I am using 'editorFor'. The problem is that I still want to return the value of the model before it was edited to the controller post method.

For example, if a user edited a qty from 7 to 10, I would want the model to change to 10 but I would also want the view to return 7 to the controller. How can I do this?

Here is my editorFor code

            @Html.LabelFor(model => model.item_qty, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.item_qty, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.item_qty, "", new { @class = "text-danger" })

Here is my edit post method

[RestrictAccess(restriction = AccessRestrictions.ModifyWorkOrder)]
        [HttpPost]
        [ValidateAntiForgeryToken]
        [Audit]
        public ActionResult Edit([Bind(Include = "ID,JobOrderID,StartDate,CompleteDate,jobSection,ItemID,item_qty,actual_item_qty,ComponentID,comp_qty,actual_comp_qty,PartID,part_qty,actual_part_qty,Notes,subDetail")] JODetails jODetails)
        {
            if (ModelState.IsValid)
            {
                JobOrder jo = db.JobOrders.Find(jODetails.JobOrderID);

                    db.Entry(jODetails).State = EntityState.Modified;

                    JODetails currentData = db.JODetails.Find(jODetails.ID);
                    Component comp = db.Components.Find(jODetails.ComponentID);
                    Item i = db.Items.Find(jODetails.ItemID);

                    int newItemCount = jODetails.item_qty != null ? (int)jODetails.item_qty : 0;
                    int oldItemCount = 0;
                    int itemDiff = newItemCount - oldItemCount;

           }

Body:
If I understand well enough, you don't need to return the value from the view. When the model is passed to the controller the value in the database has not been changed, you can read it again. Something like this:

// First. Grab the previous quantity...
// This approach won't work because of EF is already TRACKING the entity
// JODetails currentData = db.JODetails.Find(jODetails.ID);
// So, you have to access data like this...
var currentData = db.JODetails.AsNoTracking().FirstOrDefault(j => j.ID == jODetails.ID);

int previousQuantity = currentData?.item_qty;

//... do whatever with previousQuantity prop & new JODetails model. Don't forget to check if currentData is null

// Just NOW. Mutate the object via EF...
db.Entry(jODetails).State = EntityState.Modified;

// THEN. Commit changes...
db.SaveChanges();

It's not until you SaveChanges() that the record in the database it's really changed. Read some docs about how EF tracks, modifies & save objects.

This could be very helpful to understand this...

https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/examining-the-edit-methods-and-edit-view

Of course if you NEED to retrieve the Quantity data from the view (can't see why) there are some alternatives such as a ViewModel but I think this would do the trick. Yes, with this approach there's one more trip to the database, but it's minimal.


问:
Errors in sorting a dictionary
This is my code to find and print values of students with the second-lowest score in the given data

```<code>room =dict()
for _ in range(int(input())):
    name = input()
    score = float(input())
    room.update({name:score})

lowest= min(room.values())
second_lowest = None
for k,v in sorted(room.items(),reverse=True):
    if v == lowest: continue
    elif second_lowest is None:
        second_lowest = v
    elif v < second_lowest:
        second_lowest = v
    if second_lowest==v and second_lowest is not lowest:
        print('name',k)
</code>```

When given a specific set of inputs it returns more than two second_lowest key, for example, for the below input it returns harsh harry and berry where it shouldn't have returned harsh. But this problem disappears if I create a separate (key, value) loop with the same

```<code>sorted(room.items(),reverse=True)
</code>```

Sample Input:

```<code>5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
</code>```

Sample Output:

```<code>name Harsh
name Harry
name Berry
</code>```

答:
This is what you can do to find the second lowest scored student:</p>

```<code>lst = [val for val in room.values() if val != min(list(room.values()))]
for name in room.keys():
    if room[name] == min(lst):
        print('name',name)
</code>```

Title: Errors in sorting a dictionary

Body:
This is my code to find and print values of students with the second-lowest score in the given data

room =dict()
for _ in range(int(input())):
    name = input()
    score = float(input())
    room.update({name:score})

lowest= min(room.values())
second_lowest = None
for k,v in sorted(room.items(),reverse=True):
    if v == lowest: continue
    elif second_lowest is None:
        second_lowest = v
    elif v < second_lowest:
        second_lowest = v
    if second_lowest==v and second_lowest is not lowest:
        print('name',k)

When given a specific set of inputs it returns more than two second_lowest key, for example, for the below input it returns harsh harry and berry where it shouldn't have returned harsh. But this problem disappears if I create a separate (key, value) loop with the same

sorted(room.items(),reverse=True)

Sample Input:

5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39

Sample Output:

name Harsh
name Harry
name Berry

Body:
This is what you can do to find the second lowest scored student:

lst = [val for val in room.values() if val != min(list(room.values()))]
for name in room.keys():
    if room[name] == min(lst):
        print('name',name)


问:
Using Pillow for python 3.7 Mac OS?
I have Pillow installed successfully on my Mac, but when I type in

```<code>from PIL import Image
</code>```

I get an error: "Unable to import 'PIL'

I'm using VSCode by the way. Anyone know how to fix this? I've looked through almost every stack overflow post, but can't seem to figure it out. I tried uninstalling and reinstalling, deleting PIL, etc. I have Pillow-7.1.2 by the way.

答:
If you installed Pillow with:

```<code>pip install pillow
</code>```

then you can find where it is installed with:

```<code>pip show pillow
</code>```

Sample Output

```<code>Name: Pillow
Version: 7.1.2
Summary: Python Imaging Library (Fork)
Home-page: https://python-pillow.org
Author: Alex Clark (PIL Fork Author)
Author-email: aclark@python-pillow.org
License: HPND
Location: /usr/local/lib/python3.7/site-packages     <--- HERE
</code>```

Of course, if you installed with:

```<code>pip3 install pillow
</code>```

you will need:

```<code>pip3 show pillow
</code>```

Now go to your Python interpreter and check where it is looking for packages and you will surely work out the problem:

```<code>python3 -c "import sys; print(sys.path)" | tr , '\n'
</code>```

Samnple output

```<code>[
'/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python36.zip'
'/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6'
'/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload'
'/usr/local/lib/python3.6/site-packages'
'/usr/local/Cellar/numpy/1.13.3/libexec/nose/lib/python3.6/site-packages']
</code>```

Of course, if you start Python with python rather than python3, you will need:

```<code>python -c "import sys; print(sys.path)" | tr , '\n'
</code>```

Finally, go to your Terminal and find out what your shell actually runs when you enter python by running:

```<code>type python            # or "type python3" if you normally enter "python3"
</code>```

Now go in your IDE and see which Python that runs:

```<code>import sys
print(sys.executable)
</code>```

Title: Using Pillow for python 3.7 Mac OS?

Body:
I have Pillow installed successfully on my Mac, but when I type in

from PIL import Image

I get an error: "Unable to import 'PIL'

I'm using VSCode by the way. Anyone know how to fix this? I've looked through almost every stack overflow post, but can't seem to figure it out. I tried uninstalling and reinstalling, deleting PIL, etc. I have Pillow-7.1.2 by the way.

Body:
If you installed Pillow with:

pip install pillow

then you can find where it is installed with:

pip show pillow

Sample Output

Name: Pillow
Version: 7.1.2
Summary: Python Imaging Library (Fork)
Home-page: https://python-pillow.org
Author: Alex Clark (PIL Fork Author)
Author-email: aclark@python-pillow.org
License: HPND
Location: /usr/local/lib/python3.7/site-packages     <--- HERE

Of course, if you installed with:

pip3 install pillow

you will need:

pip3 show pillow

Now go to your Python interpreter and check where it is looking for packages and you will surely work out the problem:

python3 -c "import sys; print(sys.path)" | tr , '\n'

Samnple output

[
'/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python36.zip'
'/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6'
'/usr/local/Cellar/python3/3.6.3/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload'
'/usr/local/lib/python3.6/site-packages'
'/usr/local/Cellar/numpy/1.13.3/libexec/nose/lib/python3.6/site-packages']

Of course, if you start Python with python rather than python3, you will need:

python -c "import sys; print(sys.path)" | tr , '\n'

Finally, go to your Terminal and find out what your shell actually runs when you enter python by running:

type python            # or "type python3" if you normally enter "python3"

Now go in your IDE and see which Python that runs:

import sys
print(sys.executable)


问:
Enable CORS with Teapot in Smalltalk
I am creating a REST API in smalltalk with Teapot http://smalltalkhub.com/#!/~zeroflag/Teapot

But then I can not consume the data from my web application since CORS is disabled.

Access to XMLHttpRequest at 'http://localhost:8080/components' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I can't find a way to make it work. I analyzed the code and the docs with no sucess.

Any idea?

答:
The solution is : </p>

```<code>teapot after: '/*' -> [:req :resp | resp headers at: 'Access-Control-Allow-Origin' put: '*'];
</code>```

Title: Enable CORS with Teapot in Smalltalk

Body:
The solution is :

teapot after: '/*' -> [:req :resp | resp headers at: 'Access-Control-Allow-Origin' put: '*'];


问:
External Static(.a) Libraries in iPhone projects
Over the last few months I've come across various chatter of external/private libraries not being allowed in iPhone apps.[Just to be clear, this is not something thats going to come, its something I was wrongly under the impression that already exists.]

I was looking at the WunderRadio source: http://www.wunderradio.com/code.html
and I noticed they have 3+ .a files in there project.

libcCommon.a liblibmms.a and libffmpegLib.a are the ones I'm looking at.

Have I been misinformed about the use of this kinda of libraries in iPhone projects? Will Apple accept and approve projects that are using them? If so what is it thats not allowed? Is it just use of Apples own private and undocumented libraries, but you are allowed to include your own?

Many Thanks,
-Code

答: Static libraries have always been allowed for iOS development and there is no sign that position is going to change at any point (why would it?). Dynamic libraries are not allowed and will result in the rejection of your app. </p>


问:
Python IDE PyCharm won't print last line of code
I'm a complete newbie when it comes to coding, so I'm probably making a stupid mistake here. What I'm doing is following along with a Python For Beginners textbook and writing the 'Hello World' exercise. I added the variable 'name' to the code and called the variable in the very next line. However, the
print('Hello', name) line of code I wrote would not print, even though my first line print('Hello, world') did print. Here's a screenshot of the code run on the Python console There are no error codes, so I'm guessing I just incorrectly defined the variable, but I'm not sure. </p>

答:
You need to hit Enter after Python prints 'Keenan' to print the last line.

When you call input(str), str is the prompt. Once python prints the prompt, it's waiting for an input and then Enter.

So logically speaking your code should be:

```<code>name = input("What's your name?:")
print('Hello', name)
</code>```

Which will print:

What's your name?:
```

<p>where you can type:</p>

<pre class="lang-none prettyprint-override"><code>What's your name?: Keenan
</code>```

followed by Enter

Body:
You need to hit Enter after Python prints 'Keenan' to print the last line.

When you call input(str), str is the prompt. Once python prints the prompt, it's waiting for an input and then Enter.

So logically speaking your code should be:

name = input("What's your name?:")
print('Hello', name)

Which will print:

What's your name?:

where you can type:

What's your name?: Keenan

followed by Enter


问:
How to increment count id for each insert and every loop iteration?
I have for loop that should increment count_id for every query and each loop iteration. Here is example of my code:

```<code>qryCode = queryExecute("SELECT max(display_order) AS maxdisplay FROM type_ref",{},{datasource: application.datasource}); // Result set of the query is: 58
qryItems = queryExecute("SELECT DISTINCT type_id, label, type_shortcode FROM types gtr WHERE item_id = :item_id",{item_id: {cfsqltype: "cf_sql_numeric",value: arguments.item_id}},{datasource: application.datasource});

// Result set of qryItems:
TYPE_ID  LABEL    TYPE_SHORTCODE
1        2012-1   HOA
2        2012-1   HOC
5        2012-1   HOR

local.display_count = qryCode.maxdisplay;

for ( row in qryItems ) {
    local.sqlInsert &= " INSERT INTO type_ref (display_order) VALUES (?) ";
    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: display_count+1});
    local.sqlInsert &= " INSERT INTO type_ref (display_order) VALUES (?) ";
    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: display_count+2});
    display_count++;
}
</code>```

The code above will increment first two values correct (59 & 60) but for the second iteration it will start from 60 instead of 61. The code should produce count_id's int his order: 59,60,61,62,63,64. There are three records in qryItems. The qryCode has max value of 58. The first query in first iteration should start from 58 + 1 = 59. The next one should be 58 + 2 = 60. In the second iteration the first count_id should be 61 and so on. I'm not sure why the code I have above starts second iteration from 60 instead of 61. I do have this line that should increase the count_id at the end of each iteration: display_count++;.

答:
It's because you're doing 2 inserts per iteration, therefore you should increment display_count by 2 instead of 1.  So your for loop should look like this instead.

```<code>for ( row in qryItems ) {
    local.sqlInsert &= " INSERT INTO type_ref (display_order) VALUES (?) ";
    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: display_count+1});
    local.sqlInsert &= " INSERT INTO type_ref (display_order) VALUES (?) ";
    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: display_count+2});
    display_count +=2;
}
</code>```

Body:
I have for loop that should increment count_id for every query and each loop iteration. Here is example of my code:

qryCode = queryExecute("SELECT max(display_order) AS maxdisplay FROM type_ref",{},{datasource: application.datasource}); // Result set of the query is: 58
qryItems = queryExecute("SELECT DISTINCT type_id, label, type_shortcode FROM types gtr WHERE item_id = :item_id",{item_id: {cfsqltype: "cf_sql_numeric",value: arguments.item_id}},{datasource: application.datasource});

// Result set of qryItems:
TYPE_ID  LABEL    TYPE_SHORTCODE
1        2012-1   HOA
2        2012-1   HOC
5        2012-1   HOR

local.display_count = qryCode.maxdisplay;

for ( row in qryItems ) {
    local.sqlInsert &= " INSERT INTO type_ref (display_order) VALUES (?) ";
    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: display_count+1});
    local.sqlInsert &= " INSERT INTO type_ref (display_order) VALUES (?) ";
    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: display_count+2});
    display_count++;
}

The code above will increment first two values correct (59 & 60) but for the second iteration it will start from 60 instead of 61. The code should produce count_id's int his order: 59,60,61,62,63,64. There are three records in qryItems. The qryCode has max value of 58. The first query in first iteration should start from 58 + 1 = 59. The next one should be 58 + 2 = 60. In the second iteration the first count_id should be 61 and so on. I'm not sure why the code I have above starts second iteration from 60 instead of 61. I do have this line that should increase the count_id at the end of each iteration: display_count++;.

Body:
It's because you're doing 2 inserts per iteration, therefore you should increment display_count by 2 instead of 1.  So your for loop should look like this instead.

for ( row in qryItems ) {
    local.sqlInsert &= " INSERT INTO type_ref (display_order) VALUES (?) ";
    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: display_count+1});
    local.sqlInsert &= " INSERT INTO type_ref (display_order) VALUES (?) ";
    qryParams.append({cfsqltype="CF_SQL_NUMERIC", value: display_count+2});
    display_count +=2;
}


问:
mathematica code that is not working according to wanted expression
enter image description here

I failed to do the following expression and make it give accurate results if any one can help me I will be glade. I attached my expression in a pic "want this" and my trial as "my trial". the correct answer must equal 0.119 when a=1, b=10, m=3, n=6. thanks a lot in advance.

```<code>a = 1
b = 10
m = 3
n = 6
a^1 b^n (Sum[
Sum[Sum[Sum[(-1)^(k + v - n + m + 1)
     If[k == 0, 1,
     SeriesCoefficient[Series[(-Log[1 - x])^k, {x, 0, 30}],
      p + k]] If[n - k - 2 == 0, 1,
     SeriesCoefficient[
      Series[(-Log[1 - x])^(n - k - 2), {x, 0, 30}],
      q + (n - k - 2)]]
    Binomial[n - m - 1, k] Binomial[b - 1,
     v] (-PolyGamma[0, -1 + 1/a - k + n + q] +
       PolyGamma[0, 2/a + n + p + q + v])/(a (1 + k + p + v) +
       1), {q, 0, 30 - (n - k - 2)}], {p, 0, 30 - k}], {v, 0,
  b - 1}], {k, 0, n - m - 1}])/((m - 1)! (n - m - 1)!)
</code>```

答: I found the solution for the problem. the problem was when the value of k was 0 the coefficient will not equal 1 but the whole expression must be found from the start for a value of k that will start from 1 and an expression when the value of k is 0. yet I failed to solve it using MATHEMATICA but by doing the above I succeed to get the correct result. thank you all for your precious time and opinions.</p>

Body:
enter image description here

I failed to do the following expression and make it give accurate results if any one can help me I will be glade. I attached my expression in a pic "want this" and my trial as "my trial". the correct answer must equal 0.119 when a=1, b=10, m=3, n=6. thanks a lot in advance.

a = 1
b = 10
m = 3
n = 6
a^1 b^n (Sum[
Sum[Sum[Sum[(-1)^(k + v - n + m + 1)
     If[k == 0, 1,
     SeriesCoefficient[Series[(-Log[1 - x])^k, {x, 0, 30}],
      p + k]] If[n - k - 2 == 0, 1,
     SeriesCoefficient[
      Series[(-Log[1 - x])^(n - k - 2), {x, 0, 30}],
      q + (n - k - 2)]]
    Binomial[n - m - 1, k] Binomial[b - 1,
     v] (-PolyGamma[0, -1 + 1/a - k + n + q] +
       PolyGamma[0, 2/a + n + p + q + v])/(a (1 + k + p + v) +
       1), {q, 0, 30 - (n - k - 2)}], {p, 0, 30 - k}], {v, 0,
  b - 1}], {k, 0, n - m - 1}])/((m - 1)! (n - m - 1)!)


问:
How to get maximum value for each group?
In the data frame(df), I need to insert a new column for each group of Sl defining its maximum Value.

```<code>df=data.frame(
  Sl= c(1,1,2,2,2,2,3,3,4,4,4,5),
Value= c(0,2,1,3,5,2,5,8,10,3,5,7)
)

#Expected outcome:
df$col3=c(2,2,5,5,5,5,5,10,10,7,7,7)
</code>```

答:
We can use max by group

```<code>library(dplyr)
df %>%
   group_by(ID) %>%
    mutate(col3 = max(Value))
</code>```

Body:
In the data frame(df), I need to insert a new column for each group of Sl defining its maximum Value.

df=data.frame(
  Sl= c(1,1,2,2,2,2,3,3,4,4,4,5),
Value= c(0,2,1,3,5,2,5,8,10,3,5,7)
)

#Expected outcome:
df$col3=c(2,2,5,5,5,5,5,10,10,7,7,7)

Body:
We can use max by group

library(dplyr)
df %>%
   group_by(ID) %>%
    mutate(col3 = max(Value))


问:
UIButton targets not working if a UIView is added as a subview
I have a UIButton. It has two subviews. I then call:

```<code>[createButton addTarget:self action:@selector(openComposer) forControlEvents:UIControlEventTouchUpInside];
</code>```

If I tap the parts of the UIButton that aren't covered but one of its subviews, it works fine. However if I tap one of the subviews instead, it does not trigger the action.

On both subviews, I has .userInteractionEnabled set to YES.

Both subviews are plain UIViewss with a frame and backgroundColor.

How can I get the tap to "pass through" the UIView and onto the UIButton?

Thanks

EDIT: I need to use UIControlEvents because I need UIControlEventTouchDown.

EDIT 2:

Here is the code for the button.

```<code>@interface CreateButton ()

@property (nonatomic) Theme *theme;
@property (nonatomic) UIView *verticle;
@property (nonatomic) UIView *horizontal;
@property (nonatomic) BOOL mini;

@end

@implementation CreateButton

#pragma mark - Accessors

- (UIView *)verticle {
    if (! _verticle) {
        _verticle = [[UIView alloc] init];
        _verticle.backgroundColor = [self.theme colorForKey:@"createButtonPlusBackgroundColor"];
        _verticle.userInteractionEnabled = NO;
    }
    return _verticle;
}

- (UIView *)horizontal {
    if (! _horizontal) {
        _horizontal = [[UIView alloc] init];
        _horizontal.backgroundColor = [self.theme colorForKey:@"createButtonPlusBackgroundColor"];
        _verticle.userInteractionEnabled = NO;
    }
    return _horizontal;
}

#pragma mark - Init

- (instancetype)initWithTheme:(Theme *)theme frame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _theme = theme;

        self.layer.cornerRadius = roundf(frame.size.width / 2);
        self.layer.shadowColor = [UIColor blackColor].CGColor;
        self.layer.shadowOpacity = .1f;
        self.layer.shadowOffset = CGSizeZero;
        self.layer.shadowRadius = 15.f;
        self.backgroundColor = [self.theme colorForKey:@"createButtonBackgroundColor"];

        [self addSubview:self.verticle];
        [self addSubview:self.horizontal];

        [self addTarget:self action:@selector(animate) forControlEvents:UIControlEventTouchDown];
        [self addTarget:self action:@selector(animate) forControlEvents:UIControlEventTouchUpInside];
        [self addTarget:self action:@selector(animate) forControlEvents:UIControlEventTouchUpOutside];
    }
    return self;
}

#pragma mark - Actions

- (void)animate {
    [UIView animateWithDuration:0.2 delay:0 usingSpringWithDamping:0.4 initialSpringVelocity:8 options:kNilOptions animations:^{
        if (self.mini) {
            self.transform = CGAffineTransformMakeScale(1.0, 1.0);
            self.mini = NO;
        } else {
            self.transform = CGAffineTransformMakeScale(0.90, 0.90);
            self.mini = YES;
        }
    } completion:nil];
}

#pragma mark - UIView

- (void)layoutSubviews {
    CGSize size = self.bounds.size;

    NSInteger width = 3;
    NSInteger verticleInset = 12;
    self.verticle.frame = CGRectMake((size.width - width) / 2, verticleInset, width, size.height - (verticleInset * 2));
    self.horizontal.frame = CGRectMake(verticleInset, (size.height - width) / 2, size.width - (verticleInset * 2), width);
}

@end
</code>```

答: In my case, there was a .xib file for the buttons below and I added this .xib to my ViewController. @IBActions refused to work due to setting constraints for the .xib file in ViewController.

Body:
I have a UIButton. It has two subviews. I then call:

[createButton addTarget:self action:@selector(openComposer) forControlEvents:UIControlEventTouchUpInside];

If I tap the parts of the UIButton that aren't covered but one of its subviews, it works fine. However if I tap one of the subviews instead, it does not trigger the action.

On both subviews, I has .userInteractionEnabled set to YES.

Both subviews are plain UIViewss with a frame and backgroundColor.

How can I get the tap to "pass through" the UIView and onto the UIButton?

Thanks

EDIT: I need to use UIControlEvents because I need UIControlEventTouchDown.

EDIT 2:

Here is the code for the button.

@interface CreateButton ()

@property (nonatomic) Theme *theme;
@property (nonatomic) UIView *verticle;
@property (nonatomic) UIView *horizontal;
@property (nonatomic) BOOL mini;

@end

@implementation CreateButton

#pragma mark - Accessors

- (UIView *)verticle {
    if (! _verticle) {
        _verticle = [[UIView alloc] init];
        _verticle.backgroundColor = [self.theme colorForKey:@"createButtonPlusBackgroundColor"];
        _verticle.userInteractionEnabled = NO;
    }
    return _verticle;
}

- (UIView *)horizontal {
    if (! _horizontal) {
        _horizontal = [[UIView alloc] init];
        _horizontal.backgroundColor = [self.theme colorForKey:@"createButtonPlusBackgroundColor"];
        _verticle.userInteractionEnabled = NO;
    }
    return _horizontal;
}

#pragma mark - Init

- (instancetype)initWithTheme:(Theme *)theme frame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        _theme = theme;

        self.layer.cornerRadius = roundf(frame.size.width / 2);
        self.layer.shadowColor = [UIColor blackColor].CGColor;
        self.layer.shadowOpacity = .1f;
        self.layer.shadowOffset = CGSizeZero;
        self.layer.shadowRadius = 15.f;
        self.backgroundColor = [self.theme colorForKey:@"createButtonBackgroundColor"];

        [self addSubview:self.verticle];
        [self addSubview:self.horizontal];

        [self addTarget:self action:@selector(animate) forControlEvents:UIControlEventTouchDown];
        [self addTarget:self action:@selector(animate) forControlEvents:UIControlEventTouchUpInside];
        [self addTarget:self action:@selector(animate) forControlEvents:UIControlEventTouchUpOutside];
    }
    return self;
}

#pragma mark - Actions

- (void)animate {
    [UIView animateWithDuration:0.2 delay:0 usingSpringWithDamping:0.4 initialSpringVelocity:8 options:kNilOptions animations:^{
        if (self.mini) {
            self.transform = CGAffineTransformMakeScale(1.0, 1.0);
            self.mini = NO;
        } else {
            self.transform = CGAffineTransformMakeScale(0.90, 0.90);
            self.mini = YES;
        }
    } completion:nil];
}

#pragma mark - UIView

- (void)layoutSubviews {
    CGSize size = self.bounds.size;

    NSInteger width = 3;
    NSInteger verticleInset = 12;
    self.verticle.frame = CGRectMake((size.width - width) / 2, verticleInset, width, size.height - (verticleInset * 2));
    self.horizontal.frame = CGRectMake(verticleInset, (size.height - width) / 2, size.width - (verticleInset * 2), width);
}

@end


问:
Converting raw file into actual file in react-native
I'm having an raw file getting from an server for eg:

```<code>file: {
fileName:xyz,
size:7125,
mimeType:document/pdf
}
</code>```

how can i convert this to normal file and saved it to the respected directory.
Thank you.

答:
You have download that file and store inside your phone memory, For downloading you have following options.

Use that lib.

https://github.com/joltup/rn-fetch-blob#download-to-storage-directly

Open that link in your browser and download it through the browser

https://reactnative.dev/docs/linking#openurl

If you are using expo you can do in this way

https://docs.expo.io/versions/latest/sdk/filesystem/#example-usage

Body:
I'm having an raw file getting from an server for eg:

file: {
fileName:xyz,
size:7125,
mimeType:document/pdf
}

how can i convert this to normal file and saved it to the respected directory.
Thank you.


问:
Spring: How to start the logic after initializing the app
I have implemented this logic

```<code>@Component
public class SomeUpdater {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    private ExecutorService executorService;

    @PostConstruct
    public void init(){
        executorService = Executors.newSingleThreadExecutor();
        executorService.execute(()->{
            //some logic
            applicationEventPublisher.publishEvent(new PurposeEvent(this, 5));
        });
    }

}

@Component
public class SomeClass {

    @EventListener
    public void update(PurposeEvent purposeEvent){
        //update
    }
}
</code>```

But I can see from the logs that listener for update (PurposeEvent purposeEvent) is initialized later than the method applicationEventPublisher.publishEvent(new PurposeEvent(this, 5)); is called. How can I call logic after initialization? I tried using @EventListener for ContextRefreshedEvent, but as far as I understand, it can be called multiple times

答:
You can make use of spring events like below,</p>

```<code>@EventListener(ApplicationReadyEvent.class)
public void init() {
    final ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.execute(() -> {
        //some logic
        applicationEventPublisher.publishEvent(new PurposeEvent(this, 5));
    });
}
</code>```

Body:
I have implemented this logic

@Component
public class SomeUpdater {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    private ExecutorService executorService;

    @PostConstruct
    public void init(){
        executorService = Executors.newSingleThreadExecutor();
        executorService.execute(()->{
            //some logic
            applicationEventPublisher.publishEvent(new PurposeEvent(this, 5));
        });
    }

}

@Component
public class SomeClass {

    @EventListener
    public void update(PurposeEvent purposeEvent){
        //update
    }
}

But I can see from the logs that listener for update (PurposeEvent purposeEvent) is initialized later than the method applicationEventPublisher.publishEvent(new PurposeEvent(this, 5)); is called. How can I call logic after initialization? I tried using @EventListener for ContextRefreshedEvent, but as far as I understand, it can be called multiple times

Body:
You can make use of spring events like below,

@EventListener(ApplicationReadyEvent.class)
public void init() {
    final ExecutorService executorService = Executors.newSingleThreadExecutor();
    executorService.execute(() -> {
        //some logic
        applicationEventPublisher.publishEvent(new PurposeEvent(this, 5));
    });
}


问:
compile dataframe information for unique column values
I have a df that has multiple columns and rows. In one of the columns I have duplicates of user names and I want to generate a singular message to the user with all the other information in their respective rows - the df is sorted by user name. I have written this for loop (though I am sure I am complicating things). I am currently getting a list out of range error, that I'm sure has to do with the way I am trying to match up the users, any help would be appreciated.</p>

```<code>#User  Item   Age#
user1  itemA   65
user1  itemB   70
user1  itemC   30
user2  itemAA  43
user2  itemAB  3
user3  itemBA  78

</code>```

```<code>i = -1
message = 'txt'
for i, R in df.iterrows():
    i +=1
    if R['User'] != ['User'][i]:
        print ('message')
        message = R['User'] 'your item is' + str(R['Age'])
    elif R['User] == ['User'][i]:
        message2 = 'your item is' + str(R['Age'])
        message = message + message2
    else:
        print (message)
</code>```

答:
I figured out a way to get what I wanted. I created a unique list and looped through it with an imbedded loop through the dataframe to extract information for each unique user:</p>

```<code>u_users = df['User'].drop_duplicates().reset_index()
u_user.columns =['i', 'unq']

for l, i in u_users.iterrows():
    message = ''
    for r, d in df.iterrows():
        if i['unq'] == d['User']:
             message = message + R['User'] ' your item is ' + str(R['Age'])
        else:
             continue
</code>```

Body:
I have a df that has multiple columns and rows. In one of the columns I have duplicates of user names and I want to generate a singular message to the user with all the other information in their respective rows - the df is sorted by user name. I have written this for loop (though I am sure I am complicating things). I am currently getting a list out of range error, that I'm sure has to do with the way I am trying to match up the users, any help would be appreciated.

#User  Item   Age#
user1  itemA   65
user1  itemB   70
user1  itemC   30
user2  itemAA  43
user2  itemAB  3
user3  itemBA  78

i = -1
message = 'txt'
for i, R in df.iterrows():
    i +=1
    if R['User'] != ['User'][i]:
        print ('message')
        message = R['User'] 'your item is' + str(R['Age'])
    elif R['User] == ['User'][i]:
        message2 = 'your item is' + str(R['Age'])
        message = message + message2
    else:
        print (message)

Body:
I figured out a way to get what I wanted. I created a unique list and looped through it with an imbedded loop through the dataframe to extract information for each unique user:

u_users = df['User'].drop_duplicates().reset_index()
u_user.columns =['i', 'unq']

for l, i in u_users.iterrows():
    message = ''
    for r, d in df.iterrows():
        if i['unq'] == d['User']:
             message = message + R['User'] ' your item is ' + str(R['Age'])
        else:
             continue


问:
Can't connect with my frontend with kubectl
With kubernetes, I created an ingress with a service like these :

```<code>apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: syntaxmap2
spec:
  backend:
    serviceName: testsvc
    servicePort: 3000
</code>```

The service testsvc is already created.

I created a frontend service like these :

```<code>apiVersion: v1
kind: Service
metadata:
  name: syntaxmapfrontend
spec:
  selector:
    app: syntaxmap
    tier: frontend
  ports:
  - protocol: "TCP"
    port: 7000
    targetPort: 7000
  type: LoadBalancer
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: syntaxmapfrontend
spec:
  selector:
    matchLabels:
      app: syntaxmap
      tier: frontend
      track: stable
  replicas: 1
  template:
    metadata:
      labels:
        app: syntaxmap
        tier: frontend
        track: stable
    spec:
      containers:
      - name: nginx
        image: "gcr.io/google-samples/hello-frontend:1.0"
        lifecycle:
          preStop:
            exec:
              command: ["/usr/sbin/nginx","-s","quit"]
</code>```

When I do these command :

```<code>kubectl describe ingress syntaxmap2
</code>```

I have an Ip adress than i can put in my browser and I have an answer

But when I do these command :

```<code>kubctl describe service syntaxmapfrontend
</code>```

I have an Ip adress with a port and when I try to connect to it with curl, I have a time out.

How can I connect to my kubernet frontend with curl ?

答:
I have found a way.

I write :

```<code>minikube service syntaxmapfrontend
</code>```

And it open a browser with the right URL.

Body:
With kubernetes, I created an ingress with a service like these :

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: syntaxmap2
spec:
  backend:
    serviceName: testsvc
    servicePort: 3000

The service testsvc is already created.

I created a frontend service like these :

apiVersion: v1
kind: Service
metadata:
  name: syntaxmapfrontend
spec:
  selector:
    app: syntaxmap
    tier: frontend
  ports:
  - protocol: "TCP"
    port: 7000
    targetPort: 7000
  type: LoadBalancer
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: syntaxmapfrontend
spec:
  selector:
    matchLabels:
      app: syntaxmap
      tier: frontend
      track: stable
  replicas: 1
  template:
    metadata:
      labels:
        app: syntaxmap
        tier: frontend
        track: stable
    spec:
      containers:
      - name: nginx
        image: "gcr.io/google-samples/hello-frontend:1.0"
        lifecycle:
          preStop:
            exec:
              command: ["/usr/sbin/nginx","-s","quit"]

When I do these command :

kubectl describe ingress syntaxmap2

I have an Ip adress than i can put in my browser and I have an answer

But when I do these command :

kubctl describe service syntaxmapfrontend

I have an Ip adress with a port and when I try to connect to it with curl, I have a time out.

How can I connect to my kubernet frontend with curl ?

Body:
I have found a way.

I write :

minikube service syntaxmapfrontend

And it open a browser with the right URL.


问:
Shape is not working properly for circular property in flutter
I'm trying to make a circular image box, but after using shape: Boxshape.circle, it is working properly on my current image. I'm sure that the shape property doesn't depend on the image pixel or any sort of thing.

I have this code:

```<code>return Column(
    crossAxisAlignment: CrossAxisAlignment.stretch,
    children: <Widget>[
      Container(
        margin: EdgeInsets.only(right: 40.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              height: 144.0,
              width: 144.0,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                  fit: BoxFit.fill,
                  image: AssetImage('MY_IMAGE')
                )
              )
            )
          ]
        )
      )
    ],
);
</code>```

I have read about the Boxdecoration from this link: Flutter - BoxDecoration. I'm confident that the shape should work but in my case, it is not working.

This is the result which I'm getting right now:

答:
For me it works using ClipOval in the child, and increasing a bit the image size with Transform.scale</p>

```<code>                 Container(
                    decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(40))),
                    child: ClipOval(
                      child: Transform.scale(
                        scale: 1.6,
                        child: Image.asset(
                          "my asset image",
                          width: 80,
                          height: 80,
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                  )
</code>```

Body:
I'm trying to make a circular image box, but after using shape: Boxshape.circle, it is working properly on my current image. I'm sure that the shape property doesn't depend on the image pixel or any sort of thing.

I have this code:

return Column(
    crossAxisAlignment: CrossAxisAlignment.stretch,
    children: <Widget>[
      Container(
        margin: EdgeInsets.only(right: 40.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Container(
              height: 144.0,
              width: 144.0,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                  fit: BoxFit.fill,
                  image: AssetImage('MY_IMAGE')
                )
              )
            )
          ]
        )
      )
    ],
);

I have read about the Boxdecoration from this link: Flutter - BoxDecoration. I'm confident that the shape should work but in my case, it is not working.

This is the result which I'm getting right now:

Body:
For me it works using ClipOval in the child, and increasing a bit the image size with Transform.scale

                 Container(
                    decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(40))),
                    child: ClipOval(
                      child: Transform.scale(
                        scale: 1.6,
                        child: Image.asset(
                          "my asset image",
                          width: 80,
                          height: 80,
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                  )


问:
How many CUDA cores is used to process a CUDA warp?
I'm reading for the answers and there are conflict ideas:
In this link https://www.3dgep.com/cuda-thread-execution-model/, two warps (64 threads) can run concurrently on an SM (32 CUDA cores). So, I understand that the threads on a warp are splited and be processed on 16 CUDA cores. This idea makes sense for me because each CUDA core has 1 32bitALU.

However, in other links, they claimed that 1 CUDA core is able to handle 32 concurrent threads (same as a warp size) (https://cvw.cac.cornell.edu/GPU/simt_warp). So, 1 CUDA warp can be processed by one single CUDA core only. This also makes sense because all threads on the same warp using the same PC counter.

So, My question is how a CUDA warp is mapped with CUDA cores?

答:
Inside a CUDA GPU, there are computing units called SMs (Streaming Multiprocessor). Each SM has a variety of hardware resources (warp schedulers, instruction fetch/decode, register file, execution/functional units, shared memory, L1 cache, etc.) which are used to support CUDA threads of execution.

Whenever an instruction is issued, it is issued warp-wide.  Therefore, any instruction issued will require 32 functional units for that type of instruction.  CUDA low-level instructions (SASS) can be broken into a number of categories, and there is a functional unit type that will handle that instruction, or instructions in that category.  For example a load-from-memory instruction (e.g. LD) will be handled by a LD/ST unit (load/store).  There are a number of different kinds of these instruction processing units.

Some additional particular kinds of units are SP and DP units.  An SP unit can handle a single-precision floating point multiply, add, or multiply-add instruction.  A DP unit is similar except that it handles instructions working on double-precision floating point types.

To issue an instruction, therefore, a warp-scheduler will ultimately need 32 of the type of unit appropriate for that instruction type.  For a single-precision floating point multiply operation, it will require 32 SP units to be available, in that cycle, to receive that issued instruction.

Other types of instructions will still require 32 units (eventually) but there may not be 32 of a given type of unit in the SM.  When there are fewer than 32 of a particular type of unit, the warp scheduler will schedule a single instruction across multiple clock cycles.  Suppose, for example, that a particular GPU SM design was such that there are only 4 DP units.  Then the warp scheduler, when it has e.g. a DP multiply operation/instruction to issue, will use those 4 units for a total of 8 clock cycles (4x8=32) so as to provide a functional/execution unit for each instruction when considered per-thread, warp-wide.  A functional unit is ultimately needed per-thread. Each functional unit can handle one instruction, for one thread, per clock.  To handle the instruction issued warp-wide, either 32 functional units will be needed so the instruction can be issued in a single clock cycle, or the instruction will be issued over multiple clock cycles, to a smaller number of functional units.

The term "core" in CUDA is generally used to refer to a SP unit as defined above.  Given this, we can immediately determine that:

A CUDA "core" is really not like a CPU core.

A CUDA "core" will only be involved in instruction processing for a relatively small number of instruction types, including SP floating-point add, multiply, and multiply-add. Any other instruction type will require a different kind of functional unit, to handle that instruction.  And just because a SM contains, for example 128 CUDA cores (i.e. SP units), does not mean that it also contains 128 DP units, or 128 LD/ST units, or a particular number of any other functional unit type.  The number of functional units in a SM can and do vary by functional unit type.  Different GPU architectures (Maxwell, Pascal, Volta) and different compute capabilities within an architecture, may have different mixes or quantities of these functional unit types.


问:
Unexpected output in converting from long in C to long in C++ in VS?
I'm writing a program in C (with a school-specific IDE), then converting it to C++ in Visual Studio. The program in C takes a long variable as user input of 371449635398431 (using the school IDE and a unique compiler function called get_long)   When I copy this to Visual Studio, using cin >> instead of get_long, it interprets the long as 2147483647 unless I make it a long long in VS. Are longs in C different than longs in C++ (with longs in C being equivalent to long long in C++?), or  could a compiler mismatch be causing the issue? </p>

答:
The C and C++ standards say that a long must have a range of at least -2147483647 to +2147483647. (Note that C++20 requires -2147483648 as the minimum).

Microsoft's compiler for Windows has the range for a long set to -2147483648 to +2147483647. A typical Unix compiler (gcc on rhel for example) has a 64 bit type for a long.

The motivation for keeping the long as a 32 bit type on Windows 64 bit was for backward compatibility. It was really easy to convert Win32 applications to Win64 applications, back in the day.


问:
How to call class method in different javascript file?
This class is included in an external file names graph.js.  I'm trying to access the method drawchart from its class graphElement. The file is included in the html script src. I can even call the function fetchYearly() without a problem but that class method keeps throwing error. I'm using the library chart.js.

Here is my code :

class graphElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = document.querySelector('#tmpGraph').innerHTML;
    let canvas1 = document.getElementById('graph').shadowRoot.querySelector('#myChart'); let transType = ['Debit', 'Credit'];
    fetchYearlyData('CREDIT');
    fetchYearlyData('DEBIT');
    this.drawChart(transType);

  }
  drawChart(transType) {
    var ctx = document.getElementById('graph').shadowRoot.querySelector('#myChart').getContext('2d');
    var myChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: labels,
        datasets: [{
          label: transType[0],
          borderColor: "#f48480",
          pointBorderColor: "#f48480",
          pointBackgroundColor: "#f48480",
          pointHoverBackgroundColor: "#f48480",
          pointHoverBorderColor: "#f48480",
          pointBorderWidth: 10,
          pointHoverRadius: 10,
          pointHoverBorderWidth: 1,
          pointRadius: 3,
          fill: false,
          borderWidth: 4,
          data: dataDB
        },
        {
          label: transType[1],
          borderColor: "#80b6f4",
          pointBorderColor: "#80b6f4",
          pointBackgroundColor: "#80b6f4",
          pointHoverBackgroundColor: "#80b6f4",
          pointHoverBorderColor: "#80b6f4",
          pointBorderWidth: 10,
          pointHoverRadius: 10,
          pointHoverBorderWidth: 1,
          pointRadius: 3,
          fill: false,
          borderWidth: 4,
          data: dataCRD
        }],
      },
      options: {
        legend: {
          position: "top"
        },
        scales: {
          yAxes: [{
            ticks: {
              fontColor: "rgba(0,0,0,0.5)",
              fontStyle: "bold",
              beginAtZero: true,
              maxTicksLimit: 5,
              padding: 20
            },
            gridLines: {
              drawTicks: false,
              display: false
            }
          }],
          xAxes: [{
            gridLines: {
              zeroLineColor: "transparent"
            },
            ticks: {
              padding: 20,
              fontColor: "rgba(0,0,0,0.5)",
              fontStyle: "bold"
            }
          }]
        }
      }
    });
  }
}

function fetchYearlyData(transType) {
  //does some important stuff :)
}
```

I want to call the function drawchart() in another file on click. It is included in the script source of html file but throws :
Uncaught (in promise) ReferenceError: drawChart is not defined error when called, however the function fetchYearly() works completely fine. What am I doing wrong?

答: This graphElement class is web component, so if your chart element is already visible on screen, you need to find it in DOM tree, but you need to show us more code.

Body:
This class is included in an external file names graph.js.  I'm trying to access the method drawchart from its class graphElement. The file is included in the html script src. I can even call the function fetchYearly() without a problem but that class method keeps throwing error. I'm using the library chart.js.

Here is my code :

class graphElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = document.querySelector('#tmpGraph').innerHTML;
    let canvas1 = document.getElementById('graph').shadowRoot.querySelector('#myChart'); let transType = ['Debit', 'Credit'];
    fetchYearlyData('CREDIT');
    fetchYearlyData('DEBIT');
    this.drawChart(transType);

  }
  drawChart(transType) {
    var ctx = document.getElementById('graph').shadowRoot.querySelector('#myChart').getContext('2d');
    var myChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: labels,
        datasets: [{
          label: transType[0],
          borderColor: "#f48480",
          pointBorderColor: "#f48480",
          pointBackgroundColor: "#f48480",
          pointHoverBackgroundColor: "#f48480",
          pointHoverBorderColor: "#f48480",
          pointBorderWidth: 10,
          pointHoverRadius: 10,
          pointHoverBorderWidth: 1,
          pointRadius: 3,
          fill: false,
          borderWidth: 4,
          data: dataDB
        },
        {
          label: transType[1],
          borderColor: "#80b6f4",
          pointBorderColor: "#80b6f4",
          pointBackgroundColor: "#80b6f4",
          pointHoverBackgroundColor: "#80b6f4",
          pointHoverBorderColor: "#80b6f4",
          pointBorderWidth: 10,
          pointHoverRadius: 10,
          pointHoverBorderWidth: 1,
          pointRadius: 3,
          fill: false,
          borderWidth: 4,
          data: dataCRD
        }],
      },
      options: {
        legend: {
          position: "top"
        },
        scales: {
          yAxes: [{
            ticks: {
              fontColor: "rgba(0,0,0,0.5)",
              fontStyle: "bold",
              beginAtZero: true,
              maxTicksLimit: 5,
              padding: 20
            },
            gridLines: {
              drawTicks: false,
              display: false
            }
          }],
          xAxes: [{
            gridLines: {
              zeroLineColor: "transparent"
            },
            ticks: {
              padding: 20,
              fontColor: "rgba(0,0,0,0.5)",
              fontStyle: "bold"
            }
          }]
        }
      }
    });
  }
}

function fetchYearlyData(transType) {
  //does some important stuff :)
}

I want to call the function drawchart() in another file on click. It is included in the script source of html file but throws :
Uncaught (in promise) ReferenceError: drawChart is not defined error when called, however the function fetchYearly() works completely fine. What am I doing wrong?