问:
PHP snippet to allow mixed carts for certain products, but not all
I am pretty new to PHP, but I am attempting to modify a code snippet created by a previous employee. I use wordpress to host a woocommerce site. Within that site, we have 3 store locations, which we separate using product vendors. To prevent customers from adding products to their cart from multiple store locations, we have the below snippet.

We are trying to run a fundraising campagin where a product that is a donation amount can be added to anyone's cart, but disallowing multiple vendors is not letting it add. My thought was to create a new vendor and modify this code with if/elseif statements, but nothing I have tried works.

For reference, the ID of my fundraising vendor (which I want to be able to add to cart with any vendor) is 345

The vendor IDs for the store products I don't want to mix with eachother are 278, 277, and 279.

```<code>function so_validate_add_cart_item( $passed, $product_id, $quantity, $variation_id = '', $variations= '' ) {

    try {

          global $woocommerce;
    $items = $woocommerce->cart->get_cart(); //getting cart items
    $_product = array();
    foreach($items as $item => $values) {
    $_product[] = $values['data']->post;
    }
     $product_added_vendor_id = wp_get_object_terms( $product_id, WC_PRODUCT_VENDORS_TAXONOMY, array( 'fields' => 'ids' ) );  //get product id being added to cart

    foreach($_product as $productlal){
        if(isset($productlal)){
            $product_in_cart_vendor_id =  wp_get_object_terms( $productlal->ID, WC_PRODUCT_VENDORS_TAXONOMY, array( 'fields' => 'ids' ) );
            if( $product_in_cart_vendor_id[0] != $product_added_vendor_id[0] ){
                wc_add_notice(  __("Product not added to cart as it is from another location. Please complete the purchase from one store before buying from another. " . "<a class='button wc-forward' href='" . wc_get_cart_url() . "'>Go to cart to complete purchase ></a>"), $notice_type = 'error' );
                return false;
            }
         }
    }
     return $passed;
    }

 catch (Exception $e) {
    wc_add_notice(  __("EXCEPTION: " .  $e->getMessage()));
}
}
add_filter( 'woocommerce_add_to_cart_validation', 'so_validate_add_cart_item', 10, 5 );

</code>```

I attempted to change

```<code>if( $product_in_cart_vendor_id[0] != $product_added_vendor_id[0] ){
                wc_add_notice(  __("Product not added to cart as it is from another location. Please complete the purchase from one store before buying from another. " . "<a class='button wc-forward' href='" . wc_get_cart_url() . "'>Go to cart to complete purchase ></a>"), $notice_type = 'error' );
</code>```

to an elseif statment and add

```<code>if($product_in_cart_vendor_id[0]==="345")
</code>```

I also tested substituting "345" with the vendor name "fundraising" and added a wc_add_notice saying "thank you for your donation" after each try.

Body:
I am pretty new to PHP, but I am attempting to modify a code snippet created by a previous employee. I use wordpress to host a woocommerce site. Within that site, we have 3 store locations, which we separate using product vendors. To prevent customers from adding products to their cart from multiple store locations, we have the below snippet.

We are trying to run a fundraising campagin where a product that is a donation amount can be added to anyone's cart, but disallowing multiple vendors is not letting it add. My thought was to create a new vendor and modify this code with if/elseif statements, but nothing I have tried works.

For reference, the ID of my fundraising vendor (which I want to be able to add to cart with any vendor) is 345

The vendor IDs for the store products I don't want to mix with eachother are 278, 277, and 279.

function so_validate_add_cart_item( $passed, $product_id, $quantity, $variation_id = '', $variations= '' ) {

    try {

          global $woocommerce;
    $items = $woocommerce->cart->get_cart(); //getting cart items
    $_product = array();
    foreach($items as $item => $values) {
    $_product[] = $values['data']->post;
    }
     $product_added_vendor_id = wp_get_object_terms( $product_id, WC_PRODUCT_VENDORS_TAXONOMY, array( 'fields' => 'ids' ) );  //get product id being added to cart

    foreach($_product as $productlal){
        if(isset($productlal)){
            $product_in_cart_vendor_id =  wp_get_object_terms( $productlal->ID, WC_PRODUCT_VENDORS_TAXONOMY, array( 'fields' => 'ids' ) );
            if( $product_in_cart_vendor_id[0] != $product_added_vendor_id[0] ){
                wc_add_notice(  __("Product not added to cart as it is from another location. Please complete the purchase from one store before buying from another. " . "Go to cart to complete purchase >"), $notice_type = 'error' );
                return false;
            }
         }
    }
     return $passed;
    }

 catch (Exception $e) {
    wc_add_notice(  __("EXCEPTION: " .  $e->getMessage()));
}
}
add_filter( 'woocommerce_add_to_cart_validation', 'so_validate_add_cart_item', 10, 5 );

I attempted to change

if( $product_in_cart_vendor_id[0] != $product_added_vendor_id[0] ){
                wc_add_notice(  __("Product not added to cart as it is from another location. Please complete the purchase from one store before buying from another. " . "Go to cart to complete purchase >"), $notice_type = 'error' );

to an elseif statment and add

if($product_in_cart_vendor_id[0]==="345")

I also tested substituting "345" with the vendor name "fundraising" and added a wc_add_notice saying "thank you for your donation" after each try.


来源: stackexchange

问:
React trying to "let go" of item using blur
I am trying to "Let Go" of an item in React, but I am unsure of the correct method.

I am trying to use useRef to store the element .. But there seems to be no blur method available to it.  SO I know I am thinking about this wrong, but should you not be able to use useRef in order to activate things like .click and .blur ?

```<code>function Inbox() {
    const inboxItem = useRef(null);

    const toggleDrawer = (id) => () => {
        alert(id);
        inboxItem.blur; // Some sort of "let go / blur" command here
    };

    return (
        <a className="inbox-item" onClick={toggleDrawer(1)} ref={inboxItem}>
            <h4>item 1</h4>
        </a>
        <a className="inbox-item" onClick={toggleDrawer(2)} ref={inboxItem}>
            <h4>item 2</h4>
        </a>
    );
}

export default Inbox;
</code>```

I have a "swipe to delete" happening with these items, and it is interfering with the click event, as clicking on the item "holds" it ..  I need a function to be able to blur all inboxItems  -- Is my approach not viable?

ContentLicense: CC BY-SA 4.0

Body:
I am trying to "Let Go" of an item in React, but I am unsure of the correct method.

I am trying to use useRef to store the element .. But there seems to be no blur method available to it.  SO I know I am thinking about this wrong, but should you not be able to use useRef in order to activate things like .click and .blur ?

function Inbox() {
    const inboxItem = useRef(null);

    const toggleDrawer = (id) => () => {
        alert(id);
        inboxItem.blur; // Some sort of "let go / blur" command here
    };

    return (

item 1

item 2

    );
}

export default Inbox;

I have a "swipe to delete" happening with these items, and it is interfering with the click event, as clicking on the item "holds" it ..  I need a function to be able to blur all inboxItems  -- Is my approach not viable?


问:
How I can match the domain that cert is used for once I read them from a folder on nodejs?
In my application, I want to do the following:

  const fs = require('fs');
  const { exit } = require('process');

  let https;
  try {
    https = require('node:https');
  } catch (err) {
    console.log('https support is disabled!');
  }

  const cert_dir = '/etc/myapp/certs';
  const secureContext = {}

  fs.stat(cert_dir,(err,cb) => {
    if(err){
        console.log(err);
        exit(-1);
    }

    fs.readdir(cert_dir,(err, files) => {
        if (err){
            console.log(err);
        } else {
            files.filter(item => {
                return path.extname(item)=='.cert'
            }).forEach(file => {
                console.log(file);
                const cert = path.join(cert_dir,file);
                const key = path.join(cert_dir,(path.basename(file,".cert")+".key"))

                fs.stat(key, (err, stat) => {
                    if(err == null){
                        const x509 = new X509Certificate(fs.readFileSync(cert));
                        console.log("cert Info",x509);

                        // get domain here
                    }
                });
            });
        }
    });

  });

  const options = {
    SNICallback: function (domain, cb) {
        if (secureContext[domain]) {
            if (cb) {
                cb(null, secureContext[domain]);
            } else {
                // compatibility for older versions of node
                return secureContext[domain];
            }
        } else {
            throw new Error('No keys/certificates for domain requested');
        }
    },
    // must list a default key and cert because required by tls.createServer()
    key: fs.readFileSync('../path_to_key.pem'),
    cert: fs.readFileSync('../path_to_cert.crt'),
  };

  const server = https.createServer(options,handle);
  server.listen(449);
```
<p>The <code>/etc/myapp/certs</code> contains the following content:</p>
```cert1.crt
cert1.pem
cert2.crt
cert2.pem

```
<p>But according to this answer I need some certificate - domain association. In my case though, I see no association. Is there a way to somehow guess the domain out of a certificate?</p>
<p>At line:</p>
```const x509 = new X509Certificate(fs.readFileSync(cert));
```

I want to be able to extract the domain out of a certificate.

Body:
In my application, I want to do the following:

  const fs = require('fs');
  const { exit } = require('process');

  let https;
  try {
    https = require('node:https');
  } catch (err) {
    console.log('https support is disabled!');
  }

  const cert_dir = '/etc/myapp/certs';
  const secureContext = {}

  fs.stat(cert_dir,(err,cb) => {
    if(err){
        console.log(err);
        exit(-1);
    }

    fs.readdir(cert_dir,(err, files) => {
        if (err){
            console.log(err);
        } else {
            files.filter(item => {
                return path.extname(item)=='.cert'
            }).forEach(file => {
                console.log(file);
                const cert = path.join(cert_dir,file);
                const key = path.join(cert_dir,(path.basename(file,".cert")+".key"))

                fs.stat(key, (err, stat) => {
                    if(err == null){
                        const x509 = new X509Certificate(fs.readFileSync(cert));
                        console.log("cert Info",x509);

                        // get domain here
                    }
                });
            });
        }
    });

  });

  const options = {
    SNICallback: function (domain, cb) {
        if (secureContext[domain]) {
            if (cb) {
                cb(null, secureContext[domain]);
            } else {
                // compatibility for older versions of node
                return secureContext[domain];
            }
        } else {
            throw new Error('No keys/certificates for domain requested');
        }
    },
    // must list a default key and cert because required by tls.createServer()
    key: fs.readFileSync('../path_to_key.pem'),
    cert: fs.readFileSync('../path_to_cert.crt'),
  };

  const server = https.createServer(options,handle);
  server.listen(449);

The /etc/myapp/certs contains the following content:

cert1.crt
cert1.pem
cert2.crt
cert2.pem

But according to this answer I need some certificate - domain association. In my case though, I see no association. Is there a way to somehow guess the domain out of a certificate?

At line:

const x509 = new X509Certificate(fs.readFileSync(cert));

I want to be able to extract the domain out of a certificate.


问:
Parent fixed width (%), Two children autoadjust to parents width
I have been trying so many different solutions to solve this problem without reaching any solution that actually works so I cant post any css (since its not working properly, so I dont even know if its the correct "way" to build further on anyway).

Case: One div with width 100% (its parent varies in size) with two children inside. The div should never exceed hight of one text line/ text row.

```<code><div class="parent">
 <div class="child">Text from left</div>
 <div class="child">Text from right</div>
</div>
</code>```

Goal: Make the children divs auto adjust to fit as much text as possible (on that one row) and if the childrens width together exceed its parent div width then hide the overflowing text in second child with ellipsis.

Is this possible with pure CSS? With script I sort it but not with only CSS.

Thanks (sorry for bad english).

Body:
I have been trying so many different solutions to solve this problem without reaching any solution that actually works so I cant post any css (since its not working properly, so I dont even know if its the correct "way" to build further on anyway).

Case: One div with width 100% (its parent varies in size) with two children inside. The div should never exceed hight of one text line/ text row.

Text from left

Text from right

Goal: Make the children divs auto adjust to fit as much text as possible (on that one row) and if the childrens width together exceed its parent div width then hide the overflowing text in second child with ellipsis.

Is this possible with pure CSS? With script I sort it but not with only CSS.

Thanks (sorry for bad english).


问:
Why does left clicking a button run the function for right clicking a button? Python, tkinter
I'm trying to make a simple version of minesweeper using python. I have two functions, one for left clicking a button, to reveal the amount of bombs touching that button or if its a bomb, and another for right clicking a button to flag it.

```<code>def count_of_bombs(row, col):
    count = 0
    for y in range(len(board)):
        if y >= row-1 and y <= row+1:
            for x in range (len(board[y])):
                if x >= col-1 and x <= col+1:
                    if board[y][x] == 1:
                        count += 1
    return count

def clicked(row, col):
    if board[row][col] == 1:
        tk.Button(cv2, text='B', width=2, height=2, fg='blue').grid(row=row,column=col)
    elif board[row][col] == 0:
        tk.Button(cv2, text=count_of_bombs(row, col), width=2, height=2, fg='red').grid(row=row, column=col)

def right_button_clicked(chosen_row, chosen_col):
    if board[chosen_row][chosen_col] == 0:
        button = tk.Button(cv2, text="*", fg = "red", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>", lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 2
    elif board[chosen_row][chosen_col] == 2:
        button = tk.Button(cv2, text="", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>", lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 0
    elif board[chosen_row][chosen_col] == 1:
        button = tk.Button(cv2, text="*", fg="red", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>",lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 3
    elif board[chosen_row][chosen_col] == 3:
        button = tk.Button(cv2, text="", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>", lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 1
</code>```

However, when I left click a button, it runs the function for flagging the tile. But if I left click a button that has already been flagged, nothing happens. When right clicking, it works as normal, a blank tile gets flagged and a flagged tile gets unflagged.

Here's the entire code in case I overlooked something outside of the two functions.

```<code>import time
import tkinter as tk
from tkinter import *
import numpy as np

start_time=time.time() #starting the time
windows = tk.Tk()
windows.title('tk')
windows.geometry('450x700')

cv1 = tk.Canvas(windows, bg='white')
cv1.pack(side=TOP)
cv2 = tk.Canvas(windows, bg='white')
cv2.pack(side=BOTTOM)
cv3 = tk.Canvas(windows, bg='white')
cv3.pack(side=RIGHT)

bombs = [0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
np.random.shuffle(bombs)# randomizing the list so bombs are random
n = 16
board = list()
for i in range(0, len(bombs), n): #changing the list into a 16x16 2d list
    board.append(bombs[i:i+n])

c = 0
myText = """Welcome to MineSweeper!"""
def title():
    if c == 9:
        seconds = time.time() - start_time
        myText = "Success!! ElapsedTime:{:.0f} seconds".format(seconds)
        msg = Message(cv1, text=myText, width=190)
        msg.grid(row=0)
    if c != 9:
        myText = "Welcome to MineSweeper!"
        msg = Message(cv1, text=myText, width=180)
        msg.grid(row=0)

title()

def count_of_bombs(row, col):
    count = 0
    for y in range(len(board)):
        if y >= row-1 and y <= row+1:
            for x in range (len(board[y])):
                if x >= col-1 and x <= col+1:
                    if board[y][x] == 1:
                        count += 1
    return count

def clicked(row, col):
    if board[row][col] == 1:
        tk.Button(cv2, text='B', width=2, height=2, fg='blue').grid(row=row,column=col)
    elif board[row][col] == 0:
        tk.Button(cv2, text=count_of_bombs(row, col), width=2, height=2, fg='red').grid(row=row, column=col)

def right_button_clicked(chosen_row, chosen_col):
    if board[chosen_row][chosen_col] == 0:
        button = tk.Button(cv2, text="*", fg = "red", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>", lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 2
    elif board[chosen_row][chosen_col] == 2:
        button = tk.Button(cv2, text="", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>", lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 0
    elif board[chosen_row][chosen_col] == 1:
        button = tk.Button(cv2, text="*", fg="red", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>",lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 3
    elif board[chosen_row][chosen_col] == 3:
        button = tk.Button(cv2, text="", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>", lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 1

def both(row, col):
    clicked(row, col)
    right_button_clicked(row, col)

for i in range(16):
    for j in range(16):
        if board[i][j] == 0:
            button = tk.Button(cv2, text="", width=2, height=2,command=lambda current_i=i, current_j=j: both(current_i, current_j))
            button.grid(row=i, column=j)
            button.bind("<Button-3>", lambda e, current_row=i, current_col=j: right_button_clicked(current_row, current_col))
        if board[i][j] == 1:
            tk.Button(cv2, text="", width=2, height=2,command=lambda current_i=i, current_j=j: both(current_i, current_j)).grid(row=i, column=j)
            button.grid(row=i, column=j)
            button.bind("<Button-3>", lambda e, current_row=i, current_col=j: right_button_clicked(current_row, current_col))

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

I tried removing the button.bind function from the second set of buttons that are mines

```<code>if board[i][j] == 1:
    tk.Button(cv2, text="", width=2, height=2,command=lambda current_i=i, current_j=j: both(current_i, current_j)).grid(row=i, column=j)
</code>```

but that just made it so when I right clicked a mine, nothing happens.

I tried switching around the order of the functions in the both() function,

```<code>def both(row, col):
    clicked(row, col)
    right_button_clicked(row, col)

</code>```

but that didn't change anything.

I'm not sure if I made a mistake somewhere, if there's something simple I overlooked, or if I need to completely restart and implement everything in a different way.

Body:
I'm trying to make a simple version of minesweeper using python. I have two functions, one for left clicking a button, to reveal the amount of bombs touching that button or if its a bomb, and another for right clicking a button to flag it.

def count_of_bombs(row, col):
    count = 0
    for y in range(len(board)):
        if y >= row-1 and y <= row+1:
            for x in range (len(board[y])):
                if x >= col-1 and x <= col+1:
                    if board[y][x] == 1:
                        count += 1
    return count

def clicked(row, col):
    if board[row][col] == 1:
        tk.Button(cv2, text='B', width=2, height=2, fg='blue').grid(row=row,column=col)
    elif board[row][col] == 0:
        tk.Button(cv2, text=count_of_bombs(row, col), width=2, height=2, fg='red').grid(row=row, column=col)

def right_button_clicked(chosen_row, chosen_col):
    if board[chosen_row][chosen_col] == 0:
        button = tk.Button(cv2, text="*", fg = "red", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>", lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 2
    elif board[chosen_row][chosen_col] == 2:
        button = tk.Button(cv2, text="", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>", lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 0
    elif board[chosen_row][chosen_col] == 1:
        button = tk.Button(cv2, text="*", fg="red", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>",lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 3
    elif board[chosen_row][chosen_col] == 3:
        button = tk.Button(cv2, text="", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>", lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 1

However, when I left click a button, it runs the function for flagging the tile. But if I left click a button that has already been flagged, nothing happens. When right clicking, it works as normal, a blank tile gets flagged and a flagged tile gets unflagged.

Here's the entire code in case I overlooked something outside of the two functions.

import time
import tkinter as tk
from tkinter import *
import numpy as np

start_time=time.time() #starting the time
windows = tk.Tk()
windows.title('tk')
windows.geometry('450x700')

cv1 = tk.Canvas(windows, bg='white')
cv1.pack(side=TOP)
cv2 = tk.Canvas(windows, bg='white')
cv2.pack(side=BOTTOM)
cv3 = tk.Canvas(windows, bg='white')
cv3.pack(side=RIGHT)

bombs = [0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
np.random.shuffle(bombs)# randomizing the list so bombs are random
n = 16
board = list()
for i in range(0, len(bombs), n): #changing the list into a 16x16 2d list
    board.append(bombs[i:i+n])

c = 0
myText = """Welcome to MineSweeper!"""
def title():
    if c == 9:
        seconds = time.time() - start_time
        myText = "Success!! ElapsedTime:{:.0f} seconds".format(seconds)
        msg = Message(cv1, text=myText, width=190)
        msg.grid(row=0)
    if c != 9:
        myText = "Welcome to MineSweeper!"
        msg = Message(cv1, text=myText, width=180)
        msg.grid(row=0)

title()

def count_of_bombs(row, col):
    count = 0
    for y in range(len(board)):
        if y >= row-1 and y <= row+1:
            for x in range (len(board[y])):
                if x >= col-1 and x <= col+1:
                    if board[y][x] == 1:
                        count += 1
    return count

def clicked(row, col):
    if board[row][col] == 1:
        tk.Button(cv2, text='B', width=2, height=2, fg='blue').grid(row=row,column=col)
    elif board[row][col] == 0:
        tk.Button(cv2, text=count_of_bombs(row, col), width=2, height=2, fg='red').grid(row=row, column=col)

def right_button_clicked(chosen_row, chosen_col):
    if board[chosen_row][chosen_col] == 0:
        button = tk.Button(cv2, text="*", fg = "red", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>", lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 2
    elif board[chosen_row][chosen_col] == 2:
        button = tk.Button(cv2, text="", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>", lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 0
    elif board[chosen_row][chosen_col] == 1:
        button = tk.Button(cv2, text="*", fg="red", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>",lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 3
    elif board[chosen_row][chosen_col] == 3:
        button = tk.Button(cv2, text="", width=2, height=2,command=lambda current_i=i, current_j=j: right_button_clicked(current_i, current_j))
        button.grid(row=chosen_row, column=chosen_col)
        button.bind("<Button-3>", lambda e, current_row=chosen_row, current_col=chosen_col: right_button_clicked(current_row, current_col))
        board[chosen_row][chosen_col] = 1

def both(row, col):
    clicked(row, col)
    right_button_clicked(row, col)

for i in range(16):
    for j in range(16):
        if board[i][j] == 0:
            button = tk.Button(cv2, text="", width=2, height=2,command=lambda current_i=i, current_j=j: both(current_i, current_j))
            button.grid(row=i, column=j)
            button.bind("<Button-3>", lambda e, current_row=i, current_col=j: right_button_clicked(current_row, current_col))
        if board[i][j] == 1:
            tk.Button(cv2, text="", width=2, height=2,command=lambda current_i=i, current_j=j: both(current_i, current_j)).grid(row=i, column=j)
            button.grid(row=i, column=j)
            button.bind("<Button-3>", lambda e, current_row=i, current_col=j: right_button_clicked(current_row, current_col))

tk.mainloop()

I tried removing the button.bind function from the second set of buttons that are mines

if board[i][j] == 1:
    tk.Button(cv2, text="", width=2, height=2,command=lambda current_i=i, current_j=j: both(current_i, current_j)).grid(row=i, column=j)

but that just made it so when I right clicked a mine, nothing happens.

I tried switching around the order of the functions in the both() function,

def both(row, col):
    clicked(row, col)
    right_button_clicked(row, col)

but that didn't change anything.

I'm not sure if I made a mistake somewhere, if there's something simple I overlooked, or if I need to completely restart and implement everything in a different way.


问:
How to place agents on multiple nodes in AnyLogic
I was trying to put certain number of agents on multiple nodes. For that - I have created following loop and wrote in Person agent's tab startup.

```<code>for (int i=0; i<2;i++){
    main.varA = main.collection.get(i);
    Person myAgent=this;
    Point pt = main.varA.randomPointInside();
    myAgent.setLocation(pt);
}
</code>```

It seems loop is not working. When I put i<3, it is putting people only on 3rd node, when i<2 it's putting only on 2nd node and when i<1 it's putting only on 1st node. Could anyone please help me, why is happening?

main agent picture

Body:
I was trying to put certain number of agents on multiple nodes. For that - I have created following loop and wrote in Person agent's tab startup.

for (int i=0; i<2;i++){
    main.varA = main.collection.get(i);
    Person myAgent=this;
    Point pt = main.varA.randomPointInside();
    myAgent.setLocation(pt);
}

It seems loop is not working. When I put i<3, it is putting people only on 3rd node, when i<2 it's putting only on 2nd node and when i<1 it's putting only on 1st node. Could anyone please help me, why is happening?

main agent picture


问:
Bulk check-in files in SharePoint online large list
trying to bulk check in files in a list containing over 400K files
tried without CAML query, but it takes forever.
with the query, getting threshold error even with rowlimit.
is there any other way?</p>
```<code>$Result = @() #Result array

#Provide SPO Site URL
$SiteUrl = "https://contoso"

#Provide List/Document Library name
$ListName = "list"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -interactive

#CAML Query to filter only Checked-out files
$CAMLQuery = "
<View Scope='RecursiveAll'>
    <Query>
        <Where>
            <IsNotNull><FieldRef Name='CheckoutUser' /></IsNotNull>
        </Where>
    </Query>
    <RowLimit>1000</RowLimit>
</View>"

#Query All Checked out files
$ListItems = Get-PnPListItem -List $ListName -PageSize 1000 -Query $CAMLQuery
$i = 0;
$TotalFiles = $ListItems.Count

#Iterate checked-out files one by one and check-in
.......
</code>```

Body:
trying to bulk check in files in a list containing over 400K files
tried without CAML query, but it takes forever.
with the query, getting threshold error even with rowlimit.
is there any other way?

$Result = @() #Result array

#Provide SPO Site URL
$SiteUrl = "https://contoso"

#Provide List/Document Library name
$ListName = "list"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -interactive

#CAML Query to filter only Checked-out files
$CAMLQuery = "
<View Scope='RecursiveAll'>
    <Query>
        <Where>
            <IsNotNull><FieldRef Name='CheckoutUser' /></IsNotNull>
        </Where>
    </Query>
    <RowLimit>1000</RowLimit>
</View>"

#Query All Checked out files
$ListItems = Get-PnPListItem -List $ListName -PageSize 1000 -Query $CAMLQuery
$i = 0;
$TotalFiles = $ListItems.Count

#Iterate checked-out files one by one and check-in
.......


问:
Can Next.js on-demand revalidation be done at large scale?
I am working on a website with 500 000 products and we are trying ISR to keep the pages up to date. Things like price can be SEO sensitive, so it would be nice if we are not showing yesterday's prices.

Here are the possible solutions I see:

A) Pretend that it is fine with a few hour long revalidate timeout and hope that google will not penalise due to too many product prices not matching the product feeds that we send them. (Unpopular products won't get updated, may be crawlers can help us in this case?)

B) Correct the price client side. (Can't ensure which price the bot will see)

C) Redeploy and somehow mass rebuild all pages nightly.. (are we even talking about ISR at this point)

D) Use on-demand revalidation (No way vercel's lambdas can handle the whole site rebuilt)

Frequent deployments would also kill what has been cached, mass cache warming would be very much against the spirit of ISR.. I guess we shouldn't DoS our own website just to keep a numeric value up to date.

All of these solutions sound hacky to me and I am wondering if I am overthinking this and being too cautious. Can anybody share their experience with running large scale e-commerce websites using Next and ISR? I am not looking for a specific prescription as everybody's use case varies slightly in the semantics, just general advice that I won't find in the docs.


问:
"ValueError: Unable to create tensor" when trying to train a hugging face transformer
I am trying to use the "visheratin/t5-efficient-mini-grammar-correction" pre-trained model for grammar correction and I would like to add my own training examples.

I've loaded the model:

```<code>model = AutoModelForSeq2SeqLM.from_pretrained("visheratin/t5-efficient-mini-grammar-correction")
tokenizer = AutoTokenizer.from_pretrained("visheratin/t5-efficient-mini-grammar-correction")
</code>```

set the training arguments:

```<code>training_args = TrainingArguments(
    output_dir="./models",
    num_train_epochs=3,
    per_device_train_batch_size=8,
    learning_rate=3e-5,
    weight_decay=0.01,
)
</code>```

and created the training data:

```<code>training_examples = [ ('input text 1', 'output text 1'), ('input text 2', 'output text 2') ]

train_data = []
for input_text, target_text in training_examples:
    input_ids = tokenizer.encode(input_text, return_tensors="pt", truncation=True, padding=True)
    target_ids = tokenizer.encode(target_text, return_tensors="pt", truncation=True, padding=True)
    train_data.append({
        'input_ids': input_ids,
        'attention_mask': torch.ones_like(input_ids),
        'labels': target_ids,
    })
</code>```

but when I go to train:

```<code>trainer = Trainer(
    model=model,
    tokenizer=tokenizer,
    args=training_args,
    train_dataset=train_data,
)
trainer.train()
</code>```

I get this error:

```<code>ValueError: Unable to create tensor, you should probably activate truncation and/or
padding with 'padding=True' 'truncation=True' to have batched tensors with the same
length. Perhaps your features (`input_ids` in this case) have excessive nesting (inputs
type `list` where type `int` is expected).
</code>```

I already have 'padding=True' and 'truncation=True' to tokenizer.encode() and as far as I can tell I do not have any excessive nesting in my features.

This is the full Traceback:

```<code>ValueError                                Traceback (most recent call last)
File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/tokenization_utils_base.py:715, in BatchEncoding.convert_to_tensors(self, tensor_type, prepend_batch_axis)
    714 if not is_tensor(value):
--> 715     tensor = as_tensor(value)
    717     # Removing this for now in favor of controlling the shape with `prepend_batch_axis`
    718     # # at-least2d
    719     # if tensor.ndim > 2:
    720     #     tensor = tensor.squeeze(0)
    721     # elif tensor.ndim < 2:
    722     #     tensor = tensor[None, :]

ValueError: expected sequence of length 37 at dim 2 (got 44)

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
Cell In[104], line 1
----> 1 trainer.train()

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/trainer.py:1501, in Trainer.train(self, resume_from_checkpoint, trial, ignore_keys_for_eval, **kwargs)
   1496     self.model_wrapped = self.model
   1498 inner_training_loop = find_executable_batch_size(
   1499     self._inner_training_loop, self._train_batch_size, args.auto_find_batch_size
   1500 )
-> 1501 return inner_training_loop(
   1502     args=args,
   1503     resume_from_checkpoint=resume_from_checkpoint,
   1504     trial=trial,
   1505     ignore_keys_for_eval=ignore_keys_for_eval,
   1506 )

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/trainer.py:1723, in Trainer._inner_training_loop(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval)
   1720     self._load_rng_state(resume_from_checkpoint)
   1722 step = -1
-> 1723 for step, inputs in enumerate(epoch_iterator):
   1724
   1725     # Skip past any already trained steps if resuming training
   1726     if steps_trained_in_current_epoch > 0:
   1727         steps_trained_in_current_epoch -= 1

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/torch/utils/data/dataloader.py:628, in _BaseDataLoaderIter.__next__(self)
    625 if self._sampler_iter is None:
    626     # TODO(https://github.com/pytorch/pytorch/issues/76750)
    627     self._reset()  # type: ignore[call-arg]
--> 628 data = self._next_data()
    629 self._num_yielded += 1
    630 if self._dataset_kind == _DatasetKind.Iterable and \
    631         self._IterableDataset_len_called is not None and \
    632         self._num_yielded > self._IterableDataset_len_called:

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/torch/utils/data/dataloader.py:671, in _SingleProcessDataLoaderIter._next_data(self)
    669 def _next_data(self):
    670     index = self._next_index()  # may raise StopIteration
--> 671     data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
    672     if self._pin_memory:
    673         data = _utils.pin_memory.pin_memory(data, self._pin_memory_device)

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py:61, in _MapDatasetFetcher.fetch(self, possibly_batched_index)
     59 else:
     60     data = self.dataset[possibly_batched_index]
---> 61 return self.collate_fn(data)

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/trainer_utils.py:696, in RemoveColumnsCollator.__call__(self, features)
    694 def __call__(self, features: List[dict]):
    695     features = [self._remove_columns(feature) for feature in features]
--> 696     return self.data_collator(features)

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/data/data_collator.py:249, in DataCollatorWithPadding.__call__(self, features)
    248 def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
--> 249     batch = self.tokenizer.pad(
    250         features,
    251         padding=self.padding,
    252         max_length=self.max_length,
    253         pad_to_multiple_of=self.pad_to_multiple_of,
    254         return_tensors=self.return_tensors,
    255     )
    256     if "label" in batch:
    257         batch["labels"] = batch["label"]

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/tokenization_utils_base.py:2985, in PreTrainedTokenizerBase.pad(self, encoded_inputs, padding, max_length, pad_to_multiple_of, return_attention_mask, return_tensors, verbose)
   2982             batch_outputs[key] = []
   2983         batch_outputs[key].append(value)
-> 2985 return BatchEncoding(batch_outputs, tensor_type=return_tensors)

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/tokenization_utils_base.py:210, in BatchEncoding.__init__(self, data, encoding, tensor_type, prepend_batch_axis, n_sequences)
    206     n_sequences = encoding[0].n_sequences
    208 self._n_sequences = n_sequences
--> 210 self.convert_to_tensors(tensor_type=tensor_type, prepend_batch_axis=prepend_batch_axis)

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/tokenization_utils_base.py:731, in BatchEncoding.convert_to_tensors(self, tensor_type, prepend_batch_axis)
    726         if key == "overflowing_tokens":
    727             raise ValueError(
    728                 "Unable to create tensor returning overflowing tokens of different lengths. "
    729                 "Please see if a fast version of this tokenizer is available to have this feature available."
    730             )
--> 731         raise ValueError(
    732             "Unable to create tensor, you should probably activate truncation and/or padding with"
    733             " 'padding=True' 'truncation=True' to have batched tensors with the same length. Perhaps your"
    734             f" features (`{key}` in this case) have excessive nesting (inputs type `list` where type `int` is"
    735             " expected)."
    736         )
    738 return self

ValueError: Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' 'truncation=True' to have batched tensors with the same length. Perhaps your features (`input_ids` in this case) have excessive nesting (inputs type `list` where type `int` is expected).
</code>```

Could someone please help me understand what could be causing this error?

Body:
I am trying to use the "visheratin/t5-efficient-mini-grammar-correction" pre-trained model for grammar correction and I would like to add my own training examples.

I've loaded the model:

model = AutoModelForSeq2SeqLM.from_pretrained("visheratin/t5-efficient-mini-grammar-correction")
tokenizer = AutoTokenizer.from_pretrained("visheratin/t5-efficient-mini-grammar-correction")

set the training arguments:

training_args = TrainingArguments(
    output_dir="./models",
    num_train_epochs=3,
    per_device_train_batch_size=8,
    learning_rate=3e-5,
    weight_decay=0.01,
)

and created the training data:

training_examples = [ ('input text 1', 'output text 1'), ('input text 2', 'output text 2') ]

train_data = []
for input_text, target_text in training_examples:
    input_ids = tokenizer.encode(input_text, return_tensors="pt", truncation=True, padding=True)
    target_ids = tokenizer.encode(target_text, return_tensors="pt", truncation=True, padding=True)
    train_data.append({
        'input_ids': input_ids,
        'attention_mask': torch.ones_like(input_ids),
        'labels': target_ids,
    })

but when I go to train:

trainer = Trainer(
    model=model,
    tokenizer=tokenizer,
    args=training_args,
    train_dataset=train_data,
)
trainer.train()

I get this error:

ValueError: Unable to create tensor, you should probably activate truncation and/or
padding with 'padding=True' 'truncation=True' to have batched tensors with the same
length. Perhaps your features (`input_ids` in this case) have excessive nesting (inputs
type `list` where type `int` is expected).

I already have 'padding=True' and 'truncation=True' to tokenizer.encode() and as far as I can tell I do not have any excessive nesting in my features.

This is the full Traceback:

ValueError                                Traceback (most recent call last)
File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/tokenization_utils_base.py:715, in BatchEncoding.convert_to_tensors(self, tensor_type, prepend_batch_axis)
    714 if not is_tensor(value):
--> 715     tensor = as_tensor(value)
    717     # Removing this for now in favor of controlling the shape with `prepend_batch_axis`
    718     # # at-least2d
    719     # if tensor.ndim > 2:
    720     #     tensor = tensor.squeeze(0)
    721     # elif tensor.ndim < 2:
    722     #     tensor = tensor[None, :]

ValueError: expected sequence of length 37 at dim 2 (got 44)

During handling of the above exception, another exception occurred:

ValueError                                Traceback (most recent call last)
Cell In[104], line 1
----> 1 trainer.train()

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/trainer.py:1501, in Trainer.train(self, resume_from_checkpoint, trial, ignore_keys_for_eval, **kwargs)
   1496     self.model_wrapped = self.model
   1498 inner_training_loop = find_executable_batch_size(
   1499     self._inner_training_loop, self._train_batch_size, args.auto_find_batch_size
   1500 )
-> 1501 return inner_training_loop(
   1502     args=args,
   1503     resume_from_checkpoint=resume_from_checkpoint,
   1504     trial=trial,
   1505     ignore_keys_for_eval=ignore_keys_for_eval,
   1506 )

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/trainer.py:1723, in Trainer._inner_training_loop(self, batch_size, args, resume_from_checkpoint, trial, ignore_keys_for_eval)
   1720     self._load_rng_state(resume_from_checkpoint)
   1722 step = -1
-> 1723 for step, inputs in enumerate(epoch_iterator):
   1724
   1725     # Skip past any already trained steps if resuming training
   1726     if steps_trained_in_current_epoch > 0:
   1727         steps_trained_in_current_epoch -= 1

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/torch/utils/data/dataloader.py:628, in _BaseDataLoaderIter.__next__(self)
    625 if self._sampler_iter is None:
    626     # TODO(https://github.com/pytorch/pytorch/issues/76750)
    627     self._reset()  # type: ignore[call-arg]
--> 628 data = self._next_data()
    629 self._num_yielded += 1
    630 if self._dataset_kind == _DatasetKind.Iterable and \
    631         self._IterableDataset_len_called is not None and \
    632         self._num_yielded > self._IterableDataset_len_called:

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/torch/utils/data/dataloader.py:671, in _SingleProcessDataLoaderIter._next_data(self)
    669 def _next_data(self):
    670     index = self._next_index()  # may raise StopIteration
--> 671     data = self._dataset_fetcher.fetch(index)  # may raise StopIteration
    672     if self._pin_memory:
    673         data = _utils.pin_memory.pin_memory(data, self._pin_memory_device)

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py:61, in _MapDatasetFetcher.fetch(self, possibly_batched_index)
     59 else:
     60     data = self.dataset[possibly_batched_index]
---> 61 return self.collate_fn(data)

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/trainer_utils.py:696, in RemoveColumnsCollator.__call__(self, features)
    694 def __call__(self, features: List[dict]):
    695     features = [self._remove_columns(feature) for feature in features]
--> 696     return self.data_collator(features)

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/data/data_collator.py:249, in DataCollatorWithPadding.__call__(self, features)
    248 def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]:
--> 249     batch = self.tokenizer.pad(
    250         features,
    251         padding=self.padding,
    252         max_length=self.max_length,
    253         pad_to_multiple_of=self.pad_to_multiple_of,
    254         return_tensors=self.return_tensors,
    255     )
    256     if "label" in batch:
    257         batch["labels"] = batch["label"]

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/tokenization_utils_base.py:2985, in PreTrainedTokenizerBase.pad(self, encoded_inputs, padding, max_length, pad_to_multiple_of, return_attention_mask, return_tensors, verbose)
   2982             batch_outputs[key] = []
   2983         batch_outputs[key].append(value)
-> 2985 return BatchEncoding(batch_outputs, tensor_type=return_tensors)

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/tokenization_utils_base.py:210, in BatchEncoding.__init__(self, data, encoding, tensor_type, prepend_batch_axis, n_sequences)
    206     n_sequences = encoding[0].n_sequences
    208 self._n_sequences = n_sequences
--> 210 self.convert_to_tensors(tensor_type=tensor_type, prepend_batch_axis=prepend_batch_axis)

File ~/opt/miniconda3/envs/ub_nbdev2/lib/python3.10/site-packages/transformers/tokenization_utils_base.py:731, in BatchEncoding.convert_to_tensors(self, tensor_type, prepend_batch_axis)
    726         if key == "overflowing_tokens":
    727             raise ValueError(
    728                 "Unable to create tensor returning overflowing tokens of different lengths. "
    729                 "Please see if a fast version of this tokenizer is available to have this feature available."
    730             )
--> 731         raise ValueError(
    732             "Unable to create tensor, you should probably activate truncation and/or padding with"
    733             " 'padding=True' 'truncation=True' to have batched tensors with the same length. Perhaps your"
    734             f" features (`{key}` in this case) have excessive nesting (inputs type `list` where type `int` is"
    735             " expected)."
    736         )
    738 return self

ValueError: Unable to create tensor, you should probably activate truncation and/or padding with 'padding=True' 'truncation=True' to have batched tensors with the same length. Perhaps your features (`input_ids` in this case) have excessive nesting (inputs type `list` where type `int` is expected).

Could someone please help me understand what could be causing this error?


问:
How to configure source lookup path for Debug in C++ in eclipse?
I have a project which im working in with C++20 in Eclise IDE, I'm using CygWin 3.4.0-1 compiler. I edited my source lookup path for my main file as gdb had the wrong route, now i can see the main file while debugging, but it won't find the source file for any other included file that is not the main.
This is one of the errors i get:

Can't find a source file at "/usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/x86_64-pc-cygwin/bits/Pin.hpp"

If I locate the file with the actual Pin.hpp, the debugger will show it to me but the instructions it's running make no sense when going step by step.

This is my source lookup path configuration:


问:
Safari extension - Save stats to storage, then display it
Example: I have created safari extension, which, after the page loads, replaces all words "fish" with the fish emoji. I want to count how many words I replaced and store that number (total number of replaces since installing the extension). When I click on the extension icon in toolbar, I want to see that total number.

content.js handles the replacing

popup.js handles the toolbar icon menu

I only need the storing capability implemented, so I need a function in content.js called SomehowStoreThisValue() and in popup.js function SomehowRetrieveThisValue()

What I've tried: (Using the local storage)

content.js:

```<code>browser.runtime.sendMessage({
   data: "Hello popup, how are you"
   }, function (response) {
       console.dir(response);
   });
</code>```

popup.js:

```<code>browser.runtime.onMessage.addListener(function (message, sender, sendResponse) {

    sendResponse({
        data: "I am fine, thank you. How is life in the background?"
    });

    let my_value = parseInt(localStorage.getItem('stored_value'));

    document.getElementById("MY_ID").innerHTML = my_value;

    localStorage.setItem('stored_value', my_value + 1);

});
</code>```

Which does work, but only when the popup is open, when the replacement is happening, which is not ideal.

Body:
Example: I have created safari extension, which, after the page loads, replaces all words "fish" with the fish emoji. I want to count how many words I replaced and store that number (total number of replaces since installing the extension). When I click on the extension icon in toolbar, I want to see that total number.

content.js handles the replacing

popup.js handles the toolbar icon menu

I only need the storing capability implemented, so I need a function in content.js called SomehowStoreThisValue() and in popup.js function SomehowRetrieveThisValue()

What I've tried: (Using the local storage)

content.js:

browser.runtime.sendMessage({
   data: "Hello popup, how are you"
   }, function (response) {
       console.dir(response);
   });

popup.js:

browser.runtime.onMessage.addListener(function (message, sender, sendResponse) {

    sendResponse({
        data: "I am fine, thank you. How is life in the background?"
    });

    let my_value = parseInt(localStorage.getItem('stored_value'));

    document.getElementById("MY_ID").innerHTML = my_value;

    localStorage.setItem('stored_value', my_value + 1);

});

Which does work, but only when the popup is open, when the replacement is happening, which is not ideal.


问:
Does AWS ApiGateway Socket Splits Messages at 4 KB?
I'm trying to implement WebRTC Signalling Server using AWS ApiGateway with javascript in order to connect 2 clients (Client A - Web Browser; Client B - Unreal Engine's PixelStreaming Plugin).

(Note: For this implementation I'm not using the signalling sever implementation provided by Unreal, but I'm creating a replacement implementation using AWS ApiGateway)

At first I connect successfully both clients to the Api Gateway WebSocket sever and setup the required configuration.

Then I'm generating the WebRTC "offer" from the browser (Client A) and send it using method ApiGatewayManagementApiClient::PostToConnectionCommand (JS AWS SDK v3) via Lambda to the receiver's ConnectionID (Client B). I expect when the receiver (Client B) get the offer to generate an "answer". Instead of an answer from Client B I get the following error:

```<code>Error: Failed to parse SS message ...<message-chunk>...
</code>```

In the logs I get this error 2 times but with different chunks of my offer (first beginning of the JSON and second somewhere in the middle). This lead me to believe that the message got split, so I tried removing parts of the JSON (shorten it) until I stop getting the error. Doing this I found that this error disappears when the exact length of the JSON message is 4096 chars (4 KB). When I send event one byte over this I get the error (2 times).

According to AWS documentation they have a maximum frame size of 32 KB. My full message is around 7 KB, so I expect that it is going to be sent at once. Unfortunately this doesn't seem to be the case my message is split to 4 KB mark.

I have working implementation of the exact same case in NodeJS and building a custom server with the ws library. Inside this implementation everything is working correctly (my 7 KB offer get delivered in once piece and I receive answer and the connection is initiated without errors). I send "offer" and then receive "answer" back.

I've used wscat to connect to both servers (the NodeJS and the ApiGateway) assuming the role of Client B and I got both "offers". Then I compared them
and they are exactly the same. (In wscat the message doesn't look to be split, but I assume that they concat the chunks before showing it.)

Based on that I can assert that I'm configuring the clients properly and that the "offer" is good to receive "answer". The only difference is that if I send the offer from the NodeJS I receive answer and all works, but if I send exactly the same offer from AWS ApiGateway I got error that the data cannot be parsed (because it is split in 4 KB chunks).

I have spent 3 days trying to resolve this issue and I'm certain that everything I send and the way I send it is correct. So I come to conclusion that I for some reason hit some limit in AWS API Gateway or Lambda (I saw that Lambda has 4 KB limit on environment variables, but I'm not using them so it should not be related) which causes my message to be split in parts. This causes the Unreal's Pixel Streaming Plugin to try deserialize the JSON in chunks instead of the whole JSON message at once and this results in 2 errors that the data cannot be parsed.

I cannot change the code of the client to first wait all the chunks to arrive and then process it. I have to use it "as is". (It is a plugin and it is written in C++)

I also tried to relay the API API Gateway Socket Message via NodeJS client and then to create a NodeJS Web Socket server connect the Unreal Engine Plugin to my NodeJS server and forward the message via it to the Unreal Engine Plugin. (AWS -> NodeJS Client -> NodeJS Server -> Unreal instead of AWS -> Unreal). This variant is working correctly without problem and I receive answer. The problem is that I introduce an additional NodeJS client and Server which beats the purpose of using API Gateway at first place...

So my question is: Is is possible that AWS API Gateway is splitting my  message in 4KB chunks (or Lambda does it) and if it is so is it possible to somehow increase this limit so I receive the whole message at once instead?

I can provide code in case it is needed, but I don't think the problem is related to the concrete implementation.

Body:
I'm trying to implement WebRTC Signalling Server using AWS ApiGateway with javascript in order to connect 2 clients (Client A - Web Browser; Client B - Unreal Engine's PixelStreaming Plugin).

(Note: For this implementation I'm not using the signalling sever implementation provided by Unreal, but I'm creating a replacement implementation using AWS ApiGateway)

At first I connect successfully both clients to the Api Gateway WebSocket sever and setup the required configuration.

Then I'm generating the WebRTC "offer" from the browser (Client A) and send it using method ApiGatewayManagementApiClient::PostToConnectionCommand (JS AWS SDK v3) via Lambda to the receiver's ConnectionID (Client B). I expect when the receiver (Client B) get the offer to generate an "answer". Instead of an answer from Client B I get the following error:

Error: Failed to parse SS message ...<message-chunk>...

In the logs I get this error 2 times but with different chunks of my offer (first beginning of the JSON and second somewhere in the middle). This lead me to believe that the message got split, so I tried removing parts of the JSON (shorten it) until I stop getting the error. Doing this I found that this error disappears when the exact length of the JSON message is 4096 chars (4 KB). When I send event one byte over this I get the error (2 times).

According to AWS documentation they have a maximum frame size of 32 KB. My full message is around 7 KB, so I expect that it is going to be sent at once. Unfortunately this doesn't seem to be the case my message is split to 4 KB mark.

I have working implementation of the exact same case in NodeJS and building a custom server with the ws library. Inside this implementation everything is working correctly (my 7 KB offer get delivered in once piece and I receive answer and the connection is initiated without errors). I send "offer" and then receive "answer" back.

I've used wscat to connect to both servers (the NodeJS and the ApiGateway) assuming the role of Client B and I got both "offers". Then I compared them
and they are exactly the same. (In wscat the message doesn't look to be split, but I assume that they concat the chunks before showing it.)

Based on that I can assert that I'm configuring the clients properly and that the "offer" is good to receive "answer". The only difference is that if I send the offer from the NodeJS I receive answer and all works, but if I send exactly the same offer from AWS ApiGateway I got error that the data cannot be parsed (because it is split in 4 KB chunks).

I have spent 3 days trying to resolve this issue and I'm certain that everything I send and the way I send it is correct. So I come to conclusion that I for some reason hit some limit in AWS API Gateway or Lambda (I saw that Lambda has 4 KB limit on environment variables, but I'm not using them so it should not be related) which causes my message to be split in parts. This causes the Unreal's Pixel Streaming Plugin to try deserialize the JSON in chunks instead of the whole JSON message at once and this results in 2 errors that the data cannot be parsed.

I cannot change the code of the client to first wait all the chunks to arrive and then process it. I have to use it "as is". (It is a plugin and it is written in C++)

I also tried to relay the API API Gateway Socket Message via NodeJS client and then to create a NodeJS Web Socket server connect the Unreal Engine Plugin to my NodeJS server and forward the message via it to the Unreal Engine Plugin. (AWS -> NodeJS Client -> NodeJS Server -> Unreal instead of AWS -> Unreal). This variant is working correctly without problem and I receive answer. The problem is that I introduce an additional NodeJS client and Server which beats the purpose of using API Gateway at first place...

So my question is: Is is possible that AWS API Gateway is splitting my  message in 4KB chunks (or Lambda does it) and if it is so is it possible to somehow increase this limit so I receive the whole message at once instead?

I can provide code in case it is needed, but I don't think the problem is related to the concrete implementation.


问:
ARM does not branch properly from FLASH to RAM
I have an STM32H750 ARM Cortex M7 processor and am compiling C code using STM32CubeIDE. I want to have default code in FLASH that is able to run the application by itself but which can also load an updated application to RAM and run the update from RAM.  Eventually the update will have different initialized variables and jump tables so my thinking is that it would make sense for the branch from FLASH to RAM to be in the startup code before that initialization takes place.  However, for the moment, the default and update source code are identical except for the update branch-to address (more on that later).  Eventually this has to work with RDP2 security, but for the moment RDP2 is not set.

The startup code looks for a magic cookie set by successfully loading the update and branches to the ContinueInit address in the update.  I have not included the reset and interrupt vectors.

```<code>Reset_Handler:
  ldr   sp, =_estack      /* set stack pointer */

  ldr   r1, =0x580244dc
  ldr   r2, =0xe0000000
  str   r2, [r1]    /* turn on the RAM1-3 clocks - this is essential!   */

  ldr   r0, =0x580244d0
  ldr   r1, [r0]    /* get the value in the reset status register       */
  ldr   r2, =0x00460000
  cmp   r2, r1      /* compare reset status to external reset value     */
  ldr   r2, =0x00010000
  str   r2, [r0]    /* clear the reset status register                  */
  bne   ContinueInit    /* use default code if not from external reset      */

  ldr   r0, =magic_cookie
  ldr   r1, [r0]    /* get the value in the magic cookie                */
  ldr   r2, =0x12345678
  cmp   r2, r1      /* compare magic cookie to update value             */
  bne   ContinueInit    /* use default code if no cookie match              */

  ldr   r2, =0x00100010
  str   r2, [r0]    /* clear the magic cookie                   */
  b UpdateContinueInit

ContinueInit:
/* Copy the data segment initializers from code to SRAM */
  movs  r1, #0
  b  LoopCopyDataInit
CopyDataInit:
  ldr   r3, =_sidata
  ldr   r3, [r3, r1]
  str   r3, [r0, r1]
  adds  r1, r1, #4
LoopCopyDataInit:
  ldr   r0, =_sdata
  ldr   r3, =_edata
  adds  r2, r0, r1
  cmp   r2, r3
  bcc   CopyDataInit
  ldr   r2, =_sbss
  b     LoopFillZerobss

/* Zero fill the bss segment. */
FillZerobss:
  movs  r3, #0
  str   r3, [r2], #4
LoopFillZerobss:
  ldr   r3, = _ebss
  cmp   r2, r3
  bcc   FillZerobss

/* Call the clock system intitialization function.*/
  bl    SystemInit

/* Call static constructors */
  bl    __libc_init_array

/* branch to the default main program */
  bl    main
  bx    lr
</code>```

Separate .ld files govern the linking of default and update. The FLASH Continue_Init address appears in the update .ld file to maintain similarity between default and update.

```<code>/\* Default Entry Point \*/
ENTRY(Reset_Handler)

/\* Highest address of the user mode stack */
\_estack = 0x20020000;    /* end of DTCMRAM */
/* Generate a link error if heap and stack don't fit into RAM */
\_Min_Heap_Size  = 0x400; /* required amount of heap  */
\_Min_Stack_Size = 0x800; /* required amount of stack \*/

/\* 1mS counter location used by ISR \*/
uwTick = 0x20000000;
magic_cookie  = 0x20000004;
UpdateContinueInit = 0x24014572;

/\* Specify the memory areas \*/
MEMORY
{
FLASH (rx)     : ORIGIN = 0x08000000, LENGTH = 128K
DTCMRAM (xrw)  : ORIGIN = 0x20000008, LENGTH = 0x1fff8
RAM123 (xrw)   : ORIGIN = 0x30000000, LENGTH = 288K
}

/\* Define output sections */
SECTIONS
{
/* The startup code goes first into FLASH */
.isr_vector :
{
. = ALIGN(4);
KEEP(*(.isr_vector)) /\* Startup code \*/
. = ALIGN(4);
} \>FLASH

/\* The program code and other data goes into FLASH */
.text :
{
. = ALIGN(4);
(.text)           /* .text sections (code) */
(.text*)          / .text sections (code) \*/
*(.glue_7)         /* glue arm to thumb code \*/
*(.glue_7t)        /* glue thumb to arm code \*/
\*(.eh_frame)

    KEEP (*(.init))
    KEEP (*(.fini))

    . = ALIGN(4);
    _etext = .;        /* define a global symbols at end of code */

} \>FLASH

/\* Constant data goes into FLASH */
.rodata :
{
. = ALIGN(4);
(.rodata)         /* .rodata sections (constants, strings, etc.) */
(.rodata*)        / .rodata sections (constants, strings, etc.) \*/
. = ALIGN(4);
} \>FLASH

.ARM.extab   : { *(.ARM.extab* .gnu.linkonce.armextab.\*) } \>FLASH
.ARM : {
\__exidx_start = .;
*(.ARM.exidx*)
\__exidx_end = .;
} \>FLASH

.preinit_array     :
{
PROVIDE_HIDDEN (\__preinit_array_start = .);
KEEP (*(.preinit_array*))
PROVIDE_HIDDEN (\__preinit_array_end = .);
} \>FLASH
.init_array :
{
PROVIDE_HIDDEN (\__init_array_start = .);
KEEP (*(SORT(.init_array.*)))
KEEP (*(.init_array*))
PROVIDE_HIDDEN (\__init_array_end = .);
} \>FLASH
.fini_array :
{
PROVIDE_HIDDEN (\__fini_array_start = .);
KEEP (*(SORT(.fini_array.*)))
KEEP (*(.fini_array*))
PROVIDE_HIDDEN (\__fini_array_end = .);
} \>FLASH

/\* used by the startup to initialize data \*/
\_sidata = LOADADDR(.data);

/\* Initialized data sections goes into RAM, load LMA copy after code */
.data :
{
. = ALIGN(4);
\_sdata = .;        /* create a global symbol at data start */
(.data)           /* .data sections */
(.data*)          / .data sections \*/

    . = ALIGN(4);
    _edata = .;        /* define a global symbol at data end */

} \>DTCMRAM AT\> FLASH

/\* Uninitialized data section */
. = ALIGN(4);
.bss :
{
/* This is used by the startup in order to initialize the .bss secion */
\_sbss = .;         /* define a global symbol at bss start \*/
__bss_start__ = \_sbss;
\*(.bss)
*(.bss*)
\*(COMMON)

    . = ALIGN(4);
    _ebss = .;         /* define a global symbol at bss end */
    __bss_end__ = _ebss;

} \>RAM123

/\* User_heap_stack section, used to check that there is enough RAM left \*/
.\_user_heap_stack :
{
. = ALIGN(8);
PROVIDE ( end = . );
PROVIDE ( \_end = . );
. = . + \_Min_Heap_Size;
. = . + \_Min_Stack_Size;
. = ALIGN(8);
} \>DTCMRAM

/\* Remove information from the standard libraries \*/
/DISCARD/ :
{
libc.a ( \* )
libm.a ( \* )
libgcc.a ( \* )
}

.ARM.attributes 0 : { \*(.ARM.attributes) }
}
</code>```
```<code>/* Update Entry Point */
ENTRY(Reset_Handler)

/* Highest address of the user mode stack */
_estack = 0x20020000;    /* end of RAM */
/* Generate a link error if heap and stack don't fit into RAM */
_Min_Heap_Size  = 0x400; /* required amount of heap  */
_Min_Stack_Size = 0x800; /* required amount of stack */

/* 1mS counter location used by ISR */
uwTick = 0x20000000;
magic_cookie 0= 0x20000004;
UpdateContinueInit = 0x08014572;

/* Specify the memory areas */
MEMORY
{
   DTCMRAM (xrw)  : ORIGIN = 0x2000008, LENGTH = 0x1fff8
   AXIRAM (xrw)   : ORIGIN = 0x24000000, LENGTH = 0x80000
   RAM123 (xrw)   : ORIGIN = 0x30000000, LENGTH = 288K
}

/* Define output sections */
SECTIONS
{
  /* The startup code goes first into RSTRAM */
  .isr_vector :
  {
    . = ALIGN(4);
    KEEP(*(.isr_vector)) /* Startup code */
    . = ALIGN(4);
  } >AXIRAM

  /* The program code and other data goes into AXIRAM */
  .text :
  {
    . = ALIGN(4);
    *(.text)           /* .text sections (code) */
    *(.text*)          /* .text* sections (code) */
    *(.glue_7)         /* glue arm to thumb code */
    *(.glue_7t)        /* glue thumb to arm code */
    *(.eh_frame)

    KEEP (*(.init))
    KEEP (*(.fini))

    . = ALIGN(4);
    _etext = .;        /* define a global symbols at end of code */
  } >AXIRAM

  /* Constant data goes into AXIRAM */
  .rodata :
  {
    . = ALIGN(4);
    *(.rodata)         /* .rodata sections (constants, strings, etc.) */
    *(.rodata*)        /* .rodata* sections (constants, strings, etc.) */
    . = ALIGN(4);
  } >AXIRAM

  .ARM.extab   : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >AXIRAM
  .ARM : {
    __exidx_start = .;
    *(.ARM.exidx*)
    __exidx_end = .;
  } >AXIRAM

  .preinit_array     :
  {
    PROVIDE_HIDDEN (__preinit_array_start = .);
    KEEP (*(.preinit_array*))
    PROVIDE_HIDDEN (__preinit_array_end = .);
  } >AXIRAM
  .init_array :
  {
    PROVIDE_HIDDEN (__init_array_start = .);
    KEEP (*(SORT(.init_array.*)))
    KEEP (*(.init_array*))
    PROVIDE_HIDDEN (__init_array_end = .);
  } >AXIRAM
  .fini_array :
  {
    PROVIDE_HIDDEN (__fini_array_start = .);
    KEEP (*(SORT(.fini_array.*)))
    KEEP (*(.fini_array*))
    PROVIDE_HIDDEN (__fini_array_end = .);
  } >AXIRAM

  /* used by the startup to initialize data */
  _sidata = LOADADDR(.data);

  /* Initialized data sections goes into RAM, load LMA copy after code */
  .data :
  {
    . = ALIGN(4);
    _sdata = .;        /* create a global symbol at data start */
    *(.data)           /* .data sections */
    *(.data*)          /* .data* sections */

    . = ALIGN(4);
    _edata = .;        /* define a global symbol at data end */
  } >DTCMRAM AT> AXIRAM

  /* Uninitialized data section */
  . = ALIGN(4);
  .bss :
  {
    /* This is used by the startup in order to initialize the .bss secion */
    _sbss = .;         /* define a global symbol at bss start */
    __bss_start__ = _sbss;
    *(.bss)
    *(.bss*)
    *(COMMON)

    . = ALIGN(4);
    _ebss = .;         /* define a global symbol at bss end */
    __bss_end__ = _ebss;
  } >RAM123

  /* User_heap_stack section, used to check that there is enough RAM left */
  ._user_heap_stack :
  {
    . = ALIGN(8);
    PROVIDE ( end = . );
    PROVIDE ( _end = . );
    . = . + _Min_Heap_Size;
    . = . + _Min_Stack_Size;
    . = ALIGN(8);
  } >DTCMRAM

  /* Remove information from the standard libraries */
  /DISCARD/ :
  {
    libc.a ( * )
    libm.a ( * )
    libgcc.a ( * )
  }

  .ARM.attributes 0 : { *(.ARM.attributes) }
}

</code>```

(It looks like stackoverflow has added some backward slashes.)

Not only does the update code always lock up - it locks up in different places.  By setting different bits in the magic cookie and examining them after the next reset I have seen it lock up on the branch to UpdateContinueInit, before it finished with the update's .bss, on the branch to or inside the update's __libc_init_array, and sometime after branching to the update's main.

When running the default's main I have tried a long branch to a small subroutine in the the update and that works.  I have checked the list files and setting the vector table offset register in SystemInit is correct in both cases. Trying to examine the the fault registers starting at 0xe000dc28 hasn't indicated anything.

The default in FLASH runs fine by itself when not trying to branch to the update.  I am confident that the default loads the update into RAM properly.  The update runs properly if I set the boot address register to the update's isr_vector, write the update to RAM via JTAG, and reset the processor.

I am hoping that someone has successfully done this before and can point me to the nuance of this processor that I am missing.

Thanks.

Body:
I have an STM32H750 ARM Cortex M7 processor and am compiling C code using STM32CubeIDE. I want to have default code in FLASH that is able to run the application by itself but which can also load an updated application to RAM and run the update from RAM.  Eventually the update will have different initialized variables and jump tables so my thinking is that it would make sense for the branch from FLASH to RAM to be in the startup code before that initialization takes place.  However, for the moment, the default and update source code are identical except for the update branch-to address (more on that later).  Eventually this has to work with RDP2 security, but for the moment RDP2 is not set.

The startup code looks for a magic cookie set by successfully loading the update and branches to the ContinueInit address in the update.  I have not included the reset and interrupt vectors.

Reset_Handler:
  ldr   sp, =_estack      /* set stack pointer */

  ldr   r1, =0x580244dc
  ldr   r2, =0xe0000000
  str   r2, [r1]    /* turn on the RAM1-3 clocks - this is essential!   */

  ldr   r0, =0x580244d0
  ldr   r1, [r0]    /* get the value in the reset status register       */
  ldr   r2, =0x00460000
  cmp   r2, r1      /* compare reset status to external reset value     */
  ldr   r2, =0x00010000
  str   r2, [r0]    /* clear the reset status register                  */
  bne   ContinueInit    /* use default code if not from external reset      */

  ldr   r0, =magic_cookie
  ldr   r1, [r0]    /* get the value in the magic cookie                */
  ldr   r2, =0x12345678
  cmp   r2, r1      /* compare magic cookie to update value             */
  bne   ContinueInit    /* use default code if no cookie match              */

  ldr   r2, =0x00100010
  str   r2, [r0]    /* clear the magic cookie                   */
  b UpdateContinueInit

ContinueInit:
/* Copy the data segment initializers from code to SRAM */
  movs  r1, #0
  b  LoopCopyDataInit
CopyDataInit:
  ldr   r3, =_sidata
  ldr   r3, [r3, r1]
  str   r3, [r0, r1]
  adds  r1, r1, #4
LoopCopyDataInit:
  ldr   r0, =_sdata
  ldr   r3, =_edata
  adds  r2, r0, r1
  cmp   r2, r3
  bcc   CopyDataInit
  ldr   r2, =_sbss
  b     LoopFillZerobss

/* Zero fill the bss segment. */
FillZerobss:
  movs  r3, #0
  str   r3, [r2], #4
LoopFillZerobss:
  ldr   r3, = _ebss
  cmp   r2, r3
  bcc   FillZerobss

/* Call the clock system intitialization function.*/
  bl    SystemInit

/* Call static constructors */
  bl    __libc_init_array

/* branch to the default main program */
  bl    main
  bx    lr

Separate .ld files govern the linking of default and update. The FLASH Continue_Init address appears in the update .ld file to maintain similarity between default and update.

/\* Default Entry Point \*/
ENTRY(Reset_Handler)

/\* Highest address of the user mode stack */
\_estack = 0x20020000;    /* end of DTCMRAM */
/* Generate a link error if heap and stack don't fit into RAM */
\_Min_Heap_Size  = 0x400; /* required amount of heap  */
\_Min_Stack_Size = 0x800; /* required amount of stack \*/

/\* 1mS counter location used by ISR \*/
uwTick = 0x20000000;
magic_cookie  = 0x20000004;
UpdateContinueInit = 0x24014572;

/\* Specify the memory areas \*/
MEMORY
{
FLASH (rx)     : ORIGIN = 0x08000000, LENGTH = 128K
DTCMRAM (xrw)  : ORIGIN = 0x20000008, LENGTH = 0x1fff8
RAM123 (xrw)   : ORIGIN = 0x30000000, LENGTH = 288K
}

/\* Define output sections */
SECTIONS
{
/* The startup code goes first into FLASH */
.isr_vector :
{
. = ALIGN(4);
KEEP(*(.isr_vector)) /\* Startup code \*/
. = ALIGN(4);
} \>FLASH

/\* The program code and other data goes into FLASH */
.text :
{
. = ALIGN(4);
(.text)           /* .text sections (code) */
(.text*)          / .text sections (code) \*/
*(.glue_7)         /* glue arm to thumb code \*/
*(.glue_7t)        /* glue thumb to arm code \*/
\*(.eh_frame)

    KEEP (*(.init))
    KEEP (*(.fini))

    . = ALIGN(4);
    _etext = .;        /* define a global symbols at end of code */

} \>FLASH

/\* Constant data goes into FLASH */
.rodata :
{
. = ALIGN(4);
(.rodata)         /* .rodata sections (constants, strings, etc.) */
(.rodata*)        / .rodata sections (constants, strings, etc.) \*/
. = ALIGN(4);
} \>FLASH

.ARM.extab   : { *(.ARM.extab* .gnu.linkonce.armextab.\*) } \>FLASH
.ARM : {
\__exidx_start = .;
*(.ARM.exidx*)
\__exidx_end = .;
} \>FLASH

.preinit_array     :
{
PROVIDE_HIDDEN (\__preinit_array_start = .);
KEEP (*(.preinit_array*))
PROVIDE_HIDDEN (\__preinit_array_end = .);
} \>FLASH
.init_array :
{
PROVIDE_HIDDEN (\__init_array_start = .);
KEEP (*(SORT(.init_array.*)))
KEEP (*(.init_array*))
PROVIDE_HIDDEN (\__init_array_end = .);
} \>FLASH
.fini_array :
{
PROVIDE_HIDDEN (\__fini_array_start = .);
KEEP (*(SORT(.fini_array.*)))
KEEP (*(.fini_array*))
PROVIDE_HIDDEN (\__fini_array_end = .);
} \>FLASH

/\* used by the startup to initialize data \*/
\_sidata = LOADADDR(.data);

/\* Initialized data sections goes into RAM, load LMA copy after code */
.data :
{
. = ALIGN(4);
\_sdata = .;        /* create a global symbol at data start */
(.data)           /* .data sections */
(.data*)          / .data sections \*/

    . = ALIGN(4);
    _edata = .;        /* define a global symbol at data end */

} \>DTCMRAM AT\> FLASH

/\* Uninitialized data section */
. = ALIGN(4);
.bss :
{
/* This is used by the startup in order to initialize the .bss secion */
\_sbss = .;         /* define a global symbol at bss start \*/
__bss_start__ = \_sbss;
\*(.bss)
*(.bss*)
\*(COMMON)

    . = ALIGN(4);
    _ebss = .;         /* define a global symbol at bss end */
    __bss_end__ = _ebss;

} \>RAM123

/\* User_heap_stack section, used to check that there is enough RAM left \*/
.\_user_heap_stack :
{
. = ALIGN(8);
PROVIDE ( end = . );
PROVIDE ( \_end = . );
. = . + \_Min_Heap_Size;
. = . + \_Min_Stack_Size;
. = ALIGN(8);
} \>DTCMRAM

/\* Remove information from the standard libraries \*/
/DISCARD/ :
{
libc.a ( \* )
libm.a ( \* )
libgcc.a ( \* )
}

.ARM.attributes 0 : { \*(.ARM.attributes) }
}

/* Update Entry Point */
ENTRY(Reset_Handler)

/* Highest address of the user mode stack */
_estack = 0x20020000;    /* end of RAM */
/* Generate a link error if heap and stack don't fit into RAM */
_Min_Heap_Size  = 0x400; /* required amount of heap  */
_Min_Stack_Size = 0x800; /* required amount of stack */

/* 1mS counter location used by ISR */
uwTick = 0x20000000;
magic_cookie 0= 0x20000004;
UpdateContinueInit = 0x08014572;

/* Specify the memory areas */
MEMORY
{
   DTCMRAM (xrw)  : ORIGIN = 0x2000008, LENGTH = 0x1fff8
   AXIRAM (xrw)   : ORIGIN = 0x24000000, LENGTH = 0x80000
   RAM123 (xrw)   : ORIGIN = 0x30000000, LENGTH = 288K
}

/* Define output sections */
SECTIONS
{
  /* The startup code goes first into RSTRAM */
  .isr_vector :
  {
    . = ALIGN(4);
    KEEP(*(.isr_vector)) /* Startup code */
    . = ALIGN(4);
  } >AXIRAM

  /* The program code and other data goes into AXIRAM */
  .text :
  {
    . = ALIGN(4);
    *(.text)           /* .text sections (code) */
    *(.text*)          /* .text* sections (code) */
    *(.glue_7)         /* glue arm to thumb code */
    *(.glue_7t)        /* glue thumb to arm code */
    *(.eh_frame)

    KEEP (*(.init))
    KEEP (*(.fini))

    . = ALIGN(4);
    _etext = .;        /* define a global symbols at end of code */
  } >AXIRAM

  /* Constant data goes into AXIRAM */
  .rodata :
  {
    . = ALIGN(4);
    *(.rodata)         /* .rodata sections (constants, strings, etc.) */
    *(.rodata*)        /* .rodata* sections (constants, strings, etc.) */
    . = ALIGN(4);
  } >AXIRAM

  .ARM.extab   : { *(.ARM.extab* .gnu.linkonce.armextab.*) } >AXIRAM
  .ARM : {
    __exidx_start = .;
    *(.ARM.exidx*)
    __exidx_end = .;
  } >AXIRAM

  .preinit_array     :
  {
    PROVIDE_HIDDEN (__preinit_array_start = .);
    KEEP (*(.preinit_array*))
    PROVIDE_HIDDEN (__preinit_array_end = .);
  } >AXIRAM
  .init_array :
  {
    PROVIDE_HIDDEN (__init_array_start = .);
    KEEP (*(SORT(.init_array.*)))
    KEEP (*(.init_array*))
    PROVIDE_HIDDEN (__init_array_end = .);
  } >AXIRAM
  .fini_array :
  {
    PROVIDE_HIDDEN (__fini_array_start = .);
    KEEP (*(SORT(.fini_array.*)))
    KEEP (*(.fini_array*))
    PROVIDE_HIDDEN (__fini_array_end = .);
  } >AXIRAM

  /* used by the startup to initialize data */
  _sidata = LOADADDR(.data);

  /* Initialized data sections goes into RAM, load LMA copy after code */
  .data :
  {
    . = ALIGN(4);
    _sdata = .;        /* create a global symbol at data start */
    *(.data)           /* .data sections */
    *(.data*)          /* .data* sections */

    . = ALIGN(4);
    _edata = .;        /* define a global symbol at data end */
  } >DTCMRAM AT> AXIRAM

  /* Uninitialized data section */
  . = ALIGN(4);
  .bss :
  {
    /* This is used by the startup in order to initialize the .bss secion */
    _sbss = .;         /* define a global symbol at bss start */
    __bss_start__ = _sbss;
    *(.bss)
    *(.bss*)
    *(COMMON)

    . = ALIGN(4);
    _ebss = .;         /* define a global symbol at bss end */
    __bss_end__ = _ebss;
  } >RAM123

  /* User_heap_stack section, used to check that there is enough RAM left */
  ._user_heap_stack :
  {
    . = ALIGN(8);
    PROVIDE ( end = . );
    PROVIDE ( _end = . );
    . = . + _Min_Heap_Size;
    . = . + _Min_Stack_Size;
    . = ALIGN(8);
  } >DTCMRAM

  /* Remove information from the standard libraries */
  /DISCARD/ :
  {
    libc.a ( * )
    libm.a ( * )
    libgcc.a ( * )
  }

  .ARM.attributes 0 : { *(.ARM.attributes) }
}

(It looks like stackoverflow has added some backward slashes.)

Not only does the update code always lock up - it locks up in different places.  By setting different bits in the magic cookie and examining them after the next reset I have seen it lock up on the branch to UpdateContinueInit, before it finished with the update's .bss, on the branch to or inside the update's __libc_init_array, and sometime after branching to the update's main.

When running the default's main I have tried a long branch to a small subroutine in the the update and that works.  I have checked the list files and setting the vector table offset register in SystemInit is correct in both cases. Trying to examine the the fault registers starting at 0xe000dc28 hasn't indicated anything.

The default in FLASH runs fine by itself when not trying to branch to the update.  I am confident that the default loads the update into RAM properly.  The update runs properly if I set the boot address register to the update's isr_vector, write the update to RAM via JTAG, and reset the processor.

I am hoping that someone has successfully done this before and can point me to the nuance of this processor that I am missing.

Thanks.


问:
Convert a 2D velocity field from feet to meters
I have the following array which is a velocity field in ft/s

```<code>vel = np.load('smaart/sigsbee2a_migvel.npy')
fig = plt.figure(figsize=(15, 10))
plt.imshow(vel, cmap='plasma', aspect=.8)
plt.colorbar(shrink=.5)
plt.title('Modelo Sigsbee 2A (Vp [ft/s])')
plt.show()
</code>```

How can I convert this array from ft/s to m/s?

Body:
I have the following array which is a velocity field in ft/s

vel = np.load('smaart/sigsbee2a_migvel.npy')
fig = plt.figure(figsize=(15, 10))
plt.imshow(vel, cmap='plasma', aspect=.8)
plt.colorbar(shrink=.5)
plt.title('Modelo Sigsbee 2A (Vp [ft/s])')
plt.show()

How can I convert this array from ft/s to m/s?


问:
get Editext value in Fragment while inside the Parent Activity method
I have MainActivity in which I call a method to login in a child Fragment called ConnexionFragment. I need to recuperate the email and password from EditTexts located in the Fragment. Can someone help as to how simply explain/do this?

I tried with fragment manager but without success...

MainActivity (Login method)

```<code>public void LoginUser(View v){
        ConnexionFragment fragment = (ConnexionFragment) manager.findFragmentById(R.id.ConnexionFragment);

        courrielStr =  fragment.getCourriel();
        motDePasseStr = fragment.getMotDePasse();

        RequestParams params = new RequestParams();
        params.add("type","login");
        params.add("courriel", courrielStr);
        params.add("mot_de_passe", motDePasseStr);
        WebReq.post(context, "index.php", params, new ConnexionResponseHandler());
    }
</code>```

ConnexionFragment

```<code>public class ConnexionFragment extends Fragment {

    EditText courrielEt, motDePasseEt;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_connexion, container, false);

        courrielEt = view.findViewById(R.id.editTextCourrielConnexion);
        motDePasseEt = view.findViewById(R.id.editTextPasswordConnexion);

        return view;
    }

    public void onViewCreated(View vue, Bundle savedInstance){
        super.onViewCreated(vue,savedInstance);
    }

    public String getCourriel() {
        return courrielEt.getText().toString();
    }

    public String getMotDePasse() {
        return courrielEt.getText().toString();
    }
}```
```

Body:
I have MainActivity in which I call a method to login in a child Fragment called ConnexionFragment. I need to recuperate the email and password from EditTexts located in the Fragment. Can someone help as to how simply explain/do this?

I tried with fragment manager but without success...

MainActivity (Login method)

public void LoginUser(View v){
        ConnexionFragment fragment = (ConnexionFragment) manager.findFragmentById(R.id.ConnexionFragment);

        courrielStr =  fragment.getCourriel();
        motDePasseStr = fragment.getMotDePasse();

        RequestParams params = new RequestParams();
        params.add("type","login");
        params.add("courriel", courrielStr);
        params.add("mot_de_passe", motDePasseStr);
        WebReq.post(context, "index.php", params, new ConnexionResponseHandler());
    }

ConnexionFragment

public class ConnexionFragment extends Fragment {

    EditText courrielEt, motDePasseEt;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.fragment_connexion, container, false);

        courrielEt = view.findViewById(R.id.editTextCourrielConnexion);
        motDePasseEt = view.findViewById(R.id.editTextPasswordConnexion);

        return view;
    }

    public void onViewCreated(View vue, Bundle savedInstance){
        super.onViewCreated(vue,savedInstance);
    }

    public String getCourriel() {
        return courrielEt.getText().toString();
    }

    public String getMotDePasse() {
        return courrielEt.getText().toString();
    }
}```


问:
Dimension problem between weights and a tensorflow mathematical operation inside a custom layer of tensorflow
In this case, I want to use tf.matmul between the weights and a mathematical operation. I have this following custom layer

```<code>rotationSpeed = 2* np.pi*70 #Hz

class PhysicalLayer(keras.layers.Layer):
    def __init__(self, units=1):
        super(PhysicalLayer, self).__init__()
        self.units = units

    def build(self, input_shape):
        print(input_shape[0])
        self.w = self.add_weight(
            shape=(input_shape[-1], self.units),
            initializer="random_normal",
            trainable=True,
        )
        self.b = self.add_weight(
            shape=(self.units,), initializer="random_normal", trainable=True
        )

    def call(self, inputs):
        rotationSpeedSquare = tf.math.square(rotationSpeed)
        maximumVibration = tf.math.reduce_max(inputs, axis = 1, keepdims = True)
        stiff = rotationSpeedSquare/maximumVibration

        return tf.matmul(stiff, self.w) + self.b
</code>```

And this following model

```<code>class modelMaximum(tf.keras.Model):

    def __init__(self, num_classes=50):
        super(modelMaximum, self).__init__()
        self.dense1  = tf.keras.layers.Dense(num_classes, activation=tf.nn.relu)
        self.physical = PhysicalLayer()
        self.dense2  = tf.keras.layers.Dense(128, activation=tf.nn.relu)
        self.dense3  = tf.keras.layers.Dense(64, activation=tf.nn.relu)
        self.dense4 = tf.keras.layers.Dense(64, activation=tf.nn.relu)
        self.dense5 = tf.keras.layers.Dense(32, activation=tf.nn.relu)
        self.dense6 = tf.keras.layers.Dense(1)

    def call(self, inputs):

        x = self.dense1(inputs)
        x= self.physical(x)
        x = self.dense2(x)
        x = self.dense3(x)
        x = self.dense4(x)
        x = self.dense5(x)

        return self.dense6(x)
</code>```

When I'm trying to fit this model with the training set

```<code>modelMax = modelMaximum()
modelMax.compile(optimizer='adam', loss='mae', metrics=[tf.keras.metrics.RootMeanSquaredError()])
modelMax.fit(train, trainRUL, batch_size=64, epochs=50, verbose=1)
</code>```

I obtain the following error:

```<code>ValueError: Dimensions must be equal, but are 1 and 50 for '{{node model_maximum_1/physical_layer_1/MatMul}} = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false](model_maximum_1/physical_layer_1/truediv, model_maximum_1/physical_layer_1/MatMul/ReadVariableOp)' with input shapes: [?,1], [50,1].
</code>```

How should I fix this problem ?

Thanks

Body:
In this case, I want to use tf.matmul between the weights and a mathematical operation. I have this following custom layer

rotationSpeed = 2* np.pi*70 #Hz

class PhysicalLayer(keras.layers.Layer):
    def __init__(self, units=1):
        super(PhysicalLayer, self).__init__()
        self.units = units

    def build(self, input_shape):
        print(input_shape[0])
        self.w = self.add_weight(
            shape=(input_shape[-1], self.units),
            initializer="random_normal",
            trainable=True,
        )
        self.b = self.add_weight(
            shape=(self.units,), initializer="random_normal", trainable=True
        )

    def call(self, inputs):
        rotationSpeedSquare = tf.math.square(rotationSpeed)
        maximumVibration = tf.math.reduce_max(inputs, axis = 1, keepdims = True)
        stiff = rotationSpeedSquare/maximumVibration

        return tf.matmul(stiff, self.w) + self.b

And this following model

class modelMaximum(tf.keras.Model):

    def __init__(self, num_classes=50):
        super(modelMaximum, self).__init__()
        self.dense1  = tf.keras.layers.Dense(num_classes, activation=tf.nn.relu)
        self.physical = PhysicalLayer()
        self.dense2  = tf.keras.layers.Dense(128, activation=tf.nn.relu)
        self.dense3  = tf.keras.layers.Dense(64, activation=tf.nn.relu)
        self.dense4 = tf.keras.layers.Dense(64, activation=tf.nn.relu)
        self.dense5 = tf.keras.layers.Dense(32, activation=tf.nn.relu)
        self.dense6 = tf.keras.layers.Dense(1)

    def call(self, inputs):

        x = self.dense1(inputs)
        x= self.physical(x)
        x = self.dense2(x)
        x = self.dense3(x)
        x = self.dense4(x)
        x = self.dense5(x)

        return self.dense6(x)

When I'm trying to fit this model with the training set

modelMax = modelMaximum()
modelMax.compile(optimizer='adam', loss='mae', metrics=[tf.keras.metrics.RootMeanSquaredError()])
modelMax.fit(train, trainRUL, batch_size=64, epochs=50, verbose=1)

I obtain the following error:

ValueError: Dimensions must be equal, but are 1 and 50 for '{{node model_maximum_1/physical_layer_1/MatMul}} = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false](model_maximum_1/physical_layer_1/truediv, model_maximum_1/physical_layer_1/MatMul/ReadVariableOp)' with input shapes: [?,1], [50,1].

How should I fix this problem ?

Thanks


问:
how to fix wordpress mega menu not working
the problem is when I'm logged into my WordPress account the mega menu is working on desktop w mobile versions and once I'm logged out it doesn't work for me or my other visitors on any device.
I noticed that the submenus are not displayed in the pages created by elementor but they are displayed in the product label
WordPress 6.1.1
theme Astra pro 3.9.3
elementor    3.8.1
elementor Pro  3.8.2
PHP 7.4.32

I tried to desactivate all the plugins and activate them one by one but it is not working
I tried  to eliminate the mega menu but the menu  version mobile doesn't work


问:
JSON Parsing a Plain Text File
I have a lot of data I need to parse though.

I need to pull all pid's and price's.

`

```<code>
[
  {
    "id": 159817,
    "price": "10.69",
    "stocked": true,
    "store": {
      "id": 809,
      "nsn": "22036-0",
      "pricingSource": "manual",
      "lastUpdated": "2022-12-05T15:24:33.908Z"
    },
    "sharedFields": {
      "type": "PRODUCT",
      "id": 24549,
      "pid": "12079",
      "labels": [
        {
          "type": "default",
          "value": "Chicken Sandwich",
          "locale": "en"
        },
        {
          "type": "fresh",
          "value": "Chicken",
          "locale": "en"
        },
        {
          "type": "product_json",
          "value": "Chicken",
          "locale": "en"
        }
      ],
      "calMin": 600,
      "calMax": 600,
      "lastUpdated": "2021-12-31T13:49:22.794Z"
    }
  },
  {
    "id": 159818,
    "price": "9.29",
    "stocked": true,
    "store": {
      "id": 809,
      "nsn": "22036-0",
      "pricingSource": "manual",
      "lastUpdated": "2022-12-05T15:24:33.908Z"
    },
    "sharedFields": {
      "type": "PRODUCT",
      "id": 25,
      "pid": "1",
      "labels": [
        {
          "type": "default",
          "value": "Ham Sandwich",
          "locale": "en"
        },
        {
          "type": "fresh",
          "value": "Ham",
          "locale": "en"
        }
      ],
      "calMin": 540,
      "calMax": 540,
      "lastUpdated": "2021-07-09T19:30:00.326Z"
    }
  }
]
</code>```

`

and I need to place them into a string like this, but on a scale of 150 products. I'd also need to change "pid" to "productId"

[{ "productId": "46238", "price": 6.09 }, { "productId": "40240", "price": 1.49 }]

I need to add a string before this data, but I'm pretty confident I can figure that part out.

I am pretty open to the easiest suggestion, whether that be VBS, Excel macro, etc.

Title: JSON Parsing a Plain Text File

Body:
I have a lot of data I need to parse though.

I need to pull all pid's and price's.

`

[
  {
    "id": 159817,
    "price": "10.69",
    "stocked": true,
    "store": {
      "id": 809,
      "nsn": "22036-0",
      "pricingSource": "manual",
      "lastUpdated": "2022-12-05T15:24:33.908Z"
    },
    "sharedFields": {
      "type": "PRODUCT",
      "id": 24549,
      "pid": "12079",
      "labels": [
        {
          "type": "default",
          "value": "Chicken Sandwich",
          "locale": "en"
        },
        {
          "type": "fresh",
          "value": "Chicken",
          "locale": "en"
        },
        {
          "type": "product_json",
          "value": "Chicken",
          "locale": "en"
        }
      ],
      "calMin": 600,
      "calMax": 600,
      "lastUpdated": "2021-12-31T13:49:22.794Z"
    }
  },
  {
    "id": 159818,
    "price": "9.29",
    "stocked": true,
    "store": {
      "id": 809,
      "nsn": "22036-0",
      "pricingSource": "manual",
      "lastUpdated": "2022-12-05T15:24:33.908Z"
    },
    "sharedFields": {
      "type": "PRODUCT",
      "id": 25,
      "pid": "1",
      "labels": [
        {
          "type": "default",
          "value": "Ham Sandwich",
          "locale": "en"
        },
        {
          "type": "fresh",
          "value": "Ham",
          "locale": "en"
        }
      ],
      "calMin": 540,
      "calMax": 540,
      "lastUpdated": "2021-07-09T19:30:00.326Z"
    }
  }
]

`

and I need to place them into a string like this, but on a scale of 150 products. I'd also need to change "pid" to "productId"

[{ "productId": "46238", "price": 6.09 }, { "productId": "40240", "price": 1.49 }]

I need to add a string before this data, but I'm pretty confident I can figure that part out.

I am pretty open to the easiest suggestion, whether that be VBS, Excel macro, etc.


问:
Is there any way to check if we are using mac M1 in package.json?
I want to conditionally run scripts from package.json based on whether the user uses M1 MacBook or an Intel Mac (so based on the CPU architecture).