答:
Maybe this one?

    var checkbox = document.getElementById('checkbox');
    checkbox.addEventListener('change', ()=>{
      if (checkbox.checked == true){
        document.getElementById('body').classList.toggle('dark-mode',true);
        document.getElementById('body').classList.toggle('light-mode',false);
      } else {
        document.getElementById('body').classList.toggle('dark-mode',false);
        document.getElementById('body').classList.toggle('light-mode',true);
      }
    } )```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    .dark-mode {
      background-color: black;
      color: white;
    }

    .light-mode {
      background-color: white;
      color: black;
    }</code>```

       <input id="checkbox" type="checkbox" >

    ```

Title: Checkbox classList Toggle

Body:
Maybe this one?

    var checkbox = document.getElementById('checkbox');
    checkbox.addEventListener('change', ()=>{
      if (checkbox.checked == true){
        document.getElementById('body').classList.toggle('dark-mode',true);
        document.getElementById('body').classList.toggle('light-mode',false);
      } else {
        document.getElementById('body').classList.toggle('dark-mode',false);
        document.getElementById('body').classList.toggle('light-mode',true);
      }
    } )

    .dark-mode {
      background-color: black;
      color: white;
    }

    .light-mode {
      background-color: white;
      color: black;
    }

    <label class="switch">
       <input id="checkbox" type="checkbox" >
       <span class="slider round"></span>
    </label>

      <body id='body'>
    </body>


来源: stackexchange

问:
VB.NET Process Standart Output redirect does not work on OpenSSH SCP
Somehow Standart Output is not redirected when i use the OpenSSH SCP Executable with System.Diagnostics.Process

I'm working on managed Windows PC and have to send files to an SFTP Server which is password only protected. As i'm not able to install any other program or library im stuck with Windows's default OpenSSH Client which has no password argument. The PCs are behind a corporate Firewall which have no access to the internet. But thats what i'm stuck with.

My Approach is to use System.Diagnostics.Process to launch the SCP command, listen for the Password prompt and then use System.IO.StreamWriter to send it.

while this does seem to work on test cases where i listened to ipconfig and sent input afterwards, i'm struggling with scp, sftp and other programms as the DefaultOutput does not seems to be redirected.

Simplified Code:

Private Dim Output = ""
Public Function CreateAndStartProcess(FileName As String, Optional Arguments As String = "")
  Dim targetProcess As New Process()
  targetProcess.StartInfo.FileName = FileName
  targetProcess.StartInfo.Arguments = Arguments
  targetProcess.StartInfo.UseShellExecute = False
  targetProcess.StartInfo.RedirectStandardInput = True
  targetProcess.StartInfo.RedirectStandardOutput = True
  targetProcess.StartInfo.CreateNoWindow = False

  targetProcess.Start()
  AddHandler targetProcess.OutputDataReceived, OutputHandler

  return targetProcess
End Function

Sub OutputHandler(sender, e, process) //never gets called
  If String.IsNullOrEmpty(e.Data) Then
    Exit Sub
  End If

  Output = Output & Environment.NewLine & e.Data
End Sub

Dim targetProcess = CreateAndStartProcess("C:\\Windows\\Sysnative\\OpenSSH\\scp.exe", "C:\test.txt user@host:/test")
System.Threading.Thread.Sleep(2000) //just for simplification
Dim SW As System.IO.StreamWriter = targetProcess.StandardInput
SW.WriteLine("password")

```

When i put a breakpoint into OutputHandler, it never gets called. After execution the Output String is empty

Is there anything i'm missing? when using ipconfig it works just fine.

答:
Not sure how you got that to compile. You method signature for the output handler was wrong...

Based on your VB code it looks like you might be trying to recreate the C# example from https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.outputdatareceived?view=net-6.0

I don't have whatever host you are trying to connect to, so the OutputHandler when it fired for me was an empty string. However, the ErrorHandler I added in the code below had output from the process.

I'd recommend reading the doc I link above.
A couple of key points from their example code that I used to modify your code:

You have to call process.BeginOutputReadLine() to get the OutputHandler method to fire.

You need to call process.WaitForExit() or set process.EnableRaiseEvents = True and add an Exit event handler or you're never going to know when the process ends.

The output event handler only gets called when a newline (CR, LF, or CR+LF) are sent to the StandardOutput stream. It could be that line says 'Password:' is waiting for input on that line, so newline has been sent yet, and so Password: hasn't been sent to our OutputHandler. So instead of the OutputHandler method, you might need to tap into the StandardOutput stream directly to read without waiting for a newline.

You might want to add the ErrorHandler method (or something similar) in case you are getting an error message to the StandardError stream instead of the output stream.

```<code> Sub Main()
     Dim targetProcess = CreateAndStartProcess("C:\\Windows\\Sysnative\\OpenSSH\\scp.exe", "C:\test.txt user@host:/test")
     targetProcess.BeginOutputReadLine()
     targetProcess.BeginErrorReadLine()

     Dim SW As System.IO.StreamWriter = targetProcess.StandardInput
     System.Threading.Thread.Sleep(2000) '//just For simplification
     SW.WriteLine("password")

     targetProcess.WaitForExit()

     If Not String.IsNullOrEmpty(Output) Then Console.WriteLine(Output)
     If Not String.IsNullOrEmpty(ErrorOutput) Then Console.WriteLine(ErrorOutput)
     targetProcess.WaitForExit()
     targetProcess.Close()

     Console.WriteLine(Environment.NewLine & Environment.NewLine & "Press any key to exit.")
     Console.ReadLine()
 End Sub

 Private Output As String = ""
 Private ErrorOutput As String = ""
 Public Function CreateAndStartProcess(FileName As String, Optional Arguments As String = "") As Process
     Dim targetProcess As New Process()
     targetProcess.StartInfo.FileName = FileName
     targetProcess.StartInfo.Arguments = Arguments
     targetProcess.StartInfo.UseShellExecute = False
     targetProcess.StartInfo.RedirectStandardInput = True
     targetProcess.StartInfo.RedirectStandardOutput = True
     targetProcess.StartInfo.RedirectStandardError = True
     targetProcess.StartInfo.CreateNoWindow = False

     AddHandler targetProcess.ErrorDataReceived, AddressOf ErrorHandler
     AddHandler targetProcess.OutputDataReceived, AddressOf OutputHandler
     targetProcess.Start()

     Return targetProcess
 End Function

 Sub OutputHandler(sender As Object, e As DataReceivedEventArgs) '//never gets called
     If String.IsNullOrEmpty(e.Data) Then
         Exit Sub
     End If

     Output = Output & Environment.NewLine & e.Data
 End Sub

 Sub ErrorHandler(sender As Object, e As DataReceivedEventArgs) '//never gets called
     If String.IsNullOrEmpty(e.Data) Then
         Exit Sub
     End If

     ErrorOutput = ErrorOutput & Environment.NewLine & e.Data
 End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Somehow Standart Output is not redirected when i use the OpenSSH SCP Executable with System.Diagnostics.Process

I'm working on managed Windows PC and have to send files to an SFTP Server which is password only protected. As i'm not able to install any other program or library im stuck with Windows's default OpenSSH Client which has no password argument. The PCs are behind a corporate Firewall which have no access to the internet. But thats what i'm stuck with.

My Approach is to use System.Diagnostics.Process to launch the SCP command, listen for the Password prompt and then use System.IO.StreamWriter to send it.

while this does seem to work on test cases where i listened to ipconfig and sent input afterwards, i'm struggling with scp, sftp and other programms as the DefaultOutput does not seems to be redirected.

Simplified Code:

Private Dim Output = ""
Public Function CreateAndStartProcess(FileName As String, Optional Arguments As String = "")
  Dim targetProcess As New Process()
  targetProcess.StartInfo.FileName = FileName
  targetProcess.StartInfo.Arguments = Arguments
  targetProcess.StartInfo.UseShellExecute = False
  targetProcess.StartInfo.RedirectStandardInput = True
  targetProcess.StartInfo.RedirectStandardOutput = True
  targetProcess.StartInfo.CreateNoWindow = False

  targetProcess.Start()
  AddHandler targetProcess.OutputDataReceived, OutputHandler

  return targetProcess
End Function

Sub OutputHandler(sender, e, process) //never gets called
  If String.IsNullOrEmpty(e.Data) Then
    Exit Sub
  End If

  Output = Output & Environment.NewLine & e.Data
End Sub

Dim targetProcess = CreateAndStartProcess("C:\\Windows\\Sysnative\\OpenSSH\\scp.exe", "C:\test.txt user@host:/test")
System.Threading.Thread.Sleep(2000) //just for simplification
Dim SW As System.IO.StreamWriter = targetProcess.StandardInput
SW.WriteLine("password")

When i put a breakpoint into OutputHandler, it never gets called. After execution the Output String is empty

Is there anything i'm missing? when using ipconfig it works just fine.

Body:
Not sure how you got that to compile. You method signature for the output handler was wrong...

Based on your VB code it looks like you might be trying to recreate the C# example from https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.outputdatareceived?view=net-6.0

I don't have whatever host you are trying to connect to, so the OutputHandler when it fired for me was an empty string. However, the ErrorHandler I added in the code below had output from the process.

I'd recommend reading the doc I link above.
A couple of key points from their example code that I used to modify your code:

You have to call process.BeginOutputReadLine() to get the OutputHandler method to fire.

You need to call process.WaitForExit() or set process.EnableRaiseEvents = True and add an Exit event handler or you're never going to know when the process ends.

The output event handler only gets called when a newline (CR, LF, or CR+LF) are sent to the StandardOutput stream. It could be that line says 'Password:' is waiting for input on that line, so newline has been sent yet, and so Password: hasn't been sent to our OutputHandler. So instead of the OutputHandler method, you might need to tap into the StandardOutput stream directly to read without waiting for a newline.

You might want to add the ErrorHandler method (or something similar) in case you are getting an error message to the StandardError stream instead of the output stream.

 Sub Main()
     Dim targetProcess = CreateAndStartProcess("C:\\Windows\\Sysnative\\OpenSSH\\scp.exe", "C:\test.txt user@host:/test")
     targetProcess.BeginOutputReadLine()
     targetProcess.BeginErrorReadLine()

     Dim SW As System.IO.StreamWriter = targetProcess.StandardInput
     System.Threading.Thread.Sleep(2000) '//just For simplification
     SW.WriteLine("password")

     targetProcess.WaitForExit()

     If Not String.IsNullOrEmpty(Output) Then Console.WriteLine(Output)
     If Not String.IsNullOrEmpty(ErrorOutput) Then Console.WriteLine(ErrorOutput)
     targetProcess.WaitForExit()
     targetProcess.Close()

     Console.WriteLine(Environment.NewLine & Environment.NewLine & "Press any key to exit.")
     Console.ReadLine()
 End Sub

 Private Output As String = ""
 Private ErrorOutput As String = ""
 Public Function CreateAndStartProcess(FileName As String, Optional Arguments As String = "") As Process
     Dim targetProcess As New Process()
     targetProcess.StartInfo.FileName = FileName
     targetProcess.StartInfo.Arguments = Arguments
     targetProcess.StartInfo.UseShellExecute = False
     targetProcess.StartInfo.RedirectStandardInput = True
     targetProcess.StartInfo.RedirectStandardOutput = True
     targetProcess.StartInfo.RedirectStandardError = True
     targetProcess.StartInfo.CreateNoWindow = False

     AddHandler targetProcess.ErrorDataReceived, AddressOf ErrorHandler
     AddHandler targetProcess.OutputDataReceived, AddressOf OutputHandler
     targetProcess.Start()

     Return targetProcess
 End Function

 Sub OutputHandler(sender As Object, e As DataReceivedEventArgs) '//never gets called
     If String.IsNullOrEmpty(e.Data) Then
         Exit Sub
     End If

     Output = Output & Environment.NewLine & e.Data
 End Sub

 Sub ErrorHandler(sender As Object, e As DataReceivedEventArgs) '//never gets called
     If String.IsNullOrEmpty(e.Data) Then
         Exit Sub
     End If

     ErrorOutput = ErrorOutput & Environment.NewLine & e.Data
 End Sub


问:
How to get unique count by month for different categories in pandas?
I have a pandas data frame like this:

```<code>Month      ID
Sep 21     ID_1
Sep 21     ID_2
Sep 21     ID_3
Oct 21     ID_1
Oct 21     ID_2
Oct 21     ID_4
Oct 21     ID_5
Nov 21     ID_1
Nov 21     ID_2
Nov 21     ID_3
Nov 21     ID_4
Dec 21     ID_2
Dec 21     ID_3
Dec 21     ID_4
Dec 21     ID_5
Jan 22     ID_3
Jan 22     ID_4
Jan 22     ID_5
</code>```

and i want ID counts in a format like this as the output pandas dataframe:

where as values i can get unique count of IDs for each month like ID1 in October 2 should be counted under 2 months as it is appearing for 2 months now and in Nov ID2 will be counted under 3 month as it is consistently appearing for 3 months. But as ID5 appears first time in Oct it will be counted under 1 month in Oct and so on. Any ID which appears more than 4 times should be counted under 4 month+ category.

In pandas i am not sure how to go about this approach to get this unique count and have a pivot table.

答:
First, this will create a matrix of occurence. Note that I used date-time format for Month for easy-sorting.

```<code>step1 = pd.crosstab(
    df['ID'],
    pd.to_datetime(df['Month'], format='%b %y')
)

Month   2021-09-01  2021-10-01  2021-11-01  2021-12-01  2022-01-01
ID
ID_1    1   1   1   0   0
ID_2    1   1   1   1   0
ID_3    1   0   1   1   1
ID_4    0   1   1   1   1
ID_5    0   1   0   1   1
</code>```

Then, do the cumulative sum that satisfy the continuity condition

```<code>for month_prev, month_next in zip(step1.columns, step1.columns[1:]):
    step1[month_next] = (step1[month_next] + step1[month_prev]) * step1[month_next]

Month   2021-09-01  2021-10-01  2021-11-01  2021-12-01  2022-01-01
ID
ID_1    1   2   3   0   0
ID_2    1   2   3   4   0
ID_3    1   0   1   2   3
ID_4    0   1   2   3   4
ID_5    0   1   0   1   2
</code>```

Then, we apply melt, groupby, value_counts to count those cumsum-values  for each month, unstack to move Month to the columns, and the rest 3 methods to take care of formatting.

```<code>step2 = pd.melt(step1)\
    .groupby('Month')['value']\
    .value_counts()\
    .unstack(level=0)\
    .fillna(0)\
    .drop(0)\
    .astype(int)

Month   2021-09-01  2021-10-01  2021-11-01  2021-12-01  2022-01-01
value
1   3   2   1   1   0
2   0   2   1   1   1
3   0   0   2   1   1
4   0   0   0   1   1
</code>```

Last step for further formattings:

```<code>step2.columns = step2.columns.strftime('%b %y')
step2.loc[4] = step2.loc[step2.index>=4].sum()
step2.index = (step2.index.astype(str) + ' Month').str.replace('4 Month', '4 Month+')

Month   Sep 21  Oct 21  Nov 21  Dec 21  Jan 22
value
1 Month 3   2   1   1   0
2 Month 0   2   1   1   1
3 Month 0   0   2   1   1
4 Month+    0   0   0   1   1
</code>```

Body:
I have a pandas data frame like this:

Month      ID
Sep 21     ID_1
Sep 21     ID_2
Sep 21     ID_3
Oct 21     ID_1
Oct 21     ID_2
Oct 21     ID_4
Oct 21     ID_5
Nov 21     ID_1
Nov 21     ID_2
Nov 21     ID_3
Nov 21     ID_4
Dec 21     ID_2
Dec 21     ID_3
Dec 21     ID_4
Dec 21     ID_5
Jan 22     ID_3
Jan 22     ID_4
Jan 22     ID_5

and i want ID counts in a format like this as the output pandas dataframe:

where as values i can get unique count of IDs for each month like ID1 in October 2 should be counted under 2 months as it is appearing for 2 months now and in Nov ID2 will be counted under 3 month as it is consistently appearing for 3 months. But as ID5 appears first time in Oct it will be counted under 1 month in Oct and so on. Any ID which appears more than 4 times should be counted under 4 month+ category.

In pandas i am not sure how to go about this approach to get this unique count and have a pivot table.

Body:
First, this will create a matrix of occurence. Note that I used date-time format for Month for easy-sorting.

step1 = pd.crosstab(
    df['ID'],
    pd.to_datetime(df['Month'], format='%b %y')
)

Month   2021-09-01  2021-10-01  2021-11-01  2021-12-01  2022-01-01
ID
ID_1    1   1   1   0   0
ID_2    1   1   1   1   0
ID_3    1   0   1   1   1
ID_4    0   1   1   1   1
ID_5    0   1   0   1   1

Then, do the cumulative sum that satisfy the continuity condition

for month_prev, month_next in zip(step1.columns, step1.columns[1:]):
    step1[month_next] = (step1[month_next] + step1[month_prev]) * step1[month_next]

Month   2021-09-01  2021-10-01  2021-11-01  2021-12-01  2022-01-01
ID
ID_1    1   2   3   0   0
ID_2    1   2   3   4   0
ID_3    1   0   1   2   3
ID_4    0   1   2   3   4
ID_5    0   1   0   1   2

Then, we apply melt, groupby, value_counts to count those cumsum-values  for each month, unstack to move Month to the columns, and the rest 3 methods to take care of formatting.

step2 = pd.melt(step1)\
    .groupby('Month')['value']\
    .value_counts()\
    .unstack(level=0)\
    .fillna(0)\
    .drop(0)\
    .astype(int)

Month   2021-09-01  2021-10-01  2021-11-01  2021-12-01  2022-01-01
value
1   3   2   1   1   0
2   0   2   1   1   1
3   0   0   2   1   1
4   0   0   0   1   1

Last step for further formattings:

step2.columns = step2.columns.strftime('%b %y')
step2.loc[4] = step2.loc[step2.index>=4].sum()
step2.index = (step2.index.astype(str) + ' Month').str.replace('4 Month', '4 Month+')

Month   Sep 21  Oct 21  Nov 21  Dec 21  Jan 22
value
1 Month 3   2   1   1   0
2 Month 0   2   1   1   1
3 Month 0   0   2   1   1
4 Month+    0   0   0   1   1


问:
Python (Tkinter)- Selecting specific Pandas dataframe from Tkinter combobox
I am having trouble with a Tkinter app I am making where the user would first select the dataframe from a combobox (combobox #1) which is a list of facilities within a given year (i.e., 2021 or 2022).  After the dataframe is identified, the user would select a list of facilities by state in a second combobox.

If I preselect the dataframe, everything works fine.  However, the user may want different years and does not want to use the Tkinter Filedialogue function. Basically, they want a dropdown menu that selects the dataframe. As I have it now, I can get it to work if I use the Input option from the command prompt, but I don't want to do that (see TEMP_SOLUTION section).

Bottom line - how can I first select the dataframe from a combobox (i.e., combobox #1) and make the state combobox use this selected dataframe as its source?  Any help is appreciated.

```<code>import pandas as pd
from tkinter import ttk
import numpy as np
from tkinter import Tk
import tkinter as tk

# function to get unique values
def unique(list1):
    x = np.array(list1)
    print(np.unique(x))

def make_df(): #I'd like to make the dataframe from here, but I am having trouble
    val = n3.get()
    if val == 'df2022':
        df = df2022
    else:
        df = df2021

def on_click():
    val = n.get()
    df2 = df[ df['state'] == val ]
    print(df2)

#DATAFRAMES

df2022 = pd.DataFrame({
   'id': ['1','2','3'],
   'state': ['mi','mi','oh'],
   'provname': ['abc facility','123 facility','acme facility'],
   'workdate':['1/1/2022', '1/3/2022', '6/8/2022']
})

df2021 = pd.DataFrame({
   'id': ['4','5','6'],
   'state': ['al','al','az'],
   'provname': ['jimmy state facility','mack 10 facility','heathcliff facility'],
   'workdate':['3/3/2021', '12/13/2021', '10/31/2021']
})

#TEMP SOLUTION - I don't want to do this with the command prompt, but it's all I can get to work right now
temp_idea = input('enter df2021 or df2022: ')
if temp_idea == 'df2021':
    df = df2021
else:
    df = df2022

# Create Combobox for selecting dataframe (NOT WORKING)
n3 = tk.StringVar()
da = ttk.Combobox(window, width = 60, textvariable = n3)

da['values'] = ['df2022', 'df2021']
da.grid(column = 1, row = 1, padx = 3, pady = 20)

ttk.Button(window, text = "Add Dataframe", command=make_df).grid(column = 2,
          row = 1, padx = 3, pady = 10)

#STATE FILTER

values = ['all'] + list(df['state'].unique())

window = tk.Tk()
window.title('Combobox')
window.geometry('600x400')
window.focus_set()

ttk.Label(window, text = "Main Menu",
          foreground ="black",
          font = ("Times New Roman", 20)).grid(row = 0, column = 1)

#FILTER STATE - PART 1
ttk.Label(window, text = "Select the State:",
          font = ("Times New Roman", 12)).grid(column = 0,
          row = 2, padx = 3, pady = 29)

n = tk.StringVar()
state = ttk.Combobox(window, width = 60, textvariable = n)
state['values'] = sorted(list(df['state'].unique()))
state.grid(column = 1, row = 2, padx = 3, pady = 20)

ttk.Button(window, text = "OK", command=on_click).grid(column = 2,
          row = 2, padx = 3, pady = 10)

state.current()

window.mainloop()

</code>```

答:
You can update combobox state based on selected dataframe inside make_df().  Also you can bind on <<ComboboxSelected>> virtual event instead of using the Add Dataframe button:

import tkinter as tk
from tkinter import ttk
import pandas as pd

def make_df(event=None):
    global df
    val = n3.get()
    if val == 'df2022':
        df = df2022
    else:
        df = df2021
    # update combobox 'state'
    values = ['all'] + sorted(df['state'].unique())
    state['values'] = values
    state.set('all') # select 'all' initially

def on_click():
    val = n.get()
    df2 = df if val == 'all' else df[ df['state'] == val ]
    print(df2)

#DATAFRAMES

df2022 = pd.DataFrame({
   'id': ['1','2','3'],
   'state': ['mi','mi','oh'],
   'provname': ['abc facility','123 facility','acme facility'],
   'workdate':['1/1/2022', '1/3/2022', '6/8/2022']
})

df2021 = pd.DataFrame({
   'id': ['4','5','6'],
   'state': ['al','al','az'],
   'provname': ['jimmy state facility','mack 10 facility','heathcliff facility'],
   'workdate':['3/3/2021', '12/13/2021', '10/31/2021']
})

window = tk.Tk()
window.title('Combobox')
window.geometry('600x400')
window.focus_set()

ttk.Label(window, text = "Select Dataframe:",
          font = ("Times New Roman", 12)).grid(column = 0,
          row = 1, padx = 3, pady = 29)

# Create Combobox for selecting dataframe (NOT WORKING)
n3 = tk.StringVar()
da = ttk.Combobox(window, width = 60, textvariable = n3)
da['values'] = ['df2022', 'df2021']
da.grid(column = 1, row = 1, padx = 3, pady = 20)

da.bind('<<ComboboxSelected>>', make_df)  # use virtual event instead of button

#STATE FILTER

ttk.Label(window, text = "Main Menu",
          foreground ="black",
          font = ("Times New Roman", 20)).grid(row = 0, column = 1)

#FILTER STATE - PART 1
ttk.Label(window, text = "Select the State:",
          font = ("Times New Roman", 12)).grid(column = 0,
          row = 2, padx = 3, pady = 29)

n = tk.StringVar()
state = ttk.Combobox(window, width = 60, textvariable = n)
state.grid(column = 1, row = 2, padx = 3, pady = 20)

ttk.Button(window, text = "OK", command=on_click).grid(column = 2,
          row = 2, padx = 3, pady = 10)

window.mainloop()
```

Note that you should create Tk() before creating other tkinter stuff.

Body:
I am having trouble with a Tkinter app I am making where the user would first select the dataframe from a combobox (combobox #1) which is a list of facilities within a given year (i.e., 2021 or 2022).  After the dataframe is identified, the user would select a list of facilities by state in a second combobox.

If I preselect the dataframe, everything works fine.  However, the user may want different years and does not want to use the Tkinter Filedialogue function. Basically, they want a dropdown menu that selects the dataframe. As I have it now, I can get it to work if I use the Input option from the command prompt, but I don't want to do that (see TEMP_SOLUTION section).

Bottom line - how can I first select the dataframe from a combobox (i.e., combobox #1) and make the state combobox use this selected dataframe as its source?  Any help is appreciated.

import pandas as pd
from tkinter import ttk
import numpy as np
from tkinter import Tk
import tkinter as tk

# function to get unique values
def unique(list1):
    x = np.array(list1)
    print(np.unique(x))

def make_df(): #I'd like to make the dataframe from here, but I am having trouble
    val = n3.get()
    if val == 'df2022':
        df = df2022
    else:
        df = df2021

def on_click():
    val = n.get()
    df2 = df[ df['state'] == val ]
    print(df2)

#DATAFRAMES

df2022 = pd.DataFrame({
   'id': ['1','2','3'],
   'state': ['mi','mi','oh'],
   'provname': ['abc facility','123 facility','acme facility'],
   'workdate':['1/1/2022', '1/3/2022', '6/8/2022']
})

df2021 = pd.DataFrame({
   'id': ['4','5','6'],
   'state': ['al','al','az'],
   'provname': ['jimmy state facility','mack 10 facility','heathcliff facility'],
   'workdate':['3/3/2021', '12/13/2021', '10/31/2021']
})

#TEMP SOLUTION - I don't want to do this with the command prompt, but it's all I can get to work right now
temp_idea = input('enter df2021 or df2022: ')
if temp_idea == 'df2021':
    df = df2021
else:
    df = df2022

# Create Combobox for selecting dataframe (NOT WORKING)
n3 = tk.StringVar()
da = ttk.Combobox(window, width = 60, textvariable = n3)

da['values'] = ['df2022', 'df2021']
da.grid(column = 1, row = 1, padx = 3, pady = 20)

ttk.Button(window, text = "Add Dataframe", command=make_df).grid(column = 2,
          row = 1, padx = 3, pady = 10)

#STATE FILTER

values = ['all'] + list(df['state'].unique())

window = tk.Tk()
window.title('Combobox')
window.geometry('600x400')
window.focus_set()

ttk.Label(window, text = "Main Menu",
          foreground ="black",
          font = ("Times New Roman", 20)).grid(row = 0, column = 1)

#FILTER STATE - PART 1
ttk.Label(window, text = "Select the State:",
          font = ("Times New Roman", 12)).grid(column = 0,
          row = 2, padx = 3, pady = 29)

n = tk.StringVar()
state = ttk.Combobox(window, width = 60, textvariable = n)
state['values'] = sorted(list(df['state'].unique()))
state.grid(column = 1, row = 2, padx = 3, pady = 20)

ttk.Button(window, text = "OK", command=on_click).grid(column = 2,
          row = 2, padx = 3, pady = 10)

state.current()

window.mainloop()

Body:
You can update combobox state based on selected dataframe inside make_df().  Also you can bind on <<ComboboxSelected>> virtual event instead of using the Add Dataframe button:

import tkinter as tk
from tkinter import ttk
import pandas as pd

def make_df(event=None):
    global df
    val = n3.get()
    if val == 'df2022':
        df = df2022
    else:
        df = df2021
    # update combobox 'state'
    values = ['all'] + sorted(df['state'].unique())
    state['values'] = values
    state.set('all') # select 'all' initially

def on_click():
    val = n.get()
    df2 = df if val == 'all' else df[ df['state'] == val ]
    print(df2)

#DATAFRAMES

df2022 = pd.DataFrame({
   'id': ['1','2','3'],
   'state': ['mi','mi','oh'],
   'provname': ['abc facility','123 facility','acme facility'],
   'workdate':['1/1/2022', '1/3/2022', '6/8/2022']
})

df2021 = pd.DataFrame({
   'id': ['4','5','6'],
   'state': ['al','al','az'],
   'provname': ['jimmy state facility','mack 10 facility','heathcliff facility'],
   'workdate':['3/3/2021', '12/13/2021', '10/31/2021']
})

window = tk.Tk()
window.title('Combobox')
window.geometry('600x400')
window.focus_set()

ttk.Label(window, text = "Select Dataframe:",
          font = ("Times New Roman", 12)).grid(column = 0,
          row = 1, padx = 3, pady = 29)

# Create Combobox for selecting dataframe (NOT WORKING)
n3 = tk.StringVar()
da = ttk.Combobox(window, width = 60, textvariable = n3)
da['values'] = ['df2022', 'df2021']
da.grid(column = 1, row = 1, padx = 3, pady = 20)

da.bind('<<ComboboxSelected>>', make_df)  # use virtual event instead of button

#STATE FILTER

ttk.Label(window, text = "Main Menu",
          foreground ="black",
          font = ("Times New Roman", 20)).grid(row = 0, column = 1)

#FILTER STATE - PART 1
ttk.Label(window, text = "Select the State:",
          font = ("Times New Roman", 12)).grid(column = 0,
          row = 2, padx = 3, pady = 29)

n = tk.StringVar()
state = ttk.Combobox(window, width = 60, textvariable = n)
state.grid(column = 1, row = 2, padx = 3, pady = 20)

ttk.Button(window, text = "OK", command=on_click).grid(column = 2,
          row = 2, padx = 3, pady = 10)

window.mainloop()

Note that you should create Tk() before creating other tkinter stuff.


问:
Failed to set State on onClick event to store id of clicked element by using useState
I'm trying to set of my useState to id of clicked element when user clicked it. But it shows empty string when i'm trying to console it and dispatch it. So, it feels like it didn't successfully set the state. and I don't know why.

This is the snippet code of it:

```<code>const Game = () => {
   const [gameMode, setGameMode] = useState('');
   const dispatch = useDispatch();

   return (
       <div id='computer' className='to-play-computer' onClick={(e) => {
            setGameMode(e.currentTarget.id); // THIS DOESN'T CHANGE THE gameMode state to id 'computer'

            // WAIT UNTIL THIS FUNCTION DONE
            handleClickGameMode(e)
                 .then(() => {
                     console.log(gameMode); // IT WILL CONSOLE EMPTY STRING
                     dispatch(isGamePlay(gameMode));
                 })
       }}>
            <div className='icon-gameplay'>
                <FaRobot />
            </div>
            <p className='description-gameplay'>
                vs Computer
            </p>
       </div>
   )
}
</code>```

But if assigned it to simple variable, like this:

```<code>let gameMode = ""; // This will store the id of clicked element
const dispatch = useDispatch();

       return (
           <div id='computer' className='to-play-computer' onClick={(e) => {
                gameMode = e.currentTarget.id // changed

                // WAIT UNTIL THIS FUNCTION DONE
                handleClickGameMode(e)
                     .then(() => {
                         console.log(gameMode); // IT WILL SUCCESSFULY CONSOLE 'COMPUTER'
                         dispatch(isGamePlay(gameMode));
                     })
           }}>
                <div className='icon-gameplay'>
                    <FaRobot />
                </div>
                <p className='description-gameplay'>
                    vs Computer
                </p>
           </div>
       )
</code>```

So, how to make this successful using useState? And maybe you can explain me why did this happened? Because in other projects I've created, like setState from onChange input form, it didn't create this problem. Thank you.

答:
```<code> useEffect(() => {
      dispatch(isGamePlay(gameMode));
 }, [gameMode]);
</code>```

Body:
I'm trying to set of my useState to id of clicked element when user clicked it. But it shows empty string when i'm trying to console it and dispatch it. So, it feels like it didn't successfully set the state. and I don't know why.

This is the snippet code of it:

const Game = () => {
   const [gameMode, setGameMode] = useState('');
   const dispatch = useDispatch();

   return (

 {
            setGameMode(e.currentTarget.id); // THIS DOESN'T CHANGE THE gameMode state to id 'computer'

            // WAIT UNTIL THIS FUNCTION DONE
            handleClickGameMode(e)
                 .then(() => {
                     console.log(gameMode); // IT WILL CONSOLE EMPTY STRING
                     dispatch(isGamePlay(gameMode));
                 })
       }}>

                <FaRobot />

                vs Computer

   )
}

But if assigned it to simple variable, like this:

let gameMode = ""; // This will store the id of clicked element
const dispatch = useDispatch();

       return (

 {
                gameMode = e.currentTarget.id // changed

                // WAIT UNTIL THIS FUNCTION DONE
                handleClickGameMode(e)
                     .then(() => {
                         console.log(gameMode); // IT WILL SUCCESSFULY CONSOLE 'COMPUTER'
                         dispatch(isGamePlay(gameMode));
                     })
           }}>

                    <FaRobot />

                    vs Computer

       )

So, how to make this successful using useState? And maybe you can explain me why did this happened? Because in other projects I've created, like setState from onChange input form, it didn't create this problem. Thank you.


问:
Minimal 64-bit Windows executable crashes with tail-call optimization enabled by gcc
I'm trying to create a minimal 64-bit Windows executable to better understand how the Windows executable format works.

I wrote very basic assembly and C code as follows.

hi.s

```<code>    section .text

hi:
    db "hi", 0

    global sayHi
    align 16
sayHi:
    lea rax, [rel hi]
    ret
</code>```

start.c

```<code>extern int puts();
extern const char *sayHi();

void start() {
    puts(sayHi());
}
</code>```

compiled with,

```<code>nasm -fwin64 hi.s
gcc -c -ostart.obj -O3 -fno-optimize-sibling-calls start.c
# I will explain the flag
</code>```

and linked with,

```<code>golink /fo r.exe /console start.obj hi.obj msvcrt.dll
# create a console application `r.exe`
# the default entry point is `start`
</code>```

The program runs fine and prints hi, but note the gcc flag -fno-optimize-sibling-calls. That flag disables tail-call optimizations so that the program always allocates stack space and calls a function. Without the flag, the program crashes.

This is the disassembled result without tail-call optimization. Not sure why gcc put a nop there, but otherwise it's very simple and runs fine.

```<code>0000000000401000 <.text>:
  401000:   48 83 ec 28             sub    rsp,0x28
  401004:   e8 27 00 00 00          call   0x401030 # sayHi
  401009:   48 89 c1                mov    rcx,rax
  40100c:   e8 ff 2f 00 00          call   0x404010 # puts
  401011:   90                      nop
  401012:   48 83 c4 28             add    rsp,0x28
  401016:   c3                      ret
  ...
  401020:   68 69 00 90 90          push   0xffffffff90900069 # "hi"
  ...
  401030:   48 8d 05 e9 ff ff ff    lea    rax,[rip+0xffffffffffffffe9] # 0x401020
  401037:   c3                      ret
</code>```

This is when tail-call opt is enabled, in which the program crashes.

```<code>0000000000401000 <.text>:
  401000:   48 83 ec 28             sub    rsp,0x28
  401004:   e8 27 00 00 00          call   0x401030 # sayHi
  401009:   48 89 c1                mov    rcx,rax
  40100c:   48 83 c4 28             add    rsp,0x28
  401010:   e9 eb 2f 00 00          jmp    0x404000 # puts
  ...
  401020:   68 69 00 90 90          push   0xffffffff90900069 # "hi"
  ...
  401030:   48 8d 05 e9 ff ff ff    lea    rax,[rip+0xffffffffffffffe9] # 0x401020
  401037:   c3                      ret
</code>```

Now the program doesn't allocate stack space before puts and simply does a jmp instead of call.

I investigated further to see where exactly it jumps when calling puts.

In the no-tail-call case, the called address 0x404010 in the .idata section has the instruction jmp QWORD PTR [rip+0xffffffffffffffea] # 0x404000, and 0x404000 seems to contain the address to puts.

However in the tail-call case, the called address 0x404000 has 54 40 00 00 which is no meaningful instruction. The debugger says the program segfaults at 0x404003, so I'm pretty sure the program chokes trying to execute a garbage instruction.

I must be doing something wrong, but I'm not sure which, so could you explain why the tail-call case fails and how to get it work?

答:
The problem was on golink not correctly handling tail-calls. I searched a while to make GNU ld link the program with the same options given to golink.

You can create a console-mode Windows executable by GNU ld with this command.

```<code>ld -o... --subsystem=console object-files...
</code>```

--subsystem console or -subsystem=console also means the same. Use --subsystem=windows to create a GUI application.

GNU ld also handles Windows dll files, so in this case, simply giving ld a copy of msvcrt.dll from the system folder worked.

Body:
I'm trying to create a minimal 64-bit Windows executable to better understand how the Windows executable format works.

I wrote very basic assembly and C code as follows.

hi.s

    section .text

hi:
    db "hi", 0

    global sayHi
    align 16
sayHi:
    lea rax, [rel hi]
    ret

start.c

extern int puts();
extern const char *sayHi();

void start() {
    puts(sayHi());
}

compiled with,

nasm -fwin64 hi.s
gcc -c -ostart.obj -O3 -fno-optimize-sibling-calls start.c
# I will explain the flag

and linked with,

golink /fo r.exe /console start.obj hi.obj msvcrt.dll
# create a console application `r.exe`
# the default entry point is `start`

The program runs fine and prints hi, but note the gcc flag -fno-optimize-sibling-calls. That flag disables tail-call optimizations so that the program always allocates stack space and calls a function. Without the flag, the program crashes.

This is the disassembled result without tail-call optimization. Not sure why gcc put a nop there, but otherwise it's very simple and runs fine.

0000000000401000 <.text>:
  401000:   48 83 ec 28             sub    rsp,0x28
  401004:   e8 27 00 00 00          call   0x401030 # sayHi
  401009:   48 89 c1                mov    rcx,rax
  40100c:   e8 ff 2f 00 00          call   0x404010 # puts
  401011:   90                      nop
  401012:   48 83 c4 28             add    rsp,0x28
  401016:   c3                      ret
  ...
  401020:   68 69 00 90 90          push   0xffffffff90900069 # "hi"
  ...
  401030:   48 8d 05 e9 ff ff ff    lea    rax,[rip+0xffffffffffffffe9] # 0x401020
  401037:   c3                      ret

This is when tail-call opt is enabled, in which the program crashes.

0000000000401000 <.text>:
  401000:   48 83 ec 28             sub    rsp,0x28
  401004:   e8 27 00 00 00          call   0x401030 # sayHi
  401009:   48 89 c1                mov    rcx,rax
  40100c:   48 83 c4 28             add    rsp,0x28
  401010:   e9 eb 2f 00 00          jmp    0x404000 # puts
  ...
  401020:   68 69 00 90 90          push   0xffffffff90900069 # "hi"
  ...
  401030:   48 8d 05 e9 ff ff ff    lea    rax,[rip+0xffffffffffffffe9] # 0x401020
  401037:   c3                      ret

Now the program doesn't allocate stack space before puts and simply does a jmp instead of call.

I investigated further to see where exactly it jumps when calling puts.

In the no-tail-call case, the called address 0x404010 in the .idata section has the instruction jmp QWORD PTR [rip+0xffffffffffffffea] # 0x404000, and 0x404000 seems to contain the address to puts.

However in the tail-call case, the called address 0x404000 has 54 40 00 00 which is no meaningful instruction. The debugger says the program segfaults at 0x404003, so I'm pretty sure the program chokes trying to execute a garbage instruction.

I must be doing something wrong, but I'm not sure which, so could you explain why the tail-call case fails and how to get it work?

Body:
The problem was on golink not correctly handling tail-calls. I searched a while to make GNU ld link the program with the same options given to golink.

You can create a console-mode Windows executable by GNU ld with this command.

ld -o... --subsystem=console object-files...

--subsystem console or -subsystem=console also means the same. Use --subsystem=windows to create a GUI application.

GNU ld also handles Windows dll files, so in this case, simply giving ld a copy of msvcrt.dll from the system folder worked.


问:
Checkbox classList Toggle
I'm trying to use a custom slider with an input type=checkbox to toggle between dark-mode and light-mode. It is not working with the javascript code I have.

var checkbox = document.getElementById('checkbox');
    checkbox.addEventListener('change', themeChange);

    function themeChange(){
      if (checkbox.checked == true){
        document.getElementById('body').classList.toggle('dark-mode');
      } else {
        document.getElementById('body').classList.toggle('light-mode');
      }
    }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dark-mode {
      background-color: black;
      color: white;
    }

    .light-mode {
      background-color: white;
      color: black;
    }</code>```

       <input id="checkbox" type="checkbox" >

    ```

答:
You can check below snippet.

var body = document.getElementById('body');
var checkbox = document.getElementById('checkbox');
checkbox.addEventListener('change', themeChange);

function themeChange(){
  if (checkbox.checked){
    body.classList.remove('light-mode');
    body.classList.add('dark-mode');
  } else {
    body.classList.add('light-mode');
    body.classList.remove('dark-mode');
  }
} ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.dark-mode {
  background-color: black;
  color: white;
}

.light-mode {
  background-color: white;
  color: black;
}</code>```

   <input id="checkbox" type="checkbox" >
    Dark/Light Mode

```

Title: Checkbox classList Toggle

Body:
I'm trying to use a custom slider with an input type=checkbox to toggle between dark-mode and light-mode. It is not working with the javascript code I have.

var checkbox = document.getElementById('checkbox');
    checkbox.addEventListener('change', themeChange);

    function themeChange(){
      if (checkbox.checked == true){
        document.getElementById('body').classList.toggle('dark-mode');
      } else {
        document.getElementById('body').classList.toggle('light-mode');
      }
    }

.dark-mode {
      background-color: black;
      color: white;
    }

    .light-mode {
      background-color: white;
      color: black;
    }

       <input id="checkbox" type="checkbox" >

Body:
You can check below snippet.

var body = document.getElementById('body');
var checkbox = document.getElementById('checkbox');
checkbox.addEventListener('change', themeChange);

function themeChange(){
  if (checkbox.checked){
    body.classList.remove('light-mode');
    body.classList.add('dark-mode');
  } else {
    body.classList.add('light-mode');
    body.classList.remove('dark-mode');
  }
}

.dark-mode {
  background-color: black;
  color: white;
}

.light-mode {
  background-color: white;
  color: black;
}

<body id='body'>

<label class="switch">
   <input id="checkbox" type="checkbox" >
   <span class="slider round"></span> Dark/Light Mode
</label>

</body>


问:
Pre-Signed S3 URL Signature Does Not Match
Title says everything. Here is my code;

I'm using node-formidable for files.

```<code>form.on("end",function(field, file){
        params.Body = fs.createReadStream(params.filePath)
        delete params.filePath;
        S3.getSignedUrl('putObject',params, function(err, url) {
            if(err){console.log(err);}
            console.log(url);
        });
    })
</code>```

After successful upload, url variable returns s3 url, something like this;

https://bucket-name.s3.amazonaws.com/746575308_8c081369df.jpg?AWSAccessKeyId=[key]&Expires=[date]&Signature=[signature]&x-amz-acl=public-read

But still getting SignatureDoesNotMatch error. In description says

The request signature we calculated does not match the signature you provided. Check your key and signing method.

Here is my parameters

```<code>params = {
    Bucket:"bucketname",
    Key: file.name,
    ACL: 'public-read'
}
</code>```

What am i missing?

答:
I ran into the same issue. The answer from farrellw explains the reason.

And in your case, you should add the header "x-amz-acl" with value "public-read" in your client request. Because you specified "ACL" with "public-read" when presigning on the server.

You can refer to https://aboutweb.dev/blog/signaturedoesnotmatch-s3-direct-upload/ for more details

ContentLicense: CC BY-SA 3.0

Body:
Title says everything. Here is my code;

I'm using node-formidable for files.

form.on("end",function(field, file){
        params.Body = fs.createReadStream(params.filePath)
        delete params.filePath;
        S3.getSignedUrl('putObject',params, function(err, url) {
            if(err){console.log(err);}
            console.log(url);
        });
    })

After successful upload, url variable returns s3 url, something like this;

https://bucket-name.s3.amazonaws.com/746575308_8c081369df.jpg?AWSAccessKeyId=[key]&Expires=[date]&Signature=[signature]&x-amz-acl=public-read

But still getting SignatureDoesNotMatch error. In description says

The request signature we calculated does not match the signature you provided. Check your key and signing method.

Here is my parameters

params = {
    Bucket:"bucketname",
    Key: file.name,
    ACL: 'public-read'
}

What am i missing?


问:
Replacing extension in the Pandas dataframe
I have a pandas dataframe containing song url with '.mp3' file extension. I want to replace '.wav'

The dataframe looks like this

Here you can see that, Path column contains the path of the song in the Songs directory. The song has '.mp3' extension. But I want to replace it with '.wav' extension.

How should I do it?

答:
We can try this one :

df['Path'] = df['Path'].str.replace('.mp3', '.wav', regex=False)
```
<p>And if we want to be sure that we want to change the <code>.mp3</code> at the end of the string :</p>
<pre class="lang-py prettyprint-override"><code>df['Path'] = df['Path'].str.replace('.mp3$', '.wav', regex=True)
</code>```

Body:
We can try this one :

df['Path'] = df['Path'].str.replace('.mp3', '.wav', regex=False)

And if we want to be sure that we want to change the .mp3 at the end of the string :

df['Path'] = df['Path'].str.replace('.mp3$', '.wav', regex=True)


问:
How to make call to specific phone number inside Twilio Studio flow?
I trigger studio flow using REST API along with From and To parameters. In case of To number does not answer or call is failed, I need to try another number. How can I implement this ? Make Outgoing Call widget does not let modifying To parameter.</p>

答:
Twilio developer evangelist here.

A Studio flow execution is intended to represent one call, either the incoming one from the incoming call trigger or an outbound one from the REST Trigger. So, you can't trigger a new call to a different number from within the same flow.

What you could do instead is use a Function Widget to call a Twilio Function that then triggers a new Studio flow execution with a new To number.


问:
How to keep circle in sync with div
In the attached image below, I want to recreate the "1" circle to the left of the profile box. I'm currently trying to use CSS positioning to get it like the image above, but whenever I shrink my computer screen, the circle doesn't move with the profile box. I'm not quite sure how to fix it. I've attached my code below the image.

body{
    width: 100%;
}

.wrapper {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    width: 80%;
    margin: auto;
    height: 100%;
}

.Ranking{
    position: absolute;
    left: 20px;
    top: 10%;
    transform: translateY(-50%);
    background: #000;
    color: #fff;
    height: 52px;
    width: 52px;
    border-radius: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 1;
    padding-top: 4px;
    transition: background-color .25s linear .5s;
    font-family: "Decima";
    font-size: 30px;
    line-height: 30px;
    color: #f0f0f0;
    font-weight: 300;
}
.Description{
    flex:1;
    background-color: blue;
    grid-column: 2/5;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel = "stylesheet" href="styles.css">
</head>
<body>
    <div class="wrapper">
        <div class="Ranking"></div>
        <div class="Name">One</div>
        <div class="Summary">Summary: <br>He really hits, with a LF fit</div>
        <div class="Level">Highest Level: A+ <br> Age: 21</div>
        <div class="Body">Height: 6'1" <br> Weight: 215 lbs</div>
        <div class="Profile"><img src="images/Dustin Harris.jfif"> </div>
        <div class="Description">Five</div>
      </div>

</body>
</html></code>```

答:
You might want to look at two aspects: HTML markup and CSS basics. TL;DR. See this CodePen example I put together for you.

position: absolute; looks for the closest parent that has position value of relative, absolute, or fixed. If there's no parent that has such position value, the element will be positioned absolute against the body. In your example, wrapper (i.e. the immediate parent) doesn't have position defined, thus Ranking will be positioned outside your intended area.

As a matter of fact, you won't likely need absolute positioning here. transform: translateX() indeed is a good starter. Instead of translateY(), you could move it horizontally by translateX().

Again, see this CodePen example I put together for you.

Title: How to keep circle in sync with div

Body:
In the attached image below, I want to recreate the "1" circle to the left of the profile box. I'm currently trying to use CSS positioning to get it like the image above, but whenever I shrink my computer screen, the circle doesn't move with the profile box. I'm not quite sure how to fix it. I've attached my code below the image.

body{
    width: 100%;
}

.wrapper {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    width: 80%;
    margin: auto;
    height: 100%;
}

.Ranking{
    position: absolute;
    left: 20px;
    top: 10%;
    transform: translateY(-50%);
    background: #000;
    color: #fff;
    height: 52px;
    width: 52px;
    border-radius: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 1;
    padding-top: 4px;
    transition: background-color .25s linear .5s;
    font-family: "Decima";
    font-size: 30px;
    line-height: 30px;
    color: #f0f0f0;
    font-weight: 300;
}
.Description{
    flex:1;
    background-color: blue;
    grid-column: 2/5;

}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel = "stylesheet" href="styles.css">

One

Summary:
He really hits, with a LF fit

Highest Level: A+
 Age: 21

Height: 6'1"
 Weight: 215 lbs

Five


问:
Highcharts networkgraph datalabels on hover
there!

I have a networkgraph built on highcharts and I need the datalabels to start turned of for some of the points. Then, I want to turn them on whenever user hovers a connected point. For this image, for example, on hovering "Rio de Janeiro", all the 5 points connected to it should have their datalabels on.

Any ideas on how to do this?

Thanks

答:
You have provided no code I can only explain what could be done.
We can for example, we listen when user mouseOver's our series and we then turn dataLabels enabled for that series and it's children. Everything else get dataLabels disabled

series: {
            stickyTracking: true,
            events: {
                mouseOver: function () {
                  var hoverSeries = this;

                  this.chart.series.forEach(function(s){
                    if(s != hoverSeries) {
                      // Turn off other series labels
                      s.update({
                        dataLabels: {
                          enabled: false
                        }
                      });
                    } else {
                      // Turn on hover series labels
                      hoverSeries.update({
                        dataLabels: {
                          enabled: true
                        }
                      });
                    }
                  });
                },
                mouseOut: function () {
                  this.chart.series.forEach(function(s){
                    // Reset all series
                    s.setState('');
                    s.update({
                      dataLabels: {
                        enabled: true
                      }
                    });
                  });
                }
            }
        }
```

Some example: https://jsfiddle.net/fakytqhd/

Body:
You have provided no code I can only explain what could be done.
We can for example, we listen when user mouseOver's our series and we then turn dataLabels enabled for that series and it's children. Everything else get dataLabels disabled

series: {
            stickyTracking: true,
            events: {
                mouseOver: function () {
                  var hoverSeries = this;

                  this.chart.series.forEach(function(s){
                    if(s != hoverSeries) {
                      // Turn off other series labels
                      s.update({
                        dataLabels: {
                          enabled: false
                        }
                      });
                    } else {
                      // Turn on hover series labels
                      hoverSeries.update({
                        dataLabels: {
                          enabled: true
                        }
                      });
                    }
                  });
                },
                mouseOut: function () {
                  this.chart.series.forEach(function(s){
                    // Reset all series
                    s.setState('');
                    s.update({
                      dataLabels: {
                        enabled: true
                      }
                    });
                  });
                }
            }
        }

Some example: https://jsfiddle.net/fakytqhd/


问:
PyFirmata2 Arduino PermissionError(13, permission error) (Python3)
This is a auto coil maker using Arduino, I'm using PyFirmata2 to make it(I don't use C++ because C++ is kinda hard for me), then there are some error and I can't fix it:

```<code>Traceback (most recent call last):
  File "c:\Users\user\Desktop\Knob\py.py", line 9, in <module>
    board = Arduino('COM4')
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\pyfirmata2\__init__.py", line 13, in __init__
    super(Arduino, self).__init__(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\pyfirmata2\pyfirmata2.py", line 119, in __init__
    self.sp = serial.Serial(port, baudrate, timeout=timeout)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\serial\serialwin32.py", line 33, in __init__
    super(Serial, self).__init__(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\serial\serialutil.py", line 244, in __init__
    self.open()
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\serial\serialwin32.py", line 64, in open
    raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM4': PermissionError(13, '存取被拒。', None, 5)
</code>```

(sorry if you notice I'm using Chinese)

I tried reboot my PC, run as Administrator and NT AUTHORITY\SYSTEM, also I run the code on other computer, still same error.Heres my code below:

from pyfirmata2 import Arduino
import multiprocessing
import time
tmp = None
tmp2 = None
tmp3 = None
i = 0
port = 'COM4'
board = Arduino('COM4')
mycircle = float(input('How many circle you want?'))
carg = float(input('Coil arg?'))
rpm = float(input('Motor rpm?'))
print('start!')
def a0():
    board.digital[2].write(1)
    board.digital[3].write(0)
    board.digital[4].write(0)
    board.digital[5].write(0)
def a1():
    board.digital[2].write(0)
    board.digital[3].write(1)
    board.digital[4].write(0)
    board.digital[5].write(0)
def b0():
    board.digital[2].write(0)
    board.digital[3].write(0)
    board.digital[4].write(1)
    board.digital[5].write(0)
def b1():
    board.digital[2].write(0)
    board.digital[3].write(0)
    board.digital[4].write(0)
    board.digital[5].write(1)
def motor():
    global i
    print('start21')
    while True:
        for e in range(0,round(30/carg)):
            a0()
            time.sleep(tmp3)
            a1()
            time.sleep(tmp3)
            b0()
            time.sleep(tmp3)
            b1()
            time.sleep(tmp3)
            print(i)
            i = i+1
        e = 0
        for e in range(0,round(30/carg)):
            b1()
            time.sleep(tmp3)
            b0()
            time.sleep(tmp3)
            a1()
            time.sleep(tmp3)
            a0()
            time.sleep(tmp3)
            print(i)
            i = i+1
        e = 0
tmp = 60/rpm
tmp2 = 40*carg
tmp3 = tmp/tmp2
print(tmp3)
p=multiprocessing.Process(target=motor)
p.start()
board.digital[10].write(1)
while True:
    if i == mycircle:
        c = 1
        print('complate')
        p.terminate()
        board.digital[10].write(0)
        break
    else:
        pass
```

(I know it's kinda/very messy, because it's prototype)

System Info:Windows 10 Pro 2004 build 19041.1415, i7-8700, 8G ram, you can get other info by Here

答:
The answer is use Linux instead Windows. Windows have a lot of problem for me.
And Windows sux.</p>

Body:
This is a auto coil maker using Arduino, I'm using PyFirmata2 to make it(I don't use C++ because C++ is kinda hard for me), then there are some error and I can't fix it:

Traceback (most recent call last):
  File "c:\Users\user\Desktop\Knob\py.py", line 9, in <module>
    board = Arduino('COM4')
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\pyfirmata2\__init__.py", line 13, in __init__
    super(Arduino, self).__init__(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\pyfirmata2\pyfirmata2.py", line 119, in __init__
    self.sp = serial.Serial(port, baudrate, timeout=timeout)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\serial\serialwin32.py", line 33, in __init__
    super(Serial, self).__init__(*args, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\serial\serialutil.py", line 244, in __init__
    self.open()
  File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\serial\serialwin32.py", line 64, in open
    raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError()))
serial.serialutil.SerialException: could not open port 'COM4': PermissionError(13, '存取被拒。', None, 5)

(sorry if you notice I'm using Chinese)

I tried reboot my PC, run as Administrator and NT AUTHORITY\SYSTEM, also I run the code on other computer, still same error.Heres my code below:

from pyfirmata2 import Arduino
import multiprocessing
import time
tmp = None
tmp2 = None
tmp3 = None
i = 0
port = 'COM4'
board = Arduino('COM4')
mycircle = float(input('How many circle you want?'))
carg = float(input('Coil arg?'))
rpm = float(input('Motor rpm?'))
print('start!')
def a0():
    board.digital[2].write(1)
    board.digital[3].write(0)
    board.digital[4].write(0)
    board.digital[5].write(0)
def a1():
    board.digital[2].write(0)
    board.digital[3].write(1)
    board.digital[4].write(0)
    board.digital[5].write(0)
def b0():
    board.digital[2].write(0)
    board.digital[3].write(0)
    board.digital[4].write(1)
    board.digital[5].write(0)
def b1():
    board.digital[2].write(0)
    board.digital[3].write(0)
    board.digital[4].write(0)
    board.digital[5].write(1)
def motor():
    global i
    print('start21')
    while True:
        for e in range(0,round(30/carg)):
            a0()
            time.sleep(tmp3)
            a1()
            time.sleep(tmp3)
            b0()
            time.sleep(tmp3)
            b1()
            time.sleep(tmp3)
            print(i)
            i = i+1
        e = 0
        for e in range(0,round(30/carg)):
            b1()
            time.sleep(tmp3)
            b0()
            time.sleep(tmp3)
            a1()
            time.sleep(tmp3)
            a0()
            time.sleep(tmp3)
            print(i)
            i = i+1
        e = 0
tmp = 60/rpm
tmp2 = 40*carg
tmp3 = tmp/tmp2
print(tmp3)
p=multiprocessing.Process(target=motor)
p.start()
board.digital[10].write(1)
while True:
    if i == mycircle:
        c = 1
        print('complate')
        p.terminate()
        board.digital[10].write(0)
        break
    else:
        pass

(I know it's kinda/very messy, because it's prototype)

System Info:Windows 10 Pro 2004 build 19041.1415, i7-8700, 8G ram, you can get other info by Here


问:
How to solve GraphQl ImportError - cannot import name 'gql' from 'gql' in Python?
I installed GraphQl on Windows 10 Laptop using the below command:

```<code>pip install --pre gql[all]
</code>```

I tried using the Basic example available on Official Github Page. in my Python IDLE.

However, I am getting this ImportError in my IDLE.

```<code>ImportError: cannot import name 'gql' from 'gql'
</code>```

Kindly help in resolving the issue.

Thanks

答:
make sure the name of your file you're testing with isn't named something similar to a package you're importing. Just got me when I named my file ariadne.py

https://github.com/mirumee/ariadne/issues/400#issue-662473441

Body:
I installed GraphQl on Windows 10 Laptop using the below command:

pip install --pre gql[all]

I tried using the Basic example available on Official Github Page. in my Python IDLE.

However, I am getting this ImportError in my IDLE.

ImportError: cannot import name 'gql' from 'gql'

Kindly help in resolving the issue.

Thanks


问:
Escaping strings in bash
I have this simple bash script:

```<code>#!/bin/bash
isRunning=$(ps -Af | awk '{if ($11 == "HomeDir") { print $0 }}' | wc -l)
if [ $isRunning == "0" ]; then
    echo "Script is running"
fi
</code>```

The script returns:

```<code>./script.sh: line 3: [ 0: command not found
</code>```

What did i do wrong?

答:
Why do u need a script for thsi?
simple command will be enough.</p>

```<code>ps -Af | awk '{if ($11 == "HomeDir"){counter++}END{if(counter>0)print "script is running"}}'
</code>```

Title: Escaping strings in bash

Body:
I have this simple bash script:

#!/bin/bash
isRunning=$(ps -Af | awk '{if ($11 == "HomeDir") { print $0 }}' | wc -l)
if [ $isRunning == "0" ]; then
    echo "Script is running"
fi

The script returns:

./script.sh: line 3: [ 0: command not found

What did i do wrong?

Body:
Why do u need a script for thsi?
simple command will be enough.

ps -Af | awk '{if ($11 == "HomeDir"){counter++}END{if(counter>0)print "script is running"}}'


问:
Referencing HTML Form Elements in cloned table rows
First of all, thanks in advance to all those who contribute to this post.  I am trying to understand two things in the JS code below: 1) why must I check for an "undefined" element in a table row object when there is only one row, if second and third row objects can be referenced with the [x] index value... is there a simpler way to do this? 2) how do i appropriately clear field values on clone rows (in the addRow() function. What I have works, but not sure if it's the right way to do clear values).

Fiddle: https://jsfiddle.net/arperez/n6azm28k/7/

Here's the full script ("myTable" is within a FORM element named "myForm" inside the BODY tag):

```<code>function addRow() {
    var tblBody = document.getElementById("myTable").tBodies[0];
    var lastrow = tblBody.rows.length;
    var newNode = tblBody.rows[0].cloneNode(true);
    tblBody.appendChild(newNode);

    //Clear copied values from cloned row.
    document.myForm.txtQty[lastrow].value = "";  //This works, but is this the right way to clear the textbox value of the cloned row?
}

function calcTotals() {

    var qty = 0;
    var totalqty = 0;
    var rows = document.getElementById("myTable").tBodies[0].rows.length - 1;

    for (i=0; i<=rows; i++) {

        var element = document.myForm.txtQty[i];
        if (element === undefined) {  //If I don't do this check I get an error when there is only one row existing in the table and I try referencing it with [0]. Not sure why?
            qty = document.myForm.txtQty.value;  //This works, but why does txtQty[0] not work? Is this the right way to refer to the first element/row?
        } else {
            qty = document.myForm.txtQty[i].value;
        }
        totalqty = totalqty + Number(qty);
    }

    //Display total quantities calculated
    alert("Total = " + totalqty);
}

<table id="myTable">
    <thead>
         <th>Quantity</th>
    </thead>
    <tbody>
       <tr>
         <td><input type="number" id="txtQty" name="txtQty"></td>
       </tr>
   </tbody>
</table>
<button type="button" onclick="addRow();">Add Row</button>
<button type="button" onclick="calcTotals();">Calculate Total</button>
</code>```

答:
In the beginning, you have only 1 element which name is "txtQty", so the  document.myForm.txtQty is not an array.

Your solution is ok.

Here is my implementation:

function addRow() {
  var tblBody = document.getElementById("myTable").tBodies[0];
  var newRow = tblBody.rows[0].cloneNode(true);
  tblBody.appendChild(newRow);
  let textBox=newRow.querySelector("input[name='txtQty[]']");
  textBox.value="";
}

function calcTotals() {
  var totalqty = 0;
  var qty = 0;
  var totalqty = 0;
  var txtQtys = document.getElementsByName('txtQty[]');
  for (i=0;i<txtQtys.length;i++){
    totalqty +=Number(txtQtys[i].value) ;
  }
  alert("Total = " + totalqty);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<form name="myForm">

    <table id="myTable">
        <thead>
             <th>Quantity</th>
        </thead>
        <tbody>
           <tr>
             <td><input type="number" name="txtQty[]"></td>
           </tr>
       </tbody>
    </table>
    <button type="button" onclick="addRow();">Add Row</button>
    <button type="button" onclick="calcTotals();">Calculate Total</button>

</form>
</body></code>```

Body:
First of all, thanks in advance to all those who contribute to this post.  I am trying to understand two things in the JS code below: 1) why must I check for an "undefined" element in a table row object when there is only one row, if second and third row objects can be referenced with the [x] index value... is there a simpler way to do this? 2) how do i appropriately clear field values on clone rows (in the addRow() function. What I have works, but not sure if it's the right way to do clear values).

Fiddle: https://jsfiddle.net/arperez/n6azm28k/7/

Here's the full script ("myTable" is within a FORM element named "myForm" inside the BODY tag):

function addRow() {
    var tblBody = document.getElementById("myTable").tBodies[0];
    var lastrow = tblBody.rows.length;
    var newNode = tblBody.rows[0].cloneNode(true);
    tblBody.appendChild(newNode);

    //Clear copied values from cloned row.
    document.myForm.txtQty[lastrow].value = "";  //This works, but is this the right way to clear the textbox value of the cloned row?
}

function calcTotals() {

    var qty = 0;
    var totalqty = 0;
    var rows = document.getElementById("myTable").tBodies[0].rows.length - 1;

    for (i=0; i<=rows; i++) {

        var element = document.myForm.txtQty[i];
        if (element === undefined) {  //If I don't do this check I get an error when there is only one row existing in the table and I try referencing it with [0]. Not sure why?
            qty = document.myForm.txtQty.value;  //This works, but why does txtQty[0] not work? Is this the right way to refer to the first element/row?
        } else {
            qty = document.myForm.txtQty[i].value;
        }
        totalqty = totalqty + Number(qty);
    }

    //Display total quantities calculated
    alert("Total = " + totalqty);
}

         Quantity

         <input type="number" id="txtQty" name="txtQty">

<button type="button" onclick="addRow();">Add Row</button>
<button type="button" onclick="calcTotals();">Calculate Total</button>

Body:
In the beginning, you have only 1 element which name is "txtQty", so the  document.myForm.txtQty is not an array.

Your solution is ok.

Here is my implementation:

function addRow() {
  var tblBody = document.getElementById("myTable").tBodies[0];
  var newRow = tblBody.rows[0].cloneNode(true);
  tblBody.appendChild(newRow);
  let textBox=newRow.querySelector("input[name='txtQty[]']");
  textBox.value="";
}

function calcTotals() {
  var totalqty = 0;
  var qty = 0;
  var totalqty = 0;
  var txtQtys = document.getElementsByName('txtQty[]');
  for (i=0;i<txtQtys.length;i++){
    totalqty +=Number(txtQtys[i].value) ;
  }
  alert("Total = " + totalqty);
}

<body>
<form name="myForm">

    <table id="myTable">
        <thead>
             <th>Quantity</th>
        </thead>
        <tbody>
           <tr>
             <td><input type="number" name="txtQty[]"></td>
           </tr>
       </tbody>
    </table>
    <button type="button" onclick="addRow();">Add Row</button>
    <button type="button" onclick="calcTotals();">Calculate Total</button>

</form>
</body>


问:
Firebase serve error: Port 5000 is not open. Could not start functions emulator
I'm trying to serve firebase functions locally, but when I run firebase serve or firebase emulators:start the error message is: "Port 5000 is not open, could not start functions emulator."

I'm using Windows 10, so I've tried to change the port number, check if the port is blocked by Firewall and I create a new rule in Firewall to ports 5000-5010 but none of this approaches worked for me.

答:
Try this way:</p>
```<code>firebase serve --only functions -p 5002
</code>```

Body:
Try this way:

firebase serve --only functions -p 5002


问:
Precedence of function application
In order to illustrate function application has the highest precedence in Haskell the following example was provided (by schoolofhaskell):

```<code>sq b = b * b
main = print $
-- show
    sq 3+1
-- /show
</code>```

The result here is 10.

What puzzles me is that the argument constitutes a function application too. Consider the operator + being a short-cut of a function. So when the argument is taken, I would expect that its function application now takes precedence over the original one.

Written that way it delivers the expected result:

```<code>sq b = b * b
main = print $
    sq ((+) 3 1 )
</code>```

Any explanation?

答:
I think your confusion is just the result of slightly imprecise language (on the part of both the OP and the School of Haskell page linked).

When we say things like "function application has higher precedence than any operator", the term "function application" there is not actually a phrase meaning "applying a function". It's a name for the specific syntactic form func arg (where you just write two terms next to each other in order to apply the first one to the second). We are trying to draw a distinction between "normal" prefix syntax for applying a function and the infix operator syntax for applying a function. So with this specific usage, sq 3 is "function application" and 3 + 1 is not. But this isn't claiming that sq is a function and + is not!

Whereas in many other contexts "function application" does just mean "applying a function"; there it isn't a single term, but just the ordinary meaning of the words "function" and "application" that happen to be used together. In that sense, both sq 3 and 3 + 1 are examples of "function application".

These two senses of the term arise because there are two different contexts we use when thinking about the code1: logical and syntactic. Consider if we define:

```<code>add = (+)
</code>```

In the "logical" view where we think about the idealised mathematical objects represented by our code, both add and (+) are simply functions (the same function in fact). They are even exactly the same object (we defined one by saying it was equal to the other). This underlying mathematical function exists independently of any name, and has exactly the same properties no matter how we choose to refer to it. In particular, the function can be applied (since that is basically the sole defining feature of a function).

But at the syntactic level, the language simply has different rules about how you can use the names add and + (regardless of what underlying objects those names refer to). One of these names is an operator, and the other is not. We have special syntactic rules for the how you need to write the application of an operator, which differs from how you need to write the application of any non-operator term (including but not limited to non-operator names like sq2). So when talking about syntax we need to be able to draw a distinction between these two cases. But it's important to remember that this is a distinction about names and syntax, and has nothing to do with the underlying functions being referred to (proved by the fact that the exact same function can have many names in different parts of the program, some of them operators and some of them not).

There isn't really an agreed upon common term for "any term that isn't an operator"; if there was we would probably say "non-operator application has higher precedence than any operator", since that would be clearer. But for better or worse the "application by simple adjacency" syntactic feature is frequently referred to as "function application", even though that term could also mean other things in other contexts3.

So (un?)fortunately there isn't really anything deeper going on here than the phrase "function application" meaning different things in different contexts.

1 Okay, there are way more than two contexts we might use to think about our code. There are two relevant to the point I'm making.

2 For an example of other non-operator terms that can be applied we can also have arbitrary expressions in parentheses. For example (compare on fst) (1, ()) is the non-operator application of (compare `on` fst) to (1, ()); the expression being applied is itself the operator-application of on to compare and fst.

3 For yet another usage, $ is often deemed to be the "function application operator"; this is perhaps ironic when considered alongside usages that are trying to use the phrase "function application" specifically to exclude operators!

Title: Precedence of function application

Body:
In order to illustrate function application has the highest precedence in Haskell the following example was provided (by schoolofhaskell):

sq b = b * b
main = print $
-- show
    sq 3+1
-- /show

The result here is 10.

What puzzles me is that the argument constitutes a function application too. Consider the operator + being a short-cut of a function. So when the argument is taken, I would expect that its function application now takes precedence over the original one.

Written that way it delivers the expected result:

sq b = b * b
main = print $
    sq ((+) 3 1 )

Any explanation?

Body:
I think your confusion is just the result of slightly imprecise language (on the part of both the OP and the School of Haskell page linked).

When we say things like "function application has higher precedence than any operator", the term "function application" there is not actually a phrase meaning "applying a function". It's a name for the specific syntactic form func arg (where you just write two terms next to each other in order to apply the first one to the second). We are trying to draw a distinction between "normal" prefix syntax for applying a function and the infix operator syntax for applying a function. So with this specific usage, sq 3 is "function application" and 3 + 1 is not. But this isn't claiming that sq is a function and + is not!

Whereas in many other contexts "function application" does just mean "applying a function"; there it isn't a single term, but just the ordinary meaning of the words "function" and "application" that happen to be used together. In that sense, both sq 3 and 3 + 1 are examples of "function application".

These two senses of the term arise because there are two different contexts we use when thinking about the code1: logical and syntactic. Consider if we define:

add = (+)

In the "logical" view where we think about the idealised mathematical objects represented by our code, both add and (+) are simply functions (the same function in fact). They are even exactly the same object (we defined one by saying it was equal to the other). This underlying mathematical function exists independently of any name, and has exactly the same properties no matter how we choose to refer to it. In particular, the function can be applied (since that is basically the sole defining feature of a function).

But at the syntactic level, the language simply has different rules about how you can use the names add and + (regardless of what underlying objects those names refer to). One of these names is an operator, and the other is not. We have special syntactic rules for the how you need to write the application of an operator, which differs from how you need to write the application of any non-operator term (including but not limited to non-operator names like sq2). So when talking about syntax we need to be able to draw a distinction between these two cases. But it's important to remember that this is a distinction about names and syntax, and has nothing to do with the underlying functions being referred to (proved by the fact that the exact same function can have many names in different parts of the program, some of them operators and some of them not).

There isn't really an agreed upon common term for "any term that isn't an operator"; if there was we would probably say "non-operator application has higher precedence than any operator", since that would be clearer. But for better or worse the "application by simple adjacency" syntactic feature is frequently referred to as "function application", even though that term could also mean other things in other contexts3.

So (un?)fortunately there isn't really anything deeper going on here than the phrase "function application" meaning different things in different contexts.

1 Okay, there are way more than two contexts we might use to think about our code. There are two relevant to the point I'm making.

2 For an example of other non-operator terms that can be applied we can also have arbitrary expressions in parentheses. For example (compare on fst) (1, ()) is the non-operator application of (compare `on` fst) to (1, ()); the expression being applied is itself the operator-application of on to compare and fst.

3 For yet another usage, $ is often deemed to be the "function application operator"; this is perhaps ironic when considered alongside usages that are trying to use the phrase "function application" specifically to exclude operators!


问:
Prevent Chrome on Android from Popping up Search Overlay
I'm working on a browser-based music app which has an onscreen keyboard. When I test the keyboard on my android phone in chrome browser it keeps randomly popping up some kind of search overlay. It doesn't do it consistently. It doesn't seem to be tied to long or short taps. It probably only happens about once every 20+ taps. I haven't been able to figure out any pattern or gesture to predict when it's going to happen yet.

I'm not even sure where it's getting its search terms from as the keyboard does not contain text. Sometimes the terms seem to match some of my css class names. For example it once searched for "notation" which is a class name used in the notation area of my app, but not on the keyboard where I was tapping.

I have set the CSS for my keyboard to user-select: none but that did not resolve the issue.

I'm not sure if this is a feature in chrome on android, or if it is specific to my device, but I definitely don't want random searches popping up for my users and I'm hoping there is a way I can prevent this from the app itself and not some device settings.

Is anyone familiar with this search "feature" and how to stop it from "helping"?

Thanks in advance!

答: Doh, it's only once I saw my own screenshot enlarged in this question that I noticed some text from the header is getting highlighted. I must be fat-fingering the upper edge of the phone when holding it. I just need to disable user-select on the header too. Thanks anyway!</p>


问:
Android Studio Emulator disappears after Bumblebee update
So I recently updated my Android Studio to "Android Studio Bumblebee | 2021.1.1 Patch 1" and now I have this weird bug where my emulator would disappear randomly. It works fine for sometime but would randomly disappear. In the device manager it shows that emulator is running but in the emulator tab it shows "No emulator is currently running"
As you can see from the screenshot attached green dot in the device manager that means "Emulator is running", whereas it isn't. The only way to get back emulator is to "cold reboot it" from the device manager. Anyone else facing the same bug? Any suggestions as to where to look trying to debug this. I've tried deleting and installing emulator again but the issue persisted.

答:
Had exactly the same issue on BumbleBee and the only way that I found to go about this, was to use a detached emulator in a separate window.

To run the emulator in a separate window go to File > Settings > Tools > Emulator (On Mac -> *Android Studio > Preferences > Tools > Emulator ) and deselect Launch in a tool window.

This way the emulator will always be there.


问:
How do you limit the number of characters used for that username for java android?
When adding value to a username in an Android app, how do you limit the number of characters used for that username?</p>

答:
Add android:maxLength in xml

Example Code:

```<code><EditText
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:maxLength="20"/>
</code>```

Body:
Add android:maxLength in xml

Example Code:

<EditText
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:maxLength="20"/>


问:
" Pod is blocking scale down because it has local storage "
I have kubernets cluster in gcp with docker container runtime. I am trying to change docker container runtime into containerd. Following steps shows what I did.

New node pool added ( nodes with containerd )

drained old nodes

Once I perform above steps I am getting " Pod is blocking scale down because it has local storage " warning message.

答:
You need to add the once annotation to POD so that cluster autoscaler can remove that POD from POD safe to evict.

```<code>cluster-autoscaler.kubernetes.io/safe-to-evict": "true"
</code>```

above annotation, you have to add in into POD.

You can read more at : https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-autoscaler-visibility#cluster-not-scalingdown

NoScaleDown example: You found a noScaleDown event that contains a
per-node reason for your node. The message ID is
"no.scale.down.node.pod.has.local.storage" and there is a single
parameter: "test-single-pod". After consulting the list of error
messages, you discover this means that the "Pod is blocking scale down
because it requests local storage". You consult the Kubernetes Cluster
Autoscaler FAQ and find out that the solution is to add a
"cluster-autoscaler.kubernetes.io/safe-to-evict": "true" annotation to
the Pod. After applying the annotation, cluster autoscaler scales down
the cluster correctly.

Body:
You need to add the once annotation to POD so that cluster autoscaler can remove that POD from POD safe to evict.

cluster-autoscaler.kubernetes.io/safe-to-evict": "true"

above annotation, you have to add in into POD.

You can read more at : https://cloud.google.com/kubernetes-engine/docs/how-to/cluster-autoscaler-visibility#cluster-not-scalingdown

NoScaleDown example: You found a noScaleDown event that contains a
per-node reason for your node. The message ID is
"no.scale.down.node.pod.has.local.storage" and there is a single
parameter: "test-single-pod". After consulting the list of error
messages, you discover this means that the "Pod is blocking scale down
because it requests local storage". You consult the Kubernetes Cluster
Autoscaler FAQ and find out that the solution is to add a
"cluster-autoscaler.kubernetes.io/safe-to-evict": "true" annotation to
the Pod. After applying the annotation, cluster autoscaler scales down
the cluster correctly.


问:
How to enhance the speed of my C++ program in reading delimited text files?
I show you C# and C++ code that execute the same job: to read the same text file delimited by “|” and save  with “#” delimited text.

When I execute  C++ program, the time elapsed is 169 seconds.

UPDATE 1: Thanks to Seth (compilation with: cl /EHsc /Ox /Ob2 /Oi) and GWW for changing the positions of string s outside the loops, the elapsed time was reduced to 53 seconds. I updated the code also.

UPDATE 2: Do you have any other suggestion to enhace the C++ code?

When I execute the C# program, the elapsed time is 34 seconds!

The question is, how can I enhance the speed of C++ comparing with the C# one?

C++ Program:

```<code>int main ()
{
    Timer t;
    cout << t.ShowStart() << endl;

    ifstream input("in.txt");
    ofstream output("out.txt", ios::out);
    char const row_delim = '\n';
    char const field_delim = '|';
    string s1, s2;

    while (input)
    {
        if (!getline( input, s1, row_delim ))
            break;
        istringstream iss(s1);
        while (iss)
        {
            if (!getline(iss, s2, field_delim ))
                break;
            output << s2 << "#";
        }
        output << "\n";
    }

    t.Stop();
    cout << t.ShowEnd() << endl;
    cout << "Executed in: " << t.ElapsedSeconds() << " seconds." << endl;
    return 0;
}
</code>```

C# program:

```<code>    static void Main(string[] args)
    {
        long i;
        Stopwatch sw = new Stopwatch();
        Console.WriteLine(DateTime.Now);
        sw.Start();
        StreamReader sr = new StreamReader("in.txt", Encoding.Default);
        StreamWriter wr = new StreamWriter("out.txt", false, Encoding.Default);
        object[] cols = new object[0];  // allocates more elements automatically when filling
        string line;
        while (!string.Equals(line = sr.ReadLine(), null)) // Fastest way
        {
        cols = line.Split('|');  // Faster than using a List<>
        foreach (object col in cols)
            wr.Write(col + "#");
        wr.WriteLine();
        }
        sw.Stop();
        Console.WriteLine("Conteo tomó {0} secs", sw.Elapsed);
        Console.WriteLine(DateTime.Now);
    }
</code>```

UPDATE 3:

Well, I must say I am very happy for the help received and because the answer to my question has been satisfied.

I changed the text of the question a little to be more specific, and I tested the solutions that kindly raised Molbdlino and Bo Persson.

Keeping Seth indications for the compile command (i.e. cl /EHsc /Ox /Ob2 /Oi pgm.cpp):

Bo Persson's solution took 18 seconds on average to complete the execution, really a good one taking in account that the code is near to what I like).

Molbdlino solution took 6 seconds on average, really amazing!! (thanks to Constantine also).

Never too late to learn, and I learned valuable things with my question.

My best regards.

答:
As Constantine suggests, read large chunks at a time using read.

I cut the time from ~25s to ~3s on a 129M file with 5M "entries" (26 bytes each) in 100,000 lines.

```<code>#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>

using namespace std;

int main ()
{
  ifstream input("in.txt");
  ofstream output("out.txt", ios::out);

  const size_t size = 512 * 1024;
  char buffer[size];

  while (input) {
    input.read(buffer, size);
    size_t readBytes = input.gcount();
    replace(buffer, buffer+readBytes, '|', '#');
    output.write(buffer, readBytes);
  }
  input.close();
  output.close();

  return 0;
}
</code>```

Body:
I show you C# and C++ code that execute the same job: to read the same text file delimited by “|” and save  with “#” delimited text.

When I execute  C++ program, the time elapsed is 169 seconds.

UPDATE 1: Thanks to Seth (compilation with: cl /EHsc /Ox /Ob2 /Oi) and GWW for changing the positions of string s outside the loops, the elapsed time was reduced to 53 seconds. I updated the code also.

UPDATE 2: Do you have any other suggestion to enhace the C++ code?

When I execute the C# program, the elapsed time is 34 seconds!

The question is, how can I enhance the speed of C++ comparing with the C# one?

C++ Program:

int main ()
{
    Timer t;
    cout << t.ShowStart() << endl;

    ifstream input("in.txt");
    ofstream output("out.txt", ios::out);
    char const row_delim = '\n';
    char const field_delim = '|';
    string s1, s2;

    while (input)
    {
        if (!getline( input, s1, row_delim ))
            break;
        istringstream iss(s1);
        while (iss)
        {
            if (!getline(iss, s2, field_delim ))
                break;
            output << s2 << "#";
        }
        output << "\n";
    }

    t.Stop();
    cout << t.ShowEnd() << endl;
    cout << "Executed in: " << t.ElapsedSeconds() << " seconds." << endl;
    return 0;
}

C# program:

    static void Main(string[] args)
    {
        long i;
        Stopwatch sw = new Stopwatch();
        Console.WriteLine(DateTime.Now);
        sw.Start();
        StreamReader sr = new StreamReader("in.txt", Encoding.Default);
        StreamWriter wr = new StreamWriter("out.txt", false, Encoding.Default);
        object[] cols = new object[0];  // allocates more elements automatically when filling
        string line;
        while (!string.Equals(line = sr.ReadLine(), null)) // Fastest way
        {
        cols = line.Split('|');  // Faster than using a List<>
        foreach (object col in cols)
            wr.Write(col + "#");
        wr.WriteLine();
        }
        sw.Stop();
        Console.WriteLine("Conteo tomó {0} secs", sw.Elapsed);
        Console.WriteLine(DateTime.Now);
    }

UPDATE 3:

Well, I must say I am very happy for the help received and because the answer to my question has been satisfied.

I changed the text of the question a little to be more specific, and I tested the solutions that kindly raised Molbdlino and Bo Persson.

Keeping Seth indications for the compile command (i.e. cl /EHsc /Ox /Ob2 /Oi pgm.cpp):

Bo Persson's solution took 18 seconds on average to complete the execution, really a good one taking in account that the code is near to what I like).

Molbdlino solution took 6 seconds on average, really amazing!! (thanks to Constantine also).

Never too late to learn, and I learned valuable things with my question.

My best regards.

Body:
As Constantine suggests, read large chunks at a time using read.

I cut the time from ~25s to ~3s on a 129M file with 5M "entries" (26 bytes each) in 100,000 lines.

#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>

using namespace std;

int main ()
{
  ifstream input("in.txt");
  ofstream output("out.txt", ios::out);

  const size_t size = 512 * 1024;
  char buffer[size];

  while (input) {
    input.read(buffer, size);
    size_t readBytes = input.gcount();
    replace(buffer, buffer+readBytes, '|', '#');
    output.write(buffer, readBytes);
  }
  input.close();
  output.close();

  return 0;
}


问:
Retrieve calls using c# API from Twilio with a specific time range
Good day all,
I'm in the process of trying to retrieve call data from Twilio using their C# SDK. Using the StartTime seems to pull all records for that given date which is not what I want to achieve. Ultimately I want to only pull data within a time range of the given date. I have looked on the internet and have seen mention of using the StartTimeBefore and StartTimeAfter. This does not appear to work either. Any thoughts as to how I can achieve this? Below is some code that I have attempted that does not seem to work.

NOTE: I have also tried some different permutations with EndTimeAfter to put bounds on it that way as well, but again that did not work.

```<code>public class RetrieveTwilioCalls
{
    private readonly string _accountSid;

    private readonly string _authToken;

    public RetrieveTwilioCalls(IConfigurationRoot configuration)
    {
        _accountSid = configuration["TWILIO_ACCOUNT_SID"];
        _authToken = configuration["TWILIO_AUTH_TOKEN"];
    }

    public async Task ExecuteAsync()
    {
        TwilioClient.Init(_accountSid, _authToken);

        var startDateTimeUTC = new DateTime(2022, 2, 8, 15, 15, 00).ToUniversalTime();
        var endDateTimeUTC = new DateTime(2022, 2, 8, 16, 18, 01).ToUniversalTime();

        var call1 = await CallResource.ReadAsync(new ReadCallOptions { StartTimeBefore = startDateTimeUTC, EndTimeAfter = endDateTimeUTC, PageSize = 100 });

        Console.WriteLine(call1.ElementAt(0).To);
    }
}
</code>```

答:
Twilio developer evangelist here.

If you check out the documentation for listing calls you will see the StartTime and EndTime filters do not work down to the granularity level of time.

StartTime

Only include calls that started on this date. Specify a date as YYYY-MM-DD in GMT, for example: 2009-07-06, to read only calls that started on this date. You can also specify an inequality, such as StartTime<=YYYY-MM-DD, to read calls that started on or before midnight of this date, and StartTime>=YYYY-MM-DD to read calls that started on or after midnight of this date.

If you need to specify things down to times, then I recommend you fetch the calls based on the date and then filter the calls to the right time in your own code.

Body:
Good day all,
I'm in the process of trying to retrieve call data from Twilio using their C# SDK. Using the StartTime seems to pull all records for that given date which is not what I want to achieve. Ultimately I want to only pull data within a time range of the given date. I have looked on the internet and have seen mention of using the StartTimeBefore and StartTimeAfter. This does not appear to work either. Any thoughts as to how I can achieve this? Below is some code that I have attempted that does not seem to work.

NOTE: I have also tried some different permutations with EndTimeAfter to put bounds on it that way as well, but again that did not work.

public class RetrieveTwilioCalls
{
    private readonly string _accountSid;

    private readonly string _authToken;

    public RetrieveTwilioCalls(IConfigurationRoot configuration)
    {
        _accountSid = configuration["TWILIO_ACCOUNT_SID"];
        _authToken = configuration["TWILIO_AUTH_TOKEN"];
    }

    public async Task ExecuteAsync()
    {
        TwilioClient.Init(_accountSid, _authToken);

        var startDateTimeUTC = new DateTime(2022, 2, 8, 15, 15, 00).ToUniversalTime();
        var endDateTimeUTC = new DateTime(2022, 2, 8, 16, 18, 01).ToUniversalTime();

        var call1 = await CallResource.ReadAsync(new ReadCallOptions { StartTimeBefore = startDateTimeUTC, EndTimeAfter = endDateTimeUTC, PageSize = 100 });

        Console.WriteLine(call1.ElementAt(0).To);
    }
}