问:
decltype() on std::move() of a value capture in a lambda results in an incorrect type
It seems like there either is something wrong with Clang (9.0.0) or my understanding of how decltype() is specified to work in the standard. With reference to the following code,

```<code>#include <utility>
#include <string>

template <typename...> class WhichType;

template <typename T>
std::remove_reference_t<T>&& move_v2(T&& t) {
    WhichType<std::remove_reference_t<T>&&>{};
    return static_cast<std::remove_reference_t<T>&&>(t);
}

int main() {
    auto x = std::string{"a"};
    [v = x]() {
        // move_v2(v);
        // WhichType<decltype(move_v2(v))>{};
        WhichType<decltype(std::move(v))>{};
    }();
}
</code>```

The code above has the compiler output implicit instantiation of undefined template 'WhichType<std::__1::basic_string<char> &&>' instead of the expected const std::__1::basic_string<char> && in the template parameters of WhichType. Using move_v2 or WhichType in move_v2 itself seems to output the correct thing though.

However, Clang also seems to do overload resolution on the std::move(v) expression as I expected https://wandbox.org/permlink/Nv7yXnCbqxjJMVvX. This makes some of my worries go away, but I still don't understand the behavior of decltype() inside the lambda.

GCC does not seem to have this inconsistency in this particular case https://wandbox.org/permlink/5mhrOzLn5XZO8LNB.

Could someone correct me if I'm wrong with my understading of decltype() or point me to the exact places where this bug manifests in clang? Seems a bit scary from first glance.  This can cause problems when used in SFINAE or something similar.

答:
Clang is wrong.  decltype(std::move(v)) should be const && because the cv-qualifier v (which is equivalent to this->v) is the union of the cv-qualifiers of *this (which is const in the operator() of a non-mutable lambda) and v (which is none), so v is a const lvalue.  Then, std::move converts to an xvalue of the corresponding type, so decltype should be const &&.

decltype behaves specially when applied to an id-expression or a member access expression (this->v), but that's not the case here.  std::move(v) is a complicated expression, so it is treated as an ordinary expression.

Body:
It seems like there either is something wrong with Clang (9.0.0) or my understanding of how decltype() is specified to work in the standard. With reference to the following code,

#include <utility>
#include <string>

template <typename...> class WhichType;

template <typename T>
std::remove_reference_t<T>&& move_v2(T&& t) {
    WhichType<std::remove_reference_t<T>&&>{};
    return static_cast<std::remove_reference_t<T>&&>(t);
}

int main() {
    auto x = std::string{"a"};
    [v = x]() {
        // move_v2(v);
        // WhichType<decltype(move_v2(v))>{};
        WhichType<decltype(std::move(v))>{};
    }();
}

The code above has the compiler output implicit instantiation of undefined template 'WhichType<std::__1::basic_string<char> &&>' instead of the expected const std::__1::basic_string<char> && in the template parameters of WhichType. Using move_v2 or WhichType in move_v2 itself seems to output the correct thing though.

However, Clang also seems to do overload resolution on the std::move(v) expression as I expected https://wandbox.org/permlink/Nv7yXnCbqxjJMVvX. This makes some of my worries go away, but I still don't understand the behavior of decltype() inside the lambda.

GCC does not seem to have this inconsistency in this particular case https://wandbox.org/permlink/5mhrOzLn5XZO8LNB.

Could someone correct me if I'm wrong with my understading of decltype() or point me to the exact places where this bug manifests in clang? Seems a bit scary from first glance.  This can cause problems when used in SFINAE or something similar.


来源: stackexchange

问:
TCPDF: Severity: Notice --> Undefined offset: 0 in 'tcpdf/tcpdf.php' at line 20373
I am using TCPDF library for generating PDF in codeigniter. I have successfully integrated TCPDF version 6.2.8 library in Codeigniter3. Everything is working fine but with several notices. I tried a lot but not able to catch exact issue.

My codeigniter model method is:

```<code>public function saveToPdf($html, $pdfName, $QRCodeData) {
        $this->load->library('Pdf');
        $pdf = new Pdf();
        $pdf->SetAutoPageBreak(TRUE, 10); //set bottom margin
        $pdf->AddPage();
        if ($QRCodeData):
            $pdf->write2DBarcode($QRCodeData, 'QRCODE,H', 180, 13, 75, 75);
        endif;

        $pdf->lastPage();
        $pdf->writeHTML($html);

        return $pdf->Output(APPPATH . "cache" . "/" . $pdfName, 'F');
    }
</code>```

Everything is working fine but this code generates notices for undefined offset at many places.

My error log:

```<code>ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: 0 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 20373
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: 0 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 18853
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: -1 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 20227
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: 0 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 20373
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: 0 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 18853
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: -1 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 20227
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: 0 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 20373
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: 0 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 18853
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: -1 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 20227
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: 0 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 20373
</code>```

You can see my tcpdf.php on github.com at https://raw.githubusercontent.com/vsjadeja/tcpdf-codeigniter/master/application/libraries/tcpdf/tcpdf.php

Please help me.

答:
Was getting a similar error and traced through tcpdf.php trying to find what was going wrong.  For me it seems tcpdf.php needs a link. It doesn't have to be used, just has to have one.  Added a dummy one (to page 1) after AddPage() and error has vanished!

// add a page
    $pdf->AddPage();

    $dummy_tcpdf_undefined_offset_err = $pdf->AddLink(); $pdf->SetLink($dummy_tcpdf_undefined_offset_err, 0, '*1');

ContentLicense: CC BY-SA 3.0

Body:
I am using TCPDF library for generating PDF in codeigniter. I have successfully integrated TCPDF version 6.2.8 library in Codeigniter3. Everything is working fine but with several notices. I tried a lot but not able to catch exact issue.

My codeigniter model method is:

public function saveToPdf($html, $pdfName, $QRCodeData) {
        $this->load->library('Pdf');
        $pdf = new Pdf();
        $pdf->SetAutoPageBreak(TRUE, 10); //set bottom margin
        $pdf->AddPage();
        if ($QRCodeData):
            $pdf->write2DBarcode($QRCodeData, 'QRCODE,H', 180, 13, 75, 75);
        endif;

        $pdf->lastPage();
        $pdf->writeHTML($html);

        return $pdf->Output(APPPATH . "cache" . "/" . $pdfName, 'F');
    }

Everything is working fine but this code generates notices for undefined offset at many places.

My error log:

ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: 0 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 20373
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: 0 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 18853
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: -1 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 20227
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: 0 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 20373
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: 0 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 18853
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: -1 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 20227
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: 0 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 20373
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: 0 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 18853
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: -1 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 20227
ERROR - 2017-07-22 15:16:12 --> Severity: Notice --> Undefined offset: 0 /var/www/html/ts-2016/api/application/libraries/tcpdf/tcpdf.php 20373

You can see my tcpdf.php on github.com at https://raw.githubusercontent.com/vsjadeja/tcpdf-codeigniter/master/application/libraries/tcpdf/tcpdf.php

Please help me.

ContentLicense: CC BY-SA 4.0


问:
Tkinter multi line text positioning problem
Having a problem with my tkinter program on Python. On line eleven I have put a \n in place as all the text wasn't fitting into my set window size. I would like the new line to start on the right (ie like pressing enter on a text editior). It appears when a new line is called it bases the text from centre. I'm new to tkitner and so not aware of all the commands/functions so help will be appreciated. Iv'e added a photo of the problem.

```<code>
def password_basic_check():#Function that gets called when enter button is pressed. function check password matches. its lengh and if it has both upper and lower case letters
    if password_enter_txt.get() != password_reenter_txt.get():#checks if both passwords matches
        password_fault_report.configure(text='Passwords do not match, try again.')#prints this text out into the blank string

    elif len(password_reenter_txt.get()) < 8:#checks if password lengh is below 8 characters
        password_fault_report.configure(text='Password needs to be at least 8 characters long')

    elif password_reenter_txt.get().islower() == True or password_reenter_txt.get().isupper() == True:#if password returns true if string has lower and upper case letters are used
        password_fault_report.configure(text='Password needs have both upper\n and lower case lettes')

    else:
        password_fault_report.configure(text='Password correct')#if all of the password checks fail

window = Tk()
window.geometry('480x320') #setting size of window (pixles)
window.title('Password Checker')
window.iconbitmap('/Users/andypaling/Desktop/index.ico')#sets icon for window

welcome_lbl = Label(window, text='Welcome', font=('Arial', 26), fg='#71C2FE') #Label with text saying 'welcome' in light blue
welcome_lbl.place(x=15, y=10) #placing welcome label in top left of window

under_line_lbl = Label(window, text='__________________', font=('Arial', 35), fg='#FFB56B') #orange line under blue for looks
under_line_lbl.place(x=0, y=40)

intro_lbl = Label(window, text='Please enter your password: ', font=('Arial', 14, 'bold italic'))#lable with text underlined and italics
intro_lbl.place(x=10, y=90)

password_enter_lbl = Label(window, text='Password: ', font=('Candara', 10))
password_enter_lbl.place(x=10, y=120)

password_enter_txt = Entry(window, width=20, relief='raised')#entry box for user to enter their password
password_enter_txt.place(x=10, y=135)

password_reenter_lbl = Label(window, text='Re-enter password', font=('Candara', 10))#same as above for password reenter lbl and entry
password_reenter_lbl.place(x=10, y=160)

password_reenter_txt = Entry(window, width=20, relief='raised')
password_reenter_txt.place(x=10, y=175)

password_fault_report = Label(window, text='', font=('Arial', 14))#Empty label to be filled later to report password errors
password_fault_report.place(x=225, y=140)

password_enter_btn = Button(window, text='Enter.', relief='raised', width=6, bg='orange', command=password_basic_check)#button to enter password, when pressed, password_basic_check is called
password_enter_btn.place(x=10, y=210)

window.mainloop()

[photo of problem][1]

  [1]: https://i.stack.imgur.com/GdQ1Y.png
</code>```

答:
You can even go for two labels if you don't have a problem here
This is the simplest solution

```<code>from tkinter import *

def password_basic_check():  # Function that gets called when enter button is pressed. function check password matches. its lengh and if it has both upper and lower case letters
    password_fault_report1.configure(text='')
    password_fault_report2.configure(text='')
    if password_enter_txt.get() != password_reenter_txt.get():  # checks if both passwords matches
        password_fault_report1.configure(
            text='Passwords do not match, try again.')  # prints this text out into the blank string

    elif len(password_reenter_txt.get()) < 8:  # checks if password lengh is below 8 characters
        password_fault_report1.configure(text='Password needs to be at least')
        password_fault_report2.configure(text='8 characters long')

    elif password_reenter_txt.get().islower() == True or password_reenter_txt.get().isupper() == True:  # if password returns true if string has lower and upper case letters are used
        password_fault_report1.configure(text='Password needs have both upper')
        password_fault_report2.configure(text='and lower case lettes')

    else:
        password_fault_report1.configure(text='Password correct')  # if all of the password checks fail

window = Tk()
window.geometry('480x320')  # setting size of window (pixles)
window.title('Password Checker')

welcome_lbl = Label(window, text='Welcome', font=('Arial', 26),
                    fg='#71C2FE')  # Label with text saying 'welcome' in light blue
welcome_lbl.place(x=15, y=10)  # placing welcome label in top left of window

under_line_lbl = Label(window, text='__________________', font=('Arial', 35),
                       fg='#FFB56B')  # orange line under blue for looks
under_line_lbl.place(x=0, y=40)

intro_lbl = Label(window, text='Please enter your password: ',
                  font=('Arial', 14, 'bold italic'))  # lable with text underlined and italics
intro_lbl.place(x=10, y=90)

password_enter_lbl = Label(window, text='Password: ', font=('Candara', 10))
password_enter_lbl.place(x=10, y=120)

password_enter_txt = Entry(window, width=20, relief='raised')  # entry box for user to enter their password
password_enter_txt.place(x=10, y=135)

password_reenter_lbl = Label(window, text='Re-enter password',
                             font=('Candara', 10))  # same as above for password reenter lbl and entry
password_reenter_lbl.place(x=10, y=160)

password_reenter_txt = Entry(window, width=20, relief='raised')
password_reenter_txt.place(x=10, y=175)

password_fault_report1 = Label(window, text='',
                               font=('Arial', 14))  # Empty label to be filled later to report password errors
password_fault_report1.place(x=150, y=140)
password_fault_report2 = Label(window, text='',
                               font=('Arial', 14))  # Empty label to be filled later to report password errors
password_fault_report2.place(x=150, y=170)

password_enter_btn = Button(window, text='Enter.', relief='raised', width=6, bg='orange',
                            command=password_basic_check)  # button to enter password, when pressed, password_basic_check is called
password_enter_btn.place(x=10, y=210)

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

This may help :)

Body:
Having a problem with my tkinter program on Python. On line eleven I have put a \n in place as all the text wasn't fitting into my set window size. I would like the new line to start on the right (ie like pressing enter on a text editior). It appears when a new line is called it bases the text from centre. I'm new to tkitner and so not aware of all the commands/functions so help will be appreciated. Iv'e added a photo of the problem.

def password_basic_check():#Function that gets called when enter button is pressed. function check password matches. its lengh and if it has both upper and lower case letters
    if password_enter_txt.get() != password_reenter_txt.get():#checks if both passwords matches
        password_fault_report.configure(text='Passwords do not match, try again.')#prints this text out into the blank string

    elif len(password_reenter_txt.get()) < 8:#checks if password lengh is below 8 characters
        password_fault_report.configure(text='Password needs to be at least 8 characters long')

    elif password_reenter_txt.get().islower() == True or password_reenter_txt.get().isupper() == True:#if password returns true if string has lower and upper case letters are used
        password_fault_report.configure(text='Password needs have both upper\n and lower case lettes')

    else:
        password_fault_report.configure(text='Password correct')#if all of the password checks fail

window = Tk()
window.geometry('480x320') #setting size of window (pixles)
window.title('Password Checker')
window.iconbitmap('/Users/andypaling/Desktop/index.ico')#sets icon for window

welcome_lbl = Label(window, text='Welcome', font=('Arial', 26), fg='#71C2FE') #Label with text saying 'welcome' in light blue
welcome_lbl.place(x=15, y=10) #placing welcome label in top left of window

under_line_lbl = Label(window, text='__________________', font=('Arial', 35), fg='#FFB56B') #orange line under blue for looks
under_line_lbl.place(x=0, y=40)

intro_lbl = Label(window, text='Please enter your password: ', font=('Arial', 14, 'bold italic'))#lable with text underlined and italics
intro_lbl.place(x=10, y=90)

password_enter_lbl = Label(window, text='Password: ', font=('Candara', 10))
password_enter_lbl.place(x=10, y=120)

password_enter_txt = Entry(window, width=20, relief='raised')#entry box for user to enter their password
password_enter_txt.place(x=10, y=135)

password_reenter_lbl = Label(window, text='Re-enter password', font=('Candara', 10))#same as above for password reenter lbl and entry
password_reenter_lbl.place(x=10, y=160)

password_reenter_txt = Entry(window, width=20, relief='raised')
password_reenter_txt.place(x=10, y=175)

password_fault_report = Label(window, text='', font=('Arial', 14))#Empty label to be filled later to report password errors
password_fault_report.place(x=225, y=140)

password_enter_btn = Button(window, text='Enter.', relief='raised', width=6, bg='orange', command=password_basic_check)#button to enter password, when pressed, password_basic_check is called
password_enter_btn.place(x=10, y=210)

window.mainloop()

[photo of problem][1]

  [1]: https://i.stack.imgur.com/GdQ1Y.png

Body:
You can even go for two labels if you don't have a problem here
This is the simplest solution

from tkinter import *

def password_basic_check():  # Function that gets called when enter button is pressed. function check password matches. its lengh and if it has both upper and lower case letters
    password_fault_report1.configure(text='')
    password_fault_report2.configure(text='')
    if password_enter_txt.get() != password_reenter_txt.get():  # checks if both passwords matches
        password_fault_report1.configure(
            text='Passwords do not match, try again.')  # prints this text out into the blank string

    elif len(password_reenter_txt.get()) < 8:  # checks if password lengh is below 8 characters
        password_fault_report1.configure(text='Password needs to be at least')
        password_fault_report2.configure(text='8 characters long')

    elif password_reenter_txt.get().islower() == True or password_reenter_txt.get().isupper() == True:  # if password returns true if string has lower and upper case letters are used
        password_fault_report1.configure(text='Password needs have both upper')
        password_fault_report2.configure(text='and lower case lettes')

    else:
        password_fault_report1.configure(text='Password correct')  # if all of the password checks fail

window = Tk()
window.geometry('480x320')  # setting size of window (pixles)
window.title('Password Checker')

welcome_lbl = Label(window, text='Welcome', font=('Arial', 26),
                    fg='#71C2FE')  # Label with text saying 'welcome' in light blue
welcome_lbl.place(x=15, y=10)  # placing welcome label in top left of window

under_line_lbl = Label(window, text='__________________', font=('Arial', 35),
                       fg='#FFB56B')  # orange line under blue for looks
under_line_lbl.place(x=0, y=40)

intro_lbl = Label(window, text='Please enter your password: ',
                  font=('Arial', 14, 'bold italic'))  # lable with text underlined and italics
intro_lbl.place(x=10, y=90)

password_enter_lbl = Label(window, text='Password: ', font=('Candara', 10))
password_enter_lbl.place(x=10, y=120)

password_enter_txt = Entry(window, width=20, relief='raised')  # entry box for user to enter their password
password_enter_txt.place(x=10, y=135)

password_reenter_lbl = Label(window, text='Re-enter password',
                             font=('Candara', 10))  # same as above for password reenter lbl and entry
password_reenter_lbl.place(x=10, y=160)

password_reenter_txt = Entry(window, width=20, relief='raised')
password_reenter_txt.place(x=10, y=175)

password_fault_report1 = Label(window, text='',
                               font=('Arial', 14))  # Empty label to be filled later to report password errors
password_fault_report1.place(x=150, y=140)
password_fault_report2 = Label(window, text='',
                               font=('Arial', 14))  # Empty label to be filled later to report password errors
password_fault_report2.place(x=150, y=170)

password_enter_btn = Button(window, text='Enter.', relief='raised', width=6, bg='orange',
                            command=password_basic_check)  # button to enter password, when pressed, password_basic_check is called
password_enter_btn.place(x=10, y=210)

window.mainloop()

This may help :)


问:
Standard Deviation of One Variable Weighted By Second Variable
I would like to calculate standard deviation of a variable that weighs each observation by a second variable.

```<code>values <- c(100, 200, 300, 400, 200)
sizes <- c(12, 54, 1, 218, 63)
</code>```

How do I find the standard deviation of values with weighting applied based on sizes?

答:
That Hmisc is rather large. In the time it took me to install and load that package, which has multiple dependencies, I did this using base R. First, I had to check the formula from Wiki. https://en.wikipedia.org/wiki/Weighted_arithmetic_mean:

Note that V1 is just the sum of the weights. Then I just converted that into R-speak:

```<code>x <- c(100, 200, 300, 400, 200)
w <- c(12, 54, 1, 218, 63)
mu <- weighted.mean(x, w)

sqrt(sum(w * ((x-mu)^2))/(sum(w) - 1))
[1] 102.696
</code>```

Which agrees with the wtd.var function from Hmisc.

Of course, if you want added functionality, like normalisation, maximum likelihood estimation, or removing NA for you, then go with the wtd.var function. But the OP didn't specify any of that. Also, if your internet speed is slow, or you want to try to do things yourself and learn at the same time, then use my method. :)

Edit 1: And for reliability weights (normwt=TRUE):

```<code>> V1 <- sum(w)
> V2 <- sum(w^2)
> sqrt(sum(w * ((x-mw)^2))/(V1 - V2/V1))
[1] 138.3356
</code>```

Edit 2: Handling missing values (na.rm=TRUE):

```<code>obs <- !is.na(x) & !is.na(w)
x <- x[obs]
w <- w[obs]
</code>```

Then use these instead.

Body:
I would like to calculate standard deviation of a variable that weighs each observation by a second variable.

values <- c(100, 200, 300, 400, 200)
sizes <- c(12, 54, 1, 218, 63)

How do I find the standard deviation of values with weighting applied based on sizes?

Body:
That Hmisc is rather large. In the time it took me to install and load that package, which has multiple dependencies, I did this using base R. First, I had to check the formula from Wiki. https://en.wikipedia.org/wiki/Weighted_arithmetic_mean:

Note that V1 is just the sum of the weights. Then I just converted that into R-speak:

x <- c(100, 200, 300, 400, 200)
w <- c(12, 54, 1, 218, 63)
mu <- weighted.mean(x, w)

sqrt(sum(w * ((x-mu)^2))/(sum(w) - 1))
[1] 102.696

Which agrees with the wtd.var function from Hmisc.

Of course, if you want added functionality, like normalisation, maximum likelihood estimation, or removing NA for you, then go with the wtd.var function. But the OP didn't specify any of that. Also, if your internet speed is slow, or you want to try to do things yourself and learn at the same time, then use my method. :)

Edit 1: And for reliability weights (normwt=TRUE):

> V1 <- sum(w)
> V2 <- sum(w^2)
> sqrt(sum(w * ((x-mw)^2))/(V1 - V2/V1))
[1] 138.3356

Edit 2: Handling missing values (na.rm=TRUE):

obs <- !is.na(x) & !is.na(w)
x <- x[obs]
w <- w[obs]

Then use these instead.


问:
How do you find column sort and type of order in Excel by C#?
I have a table named "Products" (on "Order detail" worksheet). I want to know if whether I can get the column was sorted (in this image is column "Region") and type of order is custom list China, Taiwan.

I find out on the internet the way to Add sort to a table but I can't find the way I need to fix my problem.

I am looking forward to hearing from you. Thank you for your watching. If I have any mistake in grammar or vocabulary, please forgive to me.

```<code>void SortTableCustomList()
{
    Excel.Worksheet esh = oWB.Worksheets["Order detail"];
    MessageBox.Show(esh.ListObjects["Products"].Sort.SortFields.GetType().Name........
}
</code>```

答:
```<code>//give the value 7 (column "Region")
MessageBox.Show(esh.ListObjects["Products"].Sort.SortFields[1].Key.Column.ToString());
//give the value "xlAscending"
MessageBox.Show(esh.ListObjects["Products"].Sort.SortFields[1].Order.ToString());
</code>```

Body:
I have a table named "Products" (on "Order detail" worksheet). I want to know if whether I can get the column was sorted (in this image is column "Region") and type of order is custom list China, Taiwan.

I find out on the internet the way to Add sort to a table but I can't find the way I need to fix my problem.

I am looking forward to hearing from you. Thank you for your watching. If I have any mistake in grammar or vocabulary, please forgive to me.

void SortTableCustomList()
{
    Excel.Worksheet esh = oWB.Worksheets["Order detail"];
    MessageBox.Show(esh.ListObjects["Products"].Sort.SortFields.GetType().Name........
}


问:
How to fix 'module not found' for audio files using file-loader? Images, CSS, and JSON are working just fine
I'm new to building a browser game using Typescript/React/Redux/etc. and am trying to implement audio for the game. I've been attempting to import audio files in the same way I import image and json files, but so far to no avail. After adding mp3 to my webpack config using 'file-loader', I try importing a sample mp3 file I put in the same location as an image file I've been able to successfully import, but when I try to run web pack, it tells me that the mp3 module cannot be found.

sample file

```<code>import React from "react";
import spriteSheet from "../assets/spritesheet.gif";
import audioFile from "../assets/pillRotate.mp3";

import { Gameboard } from "./Gameboard";

export class MainGameComponent extends React.Component {
    render() {
        return (
            <div>
                <img id="spriteSheet" src={spriteSheet} hidden={true} />
                <audio src={audioFile}></audio>
                <Gameboard />
            </div>
        )
    }
}

export default MainGameComponent;
</code>```

webpack.config.js

```<code>const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    entry: "./src/index.tsx",
    output: {
        filename: "bundle.js",
        path: __dirname + "/dist"
    },

    resolve: {
        extensions: [".ts", ".tsx", ".js"]
    },

    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: "awesome-typescript-loader"
            },
            {
                test: /\.(png|jpg|gif|mp3)$/,
                use: 'file-loader',
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
        ]
    },

    plugins: [
        new HtmlWebpackPlugin({
            hash: true,
            title: 'Dr. Mario',
            template: 'index.html',
            filename: './index.html'
        })
    ]
};
</code>```

ERROR in [at-loader] ./src/components/MainGame.tsx:3:23
    TS2307: Cannot find module '../assets/pillRotate.mp3'.

答:
If you use create-react-app to setup your React project. You can try to add the follow lines in your react-app-env.d.ts:

```<code>declare module '*.mp3' {
  const src: string;
  export default src;
}
</code>```

When you try to import a mp3 file in *.tsx, typescript compiler will try to find out its declaration, the same way as you import another class file. But when you try to require a mp3 file, like this:

```<code><audio src={require('./assets/xxx.mp3')}>
</code>```

ts will not try to find its declaration, but handle it to webpack loader. This why in this way there is no compile error.

Body:
I'm new to building a browser game using Typescript/React/Redux/etc. and am trying to implement audio for the game. I've been attempting to import audio files in the same way I import image and json files, but so far to no avail. After adding mp3 to my webpack config using 'file-loader', I try importing a sample mp3 file I put in the same location as an image file I've been able to successfully import, but when I try to run web pack, it tells me that the mp3 module cannot be found.

sample file

import React from "react";
import spriteSheet from "../assets/spritesheet.gif";
import audioFile from "../assets/pillRotate.mp3";

import { Gameboard } from "./Gameboard";

export class MainGameComponent extends React.Component {
    render() {
        return (

                <audio src={audioFile}></audio>
                <Gameboard />

        )
    }
}

export default MainGameComponent;

webpack.config.js

const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
    entry: "./src/index.tsx",
    output: {
        filename: "bundle.js",
        path: __dirname + "/dist"
    },

    resolve: {
        extensions: [".ts", ".tsx", ".js"]
    },

    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: "awesome-typescript-loader"
            },
            {
                test: /\.(png|jpg|gif|mp3)$/,
                use: 'file-loader',
            },
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader'],
            },
        ]
    },

    plugins: [
        new HtmlWebpackPlugin({
            hash: true,
            title: 'Dr. Mario',
            template: 'index.html',
            filename: './index.html'
        })
    ]
};

ERROR in [at-loader] ./src/components/MainGame.tsx:3:23
    TS2307: Cannot find module '../assets/pillRotate.mp3'.

Body:
If you use create-react-app to setup your React project. You can try to add the follow lines in your react-app-env.d.ts:

declare module '*.mp3' {
  const src: string;
  export default src;
}

When you try to import a mp3 file in *.tsx, typescript compiler will try to find out its declaration, the same way as you import another class file. But when you try to require a mp3 file, like this:

<audio src={require('./assets/xxx.mp3')}>

ts will not try to find its declaration, but handle it to webpack loader. This why in this way there is no compile error.


问:
Spark-sql difference between 'YYYY-MM-dd' and 'yyyy-MM-dd' date formats
I have a use case to add some value to a timestamp column and derive a date from this. I'm trying to use from_unix and unix_timestamp functions. But it is showing different values with different formats.

```<code>select from_unixtime('1577582583',  'YYYY-MM-dd'), from_unixtime('1577582583',  'yyyy-MM-dd');
from_unixtime(CAST(1577582583 AS BIGINT), YYYY-MM-dd)   from_unixtime(CAST(1577582583 AS BIGINT), yyyy-MM-dd)
2020-12-29  2019-12-29
</code>```

Can someone tell the difference between 'YYYY-MM-dd' format and 'yyyy-MM-dd' format?

答:
YYYY is a week date and yyyy is an ordinary date. You can check it there:
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
https://en.wikipedia.org/wiki/ISO_week_date

Body:
I have a use case to add some value to a timestamp column and derive a date from this. I'm trying to use from_unix and unix_timestamp functions. But it is showing different values with different formats.

select from_unixtime('1577582583',  'YYYY-MM-dd'), from_unixtime('1577582583',  'yyyy-MM-dd');
from_unixtime(CAST(1577582583 AS BIGINT), YYYY-MM-dd)   from_unixtime(CAST(1577582583 AS BIGINT), yyyy-MM-dd)
2020-12-29  2019-12-29

Can someone tell the difference between 'YYYY-MM-dd' format and 'yyyy-MM-dd' format?


问:
Skip first result from v-for vuejs2
I'm working with laravel 5.5 and vuejs2 and lodash project. I want to skip first coming data in result like the image below. This is my vuejs2 code.

```<code>new Vue({
el:'#users',
data:{
    message:'',
    ok:false,
    noresult:false,
    arrayresults: [{id:'' ,username: '',useremail: '',userphone:'',}],
},
methods:{
    searchData: _.debounce(function(){
        if(this.message != '')
        {
            this.noresult = false;
            this.arrayresults = [{id:'' ,username: '',useremail: '',userphone:'',}],
            $.ajax({
                type:'POST',
                url: path+'usersearch',
                data: {data:this.message},
                success:(data) => {
                    if(data.length >= 1)
                    {
                        for(i = 0;i<data.length;i++)
                        {
                            this.arrayresults.push({id:data[i]['id'],username:data[i]['user_name'],useremail:data[i]['user_email'],userphone:data[i]['user_phone']})
                        }
                        this.ok = true;
                    }
                    else
                    {
                        this.ok = false;
                        this.noresult = true;
                    }
                 },
                error:function()
                {
                    console.log("error");
                }
            });
        }
        else
        {
            this.ok = false;
            this.arrayresults = [{id:'' ,username: '',useremail: '',userphone:'',}];
        }
    },1000)
}
});
</code>```

This is my laravel blade code:

```<code>        <div v-if="ok" id='search-result' v-cloak>
        <table class='table table-responsive thead-text' border='5'>
            <thead>
                <tr class='success'>
                    <td>{{trans('language.user_name')}}</td>
                    <td>{{trans('language.user_phone')}}</td>
                    <td>{{trans('language.user_email')}}</td>
                    <td>{{trans('language.settings')}}</td>
                </tr>
            </thead>
            <tbody>
                <tr v-for='(arrayresult ,key ,id) in arrayresults' class='warning'>
                    <td>@{{arrayresult.username}}</td>
                    <td>@{{arrayresult.userphone}}</td>
                    <td>@{{arrayresult.useremail}}</td>
                    <td class='hidden-print'>
                        <a v-bind:href="'/{{$path}}/users/' + arrayresult.id" class='btn btn-success'>{{trans('language.show')}}</a>
                        @can('users.update')<a v-bind:href="'/{{$path}}/users/' + arrayresult.id + '/edit'" class='btn btn-info'>{{trans('language.edit')}}</a>@endcan
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</code>```

Everything is ok so far except that the first value is looking null without result when i set the array like this:

```<code>                this.arrayresults = [{id:'' ,username: '',useremail: '',userphone:'',}],
</code>```

The result shows like this:

I want to remove the first null value from the search.

答:
What Voldymyr wrote

```<code><li v-for="(value, index) in array" v-if="value.firstName">
      {{ value.firstName }} - index: {{index}}
</li>
</code>```

seems fine to exclude data which has got firstname null or empty.
But to avoid the first record (that's what you asked), the best way I can think of is,

```<code><li v-for="(value, index) in array" v-if="index">
  {{ value.firstName }} - index: {{index}}
<li>
</code>```

The index will be 0 for the first record, and v-if(index) will be false.

Title: Skip first result from v-for vuejs2

Body:
I'm working with laravel 5.5 and vuejs2 and lodash project. I want to skip first coming data in result like the image below. This is my vuejs2 code.

new Vue({
el:'#users',
data:{
    message:'',
    ok:false,
    noresult:false,
    arrayresults: [{id:'' ,username: '',useremail: '',userphone:'',}],
},
methods:{
    searchData: _.debounce(function(){
        if(this.message != '')
        {
            this.noresult = false;
            this.arrayresults = [{id:'' ,username: '',useremail: '',userphone:'',}],
            $.ajax({
                type:'POST',
                url: path+'usersearch',
                data: {data:this.message},
                success:(data) => {
                    if(data.length >= 1)
                    {
                        for(i = 0;i<data.length;i++)
                        {
                            this.arrayresults.push({id:data[i]['id'],username:data[i]['user_name'],useremail:data[i]['user_email'],userphone:data[i]['user_phone']})
                        }
                        this.ok = true;
                    }
                    else
                    {
                        this.ok = false;
                        this.noresult = true;
                    }
                 },
                error:function()
                {
                    console.log("error");
                }
            });
        }
        else
        {
            this.ok = false;
            this.arrayresults = [{id:'' ,username: '',useremail: '',userphone:'',}];
        }
    },1000)
}
});

This is my laravel blade code:

                    {{trans('language.user_name')}}
                    {{trans('language.user_phone')}}
                    {{trans('language.user_email')}}
                    {{trans('language.settings')}}

                    @{{arrayresult.username}}
                    @{{arrayresult.userphone}}
                    @{{arrayresult.useremail}}

                        {{trans('language.show')}}
                        @can('users.update'){{trans('language.edit')}}@endcan

Everything is ok so far except that the first value is looking null without result when i set the array like this:

                this.arrayresults = [{id:'' ,username: '',useremail: '',userphone:'',}],

The result shows like this:

I want to remove the first null value from the search.

Body:
What Voldymyr wrote

<li v-for="(value, index) in array" v-if="value.firstName">
      {{ value.firstName }} - index: {{index}}
</li>

seems fine to exclude data which has got firstname null or empty.
But to avoid the first record (that's what you asked), the best way I can think of is,

<li v-for="(value, index) in array" v-if="index">
  {{ value.firstName }} - index: {{index}}
<li>

The index will be 0 for the first record, and v-if(index) will be false.


问:
Can I send batched messages through a Websphere MQ Queue using Java JMS?
I'm working in a project that requires to send multiple messages to another application via asynchronous Websphere MQ messages. Actually I'm opening and closing sessions for every message I send. I appreciate your answers. By the way this is my first post here.</p>

答:
I figure something like this should work:

```<code>Session session = connection.createSession(false, SESSION.AUTO_ACKNOWLEDGE);
// Create first message
Message msgOne = session.createTextMessage("Message One");
// Set reply-to queue to REPLY1QUEUE
msgOne.setJMSReplyTo(session.createQueue("REPLY1QUEUE"));
// Create another message.
Message msgTwo = session.createTextMessage("Message Two");
msgTwo.setJMSReplyTo(session.createQueue("REPLY2QUEUE"));

// Initialize destination queue and message producer.
MessageProducer producer = session.createProducer(session.createQueue("DESTQUEUE"));

// Connect, send and close.
connection.start();
producer.send(msgOne);
producer.send(msgTwo);
connection.close();

// Close the session.
session.close();
</code>```

If I'm not mistaken, the reply-to queue is optional.

Body:
I figure something like this should work:

Session session = connection.createSession(false, SESSION.AUTO_ACKNOWLEDGE);
// Create first message
Message msgOne = session.createTextMessage("Message One");
// Set reply-to queue to REPLY1QUEUE
msgOne.setJMSReplyTo(session.createQueue("REPLY1QUEUE"));
// Create another message.
Message msgTwo = session.createTextMessage("Message Two");
msgTwo.setJMSReplyTo(session.createQueue("REPLY2QUEUE"));

// Initialize destination queue and message producer.
MessageProducer producer = session.createProducer(session.createQueue("DESTQUEUE"));

// Connect, send and close.
connection.start();
producer.send(msgOne);
producer.send(msgTwo);
connection.close();

// Close the session.
session.close();

If I'm not mistaken, the reply-to queue is optional.


问:
How to flatten two top-level merge commits using git
I've recently encountered a git scenario which I don't know how to handle. First let's set the scene.

Ideal Workflow

Suppose you are maintaining a fork of a large open-source project, where upstream is doing development using pull requests (PRs). Since upstream is doing PRs their git history has lots of merge commits.

Periodically you will have to sync your tree with upstream. Typically this goes like so:

git checkout -b sync

git pull upstream master

Fix merge conflicts, before git adding the conflict files, then git commit.

At this point you have a neat little merge commit at the top of the tree. Nested inside are all of upstream's commits and merges. You run your continuous integration tests (CI), they pass and the branch is merged into your fork's master branch. Wonderful.

Problematic Scenario

git checkout -b sync

git pull upstream master

You fix merge conflicts, git add and git commit them.

You run your CI and tests fail because upstream broke something.

Two days later, upstream fixes the problem.

git pull upstream master

Fix merge conflicts again.

At this point your sync branch contains two merge commits authored by you. Each individual merge commit contains upstream's various commits and merges.

You could run CI and merge now, but you shouldn't, because your first merge commit will interfere with future git bisects. Ideally you'd have a single merge commit which is the sum of the two merge commits in sequence.

How does one flatten those two merge commits into one, but preserving upstream's git history?

Notes

git rebase --preserve-merges is a) deprecated, and b) all or nothing. You can't selectively preserve all of upstream's merges, but flatten yours.

I've tried using git rebase --rebase-merges -i origin/master and marking the second merge f for fixup, but this doesn't achieve the desired effect. I got merge commits on files I've never touched.

One solution would be to redo the entire merge from scratch now that upstream is fixed. The problem is, even with rerere this will be a lot of work. In these upstream syncs you end up fixing stuff which isn't a merge conflict, but is (e.g.) a compilation or logic error. Because these fixes are secondary to merge conflicts (separate commits), rerere doesn't record automatic resolutions for them.

答:
If I understand correctly, you want a single merge commit: the upstream tree, including recent fixes, merged with your sync branch. So, that's what you should do: reset your sync branch to the commit prior to the original merge, then perform the merge again.

If you have made additional changes on your sync branch after the original merge but before the upstream fixes became available, you can rebase those commits onto the commit prior to the original merge first:

```<code>git checkout -b sync
git rebase --onto ${PREMERGECOMMIT} ${MERGECOMMIT}
git pull upstream master
</code>```

Body:
If I understand correctly, you want a single merge commit: the upstream tree, including recent fixes, merged with your sync branch. So, that's what you should do: reset your sync branch to the commit prior to the original merge, then perform the merge again.

If you have made additional changes on your sync branch after the original merge but before the upstream fixes became available, you can rebase those commits onto the commit prior to the original merge first:

git checkout -b sync
git rebase --onto ${PREMERGECOMMIT} ${MERGECOMMIT}
git pull upstream master


问:
Delete row based on id from another row in another table postgresql
In my test.users table, I have

```<code>id | email         | first_name
1  | john@site.com | John
2  | bob@site.com  | Bob
</code>```

In my test.questions table, I have

```<code>id  | user_id | answer
10  | 1       | true
11  | 2       | false
</code>```

I want to delete the row in test.questions where the user_id matches the id in test.users for one specific user only.

For example, if I want to delete the row with id 10 from test.questions (since that row corresponds to john@site.com in test.users), I can do

```<code>DELETE FROM test.questions WHERE answer = true AND user_id = 1
</code>```

This will delete only the row with id = 10 from test.questions, which is what I want.

The problem is that I don't want to hardcode the id.  I want to hardcode just the user's email in the query, and get the id dynamically.  Something like

```<code>DELETE FROM test.questions WHERE answer = true AND user_id = [the id of john@site.com from test.users, which is 1]
</code>```

答:
One method uses a subquery:

```<code>DELETE FROM test.questions
    WHERE answer = true AND
          user_id = (SELECT u.id
                     FROM users u
                     WHERE u.email = 'john@site.com'
                    );
</code>```

Or you can use USING:

```<code>DELETE FROM test.questions q
    USING users u
    WHERE u.id = q.user_id AND
          u.email = 'john@site.com';
</code>```

Body:
In my test.users table, I have

id | email         | first_name
1  | john@site.com | John
2  | bob@site.com  | Bob

In my test.questions table, I have

id  | user_id | answer
10  | 1       | true
11  | 2       | false

I want to delete the row in test.questions where the user_id matches the id in test.users for one specific user only.

For example, if I want to delete the row with id 10 from test.questions (since that row corresponds to john@site.com in test.users), I can do

DELETE FROM test.questions WHERE answer = true AND user_id = 1

This will delete only the row with id = 10 from test.questions, which is what I want.

The problem is that I don't want to hardcode the id.  I want to hardcode just the user's email in the query, and get the id dynamically.  Something like

DELETE FROM test.questions WHERE answer = true AND user_id = [the id of john@site.com from test.users, which is 1]

Body:
One method uses a subquery:

DELETE FROM test.questions
    WHERE answer = true AND
          user_id = (SELECT u.id
                     FROM users u
                     WHERE u.email = 'john@site.com'
                    );

Or you can use USING:

DELETE FROM test.questions q
    USING users u
    WHERE u.id = q.user_id AND
          u.email = 'john@site.com';


问:
how to post XML to URL in Javascript
how can i post this xml to url htttp://191.165.0.51:1024/LaunchRemoteXml.ashx in Javascript

```<code>           <Pipeline Name="MyTest">

                          <Task Name="EmailReport" Timeout="0" Enabled="true" OnFail="Abort" NotifyOnError="true" CodeBase="phynn.Workflow.TaskSmtp@workflow.base.dll">

                          <Smtp>

                                         <Message From="NoOne@directmailers.com" To="xyz@we.com" Subject="TestLaunch" IsHtml="false" Priority="Normal">

                                                        <Body>Hi</Body>

                                         </Message>

                          </Smtp>

                          </Task>

           </Pipeline>
</code>```

答:
Look on this site: https://www.webucator.com/how-to/how-send-receive-xml-data-from-the-server.cfm
Or use jquery </p>

Title: how to post XML to URL in Javascript

Body:
how can i post this xml to url htttp://191.165.0.51:1024/LaunchRemoteXml.ashx in Javascript

           <Pipeline Name="MyTest">

                          <Task Name="EmailReport" Timeout="0" Enabled="true" OnFail="Abort" NotifyOnError="true" CodeBase="phynn.Workflow.TaskSmtp@workflow.base.dll">

                          <Smtp>

                                         <Message From="NoOne@directmailers.com" To="xyz@we.com" Subject="TestLaunch" IsHtml="false" Priority="Normal">

                                                        Hi

                                         </Message>

                          </Smtp>

                          </Task>

           </Pipeline>


问:
scrape a table with rvest in R that has mismatch table heading
I'm trying to scrape this table which seems like it would be super simple.
Here's the url of the table: https://fantasy.nfl.com/research/scoringleaders?position=1&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek=1

Here's what I coded:

```<code>url <- "https://fantasy.nfl.com/research/scoringleaders?position=1&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek=1"
x = data.frame(read_html(url) %>%
  html_nodes("table") %>%
  html_table())
</code>```

This works ok but gives really weird two row headers and when I try to add %>% slice(-1) to take out the top row it says I can't because it's a list. Would really like to figure out how to do this.

Body:
I'm trying to scrape this table which seems like it would be super simple.
Here's the url of the table: https://fantasy.nfl.com/research/scoringleaders?position=1&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek=1

Here's what I coded:

url <- "https://fantasy.nfl.com/research/scoringleaders?position=1&sort=pts&statCategory=stats&statSeason=2019&statType=weekStats&statWeek=1"
x = data.frame(read_html(url) %>%
  html_nodes("table") %>%
  html_table())

This works ok but gives really weird two row headers and when I try to add %>% slice(-1) to take out the top row it says I can't because it's a list. Would really like to figure out how to do this.

Body:
Here's one solution. An explanation follows.

library(rvest)
library(tidyverse)

read_html(url) %>%
  html_nodes("table") %>%
  html_table(header = T) %>%
  simplify() %>%
  first() %>%
  setNames(paste0(colnames(.), as.character(.[1,]))) %>%
  slice(-1)

Output of glimpse():

Observations: 25
Variables: 16
$ Rank          <chr> "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"…
$ Player        <chr> "Lamar Jackson QB - BAL", "Dak Prescott QB - DAL", "Deshaun W…
$ Opp           <chr> "@MIA", "NYG", "@NO", "@ARI", "@JAX", "@PHI", "PIT", "WAS", "…
$ PassingYds    <chr> "324", "405", "268", "385", "378", "380", "341", "313", "248"…
$ PassingTD     <chr> "5", "4", "3", "3", "3", "3", "3", "3", "3", "3", "2", "2", "…
$ PassingInt    <chr> "-", "-", "1", "-", "-", "-", "-", "-", "-", "1", "1", "1", "…
$ RushingYds    <chr> "6", "12", "40", "22", "2", "-", "-", "5", "24", "6", "13", "…
$ RushingTD     <chr> "-", "-", "1", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ ReceivingRec  <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ ReceivingYds  <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ ReceivingTD   <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ RetTD         <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ MiscFumTD     <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ Misc2PT       <chr> "-", "-", "-", "-", "-", "-", "-", "-", "-", "-", "1", "-", "…
$ FumLost       <chr> "-", "-", "-", "1", "-", "-", "-", "-", "-", "-", "-", "-", "…
$ FantasyPoints <chr> "33.56", "33.40", "30.72", "27.60", "27.32", "27.20", "25.64"…

Explanation

From ?html_table docs:

html_table currently makes a few assumptions:

No cells span multiple rows

Headers are in the first row

Part of your problem is solved by setting header = TRUE in html_table().

Another part of the problem is that the header cells span two rows, which html_table() does not expect.

Assuming you don't want to lose the information in either header row, you can:

Use simplify and first to pull out the data frame from the list you get from html_table

Use setNames to merge the two header rows (which are now the data frame columns and the first row)

Remove the first row (now redundant) with slice


问:
how to edit model data using django forms
i'm new to django so i'm sorry for my newbie question

i have a model and i need to let user edit data inside it using django forms or any other way.

look at the image above , i want to show this form ready populated with the data and let user update  it.

what is the best way to do this ?

EDIT : here is my views.py code

```<code>def exam_Edit(request,examName,number=0):
    numner = int(number)
    number = int(number)
    questionNo = int(numner)
    Myexam = models.Exam.objects.get(name = examName)

    QuestionsAll = models.Question.objects.filter(exam = Myexam)

    myQeustion = Question.objects.filter(exam = Myexam)[nextQuestion]

    answer1 =  models.Asnwers.objects.filter(question=myQeustion)[0]
    answer2 =  models.Asnwers.objects.filter(question=myQeustion)[1]
    answer3 =  models.Asnwers.objects.filter(question=myQeustion)[2]
    answer4 = models.Asnwers.objects.filter(question=myQeustion)[3]

    # HERE IS MY PROBLEM : the line below creates a form with a data but it doesn't save it to the save object
    form = QuestionsEditForm(initial = {'questionText':myQeustion.__unicode__() , 'firstChoiceText':answer1.__unicode__(),'secondChoiceText':answer2.__unicode__(),'thirdChoiceText':answer3.__unicode__(),'forthChoiceText':answer4.__unicode__()})

    if request.method =='POST':
        #if post

        if form.is_valid():
            questionText = form.cleaned_data['questionText']
            Myexam = Exam.objects.get(name = examName)
            myQeustion.questionText = form.cleaned_data['questionText']

            answer1.answerText = form.cleaned_data['firstChoiceText']
            answer1.save()

            answer2.answerText = form.cleaned_data['secondChoiceText']
            answer2.save()

            answer3.answerText = form.cleaned_data['thirdChoiceText']
            answer3.save()

            answer4.answerText = form.cleaned_data['forthChoiceText']
            answer4.save()

 variables = RequestContext(request,     {'form':form,'examName':examName,'questionNo':str(nextQuestion)})
 return render_to_response('exam_edit.html',variables)
</code>```

please help

答:
Assuming you are using a ModelForm, use the instance keyword argument, and pass the model you are updating.

So, if you have MyModel and MyModelForm (the latter of which must extend django.forms.ModelForm), then your code snippet might look like:

```<code>my_record = MyModel.objects.get(id=XXX)
form = MyModelForm(instance=my_record)
</code>```

And then, when the user sends back data by POST:

```<code>form = MyModelForm(request.POST, instance=my_record)
</code>```

Incidentally, the documentation for ModelForm is here: http://docs.djangoproject.com/en/1.8/topics/forms/modelforms/

Body:
i'm new to django so i'm sorry for my newbie question

i have a model and i need to let user edit data inside it using django forms or any other way.

look at the image above , i want to show this form ready populated with the data and let user update  it.

what is the best way to do this ?

EDIT : here is my views.py code

def exam_Edit(request,examName,number=0):
    numner = int(number)
    number = int(number)
    questionNo = int(numner)
    Myexam = models.Exam.objects.get(name = examName)

    QuestionsAll = models.Question.objects.filter(exam = Myexam)

    myQeustion = Question.objects.filter(exam = Myexam)[nextQuestion]

    answer1 =  models.Asnwers.objects.filter(question=myQeustion)[0]
    answer2 =  models.Asnwers.objects.filter(question=myQeustion)[1]
    answer3 =  models.Asnwers.objects.filter(question=myQeustion)[2]
    answer4 = models.Asnwers.objects.filter(question=myQeustion)[3]

    # HERE IS MY PROBLEM : the line below creates a form with a data but it doesn't save it to the save object
    form = QuestionsEditForm(initial = {'questionText':myQeustion.__unicode__() , 'firstChoiceText':answer1.__unicode__(),'secondChoiceText':answer2.__unicode__(),'thirdChoiceText':answer3.__unicode__(),'forthChoiceText':answer4.__unicode__()})

    if request.method =='POST':
        #if post

        if form.is_valid():
            questionText = form.cleaned_data['questionText']
            Myexam = Exam.objects.get(name = examName)
            myQeustion.questionText = form.cleaned_data['questionText']

            answer1.answerText = form.cleaned_data['firstChoiceText']
            answer1.save()

            answer2.answerText = form.cleaned_data['secondChoiceText']
            answer2.save()

            answer3.answerText = form.cleaned_data['thirdChoiceText']
            answer3.save()

            answer4.answerText = form.cleaned_data['forthChoiceText']
            answer4.save()

 variables = RequestContext(request,     {'form':form,'examName':examName,'questionNo':str(nextQuestion)})
 return render_to_response('exam_edit.html',variables)

please help

Body:
Assuming you are using a ModelForm, use the instance keyword argument, and pass the model you are updating.

So, if you have MyModel and MyModelForm (the latter of which must extend django.forms.ModelForm), then your code snippet might look like:

my_record = MyModel.objects.get(id=XXX)
form = MyModelForm(instance=my_record)

And then, when the user sends back data by POST:

form = MyModelForm(request.POST, instance=my_record)

Incidentally, the documentation for ModelForm is here: http://docs.djangoproject.com/en/1.8/topics/forms/modelforms/


问:
How to apply several functions on every possible row combinations within a dataframe in R?
I've got a dataframe with coordinates (lon, lat)

```<code>    lon <- list(505997.627175236, 505997.627175236, 505997.627175236, 505997.627175236)
    lon <- do.call(rbind.data.frame, lon)

    lat <- list(7941821.025438220, 7941821.025438220, 7941821.025438220, 7941821.025438220)
    lat <- do.call(rbind.data.frame, lat)

    coord <- cbind(lon, lat)
    colnames(coord) <- c("lon", "lat")
</code>```

I'm trying to calculate the euclidian distance and the angle between all the possible row combinations within the dataframe.

```<code>     lon   lat       apply function on every possible combinations such as v1-v2, v1-v3, v1-v4,
v1   x1    y1        v2-v3 and so on...
v2   x2    y2
v3   x3    y3        here are the two functions applied beetween v1 and v2 :
v4   x4    y4        **euclidian distance**    sqrt((x1-x2)^2 + (y1-y2)^2)
                     **angle**                 atan2((y1-y2),(x1-x2))*(180/pi)
</code>```

How to apply several functions on every possible row combinations and get the results in respective lists ? My goal is to use these calculations at every iteration whatever the number of row in input.

Thanks in advance for your answers and sorry if the question seems silly. I've looked at so many posts but couldn't find a solution that I could understand and replicate.

答:
For fast Euclidean calculations, you can look at this

For the other function, you can do something like

```<code>atan2(outer(coord$lat, coord$lat, `-`), outer(coord$lon, coord$lon, `-`))*180/pi
</code>```

Body:
I've got a dataframe with coordinates (lon, lat)

    lon <- list(505997.627175236, 505997.627175236, 505997.627175236, 505997.627175236)
    lon <- do.call(rbind.data.frame, lon)

    lat <- list(7941821.025438220, 7941821.025438220, 7941821.025438220, 7941821.025438220)
    lat <- do.call(rbind.data.frame, lat)

    coord <- cbind(lon, lat)
    colnames(coord) <- c("lon", "lat")

I'm trying to calculate the euclidian distance and the angle between all the possible row combinations within the dataframe.

     lon   lat       apply function on every possible combinations such as v1-v2, v1-v3, v1-v4,
v1   x1    y1        v2-v3 and so on...
v2   x2    y2
v3   x3    y3        here are the two functions applied beetween v1 and v2 :
v4   x4    y4        **euclidian distance**    sqrt((x1-x2)^2 + (y1-y2)^2)
                     **angle**                 atan2((y1-y2),(x1-x2))*(180/pi)

How to apply several functions on every possible row combinations and get the results in respective lists ? My goal is to use these calculations at every iteration whatever the number of row in input.

Thanks in advance for your answers and sorry if the question seems silly. I've looked at so many posts but couldn't find a solution that I could understand and replicate.

Body:
For fast Euclidean calculations, you can look at this

For the other function, you can do something like

atan2(outer(coord$lat, coord$lat, `-`), outer(coord$lon, coord$lon, `-`))*180/pi


问:
What is the Time Complexity of my algorithm?
This algorithm was written for LeetCode's climbing stairs problem and it ran at 20ms. I believe the time complexity is O(n), because this link https://towardsdatascience.com/understanding-time-complexity-with-python-examples-2bda6e8158a7 said O(n) is when the running time increases linearly as the size of the input gets bigger, which is what I think is going on here.

I was wondering if someone could explain to me the the time complexity here and why it would be that. Any additional info on how I could get it to linear time if I'm not there already would help too.

Here is my code:

```<code>class Solution:
    def climbStairs(self, n: int) -> int:
        if n == 0: return 1

        else:
            temp = []

            for i in range(0, n + 1):
                temp.append(i)
                if temp[i] == 0:
                    temp[i] = 1
                elif temp[i] > 1:
                    temp[i] = temp[i-1] + temp[i-2]

            return temp[-1]
</code>```

答: A constant amount of work is done for each iteration (assuming append takes constant time); there are N iterations, hence O(n) time.

Body:
This algorithm was written for LeetCode's climbing stairs problem and it ran at 20ms. I believe the time complexity is O(n), because this link https://towardsdatascience.com/understanding-time-complexity-with-python-examples-2bda6e8158a7 said O(n) is when the running time increases linearly as the size of the input gets bigger, which is what I think is going on here.

I was wondering if someone could explain to me the the time complexity here and why it would be that. Any additional info on how I could get it to linear time if I'm not there already would help too.

Here is my code:

class Solution:
    def climbStairs(self, n: int) -> int:
        if n == 0: return 1

        else:
            temp = []

            for i in range(0, n + 1):
                temp.append(i)
                if temp[i] == 0:
                    temp[i] = 1
                elif temp[i] > 1:
                    temp[i] = temp[i-1] + temp[i-2]

            return temp[-1]


答:
In this case no difference.... but normal way is yyyy not YYYY see the code FromUnixTimestamp here

I am getting the same values for both formats. I think internally catalyst is taking care even if you are passing wrong formats...

See this example to demonstrate the behaviour:

```<code>package com.examples

import org.apache.log4j.{Level, Logger}
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._

object UnixTimestamp extends App {

  val spark: SparkSession = SparkSession.builder()
    .master("local")
    .appName("UnixTimestamp")
    .getOrCreate()
  Logger.getLogger("org").setLevel(Level.WARN)

  spark.sparkContext.setLogLevel("ERROR")

  import spark.sqlContext.implicits._

  //Convert unix timestamp to date
  val dateDF = Seq(1).toDF("seq").select(
    from_unixtime(unix_timestamp(), "MM-dd-yyyy").as("date_1"),
    from_unixtime(unix_timestamp(), "dd-MM-yyyy HH:mm:ss").as("date_2"),
    from_unixtime(unix_timestamp(), "yyyy-MM-dd").as("date_3"),
    from_unixtime(unix_timestamp(), "YYYY-MM-dd").as("date_4"),
    from_unixtime(lit(1577582583), "YYYY-MM-dd").as("yourdate1"), // your example date format 1
    from_unixtime(lit(1577582583), "yyyy-MM-dd").as("yourdate2")//// your example date format 2

  )
  dateDF.printSchema()
  dateDF.show(false)
  println("lets consider sql or hive way here of what you have done")
  spark.sql("select from_unixtime('1577582583',  'YYYY-MM-dd'), from_unixtime('1577582583',  'yyyy-MM-dd')").show
}
</code>```

Result : Here yourdate1 (YYYY-MM-dd) and yourdate2 (yyyy-MM-dd) are 2 different formats

```<code>root
|-- date_1: string (nullable = true)
|-- date_2: string (nullable = true)
|-- date_3: string (nullable = true)
|-- date_4: string (nullable = true)
|-- yourdate1: string (nullable = true)
|-- yourdate2: string (nullable = true)

+----------+-------------------+----------+----------+----------+----------+
|date_1    |date_2             |date_3    |date_4    |yourdate1 |yourdate2 |
+----------+-------------------+----------+----------+----------+----------+
|02-14-2020|14-02-2020 21:19:53|2020-02-14|2020-02-14|2019-12-28|2019-12-28|
+----------+-------------------+----------+----------+----------+----------+

lets consider sql or hive way here of what you have done
+-----------------------------------------------------+-----------------------------------------------------+
|from_unixtime(CAST(1577582583 AS BIGINT), YYYY-MM-dd)|from_unixtime(CAST(1577582583 AS BIGINT), yyyy-MM-dd)|
+-----------------------------------------------------+-----------------------------------------------------+
|                                           2019-12-28|                                           2019-12-28|
+-----------------------------------------------------+-----------------------------------------------------+

</code>```

Title: Spark-sql difference between 'YYYY-MM-dd' and 'yyyy-MM-dd' date formats

Body:
In this case no difference.... but normal way is yyyy not YYYY see the code FromUnixTimestamp here

I am getting the same values for both formats. I think internally catalyst is taking care even if you are passing wrong formats...

See this example to demonstrate the behaviour:

package com.examples

import org.apache.log4j.{Level, Logger}
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions._

object UnixTimestamp extends App {

  val spark: SparkSession = SparkSession.builder()
    .master("local")
    .appName("UnixTimestamp")
    .getOrCreate()
  Logger.getLogger("org").setLevel(Level.WARN)

  spark.sparkContext.setLogLevel("ERROR")

  import spark.sqlContext.implicits._

  //Convert unix timestamp to date
  val dateDF = Seq(1).toDF("seq").select(
    from_unixtime(unix_timestamp(), "MM-dd-yyyy").as("date_1"),
    from_unixtime(unix_timestamp(), "dd-MM-yyyy HH:mm:ss").as("date_2"),
    from_unixtime(unix_timestamp(), "yyyy-MM-dd").as("date_3"),
    from_unixtime(unix_timestamp(), "YYYY-MM-dd").as("date_4"),
    from_unixtime(lit(1577582583), "YYYY-MM-dd").as("yourdate1"), // your example date format 1
    from_unixtime(lit(1577582583), "yyyy-MM-dd").as("yourdate2")//// your example date format 2

  )
  dateDF.printSchema()
  dateDF.show(false)
  println("lets consider sql or hive way here of what you have done")
  spark.sql("select from_unixtime('1577582583',  'YYYY-MM-dd'), from_unixtime('1577582583',  'yyyy-MM-dd')").show
}

Result : Here yourdate1 (YYYY-MM-dd) and yourdate2 (yyyy-MM-dd) are 2 different formats

root
|-- date_1: string (nullable = true)
|-- date_2: string (nullable = true)
|-- date_3: string (nullable = true)
|-- date_4: string (nullable = true)
|-- yourdate1: string (nullable = true)
|-- yourdate2: string (nullable = true)

+----------+-------------------+----------+----------+----------+----------+
|date_1    |date_2             |date_3    |date_4    |yourdate1 |yourdate2 |
+----------+-------------------+----------+----------+----------+----------+
|02-14-2020|14-02-2020 21:19:53|2020-02-14|2020-02-14|2019-12-28|2019-12-28|
+----------+-------------------+----------+----------+----------+----------+

lets consider sql or hive way here of what you have done
+-----------------------------------------------------+-----------------------------------------------------+
|from_unixtime(CAST(1577582583 AS BIGINT), YYYY-MM-dd)|from_unixtime(CAST(1577582583 AS BIGINT), yyyy-MM-dd)|
+-----------------------------------------------------+-----------------------------------------------------+
|                                           2019-12-28|                                           2019-12-28|
+-----------------------------------------------------+-----------------------------------------------------+


答:
I would try one of these two methods:

def sort_list(lis):
    nums = [int(num) if isdigit(num) else float(num) for num in lis]

    nums = list(set(nums))
    nums.sort()

    return [str(i) for i in nums]  # I assumed you wanted them to be strings.
```

<p>The first will raise a <code>TypeError</code> if all items in <code>lis</code> are not <code>ints</code>, <code>floats</code>, or string representations of a number. The second method doesn't have that problem, but it's a bit wonkier.</p>

<pre class="lang-py prettyprint-override"><code>def sort_list(lis):
    ints = [int(num) for num in lis if num.isdigit()]
    floats = [float(num) for num in lis if not num.isdigit()]

    nums = ints.copy()
    nums.extend(floats)
    nums = list(set(nums))
    nums.sort()

    return [str(i) for i in nums]  # I assumed you wanted them to be strings.
</code>```

Hope this helps.

Title: Sort list of strings numerically and filter duplicates?

Body:
Given a list of strings in the following format:

[
    "464782,-100,4,3,1,100,0,0"
    "465042,-166.666666666667,4,3,1,100,0,0",
    "465825,-250.000000000001,4,3,1,100,0,0",
    "466868,-166.666666666667,4,3,1,100,0,0",
    "467390,-200.000000000001,4,3,1,100,0,0",
    "469999,-100,4,3,1,100,0,0",
    "470260,-166.666666666667,4,3,1,100,0,0",
    "474173,-100,4,3,1,100,0,0",
    "474434,-166.666666666667,4,3,1,100,0,0",
    "481477,-100,4,3,1,100,0,1",
    "531564,259.011439671919,4,3,1,60,1,0",
    "24369,-333.333333333335,4,3,1,100,0,0",
    "21082,410.958904109589,4,3,1,60,1,0",
    "21082,-250,4,3,1,100,0,0",
    "22725,-142.857142857143,4,3,1,100,0,0",
    "23547,-166.666666666667,4,3,1,100,0,0",
    "24369,-333.333333333335,4,3,1,100,0,0",
    "27657,-200.000000000001,4,3,1,100,0,0",
    "29301,-142.857142857143,4,3,1,100,0,0",
    "30123,-166.666666666667,4,3,1,100,0,0",
    "30945,-250,4,3,1,100,0,0",
    "32588,-166.666666666667,4,3,1,100,0,0",
    "34232,-250,4,3,1,100,0,0",
    "35876,-142.857142857143,4,3,1,100,0,0",
    "36698,-166.666666666667,4,3,1,100,0,0",
    "37520,-250,4,3,1,100,0,0",
    "42451,-142.857142857143,4,3,1,100,0,0",
    "43273,-166.666666666667,4,3,1,100,0,0",
]

How can I sort the list based on the first number in each line with python?
And then, once sorted, remove all duplicates, if any are there?

The sorting criteria for the list is the number before the first comma in each line, which is always an integer.

I tried using list.sort() , however, this sorts the items in lexical order, not numerically.

Body:
I would try one of these two methods:

def sort_list(lis):
    nums = [int(num) if isdigit(num) else float(num) for num in lis]

    nums = list(set(nums))
    nums.sort()

    return [str(i) for i in nums]  # I assumed you wanted them to be strings.

The first will raise a TypeError if all items in lis are not ints, floats, or string representations of a number. The second method doesn't have that problem, but it's a bit wonkier.

def sort_list(lis):
    ints = [int(num) for num in lis if num.isdigit()]
    floats = [float(num) for num in lis if not num.isdigit()]

    nums = ints.copy()
    nums.extend(floats)
    nums = list(set(nums))
    nums.sort()

    return [str(i) for i in nums]  # I assumed you wanted them to be strings.

Hope this helps.


问:
Excel equation to add hours to existing cell with date time data
How to add 8 hours to existing cell

the cell content is "2020-02-14 09:41:52"

Lets say my column is in A1

I've tried

```<code>=(A1)+8
</code>```

But I'm getting #VALUE!

答: If you are sure that your cell is formatted correctly as date time, then adding integers to date time values in Excel adds to the days. Trying =A1+8/24 should do the trick.

Body:
How to add 8 hours to existing cell

the cell content is "2020-02-14 09:41:52"

Lets say my column is in A1

I've tried

=(A1)+8

But I'm getting #VALUE!


问:
Formatting multiple arguments passed to a function in Java
Often the number of arguments passed to a function can be large. Consider the following case:

```<code>calculate(dataManager.getLastUpdate().getNumberOfChildren(),
          dataManager.getLastUpdate().getNumberOfParents(),
          dataManager.getLastUpdate().getNumberOfGrandChildren(),
          long milliseconds,
          int somethingelse)
</code>```

Is there a guideline in Java that offers a way to align the arguments? Fitting all arguments in a line would not look pretty.

答:
I might assign the return values of the getNumberOf*() methods to variables:</p>

```<code>SomeObject lastUpdate = dataManager.getLastUpdate();
int children = lastUpdate.getNumberOfChildren();
int parents = lastUpdate.getNumberOfParents();
int grandChildren = lastUpdate.getNumberOfGrandChildren();
calculate(children, parents, grandChildren, milliseconds, somethingelse);
</code>```

Body:
Often the number of arguments passed to a function can be large. Consider the following case:

calculate(dataManager.getLastUpdate().getNumberOfChildren(),
          dataManager.getLastUpdate().getNumberOfParents(),
          dataManager.getLastUpdate().getNumberOfGrandChildren(),
          long milliseconds,
          int somethingelse)

Is there a guideline in Java that offers a way to align the arguments? Fitting all arguments in a line would not look pretty.

Body:
I might assign the return values of the getNumberOf*() methods to variables:

SomeObject lastUpdate = dataManager.getLastUpdate();
int children = lastUpdate.getNumberOfChildren();
int parents = lastUpdate.getNumberOfParents();
int grandChildren = lastUpdate.getNumberOfGrandChildren();
calculate(children, parents, grandChildren, milliseconds, somethingelse);


问:
error installing "rgl" package, version 0.100.19 in anaconda/jupyter-notebook. Ubuntu 18.04
I like to install "rgl" package version 0.100.19 (since the other package depends on this version) in anaconda/jupyter notebook environment and received error.
configure: error: X11 not found but required, configure aborted

I tried
sudo apt-get install xorg
sudo apt-get install libx11-dev
sudo apt-get install libglu1-mesa-dev
sudo apt-get install libfreetype6-dev
sudo apt-get install r-cran-rgl
conda install -c conda-forge xorg-libx11
conda install -c anaconda mesa
but, they did not help yet.

install.packages("rgl")
configure: error: X11 not found but required, configure aborted

答:
I came across this problem, my solution was to:

```<code>$ conda install r-rgl
</code>```

It seems like the conda install goes to the conda R (see this with which R), and the way I found to get rgl installed on conda's R version was via conda install.

Body:
I came across this problem, my solution was to:

$ conda install r-rgl

It seems like the conda install goes to the conda R (see this with which R), and the way I found to get rgl installed on conda's R version was via conda install.


问:
Update WooCommerce stock status with SQL query if stock value is greater than 0
I'm attempting to update a large product catalogue using a SQL query via phpMyAdmin if:

the _stock_status = onbackorder

the _stock > 0

Queries attempted:

```<code>Update wp_postmeta
Set meta_value = 'instock'
Where meta_key = '_stock'
And meta_value > 0
</code>```

```<code>Update wp_postmeta
Set meta_value = 'instock'
Where meta_value = 'onbackorder'
And meta_key = '_stock_status'
And meta_value > 0
And meta_key = "_stock"
</code>```

```<code>Update wp_postmeta
Set meta_value = 'instock'
Where meta_value = 'onbackorder'
AND '_stock' > 0
</code>```

None of the above have worked.

The last query reduces all stock quantities to 0 but the stock status remains on "backorder"

答:
Instead of writing those queries, you should join the table wp_postmeta. Then you can fix it, for example:

```<code>update wp_postmeta as tb1 left join wp_postmeta as tb2 on tb1.post_id = tb2.post_id set tb1.meta_value = 'instock' where tb1.meta_key = '_stock_status' and tb1.meta_value = 'onbackorder' and tb2.meta_key = '_stock' and tb2.meta_value > 0
</code>```

Body:
I'm attempting to update a large product catalogue using a SQL query via phpMyAdmin if:

the _stock_status = onbackorder

the _stock > 0

Queries attempted:

Update wp_postmeta
Set meta_value = 'instock'
Where meta_key = '_stock'
And meta_value > 0

Update wp_postmeta
Set meta_value = 'instock'
Where meta_value = 'onbackorder'
And meta_key = '_stock_status'
And meta_value > 0
And meta_key = "_stock"

Update wp_postmeta
Set meta_value = 'instock'
Where meta_value = 'onbackorder'
AND '_stock' > 0

None of the above have worked.

The last query reduces all stock quantities to 0 but the stock status remains on "backorder"

Body:
Instead of writing those queries, you should join the table wp_postmeta. Then you can fix it, for example:

update wp_postmeta as tb1 left join wp_postmeta as tb2 on tb1.post_id = tb2.post_id set tb1.meta_value = 'instock' where tb1.meta_key = '_stock_status' and tb1.meta_value = 'onbackorder' and tb2.meta_key = '_stock' and tb2.meta_value > 0


问:
How to find first element in a column by group, that fulfills a condition? If the condition is fulfilled start the counter from 0 in R
I have a large dataset similar to this. I have been trying to add a counter from zero based on a condition of the first element in a column by group.
I want to get liked this:

```<code>ID YEAR STOf counter
1 2000 0     0
1 2001 1     0
1 2002 0     1
1 2003 0     2
2 2000 0     0
2 2001 0     0
2 2002 1     0
2 2003 0     1
2 2004 0     2
</code>```

I tried this code:

```<code>ov28<- ov27 %>% group_by(ID, idx = cumsum(STOf == 1L)) %>%
       mutate(counter = row_number()) %>%
       ungroup %>%
       select(-idx)
</code>```

The issue is: counter starts from 1 and the counter needs to start only based on condition as opposed to starting from the new id as well as condition. In short, I want the counter to start only if condition is satisfied, that too from 0.

Thanks!

答:
We can do a double cumsum after grouping by 'ID' and then take the lag of the output

```<code>library(dplyr)
ov27 %>%
   group_by(ID) %>%
   mutate(counter2 = lag(cumsum(cumsum(STOf == 1)), default = 0))
# A tibble: 9 x 5
# Groups:   ID [2]
#     ID  YEAR  STOf counter counter2
#  <int> <int> <int>   <int>    <dbl>
#1     1  2000     0       0        0
#2     1  2001     1       0        0
#3     1  2002     0       1        1
#4     1  2003     0       2        2
#5     2  2000     0       0        0
#6     2  2001     0       0        0
#7     2  2002     1       0        0
#8     2  2003     0       1        1
#9     2  2004     0       2        2
</code>```

Or create a logical condition and apply cumsum once

```<code>ov27 %>%
    group_by(ID) %>%
    mutate(counter2 = cumsum(row_number() > match(1, STOf)))
</code>```

If there are no matches i.e. no 1s in group, specify the nomatch = n()

```<code>ov27 %>%
 group_by(ID) %>%
 mutate(counter2 = cumsum(row_number() > match(1, STOf, nomatch = n())))
</code>```

NOTE: Both methods also work when there are no matches in a group

Or using the same logic with data.table

```<code>library(data.table)
setDT(ov27)[, counter2 := cumsum(seq_len(.N) > match(1, STOf)), ID]
</code>```

data

```<code>ov27 <- structure(list(ID = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), YEAR = c(2000L,
2001L, 2002L, 2003L, 2000L, 2001L, 2002L, 2003L, 2004L), STOf = c(0L,
1L, 0L, 0L, 0L, 0L, 1L, 0L, 0L), counter = c(0L, 0L, 1L, 2L,
0L, 0L, 0L, 1L, 2L)), class = "data.frame", row.names = c(NA,
-9L))
</code>```

Body:
I have a large dataset similar to this. I have been trying to add a counter from zero based on a condition of the first element in a column by group.
I want to get liked this:

ID YEAR STOf counter
1 2000 0     0
1 2001 1     0
1 2002 0     1
1 2003 0     2
2 2000 0     0
2 2001 0     0
2 2002 1     0
2 2003 0     1
2 2004 0     2

I tried this code:

ov28<- ov27 %>% group_by(ID, idx = cumsum(STOf == 1L)) %>%
       mutate(counter = row_number()) %>%
       ungroup %>%
       select(-idx)

The issue is: counter starts from 1 and the counter needs to start only based on condition as opposed to starting from the new id as well as condition. In short, I want the counter to start only if condition is satisfied, that too from 0.

Thanks!

Body:
We can do a double cumsum after grouping by 'ID' and then take the lag of the output

library(dplyr)
ov27 %>%
   group_by(ID) %>%
   mutate(counter2 = lag(cumsum(cumsum(STOf == 1)), default = 0))
# A tibble: 9 x 5
# Groups:   ID [2]
#     ID  YEAR  STOf counter counter2
#  <int> <int> <int>   <int>    <dbl>
#1     1  2000     0       0        0
#2     1  2001     1       0        0
#3     1  2002     0       1        1
#4     1  2003     0       2        2
#5     2  2000     0       0        0
#6     2  2001     0       0        0
#7     2  2002     1       0        0
#8     2  2003     0       1        1
#9     2  2004     0       2        2

Or create a logical condition and apply cumsum once

ov27 %>%
    group_by(ID) %>%
    mutate(counter2 = cumsum(row_number() > match(1, STOf)))

If there are no matches i.e. no 1s in group, specify the nomatch = n()

ov27 %>%
 group_by(ID) %>%
 mutate(counter2 = cumsum(row_number() > match(1, STOf, nomatch = n())))

NOTE: Both methods also work when there are no matches in a group

Or using the same logic with data.table

library(data.table)
setDT(ov27)[, counter2 := cumsum(seq_len(.N) > match(1, STOf)), ID]

data

ov27 <- structure(list(ID = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), YEAR = c(2000L,
2001L, 2002L, 2003L, 2000L, 2001L, 2002L, 2003L, 2004L), STOf = c(0L,
1L, 0L, 0L, 0L, 0L, 1L, 0L, 0L), counter = c(0L, 0L, 1L, 2L,
0L, 0L, 0L, 1L, 2L)), class = "data.frame", row.names = c(NA,
-9L))


问:
How do I make images the same height in a flexbox side-by-side, without knowing their dimensions
I would want to make 2 images with different widths, displayed the same height side-by-side, ideally in a flex box.

The following works if I know the image dimensions (962x706 and 962x1275).

Is there a way to do this without knowing their dimensions?

```<code><div style="display: flex; margin: 0 -5px">
    <div style="flex: calc(962/706); margin: 0 5px">
        <img src="https://i.stack.imgur.com/H7QKE.jpg"/>
    </div>
    <div style="flex: calc(962/1275); margin: 0 5px">
        <img src="https://i.stack.imgur.com/nsyuX.jpg"/>
    </div>
</div>
</code>```

```<code>img {
  width: 100%;
}
</code>```

A fiddle for convenience https://jsfiddle.net/b1f6v3kc/

答:
Setting a minimum height with object fit would crop the image, avoiding distortion

img {
  width: 100%;
  min-height: 300px;
  height: 100%;
  object-fit: cover;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="display: flex; margin: 0 -5px">
    <div style=" margin: 0 5px">
        <img src="https://i.stack.imgur.com/nsyuX.jpg"/>
    </div>
    <div style=" margin: 0 5px">
        <img src="https://i.stack.imgur.com/H7QKE.jpg"/>
    </div>
</div></code>```

Body:
I would want to make 2 images with different widths, displayed the same height side-by-side, ideally in a flex box.

The following works if I know the image dimensions (962x706 and 962x1275).

Is there a way to do this without knowing their dimensions?

img {
  width: 100%;
}

A fiddle for convenience https://jsfiddle.net/b1f6v3kc/

Body:
Setting a minimum height with object fit would crop the image, avoiding distortion

img {
  width: 100%;
  min-height: 300px;
  height: 100%;
  object-fit: cover;

}

<div style="display: flex; margin: 0 -5px">
    <div style=" margin: 0 5px">
        <img src="https://i.stack.imgur.com/nsyuX.jpg"/>
    </div>
    <div style=" margin: 0 5px">
        <img src="https://i.stack.imgur.com/H7QKE.jpg"/>
    </div>
</div>


问:
MongoDB update and insert on an array
I have a mongo document as shown below :

```<code>{
  "ITEMS": [
    {
      "BUKRS": "1000",
      "GLACC": "476000",
      "NETWR": 100
    }
  ],
  "EXCEPTIONS": [
    {
      "CURR": true,
      "EVENT": "WEB",
      "DATE_TIME": "2020-02-08T22:46:29.219Z"
    },
    {
      "CURR": true,
      "EVENT": "WEB",
      "DATE_TIME": "2020-02-08T22:46:29.219Z"
    },
    {
      "CURR": false,
      "EVENT": "WEB",
      "DATE_TIME": "2020-02-08T22:46:29.219Z"
    }
  ]
}
</code>```

What I need to achieve is in one mongo query, set all EXCEPTIONS.$.CURR:false and insert a new object into EXCEPTIONS array with mostly CURR : true.

答:
You can do it in one DB call using .bulkWrite() for MongoDB version's >= 3.2 :

```<code>db.collection.bulkWrite([{
    updateOne: {
        "filter": {}, // If you've any filters to match a doc give it here
        "update": { $set: { "EXCEPTIONS.$[].CURR": false } } // $[] operator updates all elements in an array.
    }
}, {
    updateOne: {
        "filter": {},
        "update": {
            $push: {
                "EXCEPTIONS": {
                    "CURR": true,
                    "EVENT": "WEB",
                    "DATE_TIME": "New_Time"
                }
            }
        }
    }
}])
</code>```

Document in DB :

```<code>/* 1 */
{
    "_id" : ObjectId("5e475da77f8bc30a7504f0b6"),
    "ITEMS" : [
        {
            "BUKRS" : "1000",
            "GLACC" : "476000",
            "NETWR" : 100
        }
    ],
    "EXCEPTIONS" : [
        {
            "CURR" : true,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        },
        {
            "CURR" : true,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        },
        {
            "CURR" : false,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        }
    ]
}
</code>```

Response :

```<code>/* 1 */
{
    "acknowledged" : true,
    "deletedCount" : 0.0,
    "insertedCount" : 0.0,
    "matchedCount" : 2.0, // It's 2 as it modified array/doc twice
    "upsertedCount" : 0.0,
    "insertedIds" : {},
    "upsertedIds" : {}
}
</code>```

Result in DB :

```<code>/* 1 */
{
    "_id" : ObjectId("5e475da77f8bc30a7504f0b6"),
    "ITEMS" : [
        {
            "BUKRS" : "1000",
            "GLACC" : "476000",
            "NETWR" : 100
        }
    ],
    "EXCEPTIONS" : [
        {
            "CURR" : false,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        },
        {
            "CURR" : false,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        },
        {
            "CURR" : false,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        },
        {
            "CURR" : true,
            "EVENT" : "WEB",
            "DATE_TIME" : "New_Time"
        }
    ]
}
</code>```

Title: MongoDB update and insert on an array

Body:
I have a mongo document as shown below :

{
  "ITEMS": [
    {
      "BUKRS": "1000",
      "GLACC": "476000",
      "NETWR": 100
    }
  ],
  "EXCEPTIONS": [
    {
      "CURR": true,
      "EVENT": "WEB",
      "DATE_TIME": "2020-02-08T22:46:29.219Z"
    },
    {
      "CURR": true,
      "EVENT": "WEB",
      "DATE_TIME": "2020-02-08T22:46:29.219Z"
    },
    {
      "CURR": false,
      "EVENT": "WEB",
      "DATE_TIME": "2020-02-08T22:46:29.219Z"
    }
  ]
}

What I need to achieve is in one mongo query, set all EXCEPTIONS.$.CURR:false and insert a new object into EXCEPTIONS array with mostly CURR : true.

Body:
You can do it in one DB call using .bulkWrite() for MongoDB version's >= 3.2 :

db.collection.bulkWrite([{
    updateOne: {
        "filter": {}, // If you've any filters to match a doc give it here
        "update": { $set: { "EXCEPTIONS.$[].CURR": false } } // $[] operator updates all elements in an array.
    }
}, {
    updateOne: {
        "filter": {},
        "update": {
            $push: {
                "EXCEPTIONS": {
                    "CURR": true,
                    "EVENT": "WEB",
                    "DATE_TIME": "New_Time"
                }
            }
        }
    }
}])

Document in DB :

/* 1 */
{
    "_id" : ObjectId("5e475da77f8bc30a7504f0b6"),
    "ITEMS" : [
        {
            "BUKRS" : "1000",
            "GLACC" : "476000",
            "NETWR" : 100
        }
    ],
    "EXCEPTIONS" : [
        {
            "CURR" : true,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        },
        {
            "CURR" : true,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        },
        {
            "CURR" : false,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        }
    ]
}

Response :

/* 1 */
{
    "acknowledged" : true,
    "deletedCount" : 0.0,
    "insertedCount" : 0.0,
    "matchedCount" : 2.0, // It's 2 as it modified array/doc twice
    "upsertedCount" : 0.0,
    "insertedIds" : {},
    "upsertedIds" : {}
}

Result in DB :

/* 1 */
{
    "_id" : ObjectId("5e475da77f8bc30a7504f0b6"),
    "ITEMS" : [
        {
            "BUKRS" : "1000",
            "GLACC" : "476000",
            "NETWR" : 100
        }
    ],
    "EXCEPTIONS" : [
        {
            "CURR" : false,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        },
        {
            "CURR" : false,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        },
        {
            "CURR" : false,
            "EVENT" : "WEB",
            "DATE_TIME" : "2020-02-08T22:46:29.219Z"
        },
        {
            "CURR" : true,
            "EVENT" : "WEB",
            "DATE_TIME" : "New_Time"
        }
    ]
}


问:
How to get the content of a Tinymce textarea with JavaScript
i have an array of content then how we get content of Tinymce textarea in javascript</p>

答:
This work for me for version 4 (9.8):</p>

```<code>var Content = tinyMCE.editors['Your_ID'].getContent();
</code>```

Body:
This work for me for version 4 (9.8):

var Content = tinyMCE.editors['Your_ID'].getContent();


问:
Could not locate the assembly "System.Fabric"
Seeing the following build warning in command prompt,

D:\CxCache\MsBuild.Corext.14.0.23107.9\v14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3245: Coul d not resolve this reference. Could not locate
  the assembly "System.Fabric". Check to make sure the assembly exists
  on disk. If this reference is required by your code, you may get
  compilation errors.

followed by the error,

D:\CxCache\MsBuild.Corext.14.0.23107.9\v14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3245: Could not resolve this reference. Could not locate
  the assembly "System.Fabric". Check to make sure the assembly exists
  on disk. If this reference is required by your code, you may get
  compilation errors.        For SearchPath
  "{TargetFrameworkDirectory}".
                   Considered "D:\CxCache\DotNetFxRefAssemblies.Corext.4.6.0\System.Fabric.dll", but
  it didn't exist.
                   Considered "D:\CxCache\DotNetFxRefAssemblies.Corext.4.6.0\System.Fabric.exe", but
  it didn't exist.

My change,

From:

package id="Microsoft.ServiceFabric" version="5.2.207"

To:

package id="Microsoft.ServiceFabric" version="6.3.187"

I am new to Nuget and msbuild. Looking for starting pointers...Please help.

答:
Okay, I did some research and nuget has Microsoft.ServiceFabric there are 2 ways to do this. Open the Package Manager (nuget) console, or open nuget package manager.
The Package Manager is located in visual studio (Tools > Nuget Package Manager > Package Manager) and/or around that area, that one is easy to look up. For installing you want to enter this into your package manager.

[Install-Package Microsoft.ServiceFabric -Version 7.0.466] or any version that follow in your visual studio project. Looking on nuget (dot) org you can find it easily and all the accepted versions, I already said this and I'll say it again. Be sure to be in your project when you do this and the reference will be added.


问:
Convert JPG to PNG
I have used the below code to

convert JPG into PNG file:

But when i am running this code from the command line terminal using: python a.py "C:\Users\nishant.gupta2\PycharmProjects\jpgtopngconverter\photo" new

The system is giving me the error:

```<code> PermissionError: [Errno 13] Permission denied: 'C:\\Users\\nishant.gupta2\\PycharmProjects\\jpgtopngconverter\\photo'
</code>```

My code is below:

```<code>import sys
import os
from PIL import Image

image_folder=sys.argv[1]

output_folder=sys.argv[2]

if not os.path.exists(output_folder):
    os.mkdir(output_folder)

for items in os.listdir(image_folder):

    im= Image.open(f'{image_folder}')
    im.save(f'{output_folder}.png','png')
</code>```

答: It looks like this has to do with file permissions rather than your code. Your code is running under a separate user than the image folder you are specifying, depending on admin status you may get permission issues.</p>

Title: Convert JPG to PNG

Body:
I have used the below code to

convert JPG into PNG file:

But when i am running this code from the command line terminal using: python a.py "C:\Users\nishant.gupta2\PycharmProjects\jpgtopngconverter\photo" new

The system is giving me the error:

 PermissionError: [Errno 13] Permission denied: 'C:\\Users\\nishant.gupta2\\PycharmProjects\\jpgtopngconverter\\photo'

My code is below:

import sys
import os
from PIL import Image

image_folder=sys.argv[1]

output_folder=sys.argv[2]

if not os.path.exists(output_folder):
    os.mkdir(output_folder)

for items in os.listdir(image_folder):

    im= Image.open(f'{image_folder}')
    im.save(f'{output_folder}.png','png')


问:
Ending a Program Mid-Run
pythoncom.PumpMessages()

From what I understand this line basically tells the program to wait forever. For my purposes it seems to be working. However, I'd like to be able to end the program given the right stimulus. How would one go about ending the above line, or stopping the program from running any further.

答:
According to these docs, pythoncom.PumpMessages():

Pumps all messages for the current thread until a WM_QUIT message.

So one way to stop collecting messages is by posting a WM_QUIT message to the message queue by using the ctypes library to call PostQuitMessage:

```<code>ctypes.windll.user32.PostQuitMessage(0)
</code>```

Title: Ending a Program Mid-Run

Body:
According to these docs, pythoncom.PumpMessages():

Pumps all messages for the current thread until a WM_QUIT message.

So one way to stop collecting messages is by posting a WM_QUIT message to the message queue by using the ctypes library to call PostQuitMessage:

ctypes.windll.user32.PostQuitMessage(0)