问:
Merging two DataFrames into one using a bitwise operator shows TypeError
I am creating my own projects in my portfolio. Currently, I analyse Football Transfer. I would like to filter TOP5 Leagues in the world, then do an analysis and visualise my data.

Firstly, I prepared lists with these leagues and countries:

```<code>League = ["Bundesliga","Premier League","LaLiga","Serie A","Ligue 1"]
Country = ["Germany" , "England", "Spain" , "Italy", "France"]
</code>```

Then, I passed these lists to my data frame by using isin() in order to see new filtered DataFrame:

```<code>Leagues = df_transfer_players[df_transfer_players['League Destination'].isin(League)]
Countries = df_transfer_players[df_transfer_players['Country Destination'].isin(Country)]
</code>```

Lastly, I checked each assigned variables whether it works or not. Luckily, It works:

Countries

League

Finally, I would like to merge these two into one DataFrame in order to groupby it and make analysis and visualisations.

According to this website https://www.geeksforgeeks.org/python-pandas-dataframe-isin/, I try to do it like this:

```<code>df_transfer_players[Leagues&Countries]
</code>```

Unfortunately, this output was displayed:

```<code>TypeError: ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''
</code>```

I tried to solve this problem. I browsed a lot of articles and I am not able to seek any advice how to tackle it.

Would you be so kind as to give me some advice in order to obtain data with both filter applied and mandatory?

答:
The bitwise & operator works on an element-wise basis on boolean arrays. Since Leagues and Countries are DataFrames comprised of non-boolean type columns (not boolean arrays or Series), python can't evaluate the expression: Leagues & Countries. If you convert each DataFrame to a boolean type, then you can use a bitwise operator on it. So

```<code>Leagues.astype(bool) & Countries.astype(bool)`
</code>```

works. But if you want to filter df_transfer_players for rows that satisfy both conditions, you can use a boolean mask as:

```<code>msk = df_transfer_players['League Destination'].isin(League) & df_transfer_players['Country Destination'].isin(Country)
out = df_transfer_players[msk]
</code>```

Here, both the left and right hand side of the & operator is a boolean Series (created by isin) so you can perform element-wise operation. This filters rows where the League Destination is one of the leagues in League and the Country Destination is one the countries in Country.

That being said, considering Bundesliga is in Germany, Premier League is in England, etc., Leagues is entirely contained in Countries, so I think there's no need for any concatenation here. Simply use Leagues DataFrame for your analysis. Note that Countries DataFrame also includes data from the Austrian Bundesliga, so they are not exactly the same.

Body:
I am creating my own projects in my portfolio. Currently, I analyse Football Transfer. I would like to filter TOP5 Leagues in the world, then do an analysis and visualise my data.

Firstly, I prepared lists with these leagues and countries:

League = ["Bundesliga","Premier League","LaLiga","Serie A","Ligue 1"]
Country = ["Germany" , "England", "Spain" , "Italy", "France"]

Then, I passed these lists to my data frame by using isin() in order to see new filtered DataFrame:

Leagues = df_transfer_players[df_transfer_players['League Destination'].isin(League)]
Countries = df_transfer_players[df_transfer_players['Country Destination'].isin(Country)]

Lastly, I checked each assigned variables whether it works or not. Luckily, It works:

Countries

League

Finally, I would like to merge these two into one DataFrame in order to groupby it and make analysis and visualisations.

According to this website https://www.geeksforgeeks.org/python-pandas-dataframe-isin/, I try to do it like this:

df_transfer_players[Leagues&Countries]

Unfortunately, this output was displayed:

TypeError: ufunc 'bitwise_and' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

I tried to solve this problem. I browsed a lot of articles and I am not able to seek any advice how to tackle it.

Would you be so kind as to give me some advice in order to obtain data with both filter applied and mandatory?

Body:
The bitwise & operator works on an element-wise basis on boolean arrays. Since Leagues and Countries are DataFrames comprised of non-boolean type columns (not boolean arrays or Series), python can't evaluate the expression: Leagues & Countries. If you convert each DataFrame to a boolean type, then you can use a bitwise operator on it. So

Leagues.astype(bool) & Countries.astype(bool)`

works. But if you want to filter df_transfer_players for rows that satisfy both conditions, you can use a boolean mask as:

msk = df_transfer_players['League Destination'].isin(League) & df_transfer_players['Country Destination'].isin(Country)
out = df_transfer_players[msk]

Here, both the left and right hand side of the & operator is a boolean Series (created by isin) so you can perform element-wise operation. This filters rows where the League Destination is one of the leagues in League and the Country Destination is one the countries in Country.

That being said, considering Bundesliga is in Germany, Premier League is in England, etc., Leagues is entirely contained in Countries, so I think there's no need for any concatenation here. Simply use Leagues DataFrame for your analysis. Note that Countries DataFrame also includes data from the Austrian Bundesliga, so they are not exactly the same.


来源: stackexchange

问:
ClientRPC method call in Mirror does not properly keep event references for other clients
I am testing a chat system between two clients using the Mirror library for Unity. On my Player object, I attached a script which stores an event that is supposed to be called via ClientRPC.

```<code>    public delegate void ReceivedChatMessageHandler(string message);
    public event ReceivedChatMessageHandler ChatMessageReceived;

    [Client]
    public void SendChatMessage(string message)
    {
        if (!Keyboard.current.enterKey.wasPressedThisFrame) return;
        if (string.IsNullOrWhiteSpace(message)) return;
        CmdSendMessage(message);
    }

    [Command]
    private void CmdSendMessage(string message)
    {
        RpcHandleMessage(message);
    }

    [ClientRpc]
    public void RpcHandleMessage(string message)
    {
        if (ChatMessageReceived != null)
        {
            ChatMessageReceived($"[Player]: {message}\n");
        }
    }
</code>```

Each player attaches an event handler to this event for their local UI, which is supposed to display the message in a chatbox. This works fine, and both players can send a message to the server, and it will pop up in their own chat (i.e. the event handlers are properly attached on both clients). However, for the client which did not send the message, ChatMessageReceived returns null, even though it is defined locally.

I looked around online, but could not really find any proper explanations as to why this happens. How can I properly pass an event generated through a ClientRPC on to other local objects which are not part of the Player GameObject itself?

Edit:
The Event Listener is attached via a Script attached to the player game object. On Start of this script, i.e. when the Player Game Object is spawned in, it will find the Chatbox game object and pass the ChatInterface script (seen above) of the local player to another script.

```<code>    public void Start()
    {
        if (!isLocalPlayer) return;

        GameObject.Find("Chat").GetComponent<Chatbox>().PlayerLoaded(this.gameObject.GetComponent<ChatInterface>());
    }
</code>```

The Chatbox script then attaches its own local method to the event handler.

```<code>    public void PlayerLoaded(ChatInterface chat)
    {
        this.chat = chat;
        chat.ChatMessageReceived += Receive;
    }
</code>```

As said, each client receives events they send on their own client just fine, but events from other clients cause the whole event to act as if no handler was defined on it.

答:
I now found an answer to my problem in an old Unity forum thread. The important part is this:

So if Player1 sends a command "CmdMoveForward" the command is executed
on the server only on the object that is accociated with Player1.
Likewise when the server calls a ClientRPC methhod RpcMovePlayer on
the object accociated with Player3, this method is called on all
clients on the Player3 object.

As I'm creating an event listener to the local player object, but the Client RPC is executed on the player object corresponding to the user which sent the Command to the server, the event listener is not attached to this event. This also explains why there is no problem for the client who sends the RPC, as their event listener is attached to the correct player object.

I've solved this issue now by turning my Chatbox Script into a Singleton, so that it can easily be called from any player object. Another option to preserve the event-based architecture would be to attach the listener to every player object in the scene.

ContentLicense: CC BY-SA 4.0

Body:
I am testing a chat system between two clients using the Mirror library for Unity. On my Player object, I attached a script which stores an event that is supposed to be called via ClientRPC.

    public delegate void ReceivedChatMessageHandler(string message);
    public event ReceivedChatMessageHandler ChatMessageReceived;

    [Client]
    public void SendChatMessage(string message)
    {
        if (!Keyboard.current.enterKey.wasPressedThisFrame) return;
        if (string.IsNullOrWhiteSpace(message)) return;
        CmdSendMessage(message);
    }

    [Command]
    private void CmdSendMessage(string message)
    {
        RpcHandleMessage(message);
    }

    [ClientRpc]
    public void RpcHandleMessage(string message)
    {
        if (ChatMessageReceived != null)
        {
            ChatMessageReceived($"[Player]: {message}\n");
        }
    }

Each player attaches an event handler to this event for their local UI, which is supposed to display the message in a chatbox. This works fine, and both players can send a message to the server, and it will pop up in their own chat (i.e. the event handlers are properly attached on both clients). However, for the client which did not send the message, ChatMessageReceived returns null, even though it is defined locally.

I looked around online, but could not really find any proper explanations as to why this happens. How can I properly pass an event generated through a ClientRPC on to other local objects which are not part of the Player GameObject itself?

Edit:
The Event Listener is attached via a Script attached to the player game object. On Start of this script, i.e. when the Player Game Object is spawned in, it will find the Chatbox game object and pass the ChatInterface script (seen above) of the local player to another script.

    public void Start()
    {
        if (!isLocalPlayer) return;

        GameObject.Find("Chat").GetComponent<Chatbox>().PlayerLoaded(this.gameObject.GetComponent<ChatInterface>());
    }

The Chatbox script then attaches its own local method to the event handler.

    public void PlayerLoaded(ChatInterface chat)
    {
        this.chat = chat;
        chat.ChatMessageReceived += Receive;
    }

As said, each client receives events they send on their own client just fine, but events from other clients cause the whole event to act as if no handler was defined on it.


问:
Cant create 2nd textbox
I'm having problems with this code and I can't figure out why. It works fine the first time through but crashes with a "Parameter is not Valid" error the 2nd time through on this line:

```<code>Dim tbx As TextBox = New Windows.Forms.TextBox
</code>```

The full code is as follows:

```<code>Dim tbx As TextBox = New Windows.Forms.TextBox
tbx.Name = tbxName
tbx.Size = New System.Drawing.Size(55, 12)
tbx.BorderStyle = BorderStyle.None
tbx.TextAlign = HorizontalAlignment.Center
Using f As Font = tbx.Font
  tbx.Font = New Font(f.FontFamily, 8, FontStyle.Bold)
End Using
tbx.Location = New System.Drawing.Point(xCords, 44)
Select Case tbx.Name
  Case "tbxBulk01" : tbx.Text = Bulk01Label
  Case "tbxBulk02" : tbx.Text = Bulk02Label
End Select
Me.Controls.Add(tbx)
</code>```

Here's the stack trace:

at System.Drawing.Font.GetHeight(Graphics graphics)
    at System.Drawing.Font.GetHeight()
    at System.Drawing.Font.get_Height()
    at System.Windows.Forms.Control.get_FontHeight()
    at System.Windows.Forms.TextBoxBase.get_PreferredHeight()
    at System.Windows.Forms.TextBoxBase.get_DefaultSize()
    at System.Windows.Forms.Control..ctor(Boolean autoInstallSyncContext)
    at System.Windows.Forms.TextBoxBase..ctor()
    at System.Windows.Forms.TextBox..ctor()

Any help is appreciated.

答:
I know this is an old question but here is my answer.

I suspected the

USING .... END USING section as well.

I have just read that in the feedback too, oh well, never mind.

```<code>Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim xCoords As Integer = 80
        Dim myTextBox As TextBox = New TextBox

        For index As Integer = 1 To 2
            myTextBox = New TextBox
            myTextBox.Name = "MyTextBox" & index.ToString
            myTextBox.Size = New System.Drawing.Size(55, 12)
            myTextBox.BorderStyle = BorderStyle.None
            myTextBox.TextAlign = HorizontalAlignment.Center
            myTextBox.Font = New System.Drawing.Font(myTextBox.Font.FontFamily, 8, FontStyle.Bold)
            myTextBox.Location = New System.Drawing.Point(index * xCoords, 44)
            Select Case index
                Case 1 : myTextBox.Text = "Bulk01Label"
                Case 2 : myTextBox.Text = "Bulk02Label"
            End Select
            Me.Controls.Add(myTextBox)
        Next

    End Sub
End Class
</code>```

ContentLicense: CC BY-SA 2.5

Title: Cant create 2nd textbox

Body:
I'm having problems with this code and I can't figure out why. It works fine the first time through but crashes with a "Parameter is not Valid" error the 2nd time through on this line:

Dim tbx As TextBox = New Windows.Forms.TextBox

The full code is as follows:

Dim tbx As TextBox = New Windows.Forms.TextBox
tbx.Name = tbxName
tbx.Size = New System.Drawing.Size(55, 12)
tbx.BorderStyle = BorderStyle.None
tbx.TextAlign = HorizontalAlignment.Center
Using f As Font = tbx.Font
  tbx.Font = New Font(f.FontFamily, 8, FontStyle.Bold)
End Using
tbx.Location = New System.Drawing.Point(xCords, 44)
Select Case tbx.Name
  Case "tbxBulk01" : tbx.Text = Bulk01Label
  Case "tbxBulk02" : tbx.Text = Bulk02Label
End Select
Me.Controls.Add(tbx)

Here's the stack trace:

at System.Drawing.Font.GetHeight(Graphics graphics)
    at System.Drawing.Font.GetHeight()
    at System.Drawing.Font.get_Height()
    at System.Windows.Forms.Control.get_FontHeight()
    at System.Windows.Forms.TextBoxBase.get_PreferredHeight()
    at System.Windows.Forms.TextBoxBase.get_DefaultSize()
    at System.Windows.Forms.Control..ctor(Boolean autoInstallSyncContext)
    at System.Windows.Forms.TextBoxBase..ctor()
    at System.Windows.Forms.TextBox..ctor()

Any help is appreciated.

Body:
I know this is an old question but here is my answer.

I suspected the

USING .... END USING section as well.

I have just read that in the feedback too, oh well, never mind.

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim xCoords As Integer = 80
        Dim myTextBox As TextBox = New TextBox

        For index As Integer = 1 To 2
            myTextBox = New TextBox
            myTextBox.Name = "MyTextBox" & index.ToString
            myTextBox.Size = New System.Drawing.Size(55, 12)
            myTextBox.BorderStyle = BorderStyle.None
            myTextBox.TextAlign = HorizontalAlignment.Center
            myTextBox.Font = New System.Drawing.Font(myTextBox.Font.FontFamily, 8, FontStyle.Bold)
            myTextBox.Location = New System.Drawing.Point(index * xCoords, 44)
            Select Case index
                Case 1 : myTextBox.Text = "Bulk01Label"
                Case 2 : myTextBox.Text = "Bulk02Label"
            End Select
            Me.Controls.Add(myTextBox)
        Next

    End Sub
End Class

ContentLicense: CC BY-SA 3.0


问:
Increasing Value in Column by X if Value in Another Column is Like Y
I am looking for some help adjusting my VBA. I believe I am close but can't figure out the final necessary steps. I want to increase the value in column K by X percent if the string in column C is like X. Below is what I have already, please let me know if there is any further information needed. Thanks!</p>
```<code>Sub Cost_Increase()

Dim strInput As String
strInput = InputBox("Input Part Number", "Part Number for Cost Increase", "Enter your input text HERE")

Dim iInput As Integer
iInput = InputBox("Please enter an increase amount", "Increase Customer Cost")

Dim r As Long, ws As Worksheet

Set ws = Sheets("All Cust")

For r = ws.Cells(Rows.Count, "C").End(xlUp).Row To 2 Step -1

If ws.Range("C" & r).Value Like strInput Then

ws.Range("K" & r).Value = ((ws.Range("K" & r).Value * iInput) + ws.Range("K" & r).Value)

End If

Next r

End Sub
</code>```

答:
Increase By Percentage

A Quick Fix

Option Explicit

Sub Cost_Increase()

    Dim PartNumber As String
    PartNumber = InputBox("Input Part Number", "Part Number for Cost Increase", "Enter your input text HERE")
    If Len(PartNumber) = 0 Then Exit Sub ' canceled or no entry: improve!

    Dim Increase As String
    Increase = InputBox("Please enter an increase percentage", "Increase Customer Cost", "0")
    If Len(Increase) = 0 Then Exit Sub ' canceled or no entry: improve!
    If Not IsNumeric(Increase) Then Exit Sub ' not a number: improve!

    Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("All Cust")

    Dim r As Long
    For r = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row To 2 Step -1
        If InStr(1, CStr(ws.Range("C" & r).Value), PartNumber) = 1 Then ' begins with
            If IsNumeric(ws.Range("K" & r).Value) Then
                ws.Range("K" & r).Value _
                    = ws.Range("K" & r).Value * (100 + Increase) / 100
            End If
        End If
    Next r

End Sub
```

Body:
I am looking for some help adjusting my VBA. I believe I am close but can't figure out the final necessary steps. I want to increase the value in column K by X percent if the string in column C is like X. Below is what I have already, please let me know if there is any further information needed. Thanks!

Sub Cost_Increase()

Dim strInput As String
strInput = InputBox("Input Part Number", "Part Number for Cost Increase", "Enter your input text HERE")

Dim iInput As Integer
iInput = InputBox("Please enter an increase amount", "Increase Customer Cost")

Dim r As Long, ws As Worksheet

Set ws = Sheets("All Cust")

For r = ws.Cells(Rows.Count, "C").End(xlUp).Row To 2 Step -1

If ws.Range("C" & r).Value Like strInput Then

ws.Range("K" & r).Value = ((ws.Range("K" & r).Value * iInput) + ws.Range("K" & r).Value)

End If

Next r

End Sub


问:
Looping in R to only add leading zeros to specified length
how would I be able to go from a column like this:
1
1
1
2
3
4
9
25
100

to one like this:
01
01
01
02
03
04
09
25
100

Basically, I want to add a leading zero to any value with only length 1. The actual data frame is much bigger than this. Thanks!

Body:
You may also want to explore the formatC function:

vec <-  c(1, 1, 1, 2, 3, 4, 9, 25, 100)
formatC(x = vec, digits = 1, flag = "0", format = "d")

Results

"01"  "01"  "01"  "02"  "03"  "04"  "09"  "25"  "100"


问:
How to get first and last day of the current week in JavaScript
I have today = new Date(); object. I need to get first and last day of the current week. I need both variants for Sunday and Monday as a start and end day of the week. I am little bit confuse now with a code. Can your help me?

答:
Works with different months and years.

let wDate = new Date();
let dDay = wDate.getDay() > 0 ? wDate.getDay() : 7;
let first = wDate.getDate() - dDay + 1;
let firstDayWeek = new Date(wDate.setDate(first));
let lastDayWeek = new Date(wDate.setDate(firstDayWeek.getDate()+6));
console.log(firstDayWeek.toLocaleDateString());
console.log(lastDayWeek.toLocaleDateString());```


Title: How to print the elements of a tuple sided by side

Body:
I am able to print the elements one after the another but I want the result to be printed side by side: 1234, instead of:

1

2

3

4

Display which I am getting

Desired Output:

The code is to display 7 segment led display.

led_dict={
    '0':('###','# #','# #','# #','###'),
    '1':('  #','  #','  #','  #','  #'),
    '2':('###','  #','###','#  ','###'),
    '3':('###','  #','###','  #','###'),
    '4':('# #','# #','###','  #','  #'),
    '5':('###','#  ','###','  #','###'),
    '6':('###','#  ','###','# #','###'),
    '7':('###','  #','  #','  #','  #'),
    '8':('###','# #','###','# #','###'),
    '9':('###','# #','###','  #','###')
    }

x = input('Enter a number to be displayed: ')

d_list=[]

for num in str(x):
    d_list.append(led_dict[num])
print(d_list)
# for i in range(5):
#     for ab in d_list:
#         print(ab[i])

for ab in d_list:
    for i in range(5):
        print((ab[i]))

Body:
Try this:

for i in range(5):
    print(' '.join(k[i] for k in d_list))

How it works;

Each number tuple consists of five lines.
But we have to print by line. That means we have to join the same elements of the tuple for all digits, and then print the resulting string. If we do that five times, (see the index i) we will have printed the whole number.

An example:

Python 3.9.9 (main, Dec 11 2021, 14:34:11)
>>> led_dict={'0': ('###', '# #', '# #', '# #', '###'),
...  '1': ('  #', '  #', '  #', '  #', '  #'),
...  '2': ('###', '  #', '###', '#  ', '###'),
...  '3': ('###', '  #', '###', '  #', '###'),
...  '4': ('# #', '# #', '###', '  #', '  #'),
...  '5': ('###', '#  ', '###', '  #', '###'),
...  '6': ('###', '#  ', '###', '# #', '###'),
...  '7': ('###', '  #', '  #', '  #', '  #'),
...  '8': ('###', '# #', '###', '# #', '###'),
...  '9': ('###', '# #', '###', '  #', '###')}
>>> d_list=[]
>>> for num in '3427':
...     d_list.append(led_dict[num])
...
>>> for i in range(5):
...     print(' '.join(k[i] for k in d_list))
...
### # # ### ###
  # # #   #   #
### ### ###   #
  #   # #     #
###   # ###   #


问:
How can I solve 'ENOENT' error in next.js api section?
I am woking on a Next.js Project and in there I need to read data using an api and for that I have created 1 api route in /pages/api directory and that Api is using a function from `/store/manipulate.js' and I have imported that particular function in my api Route file but when I request on that api route it is giving me an error.

So, the component below is requesting for data on that api route.

Homepage.jsx

import axios from 'axios'
import { useEffect, useState } from 'react'
import EventList from '../components/events/EventList'

const HomePage = () => {

  const [featuredEvents, setFeaturedEvents] = useState([])

  useEffect(() => {
    (async () => {
      const res = await axios.get('/api/getfeaturedevents')

      if (res.status(200)) {
        console.log(res.data)
        setFeaturedEvents(res.data)
        return
      }

      console.log(res.status)
    })()
  }, [])

  return (

        The Home Page.

      <EventList items={featuredEvents} />

  )
}

export default HomePage
```
<p>Now, the code shown below is the code of api route file</p>
<p><strong>getFeaturedEvents.js</strong></p>
<pre class="lang-js prettyprint-override"><code>import { fetchFeaturedEvents } from '../../store/manipulate'

const getFeaturedEvents = (req, res) => {
    if (req.method === 'GET') {
        try {
            const data = fetchFeaturedEvents()

            res.send(data)
        } catch (error) {
            console.log(error)
            res.status(500).send()
        }
    }
}

export default getFeaturedEvents
</code>```

Now, let's take a look at manipulate.js which will just update store.json present in same folder.

manipulate.js

const path = require('path')
const fs = require('fs')

const readData = () => {
    const data = JSON.parse(fs.readFileSync(path.join(__dirname, 'store.json')))
    return data
}

export const fetchFeaturedEvents = () => {
    let data = readData()
    const result = data.filter(event => event.isFeatured)

    return result
}
```

Now, the Error I am getting is...

答: In my case, I removed the default API folder in pages</p>

Body:
I am woking on a Next.js Project and in there I need to read data using an api and for that I have created 1 api route in /pages/api directory and that Api is using a function from `/store/manipulate.js' and I have imported that particular function in my api Route file but when I request on that api route it is giving me an error.

So, the component below is requesting for data on that api route.

Homepage.jsx

import axios from 'axios'
import { useEffect, useState } from 'react'
import EventList from '../components/events/EventList'

const HomePage = () => {

  const [featuredEvents, setFeaturedEvents] = useState([])

  useEffect(() => {
    (async () => {
      const res = await axios.get('/api/getfeaturedevents')

      if (res.status(200)) {
        console.log(res.data)
        setFeaturedEvents(res.data)
        return
      }

      console.log(res.status)
    })()
  }, [])

  return (

        The Home Page.

      <EventList items={featuredEvents} />

  )
}

export default HomePage

Now, the code shown below is the code of api route file

getFeaturedEvents.js

import { fetchFeaturedEvents } from '../../store/manipulate'

const getFeaturedEvents = (req, res) => {
    if (req.method === 'GET') {
        try {
            const data = fetchFeaturedEvents()

            res.send(data)
        } catch (error) {
            console.log(error)
            res.status(500).send()
        }
    }
}

export default getFeaturedEvents

Now, let's take a look at manipulate.js which will just update store.json present in same folder.

manipulate.js

const path = require('path')
const fs = require('fs')

const readData = () => {
    const data = JSON.parse(fs.readFileSync(path.join(__dirname, 'store.json')))
    return data
}

export const fetchFeaturedEvents = () => {
    let data = readData()
    const result = data.filter(event => event.isFeatured)

    return result
}

Now, the Error I am getting is...


问:
Cannot change background color of matplotlib Figure (when saving as image)?
The actual problem that I have, is that - in the code I'm working on: when I try to save the plot image, I get the plot background in the image as fully transparent, so it looks like this in an image viewer (here eom, Mate's version of eog):

I would like to have the background color to be fully opaque white, instead.

This seems to have been a problem often, e.g.:

Matplotlib figure facecolor alpha while saving (background color, transparency)

Matplotlib savefig background always transparent

Set background color behind the image in matplotlib

https://moonbooks.org/Articles/How-to-change-the-color-background-of-a-matplotlib-figure-/

Anyways, one problem is that I cannot reproduce this with a minimal example. In my code, essentially I have to convert the figure to an image first, then process that image, then finally save it. So I tried making a minimal example, with a conversion to image data first, which is then being saved:

import matplotlib as mpl
print(f"{mpl.__version__}")
import matplotlib.pyplot as plt
import numpy as np
import io

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

subplotpars = dict(left = 0.05, right=0.99, top=0.89, wspace=0.1)
gss = mpl.gridspec.GridSpec(2,1, height_ratios=(2, 1), **subplotpars),

fig = plt.figure()
gs = gss[0]
ax = fig.add_subplot(gs[0,0])

ax.plot(t, s, color=(0.4, 0.2, 0.6, 0.6))

print(f"{fig.get_facecolor()=}, {fig.get_alpha()=}")
print(f"{fig.patch.get_facecolor()=}, {fig.patch.get_alpha()=}")

with io.BytesIO() as buf:
    fig.savefig(buf, dpi=120, format="png")
    buf.seek(0)
    fig_rgba = plt.imread(buf)

plt.imsave('example_io.png', fig_rgba, dpi=120)
```
<p>... and this code prints this for me:</p>
<pre class="lang-none prettyprint-override"><code>3.5.1
fig.get_facecolor()=(1.0, 1.0, 1.0, 1.0), fig.get_alpha()=None
fig.patch.get_facecolor()=(1.0, 1.0, 1.0, 1.0), fig.patch.get_alpha()=None
</code>```

... and tells me that I have matplotlib 3.5.1, and that the figure background color is defined as RGBA, although with alpha channel set to 1 (opaque). Ultimately, the image that is output by this code, for me, is with fully opaque white background - so this code does not demonstrate the problem.

So, while I cannot reconstruct my problem as a minimal example - I managed to narrow down the problem in my actual code, in this snippet:

        # ... time to save as image:

        print(f"A {self.fig.get_facecolor()=}, {self.fig.get_alpha()=}")
        print(f"A {self.fig.patch.get_facecolor()=}, {self.fig.patch.get_alpha()=}")

        orig_figcol = self.fig.get_facecolor()
        orig_figpatchcol = self.fig.patch.get_facecolor()
        self.fig.set_facecolor( (1.0, 1.0, 1.0, 1.0) ) # calls patch.set_facecolor anyway
        self.fig.patch.set_facecolor( (1.0, 1.0, 1.0, 1.0) )
        self.fig.canvas.draw()

        print(f"B {self.fig.get_facecolor()=}, {self.fig.get_alpha()=}")
        print(f"B {self.fig.patch.get_facecolor()=}, {self.fig.patch.get_alpha()=}")

        with io.BytesIO() as buf:
        # ...
```
<p>When this section in the code is ran, I get a printout:</p>
<pre class="lang-none prettyprint-override"><code>A self.fig.get_facecolor()=(1.0, 1.0, 1.0, 0), self.fig.get_alpha()=None
A self.fig.patch.get_facecolor()=(1.0, 1.0, 1.0, 0), self.fig.patch.get_alpha()=0
B self.fig.get_facecolor()=(1.0, 1.0, 1.0, 0), self.fig.get_alpha()=None
B self.fig.patch.get_facecolor()=(1.0, 1.0, 1.0, 0), self.fig.patch.get_alpha()=0
</code>```

So, unlike the basic example above, the starting background color of the plot, as RGBA, is (1.0, 1.0, 1.0, 0) - that is to say, alpha channel is zero (so no surprise the background is transparent).

However, I do call set_facecolor right after, with an RGBA color where alpha is 1, and I even call .draw(), to hopefully trigger a refresh/redraw -- but regardless, when try to get the same facecolor I just previously set, it still returns the old color value, where alpha was 0!

So, essentially, the way I see this is: something does not let me change the Figure background color, right before I want to save the figure as an image.

Under what circumstances would matplotlib not let me change the image background - and ultimately, how can I change the plot figure background color, right before I save the figure as image (or export it as image data, that is, pixels)?

答:
Ok, found the solution - this required some debugging and drilling down of code; it turns out, one of the forest of libraries I include in my code, decided to change matplotlib figure properties - so here is a bit of a writeup:

So, after my attempt to use pdb to debug this failed (Inspecting a variable value in other stack frames in pdb?), I found How do you watch a variable in pdb - which recommended the watchpoints library.

So basically, after my figure init (self.fig = plt.figure(...), I did:

```<code>watch(self.fig.patch._facecolor)
</code>```

... and ran the code; and finally I got something like this in the terminal printout:

====== Watchpoints Triggered ======
Call Stack (most recent call last):
...
>   figure.patch.set_alpha(0)
  set_alpha (~/venv/lib/python3.8/site-packages/matplotlib/patches.py:394):
>   self._set_facecolor(self._original_facecolor)
  to_rgba (~/venv/lib/python3.8/site-packages/matplotlib/colors.py:192):
>   return rgba
self.fig.patch._facecolor:
(1.0, 1.0, 1.0, 1.0)
->
(1.0, 1.0, 1.0, 0)
```
<p>So, one of these libraries ended up calling <code>figure.patch.set_alpha(0)</code> - which turns out to be a bit nastier than one would deduce from the naming alone; namely, once it is set to 0 - it will <em>prohibit</em> entering any other alpha value, whenever you want to set the face color!!! Here is a code that reproduces that, based on the OP code:</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib as mpl
print(f"{mpl.__version__}")
import matplotlib.pyplot as plt
import numpy as np
import io

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

subplotpars = dict(left = 0.05, right=0.99, top=0.89, wspace=0.1)
gss = mpl.gridspec.GridSpec(2,1, height_ratios=(2, 1), **subplotpars),

fig = plt.figure()
gs = gss[0]
ax = fig.add_subplot(gs[0,0])

ax.plot(t, s, color=(0.4, 0.2, 0.6, 0.6))

print(f"A {fig.get_facecolor()=}, {fig.get_alpha()=}")
print(f"A {fig.patch.get_facecolor()=}, {fig.patch.get_alpha()=}")

fig.patch.set_alpha(0)

print(f"B {fig.get_facecolor()=}, {fig.get_alpha()=}")
print(f"B {fig.patch.get_facecolor()=}, {fig.patch.get_alpha()=}")

fig.patch.set_facecolor( (0.9, 0.9, 0.9, 1.0) )

print(f"C {fig.get_facecolor()=}, {fig.get_alpha()=}")
print(f"C {fig.patch.get_facecolor()=}, {fig.patch.get_alpha()=}")

with io.BytesIO() as buf:
    fig.savefig(buf, dpi=120, format="png", facecolor=(1.0, 1.0, 1.0, 1.0))
    buf.seek(0)
    fig_rgba = plt.imread(buf)

plt.imsave('example_io.png', fig_rgba, dpi=120)
</code>```

This prints:

3.5.1
A fig.get_facecolor()=(1.0, 1.0, 1.0, 1.0), fig.get_alpha()=None
A fig.patch.get_facecolor()=(1.0, 1.0, 1.0, 1.0), fig.patch.get_alpha()=None
B fig.get_facecolor()=(1.0, 1.0, 1.0, 0), fig.get_alpha()=None
B fig.patch.get_facecolor()=(1.0, 1.0, 1.0, 0), fig.patch.get_alpha()=0
C fig.get_facecolor()=(0.9, 0.9, 0.9, 0), fig.get_alpha()=None
C fig.patch.get_facecolor()=(0.9, 0.9, 0.9, 0), fig.patch.get_alpha()=0
```
<p>So - with <code>fig.patch.set_alpha(0)</code> having ran once, <em>even</em> if I set <code>fig.patch.set_facecolor( (0.9, 0.9, 0.9, 1.0) )</code> afterward (which explicitly sets alpha to 0) - the actual fill color that ends up in the object, <em>still</em> has alpha=0 (as printout C shows)!</p>
<p>So if you run that code, you still get transparent background in the image.</p>
<p>The solution turns out to be - just set <code>fig.patch.set_alpha(1.0)</code> right before the <code>fig.savefig</code> call:</p>
<pre class="lang-py prettyprint-override"><code># ...
with io.BytesIO() as buf:
    fig.patch.set_alpha(1.0)
    fig.savefig(buf, dpi=120, format="png", facecolor=(1.0, 1.0, 1.0, 1.0))
    # ...
</code>```

Boy.... Now those were some wasted hours of my life... I wish someone would invent some machines, that you could program ... oh wait

Body:
The actual problem that I have, is that - in the code I'm working on: when I try to save the plot image, I get the plot background in the image as fully transparent, so it looks like this in an image viewer (here eom, Mate's version of eog):

I would like to have the background color to be fully opaque white, instead.

This seems to have been a problem often, e.g.:

Matplotlib figure facecolor alpha while saving (background color, transparency)

Matplotlib savefig background always transparent

Set background color behind the image in matplotlib

https://moonbooks.org/Articles/How-to-change-the-color-background-of-a-matplotlib-figure-/

Anyways, one problem is that I cannot reproduce this with a minimal example. In my code, essentially I have to convert the figure to an image first, then process that image, then finally save it. So I tried making a minimal example, with a conversion to image data first, which is then being saved:

import matplotlib as mpl
print(f"{mpl.__version__}")
import matplotlib.pyplot as plt
import numpy as np
import io

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

subplotpars = dict(left = 0.05, right=0.99, top=0.89, wspace=0.1)
gss = mpl.gridspec.GridSpec(2,1, height_ratios=(2, 1), **subplotpars),

fig = plt.figure()
gs = gss[0]
ax = fig.add_subplot(gs[0,0])

ax.plot(t, s, color=(0.4, 0.2, 0.6, 0.6))

print(f"{fig.get_facecolor()=}, {fig.get_alpha()=}")
print(f"{fig.patch.get_facecolor()=}, {fig.patch.get_alpha()=}")

with io.BytesIO() as buf:
    fig.savefig(buf, dpi=120, format="png")
    buf.seek(0)
    fig_rgba = plt.imread(buf)

plt.imsave('example_io.png', fig_rgba, dpi=120)

... and this code prints this for me:

3.5.1
fig.get_facecolor()=(1.0, 1.0, 1.0, 1.0), fig.get_alpha()=None
fig.patch.get_facecolor()=(1.0, 1.0, 1.0, 1.0), fig.patch.get_alpha()=None

... and tells me that I have matplotlib 3.5.1, and that the figure background color is defined as RGBA, although with alpha channel set to 1 (opaque). Ultimately, the image that is output by this code, for me, is with fully opaque white background - so this code does not demonstrate the problem.

So, while I cannot reconstruct my problem as a minimal example - I managed to narrow down the problem in my actual code, in this snippet:

        # ... time to save as image:

        print(f"A {self.fig.get_facecolor()=}, {self.fig.get_alpha()=}")
        print(f"A {self.fig.patch.get_facecolor()=}, {self.fig.patch.get_alpha()=}")

        orig_figcol = self.fig.get_facecolor()
        orig_figpatchcol = self.fig.patch.get_facecolor()
        self.fig.set_facecolor( (1.0, 1.0, 1.0, 1.0) ) # calls patch.set_facecolor anyway
        self.fig.patch.set_facecolor( (1.0, 1.0, 1.0, 1.0) )
        self.fig.canvas.draw()

        print(f"B {self.fig.get_facecolor()=}, {self.fig.get_alpha()=}")
        print(f"B {self.fig.patch.get_facecolor()=}, {self.fig.patch.get_alpha()=}")

        with io.BytesIO() as buf:
        # ...

When this section in the code is ran, I get a printout:

A self.fig.get_facecolor()=(1.0, 1.0, 1.0, 0), self.fig.get_alpha()=None
A self.fig.patch.get_facecolor()=(1.0, 1.0, 1.0, 0), self.fig.patch.get_alpha()=0
B self.fig.get_facecolor()=(1.0, 1.0, 1.0, 0), self.fig.get_alpha()=None
B self.fig.patch.get_facecolor()=(1.0, 1.0, 1.0, 0), self.fig.patch.get_alpha()=0

So, unlike the basic example above, the starting background color of the plot, as RGBA, is (1.0, 1.0, 1.0, 0) - that is to say, alpha channel is zero (so no surprise the background is transparent).

However, I do call set_facecolor right after, with an RGBA color where alpha is 1, and I even call .draw(), to hopefully trigger a refresh/redraw -- but regardless, when try to get the same facecolor I just previously set, it still returns the old color value, where alpha was 0!

So, essentially, the way I see this is: something does not let me change the Figure background color, right before I want to save the figure as an image.

Under what circumstances would matplotlib not let me change the image background - and ultimately, how can I change the plot figure background color, right before I save the figure as image (or export it as image data, that is, pixels)?

Body:
Ok, found the solution - this required some debugging and drilling down of code; it turns out, one of the forest of libraries I include in my code, decided to change matplotlib figure properties - so here is a bit of a writeup:

So, after my attempt to use pdb to debug this failed (Inspecting a variable value in other stack frames in pdb?), I found How do you watch a variable in pdb - which recommended the watchpoints library.

So basically, after my figure init (self.fig = plt.figure(...), I did:

watch(self.fig.patch._facecolor)

... and ran the code; and finally I got something like this in the terminal printout:

====== Watchpoints Triggered ======
Call Stack (most recent call last):
...
>   figure.patch.set_alpha(0)
  set_alpha (~/venv/lib/python3.8/site-packages/matplotlib/patches.py:394):
>   self._set_facecolor(self._original_facecolor)
  to_rgba (~/venv/lib/python3.8/site-packages/matplotlib/colors.py:192):
>   return rgba
self.fig.patch._facecolor:
(1.0, 1.0, 1.0, 1.0)
->
(1.0, 1.0, 1.0, 0)

So, one of these libraries ended up calling figure.patch.set_alpha(0) - which turns out to be a bit nastier than one would deduce from the naming alone; namely, once it is set to 0 - it will prohibit entering any other alpha value, whenever you want to set the face color!!! Here is a code that reproduces that, based on the OP code:

import matplotlib as mpl
print(f"{mpl.__version__}")
import matplotlib.pyplot as plt
import numpy as np
import io

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)

subplotpars = dict(left = 0.05, right=0.99, top=0.89, wspace=0.1)
gss = mpl.gridspec.GridSpec(2,1, height_ratios=(2, 1), **subplotpars),

fig = plt.figure()
gs = gss[0]
ax = fig.add_subplot(gs[0,0])

ax.plot(t, s, color=(0.4, 0.2, 0.6, 0.6))

print(f"A {fig.get_facecolor()=}, {fig.get_alpha()=}")
print(f"A {fig.patch.get_facecolor()=}, {fig.patch.get_alpha()=}")

fig.patch.set_alpha(0)

print(f"B {fig.get_facecolor()=}, {fig.get_alpha()=}")
print(f"B {fig.patch.get_facecolor()=}, {fig.patch.get_alpha()=}")

fig.patch.set_facecolor( (0.9, 0.9, 0.9, 1.0) )

print(f"C {fig.get_facecolor()=}, {fig.get_alpha()=}")
print(f"C {fig.patch.get_facecolor()=}, {fig.patch.get_alpha()=}")

with io.BytesIO() as buf:
    fig.savefig(buf, dpi=120, format="png", facecolor=(1.0, 1.0, 1.0, 1.0))
    buf.seek(0)
    fig_rgba = plt.imread(buf)

plt.imsave('example_io.png', fig_rgba, dpi=120)

This prints:

3.5.1
A fig.get_facecolor()=(1.0, 1.0, 1.0, 1.0), fig.get_alpha()=None
A fig.patch.get_facecolor()=(1.0, 1.0, 1.0, 1.0), fig.patch.get_alpha()=None
B fig.get_facecolor()=(1.0, 1.0, 1.0, 0), fig.get_alpha()=None
B fig.patch.get_facecolor()=(1.0, 1.0, 1.0, 0), fig.patch.get_alpha()=0
C fig.get_facecolor()=(0.9, 0.9, 0.9, 0), fig.get_alpha()=None
C fig.patch.get_facecolor()=(0.9, 0.9, 0.9, 0), fig.patch.get_alpha()=0

So - with fig.patch.set_alpha(0) having ran once, even if I set fig.patch.set_facecolor( (0.9, 0.9, 0.9, 1.0) ) afterward (which explicitly sets alpha to 0) - the actual fill color that ends up in the object, still has alpha=0 (as printout C shows)!

So if you run that code, you still get transparent background in the image.

The solution turns out to be - just set fig.patch.set_alpha(1.0) right before the fig.savefig call:

# ...
with io.BytesIO() as buf:
    fig.patch.set_alpha(1.0)
    fig.savefig(buf, dpi=120, format="png", facecolor=(1.0, 1.0, 1.0, 1.0))
    # ...

Boy.... Now those were some wasted hours of my life... I wish someone would invent some machines, that you could program ... oh wait


问:
Core Plot Bar Chart Columns
Is it possible to set some padding between the first bar and the Y axis?
The last bar is always a few pixels away from the right margin of the plot but the first column always appears cut by the Y axis</p>

答: Adjust the xRange of your plot space. Decrease the starting location and increase the length.</p>

Title: Core Plot Bar Chart Columns


问:
Check the Return Value of scanf
Probably a simple answer to this, but I am relatively new to C. I have a loop that validates that a user has entered an integer value within certain parameters. It works fine, except when a user inputs a character. I thought my code checked for this already, but I was wrong.

My code at the moment:

```<code>    while(1) {
                printf("Enter Recommended Shot Doses (1-255): ");
                if(scanf("%d", &shotDoses) == 1 &&
                    shotDoses >=1 && shotDoses <=255) break;

                printf("\033[1;31mPlease Enter a Valid Number.\033[0m\n");
            }
</code>```

I get an infinite loop if you accidentally input a character instead of a number. Any help?

Thanks

答:
Read a line to the buff, then scan it.</p>
```<code>#define MAXLINELENGHT 100

    while(1) {
                char buff[MAXLINELENGHT];
                printf("Enter Recommended Shot Doses (1-255): ");
                fgets(buff, sizeof(buff), stdin);
                if(sscanf(buff, "%d", &shotDoses) == 1 &&
                    shotDoses >=1 && shotDoses <=255) break;

                printf("\033[1;31mPlease Enter a Valid Number.\033[0m\n");
            }
</code>```

Title: Check the Return Value of scanf

Body:
Probably a simple answer to this, but I am relatively new to C. I have a loop that validates that a user has entered an integer value within certain parameters. It works fine, except when a user inputs a character. I thought my code checked for this already, but I was wrong.

My code at the moment:

    while(1) {
                printf("Enter Recommended Shot Doses (1-255): ");
                if(scanf("%d", &shotDoses) == 1 &&
                    shotDoses >=1 && shotDoses <=255) break;

                printf("\033[1;31mPlease Enter a Valid Number.\033[0m\n");
            }

I get an infinite loop if you accidentally input a character instead of a number. Any help?

Thanks

Body:
Read a line to the buff, then scan it.

#define MAXLINELENGHT 100

    while(1) {
                char buff[MAXLINELENGHT];
                printf("Enter Recommended Shot Doses (1-255): ");
                fgets(buff, sizeof(buff), stdin);
                if(sscanf(buff, "%d", &shotDoses) == 1 &&
                    shotDoses >=1 && shotDoses <=255) break;

                printf("\033[1;31mPlease Enter a Valid Number.\033[0m\n");
            }


问:
React typescript: generic useReducer dispatch type unknown when passed as a prop
I currently have a custom generic useReducer where I pass the dispatch as a prop to a child component however TS is unable to infer the actions type.
I am not sure why the actions are conisderend unknown in the child element and so is the state item is an unknown

the Item each time is a different type of object that is picked up

Type 'Dispatch<TableStateAction<myType>>' is not assignable to type 'Dispatch<TableStateAction<unknown>>'

Reducer action

export type TableStateAction<T> =
  | {
      type: "show_modal";
      value: { item: T; action: string; modal: true };
    }
  | {
      type: "hide_modal";
      value: { item: null; action: string; modal: false; message: string };
    }
```
<p>parent component</p>
<pre class="lang-tsx prettyprint-override"><code>  const [state, dispatch] = useTableHeaderState<myType>();

    <td>
     <TableItemDropDown
    showModal={dispatch}
    actionType={dropdownType}
    currentItem={item}
    />
   </td>
</code>```

Child component

interface TableItemDropDownProps<T> {
  showModal: Dispatch<TableStateAction<T>>;
  actionType: ModalActionType[];
  currentItem: T;
}

 showModal({
        type: "show_modal",
        value: {
          item: currentItem,
          action: action,
          modal: true,
        },
      })

```
<p>useReducerState</p>
<pre class="lang-tx prettyprint-override"><code>
export type TableState<T> =
  | {
      modalShown: false;
      modalItem: T;
      modalAction: string;;
    }
  | {
      modalShown: true;
      modalItem: T;
      modalAction: string;
    }
  | {
      modalShown: false;
      modalItem: null;
      modalAction: string;
    };
</code>```

UseReducer function

export function useTableHeaderState<T>(): [
  TableState<T>,
  Dispatch<TableStateAction<T>>
] {
  return useReducer(
    (state: TableState<T>, action: TableStateAction<T>): TableState<T> => {
      switch (action.type) {
     case "show_modal":
          return {
            ...state,
            modalItem: action.value.item,
            modalAction: action.value.action,
            modalShown: action.value.modal,
          };
        case "hide_modal":
          return {
            ...state,
            modalItem: action.value.item,
            modalAction: action.value.action,
            modalShown: action.value.modal,
            errorMessage: action.value.message,
          };

```

答:
The solution wasn't related to the reducer or the dispatch but rather I was using React.memo() for my child components as a result the props were lost when using a generic component. There are currently several work arounds

My approach  const MemoTest = React.memo(Test) as typeof Test;

Body:
I currently have a custom generic useReducer where I pass the dispatch as a prop to a child component however TS is unable to infer the actions type.
I am not sure why the actions are conisderend unknown in the child element and so is the state item is an unknown

the Item each time is a different type of object that is picked up

Type 'Dispatch<TableStateAction<myType>>' is not assignable to type 'Dispatch<TableStateAction<unknown>>'

Reducer action

export type TableStateAction<T> =
  | {
      type: "show_modal";
      value: { item: T; action: string; modal: true };
    }
  | {
      type: "hide_modal";
      value: { item: null; action: string; modal: false; message: string };
    }

parent component

  const [state, dispatch] = useTableHeaderState<myType>();

     <TableItemDropDown
    showModal={dispatch}
    actionType={dropdownType}
    currentItem={item}
    />

Child component

interface TableItemDropDownProps<T> {
  showModal: Dispatch<TableStateAction<T>>;
  actionType: ModalActionType[];
  currentItem: T;
}

 showModal({
        type: "show_modal",
        value: {
          item: currentItem,
          action: action,
          modal: true,
        },
      })

useReducerState

export type TableState<T> =
  | {
      modalShown: false;
      modalItem: T;
      modalAction: string;;
    }
  | {
      modalShown: true;
      modalItem: T;
      modalAction: string;
    }
  | {
      modalShown: false;
      modalItem: null;
      modalAction: string;
    };

UseReducer function

export function useTableHeaderState<T>(): [
  TableState<T>,
  Dispatch<TableStateAction<T>>
] {
  return useReducer(
    (state: TableState<T>, action: TableStateAction<T>): TableState<T> => {
      switch (action.type) {
     case "show_modal":
          return {
            ...state,
            modalItem: action.value.item,
            modalAction: action.value.action,
            modalShown: action.value.modal,
          };
        case "hide_modal":
          return {
            ...state,
            modalItem: action.value.item,
            modalAction: action.value.action,
            modalShown: action.value.modal,
            errorMessage: action.value.message,
          };


问:
Limit GitHub action workflow concurrency on push and pull_request?
I would like to limit concurrency to one run for my workflow:

on:
  pull_request:
    paths:
      - 'foo/**'
  push:
    paths:
      - 'foo/**'

concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
  cancel-in-progress: true
```

However, I found out that for push head_ref is empty and run_id is always unique (as described here: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#example-using-a-fallback-value)

How I can create a concurrency key that will be constant across pull_request and push events?

答:
I am using this concurrency key for my workflows in similar case:

```<code>group: ${{ github.workflow }}-${{ github.ref }}
</code>```

I wanted to limit it to have single workflow running on a single branch - I am cancelling previous runs.
But this allows to have multiple runs across different branches at the same time - not sure what's your case exactly.

If you want to have one instance of workflow running across whole repository, you can just go for:

```<code>group: ${{ github.workflow }}
</code>```

Body:
I would like to limit concurrency to one run for my workflow:

on:
  pull_request:
    paths:
      - 'foo/**'
  push:
    paths:
      - 'foo/**'

concurrency:
  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}
  cancel-in-progress: true

However, I found out that for push head_ref is empty and run_id is always unique (as described here: https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#example-using-a-fallback-value)

How I can create a concurrency key that will be constant across pull_request and push events?

Body:
I am using this concurrency key for my workflows in similar case:

group: ${{ github.workflow }}-${{ github.ref }}

I wanted to limit it to have single workflow running on a single branch - I am cancelling previous runs.
But this allows to have multiple runs across different branches at the same time - not sure what's your case exactly.

If you want to have one instance of workflow running across whole repository, you can just go for:

group: ${{ github.workflow }}


问:
Android Kotlin Progress Bar become unresolved reference
I am new at using Kotlin in Android Studio and I tried to learn on how to use the progress bar by following a simple tutorial on youtube. However, for some reason the "progressBar" on progressBar.max in MainActivity.kt is defined as unresolved reference although my code is identical with the guy in the video.

This is activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="335dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:scaleY="10" />

</RelativeLayout>
</code>```

This is MainActivity.kt

```<code>package com.example.game1

import android.animation.ObjectAnimator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

       progressBar.max=10

        val currentProgress = 6

        ObjectAnimator.ofInt(progressBar, propertyName: "progress", currentProgress)
        .setDuration(2000)
            .start()
    }
}
</code>```

答:
Seems like you've watched a tutorial where somebody used Kotlin synthetics to access Views from the code. They are deprecated now and I suggest you use either Muhammad Ahmed solution or View Binding

In module's build.gradle locate this piece of code:

```<code>android {
    compileSdk 31
    ...
}
</code>```

Now add the view binding build feature, it should look like this:

```<code>android {
    compileSdk 31

    buildFeatures {
        viewBinding = true
    }

   ...

}
</code>```

After you make the changes, a blue bar at the top should appear. Sync your project and now it supports view binding.

Your MainActivity.kt should look like this:

```<code>class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding  // name of your layout in camelcase

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.progressBar.max = 10
    }
}
</code>```

How do you access Views with the view binding? Use camelcase. For example, if you have TextView with id "tv_list_description" it can be accessed in the code like this:

binding.tvListDescription.text = "Sample text"

Body:
I am new at using Kotlin in Android Studio and I tried to learn on how to use the progress bar by following a simple tutorial on youtube. However, for some reason the "progressBar" on progressBar.max in MainActivity.kt is defined as unresolved reference although my code is identical with the guy in the video.

This is activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="335dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:scaleY="10" />

</RelativeLayout>

This is MainActivity.kt

package com.example.game1

import android.animation.ObjectAnimator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

       progressBar.max=10

        val currentProgress = 6

        ObjectAnimator.ofInt(progressBar, propertyName: "progress", currentProgress)
        .setDuration(2000)
            .start()
    }
}

Body:
Seems like you've watched a tutorial where somebody used Kotlin synthetics to access Views from the code. They are deprecated now and I suggest you use either Muhammad Ahmed solution or View Binding

In module's build.gradle locate this piece of code:

android {
    compileSdk 31
    ...
}

Now add the view binding build feature, it should look like this:

android {
    compileSdk 31

    buildFeatures {
        viewBinding = true
    }

   ...

}

After you make the changes, a blue bar at the top should appear. Sync your project and now it supports view binding.

Your MainActivity.kt should look like this:

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding  // name of your layout in camelcase

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.progressBar.max = 10
    }
}

How do you access Views with the view binding? Use camelcase. For example, if you have TextView with id "tv_list_description" it can be accessed in the code like this:

binding.tvListDescription.text = "Sample text"


问:
How to pass an attribute from an object to another to calculate a value
Goal: calculate a value based on the sum of attributes of another object, and an attribute from the current object an then use that value to subtract from another value

Expected Output: target_value = 5

Issue: AttributeError: type object 'x' has no attribute 'attribute1'

Object 1:

```<code>class x():

  def __init__(self, attribute1):
    self.attribute1 = attribute1
</code>```

Object 2:

```<code>from object_one import x

class y():

  def __init__(self, attribute2):
    self.attribute2 = attribute2

  def calculate_attributes(self, target):
    value = x.attribute1 + y.attribute2
    target -= value

</code>```

Main:

```<code>from object_one import x
from object_two import y

object_x = x(5)
object_y = y(10)

target_value = 20

object_y.calculate_attributes(target_value)
print(target_value)
</code>```

答:
A direct solution to your problem

In Object 1, you are declaring the field attribute1. In Object2, you are importing the class X.

The class X does not have an attribute of name attribute1 - only an object of type x does. You would have to pass in a reference to the original object x into the calculate_attributes(self, target) method by adding a parameter, like below:

```<code>class y():

  def __init__(self, attribute2):
    self.attribute2 = attribute2

  def calculate_attributes(self, target, x_obj):
    value = x_obj.attribute1 + y.attribute2
    target -= value
</code>```

After that, you would use this calculate_attributes method by doing:

```<code>object_y.calculate_attributes(target_value, object_x)
</code>```

A more in depth explanation - why did this happen?

A class is, basically, a blueprint for an object. After defining a class, you can use it by instantiating an object of its type.

With the line

```<code>object_x = x(5)
</code>```

You are making an object of the type x.

This object has its own fields - it is alive on its own, and is simply created from the blueprint that is its class (herein: "type", "blueprint", "parent class" - all mean the same thing when I speak here).

In the __init__ method, when you set self.attribute2 to the parameter with the same name, you set a field of that any object of that class that is instantiated. This means that two y type objects can have a different value of attribute2

However, you can also make the class contain a "field". This can be done like below:

```<code>class y():
  who_made_this_class = "george"
  def __init__(self, attribute2):
    self.attribute2 = attribute2
</code>```

This can be referred to as a static class variable. Now, when you instantiate a new y object, you see the behaviour shown below:

```<code>obj_one = y(15);
obj_two = y(2020);

print("Object ones attribute2 value is: " + str(obj_one.attribute2))
print("Object twos attribute2 value is: " + str(obj_two.attribute2))

print("Object ones who_made_this_class value is: " + str(obj_one.who_made_this_class))
print("Object twos who_made_this_class value is: " + str(obj_two.who_made_this_class))
</code>```

Expected output is:

```<code>Object ones attribute2 value is: 15
Object twos attribute2 value is: 2020

Object ones who_made_this_class value is: george
Object twos who_made_this_class value is: george
</code>```

Body:
Goal: calculate a value based on the sum of attributes of another object, and an attribute from the current object an then use that value to subtract from another value

Expected Output: target_value = 5

Issue: AttributeError: type object 'x' has no attribute 'attribute1'

Object 1:

class x():

  def __init__(self, attribute1):
    self.attribute1 = attribute1

Object 2:

from object_one import x

class y():

  def __init__(self, attribute2):
    self.attribute2 = attribute2

  def calculate_attributes(self, target):
    value = x.attribute1 + y.attribute2
    target -= value

Main:

from object_one import x
from object_two import y

object_x = x(5)
object_y = y(10)

target_value = 20

object_y.calculate_attributes(target_value)
print(target_value)

Body:
A direct solution to your problem

In Object 1, you are declaring the field attribute1. In Object2, you are importing the class X.

The class X does not have an attribute of name attribute1 - only an object of type x does. You would have to pass in a reference to the original object x into the calculate_attributes(self, target) method by adding a parameter, like below:

class y():

  def __init__(self, attribute2):
    self.attribute2 = attribute2

  def calculate_attributes(self, target, x_obj):
    value = x_obj.attribute1 + y.attribute2
    target -= value

After that, you would use this calculate_attributes method by doing:

object_y.calculate_attributes(target_value, object_x)

A more in depth explanation - why did this happen?

A class is, basically, a blueprint for an object. After defining a class, you can use it by instantiating an object of its type.

With the line

object_x = x(5)

You are making an object of the type x.

This object has its own fields - it is alive on its own, and is simply created from the blueprint that is its class (herein: "type", "blueprint", "parent class" - all mean the same thing when I speak here).

In the __init__ method, when you set self.attribute2 to the parameter with the same name, you set a field of that any object of that class that is instantiated. This means that two y type objects can have a different value of attribute2

However, you can also make the class contain a "field". This can be done like below:

class y():
  who_made_this_class = "george"
  def __init__(self, attribute2):
    self.attribute2 = attribute2

This can be referred to as a static class variable. Now, when you instantiate a new y object, you see the behaviour shown below:

obj_one = y(15);
obj_two = y(2020);

print("Object ones attribute2 value is: " + str(obj_one.attribute2))
print("Object twos attribute2 value is: " + str(obj_two.attribute2))

print("Object ones who_made_this_class value is: " + str(obj_one.who_made_this_class))
print("Object twos who_made_this_class value is: " + str(obj_two.who_made_this_class))

Expected output is:

Object ones attribute2 value is: 15
Object twos attribute2 value is: 2020

Object ones who_made_this_class value is: george
Object twos who_made_this_class value is: george


问:
how to change value of an object in an array in java
I am currently trying to create a vending machine. In my VendingMachine class I have a constructor that takes in 3 parameters. itemOnSale, amount, and priceOfItem. in my Testclass the vending machines are constructed and stored into an array like this:

```<code>VendingMachine[] vendingMachineList = new VendingMachine[4];

vendingMachineList[0] = new VendingMachine("Cookies", 20, 3);
vendingMachineList[1] = new VendingMachine("chips", 4, 1);
vendingMachineList[2] = new VendingMachine("Drinks", 9, 2);
vendingMachineList[3] = new VendingMachine();
</code>```

Where the bottom vending machine uses a default constructor I made. However when it comes to the user buying a cookie I need to update that particular vending machines item amount. How can I make it so that I can change the amount value only for the item they bought?

these machines are stored in an array as the assignment specifically asks us to do so.

答:
Your VendingMachine likely should have a method that allows you to perform that update.
For the sake of providing an example invocation, let us assume the method is called decreaseStock.  If you are the author of the VendingMachine class, you have the ability to create such a method if you have not already.
Invocation of that method specifically for the "Cookies" VendingMachine would look something like:</p>
```<code>vendingMachineList[0].decreaseStock();
</code>```

Body:
I am currently trying to create a vending machine. In my VendingMachine class I have a constructor that takes in 3 parameters. itemOnSale, amount, and priceOfItem. in my Testclass the vending machines are constructed and stored into an array like this:

VendingMachine[] vendingMachineList = new VendingMachine[4];

vendingMachineList[0] = new VendingMachine("Cookies", 20, 3);
vendingMachineList[1] = new VendingMachine("chips", 4, 1);
vendingMachineList[2] = new VendingMachine("Drinks", 9, 2);
vendingMachineList[3] = new VendingMachine();

Where the bottom vending machine uses a default constructor I made. However when it comes to the user buying a cookie I need to update that particular vending machines item amount. How can I make it so that I can change the amount value only for the item they bought?

these machines are stored in an array as the assignment specifically asks us to do so.

Body:
Your VendingMachine likely should have a method that allows you to perform that update.
For the sake of providing an example invocation, let us assume the method is called decreaseStock.  If you are the author of the VendingMachine class, you have the ability to create such a method if you have not already.
Invocation of that method specifically for the "Cookies" VendingMachine would look something like:

vendingMachineList[0].decreaseStock();


问:
Calculate and list how many different 4 digit numbers can be done with the numbers 0 to 9?
There is something I want to learn.

Let's say we have some single digit numbers.

Example: 1-2-3-4-5-6-7-8-9-0
Example II: 1-2-4-6-0

And with these numbers, we want to get 4-digit numbers that are different from each other.
And we want to print them as lists.

Result:

4676

4236

1247

1236

....

Is it possible to do this?

答:
You can write and run a macro like this:

```<code>// retrieve the selected text
str = document.selection.Text;

// check the input string format. The input must be something like: "1-2-4-6-0"
if( str.length == 0 ) {
    alert( "Select the input string" );
    Quit();
}
for( i = 0; i < str.length; ++i ) {
    c = str.substr( i, 1 );
    if( i % 2 == 0 ) {
        if( c < '0' || c > '9' ) {
            alert( "not digit" );
            Quit();
        }
    }
    else {
        if( c != '-' ) {
            alert( "not separated by '-'" );
            Quit();
        }
    }
}

var arr = new Array();
j = 0;
for( i = 0; i < str.length; ++i ) {
    if( i % 2 == 0 ) {
        c = str.substr( i, 1 );
        arr[j++] = c;
    }
}

if( arr.length < 4 ) {
    alert( "Input string should contain at least 4 digits" );
    Quit();
}

// list all 4-digit combinations
len = arr.length;
str = "";
for( i = 0; i < len; ++i ) {
    for( j = 0; j < len; ++j ) {
        for( k = 0; k < len; ++k ) {
            for( l = 0; l < len; ++l ) {
                str += arr[i] + arr[j] + arr[k] + arr[l] + "\r\n";
            }
        }
    }
}

// write the list in a new document
editor.EnableTab = true;
editor.NewFile();
document.write( str );
</code>```

To run this, save this code as, for instance, GenCombinations.jsee, and then select this file from Select... in the Macros menu. Finally, select Run GenCombinations.jsee in the Macros menu after selecting an input string.

Body:
You can write and run a macro like this:

// retrieve the selected text
str = document.selection.Text;

// check the input string format. The input must be something like: "1-2-4-6-0"
if( str.length == 0 ) {
    alert( "Select the input string" );
    Quit();
}
for( i = 0; i < str.length; ++i ) {
    c = str.substr( i, 1 );
    if( i % 2 == 0 ) {
        if( c < '0' || c > '9' ) {
            alert( "not digit" );
            Quit();
        }
    }
    else {
        if( c != '-' ) {
            alert( "not separated by '-'" );
            Quit();
        }
    }
}

var arr = new Array();
j = 0;
for( i = 0; i < str.length; ++i ) {
    if( i % 2 == 0 ) {
        c = str.substr( i, 1 );
        arr[j++] = c;
    }
}

if( arr.length < 4 ) {
    alert( "Input string should contain at least 4 digits" );
    Quit();
}

// list all 4-digit combinations
len = arr.length;
str = "";
for( i = 0; i < len; ++i ) {
    for( j = 0; j < len; ++j ) {
        for( k = 0; k < len; ++k ) {
            for( l = 0; l < len; ++l ) {
                str += arr[i] + arr[j] + arr[k] + arr[l] + "\r\n";
            }
        }
    }
}

// write the list in a new document
editor.EnableTab = true;
editor.NewFile();
document.write( str );

To run this, save this code as, for instance, GenCombinations.jsee, and then select this file from Select... in the Macros menu. Finally, select Run GenCombinations.jsee in the Macros menu after selecting an input string.


问:
Why is the Python code output like this? (lambda function involved)
I have found a code that orders the elements of a list according to the grades specifid in the tuples that constitute the list.
I cannot understand how it works though: shouldn't be specified somewhere that the parameter data is referred to the students list?
Thanks</p>
```<code>students = [("Squidwaard", "F", 60),
        ("Sandy", "A", 33),
        ("Patrick", "D", 36),
        ("Spongebob", "B", 20),
        ("Mr.Krabs", "C", 78)]

grade = lambda data: data[1]
students.sort(key=grade)

for i in students:
    print(i)
</code>```

答: Well here you did specify in your code. You have wrote a function (anonymous) and called in students.sort(key=grade) what key does is use the function given to sort it by. So you are sorting by the 1st index element, which is the letter grade. Hope this helped, have a nice day!

Body:
I have found a code that orders the elements of a list according to the grades specifid in the tuples that constitute the list.
I cannot understand how it works though: shouldn't be specified somewhere that the parameter data is referred to the students list?
Thanks

students = [("Squidwaard", "F", 60),
        ("Sandy", "A", 33),
        ("Patrick", "D", 36),
        ("Spongebob", "B", 20),
        ("Mr.Krabs", "C", 78)]

grade = lambda data: data[1]
students.sort(key=grade)

for i in students:
    print(i)


问:
Please help me understand Javascript anonymous functions and jQuery .proxy()
I've been trying to wrap my head around how javascript functions and scope work, and it just doesn't make sense to me. Can someone please explain why the following code outputs: 'animal says meow' instead of 'kitty says meow'?

```<code>(function($, exports){
  var animal = function(){};
  exports.Animal = animal;
})(jQuery, window);

(function($, Animal){
  var kitty = new Animal;
  kitty.sayHi = function(){
    console.log(this);
    console.log('says meow');
  }
  $($.proxy(function(){
    $('#js_test').click($.proxy(kitty.sayHi, kitty));
  }, kitty))
})(jQuery, Animal);
</code>```

UPDATE

@FunkyFresh pointed out in the comments that console.log calls toString when it's passed an object, which by default returns the object's type (animal). When I update the above code with

```<code>animal.prototype.name = 'Mammal';
</code>```

in the top block of code, and

```<code>kitty.name = 'Zax';
</code>```

in the bottom, the console outputs 'Zax says meow', which seems about right.

答:
(function($) {})(jQuery)

in this code (function($){}) declares the function. Then (jQuery) imediately calls the function passing in the jQuery object.

so the first block of code passes in jQuery and the window object. Animal is added to the window object, which is the global scope.

in the second block a click event is added to an element and kitty.sayHi is passed in as the event handler. However if the event handler was not proxied then the this keyword in the eventhandler would return the element that has triggered the event. So by using the proxy the scope of the eventhandler becomes kitty.

I hope that is correct, this is new to me also.

Body:
I've been trying to wrap my head around how javascript functions and scope work, and it just doesn't make sense to me. Can someone please explain why the following code outputs: 'animal says meow' instead of 'kitty says meow'?

(function($, exports){
  var animal = function(){};
  exports.Animal = animal;
})(jQuery, window);

(function($, Animal){
  var kitty = new Animal;
  kitty.sayHi = function(){
    console.log(this);
    console.log('says meow');
  }
  $($.proxy(function(){
    $('#js_test').click($.proxy(kitty.sayHi, kitty));
  }, kitty))
})(jQuery, Animal);

UPDATE

@FunkyFresh pointed out in the comments that console.log calls toString when it's passed an object, which by default returns the object's type (animal). When I update the above code with

animal.prototype.name = 'Mammal';

in the top block of code, and

kitty.name = 'Zax';

in the bottom, the console outputs 'Zax says meow', which seems about right.


问:
TailwindCss's mobile breakpoints do not work
I am building a custom navbar in Gatsby using TailwindCss for styling. For reference I am following a tutorial on YouTube which's code can be found here.

When I use the mobile breakpoints as prefix like in the example below only the div saying "mobile" works as it should be:

Layout.js

```<code><nav>
  <div className={"flex"}>
    <div className={"hidden md:flex"}>desktop</div>
    <div className={"md:hidden"}>mobile</div>
  </div>
</nav>
</code>```

tailwind.config.js

```<code>module.exports = {
  content: ["./public/**/*.html", "./src/**/*.{js,jsx,ts,tsx,vue}"],
  darkMode: "class",
  theme: {},
  plugins: []
};
</code>```

styles/global.css

```<code>@tailwind base;
@tailwind components;
@tailwind screens;
@tailwind utilities;
</code>```

The output "desktop" should be shown when the text "mobile" vanishes but for some reason it doesn't. Am I doing something wrong or is there a problem with Tailwind?

EDIT: Reproduction example here

答: Problem solved after I have noticed that the autoprefixer plugin was missing in the postcss.config.js. Just redid the installation for Gatsby.

Body:
I am building a custom navbar in Gatsby using TailwindCss for styling. For reference I am following a tutorial on YouTube which's code can be found here.

When I use the mobile breakpoints as prefix like in the example below only the div saying "mobile" works as it should be:

Layout.js

desktop

mobile

tailwind.config.js

module.exports = {
  content: ["./public/**/*.html", "./src/**/*.{js,jsx,ts,tsx,vue}"],
  darkMode: "class",
  theme: {},
  plugins: []
};

styles/global.css

@tailwind base;
@tailwind components;
@tailwind screens;
@tailwind utilities;

The output "desktop" should be shown when the text "mobile" vanishes but for some reason it doesn't. Am I doing something wrong or is there a problem with Tailwind?

EDIT: Reproduction example here


问:
Why my Qt test (which uses a QProcess) fails?
I created a Qt test which invokes another program thanks to a QProcess. After calling the QProcess::start method, my test waits for it to finish with the QProcess::waitForFinished method. When I run this test with Qt Creator, there's no problem. But when I run it with CTest, the QProcess::waitForFinished function always returns false. Can someone explain me why ? Thank you.

答: Finally, I found a solution : the QProcess:start method couldn't find the program because the working directory of my Qt test wasn't good. So, I changed it with the QDir::setCurrent and now, it works.


问:
Discord.py | Command raised an exception: AttributeError: 'Command' object has no attribute 'Command'
```<code>@bot.command(name='ownerinfo')
async def ownerinfo(ctx: commands.Context):
    embed=discord.Embed(title='DUCKY | Owner Info', color=0x00FFD4)
    embed.set_thumbnail(url='https://url')
    embed.add_field(name="Info", value="text here", inline=False)
    embed.set_footer(text="DUCKY HELPER BOT | -help")
    await ctx.reply(embed=embed)
</code>```

I have a command thats exactly the same as my other commands, but I get this error:

```<code>`AttributeError: 'Command' object has no attribute 'command'`
</code>```

I looked online, and I didnt find any fixes. Can anyone help?

答:
do you have a command that's called bot right before the ownerinfo command? if so, change the function name to _bot and name="bot" inside the command constructor @bot.command(name="bot")

bot = commands.Bot(...)

@bot.command()
async def first_command(ctx, ...):
    # do something

@bot.command()
async def bot(ctx, ...):
    # do something
# your previous declared variable was overridden by a Command function

@bot.command() # error, because it thinks you are using the `Command` function 'bot' instead of your Bot instance
async def ownerinfo(ctx, ...):
    # do something

bot.run()

```
<p>just change your function name:</p>
<pre class="lang-py prettyprint-override"><code>@bot.command(name="bot")
async def _bot(ctx, ...):
    # do something
# it's not overriding anymore
</code>```

Body:
@bot.command(name='ownerinfo')
async def ownerinfo(ctx: commands.Context):
    embed=discord.Embed(title='DUCKY | Owner Info', color=0x00FFD4)
    embed.set_thumbnail(url='https://url')
    embed.add_field(name="Info", value="text here", inline=False)
    embed.set_footer(text="DUCKY HELPER BOT | -help")
    await ctx.reply(embed=embed)

I have a command thats exactly the same as my other commands, but I get this error:

`AttributeError: 'Command' object has no attribute 'command'`

I looked online, and I didnt find any fixes. Can anyone help?

Body:
do you have a command that's called bot right before the ownerinfo command? if so, change the function name to _bot and name="bot" inside the command constructor @bot.command(name="bot")

bot = commands.Bot(...)

@bot.command()
async def first_command(ctx, ...):
    # do something

@bot.command()
async def bot(ctx, ...):
    # do something
# your previous declared variable was overridden by a Command function

@bot.command() # error, because it thinks you are using the `Command` function 'bot' instead of your Bot instance
async def ownerinfo(ctx, ...):
    # do something

bot.run()

just change your function name:

@bot.command(name="bot")
async def _bot(ctx, ...):
    # do something
# it's not overriding anymore


问:
Return multiple values python flask
I am trying to return a file and changing the template in Flask.

```<code>return send_file(myfile, as_attachment=True), return render_template("template.html")
</code>```

But it gives me an error.
If I try to make 2 returns like this:

```<code>return send_file(myfile, as_attachment=True)
return render_template("template.html")
</code>```

or

```<code>return render_template("template.html")
return send_file(myfile, as_attachment=True)
</code>```

It doesn't work eitherway.
How do I fix this?

Thanks

答: You only get one response per request.  You can either send a file, or send a new page.</p>

Title: Return multiple values python flask

Body:
I am trying to return a file and changing the template in Flask.

return send_file(myfile, as_attachment=True), return render_template("template.html")

But it gives me an error.
If I try to make 2 returns like this:

return send_file(myfile, as_attachment=True)
return render_template("template.html")

or

return render_template("template.html")
return send_file(myfile, as_attachment=True)

It doesn't work eitherway.
How do I fix this?

Thanks


问:
How to collect all the id values for a yadcf filtered table
I'm using datatables and yadcf to filter a table. Now I'd like to take all the table row id values, for example, and use those as arguments in a POST request. How can I "collect" the values of these ids from the result of the filters that have been applied? I've seen this example, which doesn't seem to apply to yadcf, but is similar to my use-case.

答: I was able to get the information I wanted using the answer found here. I didn't realize that jQuery will select only the visible elements, which is what I want. So, after applying the yadcf filter to my table it's simple to select all the tr.id values resulting from the filter.


问:
Running one web page across devices with the same data
I want to make a simple todo list web page for myself so that I can be a more organized person but I have a problem. I want to be able to close the website or switch to another computer and still keep the data of what I have done or not done on this to do list. I have tried to search up ways that I could do this online but I don't know what to search to find the right results.

I know about js and web design stuff but I don't know any back end stuff so.

答: One way to do this is to upload your code to Github, which is a code management application for developers. Try searching on youtube how to navigate through GitHub and how to upload your code because im not that good with explanations just yet since im a beginner. Once your code has been uploaded, you can simply log into GitHub with the other device and open your code in a code base.</p>


问:
How do I copy and filter a DAO recordset in VBA?
Due to problems with DAO (see my previous question), I need to create an Excel VBA Recordset from an Access query and filter its results using a user-defined function.

I thought I could use the following code to accomplish this:

```<code>Sub test()

Dim db As Database
Dim rs As Recordset
Dim rs_clone As Recordset

Set db = OpenDatabase(dbPath)
Set rs = db.OpenRecordset("select testVal from dataTable")
Set rs_clone = rs.Clone
rs_clone.MoveLast
rs_clone.MoveFirst
while not rs_clone.eof
 if myUDF(rs_clone!testVal) then
    rs_clone.delete
 end if
 rs_clone.moveNext
wend

End Sub
</code>```

But that actually deletes values from my source table, so the clone isn't a new recordset that I can freely alter, it's just another pointer to the original one.  How can I use my UDF to filter out the records I don't want, while leaving the original data untouched, if putting the UDF in the query itself is not an option?

答:
Use the .getrows method:

```<code>Dim rs_clone As Variant

...

rs_clone = rs.getrows(numrows)
</code>```

then process the resulting 2-d array.

Body:
Due to problems with DAO (see my previous question), I need to create an Excel VBA Recordset from an Access query and filter its results using a user-defined function.

I thought I could use the following code to accomplish this:

Sub test()

Dim db As Database
Dim rs As Recordset
Dim rs_clone As Recordset

Set db = OpenDatabase(dbPath)
Set rs = db.OpenRecordset("select testVal from dataTable")
Set rs_clone = rs.Clone
rs_clone.MoveLast
rs_clone.MoveFirst
while not rs_clone.eof
 if myUDF(rs_clone!testVal) then
    rs_clone.delete
 end if
 rs_clone.moveNext
wend

End Sub

But that actually deletes values from my source table, so the clone isn't a new recordset that I can freely alter, it's just another pointer to the original one.  How can I use my UDF to filter out the records I don't want, while leaving the original data untouched, if putting the UDF in the query itself is not an option?

Body:
Use the .getrows method:

Dim rs_clone As Variant

...

rs_clone = rs.getrows(numrows)

then process the resulting 2-d array.


问:
SIMD code for mesh normals calculation not working (Trying to convert C++ to SIMD)
C++ Code

```<code>void Mesh::RecalculateNormals()
{
        for (int i = 0; i < indexCount; i += 3)
        {
            const int ia = indices[i];
            const int ib = indices[i + 1];
            const int ic = indices[i + 2];

            const glm::vec3 e1 = glm::vec3(vert[ia].position) - glm::vec3(vert[ib].position);
            const glm::vec3 e2 = glm::vec3(vert[ic].position) - glm::vec3(vert[ib].position);
            const glm::vec3 no = cross(e1, e2);

            vert[ia].normal += glm::vec4(no, 0.0);
            vert[ib].normal += glm::vec4(no, 0.0);
            vert[ic].normal += glm::vec4(no, 0.0);
        }

        for (int i = 0; i < vertexCount; i++)
            vert[i].normal = glm::vec4(glm::normalize(glm::vec3(vert[i].normal)), 0.0f);

}
</code>```

New Code with SIMD

```<code>// From :  https://geometrian.com/programming/tutorials/cross-product/index.php
[[nodiscard]] inline static __m128 cross_product(__m128 const& vec0, __m128 const& vec1) {
    __m128 tmp0 = _mm_shuffle_ps(vec0, vec0, _MM_SHUFFLE(3, 0, 2, 1));
    __m128 tmp1 = _mm_shuffle_ps(vec1, vec1, _MM_SHUFFLE(3, 1, 0, 2));
    __m128 tmp2 = _mm_mul_ps(tmp0, vec1);
    __m128 tmp3 = _mm_mul_ps(tmp0, tmp1);
    __m128 tmp4 = _mm_shuffle_ps(tmp2, tmp2, _MM_SHUFFLE(3, 0, 2, 1));
    return _mm_sub_ps(tmp3, tmp4);
}

void normalize(const glm::vec4& lpInput, glm::vec4& lpOutput) {
    const __m128& vInput = reinterpret_cast<const __m128&>(lpInput); // load input vector (x, y, z, a)
    __m128 vSquared = _mm_mul_ps(vInput, vInput); // square the input values
    __m128 vHalfSum = _mm_hadd_ps(vSquared, vSquared);
    __m128 vSum = _mm_hadd_ps(vHalfSum, vHalfSum); // compute the sum of values
    float fInvSqrt; _mm_store_ss(&fInvSqrt, _mm_rsqrt_ss(vSum)); // compute the inverse sqrt
    __m128 vNormalized = _mm_mul_ps(vInput, _mm_set1_ps(fInvSqrt)); // normalize the input vector
    lpOutput = reinterpret_cast<const glm::vec4&>(vNormalized); // store normalized vector (x, y, z, a)
}

void Mesh::RecalculateNormals()
{
        float result[4];
        glm::vec4 tmp;
        for (int i = 0; i < indexCount; i += 3)
        {
            const int ia = indices[i];
            const int ib = indices[i + 1];
            const int ic = indices[i + 2];

            __m128 iav = _mm_set_ps(vert[ia].position.x, vert[ia].position.y, vert[ia].position.z, 0.0f);
            __m128 ibv = _mm_set_ps(vert[ib].position.x, vert[ib].position.y, vert[ib].position.z, 0.0f);
            __m128 icv = _mm_set_ps(vert[ic].position.x, vert[ic].position.y, vert[ic].position.z, 0.0f);

            __m128 e1i = _mm_sub_ps(iav, ibv);
            __m128 e2i = _mm_sub_ps(icv, ibv);

            //const glm::vec3 e1 = glm::vec3(vert[ia].position) - glm::vec3(vert[ib].position);
            //const glm::vec3 e2 = glm::vec3(vert[ic].position) - glm::vec3(vert[ib].position);
            //const glm::vec3 no = cross(e1, e2);

            __m128 no = cross_product(e1i, e2i);

            //vert[ia].normal += glm::vec4(no, 0.0);
            //vert[ib].normal += glm::vec4(no, 0.0);
            //vert[ic].normal += glm::vec4(no, 0.0);
            _mm_storeu_ps(result, no);
            tmp = glm::make_vec4(result);
            vert[ia].normal += tmp;
            vert[ib].normal += tmp;
            vert[ic].normal += tmp;
        }

        for (int i = 0; i < vertexCount; i++)
            vert[i].normal = glm::vec4(glm::normalize(glm::vec3(vert[i].normal)), 0.0f);

}
</code>```

But its not working. Please can anyone help finding the problems.

(I am very new to SIMD)

答:
Your correctness problem is probably caused by Intel screwing up the order of their _mm_set_ps and similar intrinsics.
To create a vector with x, y, z floats in the first 3 lanes, write either _mm_set_ps( 0, z, y, x ) or _mm_setr_ps( x, y, z, 0 ).

Here’s better primitive functions you gonna need for that. That code assumes you have at least SSE 4.1, that thing is introduced in the Intel Core 2 in 2007, and according to Steam survey the market penetration is 98.89% by now.

```<code>// Load an FP32 3D vector from memory
inline __m128 loadFloat3( const glm::vec3& pos )
{
    static_assert( sizeof( glm::vec3 ) == 12, "Expected to be 12 bytes (3 floats)" );

    __m128 low = _mm_castpd_ps( _mm_load_sd( (const double*)&pos ) );
    // Modern compilers are optimizing the following 2 intrinsics into a single insertps with a memory operand
    __m128 high = _mm_load_ss( ( (const float*)&pos ) + 2 );
    return _mm_insert_ps( low, high, 0x27 );
}

// Store an FP32 3D vector to memory
inline void storeFloat3( glm::vec3& pos, __m128 vec )
{
    _mm_store_sd( (double*)&pos, _mm_castps_pd( vec ) );
    ( (int*)( &pos ) )[ 2 ] = _mm_extract_ps( vec, 2 );
}

// Zero out W lane, and store an FP32 vector to memory
inline void storeFloat4( glm::vec4& pos, __m128 vec )
{
    static_assert( sizeof( glm::vec4 ) == 16, "Expected to be 16 bytes" );
    vec = _mm_insert_ps( vec, vec, 0b1000 );
    _mm_storeu_ps( (float*)&pos, vec );
}

// Normalize a 3D vector; if the source is zero, will instead return a zero vector
inline __m128 vector3Normalize( __m128 vec )
{
    // Compute x^2 + y^2 + z^2, broadcast the result to all 4 lanes
    __m128 dp = _mm_dp_ps( vec, vec, 0b01111111 );
    // res = vec / sqrt( dp )
    __m128 res = _mm_div_ps( vec, _mm_sqrt_ps( dp ) );
    // Compare for dp > 0
    __m128 positiveLength = _mm_cmpgt_ps( dp, _mm_setzero_ps() );
    // Zero out the vector if the dot product was zero
    return _mm_and_ps( res, positiveLength );
}

// Copy-pasted from there: https://github.com/microsoft/DirectXMath/blob/jan2021/Inc/DirectXMathVector.inl#L9506-L9519
// MIT license
#ifdef __AVX__
#define XM_PERMUTE_PS( v, c ) _mm_permute_ps( v, c )
#else
#define XM_PERMUTE_PS( v, c ) _mm_shuffle_ps( v, v, c )
#endif

#ifdef __AVX2__
#define XM_FNMADD_PS( a, b, c ) _mm_fnmadd_ps((a), (b), (c))
#else
#define XM_FNMADD_PS( a, b, c ) _mm_sub_ps((c), _mm_mul_ps((a), (b)))
#endif

inline __m128 vector3Cross( __m128 V1, __m128 V2 )
{
    // y1,z1,x1,w1
    __m128 vTemp1 = XM_PERMUTE_PS( V1, _MM_SHUFFLE( 3, 0, 2, 1 ) );
    // z2,x2,y2,w2
    __m128 vTemp2 = XM_PERMUTE_PS( V2, _MM_SHUFFLE( 3, 1, 0, 2 ) );
    // Perform the left operation
    __m128 vResult = _mm_mul_ps( vTemp1, vTemp2 );
    // z1, x1, y1, w1
    vTemp1 = XM_PERMUTE_PS( vTemp1, _MM_SHUFFLE( 3, 0, 2, 1 ) );
    // y2, z2, x2, w2
    vTemp2 = XM_PERMUTE_PS( vTemp2, _MM_SHUFFLE( 3, 1, 0, 2 ) );
    // Perform the right operation
    vResult = XM_FNMADD_PS( vTemp1, vTemp2, vResult );
    return vResult;
}
</code>```

You should not expect high quality results with that algorithm. It computes per-vertex normals by accumulating triangle normals weighted by triangle’s area. This means if your mesh has both small and large triangles, the normals of the small triangles will be ignored, which is suboptimal. A better way is weighting normals by triangle’s angles at vertices. See this article for more information.

Body:
C++ Code

void Mesh::RecalculateNormals()
{
        for (int i = 0; i < indexCount; i += 3)
        {
            const int ia = indices[i];
            const int ib = indices[i + 1];
            const int ic = indices[i + 2];

            const glm::vec3 e1 = glm::vec3(vert[ia].position) - glm::vec3(vert[ib].position);
            const glm::vec3 e2 = glm::vec3(vert[ic].position) - glm::vec3(vert[ib].position);
            const glm::vec3 no = cross(e1, e2);

            vert[ia].normal += glm::vec4(no, 0.0);
            vert[ib].normal += glm::vec4(no, 0.0);
            vert[ic].normal += glm::vec4(no, 0.0);
        }

        for (int i = 0; i < vertexCount; i++)
            vert[i].normal = glm::vec4(glm::normalize(glm::vec3(vert[i].normal)), 0.0f);

}

New Code with SIMD

// From :  https://geometrian.com/programming/tutorials/cross-product/index.php
[[nodiscard]] inline static __m128 cross_product(__m128 const& vec0, __m128 const& vec1) {
    __m128 tmp0 = _mm_shuffle_ps(vec0, vec0, _MM_SHUFFLE(3, 0, 2, 1));
    __m128 tmp1 = _mm_shuffle_ps(vec1, vec1, _MM_SHUFFLE(3, 1, 0, 2));
    __m128 tmp2 = _mm_mul_ps(tmp0, vec1);
    __m128 tmp3 = _mm_mul_ps(tmp0, tmp1);
    __m128 tmp4 = _mm_shuffle_ps(tmp2, tmp2, _MM_SHUFFLE(3, 0, 2, 1));
    return _mm_sub_ps(tmp3, tmp4);
}

void normalize(const glm::vec4& lpInput, glm::vec4& lpOutput) {
    const __m128& vInput = reinterpret_cast<const __m128&>(lpInput); // load input vector (x, y, z, a)
    __m128 vSquared = _mm_mul_ps(vInput, vInput); // square the input values
    __m128 vHalfSum = _mm_hadd_ps(vSquared, vSquared);
    __m128 vSum = _mm_hadd_ps(vHalfSum, vHalfSum); // compute the sum of values
    float fInvSqrt; _mm_store_ss(&fInvSqrt, _mm_rsqrt_ss(vSum)); // compute the inverse sqrt
    __m128 vNormalized = _mm_mul_ps(vInput, _mm_set1_ps(fInvSqrt)); // normalize the input vector
    lpOutput = reinterpret_cast<const glm::vec4&>(vNormalized); // store normalized vector (x, y, z, a)
}

void Mesh::RecalculateNormals()
{
        float result[4];
        glm::vec4 tmp;
        for (int i = 0; i < indexCount; i += 3)
        {
            const int ia = indices[i];
            const int ib = indices[i + 1];
            const int ic = indices[i + 2];

            __m128 iav = _mm_set_ps(vert[ia].position.x, vert[ia].position.y, vert[ia].position.z, 0.0f);
            __m128 ibv = _mm_set_ps(vert[ib].position.x, vert[ib].position.y, vert[ib].position.z, 0.0f);
            __m128 icv = _mm_set_ps(vert[ic].position.x, vert[ic].position.y, vert[ic].position.z, 0.0f);

            __m128 e1i = _mm_sub_ps(iav, ibv);
            __m128 e2i = _mm_sub_ps(icv, ibv);

            //const glm::vec3 e1 = glm::vec3(vert[ia].position) - glm::vec3(vert[ib].position);
            //const glm::vec3 e2 = glm::vec3(vert[ic].position) - glm::vec3(vert[ib].position);
            //const glm::vec3 no = cross(e1, e2);

            __m128 no = cross_product(e1i, e2i);

            //vert[ia].normal += glm::vec4(no, 0.0);
            //vert[ib].normal += glm::vec4(no, 0.0);
            //vert[ic].normal += glm::vec4(no, 0.0);
            _mm_storeu_ps(result, no);
            tmp = glm::make_vec4(result);
            vert[ia].normal += tmp;
            vert[ib].normal += tmp;
            vert[ic].normal += tmp;
        }

        for (int i = 0; i < vertexCount; i++)
            vert[i].normal = glm::vec4(glm::normalize(glm::vec3(vert[i].normal)), 0.0f);

}

But its not working. Please can anyone help finding the problems.

(I am very new to SIMD)

Body:
Your correctness problem is probably caused by Intel screwing up the order of their _mm_set_ps and similar intrinsics.
To create a vector with x, y, z floats in the first 3 lanes, write either _mm_set_ps( 0, z, y, x ) or _mm_setr_ps( x, y, z, 0 ).

Here’s better primitive functions you gonna need for that. That code assumes you have at least SSE 4.1, that thing is introduced in the Intel Core 2 in 2007, and according to Steam survey the market penetration is 98.89% by now.

// Load an FP32 3D vector from memory
inline __m128 loadFloat3( const glm::vec3& pos )
{
    static_assert( sizeof( glm::vec3 ) == 12, "Expected to be 12 bytes (3 floats)" );

    __m128 low = _mm_castpd_ps( _mm_load_sd( (const double*)&pos ) );
    // Modern compilers are optimizing the following 2 intrinsics into a single insertps with a memory operand
    __m128 high = _mm_load_ss( ( (const float*)&pos ) + 2 );
    return _mm_insert_ps( low, high, 0x27 );
}

// Store an FP32 3D vector to memory
inline void storeFloat3( glm::vec3& pos, __m128 vec )
{
    _mm_store_sd( (double*)&pos, _mm_castps_pd( vec ) );
    ( (int*)( &pos ) )[ 2 ] = _mm_extract_ps( vec, 2 );
}

// Zero out W lane, and store an FP32 vector to memory
inline void storeFloat4( glm::vec4& pos, __m128 vec )
{
    static_assert( sizeof( glm::vec4 ) == 16, "Expected to be 16 bytes" );
    vec = _mm_insert_ps( vec, vec, 0b1000 );
    _mm_storeu_ps( (float*)&pos, vec );
}

// Normalize a 3D vector; if the source is zero, will instead return a zero vector
inline __m128 vector3Normalize( __m128 vec )
{
    // Compute x^2 + y^2 + z^2, broadcast the result to all 4 lanes
    __m128 dp = _mm_dp_ps( vec, vec, 0b01111111 );
    // res = vec / sqrt( dp )
    __m128 res = _mm_div_ps( vec, _mm_sqrt_ps( dp ) );
    // Compare for dp > 0
    __m128 positiveLength = _mm_cmpgt_ps( dp, _mm_setzero_ps() );
    // Zero out the vector if the dot product was zero
    return _mm_and_ps( res, positiveLength );
}

// Copy-pasted from there: https://github.com/microsoft/DirectXMath/blob/jan2021/Inc/DirectXMathVector.inl#L9506-L9519
// MIT license
#ifdef __AVX__
#define XM_PERMUTE_PS( v, c ) _mm_permute_ps( v, c )
#else
#define XM_PERMUTE_PS( v, c ) _mm_shuffle_ps( v, v, c )
#endif

#ifdef __AVX2__
#define XM_FNMADD_PS( a, b, c ) _mm_fnmadd_ps((a), (b), (c))
#else
#define XM_FNMADD_PS( a, b, c ) _mm_sub_ps((c), _mm_mul_ps((a), (b)))
#endif

inline __m128 vector3Cross( __m128 V1, __m128 V2 )
{
    // y1,z1,x1,w1
    __m128 vTemp1 = XM_PERMUTE_PS( V1, _MM_SHUFFLE( 3, 0, 2, 1 ) );
    // z2,x2,y2,w2
    __m128 vTemp2 = XM_PERMUTE_PS( V2, _MM_SHUFFLE( 3, 1, 0, 2 ) );
    // Perform the left operation
    __m128 vResult = _mm_mul_ps( vTemp1, vTemp2 );
    // z1, x1, y1, w1
    vTemp1 = XM_PERMUTE_PS( vTemp1, _MM_SHUFFLE( 3, 0, 2, 1 ) );
    // y2, z2, x2, w2
    vTemp2 = XM_PERMUTE_PS( vTemp2, _MM_SHUFFLE( 3, 1, 0, 2 ) );
    // Perform the right operation
    vResult = XM_FNMADD_PS( vTemp1, vTemp2, vResult );
    return vResult;
}

You should not expect high quality results with that algorithm. It computes per-vertex normals by accumulating triangle normals weighted by triangle’s area. This means if your mesh has both small and large triangles, the normals of the small triangles will be ignored, which is suboptimal. A better way is weighting normals by triangle’s angles at vertices. See this article for more information.