问:
Not able to attach EventBridge Schedule to Lambda Function in AWS SAM
I'm unable to attach an EventBridge Schedule to a lambda function in AWS SAM.

Here is the section of my SAM template that intends to attach a schedule to the Lambda function:

```<code>TestLambda:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: TestLambda
      CodeUri: test_directory/
      Handler: test_file.lambda_handler
      Runtime: python3.8
      Role: !Ref LambdaApiRole
      Events:
        TestLambdaCron:
          Type: Schedule
          Properties:
            Schedule: rate(1 day)
</code>```

This is the error I get while deploying the template:

```<code>Embedded stack <stack ARN> was not successfully updated. Currently in UPDATE_ROLLBACK_IN_PROGRESS with reason: The following resource(s) failed to create: [TestLambdaTestLambdaCron].
</code>```

A solution would be much appreciated, thanks in advance!

PS: LambdaApiRole is defined in the template and can be referenced in the function (working fine), it's when TestLambdaCron is added when the issues occur

The AWS SAM CLI version I am working on is: SAM CLI, version 1.37.0

答:
Here is simple template that I have it and it works.</p>
```<code>AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: >
  Sample SAM Template for demo

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Resources:
  TestFunctionLambda:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: app/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
        - x86_64
      Role: arn:aws:iam::631249183025:role/mycstomrole
      Events:
        CWSchedule:
          Type: Schedule
          Properties:
            Schedule: "rate(1 minute)"
            Name: TestSchedule
            Description: test schedule
            Enabled: true
</code>```

Body:
I'm unable to attach an EventBridge Schedule to a lambda function in AWS SAM.

Here is the section of my SAM template that intends to attach a schedule to the Lambda function:

TestLambda:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: TestLambda
      CodeUri: test_directory/
      Handler: test_file.lambda_handler
      Runtime: python3.8
      Role: !Ref LambdaApiRole
      Events:
        TestLambdaCron:
          Type: Schedule
          Properties:
            Schedule: rate(1 day)

This is the error I get while deploying the template:

Embedded stack <stack ARN> was not successfully updated. Currently in UPDATE_ROLLBACK_IN_PROGRESS with reason: The following resource(s) failed to create: [TestLambdaTestLambdaCron].

A solution would be much appreciated, thanks in advance!

PS: LambdaApiRole is defined in the template and can be referenced in the function (working fine), it's when TestLambdaCron is added when the issues occur

The AWS SAM CLI version I am working on is: SAM CLI, version 1.37.0

Body:
Here is simple template that I have it and it works.

AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Description: >
  Sample SAM Template for demo

# More info about Globals: https://github.com/awslabs/serverless-application-model/blob/master/docs/globals.rst
Globals:
  Function:
    Timeout: 3

Resources:
  TestFunctionLambda:
    Type: AWS::Serverless::Function # More info about Function Resource: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#awsserverlessfunction
    Properties:
      CodeUri: app/
      Handler: app.lambda_handler
      Runtime: python3.9
      Architectures:
        - x86_64
      Role: arn:aws:iam::631249183025:role/mycstomrole
      Events:
        CWSchedule:
          Type: Schedule
          Properties:
            Schedule: "rate(1 minute)"
            Name: TestSchedule
            Description: test schedule
            Enabled: true


来源: stackexchange

问:
redstone.xmlrpc.XmlRpcException: A network error occurred. => How to fix this?
I have a problem with a program, which allows to run xml code and as a result call some procedures from database. I don't know much about how it should work, because it's not mine, but perhaps you could provide me some advice what is wrong. When I try to execute the xml code, I receive this stack with error messages, even though I'm connected to database:

```<code>java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
at sun.net.www.http.HttpClient.New(HttpClient.java:339)
at sun.net.www.http.HttpClient.New(HttpClient.java:357)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1220)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:984)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1334)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1309)
at redstone.xmlrpc.XmlRpcClient.endCallSimple(XmlRpcClient.java:378)
at redstone.xmlrpc.XmlRpcClient.invokeString(XmlRpcClient.java:557)
at server.TaskController$1.startVoidLogging(TaskController.java:121)
at commons.logger.LoggableEvent.startReturnableLogging(LoggableEvent.java:17)
at commons.logger.LoggableEvent.startReturnableLogging(LoggableEvent.java:11)
at commons.logger.ReturnableLoggableEvent.begin(ReturnableLoggableEvent.java:68)
at server.TaskController.executeXmlRpc(TaskController.java:131)
at org.apache.jsp.executeXmlRpc_jsp._jspService(executeXmlRpc_jsp.java:176)
at org.apache.jasper.runtime.HttpJspBase.service(HttpBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
redstone.xmlrpc.XmlRpcException: A network error occurred.
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
</code>```

What can be causing this issue and how to fix it?

答: Thank you very much for your prompt Mumrah81. Yes, the problem seemed to be with the connection to the server but fortunately I managed to fix it. Thank you anyway for your help!</p>

ContentLicense: CC BY-SA 4.0

Body:
I have a problem with a program, which allows to run xml code and as a result call some procedures from database. I don't know much about how it should work, because it's not mine, but perhaps you could provide me some advice what is wrong. When I try to execute the xml code, I receive this stack with error messages, even though I'm connected to database:

java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:242)
at sun.net.www.http.HttpClient.New(HttpClient.java:339)
at sun.net.www.http.HttpClient.New(HttpClient.java:357)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1220)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:984)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1334)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1309)
at redstone.xmlrpc.XmlRpcClient.endCallSimple(XmlRpcClient.java:378)
at redstone.xmlrpc.XmlRpcClient.invokeString(XmlRpcClient.java:557)
at server.TaskController$1.startVoidLogging(TaskController.java:121)
at commons.logger.LoggableEvent.startReturnableLogging(LoggableEvent.java:17)
at commons.logger.LoggableEvent.startReturnableLogging(LoggableEvent.java:11)
at commons.logger.ReturnableLoggableEvent.begin(ReturnableLoggableEvent.java:68)
at server.TaskController.executeXmlRpc(TaskController.java:131)
at org.apache.jsp.executeXmlRpc_jsp._jspService(executeXmlRpc_jsp.java:176)
at org.apache.jasper.runtime.HttpJspBase.service(HttpBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.jasper.servlet.JspServletWrapper.service(JspWrapper.java:438)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:396)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:340)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:217)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
redstone.xmlrpc.XmlRpcException: A network error occurred.
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)

What can be causing this issue and how to fix it?


问:
background-clip: text pertruding over text
The Design I want.
https://i.imgur.com/nw5jwsP.png

So far I get this.
https://i.imgur.com/nUuVryi.png

Code:

```<code>$--gradient-text-primary: -webkit-linear-gradient(242.06deg, #4fcc81 37.1%, #14b08b 88.56%);
$--color-text-secondary: #ffffff;
&.--hover-primary {
    background: $--gradient-text-primary;
    cursor: pointer;
    background-clip: text;
    -webkit-background-clip: text;
    color: rgb($--color-text-secondary, 1);
    transition: color 0.2s ease-in-out;

    &:hover {
      color: rgb($--color-text-secondary, 0);
    }
</code>```

I don't know why the background is protruding beyond the bounds of the text.
This doesn't seem to be a browser specific thing. Tested on chrome and firefox, latest version.

Any ideas, or am simply using text gradients wrong?

答:
I think you are doing the color wrong

.ghee{
background: linear-gradient(90deg,black,green,blue,white);
background-clip: text;
color: white;
transition: color .7s ease-in-out
}
.ghee:hover{
color:transparent;
}
.wrapper{
background:linear-gradient(90deg,pink,hotpink,black);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper"><div class="ghee">The Overflow Blog
</div></div></code>```

Body:
The Design I want.
https://i.imgur.com/nw5jwsP.png

So far I get this.
https://i.imgur.com/nUuVryi.png

Code:

$--gradient-text-primary: -webkit-linear-gradient(242.06deg, #4fcc81 37.1%, #14b08b 88.56%);
$--color-text-secondary: #ffffff;
&.--hover-primary {
    background: $--gradient-text-primary;
    cursor: pointer;
    background-clip: text;
    -webkit-background-clip: text;
    color: rgb($--color-text-secondary, 1);
    transition: color 0.2s ease-in-out;

    &:hover {
      color: rgb($--color-text-secondary, 0);
    }

I don't know why the background is protruding beyond the bounds of the text.
This doesn't seem to be a browser specific thing. Tested on chrome and firefox, latest version.

Any ideas, or am simply using text gradients wrong?

Body:
I think you are doing the color wrong

.ghee{
background: linear-gradient(90deg,black,green,blue,white);
background-clip: text;
color: white;
transition: color .7s ease-in-out
}
.ghee:hover{
color:transparent;
}
.wrapper{
background:linear-gradient(90deg,pink,hotpink,black);
}

<div class="wrapper"><div class="ghee">The Overflow Blog
</div></div>


问:
Proper CPython String Concatenation
Last night I was at a Boston Python Meetup that described various Python implementations. Part of the discussion included string concatenation.

Apparently for CPython there is less heap fragmentation if strings are concatenated starting with an empty string and then using join.

Is this an OK way to construct a string

```<code>sql_statement = "select count(*) " + \
    "from ept_inv e " + \
    "where e.ept_type =  " + str(in_row[cs.DeviceType]) + " " + \
    "and e.inv_id = " + str(in_row[cs.EndpointID]) + " ; "
</code>```

or should I have set sql_statement to "" and then joined each piece?
Thanks.

答:
This should be faster and easier to read imo. This is a fairly small amount of strings to concatenate, so I wouldn't concentrate to much on it :).</p>

```<code>" ".join([
    "select count(*)",
    "from ept_inv e",
    "where e.ept_type =",
    str(in_row[cs.DeviceType]),
    "and e.inv_id =",
    str(in_row[cs.EndpointID]),
    ";"
])
</code>```

ContentLicense: CC BY-SA 3.0

Title: Proper CPython String Concatenation

Body:
Last night I was at a Boston Python Meetup that described various Python implementations. Part of the discussion included string concatenation.

Apparently for CPython there is less heap fragmentation if strings are concatenated starting with an empty string and then using join.

Is this an OK way to construct a string

sql_statement = "select count(*) " + \
    "from ept_inv e " + \
    "where e.ept_type =  " + str(in_row[cs.DeviceType]) + " " + \
    "and e.inv_id = " + str(in_row[cs.EndpointID]) + " ; "

or should I have set sql_statement to "" and then joined each piece?
Thanks.

Body:
This should be faster and easier to read imo. This is a fairly small amount of strings to concatenate, so I wouldn't concentrate to much on it :).

" ".join([
    "select count(*)",
    "from ept_inv e",
    "where e.ept_type =",
    str(in_row[cs.DeviceType]),
    "and e.inv_id =",
    str(in_row[cs.EndpointID]),
    ";"
])


问:
Saving variable from drop down menu command with lambda function in Tkinter
I want to extract the selected data from a drop down menu in Tkinter. The drop down menu changes based on a previous drop down menu selection.

Basically, how do I save a variable from a lambda function?

I've tried declaring a global variable, and dictionary value but the problem still is that I am overwriting the original drop down menu in my function and the code is still reading the value of the original drop down. Ideally, the code would just update the actual drop down list and not overwrite the original one. Apologies for my clunky, un-pythonic code.

```<code>import tkinter as tk

HEIGHT = 500
WIDTH = 500

root = tk.Tk()

canvas = tk.Canvas(root, height = HEIGHT, width = WIDTH)
canvas.pack()

subframe = tk.Frame(root, bg = 'gray', bd = 10)
subframe.place(relx = 0.05, rely = 0.05, relwidth = 0.9, relheight = 0.9)

subframe.rowconfigure(tuple(range(4)), weight = 1)
subframe.columnconfigure(tuple(range(4)), weight = 1)

inputs = {}  ### dictionary for saved label *** I know there HAS to be a better way

### --- dropdown1 Input
label10 = tk.Label(subframe, text = 'Label 1', font = ('Century', 12), bg = 'gray', fg = 'white')
label10.grid(row = 1, column = 0, sticky = 'ew', padx = 5, pady = 5)

dropdown1_ID_series = ['A', 'B', 'C']

#global dropdown2_ID_var

def update_test_data_dropdown(dropdown1ID):
    if dropdown1ID == 'C':
        dropdown2_ID_series = ['1', '2', '3']
        dropdown2_ID_var = tk.StringVar(root)
        dropdown2_ID_var.set(dropdown2_ID_series[0])
        dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series)
        dropdown2_ID_entry.config(width=10)
        dropdown2_ID_entry.grid(row = 2, column = 1, sticky = 'ew', padx = 5, pady = 5)
        inputs['dropdown2'] = dropdown2_ID_var.get()
        print (inputs['dropdown2'])
    else:
        dropdown2_ID_series = ['4', '5','6']
        dropdown2_ID_var = tk.StringVar(root)
        dropdown2_ID_var.set(dropdown2_ID_series[0])
        dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series)
        dropdown2_ID_entry.config(width=10)
        dropdown2_ID_entry.grid(row = 2, column = 1, sticky = 'ew', padx = 5, pady = 5)
        inputs['dropdown2'] = dropdown2_ID_var.get()
    return dropdown2_ID_var  ## need to figure out how to export dropdown2_ID_var

dropdown1_ID_var = tk.StringVar(root)
dropdown1_ID_var.set(dropdown1_ID_series[0])
dropdown1_ID_entry = tk.OptionMenu(subframe, dropdown1_ID_var, *dropdown1_ID_series, command = lambda x: update_test_data_dropdown(x))
dropdown1_ID_entry.config(width=10)
dropdown1_ID_entry.grid(row = 1, column = 1, sticky = 'ew', padx = 5, pady = 5)

### --- dropdown 2 input
label20 = tk.Label(subframe, text = 'Label 2', font = ('Century', 12), bg = 'gray', fg = 'white')
label20.grid(row = 2, column = 0, sticky = 'ew', padx = 5, pady = 5)

dropdown2_ID_series = ['D', 'E', 'F']

dropdown2_ID_var = tk.StringVar(root)
dropdown2_ID_var.set(dropdown2_ID_series[0])
dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series)
dropdown2_ID_entry.config(width=10)
dropdown2_ID_entry.grid(row = 2, column = 1, sticky = 'ew', padx = 5, pady = 5)

inputs['dropdown2'] = dropdown2_ID_var.get()
print (inputs['dropdown2'])

def submit():
    label11 = tk.Label(subframe, text = dropdown1_ID_var.get(), font = ('Century', 12), bg = 'gray', fg = 'white')
    # label22 = tk.Label(subframe, text = dropdown2_ID_var.get(), font = ('Century', 12), bg = 'gray', fg = 'white')
    label22 = tk.Label(subframe, text = inputs['dropdown2'], font = ('Century', 12), bg = 'gray', fg = 'white')
    label11.grid(row = 1, column = 3, padx = 5, pady = 5)
    label22.grid(row = 2, column = 3, padx = 5, pady = 5)

### --- RUN BUTTON
button = tk.Button(subframe, text = 'SUBMIT', font = ('Century', 12, 'bold'), command = lambda: submit())
button.grid(row = 3, column = 3, ipadx = 20, padx = 5, pady = 15)

root.mainloop()
</code>```

When hitting SUBMIT on the above code, I want the selected value in the dropdowns to print next to the drop down.

答:
I figured out a better way to update the drop down list by adding the optionmenu entry and variable to the function, deleting the original list, and editing through 'menu' and add_command.  The two tricky/annoying things is having to create a loop to add the new list values individually then most importantly using tk._setit() to have the values actually selectable.  I would be happy to find out if there is a better way but this at least works.

```<code>import tkinter as tk

HEIGHT = 500
WIDTH = 500

root = tk.Tk()

canvas = tk.Canvas(root, height = HEIGHT, width = WIDTH)
canvas.pack()

subframe = tk.Frame(root, bg = 'gray', bd = 10)
subframe.place(relx = 0.05, rely = 0.05, relwidth = 0.9, relheight = 0.9)

subframe.rowconfigure(tuple(range(4)), weight = 1)
subframe.columnconfigure(tuple(range(4)), weight = 1)

### --- dropdown1 Input
label10 = tk.Label(subframe, text = 'Label 1', font = ('Century', 12), bg = 'gray', fg = 'white')
label10.grid(row = 1, column = 0, sticky = 'ew', padx = 5, pady = 5)

dropdown1_ID_series = ['A', 'B', 'C']

def update_test_data_dropdown(dropdown1ID, dropdown2_ID_entry, dropdown2_ID_var):
    if dropdown1ID == 'C':
        dropdown2_ID_series2 = ['1', '2', '3']
        dropdown2_ID_entry['menu'].delete(0,'end')
        for v in dropdown2_ID_series2:
            dropdown2_ID_entry['menu'].add_command(label = v, command= tk._setit(dropdown2_ID_var, v))
    else:
        dropdown2_ID_series2 = ['4', '5','6']
        dropdown2_ID_entry['menu'].delete(0,'end')
        for v in dropdown2_ID_series2:
            dropdown2_ID_entry['menu'].add_command(label = v, command= tk._setit(dropdown2_ID_var, v))
    dropdown2_ID_var.set(dropdown2_ID_series2[0])
    return dropdown2_ID_var  ## need to figure out how to export dropdown2_ID_var

dropdown1_ID_var = tk.StringVar(root)
dropdown1_ID_var.set(dropdown1_ID_series[0])
dropdown1_ID_entry = tk.OptionMenu(subframe, dropdown1_ID_var, *dropdown1_ID_series, command = lambda x: update_test_data_dropdown(x, dropdown2_ID_entry, dropdown2_ID_var))
dropdown1_ID_entry.config(width=10)
dropdown1_ID_entry.grid(row = 1, column = 1, sticky = 'ew', padx = 5, pady = 5)

### --- dropdown 2 input
label20 = tk.Label(subframe, text = 'Label 2', font = ('Century', 12), bg = 'gray', fg = 'white')
label20.grid(row = 2, column = 0, sticky = 'ew', padx = 5, pady = 5)

dropdown2_ID_series = ['D', 'E', 'F']

dropdown2_ID_var = tk.StringVar(root)
dropdown2_ID_var.set(dropdown2_ID_series[0])
dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series)
dropdown2_ID_entry.config(width=10)
dropdown2_ID_entry.grid(row = 2, column = 1, sticky = 'ew', padx = 5, pady = 5)

def submit():
    label11 = tk.Label(subframe, text = dropdown1_ID_var.get(), font = ('Century', 12), bg = 'gray', fg = 'white')
    label22 = tk.Label(subframe, text = dropdown2_ID_var.get(), font = ('Century', 12), bg = 'gray', fg = 'white')
    label11.grid(row = 1, column = 3, padx = 5, pady = 5)
    label22.grid(row = 2, column = 3, padx = 5, pady = 5)

### --- RUN BUTTON
button = tk.Button(subframe, text = 'SUBMIT', font = ('Centur', 12, 'bold'), command = lambda: submit())
button.grid(row = 3, column = 3, ipadx = 20, padx = 5, pady = 15)

root.mainloop()
</code>```

Body:
I want to extract the selected data from a drop down menu in Tkinter. The drop down menu changes based on a previous drop down menu selection.

Basically, how do I save a variable from a lambda function?

I've tried declaring a global variable, and dictionary value but the problem still is that I am overwriting the original drop down menu in my function and the code is still reading the value of the original drop down. Ideally, the code would just update the actual drop down list and not overwrite the original one. Apologies for my clunky, un-pythonic code.

import tkinter as tk

HEIGHT = 500
WIDTH = 500

root = tk.Tk()

canvas = tk.Canvas(root, height = HEIGHT, width = WIDTH)
canvas.pack()

subframe = tk.Frame(root, bg = 'gray', bd = 10)
subframe.place(relx = 0.05, rely = 0.05, relwidth = 0.9, relheight = 0.9)

subframe.rowconfigure(tuple(range(4)), weight = 1)
subframe.columnconfigure(tuple(range(4)), weight = 1)

inputs = {}  ### dictionary for saved label *** I know there HAS to be a better way

### --- dropdown1 Input
label10 = tk.Label(subframe, text = 'Label 1', font = ('Century', 12), bg = 'gray', fg = 'white')
label10.grid(row = 1, column = 0, sticky = 'ew', padx = 5, pady = 5)

dropdown1_ID_series = ['A', 'B', 'C']

#global dropdown2_ID_var

def update_test_data_dropdown(dropdown1ID):
    if dropdown1ID == 'C':
        dropdown2_ID_series = ['1', '2', '3']
        dropdown2_ID_var = tk.StringVar(root)
        dropdown2_ID_var.set(dropdown2_ID_series[0])
        dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series)
        dropdown2_ID_entry.config(width=10)
        dropdown2_ID_entry.grid(row = 2, column = 1, sticky = 'ew', padx = 5, pady = 5)
        inputs['dropdown2'] = dropdown2_ID_var.get()
        print (inputs['dropdown2'])
    else:
        dropdown2_ID_series = ['4', '5','6']
        dropdown2_ID_var = tk.StringVar(root)
        dropdown2_ID_var.set(dropdown2_ID_series[0])
        dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series)
        dropdown2_ID_entry.config(width=10)
        dropdown2_ID_entry.grid(row = 2, column = 1, sticky = 'ew', padx = 5, pady = 5)
        inputs['dropdown2'] = dropdown2_ID_var.get()
    return dropdown2_ID_var  ## need to figure out how to export dropdown2_ID_var

dropdown1_ID_var = tk.StringVar(root)
dropdown1_ID_var.set(dropdown1_ID_series[0])
dropdown1_ID_entry = tk.OptionMenu(subframe, dropdown1_ID_var, *dropdown1_ID_series, command = lambda x: update_test_data_dropdown(x))
dropdown1_ID_entry.config(width=10)
dropdown1_ID_entry.grid(row = 1, column = 1, sticky = 'ew', padx = 5, pady = 5)

### --- dropdown 2 input
label20 = tk.Label(subframe, text = 'Label 2', font = ('Century', 12), bg = 'gray', fg = 'white')
label20.grid(row = 2, column = 0, sticky = 'ew', padx = 5, pady = 5)

dropdown2_ID_series = ['D', 'E', 'F']

dropdown2_ID_var = tk.StringVar(root)
dropdown2_ID_var.set(dropdown2_ID_series[0])
dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series)
dropdown2_ID_entry.config(width=10)
dropdown2_ID_entry.grid(row = 2, column = 1, sticky = 'ew', padx = 5, pady = 5)

inputs['dropdown2'] = dropdown2_ID_var.get()
print (inputs['dropdown2'])

def submit():
    label11 = tk.Label(subframe, text = dropdown1_ID_var.get(), font = ('Century', 12), bg = 'gray', fg = 'white')
    # label22 = tk.Label(subframe, text = dropdown2_ID_var.get(), font = ('Century', 12), bg = 'gray', fg = 'white')
    label22 = tk.Label(subframe, text = inputs['dropdown2'], font = ('Century', 12), bg = 'gray', fg = 'white')
    label11.grid(row = 1, column = 3, padx = 5, pady = 5)
    label22.grid(row = 2, column = 3, padx = 5, pady = 5)

### --- RUN BUTTON
button = tk.Button(subframe, text = 'SUBMIT', font = ('Century', 12, 'bold'), command = lambda: submit())
button.grid(row = 3, column = 3, ipadx = 20, padx = 5, pady = 15)

root.mainloop()

When hitting SUBMIT on the above code, I want the selected value in the dropdowns to print next to the drop down.

Body:
I figured out a better way to update the drop down list by adding the optionmenu entry and variable to the function, deleting the original list, and editing through 'menu' and add_command.  The two tricky/annoying things is having to create a loop to add the new list values individually then most importantly using tk._setit() to have the values actually selectable.  I would be happy to find out if there is a better way but this at least works.

import tkinter as tk

HEIGHT = 500
WIDTH = 500

root = tk.Tk()

canvas = tk.Canvas(root, height = HEIGHT, width = WIDTH)
canvas.pack()

subframe = tk.Frame(root, bg = 'gray', bd = 10)
subframe.place(relx = 0.05, rely = 0.05, relwidth = 0.9, relheight = 0.9)

subframe.rowconfigure(tuple(range(4)), weight = 1)
subframe.columnconfigure(tuple(range(4)), weight = 1)

### --- dropdown1 Input
label10 = tk.Label(subframe, text = 'Label 1', font = ('Century', 12), bg = 'gray', fg = 'white')
label10.grid(row = 1, column = 0, sticky = 'ew', padx = 5, pady = 5)

dropdown1_ID_series = ['A', 'B', 'C']

def update_test_data_dropdown(dropdown1ID, dropdown2_ID_entry, dropdown2_ID_var):
    if dropdown1ID == 'C':
        dropdown2_ID_series2 = ['1', '2', '3']
        dropdown2_ID_entry['menu'].delete(0,'end')
        for v in dropdown2_ID_series2:
            dropdown2_ID_entry['menu'].add_command(label = v, command= tk._setit(dropdown2_ID_var, v))
    else:
        dropdown2_ID_series2 = ['4', '5','6']
        dropdown2_ID_entry['menu'].delete(0,'end')
        for v in dropdown2_ID_series2:
            dropdown2_ID_entry['menu'].add_command(label = v, command= tk._setit(dropdown2_ID_var, v))
    dropdown2_ID_var.set(dropdown2_ID_series2[0])
    return dropdown2_ID_var  ## need to figure out how to export dropdown2_ID_var

dropdown1_ID_var = tk.StringVar(root)
dropdown1_ID_var.set(dropdown1_ID_series[0])
dropdown1_ID_entry = tk.OptionMenu(subframe, dropdown1_ID_var, *dropdown1_ID_series, command = lambda x: update_test_data_dropdown(x, dropdown2_ID_entry, dropdown2_ID_var))
dropdown1_ID_entry.config(width=10)
dropdown1_ID_entry.grid(row = 1, column = 1, sticky = 'ew', padx = 5, pady = 5)

### --- dropdown 2 input
label20 = tk.Label(subframe, text = 'Label 2', font = ('Century', 12), bg = 'gray', fg = 'white')
label20.grid(row = 2, column = 0, sticky = 'ew', padx = 5, pady = 5)

dropdown2_ID_series = ['D', 'E', 'F']

dropdown2_ID_var = tk.StringVar(root)
dropdown2_ID_var.set(dropdown2_ID_series[0])
dropdown2_ID_entry = tk.OptionMenu(subframe, dropdown2_ID_var, *dropdown2_ID_series)
dropdown2_ID_entry.config(width=10)
dropdown2_ID_entry.grid(row = 2, column = 1, sticky = 'ew', padx = 5, pady = 5)

def submit():
    label11 = tk.Label(subframe, text = dropdown1_ID_var.get(), font = ('Century', 12), bg = 'gray', fg = 'white')
    label22 = tk.Label(subframe, text = dropdown2_ID_var.get(), font = ('Century', 12), bg = 'gray', fg = 'white')
    label11.grid(row = 1, column = 3, padx = 5, pady = 5)
    label22.grid(row = 2, column = 3, padx = 5, pady = 5)

### --- RUN BUTTON
button = tk.Button(subframe, text = 'SUBMIT', font = ('Centur', 12, 'bold'), command = lambda: submit())
button.grid(row = 3, column = 3, ipadx = 20, padx = 5, pady = 15)

root.mainloop()


问:
Finding spots in a numpy matrix
I have the following Matrix made of 0s and 1s which I want to identify its spots(elements with the value 1 and connected to eachothers).

```<code>M = np.array([[1,1,1,0,0,0,0,0,0,0,0],
              [1,1,1,0,0,0,0,0,0,1,1],
              [1,1,1,0,0,0,0,0,0,1,1],
              [1,1,1,0,0,1,1,1,0,0,0],
              [0,0,0,0,0,1,1,1,0,0,0],
              [1,1,1,0,1,1,1,1,0,0,0],
              [1,1,1,0,0,1,1,1,0,0,0],
              [1,1,1,0,0,1,1,1,0,0,0]])
</code>```

In the matrix there are four spots.

an example of my output should seem the following

```<code>spot_0 = array[(0,0),(0,1), (0,2), (1,0),(1,1), (1,2), (2,0),(2,1), (2,2), (3,0),(3,1), (3,2)]
Nbr_0 = 12
Top_Left = (0, 0)
and that is the same process for the other 3 spots
</code>```

Does anyone know how can I identify each spot with the number of its elements and top_left element, using numpy functions ?
Thanks

答:
You could use skimage.measure.label or other tools (for instance, OpenCV or igraph) to create labels for connected components:

```<code>#from @Jérôme's answer
from skimage.measure import label
components = label(M)

# array([[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
#        [1, 1, 1, 0, 0, 0, 0, 0, 0, 2, 2],
#        [1, 1, 1, 0, 0, 0, 0, 0, 0, 2, 2],
#        [1, 1, 1, 0, 0, 3, 3, 3, 0, 0, 0],
#        [0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0],
#        [4, 4, 4, 0, 3, 3, 3, 3, 0, 0, 0],
#        [4, 4, 4, 0, 0, 3, 3, 3, 0, 0, 0],
#        [4, 4, 4, 0, 0, 3, 3, 3, 0, 0, 0]])
</code>```

In the later part you could create a one-dimensional view of image, sort values of pixels and find dividing points of sorted label values:

```<code>components_ravel = components.ravel()
c = np.arange(1, np.max(components_ravel) + 1)
argidx = np.argsort(components_ravel)
div_points = np.searchsorted(components_ravel, c, sorter=argidx)

# Sorted label values are:
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
# 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
# 2, 2, 2, 2
# 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3
# 4, 4, 4, 4, 4, 4, 4, 4, 4
# So you find indices that divides these groups:
# [47, 59, 63, 79]
</code>```

After that you could split array of indices that sorts your one-dimensional view of image at these points and convert them into two-dimensional ones:

```<code>spots = []
for n in np.split(argidx, div_points)[1:]: #in case there are no zeros, cancel `[1:]`
    x, y = np.unravel_index(n, components.shape)
    spots.append(np.transpose([x, y]))
</code>```

It creates a list of spot coordinates of each group:

```<code>[array([[1, 0], [1, 2], [0, 2], [0, 1], [1, 1], [0, 0], [2, 2], [2, 1], [2, 0], [3, 2], [3, 1], [3, 0]]),
 array([[2, 10], [1, 9], [2, 9], [1, 10]]),
 array([[6, 5], [7, 5], [7, 6], [7, 7], [6, 7], [6, 6], [3, 5], [4, 6], [3, 6], [4, 5], [3, 7], [5, 7], [5, 6], [4, 7], [5, 5], [5, 4]]),
 array([[5, 0], [5, 1], [5, 2], [6, 2], [7, 0], [6, 0], [6, 1], [7, 1], [7, 2]])]
</code>```

Note that an order of pixels of each group is mixed. This is because np.argsort uses a sort which is not stable. You could fix it like so:

```<code>argidx = np.argsort(components_ravel, kind='stable')
</code>```

In this case you'll get:

```<code>[array([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2], [3, 0], [3, 1], [3, 2]]),
 array([[1, 9], [1, 10], [2, 9], [2, 10]]),
 array([[3, 5], [3, 6], [3, 7], [4, 5], [4, 6], [4, 7], [5, 4], [5, 5], [5, 6], [5, 7], [6, 5], [6, 6], [6, 7], [7, 5], [7, 6], [7, 7]]),
 array([[5, 0], [5, 1], [5, 2], [6, 0], [6, 1], [6, 2], [7, 0], [7, 1], [7, 2]])]
</code>```

Title: Finding spots in a numpy matrix

Body:
I have the following Matrix made of 0s and 1s which I want to identify its spots(elements with the value 1 and connected to eachothers).

M = np.array([[1,1,1,0,0,0,0,0,0,0,0],
              [1,1,1,0,0,0,0,0,0,1,1],
              [1,1,1,0,0,0,0,0,0,1,1],
              [1,1,1,0,0,1,1,1,0,0,0],
              [0,0,0,0,0,1,1,1,0,0,0],
              [1,1,1,0,1,1,1,1,0,0,0],
              [1,1,1,0,0,1,1,1,0,0,0],
              [1,1,1,0,0,1,1,1,0,0,0]])

In the matrix there are four spots.

an example of my output should seem the following

spot_0 = array[(0,0),(0,1), (0,2), (1,0),(1,1), (1,2), (2,0),(2,1), (2,2), (3,0),(3,1), (3,2)]
Nbr_0 = 12
Top_Left = (0, 0)
and that is the same process for the other 3 spots

Does anyone know how can I identify each spot with the number of its elements and top_left element, using numpy functions ?
Thanks

Body:
You could use skimage.measure.label or other tools (for instance, OpenCV or igraph) to create labels for connected components:

#from @Jérôme's answer
from skimage.measure import label
components = label(M)

# array([[1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],
#        [1, 1, 1, 0, 0, 0, 0, 0, 0, 2, 2],
#        [1, 1, 1, 0, 0, 0, 0, 0, 0, 2, 2],
#        [1, 1, 1, 0, 0, 3, 3, 3, 0, 0, 0],
#        [0, 0, 0, 0, 0, 3, 3, 3, 0, 0, 0],
#        [4, 4, 4, 0, 3, 3, 3, 3, 0, 0, 0],
#        [4, 4, 4, 0, 0, 3, 3, 3, 0, 0, 0],
#        [4, 4, 4, 0, 0, 3, 3, 3, 0, 0, 0]])

In the later part you could create a one-dimensional view of image, sort values of pixels and find dividing points of sorted label values:

components_ravel = components.ravel()
c = np.arange(1, np.max(components_ravel) + 1)
argidx = np.argsort(components_ravel)
div_points = np.searchsorted(components_ravel, c, sorter=argidx)

# Sorted label values are:
# [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
# 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
# 2, 2, 2, 2
# 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3
# 4, 4, 4, 4, 4, 4, 4, 4, 4
# So you find indices that divides these groups:
# [47, 59, 63, 79]

After that you could split array of indices that sorts your one-dimensional view of image at these points and convert them into two-dimensional ones:

spots = []
for n in np.split(argidx, div_points)[1:]: #in case there are no zeros, cancel `[1:]`
    x, y = np.unravel_index(n, components.shape)
    spots.append(np.transpose([x, y]))

It creates a list of spot coordinates of each group:

[array([[1, 0], [1, 2], [0, 2], [0, 1], [1, 1], [0, 0], [2, 2], [2, 1], [2, 0], [3, 2], [3, 1], [3, 0]]),
 array([[2, 10], [1, 9], [2, 9], [1, 10]]),
 array([[6, 5], [7, 5], [7, 6], [7, 7], [6, 7], [6, 6], [3, 5], [4, 6], [3, 6], [4, 5], [3, 7], [5, 7], [5, 6], [4, 7], [5, 5], [5, 4]]),
 array([[5, 0], [5, 1], [5, 2], [6, 2], [7, 0], [6, 0], [6, 1], [7, 1], [7, 2]])]

Note that an order of pixels of each group is mixed. This is because np.argsort uses a sort which is not stable. You could fix it like so:

argidx = np.argsort(components_ravel, kind='stable')

In this case you'll get:

[array([[0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2], [3, 0], [3, 1], [3, 2]]),
 array([[1, 9], [1, 10], [2, 9], [2, 10]]),
 array([[3, 5], [3, 6], [3, 7], [4, 5], [4, 6], [4, 7], [5, 4], [5, 5], [5, 6], [5, 7], [6, 5], [6, 6], [6, 7], [7, 5], [7, 6], [7, 7]]),
 array([[5, 0], [5, 1], [5, 2], [6, 0], [6, 1], [6, 2], [7, 0], [7, 1], [7, 2]])]


问:
How to display input value for a date in C
The output has to be printed Date: 2021-FEB-01

After receiving the input month and year value, for example, 2018 January should be displayed 2018-JAN-01.

how could I display YYYY-MMM-DD?

I used else if from Jan to Dec. Is there a simpler code?

```<code>if (month == 1)
   printf("Date: %d-JAN-01\n", year);

else if (month == 2)
   printf("Date: %d-FEB-01\n", year);

...
</code>```

答:
You can use an array of string literals:

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

int main(void)
{
    const char *months[] = {"", "JAN", "FEB", "MAR", "APR", "MAY", "JUN",
                                "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};

    int year = 2022;
    int month = 2;

    printf("Date: %d-%s-01\n", year, months[month]);
    return 0;
}
</code>```

Is there any way to express it without using arrays?

Yes, take a look to strftime:

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

int main(void)
{
    struct tm *tmp;
    time_t t;

    char str[12];

    time(&t);

    tmp = localtime(&t);

    strftime(str, sizeof(str), "%Y-%b-%d\n", tmp);

    printf("Date: %s\n", str);
    return(0);
}
</code>```

The output is:

```<code>Date: 2022-Feb-11
</code>```

Note that time() takes the current time, you can also fill a struct tm by hand:

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

int main(void)
{
    struct tm tmp = {
        .tm_year = 2022 - 1900,
        .tm_mon = 2,
        .tm_mday = 11,
        .tm_hour = 0,
        .tm_min = 0,
        .tm_sec= 0
    };

    char str[12];

    strftime(str, sizeof(str), "%Y-%b-%d\n", &tmp);

    printf("Date: %s\n", str);
    return(0);
}
</code>```

Body:
The output has to be printed Date: 2021-FEB-01

After receiving the input month and year value, for example, 2018 January should be displayed 2018-JAN-01.

how could I display YYYY-MMM-DD?

I used else if from Jan to Dec. Is there a simpler code?

if (month == 1)
   printf("Date: %d-JAN-01\n", year);

else if (month == 2)
   printf("Date: %d-FEB-01\n", year);

...

Body:
You can use an array of string literals:

#include <stdio.h>

int main(void)
{
    const char *months[] = {"", "JAN", "FEB", "MAR", "APR", "MAY", "JUN",
                                "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"};

    int year = 2022;
    int month = 2;

    printf("Date: %d-%s-01\n", year, months[month]);
    return 0;
}

Is there any way to express it without using arrays?

Yes, take a look to strftime:

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

int main(void)
{
    struct tm *tmp;
    time_t t;

    char str[12];

    time(&t);

    tmp = localtime(&t);

    strftime(str, sizeof(str), "%Y-%b-%d\n", tmp);

    printf("Date: %s\n", str);
    return(0);
}

The output is:

Date: 2022-Feb-11

Note that time() takes the current time, you can also fill a struct tm by hand:

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

int main(void)
{
    struct tm tmp = {
        .tm_year = 2022 - 1900,
        .tm_mon = 2,
        .tm_mday = 11,
        .tm_hour = 0,
        .tm_min = 0,
        .tm_sec= 0
    };

    char str[12];

    strftime(str, sizeof(str), "%Y-%b-%d\n", &tmp);

    printf("Date: %s\n", str);
    return(0);
}


问:
How to achieve @args splatting in an advanced function in Powershell?
Consider the following simple function:

```<code>function Write-HostIfNotVerbose()
{
    if ($VerbosePreference -eq 'SilentlyContinue')
    {
        Write-Host @args
    }
}
</code>```

And it works fine:

Now I want to make it an advanced function, because I want it to inherit the verbosity preference:

```<code>function Write-HostIfNotVerbose([Parameter(ValueFromRemainingArguments)]$MyArgs)
{
    if ($VerbosePreference -eq 'SilentlyContinue')
    {
        Write-Host @MyArgs
    }
}
</code>```

But it does not work:

And what drives me nuts is that I am unable to identify how $args in the first example is different from $args in the second.

I know that the native @args splatting does not work for advanced functions by default - https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-7.2#notes

But I hoped it could be simulated, yet it does not work either. My question is - what is wrong with the way I am trying to simulate it and whether it is possible to fix my code without surfacing all the Write-Host parameters at Write-HostIfNotVerbose

答:
This is too obscure for me to explain, but for the sake of answering what PowerShell could be doing with $args you can test this:

function Write-HostIfNotVerbose {
param(
    [parameter(ValueFromRemainingArguments)]
    [object[]]$MagicArgs
)
    $params = @{
        NotePropertyName = '<CommandParameterName>'
        PassThru = $true
        InputObject = ''
    }
    $z = foreach($i in $MagicArgs) {
        if($i.StartsWith('-')) {
            $params.NotePropertyValue = $i
            Add-Member @params
            continue
        }
        $i
    }

    if ($VerbosePreference -eq 'SilentlyContinue') {
        Write-Host @z
    }
}

Write-HostIfNotVerbose -ForegroundColor Green Hello world! -BackgroundColor Yellow
```
<p>A way of seeing what <code>$args</code> is doing <em>automatically</em> for us could be to serialize the variable:</p>
```function Test-Args {
    [System.Management.Automation.PSSerializer]::Serialize($args)
}

Test-Args -Argument1 Hello -Argument2 World
```
<p>Above would give us the serialized representation of <code>$args</code> where we would observe the following:</p>
```<LST>
  <Obj RefId="1">
    <S>-Argument1</S>
    <MS>
      <S N="<CommandParameterName>">Argument1</S>
    </MS>
  </Obj>
  <S>Hello</S>
  <Obj RefId="2">
    <S>-Argument2</S>
    <MS>
      <S N="<CommandParameterName>">Argument2</S>
    </MS>
  </Obj>
  <S>World</S>
</LST>
```

Body:
Consider the following simple function:

function Write-HostIfNotVerbose()
{
    if ($VerbosePreference -eq 'SilentlyContinue')
    {
        Write-Host @args
    }
}

And it works fine:

Now I want to make it an advanced function, because I want it to inherit the verbosity preference:

function Write-HostIfNotVerbose([Parameter(ValueFromRemainingArguments)]$MyArgs)
{
    if ($VerbosePreference -eq 'SilentlyContinue')
    {
        Write-Host @MyArgs
    }
}

But it does not work:

And what drives me nuts is that I am unable to identify how $args in the first example is different from $args in the second.

I know that the native @args splatting does not work for advanced functions by default - https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-7.2#notes

But I hoped it could be simulated, yet it does not work either. My question is - what is wrong with the way I am trying to simulate it and whether it is possible to fix my code without surfacing all the Write-Host parameters at Write-HostIfNotVerbose

Body:
This is too obscure for me to explain, but for the sake of answering what PowerShell could be doing with $args you can test this:

function Write-HostIfNotVerbose {
param(
    [parameter(ValueFromRemainingArguments)]
    [object[]]$MagicArgs
)
    $params = @{
        NotePropertyName = '<CommandParameterName>'
        PassThru = $true
        InputObject = ''
    }
    $z = foreach($i in $MagicArgs) {
        if($i.StartsWith('-')) {
            $params.NotePropertyValue = $i
            Add-Member @params
            continue
        }
        $i
    }

    if ($VerbosePreference -eq 'SilentlyContinue') {
        Write-Host @z
    }
}

Write-HostIfNotVerbose -ForegroundColor Green Hello world! -BackgroundColor Yellow

A way of seeing what $args is doing automatically for us could be to serialize the variable:

function Test-Args {
    [System.Management.Automation.PSSerializer]::Serialize($args)
}

Test-Args -Argument1 Hello -Argument2 World

Above would give us the serialized representation of $args where we would observe the following:

<LST>
  <Obj RefId="1">
    <S>-Argument1</S>
    <MS>
      <S N="&lt;CommandParameterName&gt;">Argument1</S>
    </MS>
  </Obj>
  <S>Hello</S>
  <Obj RefId="2">
    <S>-Argument2</S>
    <MS>
      <S N="&lt;CommandParameterName&gt;">Argument2</S>
    </MS>
  </Obj>
  <S>World</S>
</LST>


问:
Android C2DM port number choice
I noticed that the Google C2DM (push) tcp connection uses port 5228. I also know that some firewalls block ports other than 80 443 (because of htttp and https), which causes lots of users to complain that they can't use the Market app or GTalk on their phones using their company wifi for example.

Now my question is: why didn't Google choose port 443 or 80 for their persistent tcp connection?

答:
There are a few reasons I can think of that Google may have chosen to use 5228 instead of 80 or 443.

Firstly, in most (but definitely not all) cases, 5228 should not be a problem (i.e. blocked) because push notifications are largely used when devices are on the go. This means they are using cell phone data connections that do not block this port and are not firewalled.

Secondly, in the case of environments where there might be a firewall (i.e. with WiFi inside a corporation), it is also likely that http traffic is proxied or controlled in some fashion. C2DM does not rely on a standard HTTP protocol and is expected to be a long-lived connection. This means that running it on 80/443 might cause issues in these environments.

Thirdly, these services likely were using 5228 prior to the release of C2DM and there was no clear reason to change it.

Based on my experience, I think it would have been ideal if they used 5228 as a default, and attempted to fall-back to 443 in other cases (as there are definitely many scenarios where 443 would work when 5228 wouldn't). At least in the case of 443, modification of data is less-likely than if on port 80 because the protocol would normally be encrypted. However, it is still possible the connection would be prematurely terminated on 443. However, this risk exists in any network environment, and there would be no downfall in trying.

And on separate note, it is likely that enabling C2DM on 443 would have been more difficult than it seems for Google because their distributed front-end servers likely know how to specifically handle 80/443 traffic as HTTP and would require significant re-working to handle C2DM.

Title: Android C2DM port number choice


问:
Insert data from one table to another table in chunks - MySQL
I have been trying to load data from one table that has 100 million + rows into a new table based on a filter. I have tried to load using the procedure below but for some reason it just sits there with no result or activity in processlist.

I have been trying to insert data based on updated date but end up either inserting the same data each time running into a PK violation or no update.

Please advise what's the best way to load this data into a new table. Thanks

```<code>USE `mydb`;
DROP procedure IF EXISTS `insert_data`;

DELIMITER $$
USE `ods`$$
CREATE PROCEDURE `insert_data` ()
BEGIN
DECLARE i INT DEFAULT 0;
DECLARE limitSize INT DEFAULT 2000;
DECLARE maxupdate datetime;

SET maxupdate = (SELECT MAX(updated) FROM test_data);

WHILE i <= maxId DO
START TRANSACTION;
INSERT INTO test_arc
SELECT * FROM test_data
WHERE check_time>='2022-02-05' and updated> i
ORDER BY updated ASC
LIMIT limitSize;
COMMIT;
SET i = i + limitSize;
END WHILE;
END$$
DELIMITER;

--My Tables:
--Actual Table
 CREATE TABLE test_data (
 UNIQUE_ID bigint(11) NOT NULL,
 DEVICE_NAME varchar(128) NOT NULL DEFAULT '',
 PARAMETER_NAME varchar(256) DEFAULT NULL,
 GMT_OFFSET varchar(6) DEFAULT NULL,
 CHECK_TIME datetime NOT NULL DEFAULT '1970-01-01 00:00:00',
 OUTPUT_DATA text NOT NULL,
 PERF_DATA text NOT NULL,
 PRIMARY KEY (UNIQUE_ID)
 );

 --Archive Table
CREATE TABLE test_arc (
UNIQUE_ID bigint(11) NOT NULL,
DEVICE_NAME varchar(128) NOT NULL DEFAULT '',
PARAMETER_NAME varchar(256) DEFAULT NULL,
GMT_OFFSET varchar(6) DEFAULT NULL,
CHECK_TIME datetime NOT NULL DEFAULT '1970-01-01 00:00:00',
OUTPUT_DATA text NOT NULL,
PERF_DATA text NOT NULL,
PRIMARY KEY (UNIQUE_ID)
</code>```

);

答:
Transaction you don't really that is why i removed it, the rest ist controlled by LIMIT and OFFSET which you need to do such a partial updates in block

```<code>CREATE TABLE test_arc (id int,check_time datetime, updated datetime)
</code>```

```<code>CREATE TABLE test_data (id int,check_time datetime, updated Datetime)
</code>```

```<code>INSERT INTO test_data VALUES (1,NOW() - INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY),(2,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY)
,(3,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY),(4,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY)
,(5,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY),
(6,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY),(7,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY)
,(8,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY)
,(9,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY),(10,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY)
</code>```

```<code>SELECT * FROM test_data
</code>```

```
id | check_time          | updated
-: | :------------------ | :------------------
 1 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 2 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 3 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 4 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 5 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 6 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 7 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 8 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 9 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
10 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
```

```<code>CREATE PROCEDURE `insert_data` ()
BEGIN
DECLARE i BIGINT DEFAULT 0;
DECLARE limitSize INT DEFAULT 5;
DECLARE maxnumber BIGINT;

SET maxnumber = (SELECT COUNT(*) FROM test_data) + 1;

WHILE i <= maxnumber DO
     INSERT INTO test_arc
         SELECT id ,check_time, NOW() FROM test_data
         WHERE check_time>='2022-02-05'
         ORDER BY updated ASC
         LIMIT i, limitSize
     ON DUPLICATE KEY UPDATE id =VALUES(id), check_time=VALUES(check_time),updated  = Values(updated );   SET i = i + limitSize;
END WHILE;
END
</code>```
```
✓
```

```<code>CALL insert_data();
</code>```

```<code>SELECT * FROM test_arc
</code>```
```
id | check_time          | updated
-: | :------------------ | :------------------
 1 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 2 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 3 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 4 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 5 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 6 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 7 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 8 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 9 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
10 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
```

db<>fiddle here

Body:
I have been trying to load data from one table that has 100 million + rows into a new table based on a filter. I have tried to load using the procedure below but for some reason it just sits there with no result or activity in processlist.

I have been trying to insert data based on updated date but end up either inserting the same data each time running into a PK violation or no update.

Please advise what's the best way to load this data into a new table. Thanks

USE `mydb`;
DROP procedure IF EXISTS `insert_data`;

DELIMITER $$
USE `ods`$$
CREATE PROCEDURE `insert_data` ()
BEGIN
DECLARE i INT DEFAULT 0;
DECLARE limitSize INT DEFAULT 2000;
DECLARE maxupdate datetime;

SET maxupdate = (SELECT MAX(updated) FROM test_data);

WHILE i <= maxId DO
START TRANSACTION;
INSERT INTO test_arc
SELECT * FROM test_data
WHERE check_time>='2022-02-05' and updated> i
ORDER BY updated ASC
LIMIT limitSize;
COMMIT;
SET i = i + limitSize;
END WHILE;
END$$
DELIMITER;

--My Tables:
--Actual Table
 CREATE TABLE test_data (
 UNIQUE_ID bigint(11) NOT NULL,
 DEVICE_NAME varchar(128) NOT NULL DEFAULT '',
 PARAMETER_NAME varchar(256) DEFAULT NULL,
 GMT_OFFSET varchar(6) DEFAULT NULL,
 CHECK_TIME datetime NOT NULL DEFAULT '1970-01-01 00:00:00',
 OUTPUT_DATA text NOT NULL,
 PERF_DATA text NOT NULL,
 PRIMARY KEY (UNIQUE_ID)
 );

 --Archive Table
CREATE TABLE test_arc (
UNIQUE_ID bigint(11) NOT NULL,
DEVICE_NAME varchar(128) NOT NULL DEFAULT '',
PARAMETER_NAME varchar(256) DEFAULT NULL,
GMT_OFFSET varchar(6) DEFAULT NULL,
CHECK_TIME datetime NOT NULL DEFAULT '1970-01-01 00:00:00',
OUTPUT_DATA text NOT NULL,
PERF_DATA text NOT NULL,
PRIMARY KEY (UNIQUE_ID)

);

Body:
Transaction you don't really that is why i removed it, the rest ist controlled by LIMIT and OFFSET which you need to do such a partial updates in block

CREATE TABLE test_arc (id int,check_time datetime, updated datetime)

CREATE TABLE test_data (id int,check_time datetime, updated Datetime)

INSERT INTO test_data VALUES (1,NOW() - INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY),(2,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY)
,(3,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY),(4,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY)
,(5,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY),
(6,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY),(7,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY)
,(8,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY)
,(9,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY),(10,NOW()- INTERVAL 1 DAY,NOW()- INTERVAL 1 DAY)

SELECT * FROM test_data

id | check_time          | updated
-: | :------------------ | :------------------
 1 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 2 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 3 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 4 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 5 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 6 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 7 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 8 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
 9 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12
10 | 2022-02-12 18:27:12 | 2022-02-12 18:27:12

CREATE PROCEDURE `insert_data` ()
BEGIN
DECLARE i BIGINT DEFAULT 0;
DECLARE limitSize INT DEFAULT 5;
DECLARE maxnumber BIGINT;

SET maxnumber = (SELECT COUNT(*) FROM test_data) + 1;

WHILE i <= maxnumber DO
     INSERT INTO test_arc
         SELECT id ,check_time, NOW() FROM test_data
         WHERE check_time>='2022-02-05'
         ORDER BY updated ASC
         LIMIT i, limitSize
     ON DUPLICATE KEY UPDATE id =VALUES(id), check_time=VALUES(check_time),updated  = Values(updated );   SET i = i + limitSize;
END WHILE;
END

✓

CALL insert_data();

SELECT * FROM test_arc

id | check_time          | updated
-: | :------------------ | :------------------
 1 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 2 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 3 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 4 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 5 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 6 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 7 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 8 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
 9 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12
10 | 2022-02-12 18:27:12 | 2022-02-13 18:27:12

db<>fiddle here


问:
How do I disable a SwiftUI NavigationView list item row on load?
I have an array of objects (employees) that I am displaying in a navigationview. Each object has a boolean property called "Active". If the employee is active I want the navigationlink for that list item to work as it normally would but if the employee is not active then I want that list item to be disabled so that the navigationlink or any swipe actions do not work. This is my code:

```<code>NavigationView {
    List {
        CustomSearchBar(searchText: $searchText, searchCategory: $searchCategory)
        ForEach(Employees) { person in
            ZStack {
                NavigationLink(destination: DisplayDetails().environmentObject(person)) {
                    ListItem().environmentObject(person)
                }
            }
            .swipeActions(edge: .leading, content: {
                Button {
                    Employees.toggleArchiveFlag(for: person.id)
                } label: {
                    Label("Archive", systemImage: !person.archived ? "square.and.arrow.down" : "trash")
                }
                .tint(!person.archived ? .blue : .red)
            })
            .disabled(!person.active)
        }
    }
    .navigationTitle("Current Employees")
    .padding(.horizontal,-15) // remove the padding that the list adds to the screen
}
</code>```

What ends up happing is that when the view initially loads everything is enabled regardless of each employee's active status. But if I click any of the navigationlinks to load the "DisplayDetails" detailed view and then return back to the main navigationview OR if I click on any of the searchbar toggles or use the searchbar to filter my list of people then the view updates and the correct people are disabled.

It is almost as if the statement ".disabled(!person.active)" is being called too late. If that is the case then where should I be calling it? I have tried moving that statement in the following places:

The closing bracket of the Zstack. But this does nothing

Right below the "ListItem().environmentObject(person)" statement but this still shows the same behavior as mentioned earlier and when the navigationlink is eventually disabled then the swipeactions are still enabled.

Any help at all would be appreciated!

答: Figured out that the issue was with the logic that set the person.active boolean value not with the presentation of the navigation view items. Thanks.</p>

Body:
I have an array of objects (employees) that I am displaying in a navigationview. Each object has a boolean property called "Active". If the employee is active I want the navigationlink for that list item to work as it normally would but if the employee is not active then I want that list item to be disabled so that the navigationlink or any swipe actions do not work. This is my code:

NavigationView {
    List {
        CustomSearchBar(searchText: $searchText, searchCategory: $searchCategory)
        ForEach(Employees) { person in
            ZStack {
                NavigationLink(destination: DisplayDetails().environmentObject(person)) {
                    ListItem().environmentObject(person)
                }
            }
            .swipeActions(edge: .leading, content: {
                Button {
                    Employees.toggleArchiveFlag(for: person.id)
                } label: {
                    Label("Archive", systemImage: !person.archived ? "square.and.arrow.down" : "trash")
                }
                .tint(!person.archived ? .blue : .red)
            })
            .disabled(!person.active)
        }
    }
    .navigationTitle("Current Employees")
    .padding(.horizontal,-15) // remove the padding that the list adds to the screen
}

What ends up happing is that when the view initially loads everything is enabled regardless of each employee's active status. But if I click any of the navigationlinks to load the "DisplayDetails" detailed view and then return back to the main navigationview OR if I click on any of the searchbar toggles or use the searchbar to filter my list of people then the view updates and the correct people are disabled.

It is almost as if the statement ".disabled(!person.active)" is being called too late. If that is the case then where should I be calling it? I have tried moving that statement in the following places:

The closing bracket of the Zstack. But this does nothing

Right below the "ListItem().environmentObject(person)" statement but this still shows the same behavior as mentioned earlier and when the navigationlink is eventually disabled then the swipeactions are still enabled.

Any help at all would be appreciated!


问:
Need help creating a Regex
I need a regex to validate:

just numbers

it have to start with the number 20

the five number needs to be 0 or 1

the seven number needs to be 1, 2 or 3

答:
Are you going to validate a date YYYYMMDD?

Try this: http://programmerramblings.blogspot.com/2008/08/elegant-date-validation-in-c.html

Or this: http://www.c-sharpcorner.com/UploadFile/scottlysle/DateValCS02222009225005PM/DateValCS.aspx

Or this: http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx

Title: Need help creating a Regex


问:
Invalid Python SDK in PyCharm
Since this morning, I'm no longer able to run projects in PyCharm.

When generating a new virtual environment, I get an "Invalid Python SDK" error.
Cannot set up a python SDK at Python 3.11... The SDK seems invalid.

What I noticed:
No matter what base interpreter I select (3.8, 3.9, 3.10) Pycharm always generates a Python 3.11 interpreter.

I did completely uninstall PyCharm, as well as all my python installations and reinstalled everything.
I also went through the "Repair IDE" option in PyCharm.
I also removed and recreated all virtual environments.

When I run "cmd" and type 'python' then python 3.10.1 opens without a problem.

This morning, I installed a new antivirus software that did some checks and deleted some "unnecessary files" - maybe it is related (antivirus software is uninstalled again).

答:
I had the same problem on Linux. Solved it by invalidating caches as suggested here:
https://stackoverflow.com/a/45099651/3990607

In pycharm click on File menu, then choose Invalidate caches..., tick all 4 boxes and then restart PyCharm. Solved the problem for me.

Title: Invalid Python SDK in PyCharm


问:
How to pass selection from Django template to Class view
I am struggling with something that should be routine for me by now but I have a mental block.
I have a model that stores Country names and a slug version of the name.

Eg. "United States", "united-states"

I want to display the country names in a template for selection, then return the selected country's slug value to the Class based View which will then obtain the data.  The list of countries can be links or dropdown - whatever.  But I need to obtain the selected value in the View.  Here is a simplified version:

Template

```<code>{% extends 'base.html' %}
{% block content %}
<form method="POST">
    {% for country in object_list %}
        <a href="{{country.slug_name}}">{{ country.pretty_name }}</a></br>
    {% endfor %}
</form>
{% endblock content %}
</code>```

View

```<code>class CountryView(TemplateView):
    country_name = THE SLUG
    country_obj = Country(country_name)
    country_obj.build_country_dictionary()
    country_obj.display()
</code>```

So I think I need one of the get methods to access this but I cannot work it out.  Thanks for any help.

答:
The "structured way"

Have a look at FormView, where you define your form class (which you also need to create, depends on your situation can be a model form as well). The rest is pretty much handled by the view.

https://ccbv.co.uk/projects/Django/4.0/django.views.generic.edit/FormView/

PSEUDO code

class MyForm(ModelForm):
    model = YourModel

class MyFormView(FormView):
    form_class = MyForm

    # depends on what you want to do, you can overwrite form_valid to do your logic

```
<p>The quickest way</p>
<p>PSEUDO code</p>
```{% extends 'base.html' %}
{% block content %}
<form method="POST">
    {% csrf_token %}
    <select name="selection">
    {% for country in object_list %}
        <option value="{{ country.slug_name }}">{{ country.pretty_name }}</option>
    {% endfor %}
    </select>
    <input type="submit">Submit</input>
</form>
{% endblock content %}
```
<pre class="lang-py prettyprint-override"><code>class CountryView(TemplateView):
    def post(self, request, *args, **kwargs):
        selection = request.POST.get('selection')

</code>```

Body:
I am struggling with something that should be routine for me by now but I have a mental block.
I have a model that stores Country names and a slug version of the name.

Eg. "United States", "united-states"

I want to display the country names in a template for selection, then return the selected country's slug value to the Class based View which will then obtain the data.  The list of countries can be links or dropdown - whatever.  But I need to obtain the selected value in the View.  Here is a simplified version:

Template

{% extends 'base.html' %}
{% block content %}
<form method="POST">
    {% for country in object_list %}
        {{ country.pretty_name }}

    {% endfor %}
</form>
{% endblock content %}

View

class CountryView(TemplateView):
    country_name = THE SLUG
    country_obj = Country(country_name)
    country_obj.build_country_dictionary()
    country_obj.display()

So I think I need one of the get methods to access this but I cannot work it out.  Thanks for any help.

Body:
The "structured way"

Have a look at FormView, where you define your form class (which you also need to create, depends on your situation can be a model form as well). The rest is pretty much handled by the view.

https://ccbv.co.uk/projects/Django/4.0/django.views.generic.edit/FormView/

PSEUDO code

class MyForm(ModelForm):
    model = YourModel

class MyFormView(FormView):
    form_class = MyForm

    # depends on what you want to do, you can overwrite form_valid to do your logic

The quickest way

PSEUDO code

{% extends 'base.html' %}
{% block content %}
<form method="POST">
    {% csrf_token %}
    <select name="selection">
    {% for country in object_list %}
        <option value="{{ country.slug_name }}">{{ country.pretty_name }}</option>
    {% endfor %}
    </select>
    <input type="submit">Submit</input>
</form>
{% endblock content %}

class CountryView(TemplateView):
    def post(self, request, *args, **kwargs):
        selection = request.POST.get('selection')


问:
Return to next line in text using CSS?
I am having a css issue

I have a td, inside it, there is a text, the text as you can see is a code itself, but consider it as text only

my td now is bigger than the expected, because the text inside surpasses the width of the parent, for this I tried this white-space:initial property as you can see, I was expecting the text to never go out from its parent, break to next line inside text ( not words )

```<code><table>
<tr>
    <td align="center" style="text-align:center;font-size: 12px;width:130px;white-space:initial;line-height:20px;max-width:130px;" width="130">
       <a class="link-txt" href="%%=RedirectTo(CONCAT(TreatAsContent(@delivery_service_link), '&utm_content=footer&utm_clickposition=delivery_service_copy'))=%%" style="text-decoration:none;color:#2e2e2e;font-family:Arial, Helvetica, sans-serif;line-height:20px;white-space:initial; text-align:center;">
                 %%=TreatAsContent(
                @delivery_service_copy )=%%</a>
    </td>
</tr>
</table>
</code>```

end result is bad :

Expected result :

Any help would be much appreciated

This is for email development, that's why there is some inline styling

Thanks

答:
Long text will push layouts out, as you have found.

There is no one bit of code for all email environments, and it's not all CSS (some strip out the CSS or don't support it). Therefore, you'll see <wbr> which is an optional break to cover those scenarios.

Here's the snippet:

```<code><style type="text/css"> <!-- Put in <head> -->
.wordwrap {
overflow-wrap: break-all;
word-wrap: break-all;
word-break: break-all
}
</style>

<p class="wordwrap" style="overflow-wrap: break-all; word-wrap: break-all; word-break: break-all;"><a href="http://www.this.com/is/too/long/for/mobiles">http://<wbr>www.this.com/<wbr>is/too/<wbr>long/for/<wbr>mobiles</a></p>
</code>```

This requires that the information has <wbr> inside at the points you want it to attempt a break, so if it's coming dynamically, and you can't edit the dynamic values, it won't work everywhere.

Title: Return to next line in text using CSS?

Body:
I am having a css issue

I have a td, inside it, there is a text, the text as you can see is a code itself, but consider it as text only

my td now is bigger than the expected, because the text inside surpasses the width of the parent, for this I tried this white-space:initial property as you can see, I was expecting the text to never go out from its parent, break to next line inside text ( not words )

                 %%=TreatAsContent(
                @delivery_service_copy )=%%

end result is bad :

Expected result :

Any help would be much appreciated

This is for email development, that's why there is some inline styling

Thanks

Body:
Long text will push layouts out, as you have found.

There is no one bit of code for all email environments, and it's not all CSS (some strip out the CSS or don't support it). Therefore, you'll see <wbr> which is an optional break to cover those scenarios.

Here's the snippet:

<style type="text/css"> <!-- Put in <head> -->
.wordwrap {
overflow-wrap: break-all;
word-wrap: break-all;
word-break: break-all
}
</style>

<p class="wordwrap" style="overflow-wrap: break-all; word-wrap: break-all; word-break: break-all;"><a href="http://www.this.com/is/too/long/for/mobiles">http://<wbr>www.this.com/<wbr>is/too/<wbr>long/for/<wbr>mobiles</a></p>

This requires that the information has <wbr> inside at the points you want it to attempt a break, so if it's coming dynamically, and you can't edit the dynamic values, it won't work everywhere.


问:
Travelling Salesman with Momentum?
I have a task that is very similar to travelling salesman problem (TSP), but I'm not sure if it's easily mappable to TSP.  I'm wondering if this variant has a name and known solvers already, or can be just reduced to TSP somehow.

I have a graph where nodes are (x, y) locations, and edges are smooth, continuous paths connecting those locations.  As in normal TSP, the task is to visit every node while covering as little distance as possible.

The difference is that nodes have a particular orientation - and the paths linking them are constrained to pass through the node at this same orientation.  You cannot just do a sudden U-turn at a node - you have to keep going the same direction as when you entered - so there is this additional bit of "state" or "momentum" associated with your direction of travel.  See below picture for a visualization.

Is this mappable to generic TSP in some simple way that I'm not thinking of right now?  Or if not, does this variant have a name of its own?

Edit: It helps to think of the problem as trying to route a train that can never stop through all the cities as efficiently as possible.  If this problem has no name, it could be called Travelling Post Office.

In the above, a solution (possibly not the best) starting/ending at node 0 is 0->1->2->3->0->1->7->6->5->0->1->2->4->6->7->1->0.

Edit - Actually, the above solution does not work if we require that the end orientation matches the start orientation.

答:
TLDR: Here's a link to the code that solves it (or at least the example posted above).

Explaination:

Let's take funky-graph G with n nodes and tri-edges (i, j ,k).

We will represent a set of edges as a set of integers e_{ijk} which  denote how many times tri-edge (i, j, k) has been traversed. For example simple traversal of 3-graph is (0, 1, 2), (1, 2, 0), (2, 0, 1). Here e_{012} = e_{120} = e_{201} = 1 and e_{ijk} = 0 for all other i, j, k triplets.

Now we will cast the problem of finding a traversal of a funky graph  as a mixed linear programming problem.

Let's consider edge (i, j, k). We define transition matrix T_{ijk}
associated with this edge. It will be n x n matrix that is all
zeros, apart from 2 places. T_{ijk}[i, j] = -1  and T_{ijk}[j, k] = -1.

So for example

```<code>           [0 0 0]
T_{120} =  [0 0 -1]
           [1 0 0]
</code>```

(Note that we count numbers from 0, like computer scientists).

Now if for a set of edges we have

```<code>    \sum_{ijk} e_{ijk} T_{ijk} = 0
</code>```

it means that this set of edges represents a cycle.

We can now flatten / reshape these matrices $T_{ijk}$ into vectors.
For example $T_{120}$ becomes

```<code>t_{120} = [0 0 0 0 0 -1 1 0 0]
</code>```

And in this way our constraint from above becomes a matrix constraint

```<code>Te = 0
</code>```

where T is a matrix with n^2 rows and n^3 columns.
Each column has either exactly one 1 at jn + jth place and exactly one -1 at in + kth place if ijk is smooth or is all zeros if tri-edge ijk is not smooth and therefore not traversable.

The second constraint that we want is that visited at least once.
(TODO for tomorrow me to fill in details here).

And that's it! We just plug it into MIP (Mixed Integer Program) solver. Like this one https://developers.google.com/optimization/mip

Title: Travelling Salesman with Momentum?

Body:
TLDR: Here's a link to the code that solves it (or at least the example posted above).

Explaination:

Let's take funky-graph G with n nodes and tri-edges (i, j ,k).

We will represent a set of edges as a set of integers e_{ijk} which  denote how many times tri-edge (i, j, k) has been traversed. For example simple traversal of 3-graph is (0, 1, 2), (1, 2, 0), (2, 0, 1). Here e_{012} = e_{120} = e_{201} = 1 and e_{ijk} = 0 for all other i, j, k triplets.

Now we will cast the problem of finding a traversal of a funky graph  as a mixed linear programming problem.

Let's consider edge (i, j, k). We define transition matrix T_{ijk}
associated with this edge. It will be n x n matrix that is all
zeros, apart from 2 places. T_{ijk}[i, j] = -1  and T_{ijk}[j, k] = -1.

So for example

           [0 0 0]
T_{120} =  [0 0 -1]
           [1 0 0]

(Note that we count numbers from 0, like computer scientists).

Now if for a set of edges we have

    \sum_{ijk} e_{ijk} T_{ijk} = 0

it means that this set of edges represents a cycle.

We can now flatten / reshape these matrices $T_{ijk}$ into vectors.
For example $T_{120}$ becomes

t_{120} = [0 0 0 0 0 -1 1 0 0]

And in this way our constraint from above becomes a matrix constraint

Te = 0

where T is a matrix with n^2 rows and n^3 columns.
Each column has either exactly one 1 at jn + jth place and exactly one -1 at in + kth place if ijk is smooth or is all zeros if tri-edge ijk is not smooth and therefore not traversable.

The second constraint that we want is that visited at least once.
(TODO for tomorrow me to fill in details here).

And that's it! We just plug it into MIP (Mixed Integer Program) solver. Like this one https://developers.google.com/optimization/mip


问:
How to get nested properties of an AD object using Powershell?
I ran the below cmdlet with the intent to get all the properties of the AD user.

```<code>Get-ADUser -Identity targetuser -Properties *
</code>```

But I'm only getting fewer properties, not all of them (refer screenshot).

I'm assuming that the remaining properties are present within the 'PropertyNames' field (highlighted in red).
When I tried to expand it using the '-ExpandProperty' option, it only gave me the names of those nested properties but not their values.

Please advise how to proceed. My objective is to get all the properties and their values.

答: You are almost there.  Use Get-ADUser targetuser -properties * | select * to see all property values.

Body:
I ran the below cmdlet with the intent to get all the properties of the AD user.

Get-ADUser -Identity targetuser -Properties *

But I'm only getting fewer properties, not all of them (refer screenshot).

I'm assuming that the remaining properties are present within the 'PropertyNames' field (highlighted in red).
When I tried to expand it using the '-ExpandProperty' option, it only gave me the names of those nested properties but not their values.

Please advise how to proceed. My objective is to get all the properties and their values.


问:
Interpretation of python split used in code
I am new to Python 3 and trying to understand this line as it relates to the path below</p>
```<code>    path = event['path'].split('/',2)[2]

    I know the split just splits the path with the /.

    what does .split('/',2)[2] imply ?

    path = event['path'].split('/',2)[2]
    destination_url = f"https://bamboo:7676/watch/superDb/v3.0/solution/{path}"
</code>```

答:
The second argument to str.split is maxsplit and is explain by the documentation as:

If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

In the case of .split('/',2), split will split the given string for each / that it finds, but it will stop after at most 2 splits. I.e. there will be at most 3 results at the end.

For example:

```<code>In [1]: example_url = "www.example.com/my/cool/url"

In [2]: example_url.split('/',2)
Out[2]: ['www.example.com', 'my', 'cool/url']
</code>```

Body:
I am new to Python 3 and trying to understand this line as it relates to the path below

    path = event['path'].split('/',2)[2]

    I know the split just splits the path with the /.

    what does .split('/',2)[2] imply ?

    path = event['path'].split('/',2)[2]
    destination_url = f"https://bamboo:7676/watch/superDb/v3.0/solution/{path}"

Body:
The second argument to str.split is maxsplit and is explain by the documentation as:

If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

In the case of .split('/',2), split will split the given string for each / that it finds, but it will stop after at most 2 splits. I.e. there will be at most 3 results at the end.

For example:

In [1]: example_url = "www.example.com/my/cool/url"

In [2]: example_url.split('/',2)
Out[2]: ['www.example.com', 'my', 'cool/url']


问:
ERC721 Minted NFT not showing on Opensea.io testnet
I run my code on rinkeby etherscan network and it works perfectly. But the image and descriptions are not showing on opensea testnet. I run the /validate/ url it shows Valid: "false".

Here is what I found when I force update on opensea, https://testnets-api.opensea.io/api/v1/asset/0x668D179B933af761e4732B084290D32B3235C22b/0/?force_update=true

Here is my code:

```<code>    // SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./ERC2981ContractWideRoyalties.sol";
import "hardhat/console.sol";

contract SmoothApe is ERC721URIStorage, Ownable, ERC2981ContractWideRoyalties {
    using Counters for Counters.Counter;
    using Strings for uint256;

    Counters.Counter private _tokenIdCounter;

    event EmitNFT(address sender, uint256 tokenId);

    uint256 public preSaleTokenPrice = 0.01 ether;
    uint256 public costPrice = 0.02 ether;
    uint256 public maxSupply = 10000;
    uint256 public maxMintNft = 10;

    string public baseURI;
    string public baseExtension = ".json";
    string public notRevealedUri;

    bool public paused = false;
    bool public revealed = true;
    bool public presale = false;

    // set 0x7350243981aB92E2A3646e377EBbFC28e9DE96C1 as payable admn wallet
    address payable public adminWallet = payable(0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2);
    address payable public communityWallet = payable(0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db);
    address payable public t1Wallet = payable(0x78731D3Ca6b7E34aC0F824c42a7cC18A495cabaB);
    address payable public t2Wallet = payable(0x617F2E2fD72FD9D5503197092aC168c91465E7f2);
    address payable public t3Wallet = payable(0x17F6AD8Ef982297579C203069C1DbfFE4348c372);

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    constructor(string memory _name, string memory _symbol,string memory _initBaseURI, string memory _initNotRevealedUri) ERC721(_name, _symbol) {
        setBaseURI(_initBaseURI);
        setNotRevealedUri(_initNotRevealedUri);
    }

    // inherit and override erc165
    function supportsInterface(bytes4 interfaceId) public view virtual override (ERC721, ERC2981Base) returns (bool) {
        return super.supportsInterface(interfaceId);
    }

    // set Royalty value (between 0 and 10000)
    function setRoyalties(address recipient, uint256 value) public onlyOwner {
        _setRoyalties(recipient, value);
    }

    function _baseURI() internal view override returns (string memory) {
        return baseURI;
    }

    function mintApe() public payable {
        uint256 tokenId = _tokenIdCounter.current();
        require(!paused, "Minting is paused");
        require(msg.sender != owner(), "You can't mint ape to admin");
        // require(_mintAmount > 0, "Mint amount must be greater than 0");
        // require(_mintAmount <= maxSupply, "Mint amount must be less than or equal to max supply");
        if(presale == true) {
            preSaleTokenPrice = costPrice;

        }
        require(msg.value >= costPrice, string(abi.encodePacked("Must send at least ", costPrice.toString(), " ether to purchase")));
        require(balanceOf(msg.sender) < maxMintNft, "You can only own 11 ape at a time");
        // require(_mintAmount + balanceOf(msg.sender) <= maxMintNft, "You can only own 10 ape at a time");
        // adminWallet.transfer(msg.value);
        payable(owner()).transfer(msg.value);
        emit EmitNFT(msg.sender, tokenId);
        // for(uint256 i = 1; i <= _mintAmount; i++){
        _safeMint(msg.sender, tokenId);
        // _setTokenURI(tokenId, _baseURI());
        _tokenIdCounter.increment();
        // }
    }

    // admin mint ape to wallet
    function mintApeTo(address _to, uint256 _mintAmount) public onlyOwner {
        require(!paused, "Minting is paused");
        require(_mintAmount > 0, "Mint amount must be greater than 0");
        require(_mintAmount <= maxSupply, "Mint amount must be less than or equal to max supply");
        for(uint256 i = 1; i <= _mintAmount; i++){
            uint256 tokenId = _tokenIdCounter.current();
            _safeMint(_to, tokenId);
            // _setTokenURI(tokenId, _baseURI());
            _tokenIdCounter.increment();
        }
    }

    function getCostPrice() public view virtual returns (uint256) {
        return costPrice;
    }
    //  function to set cost of ape
    function setCost(uint256 _preSaleTokenPrice, uint256 _publicTokenPrice) public onlyOwner {
        preSaleTokenPrice = _preSaleTokenPrice;
        costPrice = _publicTokenPrice;
    }
    // set presale to true
    function setPresale(bool _presale) public onlyOwner {
        presale = _presale;
    }
    function reveal(bool _reveal) public onlyOwner {
        revealed = _reveal;
    }
    // pause function
    function pause() public onlyOwner {
        paused = true;
    }
    // set function for setBaseURI and setNotRevealed function
    function setBaseURI(string memory _newBaseURI) public onlyOwner {
        baseURI = _newBaseURI;
    }

    function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner {
        _setTokenURI(_tokenId, _tokenURI);
    }

    // override tokenURI function
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
        require(tokenId < _tokenIdCounter.current(), "Token ID must be less than the total supply");
        if(!revealed) {
            return notRevealedUri;
        }
        string memory currentBaseURI = _baseURI();
        return bytes(currentBaseURI).length > 0
            ? string(
                abi.encodePacked(
                    currentBaseURI,
                    tokenId.toString(),
                    baseExtension))
                    : "";
    }
}
</code>```

Here is a sample of NFT i mint:
https://testnets.opensea.io/assets/0x668D179B933af761e4732B084290D32B3235C22b/0

my ipfs CID:
ipfs://QmaoMZ19zhpC6T4id6jdBP1Qz5dQSmRZMkQZU7Zt8hyFNQ/

答: as you can see in the right up corner there is a "reload" button, you need to click it to reload the ipfs on opensea</p>

Body:
I run my code on rinkeby etherscan network and it works perfectly. But the image and descriptions are not showing on opensea testnet. I run the /validate/ url it shows Valid: "false".

Here is what I found when I force update on opensea, https://testnets-api.opensea.io/api/v1/asset/0x668D179B933af761e4732B084290D32B3235C22b/0/?force_update=true

Here is my code:

    // SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./ERC2981ContractWideRoyalties.sol";
import "hardhat/console.sol";

contract SmoothApe is ERC721URIStorage, Ownable, ERC2981ContractWideRoyalties {
    using Counters for Counters.Counter;
    using Strings for uint256;

    Counters.Counter private _tokenIdCounter;

    event EmitNFT(address sender, uint256 tokenId);

    uint256 public preSaleTokenPrice = 0.01 ether;
    uint256 public costPrice = 0.02 ether;
    uint256 public maxSupply = 10000;
    uint256 public maxMintNft = 10;

    string public baseURI;
    string public baseExtension = ".json";
    string public notRevealedUri;

    bool public paused = false;
    bool public revealed = true;
    bool public presale = false;

    // set 0x7350243981aB92E2A3646e377EBbFC28e9DE96C1 as payable admn wallet
    address payable public adminWallet = payable(0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2);
    address payable public communityWallet = payable(0x4B20993Bc481177ec7E8f571ceCaE8A9e22C02db);
    address payable public t1Wallet = payable(0x78731D3Ca6b7E34aC0F824c42a7cC18A495cabaB);
    address payable public t2Wallet = payable(0x617F2E2fD72FD9D5503197092aC168c91465E7f2);
    address payable public t3Wallet = payable(0x17F6AD8Ef982297579C203069C1DbfFE4348c372);

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    constructor(string memory _name, string memory _symbol,string memory _initBaseURI, string memory _initNotRevealedUri) ERC721(_name, _symbol) {
        setBaseURI(_initBaseURI);
        setNotRevealedUri(_initNotRevealedUri);
    }

    // inherit and override erc165
    function supportsInterface(bytes4 interfaceId) public view virtual override (ERC721, ERC2981Base) returns (bool) {
        return super.supportsInterface(interfaceId);
    }

    // set Royalty value (between 0 and 10000)
    function setRoyalties(address recipient, uint256 value) public onlyOwner {
        _setRoyalties(recipient, value);
    }

    function _baseURI() internal view override returns (string memory) {
        return baseURI;
    }

    function mintApe() public payable {
        uint256 tokenId = _tokenIdCounter.current();
        require(!paused, "Minting is paused");
        require(msg.sender != owner(), "You can't mint ape to admin");
        // require(_mintAmount > 0, "Mint amount must be greater than 0");
        // require(_mintAmount <= maxSupply, "Mint amount must be less than or equal to max supply");
        if(presale == true) {
            preSaleTokenPrice = costPrice;

        }
        require(msg.value >= costPrice, string(abi.encodePacked("Must send at least ", costPrice.toString(), " ether to purchase")));
        require(balanceOf(msg.sender) < maxMintNft, "You can only own 11 ape at a time");
        // require(_mintAmount + balanceOf(msg.sender) <= maxMintNft, "You can only own 10 ape at a time");
        // adminWallet.transfer(msg.value);
        payable(owner()).transfer(msg.value);
        emit EmitNFT(msg.sender, tokenId);
        // for(uint256 i = 1; i <= _mintAmount; i++){
        _safeMint(msg.sender, tokenId);
        // _setTokenURI(tokenId, _baseURI());
        _tokenIdCounter.increment();
        // }
    }

    // admin mint ape to wallet
    function mintApeTo(address _to, uint256 _mintAmount) public onlyOwner {
        require(!paused, "Minting is paused");
        require(_mintAmount > 0, "Mint amount must be greater than 0");
        require(_mintAmount <= maxSupply, "Mint amount must be less than or equal to max supply");
        for(uint256 i = 1; i <= _mintAmount; i++){
            uint256 tokenId = _tokenIdCounter.current();
            _safeMint(_to, tokenId);
            // _setTokenURI(tokenId, _baseURI());
            _tokenIdCounter.increment();
        }
    }

    function getCostPrice() public view virtual returns (uint256) {
        return costPrice;
    }
    //  function to set cost of ape
    function setCost(uint256 _preSaleTokenPrice, uint256 _publicTokenPrice) public onlyOwner {
        preSaleTokenPrice = _preSaleTokenPrice;
        costPrice = _publicTokenPrice;
    }
    // set presale to true
    function setPresale(bool _presale) public onlyOwner {
        presale = _presale;
    }
    function reveal(bool _reveal) public onlyOwner {
        revealed = _reveal;
    }
    // pause function
    function pause() public onlyOwner {
        paused = true;
    }
    // set function for setBaseURI and setNotRevealed function
    function setBaseURI(string memory _newBaseURI) public onlyOwner {
        baseURI = _newBaseURI;
    }

    function setTokenURI(uint256 _tokenId, string memory _tokenURI) public onlyOwner {
        _setTokenURI(_tokenId, _tokenURI);
    }

    // override tokenURI function
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
        require(tokenId < _tokenIdCounter.current(), "Token ID must be less than the total supply");
        if(!revealed) {
            return notRevealedUri;
        }
        string memory currentBaseURI = _baseURI();
        return bytes(currentBaseURI).length > 0
            ? string(
                abi.encodePacked(
                    currentBaseURI,
                    tokenId.toString(),
                    baseExtension))
                    : "";
    }
}

Here is a sample of NFT i mint:
https://testnets.opensea.io/assets/0x668D179B933af761e4732B084290D32B3235C22b/0

my ipfs CID:
ipfs://QmaoMZ19zhpC6T4id6jdBP1Qz5dQSmRZMkQZU7Zt8hyFNQ/