问:
Posting httr request to API with xmlquery in body
I am trying to retrieve data from an API with stock data from this site: nasdaqomxnordic.com.

So far, I have succesfully constructed a curl call by inspecting the page in Google Chrome. The curl call works great when I send it from reqbin.com and I receive the expected data.

However, when I try to translate it into an httr request in R, I can't make it work. It seems that httr connects succesfully to the server, but nothing happens after that - the command just keeps running forever in r, until I cancel it manually. I suspect that the issue lies in how the body of the request (the xmlquery) is sent so I have tried various formats and tried curlconverter.com, but with no luck (see code below).

Do you guys have any idea about what could be wrong?

The curl code looks like this (this works perfectly on reqbin.com):

```<code>curl 'https://www.nasdaqomxnordic.com/webproxy/DataFeedProxy.aspx' \
  -H 'authority: www.nasdaqomxnordic.com' \
  -H 'accept: */*' \
  -H 'accept-language: se-SE,se;q=0.9,en-US;q=0.8,en;q=0.7' \
  -H 'content-type: application/x-www-form-urlencoded; charset=UTF-8' \
  -H 'origin: https://www.nasdaqomxnordic.com' \
  -H 'referer: https://www.nasdaqomxnordic.com/aktier/microsite?Instrument=CSE1158&name=Novo%20Nordisk%20B&ISIN=DK0060534915' \
  -H 'sec-ch-ua: "Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "Windows"' \
  -H 'sec-fetch-dest: empty' \
  -H 'sec-fetch-mode: cors' \
  -H 'sec-fetch-site: same-origin' \
  -H 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36' \
  -H 'x-requested-with: XMLHttpRequest' \
  --data-raw 'xmlquery=%3Cpost%3E%0A%3Cparam+name%3D%22Exchange%22+value%3D%22NMF%22%2F%3E%0A%3Cparam+name%3D%22SubSystem%22+value%3D%22History%22%2F%3E%0A%3Cparam+name%3D%22Action%22+value%3D%22GetDataSeries%22%2F%3E%0A%3Cparam+name%3D%22AppendIntraDay%22+value%3D%22no%22%2F%3E%0A%3Cparam+name%3D%22Instrument%22+value%3D%22CSE1158%22%2F%3E%0A%3Cparam+name%3D%22FromDate%22+value%3D%222021-12-25%22%2F%3E%0A%3Cparam+name%3D%22ToDate%22+value%3D%222022-12-25%22%2F%3E%0A%3Cparam+name%3D%22hi__a%22+value%3D%220%2C5%2C6%2C3%2C1%2C2%2C4%2C21%2C8%2C10%2C12%2C9%2C11%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt%22+value%3D%22%2FnordicV3%2Fhi_csv.xsl%22%2F%3E%0A%3Cparam+name%3D%22OmitNoTrade%22+value%3D%22true%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_lang%22+value%3D%22en%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_options%22+value%3D%22%2Cadjusted%2C%22%2F%3E%0A%3Cparam+name%3D%22ext_contenttype%22+value%3D%22application%2Fms-excel%22%2F%3E%0A%3Cparam+name%3D%22ext_contenttypefilename%22+value%3D%22NOVO_B-2021-12-25-2022-12-25.csv%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_hiddenattrs%22+value%3D%22%2Civ%2Cip%2C%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_tableId%22+value%3D%22historicalTable%22%2F%3E%0A%3Cparam+name%3D%22DefaultDecimals%22+value%3D%22false%22%2F%3E%0A%3Cparam+name%3D%22app%22+value%3D%22%2Faktier%2Fmicrosite%22%2F%3E%0A%3C%2Fpost%3E' \
  --compressed
</code>```

My best try at an httr equivalent look like this:

```<code>require(httr)

headers = c(
  `authority` = 'www.nasdaqomxnordic.com',
  `accept` = '*/*',
  `accept-language` = 'se-SE,se;q=0.9,en-US;q=0.8,en;q=0.7',
  `content-type` = 'application/x-www-form-urlencoded; charset=UTF-8',
  `origin` = 'https://www.nasdaqomxnordic.com',
  `referer` = 'https://www.nasdaqomxnordic.com/aktier/microsite?Instrument=CSE1158&name=Novo%20Nordisk%20B&ISIN=DK0060534915',
  `sec-ch-ua` = '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
  `sec-ch-ua-mobile` = '?0',
  `sec-ch-ua-platform` = '"Windows"',
  `sec-fetch-dest` = 'empty',
  `sec-fetch-mode` = 'cors',
  `sec-fetch-site` = 'same-origin',
  `user-agent` = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',
  `x-requested-with` = 'XMLHttpRequest'
)

data = 'xmlquery=%3Cpost%3E%0A%3Cparam+name%3D%22Exchange%22+value%3D%22NMF%22%2F%3E%0A%3Cparam+name%3D%22SubSystem%22+value%3D%22History%22%2F%3E%0A%3Cparam+name%3D%22Action%22+value%3D%22GetDataSeries%22%2F%3E%0A%3Cparam+name%3D%22AppendIntraDay%22+value%3D%22no%22%2F%3E%0A%3Cparam+name%3D%22Instrument%22+value%3D%22CSE1158%22%2F%3E%0A%3Cparam+name%3D%22FromDate%22+value%3D%222021-12-25%22%2F%3E%0A%3Cparam+name%3D%22ToDate%22+value%3D%222022-12-25%22%2F%3E%0A%3Cparam+name%3D%22hi__a%22+value%3D%220%2C5%2C6%2C3%2C1%2C2%2C4%2C21%2C8%2C10%2C12%2C9%2C11%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt%22+value%3D%22%2FnordicV3%2Fhi_csv.xsl%22%2F%3E%0A%3Cparam+name%3D%22OmitNoTrade%22+value%3D%22true%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_lang%22+value%3D%22en%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_options%22+value%3D%22%2Cadjusted%2C%22%2F%3E%0A%3Cparam+name%3D%22ext_contenttype%22+value%3D%22application%2Fms-excel%22%2F%3E%0A%3Cparam+name%3D%22ext_contenttypefilename%22+value%3D%22NOVO_B-2021-12-25-2022-12-25.csv%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_hiddenattrs%22+value%3D%22%2Civ%2Cip%2C%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_tableId%22+value%3D%22historicalTable%22%2F%3E%0A%3Cparam+name%3D%22DefaultDecimals%22+value%3D%22false%22%2F%3E%0A%3Cparam+name%3D%22app%22+value%3D%22%2Faktier%2Fmicrosite%22%2F%3E%0A%3C%2Fpost%3E'

http_response <- httr::POST(url = 'https://www.nasdaqomxnordic.com/webproxy/DataFeedProxy.aspx', httr::add_headers(.headers=headers), body = data, verbose())

</code>```

I have also tried this alternate formatting of the data-part of the request, but with no better luck:

```<code>data = list(
  `xmlquery` = '<post>\n<param name="Exchange" value="NMF"/>\n<param name="SubSystem" value="History"/>\n<param name="Action" value="GetDataSeries"/>\n<param name="AppendIntraDay" value="no"/>\n<param name="Instrument" value="CSE1158"/>\n<param name="FromDate" value="2021-12-25"/>\n<param name="ToDate" value="2022-12-25"/>\n<param name="hi__a" value="0,5,6,3,1,2,4,21,8,10,12,9,11"/>\n<param name="ext_xslt" value="/nordicV3/hi_csv.xsl"/>\n<param name="OmitNoTrade" value="true"/>\n<param name="ext_xslt_lang" value="en"/>\n<param name="ext_xslt_options" value=",adjusted,"/>\n<param name="ext_contenttype" value="application/ms-excel"/>\n<param name="ext_contenttypefilename" value="NOVO_B-2021-12-25-2022-12-25.csv"/>\n<param name="ext_xslt_hiddenattrs" value=",iv,ip,"/>\n<param name="ext_xslt_tableId" value="historicalTable"/>\n<param name="DefaultDecimals" value="false"/>\n<param name="app" value="/aktier/microsite"/>\n</post>'
)
```
```

Body:
I am trying to retrieve data from an API with stock data from this site: nasdaqomxnordic.com.

So far, I have succesfully constructed a curl call by inspecting the page in Google Chrome. The curl call works great when I send it from reqbin.com and I receive the expected data.

However, when I try to translate it into an httr request in R, I can't make it work. It seems that httr connects succesfully to the server, but nothing happens after that - the command just keeps running forever in r, until I cancel it manually. I suspect that the issue lies in how the body of the request (the xmlquery) is sent so I have tried various formats and tried curlconverter.com, but with no luck (see code below).

Do you guys have any idea about what could be wrong?

The curl code looks like this (this works perfectly on reqbin.com):

curl 'https://www.nasdaqomxnordic.com/webproxy/DataFeedProxy.aspx' \
  -H 'authority: www.nasdaqomxnordic.com' \
  -H 'accept: */*' \
  -H 'accept-language: se-SE,se;q=0.9,en-US;q=0.8,en;q=0.7' \
  -H 'content-type: application/x-www-form-urlencoded; charset=UTF-8' \
  -H 'origin: https://www.nasdaqomxnordic.com' \
  -H 'referer: https://www.nasdaqomxnordic.com/aktier/microsite?Instrument=CSE1158&name=Novo%20Nordisk%20B&ISIN=DK0060534915' \
  -H 'sec-ch-ua: "Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'sec-ch-ua-platform: "Windows"' \
  -H 'sec-fetch-dest: empty' \
  -H 'sec-fetch-mode: cors' \
  -H 'sec-fetch-site: same-origin' \
  -H 'user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36' \
  -H 'x-requested-with: XMLHttpRequest' \
  --data-raw 'xmlquery=%3Cpost%3E%0A%3Cparam+name%3D%22Exchange%22+value%3D%22NMF%22%2F%3E%0A%3Cparam+name%3D%22SubSystem%22+value%3D%22History%22%2F%3E%0A%3Cparam+name%3D%22Action%22+value%3D%22GetDataSeries%22%2F%3E%0A%3Cparam+name%3D%22AppendIntraDay%22+value%3D%22no%22%2F%3E%0A%3Cparam+name%3D%22Instrument%22+value%3D%22CSE1158%22%2F%3E%0A%3Cparam+name%3D%22FromDate%22+value%3D%222021-12-25%22%2F%3E%0A%3Cparam+name%3D%22ToDate%22+value%3D%222022-12-25%22%2F%3E%0A%3Cparam+name%3D%22hi__a%22+value%3D%220%2C5%2C6%2C3%2C1%2C2%2C4%2C21%2C8%2C10%2C12%2C9%2C11%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt%22+value%3D%22%2FnordicV3%2Fhi_csv.xsl%22%2F%3E%0A%3Cparam+name%3D%22OmitNoTrade%22+value%3D%22true%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_lang%22+value%3D%22en%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_options%22+value%3D%22%2Cadjusted%2C%22%2F%3E%0A%3Cparam+name%3D%22ext_contenttype%22+value%3D%22application%2Fms-excel%22%2F%3E%0A%3Cparam+name%3D%22ext_contenttypefilename%22+value%3D%22NOVO_B-2021-12-25-2022-12-25.csv%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_hiddenattrs%22+value%3D%22%2Civ%2Cip%2C%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_tableId%22+value%3D%22historicalTable%22%2F%3E%0A%3Cparam+name%3D%22DefaultDecimals%22+value%3D%22false%22%2F%3E%0A%3Cparam+name%3D%22app%22+value%3D%22%2Faktier%2Fmicrosite%22%2F%3E%0A%3C%2Fpost%3E' \
  --compressed

My best try at an httr equivalent look like this:

require(httr)

headers = c(
  `authority` = 'www.nasdaqomxnordic.com',
  `accept` = '*/*',
  `accept-language` = 'se-SE,se;q=0.9,en-US;q=0.8,en;q=0.7',
  `content-type` = 'application/x-www-form-urlencoded; charset=UTF-8',
  `origin` = 'https://www.nasdaqomxnordic.com',
  `referer` = 'https://www.nasdaqomxnordic.com/aktier/microsite?Instrument=CSE1158&name=Novo%20Nordisk%20B&ISIN=DK0060534915',
  `sec-ch-ua` = '"Not?A_Brand";v="8", "Chromium";v="108", "Google Chrome";v="108"',
  `sec-ch-ua-mobile` = '?0',
  `sec-ch-ua-platform` = '"Windows"',
  `sec-fetch-dest` = 'empty',
  `sec-fetch-mode` = 'cors',
  `sec-fetch-site` = 'same-origin',
  `user-agent` = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36',
  `x-requested-with` = 'XMLHttpRequest'
)

data = 'xmlquery=%3Cpost%3E%0A%3Cparam+name%3D%22Exchange%22+value%3D%22NMF%22%2F%3E%0A%3Cparam+name%3D%22SubSystem%22+value%3D%22History%22%2F%3E%0A%3Cparam+name%3D%22Action%22+value%3D%22GetDataSeries%22%2F%3E%0A%3Cparam+name%3D%22AppendIntraDay%22+value%3D%22no%22%2F%3E%0A%3Cparam+name%3D%22Instrument%22+value%3D%22CSE1158%22%2F%3E%0A%3Cparam+name%3D%22FromDate%22+value%3D%222021-12-25%22%2F%3E%0A%3Cparam+name%3D%22ToDate%22+value%3D%222022-12-25%22%2F%3E%0A%3Cparam+name%3D%22hi__a%22+value%3D%220%2C5%2C6%2C3%2C1%2C2%2C4%2C21%2C8%2C10%2C12%2C9%2C11%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt%22+value%3D%22%2FnordicV3%2Fhi_csv.xsl%22%2F%3E%0A%3Cparam+name%3D%22OmitNoTrade%22+value%3D%22true%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_lang%22+value%3D%22en%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_options%22+value%3D%22%2Cadjusted%2C%22%2F%3E%0A%3Cparam+name%3D%22ext_contenttype%22+value%3D%22application%2Fms-excel%22%2F%3E%0A%3Cparam+name%3D%22ext_contenttypefilename%22+value%3D%22NOVO_B-2021-12-25-2022-12-25.csv%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_hiddenattrs%22+value%3D%22%2Civ%2Cip%2C%22%2F%3E%0A%3Cparam+name%3D%22ext_xslt_tableId%22+value%3D%22historicalTable%22%2F%3E%0A%3Cparam+name%3D%22DefaultDecimals%22+value%3D%22false%22%2F%3E%0A%3Cparam+name%3D%22app%22+value%3D%22%2Faktier%2Fmicrosite%22%2F%3E%0A%3C%2Fpost%3E'

http_response <- httr::POST(url = 'https://www.nasdaqomxnordic.com/webproxy/DataFeedProxy.aspx', httr::add_headers(.headers=headers), body = data, verbose())

I have also tried this alternate formatting of the data-part of the request, but with no better luck:

data = list(
  `xmlquery` = '<post>\n<param name="Exchange" value="NMF"/>\n<param name="SubSystem" value="History"/>\n<param name="Action" value="GetDataSeries"/>\n<param name="AppendIntraDay" value="no"/>\n<param name="Instrument" value="CSE1158"/>\n<param name="FromDate" value="2021-12-25"/>\n<param name="ToDate" value="2022-12-25"/>\n<param name="hi__a" value="0,5,6,3,1,2,4,21,8,10,12,9,11"/>\n<param name="ext_xslt" value="/nordicV3/hi_csv.xsl"/>\n<param name="OmitNoTrade" value="true"/>\n<param name="ext_xslt_lang" value="en"/>\n<param name="ext_xslt_options" value=",adjusted,"/>\n<param name="ext_contenttype" value="application/ms-excel"/>\n<param name="ext_contenttypefilename" value="NOVO_B-2021-12-25-2022-12-25.csv"/>\n<param name="ext_xslt_hiddenattrs" value=",iv,ip,"/>\n<param name="ext_xslt_tableId" value="historicalTable"/>\n<param name="DefaultDecimals" value="false"/>\n<param name="app" value="/aktier/microsite"/>\n</post>'
)
```


来源: stackexchange

问:
woocommerce how add custom data to cart with Ajax
I'm trying to add custom data to woocommerce fragment with ajax, but I don't know how to pass it properly. I found topic with similar question, but it doesn't work for me.

https://stackoverflow.com/questions/61632687/woocommerce-ajax-add-to-cart-with-additional-custom-data

this is my jquery

```<code>jQuery(document).ready(function($) {
    $('.single_add_to_cart_button').on('click', function(e){
    e.preventDefault();
    var thisbutton = $(this),
                $form = thisbutton.closest('form.cart'),
                id = thisbutton.val(),
                product_qty = $form.find('input[name=quantity]').val() || 1,
                product_id = $form.find('input[name=product_id]').val() || id,
                variation_id = $form.find('input[name=variation_id]').val() || 0;
    var data = {
            action: 'ql_woocommerce_ajax_add_to_cart',
            product_id: product_id,
            product_sku: '',
            quantity: product_qty,
            variation_id: variation_id,
            name: 'Tom',
        };
    $.ajax({
            type: 'post',
            url: wc_add_to_cart_params.ajax_url,
            data: data,
            beforeSend: function (response) {
                thisbutton.removeClass('added').addClass('loading');
            },
            complete: function (response) {
                thisbutton.addClass('added').removeClass('loading');
            },
            success: function (response) {
                if (response.error & response.product_url) {
                    window.location = response.product_url;
                    return;
                } else {
                    $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, thisbutton]);
                }
                console.log( wc_add_to_cart_params.ajax_url, data);
            },
        });
     });
});

</code>```

this is my function

```<code>add_action('wp_ajax_ql_woocommerce_ajax_add_to_cart', 'ql_woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_ql_woocommerce_ajax_add_to_cart', 'ql_woocommerce_ajax_add_to_cart');
function ql_woocommerce_ajax_add_to_cart() {

    $product_id = apply_filters('ql_woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
    $quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
    $variation_id = absint($_POST['variation_id']);
    $passed_validation = apply_filters('ql_woocommerce_add_to_cart_validation', true, $product_id, $quantity);
    $product_status = get_post_status($product_id);
    $cart_item_data['name'] = 'Tom';

    if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {
        do_action('ql_woocommerce_ajax_added_to_cart', $product_id);

            if ('yes' === get_option('ql_woocommerce_cart_redirect_after_add')) {
                wc_add_to_cart_message(array($product_id => $quantity), true);
            }

            WC_AJAX :: get_refreshed_fragments();
            } else {
                $data = array(
                    'error' => true,
                    'product_url' => apply_filters('ql_woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));
                echo wp_send_json($data);
            }
            wp_die();
        }

</code>```

I try to pass custom data to woocommerce fragment with ajax, but I don't know how to do it right.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to add custom data to woocommerce fragment with ajax, but I don't know how to pass it properly. I found topic with similar question, but it doesn't work for me.

https://stackoverflow.com/questions/61632687/woocommerce-ajax-add-to-cart-with-additional-custom-data

this is my jquery

jQuery(document).ready(function($) {
    $('.single_add_to_cart_button').on('click', function(e){
    e.preventDefault();
    var thisbutton = $(this),
                $form = thisbutton.closest('form.cart'),
                id = thisbutton.val(),
                product_qty = $form.find('input[name=quantity]').val() || 1,
                product_id = $form.find('input[name=product_id]').val() || id,
                variation_id = $form.find('input[name=variation_id]').val() || 0;
    var data = {
            action: 'ql_woocommerce_ajax_add_to_cart',
            product_id: product_id,
            product_sku: '',
            quantity: product_qty,
            variation_id: variation_id,
            name: 'Tom',
        };
    $.ajax({
            type: 'post',
            url: wc_add_to_cart_params.ajax_url,
            data: data,
            beforeSend: function (response) {
                thisbutton.removeClass('added').addClass('loading');
            },
            complete: function (response) {
                thisbutton.addClass('added').removeClass('loading');
            },
            success: function (response) {
                if (response.error & response.product_url) {
                    window.location = response.product_url;
                    return;
                } else {
                    $(document.body).trigger('added_to_cart', [response.fragments, response.cart_hash, thisbutton]);
                }
                console.log( wc_add_to_cart_params.ajax_url, data);
            },
        });
     });
});

this is my function

add_action('wp_ajax_ql_woocommerce_ajax_add_to_cart', 'ql_woocommerce_ajax_add_to_cart');
add_action('wp_ajax_nopriv_ql_woocommerce_ajax_add_to_cart', 'ql_woocommerce_ajax_add_to_cart');
function ql_woocommerce_ajax_add_to_cart() {

    $product_id = apply_filters('ql_woocommerce_add_to_cart_product_id', absint($_POST['product_id']));
    $quantity = empty($_POST['quantity']) ? 1 : wc_stock_amount($_POST['quantity']);
    $variation_id = absint($_POST['variation_id']);
    $passed_validation = apply_filters('ql_woocommerce_add_to_cart_validation', true, $product_id, $quantity);
    $product_status = get_post_status($product_id);
    $cart_item_data['name'] = 'Tom';

    if ($passed_validation && WC()->cart->add_to_cart($product_id, $quantity, $variation_id) && 'publish' === $product_status) {
        do_action('ql_woocommerce_ajax_added_to_cart', $product_id);

            if ('yes' === get_option('ql_woocommerce_cart_redirect_after_add')) {
                wc_add_to_cart_message(array($product_id => $quantity), true);
            }

            WC_AJAX :: get_refreshed_fragments();
            } else {
                $data = array(
                    'error' => true,
                    'product_url' => apply_filters('ql_woocommerce_cart_redirect_after_error', get_permalink($product_id), $product_id));
                echo wp_send_json($data);
            }
            wp_die();
        }

I try to pass custom data to woocommerce fragment with ajax, but I don't know how to do it right.


问:
Expose kernel for existing environment on Vertex AI User Managed Notebook startup
This is a continuation of this thread, posted here because it was too complicated for a comment.

TL;DR

In a Vertex AI User Managed Notebook, how does one retain the exposed kernel icons for existing venv (and conda, if possible) environments stored on the data disk, through repeated stop and start cycles?

Details

I am using User Managed Notebook Instances built off a Docker image. Once the Notebook is launched, I manually go in create a custom environment. For the moment, let's say this is a venv python environment. The environment works fine and I can expose the kernel so it shows as an icon in the Jupyter Lab's Launcher. If I shut the instance down and restart it, the icon is gone. I have been trying to create a start-up script that re-exposes the kernel, but it is not working properly. I have been trying to use method #2 proposed by @gogasca in the link above. Among other operations (which do execute correctly), my start-up script contains the following:

```<code>cat << 'EOF' > /home/jupyter/logs/exposeKernel.sh
#!/bin/bash
set -x
if [ -d /home/jupyter/envs ]; then
  # For each env creation file...
  for i in /home/jupyter/envs/*.sh; do
      tempName="${i##*/}"
      envName=${tempName%.*}
      # If there is a corresponding env directory, then expose the kernel
      if [ -d /home/jupyter/envs/${envName} ]; then
        /home/jupyter/envs/${envName}/bin/python3 -m ipykernel install --prefix=/root/.local --name $envName &>> /home/jupyter/logs/log.txt
        echo -en "Kernel created for: $envName \n" &>> /home/jupyter/logs/log.txt
      else
        echo -en "No kernels can be exposed\n" &>> /home/jupyter/logs/log.txt
      fi
  done
fi
EOF
chown root /home/jupyter/logs/exposeKernel.sh
chmod a+r+w+x /home/jupyter/logs/exposeKernel.sh
su -c '/home/jupyter/logs/exposeKernel.sh' root
echo -en "Existing environment kernels have been exposed\n\n" &>> /home/jupyter/logs/log.txt
</code>```

I am attempting to log the operations, and I see in the log that the kernel is created successfully in the same location that it would be created if I were to manually activate the environment and expose the kernel from within. Despite the apparent success in the log (no errors, at least), the kernel icon does not appear. If I manually run the exposeKernel.sh script from the terminal using su -c '/home/jupyter/logs/exposeKernel.sh' root, it also works fine and the kernel is exposed correctly. @gogasca's comments on the aforementioned thread suggest that I should be using the jupyter user instead of root, but repeated testing and logging indicates that the jupyter user fails to execute the code while root succeeds (though neither create the kernel icon when called from the start-up script).

Questions:

(1) My goal is to automatically re-expose the existing environment kernels on startup. Presumably they disappear each time the VM is stopped and started because there is some kind of linking to the boot disk that is rebuilt each time. What is the appropriate strategy here? Is there a way to build the environments (interested in both conda and venv) so that their kernel icons don't vaporize on shut-down?

(2) If the answer to (1) is no, then why does the EOF-created file fail to accomplish the job when called from a start-up script?

(3) Tangentially related, am I correct in thinking that the post-startup-script executes only once during the initial Notebook instance creation process, while the the startup-script or startup-script-url executes each time the Notebook is started?

Body:
This is a continuation of this thread, posted here because it was too complicated for a comment.

TL;DR

In a Vertex AI User Managed Notebook, how does one retain the exposed kernel icons for existing venv (and conda, if possible) environments stored on the data disk, through repeated stop and start cycles?

Details

I am using User Managed Notebook Instances built off a Docker image. Once the Notebook is launched, I manually go in create a custom environment. For the moment, let's say this is a venv python environment. The environment works fine and I can expose the kernel so it shows as an icon in the Jupyter Lab's Launcher. If I shut the instance down and restart it, the icon is gone. I have been trying to create a start-up script that re-exposes the kernel, but it is not working properly. I have been trying to use method #2 proposed by @gogasca in the link above. Among other operations (which do execute correctly), my start-up script contains the following:

cat << 'EOF' > /home/jupyter/logs/exposeKernel.sh
#!/bin/bash
set -x
if [ -d /home/jupyter/envs ]; then
  # For each env creation file...
  for i in /home/jupyter/envs/*.sh; do
      tempName="${i##*/}"
      envName=${tempName%.*}
      # If there is a corresponding env directory, then expose the kernel
      if [ -d /home/jupyter/envs/${envName} ]; then
        /home/jupyter/envs/${envName}/bin/python3 -m ipykernel install --prefix=/root/.local --name $envName &>> /home/jupyter/logs/log.txt
        echo -en "Kernel created for: $envName \n" &>> /home/jupyter/logs/log.txt
      else
        echo -en "No kernels can be exposed\n" &>> /home/jupyter/logs/log.txt
      fi
  done
fi
EOF
chown root /home/jupyter/logs/exposeKernel.sh
chmod a+r+w+x /home/jupyter/logs/exposeKernel.sh
su -c '/home/jupyter/logs/exposeKernel.sh' root
echo -en "Existing environment kernels have been exposed\n\n" &>> /home/jupyter/logs/log.txt

I am attempting to log the operations, and I see in the log that the kernel is created successfully in the same location that it would be created if I were to manually activate the environment and expose the kernel from within. Despite the apparent success in the log (no errors, at least), the kernel icon does not appear. If I manually run the exposeKernel.sh script from the terminal using su -c '/home/jupyter/logs/exposeKernel.sh' root, it also works fine and the kernel is exposed correctly. @gogasca's comments on the aforementioned thread suggest that I should be using the jupyter user instead of root, but repeated testing and logging indicates that the jupyter user fails to execute the code while root succeeds (though neither create the kernel icon when called from the start-up script).

Questions:

(1) My goal is to automatically re-expose the existing environment kernels on startup. Presumably they disappear each time the VM is stopped and started because there is some kind of linking to the boot disk that is rebuilt each time. What is the appropriate strategy here? Is there a way to build the environments (interested in both conda and venv) so that their kernel icons don't vaporize on shut-down?

(2) If the answer to (1) is no, then why does the EOF-created file fail to accomplish the job when called from a start-up script?

(3) Tangentially related, am I correct in thinking that the post-startup-script executes only once during the initial Notebook instance creation process, while the the startup-script or startup-script-url executes each time the Notebook is started?


问:
How to create a one to many relationship using Tortoise ORM?
I am creating an app in which I have a User entity and an Item entity that are related one to many.
I am using TORTOISE ORM, in a file with the path: app/models/user.py I have the following code:

```<code>from tortoise import fields

from app.models.base_class import Base

class User(Base):
    name = fields.CharField(max_length = 50, nullable = False)
    last_name = fields.CharField(max_length = 50, nullable = False)
    email = fields.CharField(max_length = 128, unique = True, nullable = False)
    password = fields.CharField(max_length = 128, nullable = False)
    create_date = fields.DatetimeField(auto_now = True)

    class Meta:
        table = 'user_db'
</code>```

Hello, I am creating an app in which I have a User entity and an Item entity that are related one to many.
I am using TORTOISE ORM, in a file with the path: app/models/user.py I have the following code:

And in the path: app/models/item.py I have the following code:

```<code>from tortoise.models import Model
from tortoise import fields

from app.models.base_class import Base

class Item(Base):
    title = fields.CharField(max_length = 50, nullable = False)
    description = fields.TextField(nullable = False)
    weight = fields.DecimalField(max_digits=3)
    cost = fields.DecimalField(max_digits=3)
    url_image = fields.CharField(max_length = 255)
    user_id = fields.ForeignKeyField(
        'app.models.user.User',
        'id',
        on_delete = fields.CASCADE
    )
</code>```

My question is if I am correctly implementing the foreign key in the user_id field, is it correct to write the path 'app.models.user.User' for the model name parameter? Do I have to import User in item.py to be able to do this?
Or, on the other hand, should I write in this parameter is 'user_db', which will be the name of the User model table? I'm tangled up with this.

Body:
I am creating an app in which I have a User entity and an Item entity that are related one to many.
I am using TORTOISE ORM, in a file with the path: app/models/user.py I have the following code:

from tortoise import fields

from app.models.base_class import Base

class User(Base):
    name = fields.CharField(max_length = 50, nullable = False)
    last_name = fields.CharField(max_length = 50, nullable = False)
    email = fields.CharField(max_length = 128, unique = True, nullable = False)
    password = fields.CharField(max_length = 128, nullable = False)
    create_date = fields.DatetimeField(auto_now = True)

    class Meta:
        table = 'user_db'

Hello, I am creating an app in which I have a User entity and an Item entity that are related one to many.
I am using TORTOISE ORM, in a file with the path: app/models/user.py I have the following code:

And in the path: app/models/item.py I have the following code:

from tortoise.models import Model
from tortoise import fields

from app.models.base_class import Base

class Item(Base):
    title = fields.CharField(max_length = 50, nullable = False)
    description = fields.TextField(nullable = False)
    weight = fields.DecimalField(max_digits=3)
    cost = fields.DecimalField(max_digits=3)
    url_image = fields.CharField(max_length = 255)
    user_id = fields.ForeignKeyField(
        'app.models.user.User',
        'id',
        on_delete = fields.CASCADE
    )

My question is if I am correctly implementing the foreign key in the user_id field, is it correct to write the path 'app.models.user.User' for the model name parameter? Do I have to import User in item.py to be able to do this?
Or, on the other hand, should I write in this parameter is 'user_db', which will be the name of the User model table? I'm tangled up with this.


问:
How to print the classification report, I want to know the f1 score for each label
I want to modify that code to print the f1 score for each label

Can anyone give a hint what to add to this colab code?

https://colab.research.google.com/drive/1M0ls7EPUi1dwqIDh6HNfJ5y826XvcgGX?usp=sharing


问:
How to improve performance of JPA batch inserts when using Spring Security and Auditing?
Due to the @EnableJpaAuditing annotation, the custom AuditorAware class is being called to getCurrentAuditor() in order to populate the audit fields lastCreatedBy and lastModifiedBy.

```<code>@Component
@RequiredArgsConstructor
public class AuditorAwareImpl implements AuditorAware<User> {

    private final UserRepository userRepository;

    @Override
    public Optional<User> getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return Optional.of(authentication)
                .map(Authentication::getName)
                .flatMap(userRepository::findByUsername);
    }
}
</code>```

This class needs to call a repository in order to get that information (extracting the username / principal from the security context and fetching a user).

This works fine in the context of saving one entity at a time, but when doing batch inserts using saveAll(), the operation turns into a loop in order to call getCurrentAuditor() for every entity/row.

What's the best way to have performant batch inserts while also having Audit data? In my case I'm dealing with a bulk import from the same user, so all the records will have the same audit values.

Body:
Due to the @EnableJpaAuditing annotation, the custom AuditorAware class is being called to getCurrentAuditor() in order to populate the audit fields lastCreatedBy and lastModifiedBy.

@Component
@RequiredArgsConstructor
public class AuditorAwareImpl implements AuditorAware<User> {

    private final UserRepository userRepository;

    @Override
    public Optional<User> getCurrentAuditor() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return Optional.of(authentication)
                .map(Authentication::getName)
                .flatMap(userRepository::findByUsername);
    }
}

This class needs to call a repository in order to get that information (extracting the username / principal from the security context and fetching a user).

This works fine in the context of saving one entity at a time, but when doing batch inserts using saveAll(), the operation turns into a loop in order to call getCurrentAuditor() for every entity/row.

What's the best way to have performant batch inserts while also having Audit data? In my case I'm dealing with a bulk import from the same user, so all the records will have the same audit values.


问:
Camel errorHandler doesn't log before or after sending message to the dead letter channel
We have a simple Camel route like below. But we have noticed that errorHandler log is not working. After some investigation, we understood that errorHandler has different log parameters then other logs(like in route or onException).

We haven't succeeded to use errorHandler log. Yes, there are so many options to log but we want to learn how to use this one. Our aim is to log some texts before or after sending messages to deadletter queue.

How can we use errorHandler log?

apache-camel : 3.19.0

spring-boot  : 2.7.5

```<code><beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:camel="http://camel.apache.org/schema/spring"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://camel.apache.org/schema/spring
                http://camel.apache.org/schema/spring/camel-spring.xsd">

    <bean id="mdcEnricher" class="com.mycompany.MDCEnricher"/>

    <camel:camelContext id="mycontext" xmlns="http://camel.apache.org/schema/spring" useMDCLogging="true">

        <camel:errorHandler id="myErrorHandler" type="DeadLetterChannel"
                            useOriginalBody="true"
                            deadLetterUri="jms:queue:mybackoutq">
            <redeliveryPolicy
                    maximumRedeliveries="1"
                    redeliveryDelay="1"
                    retryAttemptedLogLevel="WARN"
                    retriesExhaustedLogLevel="ERROR"/>
            <log id="logIncomingMsg" logName="com.mypackage"
              loggingLevel="ERROR" message="Pushing to backout queue"/>
        </camel:errorHandler>

        <camel:route id="myRoute" errorHandlerRef="myErrorHandler">
            <from uri="jms:queue:myinputq"/>
            <bean ref="mdcEnricher" method="enrich"/>
            <log message="Received exchange with message id: [${headers.JMSMessageID}], starting processing"/>
            <process ref="#class:com.mycompany.processor.MyProcessor"/>
            <to uri="jms:queue:myoutputq"/>
            <log message="Finished the processing exchange with message id: [${headers.JMSMessageID}]"/>
        </camel:route>
</code>```

Try to change log configuration and loggingLevel to DEBUG but nothing changed.

```<code><springProfile name="local">
    <logger name="org.apache.camel" level="DEBUG"/>
    <logger name="com.mycompany" level="DEBUG"/>
    <root level="DEBUG">
        <appender-ref ref="LocalConsole"/>
    </root>
</springProfile>
</code>```

Body:
We have a simple Camel route like below. But we have noticed that errorHandler log is not working. After some investigation, we understood that errorHandler has different log parameters then other logs(like in route or onException).

We haven't succeeded to use errorHandler log. Yes, there are so many options to log but we want to learn how to use this one. Our aim is to log some texts before or after sending messages to deadletter queue.

How can we use errorHandler log?

apache-camel : 3.19.0

spring-boot  : 2.7.5

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:camel="http://camel.apache.org/schema/spring"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://camel.apache.org/schema/spring
                http://camel.apache.org/schema/spring/camel-spring.xsd">

    <bean id="mdcEnricher" class="com.mycompany.MDCEnricher"/>

    <camel:camelContext id="mycontext" xmlns="http://camel.apache.org/schema/spring" useMDCLogging="true">

        <camel:errorHandler id="myErrorHandler" type="DeadLetterChannel"
                            useOriginalBody="true"
                            deadLetterUri="jms:queue:mybackoutq">
            <redeliveryPolicy
                    maximumRedeliveries="1"
                    redeliveryDelay="1"
                    retryAttemptedLogLevel="WARN"
                    retriesExhaustedLogLevel="ERROR"/>
            <log id="logIncomingMsg" logName="com.mypackage"
              loggingLevel="ERROR" message="Pushing to backout queue"/>
        </camel:errorHandler>

        <camel:route id="myRoute" errorHandlerRef="myErrorHandler">
            <from uri="jms:queue:myinputq"/>
            <bean ref="mdcEnricher" method="enrich"/>
            <log message="Received exchange with message id: [${headers.JMSMessageID}], starting processing"/>
            <process ref="#class:com.mycompany.processor.MyProcessor"/>
            <to uri="jms:queue:myoutputq"/>
            <log message="Finished the processing exchange with message id: [${headers.JMSMessageID}]"/>
        </camel:route>

Try to change log configuration and loggingLevel to DEBUG but nothing changed.

<springProfile name="local">
    <logger name="org.apache.camel" level="DEBUG"/>
    <logger name="com.mycompany" level="DEBUG"/>
    <root level="DEBUG">
        <appender-ref ref="LocalConsole"/>
    </root>
</springProfile>


问:
Getting variables from application.properties using SmallRyeConfig in quarkus fails
I followed this documentation to get configs from application.properties in a quarkus service.

I am not using CDI, so here is what I am doing to get this config:

application.properties

```<code>redis.hosts=${REDIS_HOSTS}
redis.port=${REDIS_PORT}
redis.password=${REDIS_PASSWORD}
</code>```

Note: I have set these environment variables.

RedisConfigInterface

```<code>import java.util.Set;
import io.smallrye.config.ConfigMapping;

@ConfigMapping(prefix = "redis")
interface RedisConfigInterface {
    Set<String> hosts();

    Integer port();

    String password();
}
</code>```

ConfigCreation

```<code>public class ConfigCreation {

    public ConfigCreation() {

        //Registering config
        new SmallRyeConfigBuilder()
            .withMapping(RedisConfigInterface.class)
            .build();

        // Getting config
        RedisConfigInterface config = ConfigProvider.getConfig().unwrap(SmallRyeConfig.class).getConfigMapping(RedisConfigInterface.class);

        Integer port = config.port();
        System.out.println(port);
    }
}
</code>```

It builds correctly but I got this error when executing the service:

```<code>12:17:02 ERROR [io.qu.ru.Application] (Quarkus Main Thread)  Failed to start application (with profile dev): io.smallrye.config.ConfigValidationException: Configuration validation failed:
    java.util.NoSuchElementException: SRCFG00014: The config property redis.hosts is required but it could not be found in any config source
    java.util.NoSuchElementException: SRCFG00014: The config property redis.password is required but it could not be found in any config source
    java.util.NoSuchElementException: SRCFG00014: The config property redis.port is required but it could not be found in any config source
</code>```

Am I missing something here? Everything seems to be set correctly.

Body:
I followed this documentation to get configs from application.properties in a quarkus service.

I am not using CDI, so here is what I am doing to get this config:

application.properties

redis.hosts=${REDIS_HOSTS}
redis.port=${REDIS_PORT}
redis.password=${REDIS_PASSWORD}

Note: I have set these environment variables.

RedisConfigInterface

import java.util.Set;
import io.smallrye.config.ConfigMapping;

@ConfigMapping(prefix = "redis")
interface RedisConfigInterface {
    Set<String> hosts();

    Integer port();

    String password();
}

ConfigCreation

public class ConfigCreation {

    public ConfigCreation() {

        //Registering config
        new SmallRyeConfigBuilder()
            .withMapping(RedisConfigInterface.class)
            .build();

        // Getting config
        RedisConfigInterface config = ConfigProvider.getConfig().unwrap(SmallRyeConfig.class).getConfigMapping(RedisConfigInterface.class);

        Integer port = config.port();
        System.out.println(port);
    }
}

It builds correctly but I got this error when executing the service:

12:17:02 ERROR [io.qu.ru.Application] (Quarkus Main Thread)  Failed to start application (with profile dev): io.smallrye.config.ConfigValidationException: Configuration validation failed:
    java.util.NoSuchElementException: SRCFG00014: The config property redis.hosts is required but it could not be found in any config source
    java.util.NoSuchElementException: SRCFG00014: The config property redis.password is required but it could not be found in any config source
    java.util.NoSuchElementException: SRCFG00014: The config property redis.port is required but it could not be found in any config source

Am I missing something here? Everything seems to be set correctly.


问:
set /p But wait for only one key press without needing to press enter
So I am making a game in batch which in the movement controls are WASD.
I used -
set /p input=
and if %input% is D the player goes right.
But every time I type a letter (W,A,S,D) I have to then press enter.
How can I make it so I don't need to press enter and the %input% is set whenever any key is pressed.
I know there is a way to do this, I remember making a simular project which had it. But it was so long ago I forgot how to do it.

I can't find a solution online because well it's kinda hard describing what I'm looking for.


问:
Solidity Compiler not writing any json files
VS Code suggested i install Solidity extension which I did. immediately it installed it required that I update my solidity to 0.8.17; I did then I had to update some parts of the code. after I did, I tested on remix and it worked. Back on vs code now and I've been trying to compile but it is not compiling.It creates the 'build' folder but doesn't write any JSON files in it.

Campaign.sol file:

```<code>// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.17;

contract CampaignFactory {
    address[] public deployedCampaigns;

    function createCampaign(uint minimum) public {
       Campaign newCampaign = new Campaign(minimum, msg.sender);
        deployedCampaigns.push(address(newCampaign));
    }

    function getDeployedCampaigns() public view returns (address[] memory) {
        return deployedCampaigns;
    }

}
contract Campaign {
    struct Request {
        string description;
        uint value;
        address payable recipient;
        bool complete;
        uint approvalCount;
        mapping(address => bool) approvals;
    }

    Request[] public requests;
    address public manager;
    uint public minimumContribution;
    mapping(address => bool) public approvers;
    uint public approversCount;

    modifier restricted() {
        require(msg.sender == manager);
        _;
    }

    constructor (uint minimum, address creator) {
        manager = creator;
        minimumContribution = minimum;
    }

    function contribute() public payable {
        require(msg.value > minimumContribution);

        approvers[msg.sender] = true;
        approversCount++;
    }

    function createRequest(string memory description, uint value, address payable recipient) public restricted {
        Request storage newRequest = requests.push();

        newRequest.description = description;
        newRequest.value = value;
        newRequest.recipient = recipient;
        newRequest.complete = false;
        newRequest.approvalCount = 0;
}

    function approveRequest(uint index) public {
        Request storage request = requests[index];

        require(approvers[msg.sender]);
        require(!request.approvals[msg.sender]);

        request.approvals[msg.sender] = true;
        request.approvalCount++;
    }

    function finalizeRequest(uint index) public restricted {
        Request storage request = requests[index];

        require(request.approvalCount > (approversCount / 2));
        require(!request.complete);

        request.recipient.transfer(request.value);
        request.complete = true;
    }

    function getSummary() public view returns (
        uint, uint, uint, uint, address
        ) {
        return(
            minimumContribution,
            address(this).balance,
            requests.length,
            approversCount,
            manager
        );
    }

    function getRequestsCount() public view returns (uint) {
        return requests.length;
    }
}
</code>```

compile.js file

```<code>const path = require("path");
const solc = require("solc");
const fs = require("fs-extra");

const buildPath = path.resolve(__dirname, "build");
fs.removeSync(buildPath);

const campaignPath = path.resolve(__dirname, "contracts", "Campaign.sol");
const source = fs.readFileSync(campaignPath, "utf8");
const output = solc.compile(source, 1).contracts;

fs.ensureDirSync(buildPath);

for (let contract in output) {
  fs.outputJsonSync(
    path.resolve(buildPath, contract.replace(":", "") + ".json"),
    output[contract]
  );
}
</code>```

Body:
VS Code suggested i install Solidity extension which I did. immediately it installed it required that I update my solidity to 0.8.17; I did then I had to update some parts of the code. after I did, I tested on remix and it worked. Back on vs code now and I've been trying to compile but it is not compiling.It creates the 'build' folder but doesn't write any JSON files in it.

Campaign.sol file:

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.17;

contract CampaignFactory {
    address[] public deployedCampaigns;

    function createCampaign(uint minimum) public {
       Campaign newCampaign = new Campaign(minimum, msg.sender);
        deployedCampaigns.push(address(newCampaign));
    }

    function getDeployedCampaigns() public view returns (address[] memory) {
        return deployedCampaigns;
    }

}
contract Campaign {
    struct Request {
        string description;
        uint value;
        address payable recipient;
        bool complete;
        uint approvalCount;
        mapping(address => bool) approvals;
    }

    Request[] public requests;
    address public manager;
    uint public minimumContribution;
    mapping(address => bool) public approvers;
    uint public approversCount;

    modifier restricted() {
        require(msg.sender == manager);
        _;
    }

    constructor (uint minimum, address creator) {
        manager = creator;
        minimumContribution = minimum;
    }

    function contribute() public payable {
        require(msg.value > minimumContribution);

        approvers[msg.sender] = true;
        approversCount++;
    }

    function createRequest(string memory description, uint value, address payable recipient) public restricted {
        Request storage newRequest = requests.push();

        newRequest.description = description;
        newRequest.value = value;
        newRequest.recipient = recipient;
        newRequest.complete = false;
        newRequest.approvalCount = 0;
}

    function approveRequest(uint index) public {
        Request storage request = requests[index];

        require(approvers[msg.sender]);
        require(!request.approvals[msg.sender]);

        request.approvals[msg.sender] = true;
        request.approvalCount++;
    }

    function finalizeRequest(uint index) public restricted {
        Request storage request = requests[index];

        require(request.approvalCount > (approversCount / 2));
        require(!request.complete);

        request.recipient.transfer(request.value);
        request.complete = true;
    }

    function getSummary() public view returns (
        uint, uint, uint, uint, address
        ) {
        return(
            minimumContribution,
            address(this).balance,
            requests.length,
            approversCount,
            manager
        );
    }

    function getRequestsCount() public view returns (uint) {
        return requests.length;
    }
}

compile.js file

const path = require("path");
const solc = require("solc");
const fs = require("fs-extra");

const buildPath = path.resolve(__dirname, "build");
fs.removeSync(buildPath);

const campaignPath = path.resolve(__dirname, "contracts", "Campaign.sol");
const source = fs.readFileSync(campaignPath, "utf8");
const output = solc.compile(source, 1).contracts;

fs.ensureDirSync(buildPath);

for (let contract in output) {
  fs.outputJsonSync(
    path.resolve(buildPath, contract.replace(":", "") + ".json"),
    output[contract]
  );
}


问:
How do I handle this error "Error in par[1] : object of type 'closure' is not subsettable"
I keep encountering error "Error in par[1] : object of type 'closure' is not subsettable" when  I try integrating Aa. This happens after calling Aa(par,m)-code provided. I am trying to develop EM algorithm to obtain estimates of parameters but I cannot proceed with the above error. Any suggestions will be highly appreciated.</p>
```<code>#The PDF of IPLE distribution
f<-function(alpha,beta,lambda,x){
      y=alpha*beta*lambda*(x)^(-beta-1)*exp((lambda/(x)^beta))*(exp((lambda/(x)^beta))-1)^(alpha-1)*     ((exp(lambda/(x)^beta)-1)^alpha +1)^(-2)
      return(y)
    }
#The CDF OF IPLE DISTRIBUTION
    F<-function(alpha,beta,lambda,x){
    y=1/((exp(lambda/(x)^beta)-1)^alpha +1)
    return(y)
    }
#GENERATING PROGRESSIVE TYPE II CENSORED SAMPLE
bl<-function(n,m,par){
alpha=par[[1]]
beta=par[[2]]
lambda=par[[3]]
  regw<-function(x,aalpha=alpha,bbeta=beta,llambda=lambda){
    q=llambda^(1/bbeta)*(log(((1/x)-1)^(1/aalpha)+1))^(-(1/bbeta))
    return(q)}
  w=runif(m)
  r=c()
  r[1]=rbinom(1,n-m,0.2)
  int=seq(2,m-1)
  s=r[1]
  for(i in int){
    r[i]=rbinom(1,n-m-s,0.2)
    s=s+r[i]}
  if(n-m-s>0)
    r[m]=n-m-s
  else
    r[m]=0
  p=c()
  x=c()
  v=c()
  u=c()
  y=c()
  p=r[m]
  for (i in 1:m){
    v[i]=w[i]^(1/(i+p))
    p=p+r[m-i]
  }
  x=v[m]
  for (i in 1:m){
    u[i]=1-x
    x=x*v[m-i]
    y[i]=regw(u[i],alpha,beta,lambda)
  }
  D=data.frame(y,r)
  return(D)
}

n<-40
m<-10
par<-c(0.5,0.45,0.2)
bl(n,m,par)

#INTERGRATION DEFINED
Aa<-function(par,m){
  alpha<-par[[1]]
  beta<-par[[2]]
  lambda<-par[[3]]
  y=c()
  c=c()
  for(j in 1:m){
    c[j]=1/(1-F(alpha,beta,lambda,frame$y[j]))
    g<-function(x){
      log(x)*f(alpha,beta,lambda,x)
    }
    y[j]=c[j]*integrate(g,lower =frame$y[j],upper=Inf)$value
  }
  return(y)
}

Aa(par,m)
</code>```

Body:
I keep encountering error "Error in par[1] : object of type 'closure' is not subsettable" when  I try integrating Aa. This happens after calling Aa(par,m)-code provided. I am trying to develop EM algorithm to obtain estimates of parameters but I cannot proceed with the above error. Any suggestions will be highly appreciated.

#The PDF of IPLE distribution
f<-function(alpha,beta,lambda,x){
      y=alpha*beta*lambda*(x)^(-beta-1)*exp((lambda/(x)^beta))*(exp((lambda/(x)^beta))-1)^(alpha-1)*     ((exp(lambda/(x)^beta)-1)^alpha +1)^(-2)
      return(y)
    }
#The CDF OF IPLE DISTRIBUTION
    F<-function(alpha,beta,lambda,x){
    y=1/((exp(lambda/(x)^beta)-1)^alpha +1)
    return(y)
    }
#GENERATING PROGRESSIVE TYPE II CENSORED SAMPLE
bl<-function(n,m,par){
alpha=par[[1]]
beta=par[[2]]
lambda=par[[3]]
  regw<-function(x,aalpha=alpha,bbeta=beta,llambda=lambda){
    q=llambda^(1/bbeta)*(log(((1/x)-1)^(1/aalpha)+1))^(-(1/bbeta))
    return(q)}
  w=runif(m)
  r=c()
  r[1]=rbinom(1,n-m,0.2)
  int=seq(2,m-1)
  s=r[1]
  for(i in int){
    r[i]=rbinom(1,n-m-s,0.2)
    s=s+r[i]}
  if(n-m-s>0)
    r[m]=n-m-s
  else
    r[m]=0
  p=c()
  x=c()
  v=c()
  u=c()
  y=c()
  p=r[m]
  for (i in 1:m){
    v[i]=w[i]^(1/(i+p))
    p=p+r[m-i]
  }
  x=v[m]
  for (i in 1:m){
    u[i]=1-x
    x=x*v[m-i]
    y[i]=regw(u[i],alpha,beta,lambda)
  }
  D=data.frame(y,r)
  return(D)
}

n<-40
m<-10
par<-c(0.5,0.45,0.2)
bl(n,m,par)

#INTERGRATION DEFINED
Aa<-function(par,m){
  alpha<-par[[1]]
  beta<-par[[2]]
  lambda<-par[[3]]
  y=c()
  c=c()
  for(j in 1:m){
    c[j]=1/(1-F(alpha,beta,lambda,frame$y[j]))
    g<-function(x){
      log(x)*f(alpha,beta,lambda,x)
    }
    y[j]=c[j]*integrate(g,lower =frame$y[j],upper=Inf)$value
  }
  return(y)
}

Aa(par,m)


问:
Open screenshot in Robotframework log.html on Jenkins (Robotframework plugin)
here is my problem:

I can launch a jenkins job which launches an automated Test. When this job fails and I go to the log.html, I don't see the screenshots. However when I go to the folder that hosts my Jenkins in localhost, and I open my log.html file, the screenshots appear correctly. Can you tell me why I can't see them on Jenkins please?

enter image description here

I tried to configure output path in Jenkins but nothing change this...
enter image description here

Thanks for reading this :)


问:
Mongoose findOne() method and array map() method
Today I'm a little bit confused... I'm trying to get a list of posts of logged user by _id numbers included in user mongo document. When I call promise inside map method - I'm still receiving Array of Promise{}. I'm looking for info about this behavior but I don't understand why it behaves like this. It seems coded like it should be (in promise with async and await). getListOfThoughts method is created for posts download.
Thank you in advance

```<code>
export const addThought = async (req: Request, res: Response) => {
  const { email, thoughtContent } = req.body;
  const getListOfThoughts = async (user: IUser) => {
    const result = user.posts.map(async (el) => {
      return await ThoughtModel.findOne({ _id: el });
    });
    return result;
  };
  if (email) {
    try {
      const user = await UserModel.findOne({ eMail: email });
      const newThought = await ThoughtModel.create({
        textContent: thoughtContent,
        author: {
          id: user._id,
          firstName: user.firstName,
          lastName: user.lastName,
          userPic: user.pic,
        },
      });
      await UserModel.updateOne(
        { eMail: email },
        { $push: { posts: newThought._id } }
      );
      const updatedUser = await UserModel.findOne({ eMail: email });
      const newListOfThoughts = await getListOfThoughts(updatedUser);
      console.log("new List", newListOfThoughts);
      res.status(201).send({
        message: "Thought added",
        userData: newListOfThoughts,
      });
    } catch (error) {
      console.log(error);
      res.json(error.message);
    }
  }
};

</code>```

mongoose javascript mongodb async promise

I tried:

```<code>export const addThought = async (req: Request, res: Response) => {
  const { email, thoughtContent } = req.body;
  const getListOfThoughts = async (user: IUser) => {
    const result = user.posts.map(async (el) => {
      const post = await ThoughtModel.findOne({ _id: el });
      return post;
    });
    return result;
  };
  if (email) {
    try {
      const user = await UserModel.findOne({ eMail: email });
      const newThought = await ThoughtModel.create({
        textContent: thoughtContent,
        author: {
          id: user._id,
          firstName: user.firstName,
          lastName: user.lastName,
          userPic: user.pic,
        },
      });
      await UserModel.updateOne(
        { eMail: email },
        { $push: { posts: newThought._id } }
      );
      const updatedUser = await UserModel.findOne({ eMail: email });
      const newListOfThoughts = await getListOfThoughts(updatedUser);
      res.status(201).send({
        message: "Thought added",
        userData: newListOfThoughts,
      });
    } catch (error) {
      console.log(error);
      res.json(error.message);
    }
  }
};

</code>```

Body:
Today I'm a little bit confused... I'm trying to get a list of posts of logged user by _id numbers included in user mongo document. When I call promise inside map method - I'm still receiving Array of Promise{}. I'm looking for info about this behavior but I don't understand why it behaves like this. It seems coded like it should be (in promise with async and await). getListOfThoughts method is created for posts download.
Thank you in advance

export const addThought = async (req: Request, res: Response) => {
  const { email, thoughtContent } = req.body;
  const getListOfThoughts = async (user: IUser) => {
    const result = user.posts.map(async (el) => {
      return await ThoughtModel.findOne({ _id: el });
    });
    return result;
  };
  if (email) {
    try {
      const user = await UserModel.findOne({ eMail: email });
      const newThought = await ThoughtModel.create({
        textContent: thoughtContent,
        author: {
          id: user._id,
          firstName: user.firstName,
          lastName: user.lastName,
          userPic: user.pic,
        },
      });
      await UserModel.updateOne(
        { eMail: email },
        { $push: { posts: newThought._id } }
      );
      const updatedUser = await UserModel.findOne({ eMail: email });
      const newListOfThoughts = await getListOfThoughts(updatedUser);
      console.log("new List", newListOfThoughts);
      res.status(201).send({
        message: "Thought added",
        userData: newListOfThoughts,
      });
    } catch (error) {
      console.log(error);
      res.json(error.message);
    }
  }
};

mongoose javascript mongodb async promise

I tried:

export const addThought = async (req: Request, res: Response) => {
  const { email, thoughtContent } = req.body;
  const getListOfThoughts = async (user: IUser) => {
    const result = user.posts.map(async (el) => {
      const post = await ThoughtModel.findOne({ _id: el });
      return post;
    });
    return result;
  };
  if (email) {
    try {
      const user = await UserModel.findOne({ eMail: email });
      const newThought = await ThoughtModel.create({
        textContent: thoughtContent,
        author: {
          id: user._id,
          firstName: user.firstName,
          lastName: user.lastName,
          userPic: user.pic,
        },
      });
      await UserModel.updateOne(
        { eMail: email },
        { $push: { posts: newThought._id } }
      );
      const updatedUser = await UserModel.findOne({ eMail: email });
      const newListOfThoughts = await getListOfThoughts(updatedUser);
      res.status(201).send({
        message: "Thought added",
        userData: newListOfThoughts,
      });
    } catch (error) {
      console.log(error);
      res.json(error.message);
    }
  }
};


问:
How to use creds or any var from the azure library group in bash script
NEXUS IQ has two parameters for authentication instead of using a PAT. I have the usercode and passcode, along with the organizationid stored in a var group of my az pipeline. I'm using bash for my input script. I've drawn a blank regarding variable assignment to obtain the values stored in my az library group as I'm a bit rusty. HELP

```<code>#!/bin/bash

USERCODE=$1
PASSCODE=$2
ORGANIZATIONID=$3
NEWAPP=$4

# Check required values
if [ "$USERCODE" = "" ] || [ "$PASSCODE" = "" ] || [ "$ORGANIZATIONID" = "" ] || [ "$NEWAPP" = "" ]; then
   echo 'USERCODE, PASSCODE, ORG, NEWAPP cannot be empty values.'
   exit 1
fi

# create app
count=1
uri="https://nexusiq.xxxxxx.com/api/v2/applications"
raw=$(curl -u "${USERCODE}:${PASSCODE}" "${uri}?per_page=100&page=${count}")
while : ; do
  appname=$(echo $raw | jq '.[]|{name}' | jq -s '.')
   if [ appname == '' ]; then
      applicaions=$appname
      else
      applications=$(jq -s '.[0] + .[1]' <(echo $applications | jq '.') <(echo $appname | jq '.'))
   fi
((count++))
   raw=$(curl -u "${USERCODE}:${PASSCODE}" "${uri}?per_page=100&page=${count}")
   [ "$(echo $raw | jq -r '.|length')" == "0" ] && break
done
 if [[ ! ${applications[*]} =~ "$NEWAPP" ]]; #
  JSON='{"organizationId":"'"$ORGANIZATIONID"'","publicId":"'"$NEWAPP"'","name":"'"$NEWAPP"'"}'
  curl -u "${USERCODE}:${PASSCODE}"-X POST -H "Content-Type: application/json" "https://nexusiq.xxxxx.com/api/v2/applications" -d $JSON
fi
</code>```

Variables are not being initialized in script

Body:
NEXUS IQ has two parameters for authentication instead of using a PAT. I have the usercode and passcode, along with the organizationid stored in a var group of my az pipeline. I'm using bash for my input script. I've drawn a blank regarding variable assignment to obtain the values stored in my az library group as I'm a bit rusty. HELP

#!/bin/bash

USERCODE=$1
PASSCODE=$2
ORGANIZATIONID=$3
NEWAPP=$4

# Check required values
if [ "$USERCODE" = "" ] || [ "$PASSCODE" = "" ] || [ "$ORGANIZATIONID" = "" ] || [ "$NEWAPP" = "" ]; then
   echo 'USERCODE, PASSCODE, ORG, NEWAPP cannot be empty values.'
   exit 1
fi

# create app
count=1
uri="https://nexusiq.xxxxxx.com/api/v2/applications"
raw=$(curl -u "${USERCODE}:${PASSCODE}" "${uri}?per_page=100&page=${count}")
while : ; do
  appname=$(echo $raw | jq '.[]|{name}' | jq -s '.')
   if [ appname == '' ]; then
      applicaions=$appname
      else
      applications=$(jq -s '.[0] + .[1]' <(echo $applications | jq '.') <(echo $appname | jq '.'))
   fi
((count++))
   raw=$(curl -u "${USERCODE}:${PASSCODE}" "${uri}?per_page=100&page=${count}")
   [ "$(echo $raw | jq -r '.|length')" == "0" ] && break
done
 if [[ ! ${applications[*]} =~ "$NEWAPP" ]]; #
  JSON='{"organizationId":"'"$ORGANIZATIONID"'","publicId":"'"$NEWAPP"'","name":"'"$NEWAPP"'"}'
  curl -u "${USERCODE}:${PASSCODE}"-X POST -H "Content-Type: application/json" "https://nexusiq.xxxxx.com/api/v2/applications" -d $JSON
fi

Variables are not being initialized in script


问:
WPF animated stack panel
I'm in the process of creating an ItemsControl that will have something similar to a StackPanel for its ItemsPanel. However, I want the user to be able to rearrange items in the panel, and have them animate to their final positions like this:

I've done some searching, and a lot of the examples I have found that do something similar, implement the animations by setting the desired position of all items to 0,0 and applying a RenderTransform storyboard in the Panel.ArrangeOverride method to offset each item vertically.

Whilst this works, is this the correct way to be doing it? Doesn't this mean the  controls won't take part in normal layout as they're all set to 0,0?

Will this have side effects?

I was wondering if I should use the above method for the animation, and then when the animation ends, do another final invalidation of the arrange layout, but this time using actual positions instead of render transforms?

Title: WPF animated stack panel


问:
Not able retrieve NumberLong data from MongoDB
I am not able to retrieve data from DB. I am using below query

```<code>db.getCollection('Emp_Data').find({"updatedDateTime":  {"$gte": {"$numberLong": "1671979860000"}}});
</code>```

and I have data like this in my DB

```<code>"updatedDateTime" : NumberLong(1672059880000),
"createdDateTime" : NumberLong(1671695703836),
</code>```

Please help.

```<code>db.getCollection('Emp_Data').find({"updatedDateTime":  {"$gte": {"$numberLong": "1671979860000"}}});
</code>```

I tried above query, is it right or wrong, If wrong please help.

Body:
I am not able to retrieve data from DB. I am using below query

db.getCollection('Emp_Data').find({"updatedDateTime":  {"$gte": {"$numberLong": "1671979860000"}}});

and I have data like this in my DB

"updatedDateTime" : NumberLong(1672059880000),
"createdDateTime" : NumberLong(1671695703836),

Please help.

db.getCollection('Emp_Data').find({"updatedDateTime":  {"$gte": {"$numberLong": "1671979860000"}}});

I tried above query, is it right or wrong, If wrong please help.


问:
binary signature problem using zeep in python
I am currently trying to use zeep to consume a soap service, but in the binary signature part zeep does not generate the xml as expected, the signature is expected like this:

```<code><wsse:UsernameToken wsu:Id="UsernameToken-D01D11BA2CAF83D4FD16720147918422">
            <wsse:Username>2-90155</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">wzxxxx</wsse:Password>
            <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">v47Jj/bIOMI5PIWFsdzalw==</wsse:Nonce>
            <wsu:Created>2022-12-26T00:33:11.842Z</wsu:Created>
         </wsse:UsernameToken>
</code>```

but my code generates the signature like this:

```<code><wsse:UsernameToken>
            <wsse:Username>2-901705</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">wzPxxxx</wsse:Password>
         </wsse:UsernameToken>
         <wsu:Timestamp wsu:Id="id-1b7e34ff-0f38-4651-a456-8a4f4011903b">
            <wsu:Created>2022-12-25T20:03:16Z</wsu:Created>
            <wsu:Expires>2022-12-25T20:08:16Z</wsu:Expires>
         </wsu:Timestamp>
</code>```

not generate is tag <wsse:Nonce EncodingType

my code

```<code>timestamp_token = WSU.Timestamp()
today_datetime = datetime.datetime.today()
expires_datetime = today_datetime + datetime.timedelta(minutes = 5)

timestamp_elements = [
    WSU.Created(today_datetime.strftime("%Y-%m-%dT%H:%M:%SZ")),
    WSU.Expires(expires_datetime.strftime("%Y-%m-%dT%H:%M:%SZ"))
]
timestamp_token.extend(timestamp_elements)

user_name_token = UsernameToken('2-95','wzxxxxx',timestamp_token=timestamp_token)
</code>```
```<code>wsdl_client = Client(
      wsdl=wsdl_url,
      wsse=[user_name_token, signature],
      transport=transport
   )
</code>```

Has anyone had this mishap?

Body:
I am currently trying to use zeep to consume a soap service, but in the binary signature part zeep does not generate the xml as expected, the signature is expected like this:

<wsse:UsernameToken wsu:Id="UsernameToken-D01D11BA2CAF83D4FD16720147918422">
            <wsse:Username>2-90155</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">wzxxxx</wsse:Password>
            <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">v47Jj/bIOMI5PIWFsdzalw==</wsse:Nonce>
            <wsu:Created>2022-12-26T00:33:11.842Z</wsu:Created>
         </wsse:UsernameToken>

but my code generates the signature like this:

<wsse:UsernameToken>
            <wsse:Username>2-901705</wsse:Username>
            <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">wzPxxxx</wsse:Password>
         </wsse:UsernameToken>
         <wsu:Timestamp wsu:Id="id-1b7e34ff-0f38-4651-a456-8a4f4011903b">
            <wsu:Created>2022-12-25T20:03:16Z</wsu:Created>
            <wsu:Expires>2022-12-25T20:08:16Z</wsu:Expires>
         </wsu:Timestamp>

not generate is tag <wsse:Nonce EncodingType

my code

timestamp_token = WSU.Timestamp()
today_datetime = datetime.datetime.today()
expires_datetime = today_datetime + datetime.timedelta(minutes = 5)

timestamp_elements = [
    WSU.Created(today_datetime.strftime("%Y-%m-%dT%H:%M:%SZ")),
    WSU.Expires(expires_datetime.strftime("%Y-%m-%dT%H:%M:%SZ"))
]
timestamp_token.extend(timestamp_elements)

user_name_token = UsernameToken('2-95','wzxxxxx',timestamp_token=timestamp_token)

wsdl_client = Client(
      wsdl=wsdl_url,
      wsse=[user_name_token, signature],
      transport=transport
   )

Has anyone had this mishap?


问:
Chrome failed to start: exited abnormally
When I run an acceptance test on a remote linux server in Jenkins, the job fails

```<code>Facebook\WebDriver\Exception\SessionNotCreatedException] Unable to create new service: ChromeDriverService
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:13:22.693Z'

Driver info: driver.version: unknown
</code>```

I run the selenium server with the command

```<code>java -Dwebdriver.chrome.driver=./Codeception/chromedriver -jar ./Codeception/selenium-server-standalone-3.14.0.jar -port 17570 &
</code>```

and run test

./composer.phar install

php codecept.phar run tests/acceptance/Jenkins_test_Cept.php --debug

Chrome version: 108.0.5359.124

Console log

```<code>+ java -Dwebdriver.chrome.driver=./Codeception/chromedriver -jar ./Codeception/selenium-

server-standalone-3.14.0.jar -port 17570
[workspace] $ /bin/sh -xe /tmp/***
+ cd Codeception/Brand_Analytics
+ ./composer.phar install
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Nothing to install or update
Package symfony/debug is abandoned, you should avoid using it. Use symfony/error-handler instead.
Generating autoload files
+ php codecept.phar run tests/acceptance/Jenkins_test_Cept.php --debug
</code>```

How I can solve this problem? I'm new in Jenkins and have no idea what to do

Body:
When I run an acceptance test on a remote linux server in Jenkins, the job fails

Facebook\WebDriver\Exception\SessionNotCreatedException] Unable to create new service: ChromeDriverService
Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:13:22.693Z'

Driver info: driver.version: unknown

I run the selenium server with the command

java -Dwebdriver.chrome.driver=./Codeception/chromedriver -jar ./Codeception/selenium-server-standalone-3.14.0.jar -port 17570 &

and run test

./composer.phar install

php codecept.phar run tests/acceptance/Jenkins_test_Cept.php --debug

Chrome version: 108.0.5359.124

Console log

+ java -Dwebdriver.chrome.driver=./Codeception/chromedriver -jar ./Codeception/selenium-

server-standalone-3.14.0.jar -port 17570
[workspace] $ /bin/sh -xe /tmp/***
+ cd Codeception/Brand_Analytics
+ ./composer.phar install
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Nothing to install or update
Package symfony/debug is abandoned, you should avoid using it. Use symfony/error-handler instead.
Generating autoload files
+ php codecept.phar run tests/acceptance/Jenkins_test_Cept.php --debug

How I can solve this problem? I'm new in Jenkins and have no idea what to do


问:
automatic many to many relationship in mongoengine
i'm trying to create a e-shop like site, i'm using two models, Product and User. My current problem relays in the fact that when creating new products, those new products needs to be manually inserted in the collection a specific user own, an example:

Current Approach

from api import models as md

john = md.User(name="John", mail="john@test.com").save()

laptop = md.Product()
laptop.name = "Thinkpad T440p"
laptop.price = 190
laptop.description = "foobar"
laptop.owner = john              # <-------------- as you can see here i need to specify the owner
laptop.save()

john.products.append(laptop)     # <-------------- and then append the new product into the user
```
<hr />
<h1>Spected behaviour</h1>
<p>I want to avoid this approach of doing two operations for something that is essentially the same thing. When creating a new product it should be automatically added to the user's collection. Like this:</p>
<pre class="lang-py prettyprint-override"><code>...

laptop.owner = john
laptop.save()

john.products.objects()
>>> [<Product Thinkpad T440p>]
</code>```

Models

Below you will see how i'm creating the models

from api import db

class Product(db.Document):
    name = db.StringField()
    price = db.DecimalField()
    description = db.StringField()
    owner = db.ReferenceField('User', required=True)

    def __repr__(self):
        return '<Product {}>'.format(self.name)

class User(db.Document):
    email = db.EmailField()
    name = db.StringField()
    products = db.ListField(db.ReferenceField('Product'))

    def __repr__(self):
        return '<User {}>'.format(self.username)
```

Body:
i'm trying to create a e-shop like site, i'm using two models, Product and User. My current problem relays in the fact that when creating new products, those new products needs to be manually inserted in the collection a specific user own, an example:

Current Approach

from api import models as md

john = md.User(name="John", mail="john@test.com").save()

laptop = md.Product()
laptop.name = "Thinkpad T440p"
laptop.price = 190
laptop.description = "foobar"
laptop.owner = john              # <-------------- as you can see here i need to specify the owner
laptop.save()

john.products.append(laptop)     # <-------------- and then append the new product into the user

Spected behaviour

I want to avoid this approach of doing two operations for something that is essentially the same thing. When creating a new product it should be automatically added to the user's collection. Like this:

...

laptop.owner = john
laptop.save()

john.products.objects()
>>> [<Product Thinkpad T440p>]

Models

Below you will see how i'm creating the models

from api import db

class Product(db.Document):
    name = db.StringField()
    price = db.DecimalField()
    description = db.StringField()
    owner = db.ReferenceField('User', required=True)

    def __repr__(self):
        return '<Product {}>'.format(self.name)

class User(db.Document):
    email = db.EmailField()
    name = db.StringField()
    products = db.ListField(db.ReferenceField('Product'))

    def __repr__(self):
        return '<User {}>'.format(self.username)


问:
Why does input field in my form has value of / and password field has value of dot?
I have been using express and ejs to render a login page.
When user submits form containing username and password and hence makes a post request, If there are any error then I want to re-render the page,
with error message. But want the fields to be empty if it is get request for login page.

I am passing username and password from express when I am rendering the page.
In ejs file, i am checking whether those username and password variables are undefined.
If they are then I am setting the value of fields to be empty strings and if they are passed from the
route then I am setting their value to be passed value

But, when I send a get request to login page, the form loads with value of '/' for username and '.' for password.

Note: I am also using express-flash if it makes any difference

I was expecting empty input fields when i send a get request and filled fields using previously entered value when i send post request with an error.


问:
Dynamic Dropdown Fields in Symfony Form (Symfony 6) don't return the selected Choice in AJAX
I'm trying to create a form that has 3 fields: Departamento, Provincia, Distrito (roughly equivalent to State, Province, City), so that choosing the first one fills the second one, and choosing the second one fills the third one.

The only field that is persisted is Distrito (since the entity already has information on the previous two).

The AJAX event returns the entire form, which is good, but it doesn't choose the proper option in the first Select field, and therefore returns an empty Select field for the second one (never mind events for the other fields, I haven't gotten that far).

I have tried the following JavaScript (ignore the references to $sport in the comments, they are from the example).

I'm trying to avoid using jQuery so I have substituted for the pure JavaScript versions of things, but I'm also trying it with the unmodified jQuery script and have the same problem.

The AJAX returns the form, no problem, but neither the form or the data objects contain the "departamento" that I sent in the data object. Originally I had the field be unMapped (so data wouldn't contain it) but now I'm trying with a mapped field (not ORMed) and checking the data object and it's also blank or whatever.

I've tried both POST_SET_DATA (because I also use it to set the values in the fields themselves IF there's no data - this functionality is commented right now), and PRE_SET_DATA. I don't seem to have a way to get the correct selected Departamento by the user.

```<code><script>
    var departamentoPartida = document.querySelector('#guia_remision_departamentoPartida');

    // When sport gets selected ...
    departamentoPartida.addEventListener('change', () => { // ... retrieve the corresponding form.
        var form = departamentoPartida.closest('form');
        // Simulate form data, but only include the selected sport value.
        var data = {};
        data[departamentoPartida.getAttribute('name')] = val(departamentoPartida);
        // Submit data via AJAX to the form's action path.

        console.log(JSON.stringify(data));
        fetch(form.getAttribute('action') ?? window.location.href, { // method: form.getAttribute('method'),
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        }).then(response => response.text()).then(text => { // console.log(text);
            const parser = new DOMParser();
            const htmlDocument = parser.parseFromString(text, "text/html");
            console.log(htmlDocument.documentElement.querySelector('#guia_remision_departamentoPartida'));
            const section = htmlDocument.documentElement.querySelector("#guia_remision_provinciaPartida");

            // Replace current position field ...
            // ... with the returned one from the AJAX response.
            document.querySelector('#guia_remision_provinciaPartida').replaceWith(section);
            // Position field now displays the appropriate positions.
        });
        // var $form = $(this).closest('form');
        // $.ajax({
        //     url: $form.attr('action'),
        //     type: $form.attr('method'),
        //     data: data,
        //     complete: function (html) { // Replace current position field ...
        //         console.log(html.responseText);
        //         $('#guia_remision_provinciaPartida').replaceWith(
        //             // ... with the returned one from the AJAX response.
        //                 $(html.responseText).find('#guia_remision_provinciaPartida')
        //         );
        //         // Position field now displays the appropriate positions.
        //     }
        // });
    });

...

</code>```

Here's the event listener in GuiaRemisionType.php, and associated function:

```<code>$agregarProvincias = function (
    FormInterface $form,
    ?UbigeoDepartamento $departamentoPartida,
) {
    $form
        ->add('provinciaPartida', EntityType::class, [
            'class' => UbigeoProvincia::class,
            'choice_label' => 'nombre',
            'choices' => isset($departamentoPartida) ? $departamentoPartida->getProvincias() : [],
            'mapped' => false,
            'required' => false,
        ])
};

$builder->addEventListener(
    FormEvents::POST_SET_DATA,
    function (FormEvent $event) use ($agregarProvincias) {
        $form = $event->getForm();
        /** @var GuiaRemision */
        $data = $event->getData();

        // obtener los datos de la entidad - IRRELEVANT FOR NOW
        // $entidadDistritoPartida = $data->getDistritoPartida();
        // $entidadProvinciaPartida = $entidadDistritoPartida?->getProvincia();
        // $entidadDepartamentoPartida = $entidadProvinciaPartida?->getDepartamento();

        // THE FIRST IS FOR UNMAPPED, SECOND FOR MAPPED FIELD
        // $departamentoPartida = $form->get('departamentoPartida')->getData() ?? $entidadDepartamentoPartida;
        $departamentoPartida = $data->getDepartamentoPartida();// ?? $entidadDepartamentoPartida;

        $agregarProvincias(
            $form,
            $departamentoPartida,
        );

        // $form->get('departamentoPartida')->setData($departamentoPartida);
...
</code>```


问:
Delete Query Helper & external ref path
I'm developing into PowerQuery a model that combine .Txt files contained into a folder with a specific path.
The question are two:

1- is it possible to insert the path of the folder from a cell into Excel? There is another way to change the path folder without open PowerQuery?

2- Once I connect PowerQuery to a folder path a "Query Helper" is generated automatically.
Why am I not able to delete this  "Query Helper"=
enter image description here

Title: Delete Query Helper & external ref path


问:
BouncyCastle in C# - Adding a subject with embedded commas to a Certificate Signing Request
I am using BouncyCastle 1.8.9 and C# .NET 5.0 to generate a Certificate Signing Request where one of the Organizational Unit values that must go in the subject contains an embedded comma:

OU=BANCO BILBAO VIZCAYA ARGENTARIA, S.A

If this is written verbatim in the dirName, BouncyCastle will correctly throw a "badly formated directory string" ArgumentException. Following the advice from this link, this OU value must be written delimited by quotes, which I have attempted in two different ways:

string subjectTest1 = "OU=\"BANCO BILBAO VIZCAYA ARGENTARIA, S.A\"";      // OPTION 1 - Using a string escape sequence

string subjectTest2 = @"OU=""BANCO BILBAO VIZCAYA ARGENTARIA, S.A""";     // OPTION 2 - Using a verbatim string literal

However, when checking the resulting subject name, an additional backslash is being added before the comma:

{OU=BANCO BILBAO VIZCAYA ARGENTARIA\, S.A}

¿Has someone encountered this problem before? If so, ¿how were you able to solve it?


问:
ZipArchive zip particular folder but not the root folder in Laravel
I am  trying to zip all files and folders, and it works fine in local XAMPP, but in Server it only works for the particular given Folder, not the root.

My function for zipping public folder containing folders and files which is in /home/admin/web/abc.com/public_html/public:

```<code>public function downloadProjectZip()
    {

        $rootPath = realpath('public');
        $exclusions=array('');
        $zip = new ZipArchive();
        $zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

        /** @var SplFileInfo[] $files */
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($rootPath),
            RecursiveIteratorIterator::LEAVES_ONLY
        );

        foreach($files as $name=>$file){
            if(!$file->isDir() && !in_array($file->getFilename(),$exclusions)){
                $filePath = $file->getRealPath();
                $relativePath = substr($filePath, strlen($rootPath) + 1);
                $zip->addFile($filePath, $relativePath);
            }
        }

        $zip->close();
        $fileurl = 'file.zip';
        if (file_exists($fileurl)) {
            return response()->download($fileurl, config('app.SITE_NAME').'-Project.zip', array('Content-Type: application/octet-stream','Content-Length: '. filesize($fileurl)))->deleteFileAfterSend(true);
        }
    }
</code>```

But When I $rootPath = realpath('') or $rootPath = realpath('/home/admin/web/oyebesmartest.com/public_html:/home/') for root, it gives me error:

```<code>SplFileInfo::isDir(): open_basedir restriction in effect. File(/home/admin/web/abc.com/public_html/..) is not within the allowed path(s): (/home/admin/web/abc.com/public_html:/home/admin/tmp)
</code>```

I gave 777 permission to ..public_html/*
and for check, I also gave 777 permission to abc.com/* but does not work.

How can I improve this function or alternative way to zip all files and folders of public_html/*

Body:
I am  trying to zip all files and folders, and it works fine in local XAMPP, but in Server it only works for the particular given Folder, not the root.

My function for zipping public folder containing folders and files which is in /home/admin/web/abc.com/public_html/public:

public function downloadProjectZip()
    {

        $rootPath = realpath('public');
        $exclusions=array('');
        $zip = new ZipArchive();
        $zip->open('file.zip', ZipArchive::CREATE | ZipArchive::OVERWRITE);

        /** @var SplFileInfo[] $files */
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($rootPath),
            RecursiveIteratorIterator::LEAVES_ONLY
        );

        foreach($files as $name=>$file){
            if(!$file->isDir() && !in_array($file->getFilename(),$exclusions)){
                $filePath = $file->getRealPath();
                $relativePath = substr($filePath, strlen($rootPath) + 1);
                $zip->addFile($filePath, $relativePath);
            }
        }

        $zip->close();
        $fileurl = 'file.zip';
        if (file_exists($fileurl)) {
            return response()->download($fileurl, config('app.SITE_NAME').'-Project.zip', array('Content-Type: application/octet-stream','Content-Length: '. filesize($fileurl)))->deleteFileAfterSend(true);
        }
    }

But When I $rootPath = realpath('') or $rootPath = realpath('/home/admin/web/oyebesmartest.com/public_html:/home/') for root, it gives me error:

SplFileInfo::isDir(): open_basedir restriction in effect. File(/home/admin/web/abc.com/public_html/..) is not within the allowed path(s): (/home/admin/web/abc.com/public_html:/home/admin/tmp)

I gave 777 permission to ..public_html/*
and for check, I also gave 777 permission to abc.com/* but does not work.

How can I improve this function or alternative way to zip all files and folders of public_html/*


问:
Error while connecting to supabase realtime server in python?
Error :

```<code>Traceback (most recent call last):
  File "/home/scelester/Desktop/finland-backend/test.py", line 16, in <module>
    s.connect()
  File "/home/scelester/Desktop/finland-backend/realtime/connection.py", line 90, in connect
    loop.run_until_complete(self._connect())
  File "/usr/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
  File "/home/scelester/Desktop/finland-backend/realtime/connection.py", line 94, in _connect
    ws_connection = await websockets.connect(self.url)
  File "/home/scelester/.virtualenvs/fin-land_rasp/lib/python3.9/site-packages/websockets/legacy/client.py", line 659, in __await_impl_timeout__
    return await asyncio.wait_for(self.__await_impl__(), self.open_timeout)
  File "/usr/lib/python3.9/asyncio/tasks.py", line 481, in wait_for
    return fut.result()
  File "/home/scelester/.virtualenvs/fin-land_rasp/lib/python3.9/site-packages/websockets/legacy/client.py", line 663, in __await_impl__
    _transport, _protocol = await self._create_connection()
  File "/usr/lib/python3.9/asyncio/base_events.py", line 1017, in create_connection
    infos = await self._ensure_resolved(
  File "/usr/lib/python3.9/asyncio/base_events.py", line 1396, in _ensure_resolved
    return await loop.getaddrinfo(host, port, family=family, type=type,
  File "/usr/lib/python3.9/asyncio/base_events.py", line 856, in getaddrinfo
    return await self.run_in_executor(
  File "/usr/lib/python3.9/concurrent/futures/thread.py", line 52, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/lib/python3.9/socket.py", line 953, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

</code>```

Screenshots

Here is my script that produces the error

System information

OS: Linux,Parrot os

Version of supabase-client    ==    0.2.5

Version of python == 3.9.2

version of realtime == 0.0.5

Additional context

Also i cant seem to install realtime version 0.1.1a0 as readme suggest

```<code>ERROR: Could not find a version that satisfies the requirement realtime==0.1.1a0 (from versions: 0.0.2, 0.0.3, 0.0.4, 0.0.5)
ERROR: No matching distribution found for realtime==0.1.1a0`pip install realtime==0.1.1a0
</code>```

Body:
Error :

Traceback (most recent call last):
  File "/home/scelester/Desktop/finland-backend/test.py", line 16, in <module>
    s.connect()
  File "/home/scelester/Desktop/finland-backend/realtime/connection.py", line 90, in connect
    loop.run_until_complete(self._connect())
  File "/usr/lib/python3.9/asyncio/base_events.py", line 642, in run_until_complete
    return future.result()
  File "/home/scelester/Desktop/finland-backend/realtime/connection.py", line 94, in _connect
    ws_connection = await websockets.connect(self.url)
  File "/home/scelester/.virtualenvs/fin-land_rasp/lib/python3.9/site-packages/websockets/legacy/client.py", line 659, in __await_impl_timeout__
    return await asyncio.wait_for(self.__await_impl__(), self.open_timeout)
  File "/usr/lib/python3.9/asyncio/tasks.py", line 481, in wait_for
    return fut.result()
  File "/home/scelester/.virtualenvs/fin-land_rasp/lib/python3.9/site-packages/websockets/legacy/client.py", line 663, in __await_impl__
    _transport, _protocol = await self._create_connection()
  File "/usr/lib/python3.9/asyncio/base_events.py", line 1017, in create_connection
    infos = await self._ensure_resolved(
  File "/usr/lib/python3.9/asyncio/base_events.py", line 1396, in _ensure_resolved
    return await loop.getaddrinfo(host, port, family=family, type=type,
  File "/usr/lib/python3.9/asyncio/base_events.py", line 856, in getaddrinfo
    return await self.run_in_executor(
  File "/usr/lib/python3.9/concurrent/futures/thread.py", line 52, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/usr/lib/python3.9/socket.py", line 953, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -2] Name or service not known

Screenshots

Here is my script that produces the error

System information

OS: Linux,Parrot os

Version of supabase-client    ==    0.2.5

Version of python == 3.9.2

version of realtime == 0.0.5

Additional context

Also i cant seem to install realtime version 0.1.1a0 as readme suggest

ERROR: Could not find a version that satisfies the requirement realtime==0.1.1a0 (from versions: 0.0.2, 0.0.3, 0.0.4, 0.0.5)
ERROR: No matching distribution found for realtime==0.1.1a0`pip install realtime==0.1.1a0


问:
Use ffmpeg to concatenate a video and a timelapse
Input 1: I used my phone to record a 25 fps movie with 1920x1080 resolution. There is sound.

Input 2: I used ffmpeg to create a timelapse movie i.e. 25 fps made out of 1920x1080 JPEGs. There is no sound.

When I tried to concatenate them however, the result was a mess: It seems some fine detail is not matching between the two inputs, because the resulting video squishes the time lapse down to just 1 frame at the end.

I have also tried this by first removing sound from video 1, so that both videos are soundless, and this does not give a different result.

How can I tell ffmpeg that the two inputs are not incongruent, so as to achieve a correct 25 fps 1920x1080 video using all the frames from both inputs?.


问:
Run php file in node
I have an application that I'm trying to migrate to a node server, but when it needs to query a file on my server, it always fails.

I managed to run the statics with Express, but when php makes a query it always returns an error similar to:

Cannot POST "/path-to-file/file.php"

The structure of the files is like this:

app

public

routes

index.php

statics

index.html

server.js

package.json

server.js:

```<code>const express = require('express');
const app = express();

app.listen(5000, () => console.log('Server is up and running'));

app.post('/', (req, res) => {
  res.send('POST request to the homepage')
})

app.use(express.static('public'));
</code>```

index.php :

```<code><?php

 $res = '<h1>Random Title'</h1>;

 $echo $res;
</code>```

index.html:

```<code><!DOCTYPE html>
<html>
<head>
    <title>Socket Sender</title>

</head>
<body onload="getPage()">
<div id="table_container">
</div>
<script language=javascript>
    function getPage(){
        fetch('path/to/file', {
      method: 'POST',
      mode: 'cors',
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(body),
    })
    .then((response) => response.text())
    .then((data) => {
      if(data){
        console.log(data);
      }
    }
    );
    }
</script>
</body>
</html>
</code>```

I would like help to know if it is possible to run these scripts in node or if I have to rewrite all of them

I'm new to node so if I said something absurd please ignore it

Title: Run php file in node

Body:
I have an application that I'm trying to migrate to a node server, but when it needs to query a file on my server, it always fails.

I managed to run the statics with Express, but when php makes a query it always returns an error similar to:

Cannot POST "/path-to-file/file.php"

The structure of the files is like this:

app

public

routes

index.php

statics

index.html

server.js

package.json

server.js:

const express = require('express');
const app = express();

app.listen(5000, () => console.log('Server is up and running'));

app.post('/', (req, res) => {
  res.send('POST request to the homepage')
})

app.use(express.static('public'));

index.php :

<?php

 $res = '
Random Title'
;

 $echo $res;

index.html:

<!DOCTYPE html>

    <title>Socket Sender</title>

I would like help to know if it is possible to run these scripts in node or if I have to rewrite all of them

I'm new to node so if I said something absurd please ignore it