问:
Mermaid class diagram hide/conceal certain nodes and links/edgePaths
I want to create a mermaid class diagram in a github .md file where in I can hide/conceal certain nodes and paths/links from that node using CSS.

What I want?

I want the following where the node for the Zebra is concealed and the arrow path/link from it is also concealed. But the sibling Lion class and it's link is 100% opacity.

What I have tried:

I was able to hide nodes using the cssClass feature as below:

```<code>// CSS
<style>
  .conceal {
    opacity: 20% !important;
  }
</style>

// ```mermaid
   classDiagram
       Animal <|--|> Zebra
       Animal <|--|> Lion
       cssClass "Zebra" conceal
// ```

</code>```

This produces the following chart where Zebra is concealed while lion is not

However the path from the Zebra is still 100% opacity.

To fix the opacity of the edgePath I tried the following:

  .edgePaths:has(~g>g.conceal) {
    opacity: 20% !important;
  }
```
```// CSS

//```mermaid
classDiagram
    Animal <|--|> Zebra
    Animal <|--|> Lion
    cssClass "Zebra" conceal
//```

```
<p><strong>Note:</strong> the <code>has</code> css selector does not work in Firefox yet.</p>
<p>However, this made both paths from Animal have the lowered opacity as can be seen (in Chrome):</p>
<p><img src="https://i.stack.imgur.com/1G9XV.png" alt="enter image description here" /></p>
<p>Here is the SVG as example:</p>
```<svg aria-labelledby="chart-title-mermaid-1671893404869 chart-desc-mermaid-1671893404869" role="img" viewBox="0.000003814697265625 0.00000286102294921875 170.4431915283203 195.19317626953125" style="max-width: 170.4431915283203px;" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" width="100%" id="mermaid-1671893404869">

    <title id="chart-title-mermaid-1671893404869">
    </title>
    <desc id="chart-desc-mermaid-1671893404869">
    </desc>

    <g>
        <defs>
            <marker orient="auto" markerHeight="240" markerWidth="190" refY="7" refX="0" class="marker aggregation classDiagram" id="classDiagram-aggregationStart">
                <path d="M 18,7 L9,13 L1,7 L9,1 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="28" markerWidth="20" refY="7" refX="19" class="marker aggregation classDiagram" id="classDiagram-aggregationEnd">
                <path d="M 18,7 L9,13 L1,7 L9,1 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="240" markerWidth="190" refY="7" refX="0" class="marker extension classDiagram" id="classDiagram-extensionStart">
                <path d="M 1,7 L18,13 V 1 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="28" markerWidth="20" refY="7" refX="19" class="marker extension classDiagram" id="classDiagram-extensionEnd">
                <path d="M 1,1 V 13 L18,7 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="240" markerWidth="190" refY="7" refX="0" class="marker composition classDiagram" id="classDiagram-compositionStart">
                <path d="M 18,7 L9,13 L1,7 L9,1 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="28" markerWidth="20" refY="7" refX="19" class="marker composition classDiagram" id="classDiagram-compositionEnd">
                <path d="M 18,7 L9,13 L1,7 L9,1 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="240" markerWidth="190" refY="7" refX="0" class="marker dependency classDiagram" id="classDiagram-dependencyStart">
                <path d="M 5,7 L9,13 L1,7 L9,1 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="28" markerWidth="20" refY="7" refX="19" class="marker dependency classDiagram" id="classDiagram-dependencyEnd">
                <path d="M 18,7 L9,13 L14,7 L9,1 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="240" markerWidth="190" refY="7" refX="0" class="marker lollipop classDiagram" id="classDiagram-lollipopStart">
                <circle r="6" cy="7" cx="6" fill="white" stroke="black">
                </circle>
            </marker>
        </defs>
        <g class="root">
            <g class="clusters">
            </g>
            <g class="edgePaths">
                <path marker-end="url(#classDiagram-extensionEnd)" marker-start="url(#classDiagram-extensionStart)" style="fill:none" class="edge-pattern-solid relation" id="id1" d="M58.962245118973726,72.59658813476562L55.24552626440763,76.7632548014323C51.528807409841534,80.92992146809895,44.09536970070934,89.2632548014323,40.378650846143245,97.59658813476562C36.66193199157715,105.92992146809895,36.66193199157715,114.2632548014323,36.66193199157715,118.42992146809895L36.66193199157715,122.59658813476562">
                </path>
                <path marker-end="url(#classDiagram-extensionEnd)" marker-start="url(#classDiagram-extensionStart)" style="fill:none" class="edge-pattern-solid relation" id="id2" d="M116.58321081364346,72.59658813476562L120.29992966820957,76.7632548014323C124.01664852277565,80.92992146809895,131.45008623190785,89.2632548014323,135.16680508647394,97.59658813476562C138.88352394104004,105.92992146809895,138.88352394104004,114.2632548014323,138.88352394104004,118.42992146809895L138.88352394104004,122.59658813476562">
                </path>
            </g>
            <g class="edgeLabels">
                <g class="edgeLabel">
                    <g transform="translate(0, 0)" class="label">
                        <foreignObject height="0" width="0">

                        </foreignObject>
                    </g>
                </g>
                <g class="edgeLabel">
                    <g transform="translate(0, 0)" class="label">
                        <foreignObject height="0" width="0">

                        </foreignObject>
                    </g>
                </g>
            </g>
            <g class="nodes">
                <g transform="translate(87.7727279663086, 40.29829406738281)" id="classid-Animal-0" class="node default">
                    <rect height="64.59659194946289" width="66.34659194946289" y="-32.298295974731445" x="-33.173295974731445" class="outer title-state">
                    </rect>
                    <line y2="5.298295974731445" y1="5.298295974731445" x2="33.173295974731445" x1="-33.173295974731445" class="divider">
                    </line>
                    <line y2="21.298295974731445" y1="21.298295974731445" x2="33.173295974731445" x1="-33.173295974731445" class="divider">
                    </line>
                    <g class="label">
                        <foreignObject height="0" width="0">

                        </foreignObject>
                        <foreignObject transform="translate( -25.673295974731445, -24.798295974731445)" height="25.59659194946289" width="51.34659194946289" class="classTitle">

                                    Animal

                        </foreignObject>
                    </g>
                </g>
                <g transform="translate(36.66193199157715, 154.89488220214844)" id="classid-Zebra-1" class="node default conceal">
                    <rect height="64.59659194946289" width="57.3238639831543" y="-32.298295974731445" x="-28.66193199157715" class="outer title-state">
                    </rect>
                    <line y2="5.298295974731445" y1="5.298295974731445" x2="28.66193199157715" x1="-28.66193199157715" class="divider">
                    </line>
                    <line y2="21.298295974731445" y1="21.298295974731445" x2="28.66193199157715" x1="-28.66193199157715" class="divider">
                    </line>
                    <g class="label">
                        <foreignObject height="0" width="0">

                        </foreignObject>
                        <foreignObject transform="translate( -21.16193199157715, -24.798295974731445)" height="25.59659194946289" width="42.3238639831543" class="classTitle">

                                    Zebra

                        </foreignObject>
                    </g>
                </g>
                <g transform="translate(138.88352394104004, 154.89488220214844)" id="classid-Lion-2" class="node default">
                    <rect height="64.59659194946289" width="47.119319915771484" y="-32.298295974731445" x="-23.559659957885742" class="outer title-state">
                    </rect>
                    <line y2="5.298295974731445" y1="5.298295974731445" x2="23.559659957885742" x1="-23.559659957885742" class="divider">
                    </line>
                    <line y2="21.298295974731445" y1="21.298295974731445" x2="23.559659957885742" x1="-23.559659957885742" class="divider">
                    </line>
                    <g class="label">
                        <foreignObject height="0" width="0">

                        </foreignObject>
                        <foreignObject transform="translate( -16.059659957885742, -24.798295974731445)" height="25.59659194946289" width="32.119319915771484" class="classTitle">

                                    Lion

                        </foreignObject>
                    </g>
                </g>
            </g>
        </g>
    </g>
</svg>
```

Question:

Is there a way using CSS selectors to apply the reduced opacity to only one of the edgePaths?

Body:
I want to create a mermaid class diagram in a github .md file where in I can hide/conceal certain nodes and paths/links from that node using CSS.

What I want?

I want the following where the node for the Zebra is concealed and the arrow path/link from it is also concealed. But the sibling Lion class and it's link is 100% opacity.

What I have tried:

I was able to hide nodes using the cssClass feature as below:

// CSS

// ```mermaid
   classDiagram
       Animal <|--|> Zebra
       Animal <|--|> Lion
       cssClass "Zebra" conceal
// ```

This produces the following chart where Zebra is concealed while lion is not

However the path from the Zebra is still 100% opacity.

To fix the opacity of the edgePath I tried the following:

  .edgePaths:has(~g>g.conceal) {
    opacity: 20% !important;
  }

// CSS

//```mermaid
classDiagram
    Animal <|--|> Zebra
    Animal <|--|> Lion
    cssClass "Zebra" conceal
//```

Note: the has css selector does not work in Firefox yet.

However, this made both paths from Animal have the lowered opacity as can be seen (in Chrome):

Here is the SVG as example:

<svg aria-labelledby="chart-title-mermaid-1671893404869 chart-desc-mermaid-1671893404869" role="img" viewBox="0.000003814697265625 0.00000286102294921875 170.4431915283203 195.19317626953125" style="max-width: 170.4431915283203px;" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg" width="100%" id="mermaid-1671893404869">

    <title id="chart-title-mermaid-1671893404869">
    </title>
    <desc id="chart-desc-mermaid-1671893404869">
    </desc>

    <g>
        <defs>
            <marker orient="auto" markerHeight="240" markerWidth="190" refY="7" refX="0" class="marker aggregation classDiagram" id="classDiagram-aggregationStart">
                <path d="M 18,7 L9,13 L1,7 L9,1 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="28" markerWidth="20" refY="7" refX="19" class="marker aggregation classDiagram" id="classDiagram-aggregationEnd">
                <path d="M 18,7 L9,13 L1,7 L9,1 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="240" markerWidth="190" refY="7" refX="0" class="marker extension classDiagram" id="classDiagram-extensionStart">
                <path d="M 1,7 L18,13 V 1 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="28" markerWidth="20" refY="7" refX="19" class="marker extension classDiagram" id="classDiagram-extensionEnd">
                <path d="M 1,1 V 13 L18,7 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="240" markerWidth="190" refY="7" refX="0" class="marker composition classDiagram" id="classDiagram-compositionStart">
                <path d="M 18,7 L9,13 L1,7 L9,1 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="28" markerWidth="20" refY="7" refX="19" class="marker composition classDiagram" id="classDiagram-compositionEnd">
                <path d="M 18,7 L9,13 L1,7 L9,1 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="240" markerWidth="190" refY="7" refX="0" class="marker dependency classDiagram" id="classDiagram-dependencyStart">
                <path d="M 5,7 L9,13 L1,7 L9,1 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="28" markerWidth="20" refY="7" refX="19" class="marker dependency classDiagram" id="classDiagram-dependencyEnd">
                <path d="M 18,7 L9,13 L14,7 L9,1 Z">
                </path>
            </marker>
        </defs>
        <defs>
            <marker orient="auto" markerHeight="240" markerWidth="190" refY="7" refX="0" class="marker lollipop classDiagram" id="classDiagram-lollipopStart">
                <circle r="6" cy="7" cx="6" fill="white" stroke="black">
                </circle>
            </marker>
        </defs>
        <g class="root">
            <g class="clusters">
            </g>
            <g class="edgePaths">
                <path marker-end="url(#classDiagram-extensionEnd)" marker-start="url(#classDiagram-extensionStart)" style="fill:none" class="edge-pattern-solid relation" id="id1" d="M58.962245118973726,72.59658813476562L55.24552626440763,76.7632548014323C51.528807409841534,80.92992146809895,44.09536970070934,89.2632548014323,40.378650846143245,97.59658813476562C36.66193199157715,105.92992146809895,36.66193199157715,114.2632548014323,36.66193199157715,118.42992146809895L36.66193199157715,122.59658813476562">
                </path>
                <path marker-end="url(#classDiagram-extensionEnd)" marker-start="url(#classDiagram-extensionStart)" style="fill:none" class="edge-pattern-solid relation" id="id2" d="M116.58321081364346,72.59658813476562L120.29992966820957,76.7632548014323C124.01664852277565,80.92992146809895,131.45008623190785,89.2632548014323,135.16680508647394,97.59658813476562C138.88352394104004,105.92992146809895,138.88352394104004,114.2632548014323,138.88352394104004,118.42992146809895L138.88352394104004,122.59658813476562">
                </path>
            </g>
            <g class="edgeLabels">
                <g class="edgeLabel">
                    <g transform="translate(0, 0)" class="label">
                        <foreignObject height="0" width="0">

                        </foreignObject>
                    </g>
                </g>
                <g class="edgeLabel">
                    <g transform="translate(0, 0)" class="label">
                        <foreignObject height="0" width="0">

                        </foreignObject>
                    </g>
                </g>
            </g>
            <g class="nodes">
                <g transform="translate(87.7727279663086, 40.29829406738281)" id="classid-Animal-0" class="node default">
                    <rect height="64.59659194946289" width="66.34659194946289" y="-32.298295974731445" x="-33.173295974731445" class="outer title-state">
                    </rect>
                    <line y2="5.298295974731445" y1="5.298295974731445" x2="33.173295974731445" x1="-33.173295974731445" class="divider">
                    </line>
                    <line y2="21.298295974731445" y1="21.298295974731445" x2="33.173295974731445" x1="-33.173295974731445" class="divider">
                    </line>
                    <g class="label">
                        <foreignObject height="0" width="0">

                        </foreignObject>
                        <foreignObject transform="translate( -25.673295974731445, -24.798295974731445)" height="25.59659194946289" width="51.34659194946289" class="classTitle">

                                    Animal

                        </foreignObject>
                    </g>
                </g>
                <g transform="translate(36.66193199157715, 154.89488220214844)" id="classid-Zebra-1" class="node default conceal">
                    <rect height="64.59659194946289" width="57.3238639831543" y="-32.298295974731445" x="-28.66193199157715" class="outer title-state">
                    </rect>
                    <line y2="5.298295974731445" y1="5.298295974731445" x2="28.66193199157715" x1="-28.66193199157715" class="divider">
                    </line>
                    <line y2="21.298295974731445" y1="21.298295974731445" x2="28.66193199157715" x1="-28.66193199157715" class="divider">
                    </line>
                    <g class="label">
                        <foreignObject height="0" width="0">

                        </foreignObject>
                        <foreignObject transform="translate( -21.16193199157715, -24.798295974731445)" height="25.59659194946289" width="42.3238639831543" class="classTitle">

                                    Zebra

                        </foreignObject>
                    </g>
                </g>
                <g transform="translate(138.88352394104004, 154.89488220214844)" id="classid-Lion-2" class="node default">
                    <rect height="64.59659194946289" width="47.119319915771484" y="-32.298295974731445" x="-23.559659957885742" class="outer title-state">
                    </rect>
                    <line y2="5.298295974731445" y1="5.298295974731445" x2="23.559659957885742" x1="-23.559659957885742" class="divider">
                    </line>
                    <line y2="21.298295974731445" y1="21.298295974731445" x2="23.559659957885742" x1="-23.559659957885742" class="divider">
                    </line>
                    <g class="label">
                        <foreignObject height="0" width="0">

                        </foreignObject>
                        <foreignObject transform="translate( -16.059659957885742, -24.798295974731445)" height="25.59659194946289" width="32.119319915771484" class="classTitle">

                                    Lion

                        </foreignObject>
                    </g>
                </g>
            </g>
        </g>
    </g>
</svg>

Question:

Is there a way using CSS selectors to apply the reduced opacity to only one of the edgePaths?


来源: stackexchange

问:
How does multiple inheritance in python work with each parent class taking arguments?
Say I want to create a class with two parent classes as follows:

```<code>class A:
    def __init__(self, a) -> None:
        self.a = a

class B:
    def __init__(self, b) -> None:
        self.b = b

class C(A, B):
    def __init__(self, a, b, c) -> None:
        super().__init__(a)
        super().__init__(b)
        self.c = c
</code>```

Now, how do I make sure a goes to A and b goes to B because if I try to run this:

```<code>c = C(1, 2, 3)
print(c.a, c.b, c.c, sep='\n')
</code>```

It yells AttributeError: 'C' object has no attribute 'b'.

Do I always have to create a sub-class with multiple parents like below?

```<code>class C(A, B):
def __init__(self, a, b, c) -> None:
    A.__init__(self, a)
    B.__init__(self, b)
    self.c = c
</code>```

If so, then what is the use of super?

I've also noticed that if there are no arguments, calling C() will also call __init__ from the first parent i.e. A without doing any super or A.__init__(). But how do I call B here? Again I'm unable to understand the use of super.

It might be an ambiguous question but I'm really finding hard to get answers here. Thanks in advance for any help.

ContentLicense: CC BY-SA 4.0

Body:
Say I want to create a class with two parent classes as follows:

class A:
    def __init__(self, a) -> None:
        self.a = a

class B:
    def __init__(self, b) -> None:
        self.b = b

class C(A, B):
    def __init__(self, a, b, c) -> None:
        super().__init__(a)
        super().__init__(b)
        self.c = c

Now, how do I make sure a goes to A and b goes to B because if I try to run this:

c = C(1, 2, 3)
print(c.a, c.b, c.c, sep='\n')

It yells AttributeError: 'C' object has no attribute 'b'.

Do I always have to create a sub-class with multiple parents like below?

class C(A, B):
def __init__(self, a, b, c) -> None:
    A.__init__(self, a)
    B.__init__(self, b)
    self.c = c

If so, then what is the use of super?

I've also noticed that if there are no arguments, calling C() will also call __init__ from the first parent i.e. A without doing any super or A.__init__(). But how do I call B here? Again I'm unable to understand the use of super.

It might be an ambiguous question but I'm really finding hard to get answers here. Thanks in advance for any help.


问:
Spring Boot Transaction
guys! I don't really understand one thing with DB and Spring. Could you explain me why this is happened?
I have one method

getByRegNumber(regNumber)

But after the first call, when I changed some field in DB tool(Data Grip, for example) for this row, another call return me the same entity, without changies.
For example:

```<code> MessageLogDto byRegNumber1 = messageLogReadService.getByRegNumber(regNumber);
        String statusDoc1 = byRegNumber1.getStatusDoc();
//change statusDoc in DB
     MessageLogDto byRegNumber2 = messageLogReadService.getByRegNumber(regNumber);
            String statusDoc2 = byRegNumber2.getStatusDoc();
//change statusDoc in DB
     MessageLogDto byRegNumber3 = messageLogReadService.getByRegNumber(regNumber);
            String statusDoc3 = byRegNumber3.getStatusDoc();
</code>```

In the end I have the same values for all three statusDoc.

The getByRegNumber(String regNumber) method is:

```<code>MessageLog entity = messagesLogRepository.findFirstByRegNumberAndTypeDoc(regNumber, BCM_01.ZVT.getName())
        .orElse(new MessageLog());
return mapper.toDto(entity);
</code>```

Title: Spring Boot Transaction

Body:
guys! I don't really understand one thing with DB and Spring. Could you explain me why this is happened?
I have one method

getByRegNumber(regNumber)

But after the first call, when I changed some field in DB tool(Data Grip, for example) for this row, another call return me the same entity, without changies.
For example:

 MessageLogDto byRegNumber1 = messageLogReadService.getByRegNumber(regNumber);
        String statusDoc1 = byRegNumber1.getStatusDoc();
//change statusDoc in DB
     MessageLogDto byRegNumber2 = messageLogReadService.getByRegNumber(regNumber);
            String statusDoc2 = byRegNumber2.getStatusDoc();
//change statusDoc in DB
     MessageLogDto byRegNumber3 = messageLogReadService.getByRegNumber(regNumber);
            String statusDoc3 = byRegNumber3.getStatusDoc();

In the end I have the same values for all three statusDoc.

The getByRegNumber(String regNumber) method is:

MessageLog entity = messagesLogRepository.findFirstByRegNumberAndTypeDoc(regNumber, BCM_01.ZVT.getName())
        .orElse(new MessageLog());
return mapper.toDto(entity);


问:
How to pass arguments to LanguageTool when using ltex with coc-ltex on neovim
I want to link LanguageTool to the ngram data I downloaded from their website. I was able to do this in the Visual Studio Code version of LTeX using the Language Model option. I believe this passes an argument to the executable. How do I set the Language Model path when using LanguageTool with neovim via coc-ltex?</p>


问:
Why keyboard control stopped working in vb.net when i added checkbox
Here the code all was working peacefully and without any error but when i added a checkbox to my form keys are stopped working

```<code> Dim Lefty, Righty As Boolean
 Private Sub Player_ctrl_Tick(sender As Object, e As EventArgs) Handles Player_ctrl.Tick
        Dim Speed As Integer = 23

        If Lefty And Player1.Left > Me.Left Then
            testlabel.Text += 1
            Player1.Left -= Speed
        ElseIf Righty And Player1.Left + Player1.Width < Me.Width Then
            Player1.Left += Speed
        End If
    End Sub

    Private Sub MainGame_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
        Select Case e.KeyCode
            Case Keys.Left
                Lefty = True
            Case Keys.Right
                Righty = True
        End Select

    End Sub

    Private Sub MainGame_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
        Lefty = False
        Righty = False

    End Sub

</code>```

Any fixes please?

Body:
Here the code all was working peacefully and without any error but when i added a checkbox to my form keys are stopped working

 Dim Lefty, Righty As Boolean
 Private Sub Player_ctrl_Tick(sender As Object, e As EventArgs) Handles Player_ctrl.Tick
        Dim Speed As Integer = 23

        If Lefty And Player1.Left > Me.Left Then
            testlabel.Text += 1
            Player1.Left -= Speed
        ElseIf Righty And Player1.Left + Player1.Width < Me.Width Then
            Player1.Left += Speed
        End If
    End Sub

    Private Sub MainGame_KeyDown(sender As Object, e As KeyEventArgs) Handles Me.KeyDown
        Select Case e.KeyCode
            Case Keys.Left
                Lefty = True
            Case Keys.Right
                Righty = True
        End Select

    End Sub

    Private Sub MainGame_KeyUp(sender As Object, e As KeyEventArgs) Handles Me.KeyUp
        Lefty = False
        Righty = False

    End Sub

Any fixes please?


问:
How to create an empty dataframe using lubridate in R and based on certain criteria
I am new into large datasets management, and I would like to know how to generate a dataframe in R using tidyverse or lubridate which is based on certain criteria as follows:

A column with date as dd/mm/yyyy (from the 1st of January until the 30th of March 2022), and a column with each row corresponding to minutes (for each day belonging to the interval above) from 22:00:00 to 6:00:00 (as 22:01:00, 22:02:00, 22:03:00, 22:04:00.... up to 6.00.00).

Then, I would like to repeat this exact dataframe for 3 species (adding a column where each species is assigned to A,B and C) and also by 4 locations (a, b, c, d - each species is contained in each of this locations). Any advice on doing this in tidyverse, or any other R-package?

Many thanks,
Michela

I have tried to generate date intervals, but then I don't know how to add the minute by minute information in a new column and based on the hour intervals specified above, either I don't know how to repeat that procedure for each site and species.


问:
What are the benefits of implementing OAuth (JWT access tokens with refresh tokens)

Current Setup

I'm currently building an application, and have just finished implementing an OAuth authentication server. This is my first "real" attempt at a project that has a legitimate user authentication and management component, so much of this is new to me.

I've implemented the OAuth specification. This means the following:

The authentication is deployed on a separate webserver with a separate DB than the application server.

The auth server logs in a user, and issues them two tokens. One is a JWT access token that contains information about their user identity. This has a short-lived 15 minutes expiry. The second token is a refresh-token. This  is a single-use token with a 7 day expiry. It is used to fetch another access token with the application server returns a 401 (the access token has expired).

The application server shares a secret key with the auth server, and has middleware that verifies the JWT access token.

Concerns

My concern is that I've over-engineered a project that didn't need this much complexity. Since the auth/app are distinct, this means that my client code needs to be aware of, and handle refresh token rotation. It needs to interpret 401s, and fetch another access token.

As far as I can tell from my reading, this wouldn't be necessary with simple session cookies that persist. The cookie is just included in requests to my domain. If I killed this approach, and just had my server do a DB lookup on a signed session cookie - I would avoid a lot of this client complexity.

One consideration is that I’m using a React SPA frontend client. This is also new territory for me, so I’m not sure whether or not this changes the situation.

As I said above, I'm new to a lot of this so could use some advice from people who have worked in this space for longer and have the experience. Is OAuth worth the hassle?

Options

OAuth with access tokens (JWTs) and refresh tokens:

Pros: Provides a secure and scalable way to handle user sessions.

Cons: Client needs to be aware of refresh token rotation procedure and handle 401 responses by using the refresh token to request a new access token, which can add complexity to the client-side code. Also adds complexity (and cost) to the AWS infra stuff. I need to know how to get the auth server and app server on the same base URI. Also makes my local dev environment a little more involved.

Server-side sessions using signed cookies:

Pros: Simpler for the client, as it does not need to handle refresh tokens or 401 responses.

Cons: Server needs to manage session state, which can be more resource-intensive. This means a DB call on every request.


问:
How can I scrape products price dynamically?
For my master's thesis, I was asked to create a generic web scraper that goes through a list of e-commerce sites and get all products' title, price and description. The challenge is that I should NOT use the inspection tool to get the XPath or css selector of the product's title or price.

The scraper should fetch this information on its own without any prior knowledge of the website.

When I looked into the internet, some solutions use regular expressions to solve this, but this will work to find the price if the element is like this 10.50$, BUT some prices are like this

```<code><span>10</span>
<span>.</span>
<span>50</span>
<span>$</span>
</code>```

so I need to combine them to make the total price. Another challenge is that the expression can return two prices, the real one and the discount one; how can I find the difference?

Another solution is to use a generic css selector to find_all('.price'). This will get all elements with class with name price, but there is no guarantee that all sites will use this name! Should I use Machine learning, or am I over-engineering this?

Body:
For my master's thesis, I was asked to create a generic web scraper that goes through a list of e-commerce sites and get all products' title, price and description. The challenge is that I should NOT use the inspection tool to get the XPath or css selector of the product's title or price.

The scraper should fetch this information on its own without any prior knowledge of the website.

When I looked into the internet, some solutions use regular expressions to solve this, but this will work to find the price if the element is like this 10.50$, BUT some prices are like this

10
.
50
$

so I need to combine them to make the total price. Another challenge is that the expression can return two prices, the real one and the discount one; how can I find the difference?

Another solution is to use a generic css selector to find_all('.price'). This will get all elements with class with name price, but there is no guarantee that all sites will use this name! Should I use Machine learning, or am I over-engineering this?


问:
How do I get the GPS_velocity?
How to get the previous_lat,lon and  current_lat, lon, then caculate the speed each 0.1s.
I have some code about cacluate the distance with different lat ,lon. but i don't now how to calcute vehicle itself distance and velocity.

```<code>from __future__ import print_function
import time
from dronekit import connect, VehicleMode, LocationGlobalRelative
import gps
import socket
import sys
from pymavkink import mavutil
vehicle = connect('/dev/ttyACM0', wait_ready=True, baud=115200)

def get_location_metres(original_location, dNorth, dEast):
    earth_radius = 6378137.0 #Radius of "spherical" earth
    #Coordinate offsets in radians
    dLat = dNorth/earth_radius
    dLon = dEast/(earth_radius*math.cos(math.pi*original_location.lat/180))

    #New position in decimal degrees
    newlat = original_location.lat + (dLat * 180/math.pi)
    newlon = original_location.lon + (dLon * 180/math.pi)
    if type(original_location) is LocationGlobal:
        targetlocation=LocationGlobal(newlat, newlon,original_location.alt)
    elif type(original_location) is LocationGlobalRelative:
        targetlocation=LocationGlobalRelative(newlat, newlon,original_location.alt)
    else:
        raise Exception("Invalid Location object passed")

def get_distance_metres(aLocation1, aLocation2):
    dlat = aLocation2.lat - aLocation1.lat
    dlong = aLocation2.lon - aLocation1.lon
    return math.sqrt((dlat*dlat) + (dlong*dlong)) * 1.113195e5
</code>```

other people code
Calculate the speed from two longitude and latitude GPS coordinates

```<code>def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance in kilometers between two points
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    r = 6371 # Radius of earth in kilometers. Use 3956 for miles. Determines return value units.
    return c * r

prev_data = None

while 1:
    line = ser.readline().decode('UTF-8')
    splitline = line.split(',')

    if splitline[0] == '$GPGGA':
        msg = line
        data = pynmea2.parse(msg)
        if prev_data is not None:
            distance = haversine(data.longitude, data.latitude, prev_data.longitude, prev_data.latitude)
            print('distance', distance)
            print('speed', round(distance*3600, 2))
        prev_data = data

</code>```

get the previous_lat,lon and  current_lat, lon, then caculate the speed each 0.1s. moreover, save the file as csv than compare with vehicle.velocity(get from IMU)

Title: How do I get the GPS_velocity?

Body:
How to get the previous_lat,lon and  current_lat, lon, then caculate the speed each 0.1s.
I have some code about cacluate the distance with different lat ,lon. but i don't now how to calcute vehicle itself distance and velocity.

from __future__ import print_function
import time
from dronekit import connect, VehicleMode, LocationGlobalRelative
import gps
import socket
import sys
from pymavkink import mavutil
vehicle = connect('/dev/ttyACM0', wait_ready=True, baud=115200)

def get_location_metres(original_location, dNorth, dEast):
    earth_radius = 6378137.0 #Radius of "spherical" earth
    #Coordinate offsets in radians
    dLat = dNorth/earth_radius
    dLon = dEast/(earth_radius*math.cos(math.pi*original_location.lat/180))

    #New position in decimal degrees
    newlat = original_location.lat + (dLat * 180/math.pi)
    newlon = original_location.lon + (dLon * 180/math.pi)
    if type(original_location) is LocationGlobal:
        targetlocation=LocationGlobal(newlat, newlon,original_location.alt)
    elif type(original_location) is LocationGlobalRelative:
        targetlocation=LocationGlobalRelative(newlat, newlon,original_location.alt)
    else:
        raise Exception("Invalid Location object passed")

def get_distance_metres(aLocation1, aLocation2):
    dlat = aLocation2.lat - aLocation1.lat
    dlong = aLocation2.lon - aLocation1.lon
    return math.sqrt((dlat*dlat) + (dlong*dlong)) * 1.113195e5

other people code
Calculate the speed from two longitude and latitude GPS coordinates

def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great circle distance in kilometers between two points
    on the earth (specified in decimal degrees)
    """
    # convert decimal degrees to radians
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])

    # haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a))
    r = 6371 # Radius of earth in kilometers. Use 3956 for miles. Determines return value units.
    return c * r

prev_data = None

while 1:
    line = ser.readline().decode('UTF-8')
    splitline = line.split(',')

    if splitline[0] == '$GPGGA':
        msg = line
        data = pynmea2.parse(msg)
        if prev_data is not None:
            distance = haversine(data.longitude, data.latitude, prev_data.longitude, prev_data.latitude)
            print('distance', distance)
            print('speed', round(distance*3600, 2))
        prev_data = data

get the previous_lat,lon and  current_lat, lon, then caculate the speed each 0.1s. moreover, save the file as csv than compare with vehicle.velocity(get from IMU)


问:
Dynamic galleries with PhotoSwipe
I'm initiating PhotoSwipe per the documentation:

```<code>const lightbox = new PhotoSwipeLightbox({
    gallery: '#gallery1',
    children: '.pswp-gallery__item',
    pswpModule: () => import('/static/photoswipe/photoswipe.esm.js'),
});
</code>```

It works just fine, however some of my gallery names are dynamically generated.

Each gallery has their own pictures to browse through, so I don't want to repeat #gallery1 or use a class.

Besides dynamically repeating the initialization function, is there an elegant way to allow PhotoSwipe to work on all galleries on the page (#gallery_1, #gallery_2, #gallery_3, #gallery_n)?

Title: Dynamic galleries with PhotoSwipe

Body:
I'm initiating PhotoSwipe per the documentation:

const lightbox = new PhotoSwipeLightbox({
    gallery: '#gallery1',
    children: '.pswp-gallery__item',
    pswpModule: () => import('/static/photoswipe/photoswipe.esm.js'),
});

It works just fine, however some of my gallery names are dynamically generated.

Each gallery has their own pictures to browse through, so I don't want to repeat #gallery1 or use a class.

Besides dynamically repeating the initialization function, is there an elegant way to allow PhotoSwipe to work on all galleries on the page (#gallery_1, #gallery_2, #gallery_3, #gallery_n)?


问:
Why a basic unreferenced c++ function does not get optimized away?
Consider this simple code:

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

extern "C"
{
    void p4nenc256v32();
    void p4ndec256v32();
}

void bigFunctionTest()
{
    p4nenc256v32();
    p4ndec256v32();
}

int main()
{
    printf("hello\n");
}
</code>```

Code size of those p4nenc256v32/p4ndec256v32 functions is significant, roughly 1.5MB. This binary size when compiled with latest VS2022 with optimizations enabled is 1.5MB. If I comment out that unused bigFunctionTest function then resulting binary is smaller by 1.4MB. Any ideas why would this clearly unused function wouldn't be eliminated by compiler and/or linker in release builds? By default, VS2022 in release uses /Gy and /OPT:REF.
I also tried mingw64 (gcc 12.2) with -fdata-sections -ffunction-sections -Wl,--gc-sections and results were much worse: when compiled with that dummy function exe grew by 5.2MB. Seem like ms and gcc compilers agree that for some reason these functions cannot be removed.

I created a working sample project that shows the issue: https://github.com/pps83/TestLinker.git (make sure to pull submodules as well) and filled an issue with VS issue tracker: Linker doesn't eliminate correctly dead code, however, I think I might get better explanation from SO users explaining what might be the reason for the problem.

Body:
Consider this simple code:

#include <stdio.h>

extern "C"
{
    void p4nenc256v32();
    void p4ndec256v32();
}

void bigFunctionTest()
{
    p4nenc256v32();
    p4ndec256v32();
}

int main()
{
    printf("hello\n");
}

Code size of those p4nenc256v32/p4ndec256v32 functions is significant, roughly 1.5MB. This binary size when compiled with latest VS2022 with optimizations enabled is 1.5MB. If I comment out that unused bigFunctionTest function then resulting binary is smaller by 1.4MB. Any ideas why would this clearly unused function wouldn't be eliminated by compiler and/or linker in release builds? By default, VS2022 in release uses /Gy and /OPT:REF.
I also tried mingw64 (gcc 12.2) with -fdata-sections -ffunction-sections -Wl,--gc-sections and results were much worse: when compiled with that dummy function exe grew by 5.2MB. Seem like ms and gcc compilers agree that for some reason these functions cannot be removed.

I created a working sample project that shows the issue: https://github.com/pps83/TestLinker.git (make sure to pull submodules as well) and filled an issue with VS issue tracker: Linker doesn't eliminate correctly dead code, however, I think I might get better explanation from SO users explaining what might be the reason for the problem.


问:
Is there a possibility to plot interactive scatter plot in matplotlib?
Let's consider very simple data:

```<code>x = [1, 2, 3]
y = [2, 3, 4]
</code>```

To make a plot of this data we just need to run this banal command:

```<code>import matplotlib.pyplot as plt`
plt.plot(x, y, "o")
plt.show()
</code>```

The output of this code is a simple graph. However, my desired graph would be the one, that I can point with a mouse cursor to the point at the graph, and it will tell me its coordinates.

For example, if I point with the mouse cursor at the left bottom corner point, I would like to have next to it the information (1, 2), and if I point with the mouse cursor to the right bottom corner point, I would like to get (3, 4). It is possible to achieve it in matplotlib?

Body:
Let's consider very simple data:

x = [1, 2, 3]
y = [2, 3, 4]

To make a plot of this data we just need to run this banal command:

import matplotlib.pyplot as plt`
plt.plot(x, y, "o")
plt.show()

The output of this code is a simple graph. However, my desired graph would be the one, that I can point with a mouse cursor to the point at the graph, and it will tell me its coordinates.

For example, if I point with the mouse cursor at the left bottom corner point, I would like to have next to it the information (1, 2), and if I point with the mouse cursor to the right bottom corner point, I would like to get (3, 4). It is possible to achieve it in matplotlib?


问:
Slicing MediaRecorder stream bytes in Python WebSocket produces invalid data when found processing input from FFmpeg
I have a WebSocket created using Python WebSocket.
I have a JS client.

The client uses .getUserMedia to capture only audio stream. The client uses MediaRecorder(stream), and .ondataavailable to send the WebSocket a message as a blob.

WebSocket receives the message successfully using message = websocket.recv(), and I am able to write the received audio bytes to a wav file by extending a list.

```<code>audio_bytes.extend(message)
if len(audio_bytes) > 20000:
   by = io.BytesIO(bytes(audio_bytes))
   sound = AudioSegment.from_file(by).export('new_sample.wav', format='wav')
</code>```

Works fine.

However, I don't want to keep all the bytes in a list for the duration of running this script.

When I clear the list and extend the bytes as before, not picking up the stream from the start causes an issue, or if I slice the original list and try to write to a WAV file using the same method as before.

```<code>audio_bytes.extend(message)
if len(audio_bytes) > 20000:
   audio_bytes2 = audio_bytes[3000:12000]
   by = io.BytesIO(bytes(audio_bytes2))
   sound = AudioSegment.from_file(by).export('new_sample2.wav', format='wav')
</code>```

I want to be able to basically clear the list after the length reaches > 20000, and use y, sr = librosa.load('new_sample.wav'), do further analysis and repeat.

I'm not very experienced in working with audio. I know the headers take up a certain amount of bytes at the start (around 54?).

I stored the first 1000 elements of the list in a header variable header = audio_bytes[:1000] from the first message received in the WebSocket, and extended this header to the new list I created when the length of message received reaches > 20000.

I tested this, and although the first 1000 bytes stayed the same, I was still receiving from FFmpeg:

Invalid data found when processing input

I have also written the bytes directly to a .txt file and loaded the .txt file directly with librosa, again, successful when its the full stream but if I chunk the stream and try to load a chunk at the end, librosa gives the error

Format not recognised

Body:
I have a WebSocket created using Python WebSocket.
I have a JS client.

The client uses .getUserMedia to capture only audio stream. The client uses MediaRecorder(stream), and .ondataavailable to send the WebSocket a message as a blob.

WebSocket receives the message successfully using message = websocket.recv(), and I am able to write the received audio bytes to a wav file by extending a list.

audio_bytes.extend(message)
if len(audio_bytes) > 20000:
   by = io.BytesIO(bytes(audio_bytes))
   sound = AudioSegment.from_file(by).export('new_sample.wav', format='wav')

Works fine.

However, I don't want to keep all the bytes in a list for the duration of running this script.

When I clear the list and extend the bytes as before, not picking up the stream from the start causes an issue, or if I slice the original list and try to write to a WAV file using the same method as before.

audio_bytes.extend(message)
if len(audio_bytes) > 20000:
   audio_bytes2 = audio_bytes[3000:12000]
   by = io.BytesIO(bytes(audio_bytes2))
   sound = AudioSegment.from_file(by).export('new_sample2.wav', format='wav')

I want to be able to basically clear the list after the length reaches > 20000, and use y, sr = librosa.load('new_sample.wav'), do further analysis and repeat.

I'm not very experienced in working with audio. I know the headers take up a certain amount of bytes at the start (around 54?).

I stored the first 1000 elements of the list in a header variable header = audio_bytes[:1000] from the first message received in the WebSocket, and extended this header to the new list I created when the length of message received reaches > 20000.

I tested this, and although the first 1000 bytes stayed the same, I was still receiving from FFmpeg:

Invalid data found when processing input

I have also written the bytes directly to a .txt file and loaded the .txt file directly with librosa, again, successful when its the full stream but if I chunk the stream and try to load a chunk at the end, librosa gives the error

Format not recognised


问:
Flutter Apple SignIn not returning the required credentials
the_apple_sign_in

I am using this package for sign in with apple. I am successfully complete auth process. But i cant receive credential info (like a display name, email etc.). I already tried remove app from Pass and Secure settings.

My signInMethod

```<code>Future signInWithApple({List<Scope> scopes = const [], required context}) async {
    showLoading(context);

    final result = await TheAppleSignIn.performRequests([AppleIdRequest(requestedScopes: scopes)]).then((result) {
      hideLoading(context);
      return result;
    });
    switch (result.status) {
      case AuthorizationStatus.authorized:
        final appleIdCredential = result.credential!;
        final oAuthProvider = OAuthProvider('apple.com');
        final credential = oAuthProvider.credential(
          idToken: String.fromCharCodes(appleIdCredential.identityToken!),
          accessToken: String.fromCharCodes(appleIdCredential.authorizationCode!),
        );
        final userCredential = await _auth.signInWithCredential(credential);
        final firebaseUser = userCredential.user!;
        if (scopes.contains(Scope.fullName)) {
          final fullName = appleIdCredential.fullName;
          if (fullName != null && fullName.givenName != null && fullName.familyName != null) {
            final displayName = '${fullName.givenName} ${fullName.familyName}';
            await firebaseUser.updateDisplayName(displayName);
          }
        }
        debugPrint(Scope.fullName.toString());
        debugPrint(Scope.email.toString());
        debugPrint(firebaseUser.displayName);
        debugPrint(firebaseUser.email);
        debugPrint(result.credential!.email);
        debugPrint(result.credential!.user);
        debugPrint(result.credential!.fullName.toString());
        debugPrint('${appleIdCredential.email}CREDENITAL EMAIL');
        debugPrint('Apple User UID => ${userCredential.user!.uid}');
        debugPrint('Apple User Name => ${userCredential.user!.displayName}');
        debugPrint('Apple User E-Mail => ${userCredential.user!.email}');
        debugPrint('Apple User Number => ${userCredential.user!.phoneNumber}');
        debugPrint('Apple User Photo URL => ${userCredential.user!.photoURL}');
        return firebaseUser;
      case AuthorizationStatus.error:
        return null;
      case AuthorizationStatus.cancelled:
        return null;
      default:
        return null;
    }
  }
</code>```

Body:
the_apple_sign_in

I am using this package for sign in with apple. I am successfully complete auth process. But i cant receive credential info (like a display name, email etc.). I already tried remove app from Pass and Secure settings.

My signInMethod

Future signInWithApple({List<Scope> scopes = const [], required context}) async {
    showLoading(context);

    final result = await TheAppleSignIn.performRequests([AppleIdRequest(requestedScopes: scopes)]).then((result) {
      hideLoading(context);
      return result;
    });
    switch (result.status) {
      case AuthorizationStatus.authorized:
        final appleIdCredential = result.credential!;
        final oAuthProvider = OAuthProvider('apple.com');
        final credential = oAuthProvider.credential(
          idToken: String.fromCharCodes(appleIdCredential.identityToken!),
          accessToken: String.fromCharCodes(appleIdCredential.authorizationCode!),
        );
        final userCredential = await _auth.signInWithCredential(credential);
        final firebaseUser = userCredential.user!;
        if (scopes.contains(Scope.fullName)) {
          final fullName = appleIdCredential.fullName;
          if (fullName != null && fullName.givenName != null && fullName.familyName != null) {
            final displayName = '${fullName.givenName} ${fullName.familyName}';
            await firebaseUser.updateDisplayName(displayName);
          }
        }
        debugPrint(Scope.fullName.toString());
        debugPrint(Scope.email.toString());
        debugPrint(firebaseUser.displayName);
        debugPrint(firebaseUser.email);
        debugPrint(result.credential!.email);
        debugPrint(result.credential!.user);
        debugPrint(result.credential!.fullName.toString());
        debugPrint('${appleIdCredential.email}CREDENITAL EMAIL');
        debugPrint('Apple User UID => ${userCredential.user!.uid}');
        debugPrint('Apple User Name => ${userCredential.user!.displayName}');
        debugPrint('Apple User E-Mail => ${userCredential.user!.email}');
        debugPrint('Apple User Number => ${userCredential.user!.phoneNumber}');
        debugPrint('Apple User Photo URL => ${userCredential.user!.photoURL}');
        return firebaseUser;
      case AuthorizationStatus.error:
        return null;
      case AuthorizationStatus.cancelled:
        return null;
      default:
        return null;
    }
  }


问:
I have a hyperspectral data set of size : (272, 512, 16) and I am trying to get the RGB images
I have a hyperspectral dataset of size (272, 512, 16)  where 16 is the number of bands, the idea is I want to generate the RGB images form those hyperspectral but the problem is I have tried so many codes but nothing is working with me .

this is my code to read the hyperspectral data

```<code>d2    = io.loadmat('/content/drive/MyDrive/OtherCube/Melt2.mat')
d2= d2['DataCubeC']
D2 =d2.astype(np.float32)
pc= hsi.principal_components(D2)
plt.title('Principal components')
plt.imshow(pc)
plt.axis('off')

And after this step I need to regenerate the rgb image
</code>```

I have tried so many codes but because the shape of my data is different so nothing was working with me

Body:
I have a hyperspectral dataset of size (272, 512, 16)  where 16 is the number of bands, the idea is I want to generate the RGB images form those hyperspectral but the problem is I have tried so many codes but nothing is working with me .

this is my code to read the hyperspectral data

d2    = io.loadmat('/content/drive/MyDrive/OtherCube/Melt2.mat')
d2= d2['DataCubeC']
D2 =d2.astype(np.float32)
pc= hsi.principal_components(D2)
plt.title('Principal components')
plt.imshow(pc)
plt.axis('off')

And after this step I need to regenerate the rgb image

I have tried so many codes but because the shape of my data is different so nothing was working with me


问:
How does parent process CPU/Memory limitation work?
When you set a cpu limitation for a process and that process creates several other child processes, as the child processes increase their CPU-shares, do the CPU-shares of the parent process increase as well ?

The same question would go for memory. Although, memory is different as far as I am concerned since I've learned that each process has its own heap. Would it then be correct to say that the memory limitation of a process isn't influenced by the amount of memory its child processes use ?


问:
In R/Shiny click on images change tabpanels bellow
Bellow is my code:
I need to click on image 1 change to tabpanel 1, when I click on image 2 tabpanel 2 is selected, clicking on image 3 tabpanel 3 is selected and so on...

```<code>ui <- fluidPage(
  img(id="my_img1",src="img/hexsticker.png",style="cursor:pointer;", value  = 1),
  img(id="my_img2",src="img/hexsticker.png",style="cursor:pointer;", value  = 2),
  div(style = 'display: flex; gap: 5em; width: 500px; justify-content: space-between;',
  tabsetPanel(id="navbar1",
              tabPanel("tab1", p("This is tab 1"), value = 1),
              tabPanel("tab2", p("This is tab 2"), value = 2)
  )
  )

)

server <- function(input, output,session){

  observeEvent(input$my_img1,
               {
                 updateTabsetPanel(session,
                                   inputId = 'navbar1',
                                   selected = input$navbar1)

               })
}

shinyApp(ui,server)
</code>```

I know that I can do this with shinyjs package but I need to do this with basic shiny's. Is it possible?

Body:
Bellow is my code:
I need to click on image 1 change to tabpanel 1, when I click on image 2 tabpanel 2 is selected, clicking on image 3 tabpanel 3 is selected and so on...

ui <- fluidPage(
  img(id="my_img1",src="img/hexsticker.png",style="cursor:pointer;", value  = 1),
  img(id="my_img2",src="img/hexsticker.png",style="cursor:pointer;", value  = 2),
  div(style = 'display: flex; gap: 5em; width: 500px; justify-content: space-between;',
  tabsetPanel(id="navbar1",
              tabPanel("tab1", p("This is tab 1"), value = 1),
              tabPanel("tab2", p("This is tab 2"), value = 2)
  )
  )

)

server <- function(input, output,session){

  observeEvent(input$my_img1,
               {
                 updateTabsetPanel(session,
                                   inputId = 'navbar1',
                                   selected = input$navbar1)

               })
}

shinyApp(ui,server)

I know that I can do this with shinyjs package but I need to do this with basic shiny's. Is it possible?


问:
How to export a PuTTY key .ppk to an OpenSSH key using C#?
There is a C# program that works with SSH connection. It works with clients who use .ppk keys generated by PuTTY. However, the library SSH.NET works only with OpenSSH keys.
Of course, you can use puttygen, but it would be too difficult for users. I would like to do the same thing that puttygen does, but inside my program.

I probably need to understand the structure of RSA in more detail. I will be glad if you can advise useful resources.


问:
RollupError: "XhrIo" is not exported by "node_modules/@firebase/webchannel- wrapper/dist/index.js"
Here's the complete error message :

```<code>[!] RollupError: "XhrIo" is not exported by "node_modules/@firebase/webchannel-
wrapper/dist/index.js", imported by "node_modules/@firebase/firestore/dist/index.esm2017.js"
</code>```

I am using rollup (3.8.1) to bundle my TypeScript webapp. My webapp uses firebase (9.15.0).

But as you can see when I try to bundle, firestore esm index tries to import an object from @firebase/webchannel-wrapper which resolves to the main index and not the module-typed one.

Looking into @firebase/webchannel-wrapper/package.json :

  "main": "dist/index.js",
  "module": "dist/index.esm2017.js",
  "esm5": "dist/index.esm.js",
```
<p>Nothing's wrong with the value of "module", so my guess is that the problem is in rollup (or <code>@rollup/plugin-node-resolve</code>) resolution function.</p>
<p>I tried different things but I can't find the problem.</p>
<p>My app doesn't do anything fancy yet :</p>
<pre class="lang-js prettyprint-override"><code>import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'

...

// Initialize Firebase
export const firebaseApp = initializeApp(firebaseConfig)
export const db = getFirestore(firebaseApp)
</code>```

My tsconfig.json :

  "target": "es2022",
  "module": "esnext",
  "moduleResolution": "node"
```

Body:
Here's the complete error message :

[!] RollupError: "XhrIo" is not exported by "node_modules/@firebase/webchannel-
wrapper/dist/index.js", imported by "node_modules/@firebase/firestore/dist/index.esm2017.js"

I am using rollup (3.8.1) to bundle my TypeScript webapp. My webapp uses firebase (9.15.0).

But as you can see when I try to bundle, firestore esm index tries to import an object from @firebase/webchannel-wrapper which resolves to the main index and not the module-typed one.

Looking into @firebase/webchannel-wrapper/package.json :

  "main": "dist/index.js",
  "module": "dist/index.esm2017.js",
  "esm5": "dist/index.esm.js",

Nothing's wrong with the value of "module", so my guess is that the problem is in rollup (or @rollup/plugin-node-resolve) resolution function.

I tried different things but I can't find the problem.

My app doesn't do anything fancy yet :

import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'

...

// Initialize Firebase
export const firebaseApp = initializeApp(firebaseConfig)
export const db = getFirestore(firebaseApp)

My tsconfig.json :

  "target": "es2022",
  "module": "esnext",
  "moduleResolution": "node"


问:
How do I fix "undefined reference" errors in my Qt-Creator project while linking the ffmpeg library "libav"?
I'm currently trying to use the libav library from FFmpeg in my Qt-Creator project, but I get over a thousand "undefined reference to ..." errors and I have no idea what I'm doing wrong. The errors don't depend on the actual code, because I changed it a few times, but as long as I use methods of the library these errors occur.
I have also tried to run the code in Visual Studio and that worked.

My project-file looks like this:

```<code>QT -= gui

CONFIG += c++11 console
CONFIG -= app_bundle

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0
INCLUDEPATH += D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\include

SOURCES += \
    Main.cpp

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

QMAKE_CXXFLAGS += -D__STDC_CONSTANT_MACROS

LIBS += -lMfuuid
LIBS += -lStrmiids
LIBS += -lMfplat
LIBS += -lBcrypt
LIBS += -lSecur32
LIBS += -lWs2_32
LIBS += -pthread
LIBS += -L"D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib"
LIBS += -lavdevice
LIBS += -lavfilter
LIBS += -lavformat
LIBS += -lavcodec
LIBS += -lswresample
LIBS += -lswscale
LIBS += -lavutil

HEADERS += \
    wrapper.h
</code>```

The library files are stored at D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib. The errors I get when running the program look something like this (extract).

```<code>:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/aviobuf.o):(.text$mn+0x16): undefined reference to `__security_cookie'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/aviobuf.o):(.xdata[$unwind$ff_read_string_to_bprint_overwrite]+0x1c): more undefined references to `__GSHandlerCheck' follow
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/4xm.o):(.text$mn+0x250): undefined reference to `__security_check_cookie'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.text$mn+0x2fe): undefined reference to `sscanf'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.text$mn+0x33f): undefined reference to `sscanf'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.text$mn+0x65b): undefined reference to `__report_rangecheckfailure'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.text$mn+0x18): undefined reference to `__security_cookie'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.text$mn+0x97): undefined reference to `__security_check_cookie'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.text$mn+0x14d): undefined reference to `__report_rangecheckfailure'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.xdata[$unwind$yuv4_read_header]+0x20): undefined reference to `__GSHandlerCheck'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.xdata[$unwind$yuv4_read_packet]+0x18): undefined reference to `__GSHandlerCheck'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/xwma.o):(.text$mn+0x14): undefined reference to `__security_cookie'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/xwma.o):(.text$mn+0x2e0): undefined reference to `__security_check_cookie'
...
</code>```

Is a library missing? Am I including the lMfuuid, Strmiids, Mfplat, etc. the wrong way? If you have any idea I would be very grateful. I'm really confused. I'm using the MinGW64 compiler.

Body:
I'm currently trying to use the libav library from FFmpeg in my Qt-Creator project, but I get over a thousand "undefined reference to ..." errors and I have no idea what I'm doing wrong. The errors don't depend on the actual code, because I changed it a few times, but as long as I use methods of the library these errors occur.
I have also tried to run the code in Visual Studio and that worked.

My project-file looks like this:

QT -= gui

CONFIG += c++11 console
CONFIG -= app_bundle

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0
INCLUDEPATH += D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\include

SOURCES += \
    Main.cpp

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

QMAKE_CXXFLAGS += -D__STDC_CONSTANT_MACROS

LIBS += -lMfuuid
LIBS += -lStrmiids
LIBS += -lMfplat
LIBS += -lBcrypt
LIBS += -lSecur32
LIBS += -lWs2_32
LIBS += -pthread
LIBS += -L"D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib"
LIBS += -lavdevice
LIBS += -lavfilter
LIBS += -lavformat
LIBS += -lavcodec
LIBS += -lswresample
LIBS += -lswscale
LIBS += -lavutil

HEADERS += \
    wrapper.h

The library files are stored at D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib. The errors I get when running the program look something like this (extract).

:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/aviobuf.o):(.text$mn+0x16): undefined reference to `__security_cookie'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/aviobuf.o):(.xdata[$unwind$ff_read_string_to_bprint_overwrite]+0x1c): more undefined references to `__GSHandlerCheck' follow
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/4xm.o):(.text$mn+0x250): undefined reference to `__security_check_cookie'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.text$mn+0x2fe): undefined reference to `sscanf'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.text$mn+0x33f): undefined reference to `sscanf'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.text$mn+0x65b): undefined reference to `__report_rangecheckfailure'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.text$mn+0x18): undefined reference to `__security_cookie'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.text$mn+0x97): undefined reference to `__security_check_cookie'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.text$mn+0x14d): undefined reference to `__report_rangecheckfailure'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.xdata[$unwind$yuv4_read_header]+0x20): undefined reference to `__GSHandlerCheck'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/yuv4mpegdec.o):(.xdata[$unwind$yuv4_read_packet]+0x18): undefined reference to `__GSHandlerCheck'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/xwma.o):(.text$mn+0x14): undefined reference to `__security_cookie'
:-1: Fehler: D:\Programme\ffmpeg-source\ffmpeg-5.1.2\vs2019_build\lib/libavformat.a(libavformat/xwma.o):(.text$mn+0x2e0): undefined reference to `__security_check_cookie'
...

Is a library missing? Am I including the lMfuuid, Strmiids, Mfplat, etc. the wrong way? If you have any idea I would be very grateful. I'm really confused. I'm using the MinGW64 compiler.


问:
(node:1928) UnhandledPromiseRejectionWarning: MongooseError: Operation `users.createIndex()` buffering timed out
Getting the following error when I tried to estalish connection to my MongoDB Atlas.

```<code>[nodemon] starting `node index.js`
Note-It backend listening at http://localhost:5000
(node:1928) UnhandledPromiseRejectionWarning: MongooseError: Operation `users.createIndex()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:\Users\Meet\OneDrive\Desktop\note-it-backend-api\backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:149:23)
    at listOnTimeout (internal/timers.js:557:17)
    at processTimers (internal/timers.js:500:7)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:1928) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1928) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
***********************Connected to MongoDB successfully***********************
</code>```

I cant make any HTTP requests because of this

The db.js contents are :

```<code>const mongoose = require('mongoose');

// Connection string for MongoDB ATLAS
const mongoURL = "mongodb+srv://new-meeti:<password>@meet-dev.cc0qw.mongodb.net/?retryWrites=true&w=majority"

const connectToMongo = () => {
    // .connect method taks 2 args, 2nd one is a callback function
    mongoose.connect(mongoURL, () => {
        console.log("***********************Connected to MongoDB successfully***********************");
    })
}

module.exports = connectToMongo;
</code>```

This was more than a year old project hosted on heroku but then I had to shift to to some other hosting service so again deploying is getting problematic due to various deprecation issues I think.
A help would be really appreciated. Thanks :)

PS : I checked my Network access on the MongoDB Atlas and 0.0.0.0/0  (includes your current IP address) is active.

Body:
Getting the following error when I tried to estalish connection to my MongoDB Atlas.

[nodemon] starting `node index.js`
Note-It backend listening at http://localhost:5000
(node:1928) UnhandledPromiseRejectionWarning: MongooseError: Operation `users.createIndex()` buffering timed out after 10000ms
    at Timeout.<anonymous> (C:\Users\Meet\OneDrive\Desktop\note-it-backend-api\backend\node_modules\mongoose\lib\drivers\node-mongodb-native\collection.js:149:23)
    at listOnTimeout (internal/timers.js:557:17)
    at processTimers (internal/timers.js:500:7)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:1928) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1928) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
***********************Connected to MongoDB successfully***********************

I cant make any HTTP requests because of this

The db.js contents are :

const mongoose = require('mongoose');

// Connection string for MongoDB ATLAS
const mongoURL = "mongodb+srv://new-meeti:<password>@meet-dev.cc0qw.mongodb.net/?retryWrites=true&w=majority"

const connectToMongo = () => {
    // .connect method taks 2 args, 2nd one is a callback function
    mongoose.connect(mongoURL, () => {
        console.log("***********************Connected to MongoDB successfully***********************");
    })
}

module.exports = connectToMongo;

This was more than a year old project hosted on heroku but then I had to shift to to some other hosting service so again deploying is getting problematic due to various deprecation issues I think.
A help would be really appreciated. Thanks :)

PS : I checked my Network access on the MongoDB Atlas and 0.0.0.0/0  (includes your current IP address) is active.


问:
Reflect database change in UI table immediately using .NET Core with Entity Framework
When running the application in a multiuser environment, changes made by one user i.e modifying, adding or deleting records, are not seen by other users until they refresh the page.

What is the best way of doing it?

Thanks.

As for now, I have tried refresh the page automatically every 3 minutes, but I'm looking for a better solution.

```<code>Response.Headers.Add("Refresh","180");
</code>```

Body:
When running the application in a multiuser environment, changes made by one user i.e modifying, adding or deleting records, are not seen by other users until they refresh the page.

What is the best way of doing it?

Thanks.

As for now, I have tried refresh the page automatically every 3 minutes, but I'm looking for a better solution.

Response.Headers.Add("Refresh","180");


问:
How can I solve "NoSuchMethodError: The method "[]" was called on null."
gamelist is a String List of document names in the collection.
The questionMap value is an array named text field obtained from the firestore document using the gamelist value as key. I would like to update the questionMap when I press the pass button, but when I press the pass button, I get an error like the one in the title, and the map does not seem to be rewritten properly. It is a dirty code, but I would like to know how to solve it.

This is my code:

class PlayPage extends StatefulWidget {
  List gameList;
  Map questionMap;
  String category;
  int myScore;

  PlayPage({
    required this.gameList,
    required this.category,
    required this.myScore,
    required this.questionMap,
  });

  @override
  State<PlayPage> createState() => _PlayPageState();
}

class _PlayPageState extends State<PlayPage> {
  int quizNumber = 0;
  int listNumber = 0;
  var db = FirebaseFirestore.instance;

  void changeQuiz() {
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Stack(
        children: [
          Card(
            child: SizedBox(
              height: double.infinity,
              child: SingleChildScrollView(
                child: Padding(
                  padding: const EdgeInsets.only(
                      top: 20, bottom: 200, left: 20, right: 20),
                  child: Text(
                    widget.questionMap[widget.gameList[listNumber]][quizNumber],
                    style: const TextStyle(fontSize: 20),
                  ),
                ),
              ),
            ),
          ),
          Positioned(
            right: 10,
            bottom: 30,
            child: Column(
              children: [
                ElevatedButton(
                  child: const Text(
                    "Pass",
                    style: TextStyle(fontSize: 30),
                  ),
                  onPressed: () {
                    listNumber += 1;
                    quizNumber = 0;
                    setState(
                      () {
                        var docRef = db
                            .collection(widget.category)
                            .doc(widget.gameList[listNumber]);
                        docRef.get().then(
                          (DocumentSnapshot doc) {
                            var data = doc.data() as Map<String, dynamic>;
                            List questions = selectQuiz(
                              data["text"],
                            );
                            widget.questionMap = {
                              widget.gameList[listNumber]: questions
                            };
                            print(widget.questionMap);
                          },
                        );
                      },
                    );
                  },
                ),
                const SizedBox(height: 30),
                SizedBox(
                  width: 70,
                  height: 70,
                  child: FloatingActionButton(
                    backgroundColor:
                        (quizNumber < 9) ? Colors.teal : Colors.grey,
                    child: const Icon(
                      Icons.arrow_forward,
                      size: 35,
                    ),
                    onPressed: () {
                      if (quizNumber < 9) {
                        setState(
                          () {
                            quizNumber += 1;
                          },
                        );
                      }
                    },
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
```


问:
Transformer Model isn't fitting well on Time Series Data
I have created two models LSTM, LSTM with Self-Attention. Now I am working on to create my first transformer model. I created it for multivariate time series predictions (many-to-one classification model).

I have the hourly varying data i.e., 8 different features (hour, month, temperature, humidity, windspeed, solar radiations concentration etc.) and with them I am trying to predict the time sequence (energy consumption of a building. So my input has the shape X.shape = (8783, 168, 8) i.e., 8783 time sequences, each sequence contains 168 hourly entries/vectors and each vector contains 8 features. My output has the shape Y.shape = (8783,1) i.e., 8783 sequences each containing 1 output value (i.e., building energy consumption value after every hour).

I took as a model an example from the official keras site. It is created for classification problems, I converted my output to classes  n_classes = len(np.unique(Y_train)) = 156
Input shape (X_train) = (8783, 168, 8) Output shape (Y_train) = (8783,1) n_classes = 156
In the softmax activation layer, I set the output to n_classes but it's not fitting well. Below I attach the model and I would like to know:

I)- Have I done something wrong in the model? Is the model architecture is fine? Are there maybe some other parts of the code I need to change for it to work for my problem?

II)- Also, can a transformer at all work on multivariate problems of my kind (8 features input, 1 feature output) or do transformers only work on univariate problems?

```<code>
def build_transformer_model(input_shape, head_size, num_heads, ff_dim, num_transformer_blocks,
                            mlp_units, dropout=0, mlp_dropout=0):

    inputs = keras.Input(shape=input_shape)
    x = inputs
    for _ in range(num_transformer_blocks):

        # Normalization and Attention
        x = layers.LayerNormalization(epsilon=1e-6)(x)
        x = layers.MultiHeadAttention(
            key_dim=head_size, num_heads=num_heads, dropout=dropout
        )(x, x)
        x = layers.Dropout(dropout)(x)
        res = x + inputs

        # Feed Forward Part
        x = layers.LayerNormalization(epsilon=1e-6)(res)
        x = layers.Conv1D(filters=ff_dim, kernel_size=1, activation="relu")(x)
        x = layers.Dropout(dropout)(x)
        x = layers.Conv1D(filters=inputs.shape[-1], kernel_size=1)(x)
        x = x + res

    x = layers.GlobalAveragePooling1D(data_format="channels_first")(x)
    for dim in mlp_units:
        x = layers.Dense(dim, activation="relu")(x)
        x = layers.Dropout(mlp_dropout)(x)
    x = layers.Dense(n_classes, activation="softmax")(x)
    return keras.Model(inputs, x)

model_tr = build_transformer_model(input_shape=(X_train.shape[1], X_train.shape[2]), head_size=256,
                                   num_heads=4, ff_dim=4, num_transformer_blocks=4, mlp_units=[128], mlp_dropout=0.4, dropout=0.2)
model_tr.compile(loss="sparse_categorical_crossentropy",
    optimizer=keras.optimizers.Adam(learning_rate=0.0001),
    metrics=["sparse_categorical_accuracy"],
)
plot_model(model_tr, to_file='model_plot.png', show_shapes=True, show_layer_names=True)
model_tr.summary()
m_tr_history = model_tr.fit(x=X_train, y=Y_train, validation_split=0.15, batch_size=64, epochs=100, verbose = 1)
model_tr.save('halka_transformer.h5')
</code>```

No. of epochs

Thanks in advance for this valuable assistance.

Body:
I have created two models LSTM, LSTM with Self-Attention. Now I am working on to create my first transformer model. I created it for multivariate time series predictions (many-to-one classification model).

I have the hourly varying data i.e., 8 different features (hour, month, temperature, humidity, windspeed, solar radiations concentration etc.) and with them I am trying to predict the time sequence (energy consumption of a building. So my input has the shape X.shape = (8783, 168, 8) i.e., 8783 time sequences, each sequence contains 168 hourly entries/vectors and each vector contains 8 features. My output has the shape Y.shape = (8783,1) i.e., 8783 sequences each containing 1 output value (i.e., building energy consumption value after every hour).

I took as a model an example from the official keras site. It is created for classification problems, I converted my output to classes  n_classes = len(np.unique(Y_train)) = 156
Input shape (X_train) = (8783, 168, 8) Output shape (Y_train) = (8783,1) n_classes = 156
In the softmax activation layer, I set the output to n_classes but it's not fitting well. Below I attach the model and I would like to know:

I)- Have I done something wrong in the model? Is the model architecture is fine? Are there maybe some other parts of the code I need to change for it to work for my problem?

II)- Also, can a transformer at all work on multivariate problems of my kind (8 features input, 1 feature output) or do transformers only work on univariate problems?

def build_transformer_model(input_shape, head_size, num_heads, ff_dim, num_transformer_blocks,
                            mlp_units, dropout=0, mlp_dropout=0):

    inputs = keras.Input(shape=input_shape)
    x = inputs
    for _ in range(num_transformer_blocks):

        # Normalization and Attention
        x = layers.LayerNormalization(epsilon=1e-6)(x)
        x = layers.MultiHeadAttention(
            key_dim=head_size, num_heads=num_heads, dropout=dropout
        )(x, x)
        x = layers.Dropout(dropout)(x)
        res = x + inputs

        # Feed Forward Part
        x = layers.LayerNormalization(epsilon=1e-6)(res)
        x = layers.Conv1D(filters=ff_dim, kernel_size=1, activation="relu")(x)
        x = layers.Dropout(dropout)(x)
        x = layers.Conv1D(filters=inputs.shape[-1], kernel_size=1)(x)
        x = x + res

    x = layers.GlobalAveragePooling1D(data_format="channels_first")(x)
    for dim in mlp_units:
        x = layers.Dense(dim, activation="relu")(x)
        x = layers.Dropout(mlp_dropout)(x)
    x = layers.Dense(n_classes, activation="softmax")(x)
    return keras.Model(inputs, x)

model_tr = build_transformer_model(input_shape=(X_train.shape[1], X_train.shape[2]), head_size=256,
                                   num_heads=4, ff_dim=4, num_transformer_blocks=4, mlp_units=[128], mlp_dropout=0.4, dropout=0.2)
model_tr.compile(loss="sparse_categorical_crossentropy",
    optimizer=keras.optimizers.Adam(learning_rate=0.0001),
    metrics=["sparse_categorical_accuracy"],
)
plot_model(model_tr, to_file='model_plot.png', show_shapes=True, show_layer_names=True)
model_tr.summary()
m_tr_history = model_tr.fit(x=X_train, y=Y_train, validation_split=0.15, batch_size=64, epochs=100, verbose = 1)
model_tr.save('halka_transformer.h5')

No. of epochs

Thanks in advance for this valuable assistance.


问:
How to make laravel API localization structure
I'm using laravel-translatable.
I want to make something dynamic with the return in all Resources,
So when I receive Params like lang=fr it dynamically returns the fr translation.
But I want a way to do it in one place, not in every "Model - Controller - Resource".

I was thinking of making a class that will handle the logic and then implements it in every controller.


问:
Is there a way to set default empty string "" parameter in swagger - django rest framework?

I use drf-yasg to generate swagger documentation for my api.

I would want set empty "" string instead "string" as default. How can I do?

```<code>properties = {
        'type_operator': openapi.Schema(type=openapi.TYPE_INTEGER,  description="L'operatore di insieme AND(0) OR(1)"),
        'column_to_hide': openapi.Schema(type=openapi.TYPE_STRING,description="L'elenco di colonne da nascondere separato da virgola")
    }
</code>```

Body:
I use drf-yasg to generate swagger documentation for my api.

I would want set empty "" string instead "string" as default. How can I do?

properties = {
        'type_operator': openapi.Schema(type=openapi.TYPE_INTEGER,  description="L'operatore di insieme AND(0) OR(1)"),
        'column_to_hide': openapi.Schema(type=openapi.TYPE_STRING,description="L'elenco di colonne da nascondere separato da virgola")
    }