问:
Connection refused trying to access REST endpoint on BigIP
Attempting to connect to the REST endpoint of my BigIP:

```<code>curl https://10.1.0.69/mgmt/shared/appsvcs/info
curl: (7) Failed to connect to 10.1.0.69 port 443: Connection refused
</code>```

I've seen some posts online stating that this could be due to icrd not being enabled, so to check the status:

```<code>admin@(ip-10-1-0-69)(cfg-sync Standalone)(Active)(/Common)(tmos)# show sys service icrd
Couldn't find service: icrd
</code>```

Next, I've tried enabling:

```<code>admin@(ip-10-1-0-69)(cfg-sync Standalone)(Active)(/Common)(tmos)# modify sys service icrd add
Couldn't find service: icrd
</code>```

My version info:

```<code>admin@(ip-10-1-0-69)(cfg-sync Standalone)(Active)(/Common)(tmos)# show /sys version

Sys::Version
Main Package
  Product     BIG-IP
  Version     15.1.0.2
  Build       0.0.9
  Edition     Point Release 2
  Date        Fri Mar 20 21:06:24 PDT 2020
</code>```

I've also seen some posts stating that I can do the following:

```<code>touch /etc/bigstart/scripts/scim
bigstart add --default icrd
bigstart enable icrd
bigstart start icrd
</code>```

However,

```<code>admin@(ip-10-1-0-69)(cfg-sync Standalone)(Active)(/Common)(tmos)# run /util bash
[admin@ip-10-1-0-69:Active:Standalone] ~ # touch /etc/bigstart/scripts/scim
[admin@ip-10-1-0-69:Active:Standalone] ~ # bigstart add --default icrd
Couldn't find service: icrd
</code>```

Also:

```<code>[admin@ip-10-1-0-69:Active:Standalone] ~ # bigstart status restjavad restnoded
restjavad    run (pid 6549) 49 minutes
restnoded    run (pid 5650) 49 minutes
</code>```

Also, it appears the rest api is running but on port 8100:

```<code>[admin@ip-10-1-0-69:Active:Standalone] curl http://localhost:8100/mgmt/shared/appsvcs/info
{"code":401,"message":"Authorization failed: no user authentication header or token detected. Uri:http://localhost:8100/mgmt/shared/appsvcs/info Referrer:Unknown Sender:Unknown","referer":"Unknown","restOperationId":6611305,"kind":":resterrorresponse"}
</code>```

No ports are bound to 443:

```<code>[admin@ip-10-1-0-69:Active:Standalone] ~ # netstat -nalt | grep 443
tcp        0      0 127.0.0.1:44352         127.0.0.1:6666          ESTABLISHED
tcp        0      0 127.0.0.1:6666          127.0.0.1:44352         ESTABLISHED
tcp6       0      0 :::8443                 :::*                    LISTEN
</code>```

Any ideas?

答:
You don't need to manually start the REST interface anymore (icrd), that was an artifact from pre-11.x versions.

Single NIC installs move the management port to 8443 to keep 443 available for public use on virtual IPs. Firewall ACL's then keep 8443 to mgmt nets. This changes with multi-nic deployments.

For your needs, you can grab a token for use with the API with:

```<code>{
"username": "remote_auth_user",
"password": "remote_auth_password",
"loginProviderName": "tmos"
}
</code>```

at URL: https://:8100/shared/authn/login (for remote API calls where mgmt is hidden)

or URL: https://:8443/shared/authn/login

(I'll reverify this just for my sanity)

Once you get the token, store it and you're off to the races for that session.

For the first URL you were trying to access .../shared/appsvcs/.... do you have the AS3 installed on BIG-IP? If it's not installed that URL isn't available.

Here's the AS3 overview and install instructions just in case: F5 Application Services Extension 3 Documentation

It's different from the standard module-based iControlREST for BIG-IP.

If you're still having issues, lemme know and I'll update this answer.

Body:
Attempting to connect to the REST endpoint of my BigIP:

curl https://10.1.0.69/mgmt/shared/appsvcs/info
curl: (7) Failed to connect to 10.1.0.69 port 443: Connection refused

I've seen some posts online stating that this could be due to icrd not being enabled, so to check the status:

admin@(ip-10-1-0-69)(cfg-sync Standalone)(Active)(/Common)(tmos)# show sys service icrd
Couldn't find service: icrd

Next, I've tried enabling:

admin@(ip-10-1-0-69)(cfg-sync Standalone)(Active)(/Common)(tmos)# modify sys service icrd add
Couldn't find service: icrd

My version info:

admin@(ip-10-1-0-69)(cfg-sync Standalone)(Active)(/Common)(tmos)# show /sys version

Sys::Version
Main Package
  Product     BIG-IP
  Version     15.1.0.2
  Build       0.0.9
  Edition     Point Release 2
  Date        Fri Mar 20 21:06:24 PDT 2020

I've also seen some posts stating that I can do the following:

touch /etc/bigstart/scripts/scim
bigstart add --default icrd
bigstart enable icrd
bigstart start icrd

However,

admin@(ip-10-1-0-69)(cfg-sync Standalone)(Active)(/Common)(tmos)# run /util bash
[admin@ip-10-1-0-69:Active:Standalone] ~ # touch /etc/bigstart/scripts/scim
[admin@ip-10-1-0-69:Active:Standalone] ~ # bigstart add --default icrd
Couldn't find service: icrd

Also:

[admin@ip-10-1-0-69:Active:Standalone] ~ # bigstart status restjavad restnoded
restjavad    run (pid 6549) 49 minutes
restnoded    run (pid 5650) 49 minutes

Also, it appears the rest api is running but on port 8100:

[admin@ip-10-1-0-69:Active:Standalone] curl http://localhost:8100/mgmt/shared/appsvcs/info
{"code":401,"message":"Authorization failed: no user authentication header or token detected. Uri:http://localhost:8100/mgmt/shared/appsvcs/info Referrer:Unknown Sender:Unknown","referer":"Unknown","restOperationId":6611305,"kind":":resterrorresponse"}

No ports are bound to 443:

[admin@ip-10-1-0-69:Active:Standalone] ~ # netstat -nalt | grep 443
tcp        0      0 127.0.0.1:44352         127.0.0.1:6666          ESTABLISHED
tcp        0      0 127.0.0.1:6666          127.0.0.1:44352         ESTABLISHED
tcp6       0      0 :::8443                 :::*                    LISTEN

Any ideas?

Body:
You don't need to manually start the REST interface anymore (icrd), that was an artifact from pre-11.x versions.

Single NIC installs move the management port to 8443 to keep 443 available for public use on virtual IPs. Firewall ACL's then keep 8443 to mgmt nets. This changes with multi-nic deployments.

For your needs, you can grab a token for use with the API with:

{
"username": "remote_auth_user",
"password": "remote_auth_password",
"loginProviderName": "tmos"
}

at URL: https://:8100/shared/authn/login (for remote API calls where mgmt is hidden)

or URL: https://:8443/shared/authn/login

(I'll reverify this just for my sanity)

Once you get the token, store it and you're off to the races for that session.

For the first URL you were trying to access .../shared/appsvcs/.... do you have the AS3 installed on BIG-IP? If it's not installed that URL isn't available.

Here's the AS3 overview and install instructions just in case: F5 Application Services Extension 3 Documentation

It's different from the standard module-based iControlREST for BIG-IP.

If you're still having issues, lemme know and I'll update this answer.


来源: stackexchange

问:
Ignite WAL Archive purge
We do have three nodes Ignite cluster. Out of 3 nodes I can see in one node WAL Archive path is full. Is there any way to clear that? Like currently WAL directory having todays data but WAL Archive directory having last 3 days data/old wal segments. So how to configure for the old archives which are not requried will be removed/purged by Ignite automatcally.</p>

答:
Wal Archive is automatically maintained by Ignite, and recycled on a regular basis per the checkpointing process. https://apacheignite.readme.io/docs/persistence-checkpointing

You can configure the size of the Wal Archive, but not what data is stored there.

see: https://apacheignite.readme.io/docs/write-ahead-log#tuning-wal-archive

ContentLicense: CC BY-SA 4.0

Title: Ignite WAL Archive purge


问:
Send Remote AT Command to Xbee Device in MicroPython
I am trying to create a series ZigBee networks. Each network will be in close proximity to another, as such when all devices are turned on I need them to repeatedly look for their specified network and always join it.

To configure the network I have a coordinator device turned on and it will find up to 32 other devices. Once found I want the coordinator to set the remote devices Names ("NI") and PANID ("ID"). After using xbee.discover() I have a list of devices in my network. However I can not figure out how I can set the remote devices settings using MicroPython.

Can you send AT Commands over MicroPython?

答:
Remote AT commands aren't currently supported via the MicroPython interface.  One would typically set ATNI and the PAN ID via the local serial interface (or BLE) during commissioning of the network.  But I can imagine scenarios where you'd want to interface with the I/O pins of a remote device.

You'll need to put in a feature request to Digi International to include it in an upcoming release.


问:
Shapes of hidden 3d convolutional network layers, how to compute it?
I want to computer the shape of a given hidden layer output of a CNN, so suppose the input shape is (27,27,27,1) ie one image channe, the first convolutional layer is a 16X(3,3,3) kernels, stride is 1 and padding is 0, so the output shape of this layer is : (25,25,25,16), the 16 corresponds to the number of kernels in this layer, so here we have 16 volumes of shape (25,25,25)
after that, we have a second convolutional layer of 32X(3,3,3) kernels, stride is 1 and the padding is 0, so every kernels in this layers should (normally) be applied to the whole input volume of this layers i.e to the (25,25,25,16), but here the output is of shape (23,23,23,32),
what i understand if I base myself on conv2d, is that every kernel is applied on the whole volume in the input, and we stack the result of all kernels to have a deep volume in the output of the layer in question.
so I did not understand how we got this (23,23,23,32), and where is gone the fourth dimension of the output of the first layer (ie 16)??</p>

答:
Considering only the second layer (ignoring bias)

Input shape: (25, 25, 25, 16)

Kernel size: (3, 3, 3)

Output channels: 32

Total number of weights: 16 * 32 * 3 * 3 * 3

Similar to the way that 2D conv layers are really performing multiple 3D convolutions, 3D conv layers are really performing multiple 4D convolution. Specifically, the 3D conv layer in question is performing 32 convolutions, each with a kernel of size (3, 3, 3, 16). The result of one of these convolution operations on the input feature is (23, 23, 23, 1). After all 32 of these operations are completed they are stacked along the channel dimension resulting in a final output shape of (23, 23, 23, 32).


问:
Destroying label frames
I am tinkering around with basic things in Tkinter/python. I am using the LabelFrame that corresponds with several buttons I click. I am struggling with trying to destroy the other frames and only displaying the frame I want visible when clicking on a certain button. When I run this code:

```<code>def lblframe1_view():
    lblframe3.destroy()
    lblframe2.destroy()
    lblframe1 = LabelFrame(root, text="This is Frame One", height=370, width=370, bd=5, relief=FLAT).place(x=215, y=20)
    btn1 = Button(lblframe1, text="this is button one").pack()

def lblframe2_view():
    lblframe1.destroy()
    lblframe3.destroy()
    lblframe2 = LabelFrame(root, text="Frame Two", height=370, width=370, bd=5, relief=FLAT).place(x=215, y=20)
    btn2 = Button(lblframe2, text="this is button two").pack()

def lblframe3_view():
    lblframe1.destroy()
    lblframe2.destroy
    lblframe3 = LabelFrame(root, text="this is frame 3", height=370, width=370, bd=5, relief=FLAT).place(x=215, y=20)

def exit():
    root.destroy()

manbtn1 = Button(root, text="Frame 1", bg="white", height=4, width=25, command=lblframe1).place(x=10, y=20)
mainbtn2 = Button(root, text="Frame 2, bg="white", height=4, width=25, command=lblframe2).place(x=10, y=120)
mainbtn3 = Button(root, text="Frame 3", bg="white", height=4, width=25, command=lblframe3).place(x=10, y=220)
exitbtn = Button(root, text="Exit", bg="white", height=4, width=25, command=exit).place(x=10, y=320)
</code>```

When I run this I get the following error:

NameError: name 'lblframe3' is not defined

I have tried to put the functions after buttons and got the same error. I have done research on this
and haven't been able to figure out why this keeps happening. My hunch is python

答:
I was able to do some research and found the answer I was looking for: I credit sentdex from Youtube for this. He basically stacks the frames on top of one another and a button click actually calls up the frame based on the command. </p>

```<code>from tkinter import *
import tkinter as tk
from tkinter import ttk

LARGE_FONT = ("verdana", 12)

class tool(tk.Tk):

def __init__(self, *args, **kwargs):

    tk.Tk.__init__(self, *args, **kwargs)
    tk.Tk.iconbitmap(self, default="supporticon.ico")

    self.geometry("400x400")
    self.resizable(0,0)
    container = tk.Frame(self)
    container.pack(side="top", fill="both", expand = True)
    container.grid_rowconfigure(0, weight=1)
    container.grid_columnconfigure(0, weight=1)

    self.frames = {}

    for F in (StartPage, PageOne):

        frame = F(container, self)

        self.frames[F] = frame

        frame.grid(row=0, column=0, sticky="nsew")
        frame.config(bg="darkblue")

    self.show_frame(StartPage)

def show_frame(self, cont):

    frame = self.frames[cont]
    frame.tkraise()

class StartPage(tk.Frame):

def __init__(self, parent, controller):

    tk.Frame.__init__(self,parent)

    homeframe = LabelFrame(self, text="testing this out", width=200, height=350)
    homeframe.config(background="darkblue", fg="white")
    homeframe.pack()
    label = Label(homeframe, text="Start Page", font=LARGE_FONT)
    label.config(background="darkblue", fg="white", height=400, width=450)
    label.place(x=10, y=20)

    button1 = ttk.Button(homeframe, text="Vist Page 1",
                        command=lambda: controller.show_frame(PageOne))
    button1.pack()

class PageOne(tk.Frame):
def __init__(self, parent, controller):

    tk.Frame.__init__(self, parent)
    label = tk.Label(self, text="Page One", font=LARGE_FONT)
    label.pack(pady=10, padx=10)

    button1 = tk.Button(self, text="Back to Home",
        command=lambda: controller.show_frame(StartPage))
    button1.pack()

app = tool()
app.resizabe=(0,0)
app.geometry=("450x450")
app.mainloop()
</code>```

Title: Destroying label frames

Body:
I am tinkering around with basic things in Tkinter/python. I am using the LabelFrame that corresponds with several buttons I click. I am struggling with trying to destroy the other frames and only displaying the frame I want visible when clicking on a certain button. When I run this code:

def lblframe1_view():
    lblframe3.destroy()
    lblframe2.destroy()
    lblframe1 = LabelFrame(root, text="This is Frame One", height=370, width=370, bd=5, relief=FLAT).place(x=215, y=20)
    btn1 = Button(lblframe1, text="this is button one").pack()

def lblframe2_view():
    lblframe1.destroy()
    lblframe3.destroy()
    lblframe2 = LabelFrame(root, text="Frame Two", height=370, width=370, bd=5, relief=FLAT).place(x=215, y=20)
    btn2 = Button(lblframe2, text="this is button two").pack()

def lblframe3_view():
    lblframe1.destroy()
    lblframe2.destroy
    lblframe3 = LabelFrame(root, text="this is frame 3", height=370, width=370, bd=5, relief=FLAT).place(x=215, y=20)

def exit():
    root.destroy()

manbtn1 = Button(root, text="Frame 1", bg="white", height=4, width=25, command=lblframe1).place(x=10, y=20)
mainbtn2 = Button(root, text="Frame 2, bg="white", height=4, width=25, command=lblframe2).place(x=10, y=120)
mainbtn3 = Button(root, text="Frame 3", bg="white", height=4, width=25, command=lblframe3).place(x=10, y=220)
exitbtn = Button(root, text="Exit", bg="white", height=4, width=25, command=exit).place(x=10, y=320)

When I run this I get the following error:

NameError: name 'lblframe3' is not defined

I have tried to put the functions after buttons and got the same error. I have done research on this
and haven't been able to figure out why this keeps happening. My hunch is python

Body:
I was able to do some research and found the answer I was looking for: I credit sentdex from Youtube for this. He basically stacks the frames on top of one another and a button click actually calls up the frame based on the command.

from tkinter import *
import tkinter as tk
from tkinter import ttk

LARGE_FONT = ("verdana", 12)

class tool(tk.Tk):

def __init__(self, *args, **kwargs):

    tk.Tk.__init__(self, *args, **kwargs)
    tk.Tk.iconbitmap(self, default="supporticon.ico")

    self.geometry("400x400")
    self.resizable(0,0)
    container = tk.Frame(self)
    container.pack(side="top", fill="both", expand = True)
    container.grid_rowconfigure(0, weight=1)
    container.grid_columnconfigure(0, weight=1)

    self.frames = {}

    for F in (StartPage, PageOne):

        frame = F(container, self)

        self.frames[F] = frame

        frame.grid(row=0, column=0, sticky="nsew")
        frame.config(bg="darkblue")

    self.show_frame(StartPage)

def show_frame(self, cont):

    frame = self.frames[cont]
    frame.tkraise()

class StartPage(tk.Frame):

def __init__(self, parent, controller):

    tk.Frame.__init__(self,parent)

    homeframe = LabelFrame(self, text="testing this out", width=200, height=350)
    homeframe.config(background="darkblue", fg="white")
    homeframe.pack()
    label = Label(homeframe, text="Start Page", font=LARGE_FONT)
    label.config(background="darkblue", fg="white", height=400, width=450)
    label.place(x=10, y=20)

    button1 = ttk.Button(homeframe, text="Vist Page 1",
                        command=lambda: controller.show_frame(PageOne))
    button1.pack()

class PageOne(tk.Frame):
def __init__(self, parent, controller):

    tk.Frame.__init__(self, parent)
    label = tk.Label(self, text="Page One", font=LARGE_FONT)
    label.pack(pady=10, padx=10)

    button1 = tk.Button(self, text="Back to Home",
        command=lambda: controller.show_frame(StartPage))
    button1.pack()

app = tool()
app.resizabe=(0,0)
app.geometry=("450x450")
app.mainloop()


问:
My files get deleted when moving content from the first file ("constituencies") to the second ("temp") and renaming it after
/* I want to transfer the content from the first file ("constituencies") to the second ("temp") and then delete the original ("constituencies") file then rename() ("temp") to ("constituencies") so it can be refreshed with a specific entry/line be deleted from the file by first finding it and then not adding it in the newly generated file ("temp") and then deleting the old ("constituencies") file and renaming ("temp") as the new ("constituencies") but both of my files get deleted in the process, please help */</p>

```<code>void updateOrDelete()
{
        fstream constituencies("constituencies.txt", ios::out | ios::in);
        fstream temp("temp.txt", ios::out | ios::in);
        string deleteline;
        string line;

        cout << "Which constituency do you want to remove? \n";
        cin >> deleteline;

        while (getline(constituencies, line))
        {
                if (line != deleteline)
                {
                        temp << line << endl;
                }
        }

    constituencies.close();
    temp.close();

        remove("constituencies.txt");
        rename("temp.txt", "constituencies.txt");
}
</code>```

答:
This line fails if temp.txt does not exist:

```<code>fstream temp("temp.txt", ios::out | ios::in);
</code>```

but you don't notice that since you don't check if it was successful.

Remedy:

```<code>ifstream constituencies("constituencies.txt");
if(constituencies) {
    // constituencies.txt successfully opened for reading
    ofstream temp("temp.txt");
    if(temp) {
        // temp.txt successfully opened for writing
    } else {
        // fail
    }
} else {
    // fail
}
</code>```

Here's a full version of the function with some added error checking and the user interaction moved out so you'll have to call it with the deleteline you want to remove from the file.

```<code>// returns true if successful and false otherwise
bool updateOrDelete(const std::string& deleteline) {
    static const char* orig = "constituencies.txt";
    static const char* temp1 = "temp1.txt";
    static const char* temp2 = "temp2.txt";

    // make sure you are the only one processing the file
    if(std::rename(orig, temp1) == 0) {
        // open for reading and check if it succeeded
        if(std::ifstream in(temp1); in) {
            // open for writing and check if it succeeded
            if(std::ofstream out(temp2); out) {
                std::string line;
                // do your processing
                while(std::getline(in, line)) {
                    if(line != deleteline) {
                        out << line << '\n';
                    }
                }
                // check if the new file is still in a good state before closing it
                bool success = static_cast<bool>(out);
                out.close();
                in.close();
                if(success) {
                    // all's well - move the processed file into place
                    // and remove the old (renamed) original
                    return std::rename(temp2, orig) == 0 && std::remove(temp1) == 0;
                }
                // processing failed
                // remove the corrupt/truncated file
                std::remove(temp2);
            }
        }
        // try to restore the original file
        std::rename(temp1, orig);
    }
    // if we get here, something failed
    return false;
}
</code>```

Body:
/* I want to transfer the content from the first file ("constituencies") to the second ("temp") and then delete the original ("constituencies") file then rename() ("temp") to ("constituencies") so it can be refreshed with a specific entry/line be deleted from the file by first finding it and then not adding it in the newly generated file ("temp") and then deleting the old ("constituencies") file and renaming ("temp") as the new ("constituencies") but both of my files get deleted in the process, please help */

void updateOrDelete()
{
        fstream constituencies("constituencies.txt", ios::out | ios::in);
        fstream temp("temp.txt", ios::out | ios::in);
        string deleteline;
        string line;

        cout << "Which constituency do you want to remove? \n";
        cin >> deleteline;

        while (getline(constituencies, line))
        {
                if (line != deleteline)
                {
                        temp << line << endl;
                }
        }

    constituencies.close();
    temp.close();

        remove("constituencies.txt");
        rename("temp.txt", "constituencies.txt");
}

Body:
This line fails if temp.txt does not exist:

fstream temp("temp.txt", ios::out | ios::in);

but you don't notice that since you don't check if it was successful.

Remedy:

ifstream constituencies("constituencies.txt");
if(constituencies) {
    // constituencies.txt successfully opened for reading
    ofstream temp("temp.txt");
    if(temp) {
        // temp.txt successfully opened for writing
    } else {
        // fail
    }
} else {
    // fail
}

Here's a full version of the function with some added error checking and the user interaction moved out so you'll have to call it with the deleteline you want to remove from the file.

// returns true if successful and false otherwise
bool updateOrDelete(const std::string& deleteline) {
    static const char* orig = "constituencies.txt";
    static const char* temp1 = "temp1.txt";
    static const char* temp2 = "temp2.txt";

    // make sure you are the only one processing the file
    if(std::rename(orig, temp1) == 0) {
        // open for reading and check if it succeeded
        if(std::ifstream in(temp1); in) {
            // open for writing and check if it succeeded
            if(std::ofstream out(temp2); out) {
                std::string line;
                // do your processing
                while(std::getline(in, line)) {
                    if(line != deleteline) {
                        out << line << '\n';
                    }
                }
                // check if the new file is still in a good state before closing it
                bool success = static_cast<bool>(out);
                out.close();
                in.close();
                if(success) {
                    // all's well - move the processed file into place
                    // and remove the old (renamed) original
                    return std::rename(temp2, orig) == 0 && std::remove(temp1) == 0;
                }
                // processing failed
                // remove the corrupt/truncated file
                std::remove(temp2);
            }
        }
        // try to restore the original file
        std::rename(temp1, orig);
    }
    // if we get here, something failed
    return false;
}


问:
Why doesn't C++20 use `requires` to restrict the T for atomic<T>?
A generic std::atomic<T> is required to have a T that is Copy Constructible and Copy Assignable:

[atomics.types.generic]/1

The program is ill-formed if any of

(1.1) is_trivially_copyable_v<T>,

(1.2) is_copy_constructible_v<T>,

(1.3) is_move_constructible_v<T>,

(1.4) is_copy_assignable_v<T>,

or (1.5) is_move_assignable_v<T>

is false.

The above is not new to C++20. Compilers may use static_assert to issue an error for a non-conforming T.

However, C++20 could use formal constraints with the requires syntax to formally require the above as part of the type, e.g. something like:

```<code>template< class T > requires
    std::is_trivially_copyable_v<T> &&
    std::is_copy_constructible_v<T> &&
    std::is_move_constructible_v<T> &&
    std::is_copy_assignable_v<T> &&
    std::is_move_assignable_v<T>
struct atomic { ... };
</code>```

Is there a reason why C++20 refrained from using formal constraints for this purpose?

EDIT: @T.C. points out correctly, in an answer below:

For std::atomic in particular, constraining the primary template is
simply not an option, given the atomic<shared_ptr<T>> and
atomic<weak_ptr<T>> specializations that were added in C++20.

with an option suggesting that:

Perhaps you can do something fancier (like an undefined and
unconstrained primary template plus a constrained partial
specialization), but it adds very little value.

Well, there is another option, without the need for an undefined and
unconstrained primary template, which is still a bit complex and reduces the value and fun in going with concepts for this usage, but probably better than an undefined base template:

```<code>template< class T > requires
    std::is_trivially_copyable_v<T> &&
    std::is_copy_constructible_v<T> &&
    std::is_move_constructible_v<T> &&
    std::is_copy_assignable_v<T> &&
    std::is_move_assignable_v<T>
    || std::same_as<T, std::shared_ptr<typename T::element_type>>
    || std::same_as<T, std::weak_ptr<typename T::element_type>>
struct atomic { ... };

template< class T >
struct atomic<std::shared_ptr<T>> { ... };

template< class T >
struct atomic<std::weak_ptr<T>> { ... };

// types of all other specializations are Copy Constructible and Copy Assignable
</code>```

Code: https://godbolt.org/z/JaCu78

答:
For std::atomic in particular, constraining the primary template is simply not an option, given the atomic<shared_ptr<T>> and atomic<weak_ptr<T>> specializations that were added in C++20.

Perhaps you can do something fancier (like an undefined and unconstrained primary template plus a constrained partial specialization), but it adds very little value.

Body:
A generic std::atomic<T> is required to have a T that is Copy Constructible and Copy Assignable:

[atomics.types.generic]/1

The program is ill-formed if any of

(1.1) is_trivially_copyable_v<T>,

(1.2) is_copy_constructible_v<T>,

(1.3) is_move_constructible_v<T>,

(1.4) is_copy_assignable_v<T>,

or (1.5) is_move_assignable_v<T>

is false.

The above is not new to C++20. Compilers may use static_assert to issue an error for a non-conforming T.

However, C++20 could use formal constraints with the requires syntax to formally require the above as part of the type, e.g. something like:

template< class T > requires
    std::is_trivially_copyable_v<T> &&
    std::is_copy_constructible_v<T> &&
    std::is_move_constructible_v<T> &&
    std::is_copy_assignable_v<T> &&
    std::is_move_assignable_v<T>
struct atomic { ... };

Is there a reason why C++20 refrained from using formal constraints for this purpose?

EDIT: @T.C. points out correctly, in an answer below:

For std::atomic in particular, constraining the primary template is
simply not an option, given the atomic<shared_ptr<T>> and
atomic<weak_ptr<T>> specializations that were added in C++20.

with an option suggesting that:

Perhaps you can do something fancier (like an undefined and
unconstrained primary template plus a constrained partial
specialization), but it adds very little value.

Well, there is another option, without the need for an undefined and
unconstrained primary template, which is still a bit complex and reduces the value and fun in going with concepts for this usage, but probably better than an undefined base template:

template< class T > requires
    std::is_trivially_copyable_v<T> &&
    std::is_copy_constructible_v<T> &&
    std::is_move_constructible_v<T> &&
    std::is_copy_assignable_v<T> &&
    std::is_move_assignable_v<T>
    || std::same_as<T, std::shared_ptr<typename T::element_type>>
    || std::same_as<T, std::weak_ptr<typename T::element_type>>
struct atomic { ... };

template< class T >
struct atomic<std::shared_ptr<T>> { ... };

template< class T >
struct atomic<std::weak_ptr<T>> { ... };

// types of all other specializations are Copy Constructible and Copy Assignable

Code: https://godbolt.org/z/JaCu78


问:
Unable to execute loop in react
I am trying to run a react loop to display time, and am running into an issue, please assist.
Below is my code

```<code>    populateDefaultTime() {
        alert("inside default time");
        for (let i = 1; i < 24; i++) {
            this.times.push(i);
        }
    }

    componentDidMount() {
         this.populateDefaultTime();
    }
</code>```

Below is my error

```<code>populateDefaultTime() {
  35 |     alert("inside default time");
  36 |     for (let i = 1; i < 24; i++) {
> 37 |         this.times.push(i);
     | ^  38 |     }
  39 |
  40 | }
</code>```

答:
```<code>Loop can't be used like that. You have to make use of state and the rest of React patterns and principles.
</code>```

const {
  useEffect,
  useState
} = React;
const lp = (n) => n <= 9 ? `0${n}` : n;
const Clock = () => {
  const [time, setTime] = useState(new Date());
  const hours = lp(time.getHours());
  const minutes = lp(time.getMinutes());
  const seconds = lp(time.getSeconds());

  useEffect(() => {
    const interval = setInterval(() => setTime(new Date()), 1000);
    return () => {
      clearInterval(interval);
    }
  }, []);

  return
 {
    hours
  }: {
    minutes
  }: {
    seconds
  }

}

ReactDOM.render(React.createElement(Clock, {}, null), document.body);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.profiling.min.js"></script></code>```

Title: Unable to execute loop in react

Body:
I am trying to run a react loop to display time, and am running into an issue, please assist.
Below is my code

    populateDefaultTime() {
        alert("inside default time");
        for (let i = 1; i < 24; i++) {
            this.times.push(i);
        }
    }

    componentDidMount() {
         this.populateDefaultTime();
    }

Below is my error

populateDefaultTime() {
  35 |     alert("inside default time");
  36 |     for (let i = 1; i < 24; i++) {
> 37 |         this.times.push(i);
     | ^  38 |     }
  39 |
  40 | }

Body:
Loop can't be used like that. You have to make use of state and the rest of React patterns and principles.

const {
  useEffect,
  useState
} = React;
const lp = (n) => n <= 9 ? `0${n}` : n;
const Clock = () => {
  const [time, setTime] = useState(new Date());
  const hours = lp(time.getHours());
  const minutes = lp(time.getMinutes());
  const seconds = lp(time.getSeconds());

  useEffect(() => {
    const interval = setInterval(() => setTime(new Date()), 1000);
    return () => {
      clearInterval(interval);
    }
  }, []);

  return <div > {
    hours
  }: {
    minutes
  }: {
    seconds
  } < /div>
}

ReactDOM.render(React.createElement(Clock, {}, null), document.body);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.profiling.min.js"></script>


问:
Need help deleting/removing kivy widgets
The code below makes an app with a big button which makes and appends individual "rows" of widgets (really just 3 labels and a button in a  single gridlayout, representing a single widget)

to the bottom of a scrollview.

I want some way to press the 'delete this' button in a row to delete that particular row.

I imagine I'd need some way to differentiate between these generated rows somehow but I haven't gotten that figured out yet either.
I'd be extatic if someone had an elegant solution for this, as I've been stuck here for quite some time.

screenshot of dummy program

```<code>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
from kivy.uix.button import Button
from kivy.uix.label import Label

kv = '''
<Label>:
    font_size: 35

<delete_btn>:
    background_color: 1, 0, 0, 1
    size_hint_y: None
    text: 'Delete this'
    font_size: 25

<RootWidget>:
    orientation: 'vertical'

    Button:
        size_hint: 1, .25
        font_size: 50
        pos_hint: {'x': 0, 'top': 1}
        text: 'append row'
        on_press: rootgrid.append_row()

    ScrollviewLayout:
        scroll_type: ['bars', 'content']
        bar_width: 10
        pos_hint: {'x': 0, 'y': .2}

        RootGridLayout:
            id: rootgrid
            cols: 1
            size_hint_y: None
            height: self.minimum_height

'''

class GridRow(GridLayout):
    def __init__(self, **kwargs):
        super(GridRow, self).__init__(**kwargs)
        self.size_hint_y = None

        self.cols = 4
        self.add_widget(delete_btn())
        self.add_widget(Label(text='00:00:00', size_hint_y=None))
        self.add_widget(Label(text='00:00:00', size_hint_y=None))
        self.add_widget(Label(text='00:00:00', size_hint_y=None))

class RootGridLayout(GridLayout):
    def append_row(self):
        self.add_widget(GridRow())

class delete_btn(Button):
    pass

class ScrollviewLayout(ScrollView):
    pass

class RootWidget(BoxLayout):
    pass

class remtimeApp(App):
    def build(self):
        root = RootWidget()
        return root

if __name__ == '__main__':
    Builder.load_string(kv)
    remtimeApp().run()

</code>```

答:
You can pass the information needed for the deletion when you create the GridRow and the delete_btn. Here are the affected classes with the changes:

```<code>class GridRow(GridLayout):
    def __init__(self, **kwargs):
        self.container = kwargs.pop('container', None)
        super(GridRow, self).__init__(**kwargs)
        self.size_hint_y = None

        self.cols = 4
        self.add_widget(delete_btn(row=self, container=self.container))
        self.add_widget(Label(text='00:00:00', size_hint_y=None))
        self.add_widget(Label(text='00:00:00', size_hint_y=None))
        self.add_widget(Label(text='00:00:00', size_hint_y=None))

class RootGridLayout(GridLayout):
    def append_row(self):
        self.add_widget(GridRow(container=self))

class delete_btn(Button):
    def __init__(self, **kwargs):
        self.container = kwargs.pop('container', None)
        self.row = kwargs.pop('row', None)
        super(delete_btn, self).__init__(**kwargs)

    def on_release(self):
        self.container.remove_widget(self.row)
</code>```

So the GridRow __init__() method now takes a keyword parameter of container, which should be the RootGridLayout that contains the GridRows. And the delete_btn __init__() method takes two keyword arguments, container (just passed along from the GridRow) and row, which is the GridRow instance containing the delete_btn. That provide the delete_btn with all the information necessary to remove its GridRow from the RootGridLayout. Now the on_release() method of the delete_btn just does the remove_widget().

Body:
The code below makes an app with a big button which makes and appends individual "rows" of widgets (really just 3 labels and a button in a  single gridlayout, representing a single widget)

to the bottom of a scrollview.

I want some way to press the 'delete this' button in a row to delete that particular row.

I imagine I'd need some way to differentiate between these generated rows somehow but I haven't gotten that figured out yet either.
I'd be extatic if someone had an elegant solution for this, as I've been stuck here for quite some time.

screenshot of dummy program

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView
from kivy.uix.button import Button
from kivy.uix.label import Label

kv = '''
:
    font_size: 35

<delete_btn>:
    background_color: 1, 0, 0, 1
    size_hint_y: None
    text: 'Delete this'
    font_size: 25

<RootWidget>:
    orientation: 'vertical'

    Button:
        size_hint: 1, .25
        font_size: 50
        pos_hint: {'x': 0, 'top': 1}
        text: 'append row'
        on_press: rootgrid.append_row()

    ScrollviewLayout:
        scroll_type: ['bars', 'content']
        bar_width: 10
        pos_hint: {'x': 0, 'y': .2}

        RootGridLayout:
            id: rootgrid
            cols: 1
            size_hint_y: None
            height: self.minimum_height

'''

class GridRow(GridLayout):
    def __init__(self, **kwargs):
        super(GridRow, self).__init__(**kwargs)
        self.size_hint_y = None

        self.cols = 4
        self.add_widget(delete_btn())
        self.add_widget(Label(text='00:00:00', size_hint_y=None))
        self.add_widget(Label(text='00:00:00', size_hint_y=None))
        self.add_widget(Label(text='00:00:00', size_hint_y=None))

class RootGridLayout(GridLayout):
    def append_row(self):
        self.add_widget(GridRow())

class delete_btn(Button):
    pass

class ScrollviewLayout(ScrollView):
    pass

class RootWidget(BoxLayout):
    pass

class remtimeApp(App):
    def build(self):
        root = RootWidget()
        return root

if __name__ == '__main__':
    Builder.load_string(kv)
    remtimeApp().run()

Body:
You can pass the information needed for the deletion when you create the GridRow and the delete_btn. Here are the affected classes with the changes:

class GridRow(GridLayout):
    def __init__(self, **kwargs):
        self.container = kwargs.pop('container', None)
        super(GridRow, self).__init__(**kwargs)
        self.size_hint_y = None

        self.cols = 4
        self.add_widget(delete_btn(row=self, container=self.container))
        self.add_widget(Label(text='00:00:00', size_hint_y=None))
        self.add_widget(Label(text='00:00:00', size_hint_y=None))
        self.add_widget(Label(text='00:00:00', size_hint_y=None))

class RootGridLayout(GridLayout):
    def append_row(self):
        self.add_widget(GridRow(container=self))

class delete_btn(Button):
    def __init__(self, **kwargs):
        self.container = kwargs.pop('container', None)
        self.row = kwargs.pop('row', None)
        super(delete_btn, self).__init__(**kwargs)

    def on_release(self):
        self.container.remove_widget(self.row)

So the GridRow __init__() method now takes a keyword parameter of container, which should be the RootGridLayout that contains the GridRows. And the delete_btn __init__() method takes two keyword arguments, container (just passed along from the GridRow) and row, which is the GridRow instance containing the delete_btn. That provide the delete_btn with all the information necessary to remove its GridRow from the RootGridLayout. Now the on_release() method of the delete_btn just does the remove_widget().


问:
Uncaught TypeError: Cannot read property 'innerHTML' of null at text inside this blog website I'm trying to write

var x = 0;

function text() {
  var blogtext = document.getElementById("Textarea").value;
  var y = "p" + String(x);
  console.log(typeof y);
  //problem
  document.createElement("p").id = y;
  //
  document.getElementById(y).innerHTML = blogtext;
  //document.write("
"+blogtext+"
");
  x = x + 1;
}
```

When I run this code inside an HTML file the error: Uncaught TypeError occurs, the code is supposed to create a new paragraph tag whose content is the text inputted by the user inside the text area and each paragraph would have a different id as x increases.
Sorry, I'm new to coding this is one of my school's projects.

答:
You made a few omissions in your code and just a bit of cleanup solves your problem

var x = 0;

function text() {
  var blogtext = document.getElementById("Textarea").value;
  var y = "p" + String(x);
  console.log(typeof y);
  //solution
 var p = document.createElement("p")
 document.body.append(p)
 p.setAttribute("id",y)
  //
 p.innerHTML = blogtext;
  //document.write("
"+blogtext+"
");
  x = x + 1;
  console.log()
}

//text()```
<pre class="snippet-code-html lang-html prettyprint-override"><code><textarea id="Textarea" onChange=text()></textarea> <br></code>```

Body:
var x = 0;

function text() {
  var blogtext = document.getElementById("Textarea").value;
  var y = "p" + String(x);
  console.log(typeof y);
  //problem
  document.createElement("p").id = y;
  //
  document.getElementById(y).innerHTML = blogtext;
  //document.write("
"+blogtext+"
");
  x = x + 1;
}

When I run this code inside an HTML file the error: Uncaught TypeError occurs, the code is supposed to create a new paragraph tag whose content is the text inputted by the user inside the text area and each paragraph would have a different id as x increases.
Sorry, I'm new to coding this is one of my school's projects.

Body:
You made a few omissions in your code and just a bit of cleanup solves your problem

var x = 0;

function text() {
  var blogtext = document.getElementById("Textarea").value;
  var y = "p" + String(x);
  console.log(typeof y);
  //solution
 var p = document.createElement("p")
 document.body.append(p)
 p.setAttribute("id",y)
  //
 p.innerHTML = blogtext;
  //document.write("<p>"+blogtext+"<p>");
  x = x + 1;
  console.log()
}

//text()

<textarea id="Textarea" onChange=text()></textarea> <br>


答:
You can use cross apply to unpivot this dataset:

```<code>select
    s.from_miles,
    s.to_miles,
    x.*
from source s
cross apply (values
    (1000, 1099, s.[1000_to_1099]),
    (1100, 1199, s.[1100_to_1199]),
    (1200, 1299, s.[1200_to_1299]),
    (1300, 1399, s.[1300_to_1399]),
    (1400, 1499, s.[1400_to_1499])
) as x(weight_from, weigh_to, rate)
</code>```

You can easily turn this to an insert statement:

```<code>insert into newtable (from_moles, to_moles, weight_from, weight_to, rate)
select ... -- above query
</code>```

Title: INSERT INTO target table new entry for each column within a row of source table

Body:
I'm sorry if the title is confusing. I have a very large source table that is structured somewhat like this

From Mile  | To Mile |
           |         |From Weight| 1000       | 1100 | 1200 | 1300... | 22500 | 23000
           |         |To Weight  | 1099       | 1199 | 1299 | 1499... | 22999 | 23499
==========================================================================
     1     |   20    |           | 1500       | 1505 | 1489 | 1854... | 3400  | 2990
------------------------------------------------------------------------
     21    |   40    |           | 1400       | 1705 | 491  | 5581... | 1600  | 2989
------------------------------------------------------------------------
     41    |   60    |           | 1800       | 1635 | 1982 | 1888... | 3200  | 3480
------------------------------------------------------------------------

Where one can pick a certain milage, e.g. 23, and a certain weight, e.g. 1250, and get a "rate" - in this case, 491.

From Mile  | To Mile |
           |         |From Weight|            |      | 1200 |         |       |
           |         |To Weight  |            |      | 1299 |         |       |
==========================================================================
           |         |           |            |      |      |     ... |       |
------------------------------------------------------------------------
     21    |   40    |           |            |      | 491  |     ... |       |
------------------------------------------------------------------------
           |         |           |            |      |      |     ... |       |
------------------------------------------------------------------------

I would want to insert each rate with their corresponding weight and mile ranges.

Id   | Mile_To | Mile_From | Weight_To | Weight_From | Rate
===========================================================
0    | 1       | 20        | 1000      | 1099        | 1500
-----------------------------------------------------------
1    | 1       | 20        | 1100      | 1199        | 1505
-----------------------------------------------------------
2    | 1       | 20        | 1200      | 1299        | 1389
-----------------------------------------------------------
3    | 1       | 20        | 1300      | 1499        | 1854
-----------------------------------------------------------
...
-----------------------------------------------------------
40   | 1       | 20        | 22500     | 22999       | 3400
-----------------------------------------------------------
41   | 1       | 20        | 23000     | 23499       | 2990
-----------------------------------------------------------
42   | 21      | 40        | 1000      | 1199        | 1400

What is the best way to step through the source table and insert the data as formatted above? There around hundreds of rows and columns, so naming each one would be similar to manually entering the data.

Here is a SQLFiddle with an example of the source table: http://sqlfiddle.com/#!18/48777a/1

Body:
You can use cross apply to unpivot this dataset:

select
    s.from_miles,
    s.to_miles,
    x.*
from source s
cross apply (values
    (1000, 1099, s.[1000_to_1099]),
    (1100, 1199, s.[1100_to_1199]),
    (1200, 1299, s.[1200_to_1299]),
    (1300, 1399, s.[1300_to_1399]),
    (1400, 1499, s.[1400_to_1499])
) as x(weight_from, weigh_to, rate)

You can easily turn this to an insert statement:

insert into newtable (from_moles, to_moles, weight_from, weight_to, rate)
select ... -- above query


问:
C++: get time zone deviation
So I want to creata a time stamp (as a string) with the format HH:MM:SS in C++. I use std::chrono to get a unix time stamp and then calculate the hours, minutes and seconds.

// Get unix time stamp in seconds.
const auto unix_time_stamp = std::chrono::system_clock::now();
long long seconds_since_epoch = std::chrono::duration_cast<std::chrono::seconds>(unix_time_stamp.time_since_epoch()).count();

// Calculate current time (hours, minutes, seconds).
uint8_t hours = (seconds_since_epoch % 86400) / 3600;
uint8_t minutes = (seconds_since_epoch % 3600) / 60;
uint8_t seconds = (seconds_since_epoch % 60);

// Create strings for hours, minutes, seconds.
std::string hours_string = std::to_string(hours);
std::string minutes_string = std::to_string(minutes);
std::string seconds_string = std::to_string(seconds);

// Check if the number is only one digit. If it is, add a 0 in the beginning (5:3:9 --> 05:03:09).
if(hours_string.size() == 1)
{
  hours_string = "0" + hours_string;
}
if(minutes_string.size() == 1)
{
  minutes_string = "0" + minutes_string;
}
if(seconds_string.size() == 1)
{
  seconds_string = "0" + seconds_string;
}

// Append to a final string.
std::string time_stamp = hours_string + ":" + minutes_string + ":" + seconds_string;
```

This is all working fine and great but there is one big problem: time zones.
With this way, I'm only calculating the time stamp for GMT. Is there any easy, fast and, most importantly, portable way to get the "offset" in seconds or minutes or hours for your system's time zone? By "portable" I mean platform-independent.

Please note: I know you can do all of this more easily with std::strftime and so on, but I really want to implement this by myself.

答:
Some implementations of std::tm will contain a member that has the local offset as a member.  ...  But it isn't portable.

One trick is to take your seconds_since_epoch, and either assign it to a std::time_t, or just make its type std::time_t in the first place instead of long long.

... Oh, wait that isn't quite portable.  Some platforms still use a 32 bit time_t.  But assuming a 64 bit time_t ...

Then use localtime to get a std::tm:

```<code>std::tm tm = *localtime(&seconds_since_epoch);
</code>```

This isn't officially portable because system_clock and time_t aren't guaranteed to have the same epoch.  But in practice they do.

Now take the {year, month, day, hour, minute, second} fields out of the tm and compute a "local epoch".  The hard part of this computation is converting the {year, month, day} part into a count of days.  You can use days_from_civil from here to do that computation efficiently.  Be sure to take the weird offsets into account for tm_year and tm_mon when doing this.

After you get this then subtract seconds_since_epoch from it:

```<code> auto offset = local_epoch - seconds_since_epoch;
</code>```

This is your signed UTC offset in seconds.  Positive is east of the prime meridian.

In C++20 this simplifies down to:

```<code>auto offset = std::chrono::current_zone()->get_info(system_clock::now()).offset;
</code>```

and offset will have type std::chrono::seconds.

You can get a free, open-source preview of this here.  It does require some installation.

Title: C++: get time zone deviation

Body:
So I want to creata a time stamp (as a string) with the format HH:MM:SS in C++. I use std::chrono to get a unix time stamp and then calculate the hours, minutes and seconds.

// Get unix time stamp in seconds.
const auto unix_time_stamp = std::chrono::system_clock::now();
long long seconds_since_epoch = std::chrono::duration_cast<std::chrono::seconds>(unix_time_stamp.time_since_epoch()).count();

// Calculate current time (hours, minutes, seconds).
uint8_t hours = (seconds_since_epoch % 86400) / 3600;
uint8_t minutes = (seconds_since_epoch % 3600) / 60;
uint8_t seconds = (seconds_since_epoch % 60);

// Create strings for hours, minutes, seconds.
std::string hours_string = std::to_string(hours);
std::string minutes_string = std::to_string(minutes);
std::string seconds_string = std::to_string(seconds);

// Check if the number is only one digit. If it is, add a 0 in the beginning (5:3:9 --> 05:03:09).
if(hours_string.size() == 1)
{
  hours_string = "0" + hours_string;
}
if(minutes_string.size() == 1)
{
  minutes_string = "0" + minutes_string;
}
if(seconds_string.size() == 1)
{
  seconds_string = "0" + seconds_string;
}

// Append to a final string.
std::string time_stamp = hours_string + ":" + minutes_string + ":" + seconds_string;

This is all working fine and great but there is one big problem: time zones.
With this way, I'm only calculating the time stamp for GMT. Is there any easy, fast and, most importantly, portable way to get the "offset" in seconds or minutes or hours for your system's time zone? By "portable" I mean platform-independent.

Please note: I know you can do all of this more easily with std::strftime and so on, but I really want to implement this by myself.

Body:
Some implementations of std::tm will contain a member that has the local offset as a member.  ...  But it isn't portable.

One trick is to take your seconds_since_epoch, and either assign it to a std::time_t, or just make its type std::time_t in the first place instead of long long.

... Oh, wait that isn't quite portable.  Some platforms still use a 32 bit time_t.  But assuming a 64 bit time_t ...

Then use localtime to get a std::tm:

std::tm tm = *localtime(&seconds_since_epoch);

This isn't officially portable because system_clock and time_t aren't guaranteed to have the same epoch.  But in practice they do.

Now take the {year, month, day, hour, minute, second} fields out of the tm and compute a "local epoch".  The hard part of this computation is converting the {year, month, day} part into a count of days.  You can use days_from_civil from here to do that computation efficiently.  Be sure to take the weird offsets into account for tm_year and tm_mon when doing this.

After you get this then subtract seconds_since_epoch from it:

 auto offset = local_epoch - seconds_since_epoch;

This is your signed UTC offset in seconds.  Positive is east of the prime meridian.

In C++20 this simplifies down to:

auto offset = std::chrono::current_zone()->get_info(system_clock::now()).offset;

and offset will have type std::chrono::seconds.

You can get a free, open-source preview of this here.  It does require some installation.


问:
GridSearchCV returning results not in the param grid
I have defined my parameter grid and gridsearch here. The weird thing is, the output does not include any of the parameter options I set. E.g. max features has been set to auto.

Have I done something wrong?

```<code>from sklearn.grid_search import GridSearchCV

param_grid = {
'bootstrap': [True],
'max_depth': [90, 100, 110],
'max_features': [2, 3, 10, 20],
'min_samples_leaf': [3, 4, 5, 10],
'min_samples_split': [2, 5, 8, 10, 12],
'n_estimators': [10, 20, 50, 60, 70]
}

model = RandomForestClassifier()

# Instantiate the grid search model
best = GridSearchCV(estimator = model, param_grid = param_grid,
cv = 3, n_jobs = -1, verbose = 2)

best.fit(x, y.ravel())
</code>```

答:
You have to take the return value of the best.fit() function.

fitted_grid = best.fit(x, y.ravel())
best_classifier = fitted_grid.best_estimator_
best_parameters = fitted_grid.best_params_
```

I did not see that part in your code snippet, so maybe that's where you were missing something ?

Body:
I have defined my parameter grid and gridsearch here. The weird thing is, the output does not include any of the parameter options I set. E.g. max features has been set to auto.

Have I done something wrong?

from sklearn.grid_search import GridSearchCV

param_grid = {
'bootstrap': [True],
'max_depth': [90, 100, 110],
'max_features': [2, 3, 10, 20],
'min_samples_leaf': [3, 4, 5, 10],
'min_samples_split': [2, 5, 8, 10, 12],
'n_estimators': [10, 20, 50, 60, 70]
}

model = RandomForestClassifier()

# Instantiate the grid search model
best = GridSearchCV(estimator = model, param_grid = param_grid,
cv = 3, n_jobs = -1, verbose = 2)

best.fit(x, y.ravel())

Body:
You have to take the return value of the best.fit() function.

fitted_grid = best.fit(x, y.ravel())
best_classifier = fitted_grid.best_estimator_
best_parameters = fitted_grid.best_params_

I did not see that part in your code snippet, so maybe that's where you were missing something ?


问:
how to replace gridStore to gridFSBucket?
I have this error message:

```<code>(node:11976) DeprecationWarning: GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead
</code>```

and sometimes I have trouble viewing the picture , I guess because of that, due to poor documentation I have no idea how to switch my code to GridFSBucket, this is it:

```<code>conn.once("open", () => {
  // Init stream
  gfs = Grid(conn.db, mongoose.mongo);
  //gfs = new mongoose.mongo.GridFSBucket(conn.db);
  gfs.collection("user_images");
});

var storageImage = new GridFsStorage({
  url: dbURI,
  options: { useNewUrlParser: true, useUnifiedTopology: true },
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(16, (err, buf) => {
        if (err) {
          return reject(err);
        }
        const filename = buf.toString("hex") + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: "user_images"
        };
        resolve(fileInfo);
      });
    });
  }
});
const uploadImage = multer({ storage: storageImage });

    const uploadImage = multer({ storage: storageImage });
router.get("/image/:filename", (req, res) => {
  gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
    if (!file || file.length === 0) {
      return res.status(404).json({
        err: "No file exists"
      });
    }

    if (file.contentType === "image/jpeg" || file.contentType === "image/png") {
      const readstream = gfs.createReadStream(file.filename);
      //const readstream = gridFSBucket.openUploadStream(file.filename);
      readstream.pipe(res);
    } else {
      res.status(404).json({
        err: "Not an image"
      });
    }
  });
});
</code>```

I would really appreciate the help, what do I need to change here to make it work with GridFsBucket, huge thanks in advance!

答:
I followed this tutorial to create this recipe. Tutorial is awesome it explains all the steps quite nicely. Complete code example can be found here.

Html form example:

```<code><form action="http://localhost:4000/upload" method="post" enctype="multipart/form-data">
      <input type="file"  name='image' />
      <button type="submit" >Submit</button>
</form>
</code>```

Controller recipe to upload image to mongodb:

```<code>const path = require('path');
const crypto = require('crypto');
const mongoose = require('mongoose');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');

const mongodbURL="mongodb+srv://<user>:<pass>@cluster.mongodb.net/<databaseName>"
const connection = mongoose.createConnection(mongoURI);

// Init gfs
let gfs;
const image_bucket_name = "user_images"

connection.once('open', () => {
    // Init stream
    gfs = Grid(connection.db, mongoose.mongo);
    gfs.collection(image_bucket_name);
})

// Create storage engine
const storage = new GridFsStorage({
    url: mongoURI,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (error, buffer) => {
                if (error) {
                    return reject(error);
                }
                const filename = buffer.toString('hex') + path.extname(file.originalname);
                const fileinfo = {
                    filename: filename,
                    bucketName: image_bucket_name
                };
                resolve(fileinfo);
            })
        });
    }
});

const upload = multer({ storage });
app.post('/upload', upload.single('image'), async (req, res) => {
    console.log("uploaded image: "+req.file.
});
</code>```

Body:
I have this error message:

(node:11976) DeprecationWarning: GridStore is deprecated, and will be removed in a future version. Please use GridFSBucket instead

and sometimes I have trouble viewing the picture , I guess because of that, due to poor documentation I have no idea how to switch my code to GridFSBucket, this is it:

conn.once("open", () => {
  // Init stream
  gfs = Grid(conn.db, mongoose.mongo);
  //gfs = new mongoose.mongo.GridFSBucket(conn.db);
  gfs.collection("user_images");
});

var storageImage = new GridFsStorage({
  url: dbURI,
  options: { useNewUrlParser: true, useUnifiedTopology: true },
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(16, (err, buf) => {
        if (err) {
          return reject(err);
        }
        const filename = buf.toString("hex") + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: "user_images"
        };
        resolve(fileInfo);
      });
    });
  }
});
const uploadImage = multer({ storage: storageImage });

    const uploadImage = multer({ storage: storageImage });
router.get("/image/:filename", (req, res) => {
  gfs.files.findOne({ filename: req.params.filename }, (err, file) => {
    if (!file || file.length === 0) {
      return res.status(404).json({
        err: "No file exists"
      });
    }

    if (file.contentType === "image/jpeg" || file.contentType === "image/png") {
      const readstream = gfs.createReadStream(file.filename);
      //const readstream = gridFSBucket.openUploadStream(file.filename);
      readstream.pipe(res);
    } else {
      res.status(404).json({
        err: "Not an image"
      });
    }
  });
});

I would really appreciate the help, what do I need to change here to make it work with GridFsBucket, huge thanks in advance!

Body:
I followed this tutorial to create this recipe. Tutorial is awesome it explains all the steps quite nicely. Complete code example can be found here.

Html form example:

<form action="http://localhost:4000/upload" method="post" enctype="multipart/form-data">
      <input type="file"  name='image' />
      <button type="submit" >Submit</button>
</form>

Controller recipe to upload image to mongodb:

const path = require('path');
const crypto = require('crypto');
const mongoose = require('mongoose');
const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');

const mongodbURL="mongodb+srv://<user>:<pass>@cluster.mongodb.net/<databaseName>"
const connection = mongoose.createConnection(mongoURI);

// Init gfs
let gfs;
const image_bucket_name = "user_images"

connection.once('open', () => {
    // Init stream
    gfs = Grid(connection.db, mongoose.mongo);
    gfs.collection(image_bucket_name);
})

// Create storage engine
const storage = new GridFsStorage({
    url: mongoURI,
    file: (req, file) => {
        return new Promise((resolve, reject) => {
            crypto.randomBytes(16, (error, buffer) => {
                if (error) {
                    return reject(error);
                }
                const filename = buffer.toString('hex') + path.extname(file.originalname);
                const fileinfo = {
                    filename: filename,
                    bucketName: image_bucket_name
                };
                resolve(fileinfo);
            })
        });
    }
});

const upload = multer({ storage });
app.post('/upload', upload.single('image'), async (req, res) => {
    console.log("uploaded image: "+req.file.
});


问:
Can I sniff UDP packets addressed another Linux machine using Python?
I have a Python process on one Linux machine server1 that receives and processes raw UDP packets. I want to have another Linux machine server2 capable of listening to the same UDP packets server1 is receiving.

Is there any Python solution capable of sniffing UDP packets addressed to the another (Linux) machine?

答:
This not depends on Python but on your network architecture. If server1 and server2 are connected  (probably they are) through a switch then you can't do it, because the packet passing through the router will be sent only to the requested IP.

So first of all, tell us how is composed your network architecture. Where are server1 and server2? How the reach each other?

Your problem solution won't depend neither on your OS nor in the language used.
Anyway, you tagged your question "linux", so I think you are familiar with that OS.
If this is the case, and server1 and server2 access the LAN through the same router, you can evaluate the possibility of installing linux on your router (have a look at openwrt), and perform the sniffing and whatever from the router itself.

ContentLicense: CC BY-SA 3.0


问:
REGEX Match a String (Google Analytics)
I need to pull out links only have just string with excluding numbers and queries in URL in Google Analytics.

so, I need this URL

```<code>  www.site.com/en/rent/cairo/apartments-for-rent/
</code>```

and exclude these

```<code>www.site.com/en/buy/apartment-for-sale-in-acacia-compound-new-cairo-947145/

  www.site.com/en/buy/apartment-for-sale-in-acacia-compound-new-cairo-947145/?price=1000
</code>```

Thank you

答: If each URL is on its own line, and that's the only thing on the line (not even whitespace), this simple regex will do the trick: ^[^0-9|?| ]*$

Title: REGEX Match a String (Google Analytics)

Body:
I need to pull out links only have just string with excluding numbers and queries in URL in Google Analytics.

so, I need this URL

  www.site.com/en/rent/cairo/apartments-for-rent/

and exclude these

www.site.com/en/buy/apartment-for-sale-in-acacia-compound-new-cairo-947145/

  www.site.com/en/buy/apartment-for-sale-in-acacia-compound-new-cairo-947145/?price=1000

Thank you


问:
Azure AD B2C with React Native Expo
I am new to mobile app development with react-native and expo. I'm trying to add authentication/authorization in my mobile app with Azure AD B2C but I find it more difficult to understand from Microsoft docs and even I couldn't find any clear directions on Google. Could anyone with this experience please guide me in right direction. Any help would be appreciated.</p>

答:
We do not have native SDKs for ReactNative or ReactJS. Here is a sample for React Native:
https://github.com/azure-ad-b2c/apps/tree/master/apps/mobile-react-native-ios-android-appauth.</p>

Title: Azure AD B2C with React Native Expo


问:
Optional recipient role template docusign
I created a template by the UI, and use it to create envelopes through the rest API. So far so good.

In the template, 4 roles were created. But one of these should be optional when creating the envelope, that is, in certain envelopes there will only be 3 signers.

The problem is that if I only send information for 3 templatesroles the docusign returns an error of INVALID_EMAIL_ADDRESS_FOR_RECIPIENT, for the role that was not informed.

My question is if there is a way to create a "optional" role in template. Which will only be informed in some envelopes.

Edit:

I'm creating the envelope with the status "created". I do that bc we have to add some documents to the envelope before sending. After that I update the envelope changing the status to "sent".

The error happens when I update the status to "sent". If I create the envelope already with the "sent" status the error doesn't happens.

Here's my code:

```<code> $result = Docusign::createEnvelope(array(
        'templateId' => $saleContract->obra->template_id,
        'emailSubject' => 'Contrato de Compra - ' . $saleContract->obra->nome_fantasia,
        'status' => 'created',
        'templateRoles' => $this->getRoles($saleContract, $tabs),
    ));

   $this->addDocuments($saleContract, $result['envelopeId']);

    //HERE IS WHERE THE ERROR HAPPENS
    Docusign::updateEnvelope($result['envelopeId'], ['status' => 'sent']);
</code>```

答:
By default, template roles are optional. This means that you can successfully do the following:

Create a single template that contains the maximum number of recipients (and fields/tabs for all recipients).

Each time you create an Envelope via API, include Recipient information in the "Create Envelope" API request only for the needed recipients (Roles).

Any Recipient Roles that you do not specify information for when you POST /envelopes will not be included. In the event you want to create your envelope in draft, make modifications, and then send,  set the "merge roles on draft" qp to true.

```<code>merge_roles_on_draft    string
When set to true, template roles will be merged, and empty recipients will be removed. This parameter applies when you create a draft envelope with multiple templates. (To create a draft envelope, the status field is set to created.)
</code>```

If you're still having problems, double-check that you haven't prepopulated your template role with name or email values. That will fudge up the merge ^

Body:
I created a template by the UI, and use it to create envelopes through the rest API. So far so good.

In the template, 4 roles were created. But one of these should be optional when creating the envelope, that is, in certain envelopes there will only be 3 signers.

The problem is that if I only send information for 3 templatesroles the docusign returns an error of INVALID_EMAIL_ADDRESS_FOR_RECIPIENT, for the role that was not informed.

My question is if there is a way to create a "optional" role in template. Which will only be informed in some envelopes.

Edit:

I'm creating the envelope with the status "created". I do that bc we have to add some documents to the envelope before sending. After that I update the envelope changing the status to "sent".

The error happens when I update the status to "sent". If I create the envelope already with the "sent" status the error doesn't happens.

Here's my code:

 $result = Docusign::createEnvelope(array(
        'templateId' => $saleContract->obra->template_id,
        'emailSubject' => 'Contrato de Compra - ' . $saleContract->obra->nome_fantasia,
        'status' => 'created',
        'templateRoles' => $this->getRoles($saleContract, $tabs),
    ));

   $this->addDocuments($saleContract, $result['envelopeId']);

    //HERE IS WHERE THE ERROR HAPPENS
    Docusign::updateEnvelope($result['envelopeId'], ['status' => 'sent']);

Body:
By default, template roles are optional. This means that you can successfully do the following:

Create a single template that contains the maximum number of recipients (and fields/tabs for all recipients).

Each time you create an Envelope via API, include Recipient information in the "Create Envelope" API request only for the needed recipients (Roles).

Any Recipient Roles that you do not specify information for when you POST /envelopes will not be included. In the event you want to create your envelope in draft, make modifications, and then send,  set the "merge roles on draft" qp to true.

merge_roles_on_draft    string
When set to true, template roles will be merged, and empty recipients will be removed. This parameter applies when you create a draft envelope with multiple templates. (To create a draft envelope, the status field is set to created.)

If you're still having problems, double-check that you haven't prepopulated your template role with name or email values. That will fudge up the merge ^


问:
What is the equivalent of TestName rule in JUnit 5?
How can I get name of the test method in JUnit 5?</p>

答:
In addition to what is written about injecting TestInfo to test method it is also possible to inject TestInfo to methods annotated with @BeforeEach and @AfterEach which might be useful sometimes:

```<code>@BeforeEach
void setUp(TestInfo testInfo) {
  log.info(String.format("test started: %s", testInfo.getDisplayName()));
}
@AfterEach
void tearDown(TestInfo testInfo) {
  log.info(String.format("test finished: %s", testInfo.getDisplayName()));
}
</code>```

Body:
In addition to what is written about injecting TestInfo to test method it is also possible to inject TestInfo to methods annotated with @BeforeEach and @AfterEach which might be useful sometimes:

@BeforeEach
void setUp(TestInfo testInfo) {
  log.info(String.format("test started: %s", testInfo.getDisplayName()));
}
@AfterEach
void tearDown(TestInfo testInfo) {
  log.info(String.format("test finished: %s", testInfo.getDisplayName()));
}


问:
putting a space between the 3rd and 4th characters of postal code in Python
I have a df (data frame) in Python with with a postal_code variable that has Canadian  postal codes. All the postal codes are collected in a row such as k1b6j2. But , for me to use the the 'pgeocode' package i need the postal code in a standard form which is like k1b 6j2 (there must be a space between the 3rd and 4th character)

So, is there a way to replace all the postal codes with the modified ones in the df?

Many Thanks,
Ben

答:
Another way to do this is to use the pandas string support that has a bunch of nice methods to work on strings such as direct slicing of string columns:</p>

```<code>>>> import pandas as pd
>>> df = pd.DataFrame({"index": range(10), "code": ["k1b6j2"]*10})
>>> df["postal_code"] = df["code"].str[:3] + " " + df["code"].str[3:]
>>> df
   index    code postal_code
0      0  k1b6j2     k1b 6j2
1      1  k1b6j2     k1b 6j2
2      2  k1b6j2     k1b 6j2
3      3  k1b6j2     k1b 6j2
4      4  k1b6j2     k1b 6j2
5      5  k1b6j2     k1b 6j2
6      6  k1b6j2     k1b 6j2
7      7  k1b6j2     k1b 6j2
8      8  k1b6j2     k1b 6j2
9      9  k1b6j2     k1b 6j2
</code>```

Body:
Another way to do this is to use the pandas string support that has a bunch of nice methods to work on strings such as direct slicing of string columns:

>>> import pandas as pd
>>> df = pd.DataFrame({"index": range(10), "code": ["k1b6j2"]*10})
>>> df["postal_code"] = df["code"].str[:3] + " " + df["code"].str[3:]
>>> df
   index    code postal_code
0      0  k1b6j2     k1b 6j2
1      1  k1b6j2     k1b 6j2
2      2  k1b6j2     k1b 6j2
3      3  k1b6j2     k1b 6j2
4      4  k1b6j2     k1b 6j2
5      5  k1b6j2     k1b 6j2
6      6  k1b6j2     k1b 6j2
7      7  k1b6j2     k1b 6j2
8      8  k1b6j2     k1b 6j2
9      9  k1b6j2     k1b 6j2


问:
How would you read image data in from a program like Image Magick In Java?
I am working with ImageMagick and am wondering what the best way to read image data in from StdOut of the ImageMagick process.

I an invoking the command to the process like so:
/opt/local/bin/convert -resize 8000@ - -

and then piping a byte array to the process for processing.

what is the best way to read data from a process like this?

答:
You might want to look at Apache Commons Exec this gives you a good way of running executables and passing the results into Java.

It's similar to using the method Michael mentioned except should allow you more control.

There are some good examples of usage on the tutorial page.

OwnerDisplayName: DanielHonig

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Mark Davidson


问:
Parse JSON using GSON in Kotlin
I have JSON data like this and I want to parse using GSON in Kotlin

```<code>{"items":["Green Tea","19,90"]}

</code>```

First item is name of product, second is price of product.

I am not really sure how to do it. Json format is correct. Do I have to create data class? How it should look like?

答:
After Giorgi answer and some research I have result:</p>

```<code>class Items(val items: List<String>)
val gson = GsonBuilder().create()
val getItem = gson.fromJson(body, Items::class.java)
val result = getItem.items

runOnUiThread {
    textView.append(result[0].toString() + " " + result[1].toString())
              }
</code>```

Title: Parse JSON using GSON in Kotlin

Body:
I have JSON data like this and I want to parse using GSON in Kotlin

{"items":["Green Tea","19,90"]}

First item is name of product, second is price of product.

I am not really sure how to do it. Json format is correct. Do I have to create data class? How it should look like?

Body:
After Giorgi answer and some research I have result:

class Items(val items: List<String>)
val gson = GsonBuilder().create()
val getItem = gson.fromJson(body, Items::class.java)
val result = getItem.items

runOnUiThread {
    textView.append(result[0].toString() + " " + result[1].toString())
              }


问:
How to call class method in different javascript file?
This class is included in an external file names graph.js.  I'm trying to access the method drawchart from its class graphElement. The file is included in the html script src. I can even call the function fetchYearly() without a problem but that class method keeps throwing error. I'm using the library chart.js.

Here is my code :

class graphElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = document.querySelector('#tmpGraph').innerHTML;
    let canvas1 = document.getElementById('graph').shadowRoot.querySelector('#myChart'); let transType = ['Debit', 'Credit'];
    fetchYearlyData('CREDIT');
    fetchYearlyData('DEBIT');
    this.drawChart(transType);

  }
  drawChart(transType) {
    var ctx = document.getElementById('graph').shadowRoot.querySelector('#myChart').getContext('2d');
    var myChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: labels,
        datasets: [{
          label: transType[0],
          borderColor: "#f48480",
          pointBorderColor: "#f48480",
          pointBackgroundColor: "#f48480",
          pointHoverBackgroundColor: "#f48480",
          pointHoverBorderColor: "#f48480",
          pointBorderWidth: 10,
          pointHoverRadius: 10,
          pointHoverBorderWidth: 1,
          pointRadius: 3,
          fill: false,
          borderWidth: 4,
          data: dataDB
        },
        {
          label: transType[1],
          borderColor: "#80b6f4",
          pointBorderColor: "#80b6f4",
          pointBackgroundColor: "#80b6f4",
          pointHoverBackgroundColor: "#80b6f4",
          pointHoverBorderColor: "#80b6f4",
          pointBorderWidth: 10,
          pointHoverRadius: 10,
          pointHoverBorderWidth: 1,
          pointRadius: 3,
          fill: false,
          borderWidth: 4,
          data: dataCRD
        }],
      },
      options: {
        legend: {
          position: "top"
        },
        scales: {
          yAxes: [{
            ticks: {
              fontColor: "rgba(0,0,0,0.5)",
              fontStyle: "bold",
              beginAtZero: true,
              maxTicksLimit: 5,
              padding: 20
            },
            gridLines: {
              drawTicks: false,
              display: false
            }
          }],
          xAxes: [{
            gridLines: {
              zeroLineColor: "transparent"
            },
            ticks: {
              padding: 20,
              fontColor: "rgba(0,0,0,0.5)",
              fontStyle: "bold"
            }
          }]
        }
      }
    });
  }
}

function fetchYearlyData(transType) {
  //does some important stuff :)
}
```

I want to call the function drawchart() in another file on click. It is included in the script source of html file but throws :
Uncaught (in promise) ReferenceError: drawChart is not defined error when called, however the function fetchYearly() works completely fine. What am I doing wrong?

答:
fetchYearly is a function. drawChart is not: it is an instance method of the class graphElement. You need to instantiate a graphElement and invoke drawChart on it. It will likely look something like

```<code>let graph = new graphElement();
graph.drawChart();
</code>```

Body:
This class is included in an external file names graph.js.  I'm trying to access the method drawchart from its class graphElement. The file is included in the html script src. I can even call the function fetchYearly() without a problem but that class method keeps throwing error. I'm using the library chart.js.

Here is my code :

class graphElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: 'open' });
    this.shadowRoot.innerHTML = document.querySelector('#tmpGraph').innerHTML;
    let canvas1 = document.getElementById('graph').shadowRoot.querySelector('#myChart'); let transType = ['Debit', 'Credit'];
    fetchYearlyData('CREDIT');
    fetchYearlyData('DEBIT');
    this.drawChart(transType);

  }
  drawChart(transType) {
    var ctx = document.getElementById('graph').shadowRoot.querySelector('#myChart').getContext('2d');
    var myChart = new Chart(ctx, {
      type: 'bar',
      data: {
        labels: labels,
        datasets: [{
          label: transType[0],
          borderColor: "#f48480",
          pointBorderColor: "#f48480",
          pointBackgroundColor: "#f48480",
          pointHoverBackgroundColor: "#f48480",
          pointHoverBorderColor: "#f48480",
          pointBorderWidth: 10,
          pointHoverRadius: 10,
          pointHoverBorderWidth: 1,
          pointRadius: 3,
          fill: false,
          borderWidth: 4,
          data: dataDB
        },
        {
          label: transType[1],
          borderColor: "#80b6f4",
          pointBorderColor: "#80b6f4",
          pointBackgroundColor: "#80b6f4",
          pointHoverBackgroundColor: "#80b6f4",
          pointHoverBorderColor: "#80b6f4",
          pointBorderWidth: 10,
          pointHoverRadius: 10,
          pointHoverBorderWidth: 1,
          pointRadius: 3,
          fill: false,
          borderWidth: 4,
          data: dataCRD
        }],
      },
      options: {
        legend: {
          position: "top"
        },
        scales: {
          yAxes: [{
            ticks: {
              fontColor: "rgba(0,0,0,0.5)",
              fontStyle: "bold",
              beginAtZero: true,
              maxTicksLimit: 5,
              padding: 20
            },
            gridLines: {
              drawTicks: false,
              display: false
            }
          }],
          xAxes: [{
            gridLines: {
              zeroLineColor: "transparent"
            },
            ticks: {
              padding: 20,
              fontColor: "rgba(0,0,0,0.5)",
              fontStyle: "bold"
            }
          }]
        }
      }
    });
  }
}

function fetchYearlyData(transType) {
  //does some important stuff :)
}

I want to call the function drawchart() in another file on click. It is included in the script source of html file but throws :
Uncaught (in promise) ReferenceError: drawChart is not defined error when called, however the function fetchYearly() works completely fine. What am I doing wrong?

Body:
fetchYearly is a function. drawChart is not: it is an instance method of the class graphElement. You need to instantiate a graphElement and invoke drawChart on it. It will likely look something like

let graph = new graphElement();
graph.drawChart();


问:
R - Repetitions of an array in other array
From a dataframe I get a new array, sliced from a dataframe.
I want to get the amount of times a certain repetition appears on it.

For example

```<code>main <- c(A,B,C,A,B,V,A,B,C,D,E)
p <- c(A,B,C)
q <- c(A,B)

someFunction(main,p)
2

someFunction(main,q)
3
</code>```

I've been messing around with rle but it counts every subrepetion also, undersirable.

Is there a quick solution I'm missing?

答:
You can use one of the regular expression tools in R since this is really a pattern matching exercise, specifically gregexpr for this question. The p and q vectors represent the search pattern and main is where we want to search for those patterns. From the help page for gregexpr:

```<code>gregexpr returns a list of the same length as text each element of which is of
the same form as the return value for regexpr, except that the starting positions
of every (disjoint) match are given.
</code>```

So we can take the length of the first list returned by gregexpr which gives the starting positions of the matches. We'll first collapse the vectors and then do the searching:

```<code>someFunction <- function(haystack, needle) {
    haystack <- paste(haystack, collapse = "")
    needle <- paste(needle, collapse = "")
    out <- gregexpr(needle, haystack)
    out.length <- length(out[[1]])
    return(out.length)
}

> someFunction(main, p)
[1] 2
> someFunction(main, q)
[1] 3
</code>```

Note - you also need to throw "" around your vector main, p, and q vectors unless you have variables A, B, C, et al defined.

```<code>main <- c("A","B","C","A","B","V","A","B","C","D","E")
p <- c("A","B","C")
q <- c("A","B")
</code>```

Body:
From a dataframe I get a new array, sliced from a dataframe.
I want to get the amount of times a certain repetition appears on it.

For example

main <- c(A,B,C,A,B,V,A,B,C,D,E)
p <- c(A,B,C)
q <- c(A,B)

someFunction(main,p)
2

someFunction(main,q)
3

I've been messing around with rle but it counts every subrepetion also, undersirable.

Is there a quick solution I'm missing?

Body:
You can use one of the regular expression tools in R since this is really a pattern matching exercise, specifically gregexpr for this question. The p and q vectors represent the search pattern and main is where we want to search for those patterns. From the help page for gregexpr:

gregexpr returns a list of the same length as text each element of which is of
the same form as the return value for regexpr, except that the starting positions
of every (disjoint) match are given.

So we can take the length of the first list returned by gregexpr which gives the starting positions of the matches. We'll first collapse the vectors and then do the searching:

someFunction <- function(haystack, needle) {
    haystack <- paste(haystack, collapse = "")
    needle <- paste(needle, collapse = "")
    out <- gregexpr(needle, haystack)
    out.length <- length(out[[1]])
    return(out.length)
}

> someFunction(main, p)
[1] 2
> someFunction(main, q)
[1] 3

Note - you also need to throw "" around your vector main, p, and q vectors unless you have variables A, B, C, et al defined.

main <- c("A","B","C","A","B","V","A","B","C","D","E")
p <- c("A","B","C")
q <- c("A","B")


问:
How to escape closing square bracket within regular expression character class?
This command works as expected:

$ echo "foo}bar]baz" | sed 's/}/@/g; s/]/@/g'
foo@bar@baz
```

<p>Now I am trying to do the same thing using character class like this:</p>

<pre class="lang-sh prettyprint-override"><code>$ echo "foo}bar]baz" | sed 's/[}\]]/@/g'
foo}bar]baz
</code>```

This did not work. I want to have a character class with two characters } and ] so I thought escaping the square bracket like }\] would work but it did not.

What am I missing?

答:
This can be done in bash itself without calling any external utility like awk or sed:

```<code>s="foo}bar]baz"
echo "${s//[]\}]/@}"
</code>```

```<code>foo@bar@baz
</code>```

Another option is tr:

```<code>tr '[]}]' '@' <<< "$s"
</code>```

```<code>foo@bar@baz
</code>```

Body:
This command works as expected:

$ echo "foo}bar]baz" | sed 's/}/@/g; s/]/@/g'
foo@bar@baz

Now I am trying to do the same thing using character class like this:

$ echo "foo}bar]baz" | sed 's/[}\]]/@/g'
foo}bar]baz

This did not work. I want to have a character class with two characters } and ] so I thought escaping the square bracket like }\] would work but it did not.

What am I missing?

Body:
This can be done in bash itself without calling any external utility like awk or sed:

s="foo}bar]baz"
echo "${s//[]\}]/@}"

foo@bar@baz

Another option is tr:

tr '[]}]' '@' <<< "$s"

foo@bar@baz


问:
Compare Dates in Array of MongoDB Object with different formats
I am using a datepicker in my frontend which sends a date using an AJAX Request.
Now this date is in the format - 'YYYY-MM-DD'. I have an array of dates which I have to compare this date with and pick out which are equal. This array is from a Mongo DB collection where I have TimeZone included in the field as well, for example - "2020-06-03T00:00:00.000Z"

My Slot Json Object

```<code>{
  date: [
    2020-06-03T00:00:00.000Z,
    2020-06-05T00:00:00.000Z,
    2020-06-07T00:00:00.000Z
  ],
  __v: 0
}
</code>```

I have to loop over each date in the date array and compare it with the date I get from frontend.

Let's say user input date is

```<code>let userInput = '2020-06-03';
</code>```

And now I have to compare it with the date array
How do I ensure that the following comparision leads me to get a true value for

```<code>'2020-06-03' and '2020-06-03T00:00:00.000Z'
</code>```

I am looking at a solution which is appropriate when looping over all these array elements.

答:
assuming, that your date array always is at 00:00:00 o'clock, i'd suggest something like this:

const dates = [
  '2020-06-03T00:00:00.000Z',
  '2020-06-05T00:00:00.000Z',
  '2020-06-07T00:00:00.000Z'
];

let userInput = '2020-06-03';

function findDates(date) {
  const searchDate = Date.parse(date);
  const foundDates = [];

  dates.forEach(date => {
    const tempDate = Date.parse(date);

    if (tempDate === searchDate) {
      foundDates.push(date);
    }
  });

  return foundDates;
}

console.log(findDates(userInput));```

if there's more to consider, please say so

Body:
I am using a datepicker in my frontend which sends a date using an AJAX Request.
Now this date is in the format - 'YYYY-MM-DD'. I have an array of dates which I have to compare this date with and pick out which are equal. This array is from a Mongo DB collection where I have TimeZone included in the field as well, for example - "2020-06-03T00:00:00.000Z"

My Slot Json Object

{
  date: [
    2020-06-03T00:00:00.000Z,
    2020-06-05T00:00:00.000Z,
    2020-06-07T00:00:00.000Z
  ],
  __v: 0
}

I have to loop over each date in the date array and compare it with the date I get from frontend.

Let's say user input date is

let userInput = '2020-06-03';

And now I have to compare it with the date array
How do I ensure that the following comparision leads me to get a true value for

'2020-06-03' and '2020-06-03T00:00:00.000Z'

I am looking at a solution which is appropriate when looping over all these array elements.

Body:
assuming, that your date array always is at 00:00:00 o'clock, i'd suggest something like this:

const dates = [
  '2020-06-03T00:00:00.000Z',
  '2020-06-05T00:00:00.000Z',
  '2020-06-07T00:00:00.000Z'
];

let userInput = '2020-06-03';

function findDates(date) {
  const searchDate = Date.parse(date);
  const foundDates = [];

  dates.forEach(date => {
    const tempDate = Date.parse(date);

    if (tempDate === searchDate) {
      foundDates.push(date);
    }
  });

  return foundDates;
}

console.log(findDates(userInput));

if there's more to consider, please say so