问:
Returning a quad precision variable from fortran
So i'm trying to return a quad precision (128 bit) value from fortran and manipulate it in python. But the return value i get does not seem to match what i expect.

Fortran code:

```<code>module testquad

    implicit none

    integer, parameter :: qp = selected_real_kind(p=30)

    contains

    real(qp) function func_quad()
        real(qp) :: x

        x = 5_qp

        write(*,*) x,sizeof(x)
        write(*,'(B128)') x

        func_quad = x

    end function func_quad

end module testquad
</code>```

Compiled with:

```<code>gfortran -fpic -shared -fdump-tree-all -o libtestquad.so testQuad.f90
</code>```

Python side I use a c_ubyte*16 array to hold the return value (as ctypes doesn't expose a 128 bit quad type)

import ctypes

lib = ctypes.CDLL('./libtestquad.so')

f = getattr(lib, '__testquad_MOD_func_quad')

f.argtypes = []
f.restype = ctypes.c_ubyte*16

result = f()

bb=[]
for i in bytearray(result)[::-1]:
    bb.append(bin(i)[2:].rjust(8,'0'))

bb=''.join(bb)
print(bb)
```

<p>Running the code the output from calling the fortran function is:</p>

```5.00000000000000000000000000000000000                         16
 1000000000000010100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
```

<p>So we get the 5 and we see the size is 16 (so i am getting a quad number)</p>

<p>It seems gfortran skips printing the first 0/1 for the sign bit. But we can see it has 3 1's and the rest are 0's in the bit pattern.</p>

<p>Following the wikipedia page on quad's then we have</p>

```sign = 0 (gfortran misses this)
exponent = 100000000000001
significand = 0100....
```

<p>Converting that out:</p>

<pre class="lang-py prettyprint-override"><code>a = 2**(int('100000000000001',base=2)-16383) # 4
b = 1 + 0/2**1 + 1/2**2 + 0/2**3 .... # 1.25
print(a * b)
5
</code>```

So gfortran is, as expected, printing the right bit pattern for the number 5.

However, printing out a bit pattern in python for the result:

```<code>00000000000000000111111110110001001111101010010111111001001010000000000000000000000000000000000000000000000000000000000000000000
</code>```

Which is clearly different.

Have i screwed up printing the bit pattern?

Is there something special in how gfortran returns a __float128 that means I can't just interpret it as 16 bytes?

Is there something special in how ctypes handles returning an array of c_bytes that breaks things?

Something else?

Extras:

using -fdump-tree-all and looking at the .original file we see:

```<code>func_quad ()
{
  real(kind=16) x;
  real(kind=16) __result_func_quad;

  x = 5.0e+0;
  // snip write statement code
  __result_func_quad = x;
  return __result_func_quad;
}
</code>```

So it seems there is nothing "special" going on, variables are not being assigned to structs/pointers/arrays to handle the quad type.

答: Looks like i'm running into this https://stackoverflow.com/a/423479/2270574 answer. Which points out you can't use a byte array for a floating point number as its not stored in the normal %eax register.</p>

Body:
So i'm trying to return a quad precision (128 bit) value from fortran and manipulate it in python. But the return value i get does not seem to match what i expect.

Fortran code:

module testquad

    implicit none

    integer, parameter :: qp = selected_real_kind(p=30)

    contains

    real(qp) function func_quad()
        real(qp) :: x

        x = 5_qp

        write(*,*) x,sizeof(x)
        write(*,'(B128)') x

        func_quad = x

    end function func_quad

end module testquad

Compiled with:

gfortran -fpic -shared -fdump-tree-all -o libtestquad.so testQuad.f90

Python side I use a c_ubyte*16 array to hold the return value (as ctypes doesn't expose a 128 bit quad type)

import ctypes

lib = ctypes.CDLL('./libtestquad.so')

f = getattr(lib, '__testquad_MOD_func_quad')

f.argtypes = []
f.restype = ctypes.c_ubyte*16

result = f()

bb=[]
for i in bytearray(result)[::-1]:
    bb.append(bin(i)[2:].rjust(8,'0'))

bb=''.join(bb)
print(bb)

Running the code the output from calling the fortran function is:

5.00000000000000000000000000000000000                         16
 1000000000000010100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

So we get the 5 and we see the size is 16 (so i am getting a quad number)

It seems gfortran skips printing the first 0/1 for the sign bit. But we can see it has 3 1's and the rest are 0's in the bit pattern.

Following the wikipedia page on quad's then we have

sign = 0 (gfortran misses this)
exponent = 100000000000001
significand = 0100....

Converting that out:

a = 2**(int('100000000000001',base=2)-16383) # 4
b = 1 + 0/2**1 + 1/2**2 + 0/2**3 .... # 1.25
print(a * b)
5

So gfortran is, as expected, printing the right bit pattern for the number 5.

However, printing out a bit pattern in python for the result:

00000000000000000111111110110001001111101010010111111001001010000000000000000000000000000000000000000000000000000000000000000000

Which is clearly different.

Have i screwed up printing the bit pattern?

Is there something special in how gfortran returns a __float128 that means I can't just interpret it as 16 bytes?

Is there something special in how ctypes handles returning an array of c_bytes that breaks things?

Something else?

Extras:

using -fdump-tree-all and looking at the .original file we see:

func_quad ()
{
  real(kind=16) x;
  real(kind=16) __result_func_quad;

  x = 5.0e+0;
  // snip write statement code
  __result_func_quad = x;
  return __result_func_quad;
}

So it seems there is nothing "special" going on, variables are not being assigned to structs/pointers/arrays to handle the quad type.


来源: stackexchange

问:
Client side showing , hiding is risky
I have a div which contains a button .I am initially setting div display:none & depending upon the user rights i am showing it to user using javascript.

```<code><div id="mydiv" style="display:none">
    <asp:Button id="btn" runat="server"/>
</div>

PageMethods.GetRights(onsuccess);

function onsuccess(result){
   if(result.isaccessible)
   {
      $("#mydiv").show();
   }
}
</code>```

Is Showing,Hiding at client risky. I dont want to use updatepanel if it is risky what is an alternative to this i have?

答:
Anyone could view this div if they changed the display to "block" with an html inspector.
If you are wanting this information to remain private I would suggest a different way of doing this.

The first, and the best way, is to skip the JavaScript and use the server to check the user's rights and display the div.

The second way is to make an Ajax call. If you would like this to work with JavaScript than I would suggest using an ajax call to the server in order to get the information you want. Let the server check the user rights and return the div on success. Then simply replace the div's html with that returned from the server. Something like this might work:

```<code>var getHiddenDiv = function(){
   $.ajax({
      url: yourUrl,
      type: GET,
      success: function(data){
         $("#mydiv").html(data);
      }
   });
};
</code>```

ContentLicense: CC BY-SA 3.0

Title: Client side showing , hiding is risky

Body:
I have a div which contains a button .I am initially setting div display:none & depending upon the user rights i am showing it to user using javascript.

    <asp:Button id="btn" runat="server"/>

PageMethods.GetRights(onsuccess);

function onsuccess(result){
   if(result.isaccessible)
   {
      $("#mydiv").show();
   }
}

Is Showing,Hiding at client risky. I dont want to use updatepanel if it is risky what is an alternative to this i have?

Body:
Anyone could view this div if they changed the display to "block" with an html inspector.
If you are wanting this information to remain private I would suggest a different way of doing this.

The first, and the best way, is to skip the JavaScript and use the server to check the user's rights and display the div.

The second way is to make an Ajax call. If you would like this to work with JavaScript than I would suggest using an ajax call to the server in order to get the information you want. Let the server check the user rights and return the div on success. Then simply replace the div's html with that returned from the server. Something like this might work:

var getHiddenDiv = function(){
   $.ajax({
      url: yourUrl,
      type: GET,
      success: function(data){
         $("#mydiv").html(data);
      }
   });
};


问:
Why does this pattern not match after the “-”?
I have the following pattern which should work in C++ regex, perl and grep.  Does anyone know why the string of 0000 is not matching after the minus sign -?</p>

```<code>$ echo AB 00000-0000 | grep -Po "(\w{2}\s*\d{5}(−\d{4})?)"
AB 00000
$ echo AB00000-0000 | grep -Po "(\w{2}\s*\d{5}(−\d{4})?)"
AB00000
</code>```

答:
It looks like the dash literal you used in your regular expression is not the same dash as is in the input.  The input dash is a small -, while the dash in your regexp is slightly longer.  Not sure how your input device is different, but when I swapped your dash for a short dash: - your expression worked fine.

(\w{2}\s*\d{5}(-\d{4})?)

Here's a great tool that might help you, I use it a lot:
https://regex101.com/

ContentLicense: CC BY-SA 4.0

Body:
I have the following pattern which should work in C++ regex, perl and grep.  Does anyone know why the string of 0000 is not matching after the minus sign -?

$ echo AB 00000-0000 | grep -Po "(\w{2}\s*\d{5}(−\d{4})?)"
AB 00000
$ echo AB00000-0000 | grep -Po "(\w{2}\s*\d{5}(−\d{4})?)"
AB00000


问:
Problem with installing RQDA package since it was archived 20/05/2020
I receive an error when installing RQDA on Windows 10.
I had run RQDA successfully, then a package wouldn't load and I deleted and tried to reinstall RQDA with these instructions: http://rqda.r-forge.r-project.org/.
Since then, I receive errors pointing towards RGtk2 and GTK+.
I tried loading RQDA both using the newest and older versions of R and RStudio. I tried on 3 different Windows computers.

Here is the link that shows the RQDA package was recently archived:
https://cran.r-project.org/web/packages/RQDA/index.html
The archive points towards requiring gWidgets, so I made sure the library of gWidgets loads successfully, which it does, as does library(gWidgetsRGtk2).
I also took care to install RTools4.0 for R 4.0.0 (https://cran.r-project.org/bin/windows/Rtools/).

I made sure GTK+ is on my PATH. (Path: %GTK_BASEPATH%\bin;) (GTK_PATH: C:\GTK).

I also tried loading RQDA and dependencies manually, but that's a never ending process.

Here is the error I receive:

```<code>Failed to load RGtk2 dynamic library, attempting to install it.
Please install GTK+ from http://ftp.gnome.org/pub/gnome/binaries/win64/gtk+/2.22/gtk+-bundle_2.22.1-20101229_win64.zip
If the package still does not load, please ensure that GTK+ is installed and that it is on your PATH environment variable
IN ANY CASE, RESTART R BEFORE TRYING TO LOAD THE PACKAGE AGAIN
Error in getOption("encoding") : Knotenstack-Überlauf
Zusätzlich: Warnmeldung:
Failed to load RGtk2 dynamic library, attempting to install it.
Please install GTK+ from http://ftp.gnome.org/pub/gnome/binaries/win64/gtk+/2.22/gtk+-bundle_2.22.1-20101229_win64.zip
If the package still does not load, please ensure that GTK+ is installed and that it is on your PATH environment variable
IN ANY CASE, RESTART R BEFORE TRYING TO LOAD THE PACKAGE AGAIN
Error: package or namespace load failed for 'RGtk2':
 .onLoad in loadNamespace() für 'RGtk2' fehlgeschlagen, Details:
  Aufruf: NULL
  Fehler: Knotenstack-Überlauf
Fehler: Paket 'RGtk2' konnte nicht geladen werden
Zusätzlich: Warnmeldung:
Failed to load RGtk2 dynamic library, attempting to install it.
Ausführung angehalten
ERROR: lazy loading failed for package 'RQDA'
* removing 'C:/Users/haunschild/Documents/R/win-library/4.0/RQDA'
Warning in install.packages :
  installation of package ‘RQDA_0.3-1.tar.gz’ had non-zero exit status
</code>```

Trying to install RGtk2, I receive the following:

```<code>Error in inDL(x, as.logical(local), as.logical(now), ...) :
  kann shared object 'C:/Users/haunschild/Documents/R/win-library/4.0/RGtk2/libs/x64/RGtk2.dll' nicht laden:
  LoadLibrary failure:  %1 ist keine zulässige Win32-Anwendung.

versuche URL 'http://ftp.gnome.org/pub/gnome/binaries/win64/gtk+/2.22/gtk+-bundle_2.22.1-20101229_win64.zip'
Content type 'application/zip' length 25830230 bytes (24.6 MB)
downloaded 24.6 MB

Learn more about GTK+ at http://www.gtk.org
If the package still does not load, please ensure that GTK+ is installed and that it is on your PATH environment variable
IN ANY CASE, RESTART R BEFORE TRYING TO LOAD THE PACKAGE AGAIN
Lade nötiges Paket: cairoDevice
Warnmeldungen:
1: Failed to load RGtk2 dynamic library, attempting to install it.
2: In dir.create(config_path, recursive = TRUE) :
  'C:\Users\haunschild\Documents\R\win-library\4.0\RGtk2\gtk\x64\etc\gtk-2.0' existiert bereits
> detach("package:RGtk2", unload = TRUE)
Fehler: Paket ‘RGtk2’ wird von ‘gWidgetsRGtk2’ benötigt, wird deshalb nicht detached ("Is needed by gWidgetsRGTk2', is therefore not detached")
> library(RGtk2)
</code>```

I also tried:

```<code>pkgFile <- "RQDA_0.3-1.tar.gz"
download.file(url = url, destfile = pkgFile)

# Install dependencies

install.packages(c("DBI","RSQLite","RGtk2","gWidgets","gWidgetsRGtk2"))

# Install package
install.packages(pkgs=pkgFile, type="source", repos=NULL)

# Delete package tarball
unlink(pkgFile)
</code>```

An received the same RGTk2 error loop.

Any help would be greatly appreciated! Thanks!

答:
We've been discussing this issue at : https://github.com/Ronggui/RQDA/issues/38
Some have reported success installing it and have given feedback on how to do it.
Some contributors are working to port RQDA to gWidgets2. May be one of their solutions works for you.
Good luck.

After I gave the answer above I tryed to install it my self and this was as far as I've got using RKWard 0.7.1b, on VM with MsWins10.
https://rkward.kde.org/
with R 3.6.3 in RKWard library (I had RQDA working before. So I uninstalled RKWard and deleted the library directory on C:\Program Files):
https://cran.r-project.org/bin/windows/base/old/3.6.3
and RTools35
https://cran.r-project.org/bin/windows/Rtools/history.html
also installed.

```<code>install.packages(c("gWidgets", "gWidgetsRGtk2", "RGtk2", "igraph","plogr","bit","RSQLite"),depen=T)

update.packages(ask = FALSE, checkBuilt = TRUE)

library(RGtk2)
</code>```

Selected GTK+
Restarted RKWard
Installing ""RQDA_0.3-1.tar.gz", type = "source"", gave me an error: "Failed to load RGtk2 dynamic library, attempting to install it". But by chance, I just saw the post by @JanMarvin and it worked!!!

```<code>install.packages("https://cran.r-project.org/src/contrib/Archive/RQDA/RQDA_0.3-1.tar.gz", type = "source", INSTALL_opts = "--no-multiarch")
</code>```

Then I ran:

```<code>update.packages(ask = FALSE, checkBuilt = TRUE)
</code>```

And then

```<code>library (RQDA)
</code>```

And it worked!!
If anyone could please refine it or give other suggestions as how to install it on MsWin, would be very much appreciated!
Thanks to @sjewo and @JanMarvin for their hard work!! porting this package to R 4.

Body:
I receive an error when installing RQDA on Windows 10.
I had run RQDA successfully, then a package wouldn't load and I deleted and tried to reinstall RQDA with these instructions: http://rqda.r-forge.r-project.org/.
Since then, I receive errors pointing towards RGtk2 and GTK+.
I tried loading RQDA both using the newest and older versions of R and RStudio. I tried on 3 different Windows computers.

Here is the link that shows the RQDA package was recently archived:
https://cran.r-project.org/web/packages/RQDA/index.html
The archive points towards requiring gWidgets, so I made sure the library of gWidgets loads successfully, which it does, as does library(gWidgetsRGtk2).
I also took care to install RTools4.0 for R 4.0.0 (https://cran.r-project.org/bin/windows/Rtools/).

I made sure GTK+ is on my PATH. (Path: %GTK_BASEPATH%\bin;) (GTK_PATH: C:\GTK).

I also tried loading RQDA and dependencies manually, but that's a never ending process.

Here is the error I receive:

Failed to load RGtk2 dynamic library, attempting to install it.
Please install GTK+ from http://ftp.gnome.org/pub/gnome/binaries/win64/gtk+/2.22/gtk+-bundle_2.22.1-20101229_win64.zip
If the package still does not load, please ensure that GTK+ is installed and that it is on your PATH environment variable
IN ANY CASE, RESTART R BEFORE TRYING TO LOAD THE PACKAGE AGAIN
Error in getOption("encoding") : Knotenstack-Überlauf
Zusätzlich: Warnmeldung:
Failed to load RGtk2 dynamic library, attempting to install it.
Please install GTK+ from http://ftp.gnome.org/pub/gnome/binaries/win64/gtk+/2.22/gtk+-bundle_2.22.1-20101229_win64.zip
If the package still does not load, please ensure that GTK+ is installed and that it is on your PATH environment variable
IN ANY CASE, RESTART R BEFORE TRYING TO LOAD THE PACKAGE AGAIN
Error: package or namespace load failed for 'RGtk2':
 .onLoad in loadNamespace() für 'RGtk2' fehlgeschlagen, Details:
  Aufruf: NULL
  Fehler: Knotenstack-Überlauf
Fehler: Paket 'RGtk2' konnte nicht geladen werden
Zusätzlich: Warnmeldung:
Failed to load RGtk2 dynamic library, attempting to install it.
Ausführung angehalten
ERROR: lazy loading failed for package 'RQDA'
* removing 'C:/Users/haunschild/Documents/R/win-library/4.0/RQDA'
Warning in install.packages :
  installation of package ‘RQDA_0.3-1.tar.gz’ had non-zero exit status

Trying to install RGtk2, I receive the following:

Error in inDL(x, as.logical(local), as.logical(now), ...) :
  kann shared object 'C:/Users/haunschild/Documents/R/win-library/4.0/RGtk2/libs/x64/RGtk2.dll' nicht laden:
  LoadLibrary failure:  %1 ist keine zulässige Win32-Anwendung.

versuche URL 'http://ftp.gnome.org/pub/gnome/binaries/win64/gtk+/2.22/gtk+-bundle_2.22.1-20101229_win64.zip'
Content type 'application/zip' length 25830230 bytes (24.6 MB)
downloaded 24.6 MB

Learn more about GTK+ at http://www.gtk.org
If the package still does not load, please ensure that GTK+ is installed and that it is on your PATH environment variable
IN ANY CASE, RESTART R BEFORE TRYING TO LOAD THE PACKAGE AGAIN
Lade nötiges Paket: cairoDevice
Warnmeldungen:
1: Failed to load RGtk2 dynamic library, attempting to install it.
2: In dir.create(config_path, recursive = TRUE) :
  'C:\Users\haunschild\Documents\R\win-library\4.0\RGtk2\gtk\x64\etc\gtk-2.0' existiert bereits
> detach("package:RGtk2", unload = TRUE)
Fehler: Paket ‘RGtk2’ wird von ‘gWidgetsRGtk2’ benötigt, wird deshalb nicht detached ("Is needed by gWidgetsRGTk2', is therefore not detached")
> library(RGtk2)

I also tried:

pkgFile <- "RQDA_0.3-1.tar.gz"
download.file(url = url, destfile = pkgFile)

# Install dependencies

install.packages(c("DBI","RSQLite","RGtk2","gWidgets","gWidgetsRGtk2"))

# Install package
install.packages(pkgs=pkgFile, type="source", repos=NULL)

# Delete package tarball
unlink(pkgFile)

An received the same RGTk2 error loop.

Any help would be greatly appreciated! Thanks!

Body:
We've been discussing this issue at : https://github.com/Ronggui/RQDA/issues/38
Some have reported success installing it and have given feedback on how to do it.
Some contributors are working to port RQDA to gWidgets2. May be one of their solutions works for you.
Good luck.

After I gave the answer above I tryed to install it my self and this was as far as I've got using RKWard 0.7.1b, on VM with MsWins10.
https://rkward.kde.org/
with R 3.6.3 in RKWard library (I had RQDA working before. So I uninstalled RKWard and deleted the library directory on C:\Program Files):
https://cran.r-project.org/bin/windows/base/old/3.6.3
and RTools35
https://cran.r-project.org/bin/windows/Rtools/history.html
also installed.

install.packages(c("gWidgets", "gWidgetsRGtk2", "RGtk2", "igraph","plogr","bit","RSQLite"),depen=T)

update.packages(ask = FALSE, checkBuilt = TRUE)

library(RGtk2)

Selected GTK+
Restarted RKWard
Installing ""RQDA_0.3-1.tar.gz", type = "source"", gave me an error: "Failed to load RGtk2 dynamic library, attempting to install it". But by chance, I just saw the post by @JanMarvin and it worked!!!

install.packages("https://cran.r-project.org/src/contrib/Archive/RQDA/RQDA_0.3-1.tar.gz", type = "source", INSTALL_opts = "--no-multiarch")

Then I ran:

update.packages(ask = FALSE, checkBuilt = TRUE)

And then

library (RQDA)

And it worked!!
If anyone could please refine it or give other suggestions as how to install it on MsWin, would be very much appreciated!
Thanks to @sjewo and @JanMarvin for their hard work!! porting this package to R 4.


问:
Barebones Facebook Connection with flashbuilder 4.5 (mobile app)
I am looking for a barebones facebook connection from pure actionscript to use in a mobile.  Does anyone know of any examples.  Been having a hard time finding what I want in Google

Thanks!

答:
You cant connect to facebook with only actionscript - flash does not implement OAuth which you need to get a valid access token.
You have to either get an access token through PHP, or Javascript.
If you are making a mobile web-app you can check out
http://blog.yoz.sk/2010/04/facebook-now-with-oauth-and-open-graph/

Jozef Chúťka put together a great walkthrough and classes for AS3 and facebook.
So you can make a web app or use a web view in AIR to handle your authentication.


问:
Make sure the same array items are not next to each other in php
I am struggling with this case. I have a random array that similar items can be in the next to each other and I don't want it to happen.

Example :

```<code>array("red","red","blue","green","green","blue");

Expected Output : array("red","blue","red","green","blue","green")
</code>```

So I was thinking about shuffle the items until there are no similar items in the next to each other. But it will take a lot of time if the array has a lot of values.

Is there any effective way to make it happen?

Any help would be appreciated. Thanks

答:
Just another idea:

Take the array and scan from start to end

Compare the next with current, when not equal, then continue

Compare the next with current, when equal, search the next different and swap next with next different

Based on your comment of an even more worse case than in the original question, I suggest trying this, ensuring never one word will be twice next together.

$colors = ["red", "red", "red", "red", "red", "red", "blue", "blue", "green", "green", "green", "green", "green", "green", "red", "red", "red"];

for ($i = 0; $i < count($colors) - 1; $i++) {
    if ($colors[$i] !== $colors[$i + 1]) continue;

    for ($k = $i + 2; $k < count($colors) - 1; $k++) {
        if ($colors[$i + 1] === $colors[$k]) continue;
        $tmp = $colors[$i + 1];
        $colors[$i + 1] = $colors[$k];
        $colors[$k] = $tmp;
        break;
    }
}

print_r($colors);

```

```Array
(
    [0] => red
    [1] => blue
    [2] => red
    [3] => blue
    [4] => red
    [5] => green
    [6] => red
    [7] => green
    [8] => red
    [9] => green
    [10] => red
    [11] => green
    [12] => red
    [13] => green
    [14] => red
    [15] => green
    [16] => red
)
```

Body:
I am struggling with this case. I have a random array that similar items can be in the next to each other and I don't want it to happen.

Example :

array("red","red","blue","green","green","blue");

Expected Output : array("red","blue","red","green","blue","green")

So I was thinking about shuffle the items until there are no similar items in the next to each other. But it will take a lot of time if the array has a lot of values.

Is there any effective way to make it happen?

Any help would be appreciated. Thanks

Body:
Just another idea:

Take the array and scan from start to end

Compare the next with current, when not equal, then continue

Compare the next with current, when equal, search the next different and swap next with next different

Based on your comment of an even more worse case than in the original question, I suggest trying this, ensuring never one word will be twice next together.

$colors = ["red", "red", "red", "red", "red", "red", "blue", "blue", "green", "green", "green", "green", "green", "green", "red", "red", "red"];

for ($i = 0; $i < count($colors) - 1; $i++) {
    if ($colors[$i] !== $colors[$i + 1]) continue;

    for ($k = $i + 2; $k < count($colors) - 1; $k++) {
        if ($colors[$i + 1] === $colors[$k]) continue;
        $tmp = $colors[$i + 1];
        $colors[$i + 1] = $colors[$k];
        $colors[$k] = $tmp;
        break;
    }
}

print_r($colors);

Array
(
    [0] => red
    [1] => blue
    [2] => red
    [3] => blue
    [4] => red
    [5] => green
    [6] => red
    [7] => green
    [8] => red
    [9] => green
    [10] => red
    [11] => green
    [12] => red
    [13] => green
    [14] => red
    [15] => green
    [16] => red
)


问:
When to use this.prop when passing down props?
I'm a beginner in JS/React and I am trying to wrap my head around the concept of when to use this.prop or just passing props down without this in React.

In some sources, the coder always uses this.prop while in others this seems to be unnecessary. Could anyone please clarify?

In this example, we are passing props username, authed, logout, and header from apps to hello. To do so, we use this.props. everytime we import.

However, in this example (React Native), we pass down term, onTermChange, and onTermSubmit from searchscreen to searchbar, without using this.props. Then I believe we re-defined our props in the TextInput of Search bar so its onEndEditing is the same as the onTermSubmit from the searchscreen.

I thought this.props may be a react syntax which became streamlined in React Native. However, I came across yet another example in React which does not use this.props:

答:
You will use "this" when you have a class component. When you have a functional component there is no need , because you're not creating an instance of a class. All arguments passed to a class are stored into "this.props".

So in your second example and third example , you have functional components, which take the consts passed to them not as props, but as actual constants with their own names.

Hope this helps.


问:
TypeError: songs.map is not a function
Hi I'm new to react Every time when i run the code it shows the same error. Can anyone explain what is wrong with this code.</p>

```<code>import React, { Component } from 'react'
import '../Search.css'
import axios from 'axios'

export default class Search extends Component {

    state = {
        songs: [],
    };

componentDidMount(key) {
    axios.get(`https://cors-anywhere.herokuapp.com/https://itunes.apple.com/search?term=`+key).then(res => {
        console.log(res);
        this.setState({songs: res.data});
    });
}
render() {
    const {songs} = this.state;
    return (
        <div className="container-fluid">

                    <input
                    type="text"
                    name="search"
                    placeholder="Search..."
                    id="search"
                    onChange={(event) => this.componentDidMount(event.target.value)}
                    />

                    <div>
                        {songs.map(song => (
                            <h1>{song.artistName}</h1>
                        ))}
                    </div>

        </div>

    )
  }
}
</code>```

答:
You should display the data only when it's available:

render() {
    const {songs} = this.state;
    return (

                    <input
                    type="text"
                    name="search"
                    placeholder="Search..."
                    id="search"
                    onChange={(event) => this.componentDidMount(event.target.value)}
                    />

                        {songs && songs.map(song => (

{song.artistName}

                        ))}

    )
  }
}
```

Title: TypeError: songs.map is not a function

Body:
Hi I'm new to react Every time when i run the code it shows the same error. Can anyone explain what is wrong with this code.

import React, { Component } from 'react'
import '../Search.css'
import axios from 'axios'

export default class Search extends Component {

    state = {
        songs: [],
    };

componentDidMount(key) {
    axios.get(`https://cors-anywhere.herokuapp.com/https://itunes.apple.com/search?term=`+key).then(res => {
        console.log(res);
        this.setState({songs: res.data});
    });
}
render() {
    const {songs} = this.state;
    return (

                    <input
                    type="text"
                    name="search"
                    placeholder="Search..."
                    id="search"
                    onChange={(event) => this.componentDidMount(event.target.value)}
                    />

                        {songs.map(song => (

{song.artistName}

                        ))}

    )
  }
}

Body:
You should display the data only when it's available:

render() {
    const {songs} = this.state;
    return (
        <div className="container-fluid">
                    <input
                    type="text"
                    name="search"
                    placeholder="Search..."
                    id="search"
                    onChange={(event) => this.componentDidMount(event.target.value)}
                    />
                    <div>
                        {songs && songs.map(song => (
                            <h1>{song.artistName}</h1>
                        ))}
                    </div>
        </div>
    )
  }
}


问:
SocketException: No such host is known
In my ASP.NET Core 1.1.1 app developed on VS2017 Ver 15.3.3, I'm using Account confirmation and password recovery in ASP.NET Core and MailKit to implement the above article's functionality but I'm getting the following error:

Note:

The error occurs at line await client.ConnectAsync("smtp.relay.uri", 25, SecureSocketOptions.None).ConfigureAwait(false); of SendEmailAsync(...) method below and

at line await _emailSender.SendEmailAsync(model.Email, "Confirm your account", $"Please confirm your account by clicking this link: link"); of the Register(...) post method also shown below:

ERROR

SocketException: No such host is known

MessageServices.cs class

```<code>public class AuthMessageSender : IEmailSender, ISmsSender
{
    public async Task SendEmailAsync(string email, string subject, string message)
    {
        // Plug in your email service here to send an email.
        //return Task.FromResult(0);
        var emailMessage = new MimeMessage();

        //You can if required (and I have done in my code) set the LocalDomain used when communicating with the SMTP server
        //This will be presented as the origin of the emails. In my case I needed to supply the domain so that our internal testing SMTP server would accept and relay my emails.
        //We then asynchronously connect to the SMTP server. The ConnectAsync method can take just the uri of the SMTP server or as I’ve done here be overloaded with a port and SSL option. For my case when testing with our local test SMTP server no SSL was required so I specified this explicitly to make it work.
        emailMessage.From.Add(new MailboxAddress("MyName", "MyEmail@MyDomain.com"));
        emailMessage.To.Add(new MailboxAddress("", email));
        emailMessage.Subject = subject;
        emailMessage.Body = new TextPart("plain") { Text = message };

        using (var client = new SmtpClient())
        {
            client.LocalDomain = "smtp.MyDomain.com";
            await client.ConnectAsync("smtp.relay.uri", 25, SecureSocketOptions.None).ConfigureAwait(false);
            await client.SendAsync(emailMessage).ConfigureAwait(false);
            await client.DisconnectAsync(true).ConfigureAwait(false);
        }
    }
</code>```

Register post method in AccountController.cs

```<code>[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
        var result = await _userManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
            // Send an email with this link
            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
            await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>");
            await _signInManager.SignInAsync(user, isPersistent: false);
            _logger.LogInformation(3, "User created a new account with password.");
            return RedirectToLocal(returnUrl);
        }
        AddErrors(result);
    }
</code>```

UPDATE

Not certain, but the error may be related to me not using my email host info correctly:

I'm using a website/email hosting company DiscountASP.NET's webmail feature. Their SMTP Server name for each subscriber is smtp.YourDomainName.com. And hence, in the SendEmailAsync(...) method above, I'm using client.LocalDomain = "smtp.MyDomain.com";

For MailKit implementation I'm following Sending email via a SMTP server section of this article.

答:
Open your cmd and write ipconfig /all for windows and search for your hostname of your PC
then enter your Hostname in this function

using (var client = new SmtpClient())
    {
        client.LocalDomain = "smtp.MyDomain.com";
        await client.ConnectAsync("YourHostName", 25,false);
        await client.SendAsync(emailMessage).ConfigureAwait(false);
        await client.DisconnectAsync(true).ConfigureAwait(false);
    }```

Title: SocketException: No such host is known

Body:
In my ASP.NET Core 1.1.1 app developed on VS2017 Ver 15.3.3, I'm using Account confirmation and password recovery in ASP.NET Core and MailKit to implement the above article's functionality but I'm getting the following error:

Note:

The error occurs at line await client.ConnectAsync("smtp.relay.uri", 25, SecureSocketOptions.None).ConfigureAwait(false); of SendEmailAsync(...) method below and

at line await _emailSender.SendEmailAsync(model.Email, "Confirm your account", $"Please confirm your account by clicking this link: link"); of the Register(...) post method also shown below:

ERROR

SocketException: No such host is known

MessageServices.cs class

public class AuthMessageSender : IEmailSender, ISmsSender
{
    public async Task SendEmailAsync(string email, string subject, string message)
    {
        // Plug in your email service here to send an email.
        //return Task.FromResult(0);
        var emailMessage = new MimeMessage();

        //You can if required (and I have done in my code) set the LocalDomain used when communicating with the SMTP server
        //This will be presented as the origin of the emails. In my case I needed to supply the domain so that our internal testing SMTP server would accept and relay my emails.
        //We then asynchronously connect to the SMTP server. The ConnectAsync method can take just the uri of the SMTP server or as I’ve done here be overloaded with a port and SSL option. For my case when testing with our local test SMTP server no SSL was required so I specified this explicitly to make it work.
        emailMessage.From.Add(new MailboxAddress("MyName", "MyEmail@MyDomain.com"));
        emailMessage.To.Add(new MailboxAddress("", email));
        emailMessage.Subject = subject;
        emailMessage.Body = new TextPart("plain") { Text = message };

        using (var client = new SmtpClient())
        {
            client.LocalDomain = "smtp.MyDomain.com";
            await client.ConnectAsync("smtp.relay.uri", 25, SecureSocketOptions.None).ConfigureAwait(false);
            await client.SendAsync(emailMessage).ConfigureAwait(false);
            await client.DisconnectAsync(true).ConfigureAwait(false);
        }
    }

Register post method in AccountController.cs

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null)
{
    ViewData["ReturnUrl"] = returnUrl;
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
        var result = await _userManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713
            // Send an email with this link
            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            var callbackUrl = Url.Action(nameof(ConfirmEmail), "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
            await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
                $"Please confirm your account by clicking this link: link");
            await _signInManager.SignInAsync(user, isPersistent: false);
            _logger.LogInformation(3, "User created a new account with password.");
            return RedirectToLocal(returnUrl);
        }
        AddErrors(result);
    }

UPDATE

Not certain, but the error may be related to me not using my email host info correctly:

I'm using a website/email hosting company DiscountASP.NET's webmail feature. Their SMTP Server name for each subscriber is smtp.YourDomainName.com. And hence, in the SendEmailAsync(...) method above, I'm using client.LocalDomain = "smtp.MyDomain.com";

For MailKit implementation I'm following Sending email via a SMTP server section of this article.


问:
Unique index by another column for postgresql
For example, I have this table (postgresql):

CREATE TABLE t(
 a TEXT,
 b TEXT
);
CREATE UNIQUE INDEX t_a_uniq_idx ON t(a);
```

<p>I want to create unique constraint/index for <code>b</code> and <code>a</code> columns. But not simple <code>ADD CONSTRAINT t_ab UNIQUE (a, b)</code>. I want unique <code>b</code> by <code>a</code>:</p>

<pre class="lang-sql prettyprint-override"><code>INSERT INTO t(a,b) VALUES('123', null); -- this is ok
INSERT INTO t(a,b) VALUES('456', '123'); -- this is not ok, because duplicate '123'
</code>```

How can I do this?

Edit:

Why do I need this? For example, If I have users table and I want to create email changing feature, I need structure like this:

CREATE TABLE users(
 email TEXT,
 unconfirmed_email TEXT
 -- some other data
);
CREATE UNIQUE INDEX unq_users_email_idx ON users(email);
```

User can set value into unconfirmed_email column, but only if this value don't used in email column.

答:
If uniqueness is needed across both columns, I think you have the wrong data model.  Instead of storing pairs on a single row, you should have two tables:

```<code>create table pairs (
    pairid int generated always as identity,
    . . .   -- more information about the pair, if needed
);

create table pairElements (
    pairElementId int generated always as identity,
    pairId int references pairs(pairid),
    which int check (which in (1, 2)),
    value text,
    unique (pairid, which)
);
</code>```

Then the condition is simple:

```<code>create constraint unq_pairelements_value unique pairelements(value);
</code>```

Body:
For example, I have this table (postgresql):

CREATE TABLE t(
 a TEXT,
 b TEXT
);
CREATE UNIQUE INDEX t_a_uniq_idx ON t(a);

I want to create unique constraint/index for b and a columns. But not simple ADD CONSTRAINT t_ab UNIQUE (a, b). I want unique b by a:

INSERT INTO t(a,b) VALUES('123', null); -- this is ok
INSERT INTO t(a,b) VALUES('456', '123'); -- this is not ok, because duplicate '123'

How can I do this?

Edit:

Why do I need this? For example, If I have users table and I want to create email changing feature, I need structure like this:

CREATE TABLE users(
 email TEXT,
 unconfirmed_email TEXT
 -- some other data
);
CREATE UNIQUE INDEX unq_users_email_idx ON users(email);

User can set value into unconfirmed_email column, but only if this value don't used in email column.

Body:
If uniqueness is needed across both columns, I think you have the wrong data model.  Instead of storing pairs on a single row, you should have two tables:

create table pairs (
    pairid int generated always as identity,
    . . .   -- more information about the pair, if needed
);

create table pairElements (
    pairElementId int generated always as identity,
    pairId int references pairs(pairid),
    which int check (which in (1, 2)),
    value text,
    unique (pairid, which)
);

Then the condition is simple:

create constraint unq_pairelements_value unique pairelements(value);


问:
What data do I need to implement k nearest neighbor?
I currently have a reddit-clone type website. I'm trying to recommend posts based on the posts that my users have previously liked.

It seems like K nearest neighbor or k means are the best way to do this.

I can't seem to understand how to actually implement this. I've seen some mathematical formulas (such as the one on the k means wikipedia page), but they don't really make sense to me.

Could someone maybe recommend some pseudo code, or places to look so I can get a better feel on how to do this?

答:
To do k-nearest neighbors you mostly need a notion of distance and a way of finding the k nearest neighbours to a point that you can afford (you probably don't want to search through all your data points one by one). There is a library for approximate nearest neighbour at http://www.cs.umd.edu/~mount/ANN/. It's a very simple classification algorithm - to classify a new point p, find its k nearest neighbours and classify p according to the most popular classes amongst those k neighbours.

I guess in your case you could provide somebody with a list of similar posts as soon as you decide what nearest means, and then monitor click-through from this and try to learn from that to predict which of those alternatives would be most popular.

If you are interested in finding a particularly good learning algorithm for your purposes, have a look at http://www.cs.waikato.ac.nz/ml/weka/ - it allows you to try out a large number of different algorithms, and also to write your own as plug-ins.


问:
How to copy/paste particular column from one df to another by pandas
I have got 'a' dataframe as sample:

```<code>Date    old
01.04.2020. 637
02.04.2020. 1676
03.04.2020. 1079
04.04.2020. 3091
05.04.2020. 330
06.04.2020. 319
07.04.2020. 73
08.04.2020. 909
09.04.2020. 12
10.04.2020. 46626
</code>```

How to copy/paste single (or several) columns to variable b by using pandas library. This syntax b['new'] = a['old'] does not work and I cannot figure out how to use 'columns' or other methods.

Thank you!

Valters

答:
Thanks to Ch3steR this is the answer:

```<code>b=pd.DataFrame()
b['new'] = a['old']
</code>```

Body:
I have got 'a' dataframe as sample:

Date    old
01.04.2020. 637
02.04.2020. 1676
03.04.2020. 1079
04.04.2020. 3091
05.04.2020. 330
06.04.2020. 319
07.04.2020. 73
08.04.2020. 909
09.04.2020. 12
10.04.2020. 46626

How to copy/paste single (or several) columns to variable b by using pandas library. This syntax b['new'] = a['old'] does not work and I cannot figure out how to use 'columns' or other methods.

Thank you!

Valters

Body:
Thanks to Ch3steR this is the answer:

b=pd.DataFrame()
b['new'] = a['old']


问:
Vuetify stopped working when included in a Typescript-enabled Vue.js project
I have recently tried to create a simple app that combines Vue.js, Vuetify.js and Typescript. However, even though at first Vuetify seemed to work when combined with Typescript, upon my most recent app compilation, all I get are error messages of the type "Unknown custom component".

Here is the configuration for my vuetify.js file:

```<code>import '@mdi/font/css/materialdesignicons.css'
import Vue from 'vue'
import Vuetify from 'vuetify/lib'

Vue.use(Vuetify)

export default new Vuetify({
icons: {
    iconfont: 'mdi',
  },
})
</code>```

And here is the config for my main.ts file:

```<code>import Vue from 'vue';
import App from './App.vue';
import router from './router';
import './registerServiceWorker';
import vuetify from '@/plugins/vuetify.js';

Vue.config.productionTip = false;

new Vue({
  router,
  vuetify,
  render: (h) => h(App),
}).$mount('#app');
</code>```

I installed Vuetify using npm install vuetify and not through the Vue CLI.

答:
Those who are still find trouble with Vuetify + Vue + Typescript.

```<code>vue create project-name
cd project-name
vue add vuetify
</code>```

when your vuetify added, you will see under plugins folder, a file name vuetify.ts just created where you can custom your vuetify theme and also vuetify will be added to main.ts . Then you will able to find

```<code>node_module/vuetify/types
</code>```

This file need to add in tsconfig.json

```<code>"types": [
  ...
  "vuetify"
],

// then add this
"typeRoots": [
  "./node_modules/@types",
  "./node_modules/vuetify/types"
]
</code>```

Enjoy !!

Body:
I have recently tried to create a simple app that combines Vue.js, Vuetify.js and Typescript. However, even though at first Vuetify seemed to work when combined with Typescript, upon my most recent app compilation, all I get are error messages of the type "Unknown custom component".

Here is the configuration for my vuetify.js file:

import '@mdi/font/css/materialdesignicons.css'
import Vue from 'vue'
import Vuetify from 'vuetify/lib'

Vue.use(Vuetify)

export default new Vuetify({
icons: {
    iconfont: 'mdi',
  },
})

And here is the config for my main.ts file:

import Vue from 'vue';
import App from './App.vue';
import router from './router';
import './registerServiceWorker';
import vuetify from '@/plugins/vuetify.js';

Vue.config.productionTip = false;

new Vue({
  router,
  vuetify,
  render: (h) => h(App),
}).$mount('#app');

I installed Vuetify using npm install vuetify and not through the Vue CLI.

Body:
Those who are still find trouble with Vuetify + Vue + Typescript.

vue create project-name
cd project-name
vue add vuetify

when your vuetify added, you will see under plugins folder, a file name vuetify.ts just created where you can custom your vuetify theme and also vuetify will be added to main.ts . Then you will able to find

node_module/vuetify/types

This file need to add in tsconfig.json

"types": [
  ...
  "vuetify"
],

// then add this
"typeRoots": [
  "./node_modules/@types",
  "./node_modules/vuetify/types"
]

Enjoy !!


答:
props is being used in both scenarios. You are just accessing props values differently. First example uses Class component. That means props is passed to children as this.props, where as second example uses stateless/ functional component, which means no this. And

```<code>    const FunctionalComponent = (props) => {
        const {name, onLogin} = props
     ......
    }
</code>```

is equivalent to

```<code>   const FunctionalComponent = ({name, onLogin}) => {
   .....
   }
</code>```

due to Object Destructuring, hence you are not seeing explicit use of props in second example.

Title: When to use this.prop when passing down props?

Body:
I'm a beginner in JS/React and I am trying to wrap my head around the concept of when to use this.prop or just passing props down without this in React.

In some sources, the coder always uses this.prop while in others this seems to be unnecessary. Could anyone please clarify?

In this example, we are passing props username, authed, logout, and header from apps to hello. To do so, we use this.props. everytime we import.

However, in this example (React Native), we pass down term, onTermChange, and onTermSubmit from searchscreen to searchbar, without using this.props. Then I believe we re-defined our props in the TextInput of Search bar so its onEndEditing is the same as the onTermSubmit from the searchscreen.

I thought this.props may be a react syntax which became streamlined in React Native. However, I came across yet another example in React which does not use this.props:

Body:
props is being used in both scenarios. You are just accessing props values differently. First example uses Class component. That means props is passed to children as this.props, where as second example uses stateless/ functional component, which means no this. And

    const FunctionalComponent = (props) => {
        const {name, onLogin} = props
     ......
    }

is equivalent to

   const FunctionalComponent = ({name, onLogin}) => {
   .....
   }

due to Object Destructuring, hence you are not seeing explicit use of props in second example.


问:
how to design react native OTP enter screen?
I am new in react native design .Let me know how to achieve the screen shown below

is it necessary to use 4 TextInput or possible with one?

答:
I solved this problem for 6 digit otp by Following Chethan's answer.
Firstly create a array 'otp' initialised with otp = ['-','-','-','-','-','-'] in state,then create a otpVal string in state like this

```<code>const [otp, setOtp] = useState(['-', '-', '-', '-', '-', '-']);
const [otpVal, setOtpVal] = useState('');
</code>```

Now the actual logic of rendering otp boxes willbe as follows.

```<code>                   <TextInput
                    onChangeText={value => {
                        if (isNaN(value)) {
                            return;
                        }
                        if (value.length > 6) {
                            return;
                        }
                        let val =
                            value + '------'.substr(0, 6 - value.length);
                        let a = [...val];
                        setOtpVal(a);
                        setOtp(value);
                    }}
                    style={{ height: 0 }}
                    autoFocus = {true}
                />
                <View style={styles.otpBoxesContainer}>
                    {[0, 1, 2, 3, 4, 5].map((item, index) => (
                        <Text style={styles.otpBox} key={index}>
                            {otp[item]}
                        </Text>
                    ))}
                </View>
</code>```

with styles of otpBoxesContainer and otpBox as below:

```<code> otpBoxesContainer: {
    flexDirection: 'row'
},
otpBox: {
    padding: 10,
    marginRight: 10,
    borderWidth: 1,
    borderColor: lightGrey,
    height: 45,
    width: 45,
    textAlign: 'center'
}
</code>```

Now , since height of TextInput is set to 0, it doesn't show up to the user but it still takes the input. And we modify and store that input in such a way, that we can show it like values are entered in separate input boxes.

Body:
I solved this problem for 6 digit otp by Following Chethan's answer.
Firstly create a array 'otp' initialised with otp = ['-','-','-','-','-','-'] in state,then create a otpVal string in state like this

const [otp, setOtp] = useState(['-', '-', '-', '-', '-', '-']);
const [otpVal, setOtpVal] = useState('');

Now the actual logic of rendering otp boxes willbe as follows.

                   <TextInput
                    onChangeText={value => {
                        if (isNaN(value)) {
                            return;
                        }
                        if (value.length > 6) {
                            return;
                        }
                        let val =
                            value + '------'.substr(0, 6 - value.length);
                        let a = [...val];
                        setOtpVal(a);
                        setOtp(value);
                    }}
                    style={{ height: 0 }}
                    autoFocus = {true}
                />
                <View style={styles.otpBoxesContainer}>
                    {[0, 1, 2, 3, 4, 5].map((item, index) => (
                        <Text style={styles.otpBox} key={index}>
                            {otp[item]}
                        </Text>
                    ))}
                </View>

with styles of otpBoxesContainer and otpBox as below:

 otpBoxesContainer: {
    flexDirection: 'row'
},
otpBox: {
    padding: 10,
    marginRight: 10,
    borderWidth: 1,
    borderColor: lightGrey,
    height: 45,
    width: 45,
    textAlign: 'center'
}

Now , since height of TextInput is set to 0, it doesn't show up to the user but it still takes the input. And we modify and store that input in such a way, that we can show it like values are entered in separate input boxes.


问:
How to manage slug in views.py django
I'm having trouble dealing with slugs: I have defined different slugs for every article in admin panel but on my website, if I type any random slug(e.g- fvrryybr,34,d4g5tg5) on any page of my app it takes me to the webpage of article function of views.py

I don't know how to deal with as I a beginner in Django

____view.py___

```<code> def article(request,slug):
    allarticles = Article.objects.all()
    context = {'allarticles':allarticles}
    return render(request,"news/Home/tnews/blog-single.html",context)
</code>```

models.py

```<code>class Post(models.Model):
    no = models.CharField(max_length=1000,primary_key=True)
    title = models.CharField(max_length=100)
    content = models.TextField()
    cover = models.ImageField(upload_to='images/')
    timeStamp = models.DateTimeField(blank=True)
    slug = models.SlugField(null=False,unique=True)

    def __str__(self):
        return self.title

class Article(models.Model):
   heading = models.CharField(max_length=1000)
   player = models.CharField(max_length=100)
   article = models.TextField()
   source = models.CharField(max_length=50)
   date = models.DateTimeField(blank=True)
   image = models.ImageField(upload_to='images/')

   def __str__(self):
    return 'Article on '+ self.player
</code>```

urls.py

```<code>   path("<slug:slug>",views.article,name='article')
</code>```

答:
Add slug to article model

```<code>Class Article(models.Model):
    slug = models.SlugField(unique=True)
</code>```

```<code>from django.shortcuts import get_object_or_404

def article_detail(request, article):
    article = get_object_or_404(Model_Name, slug=article)
    context = {'article ': article}
    return render(request,"news/Home/tnews/blog-single.html",context)

</code>```

In urls.py
path('<slug:article>/", views.article_detail, name='detail'),

get_object_or_404 is a function similar to get() function, it returns an object if it exists or 404 if it doesn't exist.

If you want to add link in template set href attribute of a tag
href="{% url 'article' article.slug %}"
Also I think you want to get details of an article so make a new function like I did article_detail and pass variables to template.

Title: How to manage slug in views.py django

Body:
I'm having trouble dealing with slugs: I have defined different slugs for every article in admin panel but on my website, if I type any random slug(e.g- fvrryybr,34,d4g5tg5) on any page of my app it takes me to the webpage of article function of views.py

I don't know how to deal with as I a beginner in Django

____view.py___

 def article(request,slug):
    allarticles = Article.objects.all()
    context = {'allarticles':allarticles}
    return render(request,"news/Home/tnews/blog-single.html",context)

models.py

class Post(models.Model):
    no = models.CharField(max_length=1000,primary_key=True)
    title = models.CharField(max_length=100)
    content = models.TextField()
    cover = models.ImageField(upload_to='images/')
    timeStamp = models.DateTimeField(blank=True)
    slug = models.SlugField(null=False,unique=True)

    def __str__(self):
        return self.title

class Article(models.Model):
   heading = models.CharField(max_length=1000)
   player = models.CharField(max_length=100)
   article = models.TextField()
   source = models.CharField(max_length=50)
   date = models.DateTimeField(blank=True)
   image = models.ImageField(upload_to='images/')

   def __str__(self):
    return 'Article on '+ self.player

urls.py

   path("<slug:slug>",views.article,name='article')

Body:
Add slug to article model

Class Article(models.Model):
    slug = models.SlugField(unique=True)

from django.shortcuts import get_object_or_404

def article_detail(request, article):
    article = get_object_or_404(Model_Name, slug=article)
    context = {'article ': article}
    return render(request,"news/Home/tnews/blog-single.html",context)

In urls.py
path('<slug:article>/", views.article_detail, name='detail'),

get_object_or_404 is a function similar to get() function, it returns an object if it exists or 404 if it doesn't exist.

If you want to add link in template set href attribute of a tag
href="{% url 'article' article.slug %}"
Also I think you want to get details of an article so make a new function like I did article_detail and pass variables to template.


问:
Reading a file in a table format and print it
So, what I'm trying to do is, at first create a file in a table format then read that file and put that file in 4 different dynamic arrays using struct and print them in order

So, here is the struct I'm using: I used capacity = 5 to change the size of dynamic array later but still don't know how to change it

```<code>struct score{
    char *str1;
    char *str2;
    int *num1;
    int *num2;
};

int main(){
    int capacity = 5;
    struct score table;
    table.str1=(char *)malloc(sizeof(int)*capacity);
    table.str2=(char *)malloc(sizeof(int)*capacity);
    table.num1=(int *)malloc(sizeof(int)*capacity);
    table.num2=(int *)malloc(sizeof(int)*capacity);
</code>```

After I created a File to write:

```<code>    inFile = fopen("Subject.txt", "w");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }

    char names[] = {"Joe Math 52 85\nBilly Phy 65 70\nSophia Chem 86 71"};

    fprintf(inFile,"%s",names);
    fclose(inFile);
</code>```

At the end reading a File and putting them in arrays:

```<code>    inFile = fopen("Subject.txt", "r");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }
    fscanf(inFile, "%s %s %d %d",table.str1, table.str2, table.num1, table.num2);
    fclose(inFile);

    for(i=0;i<6;i++){
        printf("%s %s %d %d\n",table.str1, table.str2, table.num1, table.num2);
    }
</code>```

So, I need this code to print like this, and I couldn't do it:

```<code>Name   Subj.  Test1  Test2
------------------------
Joe    Math   52     85
Billy  Phy    65     70
Sophia Chem   86     71
</code>```

Here is my full Code just in case:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct score{
    char *str1;
    char *str2;
    int *num1;
    int *num2;
};

int main(){
    FILE *inFile;
    int num, capacity = 5, i;
    struct score table;
    table.str1=(char *)malloc(sizeof(int)*capacity);
    table.str2=(char *)malloc(sizeof(int)*capacity);
    table.num1=(int *)malloc(sizeof(int)*capacity);
    table.num2=(int *)malloc(sizeof(int)*capacity);
    inFile = fopen("Subject.txt", "w");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }

    char names[] = {"Joe Math 52 85\nBilly Phy 65 70\nSophia Chem 86 71"};

    fprintf(inFile,"%s",names);
    fclose(inFile);

    inFile = fopen("Subject.txt", "r");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }
    fscanf(inFile, "%s %s %d %d",table.str1, table.str2, table.num1, table.num2);
    fclose(inFile);

    for(i=0;i<6;i++){
        printf("%s %s %d %d\n",table.str1, table.str2, table.num1, table.num2);
    }
}
</code>```

答:
You want an array of structs.

But, you've got a fixed number of scores (e.g. num1, num2). This, also, should be an array.

I think you'll be better off with a second struct. That is, struct student and struct score

And, Paul outlined how to do this with fixed limits.

In general, you could allocate things dynamically to accomodate an arbitrary number of students that have an arbitrary (and varying) number of test scores.

Based on your sample data, your input format is:

```<code><name> <subject> <score1> <score2> ... <scoreN>
</code>```

Because of this, I interpret the subject to be the students major, so it gets grouped in the student record.

Otherwise, we'd need something like:

```<code><name> <subject1> <score1> <subject2> <score2> ... <subjectN> <scoreN>
</code>```

And, then, the subject would go into the score record

To get it to work, I had to [heavily] refactor your code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct score {
    int score;
};

struct student {
    char *name;
    char *subject;
    struct score *scores;
    int count;
};

int
main(void)
{
    FILE *inFile;
    struct student *students = NULL;
    int student_count = 0;
    struct student *who;
    struct score *score;
    const char *delim = " \t\n";
    char *cp;
    char buf[1000];

    inFile = fopen("Subject.txt", "w");
    if (inFile == NULL) {
        printf("Error!");
        exit(1);
    }

    char names[] = { "Joe Math 52 85\nBilly Phy 65 70\nSophia Chem 86 71" };

    fprintf(inFile, "%s", names);
    fclose(inFile);

    inFile = fopen("Subject.txt", "r");
    if (inFile == NULL) {
        printf("Error!");
        exit(1);
    }

    while (1) {
        // get a line
        cp = fgets(buf,sizeof(buf),inFile);
        if (cp == NULL)
            break;

        // get the student name
        cp = strtok(buf,delim);
        if (cp == NULL)
            continue;

        // allocate new student record
        students = realloc(students,
            sizeof(struct student) * (student_count + 1));
        who = &students[student_count];
        student_count += 1;

        // save the student name
        who->name = strdup(cp);

        // get the subject and save it
        cp = strtok(NULL,delim);
        if (cp == NULL)
            break;
        who->subject = strdup(cp);

        // clear out the scores array
        who->count = 0;
        who->scores = NULL;

        // get all scores
        while (1) {
            cp = strtok(NULL,delim);
            if (cp == NULL)
                break;

            // increase the size of the scores array for this student
            who->scores = realloc(who->scores,
                sizeof(struct score) * (who->count + 1));
            score = &who->scores[who->count];
            who->count += 1;

            score->score = atoi(cp);
        }
    }

    fclose(inFile);

    for (who = &students[0];  who < &students[student_count];  ++who) {
        printf("%10s %10s", who->name, who->subject);

        for (score = who->scores;  score < &who->scores[who->count];  ++score)
            printf("%4d",score->score);

        printf("\n");
    }

    return 0;
}
</code>```

Here's the program output:

```<code>       Joe       Math  52  85
     Billy        Phy  65  70
    Sophia       Chem  86  71
</code>```

Body:
So, what I'm trying to do is, at first create a file in a table format then read that file and put that file in 4 different dynamic arrays using struct and print them in order

So, here is the struct I'm using: I used capacity = 5 to change the size of dynamic array later but still don't know how to change it

struct score{
    char *str1;
    char *str2;
    int *num1;
    int *num2;
};

int main(){
    int capacity = 5;
    struct score table;
    table.str1=(char *)malloc(sizeof(int)*capacity);
    table.str2=(char *)malloc(sizeof(int)*capacity);
    table.num1=(int *)malloc(sizeof(int)*capacity);
    table.num2=(int *)malloc(sizeof(int)*capacity);

After I created a File to write:

    inFile = fopen("Subject.txt", "w");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }

    char names[] = {"Joe Math 52 85\nBilly Phy 65 70\nSophia Chem 86 71"};

    fprintf(inFile,"%s",names);
    fclose(inFile);

At the end reading a File and putting them in arrays:

    inFile = fopen("Subject.txt", "r");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }
    fscanf(inFile, "%s %s %d %d",table.str1, table.str2, table.num1, table.num2);
    fclose(inFile);

    for(i=0;i<6;i++){
        printf("%s %s %d %d\n",table.str1, table.str2, table.num1, table.num2);
    }

So, I need this code to print like this, and I couldn't do it:

Name   Subj.  Test1  Test2
------------------------
Joe    Math   52     85
Billy  Phy    65     70
Sophia Chem   86     71

Here is my full Code just in case:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct score{
    char *str1;
    char *str2;
    int *num1;
    int *num2;
};

int main(){
    FILE *inFile;
    int num, capacity = 5, i;
    struct score table;
    table.str1=(char *)malloc(sizeof(int)*capacity);
    table.str2=(char *)malloc(sizeof(int)*capacity);
    table.num1=(int *)malloc(sizeof(int)*capacity);
    table.num2=(int *)malloc(sizeof(int)*capacity);
    inFile = fopen("Subject.txt", "w");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }

    char names[] = {"Joe Math 52 85\nBilly Phy 65 70\nSophia Chem 86 71"};

    fprintf(inFile,"%s",names);
    fclose(inFile);

    inFile = fopen("Subject.txt", "r");
    if(inFile == NULL)
    {
      printf("Error!");
      exit(1);
    }
    fscanf(inFile, "%s %s %d %d",table.str1, table.str2, table.num1, table.num2);
    fclose(inFile);

    for(i=0;i<6;i++){
        printf("%s %s %d %d\n",table.str1, table.str2, table.num1, table.num2);
    }
}

Body:
You want an array of structs.

But, you've got a fixed number of scores (e.g. num1, num2). This, also, should be an array.

I think you'll be better off with a second struct. That is, struct student and struct score

And, Paul outlined how to do this with fixed limits.

In general, you could allocate things dynamically to accomodate an arbitrary number of students that have an arbitrary (and varying) number of test scores.

Based on your sample data, your input format is:

<name> <subject> <score1> <score2> ... <scoreN>

Because of this, I interpret the subject to be the students major, so it gets grouped in the student record.

Otherwise, we'd need something like:

<name> <subject1> <score1> <subject2> <score2> ... <subjectN> <scoreN>

And, then, the subject would go into the score record

To get it to work, I had to [heavily] refactor your code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct score {
    int score;
};

struct student {
    char *name;
    char *subject;
    struct score *scores;
    int count;
};

int
main(void)
{
    FILE *inFile;
    struct student *students = NULL;
    int student_count = 0;
    struct student *who;
    struct score *score;
    const char *delim = " \t\n";
    char *cp;
    char buf[1000];

    inFile = fopen("Subject.txt", "w");
    if (inFile == NULL) {
        printf("Error!");
        exit(1);
    }

    char names[] = { "Joe Math 52 85\nBilly Phy 65 70\nSophia Chem 86 71" };

    fprintf(inFile, "%s", names);
    fclose(inFile);

    inFile = fopen("Subject.txt", "r");
    if (inFile == NULL) {
        printf("Error!");
        exit(1);
    }

    while (1) {
        // get a line
        cp = fgets(buf,sizeof(buf),inFile);
        if (cp == NULL)
            break;

        // get the student name
        cp = strtok(buf,delim);
        if (cp == NULL)
            continue;

        // allocate new student record
        students = realloc(students,
            sizeof(struct student) * (student_count + 1));
        who = &students[student_count];
        student_count += 1;

        // save the student name
        who->name = strdup(cp);

        // get the subject and save it
        cp = strtok(NULL,delim);
        if (cp == NULL)
            break;
        who->subject = strdup(cp);

        // clear out the scores array
        who->count = 0;
        who->scores = NULL;

        // get all scores
        while (1) {
            cp = strtok(NULL,delim);
            if (cp == NULL)
                break;

            // increase the size of the scores array for this student
            who->scores = realloc(who->scores,
                sizeof(struct score) * (who->count + 1));
            score = &who->scores[who->count];
            who->count += 1;

            score->score = atoi(cp);
        }
    }

    fclose(inFile);

    for (who = &students[0];  who < &students[student_count];  ++who) {
        printf("%10s %10s", who->name, who->subject);

        for (score = who->scores;  score < &who->scores[who->count];  ++score)
            printf("%4d",score->score);

        printf("\n");
    }

    return 0;
}

Here's the program output:

       Joe       Math  52  85
     Billy        Phy  65  70
    Sophia       Chem  86  71


问:
Vue: How to use variable as array key in component binding
How can I use variable array keys for bindings in my custom component? In the following example, title must be 'Title 1 for default settings' if componenttype is set to 'default', 'Title 1 for guest settings' if componenttype is set to 'guest' etc. I tried to interpolate it in several ways, but nothing worked so far. Any hints?

```<code><my-component
    v-for="item in items"
    :id="item.id"
    :title="item['componenttype'].title"     <-- how to interpolate here?
>
</my-component>

...
data() {
   return {
      componenttype: 'default',
      items: [
         {
            1: {
               default: {
                  title: 'Title 1 for default settings',
               },
               guest: {
                  title: 'Title 1 for guest settings'
               }
            },
            2: {
               default: {
                  title: 'Title 2 for default settings',
               },
               guest: {
                  title: 'Title 2 for guest settings'
               }
            },
         }
      ]
   }
}
...
</code>```

答:
Your array currently contains only one object, with multiple nested objects. It should be:

```<code>items: [
            {
               default: {
                  title: 'Title 1 for default settings',
               },
               guest: {
                  title: 'Title 1 for guest settings'
               }
            },
            {
               default: {
                  title: 'Title 2 for default settings',
               },
               guest: {
                  title: 'Title 2 for guest settings'
               }
            }
      ]
</code>```

With this the following should work:

```<code><my-component v-for="item in items"
    :title="item[componenttype].title"
/>
</code>```

Body:
How can I use variable array keys for bindings in my custom component? In the following example, title must be 'Title 1 for default settings' if componenttype is set to 'default', 'Title 1 for guest settings' if componenttype is set to 'guest' etc. I tried to interpolate it in several ways, but nothing worked so far. Any hints?

<my-component
    v-for="item in items"
    :id="item.id"
    :title="item['componenttype'].title"     <-- how to interpolate here?
>
</my-component>

...
data() {
   return {
      componenttype: 'default',
      items: [
         {
            1: {
               default: {
                  title: 'Title 1 for default settings',
               },
               guest: {
                  title: 'Title 1 for guest settings'
               }
            },
            2: {
               default: {
                  title: 'Title 2 for default settings',
               },
               guest: {
                  title: 'Title 2 for guest settings'
               }
            },
         }
      ]
   }
}
...

Body:
Your array currently contains only one object, with multiple nested objects. It should be:

items: [
            {
               default: {
                  title: 'Title 1 for default settings',
               },
               guest: {
                  title: 'Title 1 for guest settings'
               }
            },
            {
               default: {
                  title: 'Title 2 for default settings',
               },
               guest: {
                  title: 'Title 2 for guest settings'
               }
            }
      ]

With this the following should work:

<my-component v-for="item in items"
    :title="item[componenttype].title"
/>


答:
It's not a React thing but a JavaScript thing.

Classes - Here you need to access the state and props using the this keyword.

Functions - Here you don't need to use this in React. The argument to your function component here are props so you can directly use props.something and not this.props.something.

In your Searchbar component:-

const Searchbar = ({term,onTermSubmit,onTermChange}) means that the properties
term,onTermSubmit and onTermChange are being destructured from the props object and so can now be used directly. You don't need to access them like props.term anymore. They can directly be accessed like term wherever you want them to be.


答:
If you want to copy independently you can do it as following:

```<code>import copy

b = pd.DataFrame()
b['new'] = copy.deepcopy(a['old'])
</code>```

Above code will copy column data of one dataframe into another.

Title: How to copy/paste particular column from one df to another by pandas

Body:
If you want to copy independently you can do it as following:

import copy

b = pd.DataFrame()
b['new'] = copy.deepcopy(a['old'])

Above code will copy column data of one dataframe into another.


问:
Checking for duplicate data in SQL Server
Please don't ask me why but there is a lot of duplicate data where every field is duplicated.

For example

```<code>alex, 1
alex, 1
liza, 32
hary, 34
</code>```

I will need to eliminate from this table one of the alex, 1 rows

I know this algorithm will be very ineffecient, but it does not matter. I will need to remove duplicate data.

What is the best way to do this? Please keep in mind I do not have 2 fields, I actually have about 10 fields to check on.

答:
A bit different solution which requires primary key(or unique index):
Suppose you have a table your_table(id - PK, name, and num)

```<code>DELETE
FROM your_table
FROM your_table AS t2
WHERE
(select  COUNT(*) FROM your_table y
  where t2.name = y.name and  t2.num = y.num) >1
AND t2.id !=
(SELECT top 1 id FROM your_table z
 WHERE t2.name = z.name and  t2.num = z.num);
</code>```

I assumed that name and num are NOT NULL, if they can contain NULL values, you need to change wheres in sub-queries.

Body:
Please don't ask me why but there is a lot of duplicate data where every field is duplicated.

For example

alex, 1
alex, 1
liza, 32
hary, 34

I will need to eliminate from this table one of the alex, 1 rows

I know this algorithm will be very ineffecient, but it does not matter. I will need to remove duplicate data.

What is the best way to do this? Please keep in mind I do not have 2 fields, I actually have about 10 fields to check on.

Body:
A bit different solution which requires primary key(or unique index):
Suppose you have a table your_table(id - PK, name, and num)

DELETE
FROM your_table
FROM your_table AS t2
WHERE
(select  COUNT(*) FROM your_table y
  where t2.name = y.name and  t2.num = y.num) >1
AND t2.id !=
(SELECT top 1 id FROM your_table z
 WHERE t2.name = z.name and  t2.num = z.num);

I assumed that name and num are NOT NULL, if they can contain NULL values, you need to change wheres in sub-queries.


答:
```<code>from django.shortcuts import get_object_or_404

def article(request,slug):
    allarticles= get_object_or_404(Article, slug=slug)
    context = {'allarticles':allarticles}
    return render(request,"news/Home/tnews/blog-single.html",context)
</code>```

and urls.py

```<code>   path("<str:slug>",views.article,name='article')
</code>```

and

```<code>class Article(models.Model):
   heading = models.CharField(max_length=1000)
   player = models.CharField(max_length=100)
   article = models.TextField()
   source = models.CharField(max_length=50)
   date = models.DateTimeField(blank=True)
   image = models.ImageField(upload_to='images/')

  slug = models.SlugField(unique=True)

   def __str__(self):
    return 'Article on '+ self.player
</code>```

Title: How to manage slug in views.py django

Body:
from django.shortcuts import get_object_or_404

def article(request,slug):
    allarticles= get_object_or_404(Article, slug=slug)
    context = {'allarticles':allarticles}
    return render(request,"news/Home/tnews/blog-single.html",context)

and urls.py

   path("<str:slug>",views.article,name='article')

and

class Article(models.Model):
   heading = models.CharField(max_length=1000)
   player = models.CharField(max_length=100)
   article = models.TextField()
   source = models.CharField(max_length=50)
   date = models.DateTimeField(blank=True)
   image = models.ImageField(upload_to='images/')

  slug = models.SlugField(unique=True)

   def __str__(self):
    return 'Article on '+ self.player


问:
Natural Tranformation in a More General Context
I've been building my way up through some category theory in Haskell on my way to creating more general Monads.

Before I can move onto the next step I am going to need to be able to work with natural transformations.

Now natural transformations on regular Functors are easy enough they are just functions

```<code>trans :: forall a . F a -> G a
</code>```

(where F and G are Functors) with the additional restriction that

```<code>fmap f . trans = trans . fmap f
</code>```

equivalent to the commutative diagram:

However when I move on to more categorical functors

```<code>class
  ( Category cat1
  , Category cat2
  )
    => Functor cat1 cat2 f
  where
    map :: cat1 a b -> cat2 (f a) (f b)
</code>```

I am not sure how I can augment the definition of natural transformation to keep up.

The diagram implies that

```<code>trans :: forall a . cat2 (F a) (G a)
</code>```

where

```<code>Functor cat1  cat2 F
Functor cat1' cat2 G
</code>```

However it is not clear to me that it must be the case that cat1 ~ cat1'.  Or what the relationship between the transformation and the precategories of both functors are.

What does a natural tranformation look like in the broader context of Haskell Functors over more general categories?

答:
However it is not clear to me that it must be the case that cat1 ~ cat1'.

It's part of the definition of a natural transformation that the functors F and G have the same domain and codomain. From nlab:

Given categories C and D, and functors F, G : C -> D

So a direct translation of the definition in Haskell is that a natural transformation between functors F, G with domain cat1 and codomain cat2 is as a polymorphic term, a family of morphisms cat2 (F a) (G a) indexed by objects a:

n :: forall a. cat2 (F a) (G a)
```

<p>such that a certain diagram commutes for all <code>f :: cat1 a b</code>, i.e., we have the following equation, where <code>(.)</code> is composition in <code>cat2</code>:</p>

<pre class="lang-hs prettyprint-override"><code>fmap f . n = n . fmap f
</code>```

where n is specialized at type a on the left, and at type b on the right.

Note that this encoding is limited in expressiveness, because Haskell forall is not identical to English "for all". The behavior of n :: forall a. ... cannot really depend on a. forall implies a form of "uniformity" (aka. parametricity) which is not found in the definition of "natural transformations".

Body:
I've been building my way up through some category theory in Haskell on my way to creating more general Monads.

Before I can move onto the next step I am going to need to be able to work with natural transformations.

Now natural transformations on regular Functors are easy enough they are just functions

trans :: forall a . F a -> G a

(where F and G are Functors) with the additional restriction that

fmap f . trans = trans . fmap f

equivalent to the commutative diagram:

However when I move on to more categorical functors

class
  ( Category cat1
  , Category cat2
  )
    => Functor cat1 cat2 f
  where
    map :: cat1 a b -> cat2 (f a) (f b)

I am not sure how I can augment the definition of natural transformation to keep up.

The diagram implies that

trans :: forall a . cat2 (F a) (G a)

where

Functor cat1  cat2 F
Functor cat1' cat2 G

However it is not clear to me that it must be the case that cat1 ~ cat1'.  Or what the relationship between the transformation and the precategories of both functors are.

What does a natural tranformation look like in the broader context of Haskell Functors over more general categories?

Body:
However it is not clear to me that it must be the case that cat1 ~ cat1'.

It's part of the definition of a natural transformation that the functors F and G have the same domain and codomain. From nlab:

Given categories C and D, and functors F, G : C -> D

So a direct translation of the definition in Haskell is that a natural transformation between functors F, G with domain cat1 and codomain cat2 is as a polymorphic term, a family of morphisms cat2 (F a) (G a) indexed by objects a:

n :: forall a. cat2 (F a) (G a)

such that a certain diagram commutes for all f :: cat1 a b, i.e., we have the following equation, where (.) is composition in cat2:

fmap f . n = n . fmap f

where n is specialized at type a on the left, and at type b on the right.

Note that this encoding is limited in expressiveness, because Haskell forall is not identical to English "for all". The behavior of n :: forall a. ... cannot really depend on a. forall implies a form of "uniformity" (aka. parametricity) which is not found in the definition of "natural transformations".