问:
Can anyone help me with the fortran program I made?
```<code>program diziler
    implicit none
    integer :: N, i
    real :: arr(N), sum, mean, stddev, var

    ! Get the value of N
    write(*,'(A)') "Enter the number of elements in the array:"
    read(*,'(I)') N

    ! Get the elements of the array
    write(*,'(A)') "Enter the elements of the array:"
    do i = 1, N
        read(*,'(F)') arr(i)
        sum = sum + arr(i)
    end do

    ! Calculate the mean
    mean = sum / N

    ! Calculate the variance
    do i = 1, N
        var = var + (arr(i) - mean)**2
    end do
    var = var / N

    ! Calculate the standard deviation
    stddev = sqrt(var)

    ! Print the results
    write(*,'(A,F)') "Mean: ", mean
    write(*,'(A,F)') "Standard deviation: ", stddev
end program diziler
</code>```

it gives error like this

```<code>C:\Users\Teknik\Desktop\6.odev.F95(8) : error 270 - Missing width count for 'I' descriptor
C:\Users\Teknik\Desktop\6.odev.F95(13) : error 270 - Missing width count for 'F' descriptor
C:\Users\Teknik\Desktop\6.odev.F95(30) : error 270 - Missing width count for 'F' descriptor
C:\Users\Teknik\Desktop\6.odev.F95(31) : error 270 - Missing width count for 'F' descriptor
C:\Users\Teknik\Desktop\6.odev.F95(3) : error 542 - N appears in the dimension of a variable, yet is not a dummy argument, a variable available through USE or CONTAINS association, a COMMON variable, a PARAMETER, or
</code>```

Body:
program diziler
    implicit none
    integer :: N, i
    real :: arr(N), sum, mean, stddev, var

    ! Get the value of N
    write(*,'(A)') "Enter the number of elements in the array:"
    read(*,'(I)') N

    ! Get the elements of the array
    write(*,'(A)') "Enter the elements of the array:"
    do i = 1, N
        read(*,'(F)') arr(i)
        sum = sum + arr(i)
    end do

    ! Calculate the mean
    mean = sum / N

    ! Calculate the variance
    do i = 1, N
        var = var + (arr(i) - mean)**2
    end do
    var = var / N

    ! Calculate the standard deviation
    stddev = sqrt(var)

    ! Print the results
    write(*,'(A,F)') "Mean: ", mean
    write(*,'(A,F)') "Standard deviation: ", stddev
end program diziler

it gives error like this

C:\Users\Teknik\Desktop\6.odev.F95(8) : error 270 - Missing width count for 'I' descriptor
C:\Users\Teknik\Desktop\6.odev.F95(13) : error 270 - Missing width count for 'F' descriptor
C:\Users\Teknik\Desktop\6.odev.F95(30) : error 270 - Missing width count for 'F' descriptor
C:\Users\Teknik\Desktop\6.odev.F95(31) : error 270 - Missing width count for 'F' descriptor
C:\Users\Teknik\Desktop\6.odev.F95(3) : error 542 - N appears in the dimension of a variable, yet is not a dummy argument, a variable available through USE or CONTAINS association, a COMMON variable, a PARAMETER, or


来源: stackexchange

问:
Highest values among corresponding field in oracle
I have two supplier_type (Direct and Indirect) for one supply code. I want to produce a new column supplier_type based on supplier_Name for one supply_code like

Example:

If supply_Name is Apple,Dell,Hp,Lenovo then supply_type as Direct

If supply_Name is laptops,mouse,keyboard then indirect for the supplier_code 2023.

Here I want to get the highest value of supplier_type by counting how many supplier_type are Direct and indirect for each supplier_code.

Sample table:

```<code>S_CODE  S_NAME  S_TYPE
----------------------
2023.   APPLE.  DIRECT
2023.   DELL.   DIRECT
2023.   MOUSE.  INDIRECT
2023.   LENOVO. DIRECT
2022.   DELL.   DIRECT
2022.   LAPTOP. INDIRECT
2022.   MOUSE.  INDIRECT
</code>```

Here, we have supplier code 2023 and 2022

For supplier code 2023 we have 3 direct and 1 indirect, so we need to pass the value as Direct in supplier_type column

And for supplier code 2022 we have 1 direct and 2 indirect, so we need to pass the value as Indirect in supplier_type column.

```<code>select supplier_type
from supplier_table
where count_of_supplier in (select distinct max(count_of_supplier)
                            from supplier table
                            group by supplier_type)
order by supplier_code
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two supplier_type (Direct and Indirect) for one supply code. I want to produce a new column supplier_type based on supplier_Name for one supply_code like

Example:

If supply_Name is Apple,Dell,Hp,Lenovo then supply_type as Direct

If supply_Name is laptops,mouse,keyboard then indirect for the supplier_code 2023.

Here I want to get the highest value of supplier_type by counting how many supplier_type are Direct and indirect for each supplier_code.

Sample table:

S_CODE  S_NAME  S_TYPE
----------------------
2023.   APPLE.  DIRECT
2023.   DELL.   DIRECT
2023.   MOUSE.  INDIRECT
2023.   LENOVO. DIRECT
2022.   DELL.   DIRECT
2022.   LAPTOP. INDIRECT
2022.   MOUSE.  INDIRECT

Here, we have supplier code 2023 and 2022

For supplier code 2023 we have 3 direct and 1 indirect, so we need to pass the value as Direct in supplier_type column

And for supplier code 2022 we have 1 direct and 2 indirect, so we need to pass the value as Indirect in supplier_type column.

select supplier_type
from supplier_table
where count_of_supplier in (select distinct max(count_of_supplier)
                            from supplier table
                            group by supplier_type)
order by supplier_code


问:
Wordpress theme localization
Am working on a simple page using Wordpress. It's a simple web with mostly static content that is going to be updated rarely, let's say once per month.

The content will consist of cca 20 pages that are going to be edited by the site admin. No posts, no discussion forums or so.

I need to localize these pages to three langauges. My idea is to create three versions of each Page and that's it. Let's say index_en, index_de, index_es etc. So far so good.

But there is going to be a custom theme with generic header, footer and menu and all these will contain strings that needs to be translated. I intend to have language switcher in the header (probably small flag icons) and on language change I would navigate to relevant page eg. "index_de" for German. But how can I change the language for the theme itself - the strings in the header, footer and menu...

My supplier offers me three options

automated translation by Google Translate (not a good option)

tree installations of Wordpress - one for each language, not very comfortable from maintenanace point of view

plugins (TranslatePress, WPML, ...), always paid as recurring subscription. Not very good option from costs point of view.

I really can't believe there is no simple option for such a task that nearly everyone needs to resolve... Any ideas how to do that?

thanks

Jiri

Title: Wordpress theme localization


问:
WebSockets connection
I recently had WebSockets running on my laptop with XSockets. I then had to rebuild my laptop, installed just like before, and now WebSockets don't work.

I have Norton Internet Security installed just like before. I looked at all my acive ports, checked out my firewall rules, what have ya, and I'm dead in the water. When I try to connect to my server, it immediately closes.

I dont know what else to check. I even turned off firewall protection from norton, and still it doesn't work.

Any help on what else to check, I surely would appreciate it. I'm running Windows 7.

ContentLicense: CC BY-SA 3.0

Title: WebSockets connection


问:
Save new blobs files using azure durable functions Python
i have a proyect that will be conterized in docker, it consists on a DurableFunctionsHttpStart, a Orchestactor and a activity function, the activity function its web scraper that once the data has been downloaded will save a csv into the azure blob storage, once i tested my function i got the next error inside the Docker container:

HttpResponseError: This request is not authorized to perform this operation using this resource type.

i tried using the function biding with an out blob as below:

and tried using the python sdk as showen below:

this is the host.json of my activity function

the problem its since i use the durable function because in normal httptrigger i dont have any issue.


问:
How to merge HoloLens2 coordinate system with another coordinatesystem?
There is a coordinate origin, for example from a robot system in a corner of a room in the real world. From this, I get coordinates with the origin in the corner that I want to use for a hologram that I want to display on HoloLens2. However, the HoloLens has its own coordinate origin when an app is launched. For example, in the middle of the room when I'm standing there.
So I can't use the coordinates with the origin in the corner directly for the HoloLens because the coordinate origins of the systems are different.

Can I merge the coordinate origin of the HoloLens with the coordinate origin in the corner?
How can I use the coordinates with the coordinate origin in the corner for HoloLens so that the hologram is displayed in the correct position?
Are there any tools that implement this?

I am using MRTK 2.8, Unity 2020.3.4.
Thanks for your help


问:
jsPDF and html2canvas content when passing the limit of the first page and going to the second, ends up being cut
I have a problem when using html2canvas and jsPDF, I'm managing to move my content to another page, but my content ends up being cut and becoming visually ugly, how to solve this?

this is my code

```<code> getPDF() {
    this.isPrinting = true;

    setTimeout(() => {
      changeChartSvgFont(this.print, 'text', 'Proxima Nova');

      html2canvas(this.print.nativeElement, { scale: 2 }).then((canvas) => {
        var imgData = canvas.toDataURL('image/png');
        var imgWidth = 210;
        var pageHeight = 295;
        var imgHeight = (canvas.height * imgWidth) / canvas.width;
        var heightLeft = imgHeight;

        var doc = new jsPDF('p', 'mm', 'a4');
        var position = 0;

        doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight + 15);
        heightLeft -= pageHeight;

        while (heightLeft >= 0) {
          position = heightLeft - imgHeight;
          doc.addPage();
          doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight + 15);
          heightLeft -= pageHeight;
        }

        doc.save(`exemple.pdf`);
        this.isPrinting = false;

        return;
      });
    }, 1000);
  }
</code>```

this is how it's getting

enter image description here

Body:
I have a problem when using html2canvas and jsPDF, I'm managing to move my content to another page, but my content ends up being cut and becoming visually ugly, how to solve this?

this is my code

 getPDF() {
    this.isPrinting = true;

    setTimeout(() => {
      changeChartSvgFont(this.print, 'text', 'Proxima Nova');

      html2canvas(this.print.nativeElement, { scale: 2 }).then((canvas) => {
        var imgData = canvas.toDataURL('image/png');
        var imgWidth = 210;
        var pageHeight = 295;
        var imgHeight = (canvas.height * imgWidth) / canvas.width;
        var heightLeft = imgHeight;

        var doc = new jsPDF('p', 'mm', 'a4');
        var position = 0;

        doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight + 15);
        heightLeft -= pageHeight;

        while (heightLeft >= 0) {
          position = heightLeft - imgHeight;
          doc.addPage();
          doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight + 15);
          heightLeft -= pageHeight;
        }

        doc.save(`exemple.pdf`);
        this.isPrinting = false;

        return;
      });
    }, 1000);
  }

this is how it's getting

enter image description here


问:
Integrate Latex (Overleaf) and Rmarkdown
I'm writing my master's thesis in Overleaf, and I want to write my "Results" chapter in rmarkdown. I want to know how can I integrate these two. I know that I can include

```<code>output:
  pdf_document:
    keep_tex: yes
</code>```

in rmarkdown to get the Latex file and upload it in overleaf, but that is not a desirable integration. Does anyone know a better way?

Thanks!

Body:
I'm writing my master's thesis in Overleaf, and I want to write my "Results" chapter in rmarkdown. I want to know how can I integrate these two. I know that I can include

output:
  pdf_document:
    keep_tex: yes

in rmarkdown to get the Latex file and upload it in overleaf, but that is not a desirable integration. Does anyone know a better way?

Thanks!


问:
Stop sp from running rest statements when there is an error
We have some sps which contains rather complicated logics.

If something went wrong in a statement, the rest sql statements will continue. For example:

```<code>create procedure jerry
as
SELECT 1 AS TestColumn
INTO #TestTempTable

DECLARE @DS NVARCHAR(MAX) = 'SELECT * FROM #TestTempTable'
EXEC sp_EXECUTESQL @DS
SELECT 1/0
select 'aaa'
</code>```

The only way to stop select 'aaa' from running is to use try catch. But in the real sp, there are quite a lot statements. Is there an easy way to stop rest statements from running if something goes wrong?

Body:
We have some sps which contains rather complicated logics.

If something went wrong in a statement, the rest sql statements will continue. For example:

create procedure jerry
as
SELECT 1 AS TestColumn
INTO #TestTempTable

DECLARE @DS NVARCHAR(MAX) = 'SELECT * FROM #TestTempTable'
EXEC sp_EXECUTESQL @DS
SELECT 1/0
select 'aaa'

The only way to stop select 'aaa' from running is to use try catch. But in the real sp, there are quite a lot statements. Is there an easy way to stop rest statements from running if something goes wrong?


问:
How to split multiple entries in a string to multiple zip files
I have a large VMDK file that has to be broken down into smaller segments to send via website. I have the scripting down to where I split the VMDK into 2GB increments for a total of 30 files. I then put the files together in a string. My problem is taking the string and delimiting it into groups of four and sending them into multiple zip file (website has an 8GB transfer limit). I'm not sure if using and array would be an easier option. New at using Powershell so any advice is welcome.

This is the script I have so far.

```<code>function Split-File
{
    $inFile = "C:\Users\Justin\Desktop\Split_Test\disk1.vmdk"

    ([Long]$bufSize = 2000mb)
    $stream = [System.IO.File]::OpenRead($inFile)
    $chunkNum = 1
    $barr = New-Object byte[] $bufSize

    $fileinfo = [System.IO.FileInfo]$inFile
    $name = $fileinfo.Name
    $dir = $fileinfo.Directory

    while ($bytesRead = $stream.Read($barr, 0, [Long]$bufsize)) {
        $outFile = Join-Path $dir "$name.part$chunkNum"
        $ostream = [System.IO.File]::OpenWrite($outFile)
        $ostream.Write($barr, 0, $bytesRead)
        $ostream.Close()
        Write-Host "Wrote $outFile"
        $chunkNum += 1
    }
    $stream.Close()
}
Split-File
</code>```

I then put the output files into a string using.

```<code>$Split = Get-ChildItem C:\Users\Justin\Desktop\Split_Test | Where-Object {$_.Extension -ne ".ps1"}
</code>```

Body:
I have a large VMDK file that has to be broken down into smaller segments to send via website. I have the scripting down to where I split the VMDK into 2GB increments for a total of 30 files. I then put the files together in a string. My problem is taking the string and delimiting it into groups of four and sending them into multiple zip file (website has an 8GB transfer limit). I'm not sure if using and array would be an easier option. New at using Powershell so any advice is welcome.

This is the script I have so far.

function Split-File
{
    $inFile = "C:\Users\Justin\Desktop\Split_Test\disk1.vmdk"

    ([Long]$bufSize = 2000mb)
    $stream = [System.IO.File]::OpenRead($inFile)
    $chunkNum = 1
    $barr = New-Object byte[] $bufSize

    $fileinfo = [System.IO.FileInfo]$inFile
    $name = $fileinfo.Name
    $dir = $fileinfo.Directory

    while ($bytesRead = $stream.Read($barr, 0, [Long]$bufsize)) {
        $outFile = Join-Path $dir "$name.part$chunkNum"
        $ostream = [System.IO.File]::OpenWrite($outFile)
        $ostream.Write($barr, 0, $bytesRead)
        $ostream.Close()
        Write-Host "Wrote $outFile"
        $chunkNum += 1
    }
    $stream.Close()
}
Split-File

I then put the output files into a string using.

$Split = Get-ChildItem C:\Users\Justin\Desktop\Split_Test | Where-Object {$_.Extension -ne ".ps1"}


问:
Brace initialisation of vector of variant containing unique_ptr
Why does the following code compile when using std::array but not when using std::vector:

```<code>using varianttypes = std::variant<int, double, std::unique_ptr<double>>;
std::array<varianttypes, 4> a{1, 2.2, 3, 4.3}; // compiles fine
std::vector<varianttypes> a{1, 2.2, 3, 4.3}; // gives an error
</code>```

I get this error:

```<code>/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__memory/allocator_traits.h:298:9: error: no matching function for call to 'construct_at'
        _VSTD::construct_at(__p, _VSTD::forward<_Args>(__args)...);
        ^~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__config:858:15: note: expanded from macro '_VSTD'
#define _VSTD std::_LIBCPP_ABI_NAMESPACE
              ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/memory:750:18: note: in instantiation of function template specialization 'std::allocator_traits<std::allocator<std::variant<int, double, std::unique_ptr<double>>>>::construct<std::variant<int, double, std::unique_ptr<double>>, const std::variant<int, double, std::unique_ptr<double>> &, void, void>' requested here
        _Traits::construct(__a, _VSTD::__to_address(__begin2), *__begin1);
                 ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/vector:1099:12: note: in instantiation of function template specialization 'std::__construct_range_forward<std::allocator<std::variant<int, double, std::unique_ptr<double>>>, const std::variant<int, double, std::unique_ptr<double>> *, std::variant<int, double, std::unique_ptr<double>> *>' requested here
    _VSTD::__construct_range_forward(this->__alloc(), __first, __last, __tx.__pos_);
           ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/vector:1357:9: note: in instantiation of function template specialization 'std::vector<std::variant<int, double, std::unique_ptr<double>>>::__construct_at_end<const std::variant<int, double, std::unique_ptr<double>> *>' requested here
        __construct_at_end(__il.begin(), __il.end(), __il.size());
        ^
variantstuff.cpp:82:29: note: in instantiation of member function 'std::vector<std::variant<int, double, std::unique_ptr<double>>>::vector' requested here
  std::vector<varianttypes> a{1, 2.2, 3, 4.3};
                            ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__memory/construct_at.h:35:16: note: candidate template ignored: substitution failure [with _Tp = std::variant<int, double, std::unique_ptr<double>>, _Args = <const std::variant<int, double, std::unique_ptr<double>> &>]: call to implicitly-deleted copy constructor of 'std::variant<int, double, std::unique_ptr<double>>'
constexpr _Tp* construct_at(_Tp* __location, _Args&& ...__args) {
               ^
1 error generated.
make: *** [variantstuff.o] Error 1
</code>```

Body:
Why does the following code compile when using std::array but not when using std::vector:

using varianttypes = std::variant<int, double, std::unique_ptr<double>>;
std::array<varianttypes, 4> a{1, 2.2, 3, 4.3}; // compiles fine
std::vector<varianttypes> a{1, 2.2, 3, 4.3}; // gives an error

I get this error:

/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__memory/allocator_traits.h:298:9: error: no matching function for call to 'construct_at'
        _VSTD::construct_at(__p, _VSTD::forward<_Args>(__args)...);
        ^~~~~~~~~~~~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__config:858:15: note: expanded from macro '_VSTD'
#define _VSTD std::_LIBCPP_ABI_NAMESPACE
              ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/memory:750:18: note: in instantiation of function template specialization 'std::allocator_traits<std::allocator<std::variant<int, double, std::unique_ptr<double>>>>::construct<std::variant<int, double, std::unique_ptr<double>>, const std::variant<int, double, std::unique_ptr<double>> &, void, void>' requested here
        _Traits::construct(__a, _VSTD::__to_address(__begin2), *__begin1);
                 ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/vector:1099:12: note: in instantiation of function template specialization 'std::__construct_range_forward<std::allocator<std::variant<int, double, std::unique_ptr<double>>>, const std::variant<int, double, std::unique_ptr<double>> *, std::variant<int, double, std::unique_ptr<double>> *>' requested here
    _VSTD::__construct_range_forward(this->__alloc(), __first, __last, __tx.__pos_);
           ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/vector:1357:9: note: in instantiation of function template specialization 'std::vector<std::variant<int, double, std::unique_ptr<double>>>::__construct_at_end<const std::variant<int, double, std::unique_ptr<double>> *>' requested here
        __construct_at_end(__il.begin(), __il.end(), __il.size());
        ^
variantstuff.cpp:82:29: note: in instantiation of member function 'std::vector<std::variant<int, double, std::unique_ptr<double>>>::vector' requested here
  std::vector<varianttypes> a{1, 2.2, 3, 4.3};
                            ^
/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include/c++/v1/__memory/construct_at.h:35:16: note: candidate template ignored: substitution failure [with _Tp = std::variant<int, double, std::unique_ptr<double>>, _Args = <const std::variant<int, double, std::unique_ptr<double>> &>]: call to implicitly-deleted copy constructor of 'std::variant<int, double, std::unique_ptr<double>>'
constexpr _Tp* construct_at(_Tp* __location, _Args&& ...__args) {
               ^
1 error generated.
make: *** [variantstuff.o] Error 1


问:
Wordpress inserting styles
Has anyone had any experience and possibly know what is causing wordpress to add extra css to our pages.

Examples of the css being inserted below:

```<code><style>div.wp-container-1>div>p:nth-of-type(2){display: none}</style>
<style>div.wp-container-16{display: none}</style>
<style>div.accordion>div:nth-of-type(7){display: none}</style>
</code>```

I've gone and uninstalled all the plugins, tried incognito mode, cleared my cache and it hasn't helped.

Title: Wordpress inserting styles

Body:
Has anyone had any experience and possibly know what is causing wordpress to add extra css to our pages.

Examples of the css being inserted below:

I've gone and uninstalled all the plugins, tried incognito mode, cleared my cache and it hasn't helped.


问:
TypeError: Cannot Read Property of Undefined Even Though I Defined It
I'm a beginner to JavaScript. I've looked through a few questions on here regarding "TypeError: ... undefined even though the property is defined" but their examples are either too dense for me to grasp or they realize they've incorrectly assigned something downstream. Here I think my example is quite simple, and I don't think I've incorrectly assigned anything.

I've defined position in my class MoveableObjects and when I call player = new MoveableObject(position, other params ...) I don't get any errors.

When I change this to player = new Sprite(position, other params ...) where Sprite extends MoveableObjects and then try to call a function inside Sprite it tells me position.x is undefined. I put console.log(player) immediately after the declaration and it does in fact show position as undefined, but I don't understand why it does since I've clearly defined it.

Here is the constructor of MoveableObjects

```<code>class MoveableObject {

    constructor({ colorRGB, width, height, position, velocity}) {
        this.width = width;
        this.height = height;
        this.position = position;
        this.velocity = velocity;
        this.colorRGB = colorRGB;

        // If the side of the object is touching or beyond the side of the canvas it is flagged as bounded.
        this.inUpLimit = false;
        this.inDownLimit = false;
        this.inLeftLimit = false;
        this.inRightLimit = false;

        // Translate the velocity into directional words
        this.movingLeft = false;
        this.movingRight = false;
        this.movingUp = false;
        this.movingDown = false;
    }
</code>```

Here is the constructor of Sprite and the draw() function it uses.

```<code>// Sprite represents moveable objects with an animated image.
class Sprite extends MoveableObject {

    constructor({ imageSrc, numRows = 1, numCols = 1, spacing = 0, margin = 0, animationSpeed = 10, position, velocity}) {

        super(position, velocity)

        this.image = new Image()                             // Image can be a single image or a spritesheet.
        this.image.src = imageSrc
        this.numRows = numRows                               // # animation sequences in the spritesheet
        this.numCols = numCols                               // # frames in an animation sequence
        this.spacing = spacing                               // # pixels between each frame
        this.margin = margin                                 // # pixels between image border and sprite border. Vertical and horizontal margins should be equal.
        this.animation = new Object()
        this.animation.speed = animationSpeed                // # times draw function is called before the next frame in the animation sequence is called.
        this.animation.counter = 0                           // # times the draw function has been called
        this.animation.enabled = false                       // Whether or not the animation sequence is currently running
        this.animation.row = 1;                              // The row of the current frame being drawn
        this.animation.col = 1;                              // The column of the current frame being drawn
        this.animation.firstRow = 1;                         // The row of the frame to initialize the animation loop on
        this.animation.firstCol = 1;                         // The column of the frame to initialize the animation loop on
        this.animation.lastRow = 1;                          // The row of the frame to restart the animation loop on
        this.animation.lastCol = 1;                          // The column of the frame to restart the animation loop on

        this.frame = new Object();
        this.frame.width = 0;                               // Init image.onload
        this.frame.height = 0;                              // Init image.onload
        this.image.onload = () => {                                 // Calculates width and height of animation frame based on numRows, numColumns, spacing, and margin

            let imageWidth = this.image.width;
            let spriteSheetWidth = imageWidth - (2 * this.margin);
            let widthNoSpacing = spriteSheetWidth - this.spacing * (this.numCols - 1);
            let frameWidth = widthNoSpacing / this.numCols;

            let imageHeight = this.image.height;
            let spriteSheetHeight = imageHeight - (2 * this.margin);
            let heightNoSpacing = spriteSheetHeight - this.spacing * (this.numRows - 1);
            let frameHeight = heightNoSpacing / numRows;

            this.frame.width = frameWidth;
            this.frame.height = frameHeight;
        }

    }

    draw() {

        // Draw the frame at the current row and column.
        context.drawImage(
            this.image,                             // the entire image being loaded
            this.animation.col * this.frame.width,  // sx, x coordinate to begin crop
            this.animation.row * this.frame.height, // sy, y coordinate to begin crop
            this.frame.width,                       // swidth, width of cropped image
            this.frame.height,                      // sheight, height of cropped image
            this.position.x,                        // x coordinate where to place image on canvas
            this.position.y,                        // y coordinate where to place image on canvas
            this.frame.width,                       // the width to stretch/shrink it to
            this.frame.height                       // the height to stretch/shrink it to
        )
</code>```

Here I create a new MoveableObject with position defined and then console.log() it. It shows position to be what I set it to. I copy/paste that declaration and change "new MoveableObject" to "new Sprite" (with a new variable name of course) and print that, and it shows position is undefined:

```<code>// Initializers for main()
const gravity = 0.8;
const player = new Sprite({
    imageSrc: './lib/img/template.png',
    numRows: 21,
    numCols: 4,
    spacing: 0,
    margin: 0,
    position: {
        x: 0,
        y: 0
    },
    velocity: {
        x: 0,
        y: 0
    }
})
console.log(player)
const enemy = new MoveableObject({
    colorRGB: 'blue',
    width: 50,
    height: 150,
    position: {
        x: 150,
        y: 50
    },
    velocity: {
        x: 0,
        y: 0
    }
})
console.log(enemy)
const moveableObjects = [player, enemy];

// The main function of the script updates the game state every frame.
function main() {

    // When the game starts the canvas, then player, then enemy are rendered.
    context.fillStyle = 'black';
    context.fillRect(0, 0, canvas.width, canvas.height);
    player.draw();
    enemy.draw();
</code>```

The error is raised on player.draw() and reads "Uncaught TypeError: Cannot read properties of undefined (reading 'x')"

Does anyone understand why this is the case? It seems to me like the error is maybe produced by not properly extending my class or using super() incorrectly to pass attributes, but I haven't found an example that proves that.

Body:
I'm a beginner to JavaScript. I've looked through a few questions on here regarding "TypeError: ... undefined even though the property is defined" but their examples are either too dense for me to grasp or they realize they've incorrectly assigned something downstream. Here I think my example is quite simple, and I don't think I've incorrectly assigned anything.

I've defined position in my class MoveableObjects and when I call player = new MoveableObject(position, other params ...) I don't get any errors.

When I change this to player = new Sprite(position, other params ...) where Sprite extends MoveableObjects and then try to call a function inside Sprite it tells me position.x is undefined. I put console.log(player) immediately after the declaration and it does in fact show position as undefined, but I don't understand why it does since I've clearly defined it.

Here is the constructor of MoveableObjects

class MoveableObject {

    constructor({ colorRGB, width, height, position, velocity}) {
        this.width = width;
        this.height = height;
        this.position = position;
        this.velocity = velocity;
        this.colorRGB = colorRGB;

        // If the side of the object is touching or beyond the side of the canvas it is flagged as bounded.
        this.inUpLimit = false;
        this.inDownLimit = false;
        this.inLeftLimit = false;
        this.inRightLimit = false;

        // Translate the velocity into directional words
        this.movingLeft = false;
        this.movingRight = false;
        this.movingUp = false;
        this.movingDown = false;
    }

Here is the constructor of Sprite and the draw() function it uses.

// Sprite represents moveable objects with an animated image.
class Sprite extends MoveableObject {

    constructor({ imageSrc, numRows = 1, numCols = 1, spacing = 0, margin = 0, animationSpeed = 10, position, velocity}) {

        super(position, velocity)

        this.image = new Image()                             // Image can be a single image or a spritesheet.
        this.image.src = imageSrc
        this.numRows = numRows                               // # animation sequences in the spritesheet
        this.numCols = numCols                               // # frames in an animation sequence
        this.spacing = spacing                               // # pixels between each frame
        this.margin = margin                                 // # pixels between image border and sprite border. Vertical and horizontal margins should be equal.
        this.animation = new Object()
        this.animation.speed = animationSpeed                // # times draw function is called before the next frame in the animation sequence is called.
        this.animation.counter = 0                           // # times the draw function has been called
        this.animation.enabled = false                       // Whether or not the animation sequence is currently running
        this.animation.row = 1;                              // The row of the current frame being drawn
        this.animation.col = 1;                              // The column of the current frame being drawn
        this.animation.firstRow = 1;                         // The row of the frame to initialize the animation loop on
        this.animation.firstCol = 1;                         // The column of the frame to initialize the animation loop on
        this.animation.lastRow = 1;                          // The row of the frame to restart the animation loop on
        this.animation.lastCol = 1;                          // The column of the frame to restart the animation loop on

        this.frame = new Object();
        this.frame.width = 0;                               // Init image.onload
        this.frame.height = 0;                              // Init image.onload
        this.image.onload = () => {                                 // Calculates width and height of animation frame based on numRows, numColumns, spacing, and margin

            let imageWidth = this.image.width;
            let spriteSheetWidth = imageWidth - (2 * this.margin);
            let widthNoSpacing = spriteSheetWidth - this.spacing * (this.numCols - 1);
            let frameWidth = widthNoSpacing / this.numCols;

            let imageHeight = this.image.height;
            let spriteSheetHeight = imageHeight - (2 * this.margin);
            let heightNoSpacing = spriteSheetHeight - this.spacing * (this.numRows - 1);
            let frameHeight = heightNoSpacing / numRows;

            this.frame.width = frameWidth;
            this.frame.height = frameHeight;
        }

    }

    draw() {

        // Draw the frame at the current row and column.
        context.drawImage(
            this.image,                             // the entire image being loaded
            this.animation.col * this.frame.width,  // sx, x coordinate to begin crop
            this.animation.row * this.frame.height, // sy, y coordinate to begin crop
            this.frame.width,                       // swidth, width of cropped image
            this.frame.height,                      // sheight, height of cropped image
            this.position.x,                        // x coordinate where to place image on canvas
            this.position.y,                        // y coordinate where to place image on canvas
            this.frame.width,                       // the width to stretch/shrink it to
            this.frame.height                       // the height to stretch/shrink it to
        )

Here I create a new MoveableObject with position defined and then console.log() it. It shows position to be what I set it to. I copy/paste that declaration and change "new MoveableObject" to "new Sprite" (with a new variable name of course) and print that, and it shows position is undefined:

// Initializers for main()
const gravity = 0.8;
const player = new Sprite({
    imageSrc: './lib/img/template.png',
    numRows: 21,
    numCols: 4,
    spacing: 0,
    margin: 0,
    position: {
        x: 0,
        y: 0
    },
    velocity: {
        x: 0,
        y: 0
    }
})
console.log(player)
const enemy = new MoveableObject({
    colorRGB: 'blue',
    width: 50,
    height: 150,
    position: {
        x: 150,
        y: 50
    },
    velocity: {
        x: 0,
        y: 0
    }
})
console.log(enemy)
const moveableObjects = [player, enemy];

// The main function of the script updates the game state every frame.
function main() {

    // When the game starts the canvas, then player, then enemy are rendered.
    context.fillStyle = 'black';
    context.fillRect(0, 0, canvas.width, canvas.height);
    player.draw();
    enemy.draw();

The error is raised on player.draw() and reads "Uncaught TypeError: Cannot read properties of undefined (reading 'x')"

Does anyone understand why this is the case? It seems to me like the error is maybe produced by not properly extending my class or using super() incorrectly to pass attributes, but I haven't found an example that proves that.


问:
Web Serial API crashes Zebra DS9208 on initial connection
I am attempting to use a Zebra DS9208 scanner to capture barcode data into a web page. For some reason, when I first select the serial port and connect to the scanner, the very first scan causes the barcode reader to crash (it locks into read mode, refuses to read additional scans, then disconnects from the computer and reboots itself). When I establish the connection a second time, the scanner continuously reads scans without issues. Anyone able to spot anything in my code that could cause this?

Connect Script:

```<code>async function connect() {
     // - Request a port and open a connection.
     port = await navigator.serial.requestPort();

     // - Wait for the port to open.
     await port.open({ baudRate: 9600 });

     // Send a bunch of Bell characters so we can hear that the scanner understands us.
     await quadBeep();

     // Read the stream let textDecoder = new TextDecoderStream();
     inputDone = port.readable.pipeTo(textDecoder.writable);
     reader = textDecoder.readable.getReader();

readScans();

}
</code>```

Beep Script (used to make the scanner beep by sending a BELL character)

```<code>function quadBeep() {
     console.log('Quad Beep Requested');
     //Write to output stream
     const writer = port.writable.getWriter();
     const data = new Uint8Array([07, 07, 07, 07]);
     writer.write(data);
     //allow the serial port to be closed later
     writer.releaseLock();
     return;
}
</code>```

Read Loop to source data from the scanner:
`async function readScans() {
//Listen to data coming from the serial device

```<code>async function readScans() {
     while (true) {
          try {
            const { value, done } = await reader.read();

            await saveScan(value); //process the scan

            console.log('readScans Barcode: ' + value);
            document.getElementById('scan').innerHTML += value;

            if (done) {
              //Allow the serial port to be closed later.
              console.log('readScans done value: ' + done);
              reader.releaseLock();
              break;
            }

          } catch(error) {
            console.log('readScans Error: ' + error);
            break;
          }
     }
}
</code>```

Save Function, to write the data (eventually will submit the barcode via AJAX)

```<code>function saveScan(barcode) {
     var session = document.getElementById('sessionID').getAttribute('data-value');
     if (barcode == previousBarcode) {
          //duplicate scan.
          console.log('saveScan Duplicate');
          return;
     } else {
          //Submit the scan
          previousBarcode = barcode; //store the barcode so it doesn't get rescanned
          console.log('saveScan Previous set to: ' + barcode);
          //future AJAX FUNCTION GOES HERE
          return;
     }
}
</code>```

Body:
I am attempting to use a Zebra DS9208 scanner to capture barcode data into a web page. For some reason, when I first select the serial port and connect to the scanner, the very first scan causes the barcode reader to crash (it locks into read mode, refuses to read additional scans, then disconnects from the computer and reboots itself). When I establish the connection a second time, the scanner continuously reads scans without issues. Anyone able to spot anything in my code that could cause this?

Connect Script:

async function connect() {
     // - Request a port and open a connection.
     port = await navigator.serial.requestPort();

     // - Wait for the port to open.
     await port.open({ baudRate: 9600 });

     // Send a bunch of Bell characters so we can hear that the scanner understands us.
     await quadBeep();

     // Read the stream let textDecoder = new TextDecoderStream();
     inputDone = port.readable.pipeTo(textDecoder.writable);
     reader = textDecoder.readable.getReader();

readScans();

}

Beep Script (used to make the scanner beep by sending a BELL character)

function quadBeep() {
     console.log('Quad Beep Requested');
     //Write to output stream
     const writer = port.writable.getWriter();
     const data = new Uint8Array([07, 07, 07, 07]);
     writer.write(data);
     //allow the serial port to be closed later
     writer.releaseLock();
     return;
}

Read Loop to source data from the scanner:
`async function readScans() {
//Listen to data coming from the serial device

async function readScans() {
     while (true) {
          try {
            const { value, done } = await reader.read();

            await saveScan(value); //process the scan

            console.log('readScans Barcode: ' + value);
            document.getElementById('scan').innerHTML += value;

            if (done) {
              //Allow the serial port to be closed later.
              console.log('readScans done value: ' + done);
              reader.releaseLock();
              break;
            }

          } catch(error) {
            console.log('readScans Error: ' + error);
            break;
          }
     }
}

Save Function, to write the data (eventually will submit the barcode via AJAX)

function saveScan(barcode) {
     var session = document.getElementById('sessionID').getAttribute('data-value');
     if (barcode == previousBarcode) {
          //duplicate scan.
          console.log('saveScan Duplicate');
          return;
     } else {
          //Submit the scan
          previousBarcode = barcode; //store the barcode so it doesn't get rescanned
          console.log('saveScan Previous set to: ' + barcode);
          //future AJAX FUNCTION GOES HERE
          return;
     }
}


问:
How to set .jar entry point class that is located in other package
I'm using Windows 10. Currently trying to figure out how to work with java files from the console. Bumped into a problem - I have 3 .java files and .\bin directory where all my .class files are stored. I want to create a .jar file, put all .class files in it and make .\bin\Test1.class file an entry point for this archive

So I tried this command that I found on Oracle docs

```<code>jar cfe app.jar bin/Test1 bin/*.class
</code>```

It worked and I got everything I need in this archive but when I try to run the application by

```<code>java -jar app.jar
</code>```

the error appears and tells that It could not find the main class
Error text

So I tried using different delimiters in command and manifest file, added Class-Path: attribute in manifest (however not sure what exactly should be in it), tried running from administrator. Nothing works

Body:
I'm using Windows 10. Currently trying to figure out how to work with java files from the console. Bumped into a problem - I have 3 .java files and .\bin directory where all my .class files are stored. I want to create a .jar file, put all .class files in it and make .\bin\Test1.class file an entry point for this archive

So I tried this command that I found on Oracle docs

jar cfe app.jar bin/Test1 bin/*.class

It worked and I got everything I need in this archive but when I try to run the application by

java -jar app.jar

the error appears and tells that It could not find the main class
Error text

So I tried using different delimiters in command and manifest file, added Class-Path: attribute in manifest (however not sure what exactly should be in it), tried running from administrator. Nothing works


问:
Tkinter window on each display
I've got a python tkinter gui on ubuntu that is working just fine, and I'd like to make it so that the gui duplicates itself for each display connected when the python script is run.

I've looked into messing around with the geometry property of the window, like modifying the x and y coordinates and creating a window at specific coords, but I can't figure out how to get coordinates for each individual display to make the windows open at.

Title: Tkinter window on each display


问:
How the max_feature hyperparameter is used in a Random Forest?
I am working with a python and I created a random forest model that looks like this

```<code>clf = RFC(n_estimators=100, random_state=0, max_depth=7, max_features = 2)
</code>```

As you can see my max_features is set to 2. I have one doubt about how this works. Does this means that for the creation of one individual decision tree in my random forest the model will look for two random features to create the decision tree or does it means that every time a new node is created within a decision tree the model randomly selects 2 features and then it only uses the one that better reduces entropy/impurity?

to put it mode simply, imagine that I have feature1, feature2, ......, feature10.

```<code>max_features = 2

randomly selected features to create the root = feature3 and feature7

(sample decision tree)

   feature3 <= 5.35 (sample = 200)
               /  \
              /    \
             /      \
feature3 <=3.35     feature7 <=6.05
(sample = 80)            (sample = 120)

etc...

and it continues using feature3 and feature7 in
the best way until reaching purity or until reaching
max_depth

</code>```

The second option (the one that I thought until now was the correct one).

```<code>max_features = 2

randomly selected features to create the root = feature3 and feature7

(sample decision tree)
(the model select feature3 because is the one that better reduces entropy/impurity)

   feature3 <= 5.35 (sample = 200)
               /  \
              /    \
             / ***  \

feature5 <=3.35     feature2 <=6.05
(sample = 80)            (sample = 120)

***now, for the left node, it randomly extracts 2 features
(let's say feature1 and feature5) and uses the one that better
reduces entropy (feature5), and for the right node, it shuffles
the features again and extracts two new features (let's say
feature2 and feature3) and selects the one that better reduces
entropy (feature2)

</code>```

which is correct? It shuffles two features at the being and keeps using them until it is finished or it selects a feature each and every time a node is created?

Thanks.

Body:
I am working with a python and I created a random forest model that looks like this

clf = RFC(n_estimators=100, random_state=0, max_depth=7, max_features = 2)

As you can see my max_features is set to 2. I have one doubt about how this works. Does this means that for the creation of one individual decision tree in my random forest the model will look for two random features to create the decision tree or does it means that every time a new node is created within a decision tree the model randomly selects 2 features and then it only uses the one that better reduces entropy/impurity?

to put it mode simply, imagine that I have feature1, feature2, ......, feature10.

max_features = 2

randomly selected features to create the root = feature3 and feature7

(sample decision tree)

   feature3 <= 5.35 (sample = 200)
               /  \
              /    \
             /      \
feature3 <=3.35     feature7 <=6.05
(sample = 80)            (sample = 120)

etc...

and it continues using feature3 and feature7 in
the best way until reaching purity or until reaching
max_depth

The second option (the one that I thought until now was the correct one).

max_features = 2

randomly selected features to create the root = feature3 and feature7

(sample decision tree)
(the model select feature3 because is the one that better reduces entropy/impurity)

   feature3 <= 5.35 (sample = 200)
               /  \
              /    \
             / ***  \

feature5 <=3.35     feature2 <=6.05
(sample = 80)            (sample = 120)

***now, for the left node, it randomly extracts 2 features
(let's say feature1 and feature5) and uses the one that better
reduces entropy (feature5), and for the right node, it shuffles
the features again and extracts two new features (let's say
feature2 and feature3) and selects the one that better reduces
entropy (feature2)

which is correct? It shuffles two features at the being and keeps using them until it is finished or it selects a feature each and every time a node is created?

Thanks.


问:
not-able-to-open-AWS quicksight-after-migration-from-gsuite-to-office-365
I recently migrated my email mailbox and mangement from GSuite to Microsoft office 365. After this I am getting below error while opening quicksight from my AWS account.

The AWS principal tag corresponding to “PrincipalTag:Email” in your SAML assertion or OIDC token is either an invalid email or not present. Please reach out to your QuickSight account’s admin to ensure that the email address for this AWS principal tag is correct.

Please let me know if you any solution or document to resolve this.

I checked many AWS SSO document but none are helping. I am using cognito as IDP.


问:
Multiple aspect ratio adding single video element?
When i started to create the webrtc using videocall app,and i set constraint video object aspectratio at responsive screen orientation purpose

```<code>    Constrain = video{
    aspectratio :Window.width*window.pixelratio/window.height*window.pixelratio
}
</code>```

This ratio is used for capture the streamed video at responsively in portrait mode.

But i could not modify the UI layout design responsively

I want like this

How to dynamically add the multiple aspect ratio  in single video element

Body:
When i started to create the webrtc using videocall app,and i set constraint video object aspectratio at responsive screen orientation purpose

    Constrain = video{
    aspectratio :Window.width*window.pixelratio/window.height*window.pixelratio
}

This ratio is used for capture the streamed video at responsively in portrait mode.

But i could not modify the UI layout design responsively

I want like this

How to dynamically add the multiple aspect ratio  in single video element


问:
Tensor dimension mismatch when neural network output changed from dense-linear type to dense-1-hot type
I have a deep neural-network in tensorflow that trains fine with a 5-unit dense output layer with linear activation (data labels are linear scaled values similar to linear regression).  When I change the output label encoding to 1-hot and the output layer to 5 individual, 25-unit dense 'heads' tensorflow will not train (ie .fit) and complains about the tensor shape being incompatible.  It seems like a straight forward issue but the data label shape looks fine to me.

```<code>ValueError: Shapes (128, 1, 25) and (128, 128, 25) are incompatible
</code>```

Details below:

Model's output layer details:

Linear dense output model:

```<code>X_in = Input(batch_input_shape=(batch_size=128, 128, 14), name='input')
... many layers...
yhat = Dense(5, activation='linear', name='Lin_classify')(X)
model = Model(inputs=X_in, outputs=[yhat])
model.compile(loss='mse', optimizer=Adam(learning_rate=model_params['learn_rate']), metrics=['accuracy'])
</code>```

```<code>model.summary()
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
FC_1 (TimeDistributed)          (128, 128, 128)      32896       BDLSTM_3[0][0]
__________________________________________________________________________________________________
Lin_classify (Dense)            (128, 128, 5)        645         FC_1[0][0]
==================================================================================================
</code>```

1-hot encoded model:

Changed output layer to multi-head.

The output layer will pick 5 objects that can each be 1 of 25 classes

```<code>X_in = Input(batch_input_shape=(batch_size=128, 128, 14), name='input')
... many layers...
yhat1 = Dense(25, activation='softmax', name='y_1hot_1')(X)
yhat2 = Dense(25, activation='softmax', name='y_1hot_2')(X)
yhat3 = Dense(25, activation='softmax', name='y_1hot_3')(X)
yhat4 = Dense(25, activation='softmax', name='y_1hot_4')(X)
yhat5 = Dense(25, activation='softmax', name='y_1hot_5')(X)
model = Model(inputs=X_in, outputs=[yhat1, yhat2, yhat3, yhat4, yhat5])
model.compile(loss={'y_1hot_1':loss, 'y_1hot_2':loss, 'y_1hot_3':loss, 'y_1hot_4':loss, 'y_1hot_5':loss},
              optimizer=Adam(learning_rate=model_params['learn_rate']),
              metrics={'y_1hot_1':metric, 'y_1hot_2':metric,'y_1hot_3':metric, 'y_1hot_4':metric, 'y_1hot_5':metric})
</code>```

```<code>model.summary()
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
FC_1 (TimeDistributed)          (128, 128, 128)      32896       BDLSTM_3[0][0]
__________________________________________________________________________________________________
y_1hot_1 (Dense)                (128, 128, 25)       3225        FC_1[0][0]
__________________________________________________________________________________________________
y_1hot_2 (Dense)                (128, 128, 25)       3225        FC_1[0][0]
__________________________________________________________________________________________________
y_1hot_3 (Dense)                (128, 128, 25)       3225        FC_1[0][0]
__________________________________________________________________________________________________
y_1hot_4 (Dense)                (128, 128, 25)       3225        FC_1[0][0]
__________________________________________________________________________________________________
y_1hot_5 (Dense)                (128, 128, 25)       3225        FC_1[0][0]
==================================================================================================
</code>```

Both varieties of models compile as expected.  Note that the output shapes of both models are similar (128, 128, x) except that the 1-hot model has 5 output heads.

Data:

X_train dims: (num_samples, window_length, num_features)

Linear model: X_train.shape = (3840, 128, 14); Y_train.shape = (3840, 1, 5)

1-hot model:  X_train.shape = (3840, 128, 14); Y_train[0:5].shape = (3840, 1, 25)

Linear model:

```<code>print(model.inputs)
>[<KerasTensor: shape=(128, 128, 14) dtype=float32 (created by layer 'input')>]
print(model.outputs)
>[<KerasTensor: shape=(128, 128, 5) dtype=float32 (created by layer 'Lin_classify')>]
</code>```

Note: label shape: (m, 1, 5) Output shape: (128, 128, 5) This trains fine

1-hot model:

```<code>print(model.inputs)
>[<KerasTensor: shape=(128, 128, 14) dtype=float32 (created by layer 'input')>]
print(model.outputs)
>[<KerasTensor: shape=(128, 128, 25) dtype=float32 (created by layer 'y_1hot_1')>,
 <KerasTensor: shape=(128, 128, 25) dtype=float32 (created by layer 'y_1hot_2')>,
 <KerasTensor: shape=(128, 128, 25) dtype=float32 (created by layer 'y_1hot_3')>,
 <KerasTensor: shape=(128, 128, 25) dtype=float32 (created by layer 'y_1hot_4')>,
 <KerasTensor: shape=(128, 128, 25) dtype=float32 (created by layer 'y_1hot_5')>]
</code>```

Note: label shape: (m, 1, 25) Output shape: (128, 128, 25) This fails with mismatch error

Training is the same for both models and occurs 1 epoch at a time in stateful mode (stateful applies to hidden lstm layers, not the output layer):

```<code>for i in range(n_epochs):
    ehist = model.fit(x=X_train, y=Y_train, batch_size=128, epochs=1,
                        shuffle=False, verbose=2)
    model.reset_states()
</code>```

The model receives batches of 128 examples of 128x14 input data and outputs 128, 1x5 predictions in the case of the linear model.  And outputs 5 individual 128, 1x25 predictions in the case of the 1-hot model.

Question:

Why does training the 1-hot model immediately fail with the following error?

```<code>ValueError: Shapes (128, 1, 25) and (128, 128, 25) are incompatible
</code>```

(the linear model does not complain and the main difference between model outputs is the 3rd dimension; ie 5 -> 25).

Any help with this would be greatly appreciated.

Here is the full error message:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[23], line 7
      6 for i in range(n_epochs):
----> 7     ehist = model.fit(x=X_train, y=Y_train, batch_size=batch_sz, epochs=1,
      8                         shuffle=False, verbose=2)
      9     model.reset_states()

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\training.py:1184, in Model.fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1177 with tf.profiler.experimental.Trace(
   1178     'train',
   1179     epoch_num=epoch,
   1180     step_num=step,
   1181     batch_size=batch_size,
   1182     _r=1):
   1183   callbacks.on_train_batch_begin(step)
-> 1184   tmp_logs = self.train_function(iterator)
   1185   if data_handler.should_sync:
   1186     context.async_wait()

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\eager\def_function.py:885, in Function.__call__(self, *args, **kwds)
    882 compiler = "xla" if self._jit_compile else "nonXla"
    884 with OptionalXlaContext(self._jit_compile):
--> 885   result = self._call(*args, **kwds)
    887 new_tracing_count = self.experimental_get_tracing_count()
    888 without_tracing = (tracing_count == new_tracing_count)

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\eager\def_function.py:933, in Function._call(self, *args, **kwds)
    930 try:
    931   # This is the first call of __call__, so we have to initialize.
    932   initializers = []
--> 933   self._initialize(args, kwds, add_initializers_to=initializers)
    934 finally:
    935   # At this point we know that the initialization is complete (or less
    936   # interestingly an exception was raised) so we no longer need a lock.
    937   self._lock.release()

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\eager\def_function.py:759, in Function._initialize(self, args, kwds, add_initializers_to)
    756 self._lifted_initializer_graph = lifted_initializer_graph
    757 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)
    758 self._concrete_stateful_fn = (
--> 759     self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
    760         *args, **kwds))
    762 def invalid_creator_scope(*unused_args, **unused_kwds):
    763   """Disables variable creation."""

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\eager\function.py:3066, in Function._get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   3064   args, kwargs = None, None
   3065 with self._lock:
-> 3066   graph_function, _ = self._maybe_define_function(args, kwargs)
   3067 return graph_function

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\eager\function.py:3463, in Function._maybe_define_function(self, args, kwargs)
   3459   return self._define_function_with_shape_relaxation(
   3460       args, kwargs, flat_args, filtered_flat_args, cache_key_context)
   3462 self._function_cache.missed.add(call_context_key)
-> 3463 graph_function = self._create_graph_function(args, kwargs)
   3464 self._function_cache.primary[cache_key] = graph_function
   3466 return graph_function, filtered_flat_args

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\eager\function.py:3298, in Function._create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   3293 missing_arg_names = [
   3294     "%s_%d" % (arg, i) for i, arg in enumerate(missing_arg_names)
   3295 ]
   3296 arg_names = base_arg_names + missing_arg_names
   3297 graph_function = ConcreteFunction(
-> 3298     func_graph_module.func_graph_from_py_func(
   3299         self._name,
   3300         self._python_function,
   3301         args,
   3302         kwargs,
   3303         self.input_signature,
   3304         autograph=self._autograph,
   3305         autograph_options=self._autograph_options,
   3306         arg_names=arg_names,
   3307         override_flat_arg_shapes=override_flat_arg_shapes,
   3308         capture_by_value=self._capture_by_value),
   3309     self._function_attributes,
   3310     function_spec=self.function_spec,
   3311     # Tell the ConcreteFunction to clean up its graph once it goes out of
   3312     # scope. This is not the default behavior since it gets used in some
   3313     # places (like Keras) where the FuncGraph lives longer than the
   3314     # ConcreteFunction.
   3315     shared_func_graph=False)
   3316 return graph_function

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\framework\func_graph.py:1007, in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes, acd_record_initial_resource_uses)
   1004 else:
   1005   _, original_func = tf_decorator.unwrap(python_func)
-> 1007 func_outputs = python_func(*func_args, **func_kwargs)
   1009 # invariant: `func_outputs` contains only Tensors, CompositeTensors,
   1010 # TensorArrays and `None`s.
   1011 func_outputs = nest.map_structure(convert, func_outputs,
   1012                                   expand_composites=True)

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\eager\def_function.py:668, in Function._defun_with_scope.<locals>.wrapped_fn(*args, **kwds)
    664 with default_graph._variable_creator_scope(scope, priority=50):  # pylint: disable=protected-access
    665   # __wrapped__ allows AutoGraph to swap in a converted function. We give
    666   # the function a weak reference to itself to avoid a reference cycle.
    667   with OptionalXlaContext(compile_with_xla):
--> 668     out = weak_wrapped_fn().__wrapped__(*args, **kwds)
    669   return out

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\framework\func_graph.py:994, in func_graph_from_py_func.<locals>.wrapper(*args, **kwargs)
    992 except Exception as e:  # pylint:disable=broad-except
    993   if hasattr(e, "ag_error_metadata"):
--> 994     raise e.ag_error_metadata.to_exception(e)
    995   else:
    996     raise

ValueError: in user code:

    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\training.py:853 train_function  *
        return step_function(self, iterator)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\training.py:842 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:1286 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2849 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:3632 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\training.py:835 run_step  **
        outputs = model.train_step(data)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\training.py:788 train_step
        loss = self.compiled_loss(
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\compile_utils.py:201 __call__
        loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\losses.py:141 __call__
        losses = call_fn(y_true, y_pred)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\losses.py:245 call  **
        return ag_fn(y_true, y_pred, **self._fn_kwargs)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\util\dispatch.py:206 wrapper
        return target(*args, **kwargs)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\losses.py:1665 categorical_crossentropy
        return backend.categorical_crossentropy(
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\util\dispatch.py:206 wrapper
        return target(*args, **kwargs)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\backend.py:4839 categorical_crossentropy
        target.shape.assert_is_compatible_with(output.shape)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\framework\tensor_shape.py:1161 assert_is_compatible_with
        raise ValueError("Shapes %s and %s are incompatible" % (self, other))

    ValueError: Shapes (128, 1, 44) and (128, 128, 44) are incompatible

</code>```

Body:
I have a deep neural-network in tensorflow that trains fine with a 5-unit dense output layer with linear activation (data labels are linear scaled values similar to linear regression).  When I change the output label encoding to 1-hot and the output layer to 5 individual, 25-unit dense 'heads' tensorflow will not train (ie .fit) and complains about the tensor shape being incompatible.  It seems like a straight forward issue but the data label shape looks fine to me.

ValueError: Shapes (128, 1, 25) and (128, 128, 25) are incompatible

Details below:

Model's output layer details:

Linear dense output model:

X_in = Input(batch_input_shape=(batch_size=128, 128, 14), name='input')
... many layers...
yhat = Dense(5, activation='linear', name='Lin_classify')(X)
model = Model(inputs=X_in, outputs=[yhat])
model.compile(loss='mse', optimizer=Adam(learning_rate=model_params['learn_rate']), metrics=['accuracy'])

model.summary()
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
FC_1 (TimeDistributed)          (128, 128, 128)      32896       BDLSTM_3[0][0]
__________________________________________________________________________________________________
Lin_classify (Dense)            (128, 128, 5)        645         FC_1[0][0]
==================================================================================================

1-hot encoded model:

Changed output layer to multi-head.

The output layer will pick 5 objects that can each be 1 of 25 classes

X_in = Input(batch_input_shape=(batch_size=128, 128, 14), name='input')
... many layers...
yhat1 = Dense(25, activation='softmax', name='y_1hot_1')(X)
yhat2 = Dense(25, activation='softmax', name='y_1hot_2')(X)
yhat3 = Dense(25, activation='softmax', name='y_1hot_3')(X)
yhat4 = Dense(25, activation='softmax', name='y_1hot_4')(X)
yhat5 = Dense(25, activation='softmax', name='y_1hot_5')(X)
model = Model(inputs=X_in, outputs=[yhat1, yhat2, yhat3, yhat4, yhat5])
model.compile(loss={'y_1hot_1':loss, 'y_1hot_2':loss, 'y_1hot_3':loss, 'y_1hot_4':loss, 'y_1hot_5':loss},
              optimizer=Adam(learning_rate=model_params['learn_rate']),
              metrics={'y_1hot_1':metric, 'y_1hot_2':metric,'y_1hot_3':metric, 'y_1hot_4':metric, 'y_1hot_5':metric})

model.summary()
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to
==================================================================================================
FC_1 (TimeDistributed)          (128, 128, 128)      32896       BDLSTM_3[0][0]
__________________________________________________________________________________________________
y_1hot_1 (Dense)                (128, 128, 25)       3225        FC_1[0][0]
__________________________________________________________________________________________________
y_1hot_2 (Dense)                (128, 128, 25)       3225        FC_1[0][0]
__________________________________________________________________________________________________
y_1hot_3 (Dense)                (128, 128, 25)       3225        FC_1[0][0]
__________________________________________________________________________________________________
y_1hot_4 (Dense)                (128, 128, 25)       3225        FC_1[0][0]
__________________________________________________________________________________________________
y_1hot_5 (Dense)                (128, 128, 25)       3225        FC_1[0][0]
==================================================================================================

Both varieties of models compile as expected.  Note that the output shapes of both models are similar (128, 128, x) except that the 1-hot model has 5 output heads.

Data:

X_train dims: (num_samples, window_length, num_features)

Linear model: X_train.shape = (3840, 128, 14); Y_train.shape = (3840, 1, 5)

1-hot model:  X_train.shape = (3840, 128, 14); Y_train[0:5].shape = (3840, 1, 25)

Linear model:

print(model.inputs)
>[<KerasTensor: shape=(128, 128, 14) dtype=float32 (created by layer 'input')>]
print(model.outputs)
>[<KerasTensor: shape=(128, 128, 5) dtype=float32 (created by layer 'Lin_classify')>]

Note: label shape: (m, 1, 5) Output shape: (128, 128, 5) This trains fine

1-hot model:

print(model.inputs)
>[<KerasTensor: shape=(128, 128, 14) dtype=float32 (created by layer 'input')>]
print(model.outputs)
>[<KerasTensor: shape=(128, 128, 25) dtype=float32 (created by layer 'y_1hot_1')>,
 <KerasTensor: shape=(128, 128, 25) dtype=float32 (created by layer 'y_1hot_2')>,
 <KerasTensor: shape=(128, 128, 25) dtype=float32 (created by layer 'y_1hot_3')>,
 <KerasTensor: shape=(128, 128, 25) dtype=float32 (created by layer 'y_1hot_4')>,
 <KerasTensor: shape=(128, 128, 25) dtype=float32 (created by layer 'y_1hot_5')>]

Note: label shape: (m, 1, 25) Output shape: (128, 128, 25) This fails with mismatch error

Training is the same for both models and occurs 1 epoch at a time in stateful mode (stateful applies to hidden lstm layers, not the output layer):

for i in range(n_epochs):
    ehist = model.fit(x=X_train, y=Y_train, batch_size=128, epochs=1,
                        shuffle=False, verbose=2)
    model.reset_states()

The model receives batches of 128 examples of 128x14 input data and outputs 128, 1x5 predictions in the case of the linear model.  And outputs 5 individual 128, 1x25 predictions in the case of the 1-hot model.

Question:

Why does training the 1-hot model immediately fail with the following error?

ValueError: Shapes (128, 1, 25) and (128, 128, 25) are incompatible

(the linear model does not complain and the main difference between model outputs is the 3rd dimension; ie 5 -> 25).

Any help with this would be greatly appreciated.

Here is the full error message:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
Cell In[23], line 7
      6 for i in range(n_epochs):
----> 7     ehist = model.fit(x=X_train, y=Y_train, batch_size=batch_sz, epochs=1,
      8                         shuffle=False, verbose=2)
      9     model.reset_states()

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\training.py:1184, in Model.fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1177 with tf.profiler.experimental.Trace(
   1178     'train',
   1179     epoch_num=epoch,
   1180     step_num=step,
   1181     batch_size=batch_size,
   1182     _r=1):
   1183   callbacks.on_train_batch_begin(step)
-> 1184   tmp_logs = self.train_function(iterator)
   1185   if data_handler.should_sync:
   1186     context.async_wait()

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\eager\def_function.py:885, in Function.__call__(self, *args, **kwds)
    882 compiler = "xla" if self._jit_compile else "nonXla"
    884 with OptionalXlaContext(self._jit_compile):
--> 885   result = self._call(*args, **kwds)
    887 new_tracing_count = self.experimental_get_tracing_count()
    888 without_tracing = (tracing_count == new_tracing_count)

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\eager\def_function.py:933, in Function._call(self, *args, **kwds)
    930 try:
    931   # This is the first call of __call__, so we have to initialize.
    932   initializers = []
--> 933   self._initialize(args, kwds, add_initializers_to=initializers)
    934 finally:
    935   # At this point we know that the initialization is complete (or less
    936   # interestingly an exception was raised) so we no longer need a lock.
    937   self._lock.release()

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\eager\def_function.py:759, in Function._initialize(self, args, kwds, add_initializers_to)
    756 self._lifted_initializer_graph = lifted_initializer_graph
    757 self._graph_deleter = FunctionDeleter(self._lifted_initializer_graph)
    758 self._concrete_stateful_fn = (
--> 759     self._stateful_fn._get_concrete_function_internal_garbage_collected(  # pylint: disable=protected-access
    760         *args, **kwds))
    762 def invalid_creator_scope(*unused_args, **unused_kwds):
    763   """Disables variable creation."""

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\eager\function.py:3066, in Function._get_concrete_function_internal_garbage_collected(self, *args, **kwargs)
   3064   args, kwargs = None, None
   3065 with self._lock:
-> 3066   graph_function, _ = self._maybe_define_function(args, kwargs)
   3067 return graph_function

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\eager\function.py:3463, in Function._maybe_define_function(self, args, kwargs)
   3459   return self._define_function_with_shape_relaxation(
   3460       args, kwargs, flat_args, filtered_flat_args, cache_key_context)
   3462 self._function_cache.missed.add(call_context_key)
-> 3463 graph_function = self._create_graph_function(args, kwargs)
   3464 self._function_cache.primary[cache_key] = graph_function
   3466 return graph_function, filtered_flat_args

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\eager\function.py:3298, in Function._create_graph_function(self, args, kwargs, override_flat_arg_shapes)
   3293 missing_arg_names = [
   3294     "%s_%d" % (arg, i) for i, arg in enumerate(missing_arg_names)
   3295 ]
   3296 arg_names = base_arg_names + missing_arg_names
   3297 graph_function = ConcreteFunction(
-> 3298     func_graph_module.func_graph_from_py_func(
   3299         self._name,
   3300         self._python_function,
   3301         args,
   3302         kwargs,
   3303         self.input_signature,
   3304         autograph=self._autograph,
   3305         autograph_options=self._autograph_options,
   3306         arg_names=arg_names,
   3307         override_flat_arg_shapes=override_flat_arg_shapes,
   3308         capture_by_value=self._capture_by_value),
   3309     self._function_attributes,
   3310     function_spec=self.function_spec,
   3311     # Tell the ConcreteFunction to clean up its graph once it goes out of
   3312     # scope. This is not the default behavior since it gets used in some
   3313     # places (like Keras) where the FuncGraph lives longer than the
   3314     # ConcreteFunction.
   3315     shared_func_graph=False)
   3316 return graph_function

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\framework\func_graph.py:1007, in func_graph_from_py_func(name, python_func, args, kwargs, signature, func_graph, autograph, autograph_options, add_control_dependencies, arg_names, op_return_value, collections, capture_by_value, override_flat_arg_shapes, acd_record_initial_resource_uses)
   1004 else:
   1005   _, original_func = tf_decorator.unwrap(python_func)
-> 1007 func_outputs = python_func(*func_args, **func_kwargs)
   1009 # invariant: `func_outputs` contains only Tensors, CompositeTensors,
   1010 # TensorArrays and `None`s.
   1011 func_outputs = nest.map_structure(convert, func_outputs,
   1012                                   expand_composites=True)

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\eager\def_function.py:668, in Function._defun_with_scope.<locals>.wrapped_fn(*args, **kwds)
    664 with default_graph._variable_creator_scope(scope, priority=50):  # pylint: disable=protected-access
    665   # __wrapped__ allows AutoGraph to swap in a converted function. We give
    666   # the function a weak reference to itself to avoid a reference cycle.
    667   with OptionalXlaContext(compile_with_xla):
--> 668     out = weak_wrapped_fn().__wrapped__(*args, **kwds)
    669   return out

File ~\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\framework\func_graph.py:994, in func_graph_from_py_func.<locals>.wrapper(*args, **kwargs)
    992 except Exception as e:  # pylint:disable=broad-except
    993   if hasattr(e, "ag_error_metadata"):
--> 994     raise e.ag_error_metadata.to_exception(e)
    995   else:
    996     raise

ValueError: in user code:

    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\training.py:853 train_function  *
        return step_function(self, iterator)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\training.py:842 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:1286 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:2849 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\distribute\distribute_lib.py:3632 _call_for_each_replica
        return fn(*args, **kwargs)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\training.py:835 run_step  **
        outputs = model.train_step(data)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\training.py:788 train_step
        loss = self.compiled_loss(
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\engine\compile_utils.py:201 __call__
        loss_value = loss_obj(y_t, y_p, sample_weight=sw)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\losses.py:141 __call__
        losses = call_fn(y_true, y_pred)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\losses.py:245 call  **
        return ag_fn(y_true, y_pred, **self._fn_kwargs)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\util\dispatch.py:206 wrapper
        return target(*args, **kwargs)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\losses.py:1665 categorical_crossentropy
        return backend.categorical_crossentropy(
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\util\dispatch.py:206 wrapper
        return target(*args, **kwargs)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\keras\backend.py:4839 categorical_crossentropy
        target.shape.assert_is_compatible_with(output.shape)
    C:\Users\tm2\Anaconda3\envs\tensorflow-gpu\lib\site-packages\tensorflow\python\framework\tensor_shape.py:1161 assert_is_compatible_with
        raise ValueError("Shapes %s and %s are incompatible" % (self, other))

    ValueError: Shapes (128, 1, 44) and (128, 128, 44) are incompatible


问:
How do I fix a jittery/jumpy interface (specifically the refresh wheel) when loading data asynchronously in SwiftUI?
I've built an iPhone app to display train schedule and system alert data for the Washington DC Metro.

I have a Firebase Realtime Database in which I store data that I've pulled from WMATA's API, and my app loads data asynchronously and displays it for the user.

The app works properly, but sometimes the interface is a bit jittery, with the refresh wheel jumping quickly to the left before centering, and pages quickly flashing blank before data loads. I think this has something to do with the way I'm refreshing the interface before refreshing the actual data, which seems to be the "correct" way of doing things, but makes the app look more disjointed than I'd like. I'd probably be fine if I can figure out how to keep the refresh wheel from jumping around, but I'm also curious as to whether there's a good way of preventing UI elements from loading (in this case, the "All Tweets" link) until after the asynchronous data has loaded.

Here is the Alerts tab in my app, which shows the jumpy interface and quick flash of an uncentered "All Tweets" link before the page fully loads:

Here is my attempt at writing a simpler version of the code I'm using to display this page, which asynchronously loads alerts from Firebase as a task when the page loads.

```<code>import SwiftUI
import FirebaseDatabase

class AlertListDebug: ObservableObject {
    @Published var alerts = [String:[String:Any]]()

    //Initializers
    init() {

    }

    //Get data asynchronously
    @MainActor
    func getAlertsDataDebug(refAlertsRaw: DatabaseReference!, officialTwitter: String) async {
        self.alerts = [:]

        //Generate query
        var query: DatabaseQuery
        query = refAlertsRaw.child("alerts").child("raw_" + officialTwitter)

        //Query data
        query.observeSingleEvent(of: .value) { snapshot  in
            if(!(snapshot.value is NSNull)) {
                let dict = snapshot.value as! [String: Any]
                for element in dict {
                    let key = element.key
                    let alertRaw = element.value as! [String: Any]
                    let alert = ["lines": alertRaw["Line"]!, "text": alertRaw["Text"]!]

                    //Add alert element to list
                    self.alerts[key] = alert
                }
            }
        }

    }
}

struct AlertsViewDebug: View {
    @StateObject var alertList = AlertListDebug()

    //Variable tracking whether official or Twitter alerts are being shown
    @State var officialTwitter = "official"

    //Create database reference
    var refAlertsRaw: DatabaseReference! = Database.database().reference()

    var body: some View {
        VStack(alignment: .leading, spacing: 0){
            //Official and Twitter alert source buttons
            HStack {
                Button(action: {
                    officialTwitter = "official";
                    Task {
                        await alertList.getAlertsDataDebug(refAlertsRaw: refAlertsRaw, officialTwitter: officialTwitter)
                    }
                }) {
                    Text("Official Alerts")
                }
                Spacer()
                Button(action: {
                    officialTwitter = "twitter";
                    Task {
                        await alertList.getAlertsDataDebug(refAlertsRaw: refAlertsRaw, officialTwitter: officialTwitter)
                    }
                }) {
                    Text("Twitter Feed")
                }
            }
            //Display list of alerts
            ScrollView {
                VStack(spacing: 0) {
                    if(alertList.alerts.count > 0) {
                        ForEach(alertList.alerts.keys.sorted(), id: \.self) {alertKey in

                            Text(alertKey)
                                .font(.system(size: 16))
                                .foregroundColor(.black)
                                .frame(width: 320)

                        }
                    }
                }.overlay(
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(.black, lineWidth: 1)
                )
                .padding(.vertical, 5)
                if(officialTwitter == "twitter") {
                    //Browser link to Twitter feed
                    Text("All Tweets")
                }
            }.task {
                await alertList.getAlertsDataDebug(refAlertsRaw: refAlertsRaw, officialTwitter: officialTwitter)
            }.refreshable {
                await alertList.getAlertsDataDebug(refAlertsRaw: refAlertsRaw, officialTwitter: officialTwitter)
            }
            Spacer()
        }.navigationTitle("Alerts")
        .navigationBarTitleDisplayMode(.inline)
    }
}
</code>```

Please let me know if I'm going about this incorrectly - thank you!

Body:
I've built an iPhone app to display train schedule and system alert data for the Washington DC Metro.

I have a Firebase Realtime Database in which I store data that I've pulled from WMATA's API, and my app loads data asynchronously and displays it for the user.

The app works properly, but sometimes the interface is a bit jittery, with the refresh wheel jumping quickly to the left before centering, and pages quickly flashing blank before data loads. I think this has something to do with the way I'm refreshing the interface before refreshing the actual data, which seems to be the "correct" way of doing things, but makes the app look more disjointed than I'd like. I'd probably be fine if I can figure out how to keep the refresh wheel from jumping around, but I'm also curious as to whether there's a good way of preventing UI elements from loading (in this case, the "All Tweets" link) until after the asynchronous data has loaded.

Here is the Alerts tab in my app, which shows the jumpy interface and quick flash of an uncentered "All Tweets" link before the page fully loads:

Here is my attempt at writing a simpler version of the code I'm using to display this page, which asynchronously loads alerts from Firebase as a task when the page loads.

import SwiftUI
import FirebaseDatabase

class AlertListDebug: ObservableObject {
    @Published var alerts = [String:[String:Any]]()

    //Initializers
    init() {

    }

    //Get data asynchronously
    @MainActor
    func getAlertsDataDebug(refAlertsRaw: DatabaseReference!, officialTwitter: String) async {
        self.alerts = [:]

        //Generate query
        var query: DatabaseQuery
        query = refAlertsRaw.child("alerts").child("raw_" + officialTwitter)

        //Query data
        query.observeSingleEvent(of: .value) { snapshot  in
            if(!(snapshot.value is NSNull)) {
                let dict = snapshot.value as! [String: Any]
                for element in dict {
                    let key = element.key
                    let alertRaw = element.value as! [String: Any]
                    let alert = ["lines": alertRaw["Line"]!, "text": alertRaw["Text"]!]

                    //Add alert element to list
                    self.alerts[key] = alert
                }
            }
        }

    }
}

struct AlertsViewDebug: View {
    @StateObject var alertList = AlertListDebug()

    //Variable tracking whether official or Twitter alerts are being shown
    @State var officialTwitter = "official"

    //Create database reference
    var refAlertsRaw: DatabaseReference! = Database.database().reference()

    var body: some View {
        VStack(alignment: .leading, spacing: 0){
            //Official and Twitter alert source buttons
            HStack {
                Button(action: {
                    officialTwitter = "official";
                    Task {
                        await alertList.getAlertsDataDebug(refAlertsRaw: refAlertsRaw, officialTwitter: officialTwitter)
                    }
                }) {
                    Text("Official Alerts")
                }
                Spacer()
                Button(action: {
                    officialTwitter = "twitter";
                    Task {
                        await alertList.getAlertsDataDebug(refAlertsRaw: refAlertsRaw, officialTwitter: officialTwitter)
                    }
                }) {
                    Text("Twitter Feed")
                }
            }
            //Display list of alerts
            ScrollView {
                VStack(spacing: 0) {
                    if(alertList.alerts.count > 0) {
                        ForEach(alertList.alerts.keys.sorted(), id: \.self) {alertKey in

                            Text(alertKey)
                                .font(.system(size: 16))
                                .foregroundColor(.black)
                                .frame(width: 320)

                        }
                    }
                }.overlay(
                    RoundedRectangle(cornerRadius: 10)
                        .stroke(.black, lineWidth: 1)
                )
                .padding(.vertical, 5)
                if(officialTwitter == "twitter") {
                    //Browser link to Twitter feed
                    Text("All Tweets")
                }
            }.task {
                await alertList.getAlertsDataDebug(refAlertsRaw: refAlertsRaw, officialTwitter: officialTwitter)
            }.refreshable {
                await alertList.getAlertsDataDebug(refAlertsRaw: refAlertsRaw, officialTwitter: officialTwitter)
            }
            Spacer()
        }.navigationTitle("Alerts")
        .navigationBarTitleDisplayMode(.inline)
    }
}

Please let me know if I'm going about this incorrectly - thank you!


问:
Using a classification model to categorize foods
I have a df_cat dataframe containing many foods and their corresponding categories:

```<code>df_cat

    Food                      Category
0   Cows milk                 Dairy products
1   Milk skim                 Dairy products
2   Buttermilk                Dairy products
3   Evaporated, undiluted     Dairy products
4   Fortified milk            Dairy products
... ...                       ...
316 Fruit-flavored soda       Drinks,Alcohol, Beverages
317 Ginger ale                Drinks,Alcohol, Beverages
318 Root beer                 Drinks,Alcohol, Beverages
319 Coffee                    Drinks,Alcohol, Beverages
320 Tea                       Drinks,Alcohol, Beverages
</code>```

I have another dataframe df_ingredients containing many recipe ingredients but no food category:

```<code>df_ingredients

    Food                Measurement       Amount
0   Brioche bun         piece(s)          2.0
1   Potatoes            gram              1000.0
2   Broccoli            gram              200.0
3   Kumato tomato       piece(s)          1.0
4   Portobello          gram              160.0
... ...                 ...               ...
29  Grated aged cheese  gram              50.0
30  Parmigiano reggiano gram              60.0
31  Butter              tbsp              2.5
32  Cream               ml                132.0
33  Chicken fillet      piece(s)          2.0
</code>```

I'd like to train a classification model using df_cat to map a Category column in df_ingredients. I have tried following this tutorial using a bag-of-words approach, a CountVectorizer(), and LogisticRegression() but I'm getting some bad accuracy results and I'm not sure how I can use the model to map the Category column in df_ingredients. Here's the code I've used thus far and the results - any guidance/help would be greatly appreciated!

```<code>from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

df_ingredients = pd.read_csv("df_ingredients.csv")
df_cat = pd.read_csv("nutrients_csvfile.csv")

foods = df_cat["Food"].values
categories = df_cat["Category"].values

foods_train, foods_test, categories_train, categories_test = train_test_split(foods, categories, test_size=0.20) #, random_state=1000

vectorizer = CountVectorizer()
vectorizer.fit(foods_train)
food_train = vectorizer.transform(foods_train)
food_test  = vectorizer.transform(foods_test)

classifier = LogisticRegression()
classifier.fit(food_train, categories_train)
score = classifier.score(food_test, categories_test)

print("Accuracy:", score)
Accuracy: 0.33846
</code>```

Body:
I have a df_cat dataframe containing many foods and their corresponding categories:

df_cat

    Food                      Category
0   Cows milk                 Dairy products
1   Milk skim                 Dairy products
2   Buttermilk                Dairy products
3   Evaporated, undiluted     Dairy products
4   Fortified milk            Dairy products
... ...                       ...
316 Fruit-flavored soda       Drinks,Alcohol, Beverages
317 Ginger ale                Drinks,Alcohol, Beverages
318 Root beer                 Drinks,Alcohol, Beverages
319 Coffee                    Drinks,Alcohol, Beverages
320 Tea                       Drinks,Alcohol, Beverages

I have another dataframe df_ingredients containing many recipe ingredients but no food category:

df_ingredients

    Food                Measurement       Amount
0   Brioche bun         piece(s)          2.0
1   Potatoes            gram              1000.0
2   Broccoli            gram              200.0
3   Kumato tomato       piece(s)          1.0
4   Portobello          gram              160.0
... ...                 ...               ...
29  Grated aged cheese  gram              50.0
30  Parmigiano reggiano gram              60.0
31  Butter              tbsp              2.5
32  Cream               ml                132.0
33  Chicken fillet      piece(s)          2.0

I'd like to train a classification model using df_cat to map a Category column in df_ingredients. I have tried following this tutorial using a bag-of-words approach, a CountVectorizer(), and LogisticRegression() but I'm getting some bad accuracy results and I'm not sure how I can use the model to map the Category column in df_ingredients. Here's the code I've used thus far and the results - any guidance/help would be greatly appreciated!

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

df_ingredients = pd.read_csv("df_ingredients.csv")
df_cat = pd.read_csv("nutrients_csvfile.csv")

foods = df_cat["Food"].values
categories = df_cat["Category"].values

foods_train, foods_test, categories_train, categories_test = train_test_split(foods, categories, test_size=0.20) #, random_state=1000

vectorizer = CountVectorizer()
vectorizer.fit(foods_train)
food_train = vectorizer.transform(foods_train)
food_test  = vectorizer.transform(foods_test)

classifier = LogisticRegression()
classifier.fit(food_train, categories_train)
score = classifier.score(food_test, categories_test)

print("Accuracy:", score)
Accuracy: 0.33846


问:
404 page after importing project from github to vercel
This is my 5th project deployed to the Vercel via GitHub (after almost year break). However after importing the project from the GitHub and pushing it to Vercel I am getting 404 page with a link to unhelpful page with explanation why I might see the 404 page (which naturally does not resolve even remotely the issue). I don't understand. My previous 4 projects were deployed this way and they work to this day. Simple push to the GitHub will update the project and publish it live. The projects says it is build, there are no errors. It works on local building it with npm run dev.

The project was added the recommended way as per the Next documentation using npx - command was copy-pasted from the documentation.

I have consulted this with how to publish Next.js project to Vercel and there are simple 4 steps which I did.

Does anyone maybe had similar experience and managed to resolve this kind of issue? Thank you kindly for your time.