问:
How to move a player around the square boundary?
I'm trying make a game wherein for each level, the character starts off by moving in a counter-clockwise direction around the inside border of the square over and over again (Shown in picture).
Also, the character should not be controlled by the user, it moves by itself around.

The picture of my screen and how I want the square to function

I've tried using triggers, changing the position coordinates of the transform, and collision detections between the outer walls to change the direction of the character, but nothing seems to work. Here is some of the code I've tried for using the transform.MoveTowards method and the OnCollisionEnter2D function:

public Vector2 targetPosition;

public Vector2 targetPosition2;

public Vector2 targetPosition3;

public Vector2 targetPosition4;

public float speed = 5f;

```<code>private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag == "Bottom Wall")
        {
            Debug.Log("Hit");
            transform.position = Vector2.MoveTowards(transform.position, targetPosition, speed *        Time.deltaTime);
        }
        else if (collision.collider.tag == "Right wall")
        {
            transform.position = Vector2.MoveTowards(transform.position, targetPosition2, speed * Time.deltaTime);
        }
    }
</code>```

I have a feeling that the main problem is the fact that I cannot use the collision detection function in the fixed update function to make sure the character continuously moves towards the target.

Does anyone have any idea as to how I can solve this problem? Any help would be appreciated!

Body:
I'm trying make a game wherein for each level, the character starts off by moving in a counter-clockwise direction around the inside border of the square over and over again (Shown in picture).
Also, the character should not be controlled by the user, it moves by itself around.

The picture of my screen and how I want the square to function

I've tried using triggers, changing the position coordinates of the transform, and collision detections between the outer walls to change the direction of the character, but nothing seems to work. Here is some of the code I've tried for using the transform.MoveTowards method and the OnCollisionEnter2D function:

public Vector2 targetPosition;

public Vector2 targetPosition2;

public Vector2 targetPosition3;

public Vector2 targetPosition4;

public float speed = 5f;

private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.tag == "Bottom Wall")
        {
            Debug.Log("Hit");
            transform.position = Vector2.MoveTowards(transform.position, targetPosition, speed *        Time.deltaTime);
        }
        else if (collision.collider.tag == "Right wall")
        {
            transform.position = Vector2.MoveTowards(transform.position, targetPosition2, speed * Time.deltaTime);
        }
    }

I have a feeling that the main problem is the fact that I cannot use the collision detection function in the fixed update function to make sure the character continuously moves towards the target.

Does anyone have any idea as to how I can solve this problem? Any help would be appreciated!


来源: stackexchange

问:
Package: react-js-pagination not compatible with ReactJS version 18
react-js-pagination is not installing with my react js version 18. And I don't prefer to install any package by using the keyword --force at the end of the installation command.
Is there any other option to install it without downgrading my reactjs version from 18?

ContentLicense: CC BY-SA 4.0


问:
dynamically creating menu items that call a function, passing a different variable for each item
What I need, is a menu in tkinter, where each item has the name of a playlist, and each item will go to the same function (ImportPlaylist()) , but passes a different variable, namely: the rownumber for a csv file where that playlist is stored.

This cannot be done just by hand, because it happens dynamically, i.e. the user can make his own set of playlist with his own names.

I have made a music player, and am just experimenting now with reading and writing csv files. I made a csv file, and made a function to save playlists to that csv file. The way they are saved is that in each row, the first item is the name of the playlist, after that come youtube links one by one.

What I want is now to have functions for importing the playlists. The functions should be called from a tkinter menu. So they need to be created at the opening of the program.
I was hoping to do this with a for-loop. So, the for loop would go through the csv file row by row, and for every row create a menu-item, whose name is the first item in the row, and who refers to a function ImportPlaylist, passing some argument to indicate from which row the playlist needs to be imported.
Is this even possible?

To import a playlist, I made this little bit of code, generating menu items in a tkinter window:

```<code>with open(os.path.join(sys.path[0], "AntiTubePlaylists.txt"), "r") as csv_file:
    csv_reader = csv.reader(csv_file, quotechar='"', delimiter=',')
    counter = 0
    for row in csv_reader:
        playlistmenu.add_command(label=row[0], command=(lambda:  ImportPlaylist(counter)))
        counter += 1
</code>```

This doesn't work. Which I kind of understand. I suppose counter is a global variable, and therefor all my nicely generated menu items refer to the same number, which is an empty row.

Any thoughts on this?

Body:
What I need, is a menu in tkinter, where each item has the name of a playlist, and each item will go to the same function (ImportPlaylist()) , but passes a different variable, namely: the rownumber for a csv file where that playlist is stored.

This cannot be done just by hand, because it happens dynamically, i.e. the user can make his own set of playlist with his own names.

I have made a music player, and am just experimenting now with reading and writing csv files. I made a csv file, and made a function to save playlists to that csv file. The way they are saved is that in each row, the first item is the name of the playlist, after that come youtube links one by one.

What I want is now to have functions for importing the playlists. The functions should be called from a tkinter menu. So they need to be created at the opening of the program.
I was hoping to do this with a for-loop. So, the for loop would go through the csv file row by row, and for every row create a menu-item, whose name is the first item in the row, and who refers to a function ImportPlaylist, passing some argument to indicate from which row the playlist needs to be imported.
Is this even possible?

To import a playlist, I made this little bit of code, generating menu items in a tkinter window:

with open(os.path.join(sys.path[0], "AntiTubePlaylists.txt"), "r") as csv_file:
    csv_reader = csv.reader(csv_file, quotechar='"', delimiter=',')
    counter = 0
    for row in csv_reader:
        playlistmenu.add_command(label=row[0], command=(lambda:  ImportPlaylist(counter)))
        counter += 1

This doesn't work. Which I kind of understand. I suppose counter is a global variable, and therefor all my nicely generated menu items refer to the same number, which is an empty row.

Any thoughts on this?


问:
npm install got stuck when I try to install a library
when I try to install puppeteer, it goes stack at this point :

any ideas on how to solve it?


问:
PIco W: is there a way to detect if usb power is connected in micropython?
I am trying to detect (ideally fire an interrupt) when a usb host is connected and supplies 5v. (in this design i have a separate "always on" Vsys supplied from another source).

According to the schematics in https://datasheets.raspberrypi.com/picow/pico-w-datasheet.pdf it would be possible to know this by reading the state of the WL_GPOI2 pin. Unfortunately this pin is actually located on the CYW43439 wifi chip.

The green led on the board (connected to WL_GPOI0) is trivially accessible by using the below so it seems possible to get to the GPIO on the wifi chip.

```<code>from machine import Pin

led = Pin("LED", Pin.OUT)
</code>```

Is there a way of reading the WL_GPOI2 pin or otherwise finding out if a usb cable is connected?
ideal would be to fire an interrupt, but polling a status would also work.

Body:
I am trying to detect (ideally fire an interrupt) when a usb host is connected and supplies 5v. (in this design i have a separate "always on" Vsys supplied from another source).

According to the schematics in https://datasheets.raspberrypi.com/picow/pico-w-datasheet.pdf it would be possible to know this by reading the state of the WL_GPOI2 pin. Unfortunately this pin is actually located on the CYW43439 wifi chip.

The green led on the board (connected to WL_GPOI0) is trivially accessible by using the below so it seems possible to get to the GPIO on the wifi chip.

from machine import Pin

led = Pin("LED", Pin.OUT)

Is there a way of reading the WL_GPOI2 pin or otherwise finding out if a usb cable is connected?
ideal would be to fire an interrupt, but polling a status would also work.


问:
Trying to toggle between read and unread
I am new to javascript and I am trying to have my button say read or unread when a user clicks on it I've tried adding my readBookfunction to the onclick but I get an error like this, any help would be appreciated

I want it to look like this below and have the button either be read or unread

script.js

class Book {
  constructor(title, author, read) {
    this.title = title;
    this.author = author;
    this.read = read;

    addBookToLibrary(this);
  }
}

let myLibrary = [];

const table = document.getElementById('libraryTable');

let hiddenForm = document.getElementById('hiddenForm')
//toggles the input form opacity and z-index
function showForm() {
  hiddenForm.classList.toggle('active')
}

function clearInput() {
  inputs = document.getElementsByTagName('input')
  for (let i in inputs) {
    inputs[i].value = ''
  }
}

function createBook() {
  new Book(document.getElementById('title').value,
    document.getElementById('author').value,
    document.getElementById('read').value);
}

const harrypotter = new Book('Harry Potter', 'JK Rowling', 'read')
const stripedpajamas = new Book('The Boy in the Striped pajamas', 'John Boyne', 'read')
const randomBook = new Book('The random book', 'random author', 'read')

function addBookToLibrary(book) {
  myLibrary.push(book);
}

function readBook(Book) {
  let position = 0;

  for (i = 0; i < myLibrary.length; i++) {
    if (Book.title == myLibrary[i].title) {
      position = i;
    }
  }

  if (myLibrary[position].read == 'read') {
    myLibrary[position].read = "unread";
  } else {
    myLibrary[position].read = "read";
  }
  return myLibrary[position].read;
}

function displayBooks() {
  table.textContent = '';

  for (i = 0; i < myLibrary.length; i++) {
    let newRow = table.insertRow(i);
    newRow.insertCell(0).innerText = myLibrary[i].title;
    newRow.insertCell(1).innerText = myLibrary[i].author;
    newRow.insertCell(2).innerHTML = `<button onclick='${i}' class='tableButtons' >${myLibrary[i].read}</button>`
    newRow.insertCell(2).innerHTML = `<button onclick='removeBook(${i})' class='tableButtons' >Delete</button>`
  }
}

function removeBook(index) {
  if (index > 1) {
    myLibrary.splice(index, index - 1);
  } else if (index == 1) {
    myLibrary.splice(index, index);
  } else if (index == 0) {
    myLibrary.shift();
  }

}

const displayButton = document.querySelector(".display");

displayButton.addEventListener('click', button => {
  displayBooks();
});```


问:
Is it possible to see the response of a API call from Mirage JS in browser without calling it from code?
Here is the server creation :

```<code>import { createServer } from "miragejs"

export default function () {
  createServer({
    routes() {
      this.get("/api/reminders", () => ({
        reminders: [
            { id: 1, text: "Walk the dog" },
            { id: 2, text: "Take out the trash" },
            { id: 3, text: "Work out" },
          ],
      }))
    },
  })
}
Footer
</code>```

https://github.com/sultanshaik/MirageBrowserTest/blob/main/mirage-tutorial/src/server.js

I am able to see the response when I make the call from code.

https://github.com/sultanshaik/MirageBrowserTest/blob/main/mirage-tutorial/src/components/Reminders.js

I am trying to see if it is possible to make a get request in Mirage JS using the browser.I wanted to know if it is possible to see the same by visiting "https://localhost:3000//api/reminders". I don't see the route directly.What am I doing wrong?

Body:
Here is the server creation :

import { createServer } from "miragejs"

export default function () {
  createServer({
    routes() {
      this.get("/api/reminders", () => ({
        reminders: [
            { id: 1, text: "Walk the dog" },
            { id: 2, text: "Take out the trash" },
            { id: 3, text: "Work out" },
          ],
      }))
    },
  })
}
Footer

https://github.com/sultanshaik/MirageBrowserTest/blob/main/mirage-tutorial/src/server.js

I am able to see the response when I make the call from code.

https://github.com/sultanshaik/MirageBrowserTest/blob/main/mirage-tutorial/src/components/Reminders.js

I am trying to see if it is possible to make a get request in Mirage JS using the browser.I wanted to know if it is possible to see the same by visiting "https://localhost:3000//api/reminders". I don't see the route directly.What am I doing wrong?


问:
Nx Daemon stops working when using custom remote cache
Whenever I build my Angular application with my custom task runner that uses a custom remote cache, the Nx daemon stops working. A commit, like you often read, does not solve the issue. I suspect that my custom remote cache implementation of the store method might have issues:

```<code>store = async (hash: string, cacheDirectory: string): Promise<boolean> => {
    console.debug('writing in cache...');
    console.debug(`hash: ${hash}`);
    const hashCommit = hash + '.commit';
    const localCommit = path.join(cacheDirectory, hashCommit);
    const local = path.join(cacheDirectory, hash);
    const zipped = zip(local);

    const blobContainer = getBlobContainer(
      this.connectionString,
      this.container
    );

    const remote = blobContainer.getBlockBlobClient(`${hash}.zip`);
    const remoteCommit = blobContainer.getBlockBlobClient(hashCommit);

    await remote.uploadData(zipped);
    await remoteCommit.uploadFile(localCommit);

    return Promise.resolve(true);
  };
</code>```

NX   Failed to start or connect to the Nx Daemon process.

Messages from the log:    [NX Daemon Server] -
2022-12-24T22:56:35.583Z - [REQUEST]: Client Request for Project Graph
Received    [NX Daemon Server] - 2022-12-24T22:56:35.635Z - [REQUEST]:
Updated file-hasher based on watched changes, recomputing project
graph...    [NX Daemon Server] - 2022-12-24T22:56:36.541Z - Started
listening on:
\.\pipe\nx\C:\Users\stefa\AppData\Local\Temp\78c4dcdc4cfc72d78c62\d.sock
[NX Daemon Server] - 2022-12-24T22:56:37.033Z - Established a
connection. Number of open connections: 1    [NX Daemon Server] -
2022-12-24T22:56:37.034Z - Established a connection. Number of open
connections: 2    [NX Daemon Server] - 2022-12-24T22:56:37.035Z -
[WATCHER]: Subscribed to changes within:
c:\Users\stefa\Local_Storage\projects\nx-giant    [NX Daemon Server] -
2022-12-24T22:56:37.037Z - [REQUEST]: Client Request for Project Graph
Received    [NX Daemon Server] - 2022-12-24T22:56:37.073Z - [REQUEST]:
Updated file-hasher based on watched changes, recomputing project
graph...    [NX Daemon Server] - 2022-12-24T22:56:37.327Z - [REQUEST]:
Responding to the client. project-graph    [NX Daemon Server] -
2022-12-24T22:56:37.331Z - Time taken for 'total for creating and
serializing project graph' 289.47169998288155ms    [NX Daemon Server]

2022-12-24T22:56:37.335Z - Closed a connection. Number of open connections: 1    [NX Daemon Server] - 2022-12-24T22:56:37.335Z - Done
responding to the client project-graph    [NX Daemon Server] -
2022-12-24T22:56:37.614Z - Established a connection. Number of open
connections: 2    [NX Daemon Server] - 2022-12-24T22:56:37.614Z -
Established a   [NX Daemon Server] - 2022-12-24T22:56:37.618Z -
[REQUEST]: Responding to the client. project-graph   [NX Daemon
Server] - 2022-12-24T22:56:37.622Z - Time taken for 'total for
creating and serializing project graph' 0.30550000071525574ms    [NX
Daemon Server] - 2022-12-24T22:56:37.622Z - Done responding to the
client project-graph

Body:
Whenever I build my Angular application with my custom task runner that uses a custom remote cache, the Nx daemon stops working. A commit, like you often read, does not solve the issue. I suspect that my custom remote cache implementation of the store method might have issues:

store = async (hash: string, cacheDirectory: string): Promise<boolean> => {
    console.debug('writing in cache...');
    console.debug(`hash: ${hash}`);
    const hashCommit = hash + '.commit';
    const localCommit = path.join(cacheDirectory, hashCommit);
    const local = path.join(cacheDirectory, hash);
    const zipped = zip(local);

    const blobContainer = getBlobContainer(
      this.connectionString,
      this.container
    );

    const remote = blobContainer.getBlockBlobClient(`${hash}.zip`);
    const remoteCommit = blobContainer.getBlockBlobClient(hashCommit);

    await remote.uploadData(zipped);
    await remoteCommit.uploadFile(localCommit);

    return Promise.resolve(true);
  };

NX   Failed to start or connect to the Nx Daemon process.

Messages from the log:    [NX Daemon Server] -
2022-12-24T22:56:35.583Z - [REQUEST]: Client Request for Project Graph
Received    [NX Daemon Server] - 2022-12-24T22:56:35.635Z - [REQUEST]:
Updated file-hasher based on watched changes, recomputing project
graph...    [NX Daemon Server] - 2022-12-24T22:56:36.541Z - Started
listening on:
\.\pipe\nx\C:\Users\stefa\AppData\Local\Temp\78c4dcdc4cfc72d78c62\d.sock
[NX Daemon Server] - 2022-12-24T22:56:37.033Z - Established a
connection. Number of open connections: 1    [NX Daemon Server] -
2022-12-24T22:56:37.034Z - Established a connection. Number of open
connections: 2    [NX Daemon Server] - 2022-12-24T22:56:37.035Z -
[WATCHER]: Subscribed to changes within:
c:\Users\stefa\Local_Storage\projects\nx-giant    [NX Daemon Server] -
2022-12-24T22:56:37.037Z - [REQUEST]: Client Request for Project Graph
Received    [NX Daemon Server] - 2022-12-24T22:56:37.073Z - [REQUEST]:
Updated file-hasher based on watched changes, recomputing project
graph...    [NX Daemon Server] - 2022-12-24T22:56:37.327Z - [REQUEST]:
Responding to the client. project-graph    [NX Daemon Server] -
2022-12-24T22:56:37.331Z - Time taken for 'total for creating and
serializing project graph' 289.47169998288155ms    [NX Daemon Server]

2022-12-24T22:56:37.335Z - Closed a connection. Number of open connections: 1    [NX Daemon Server] - 2022-12-24T22:56:37.335Z - Done
responding to the client project-graph    [NX Daemon Server] -
2022-12-24T22:56:37.614Z - Established a connection. Number of open
connections: 2    [NX Daemon Server] - 2022-12-24T22:56:37.614Z -
Established a   [NX Daemon Server] - 2022-12-24T22:56:37.618Z -
[REQUEST]: Responding to the client. project-graph   [NX Daemon
Server] - 2022-12-24T22:56:37.622Z - Time taken for 'total for
creating and serializing project graph' 0.30550000071525574ms    [NX
Daemon Server] - 2022-12-24T22:56:37.622Z - Done responding to the
client project-graph


问:
Bring an AsyncImage to the top of the Screen SwiftUI
I got the problem that whatever I tried didn't work to bring the informations on the bottom of the picture right under the pokemons picture. What can i do to fix this?

```<code>struct PokeDetailView: View {
 var pokemon: ViewModel.PokeMon
 var body: some View {
  VStack{
   AsyncImage(url: URL(string: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/\(pokemon.id).png")) {
    image in image
     .image?.resizable()
     .aspectRatio(contentMode: .fit)

   }

   VStack{
    Text("\(pokemon.name.english)")
    HStack{
     Text("Type: ")
     Text("\(pokemon.type[0])")
     Image("Pokemon_Type_Icon_\(String(pokemon.type[0]))")
      .resizable()
      .frame(width: 20,height: 20)

     if(pokemon.type.count > 1){
      Text("\(pokemon.type[1])")
      Image("Pokemon_Type_Icon_\(String(pokemon.type[1]))")
       .resizable()
       .frame(width: 20,height: 20)

     }

    }

   }
  }
 }

}

</code>```

https://i.stack.imgur.com/T3WxK.png

Body:
I got the problem that whatever I tried didn't work to bring the informations on the bottom of the picture right under the pokemons picture. What can i do to fix this?

struct PokeDetailView: View {
 var pokemon: ViewModel.PokeMon
 var body: some View {
  VStack{
   AsyncImage(url: URL(string: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/\(pokemon.id).png")) {
    image in image
     .image?.resizable()
     .aspectRatio(contentMode: .fit)

   }

   VStack{
    Text("\(pokemon.name.english)")
    HStack{
     Text("Type: ")
     Text("\(pokemon.type[0])")
     Image("Pokemon_Type_Icon_\(String(pokemon.type[0]))")
      .resizable()
      .frame(width: 20,height: 20)

     if(pokemon.type.count > 1){
      Text("\(pokemon.type[1])")
      Image("Pokemon_Type_Icon_\(String(pokemon.type[1]))")
       .resizable()
       .frame(width: 20,height: 20)

     }

    }

   }
  }
 }

}

https://i.stack.imgur.com/T3WxK.png


问:
Google API query when run from try API but get 400 return code when run from Jupyter
I have a Google Custom search JSON API call set up like:

```<code>endpoint = 'https://customsearch.googleapis.com/customsearch/v1'
params = {
    'key': api_key,
    'cx': 'my csx key',
    'q': query,
    'cr': CR,
    'count' : Num,
    'startIndex' : Start,
}
response = requests.get(endpoint, params=params)
</code>```

I've checked all the values and they are valid

```<code>query = 'site:xxx.com'
Num = 10
Start = 1
</code>```

When run from Jupyter notebook with a Python 3 kernel I get a 400 return code.

When  run it from the Google API try this page I get a 200 return code: the request section from the response

```<code>request": [
      {
        "title": "Google Custom Search - site:xxx.com",
        "totalResults": "1620000",
        "searchTerms": "site:xxx.com",
        "count": 10,
        "startIndex": 1,
        "inputEncoding": "utf8",
        "outputEncoding": "utf8",
        "safe": "off",
        "cx": "valid csx",
        "cr": "countryUSA"
    }
</code>```

Tried same call from Try API page on google developers page and from Juypter notebook (both Anaconda  and Carnets).

Get a 400 return code when running from Juypter notebooks and a 200 (success) from the Try API page.

Copied API and CSX from notebook to Try API to insure those params were correct. I also confirmed that all parameters were the correct type.

Body:
I have a Google Custom search JSON API call set up like:

endpoint = 'https://customsearch.googleapis.com/customsearch/v1'
params = {
    'key': api_key,
    'cx': 'my csx key',
    'q': query,
    'cr': CR,
    'count' : Num,
    'startIndex' : Start,
}
response = requests.get(endpoint, params=params)

I've checked all the values and they are valid

query = 'site:xxx.com'
Num = 10
Start = 1

When run from Jupyter notebook with a Python 3 kernel I get a 400 return code.

When  run it from the Google API try this page I get a 200 return code: the request section from the response

request": [
      {
        "title": "Google Custom Search - site:xxx.com",
        "totalResults": "1620000",
        "searchTerms": "site:xxx.com",
        "count": 10,
        "startIndex": 1,
        "inputEncoding": "utf8",
        "outputEncoding": "utf8",
        "safe": "off",
        "cx": "valid csx",
        "cr": "countryUSA"
    }

Tried same call from Try API page on google developers page and from Juypter notebook (both Anaconda  and Carnets).

Get a 400 return code when running from Juypter notebooks and a 200 (success) from the Try API page.

Copied API and CSX from notebook to Try API to insure those params were correct. I also confirmed that all parameters were the correct type.


问:
intent.getAction() is always null inside onNewIntent() when NFC tag scan
I tagged nfc after running the app I made.

After the tag, newIntent is executed, but getAction() always return null.

I have attached java code and xml code.

Please.

Please tell me the solution.

bellow code is java code

public class MainActivity extends AppCompatActivity {

    TextView nfcText;
    private final String[][] techList = new String[][] {
            new String[] {NfcA.class.getName(), NfcB.class.getName(),
                    NfcF.class.getName(), NfcV.class.getName(),
                    NdefFormatable.class.getName(), TagTechnology.class.getName(),
                    IsoDep.class.getName(), MifareClassic.class.getName(),
                    MifareUltralight.class.getName(), Ndef.class.getName()}
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onResume() {
        super.onResume();
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_IMMUTABLE);

        IntentFilter filter = new IntentFilter();
        //filter.addCategory(Intent.CATEGORY_DEFAULT);

        filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, new IntentFilter[]{filter}, this.techList);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        //super.onNewIntent(intent);
        //setIntent(intent);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction()) ||
                NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) ||
                NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            nfcText = (TextView) findViewById(R.id.nfcText);
            nfcText.setText(byteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID)));
        }
    }
}
```
<p>The picture below is the param value when checking intent.getAction().</p>
<p><img src="https://i.stack.imgur.com/sAlVj.png" alt="enter image description here" /></p>
<p>and bellow code is androidManifest.xml code</p>
<p>androidManifest</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.nfcactivity">
    <uses-sdk android:minSdkVersion="10"></uses-sdk>
    <uses-permission android:name="android.permission.NFC" />
    <uses-feature android:name="android.hardware.nfc" android:required="true" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.NfcActivity">
        <activity >
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.nfc.action.TAG_DISCOVERED"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
                <data android:mimeType="text/plain"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

Body:
I tagged nfc after running the app I made.

After the tag, newIntent is executed, but getAction() always return null.

I have attached java code and xml code.

Please.

Please tell me the solution.

bellow code is java code

public class MainActivity extends AppCompatActivity {

    TextView nfcText;
    private final String[][] techList = new String[][] {
            new String[] {NfcA.class.getName(), NfcB.class.getName(),
                    NfcF.class.getName(), NfcV.class.getName(),
                    NdefFormatable.class.getName(), TagTechnology.class.getName(),
                    IsoDep.class.getName(), MifareClassic.class.getName(),
                    MifareUltralight.class.getName(), Ndef.class.getName()}
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onResume() {
        super.onResume();
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_IMMUTABLE);

        IntentFilter filter = new IntentFilter();
        //filter.addCategory(Intent.CATEGORY_DEFAULT);

        filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
        filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);
        NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, new IntentFilter[]{filter}, this.techList);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        //super.onNewIntent(intent);
        //setIntent(intent);
        if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(intent.getAction()) ||
                NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) ||
                NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            nfcText = (TextView) findViewById(R.id.nfcText);
            nfcText.setText(byteArrayToHexString(intent.getByteArrayExtra(NfcAdapter.EXTRA_ID)));
        }
    }
}

The picture below is the param value when checking intent.getAction().

and bellow code is androidManifest.xml code

androidManifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.nfcactivity">
    <uses-sdk android:minSdkVersion="10"></uses-sdk>
    <uses-permission android:name="android.permission.NFC" />
    <uses-feature android:name="android.hardware.nfc" android:required="true" />
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.NfcActivity">
        <activity >
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.nfc.action.TAG_DISCOVERED"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
                <data android:mimeType="text/plain"/>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>


问:
Remove dates that are NOT selectable from Bootstrap datepicker
I am using what I believe to be a bootstrap-datepicker plugin. I am using a datepicker and I only have the startDate set to today and the endDate set to 3 days later. This works in that I am only able to select the dates in my date range. The issue I am experiencing is, even if I cannot select example yesterday's date, it isnt greyed out or disabled, it looks like it can be selected. This is an issue cause a user is going ton be clicking it and wondering why it's not being selected and think the datepicker is an issue.

I have the following code.

```<code>         $('#kt_datepicker_1, #kt_datepicker_1_validate').datepicker({
            rtl: KTUtil.isRTL(),
            todayHighlight: true,
            clearBtn: true,
            startDate: new Date(),
            endDate: '+3D',
            beforeShowDay: function (date) {
                console.log(date);
                if (date >= $('#kt_datepicker_1, #kt_datepicker_1_validate').datepicker('option', 'startDate') && date
                    <= $('#kt_datepicker_1, #kt_datepicker_1_validate').datepicker('option', 'endDate')) {
                    console.log("test");
                }
                if (date < $('#kt_datepicker_1, #kt_datepicker_1_validate').datepicker('option', 'startDate') ||
                    date > $('#kt_datepicker_1, #kt_datepicker_1_validate').datepicker('option', 'endDate')) {
                    return [false, '', ''];
                }
                return [true, '', ''];
            }
           // templates: arrows,

        });
</code>```

When I run it, the first console.log displays all dates from 27 nov to 7th jan (entire month calendar) , where as the second console.log is not hit. Appreciate if I could get some assistance in removing the dates that are NOT selectable from my datepicker.

Regards

Body:
I am using what I believe to be a bootstrap-datepicker plugin. I am using a datepicker and I only have the startDate set to today and the endDate set to 3 days later. This works in that I am only able to select the dates in my date range. The issue I am experiencing is, even if I cannot select example yesterday's date, it isnt greyed out or disabled, it looks like it can be selected. This is an issue cause a user is going ton be clicking it and wondering why it's not being selected and think the datepicker is an issue.

I have the following code.

         $('#kt_datepicker_1, #kt_datepicker_1_validate').datepicker({
            rtl: KTUtil.isRTL(),
            todayHighlight: true,
            clearBtn: true,
            startDate: new Date(),
            endDate: '+3D',
            beforeShowDay: function (date) {
                console.log(date);
                if (date >= $('#kt_datepicker_1, #kt_datepicker_1_validate').datepicker('option', 'startDate') && date
                    <= $('#kt_datepicker_1, #kt_datepicker_1_validate').datepicker('option', 'endDate')) {
                    console.log("test");
                }
                if (date < $('#kt_datepicker_1, #kt_datepicker_1_validate').datepicker('option', 'startDate') ||
                    date > $('#kt_datepicker_1, #kt_datepicker_1_validate').datepicker('option', 'endDate')) {
                    return [false, '', ''];
                }
                return [true, '', ''];
            }
           // templates: arrows,

        });

When I run it, the first console.log displays all dates from 27 nov to 7th jan (entire month calendar) , where as the second console.log is not hit. Appreciate if I could get some assistance in removing the dates that are NOT selectable from my datepicker.

Regards


问:
Error: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(None, None, None, 224, 224, 3)
I am trying to create a model that can detect balloons by creating a CNN model. When I try to fit() the model I get this error:
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(None, None, None, 224, 224, 3)

I have tried making some changes (primarily small changes) but nothing really worked. I don't know what can cause that so anything will be helpful.

My code:

```<code>import numpy as np
import pandas as pd

import tensorflow as tf
import tensorflow_datasets as tfds
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

model = tf.keras.Sequential([
    tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

 model.compile(loss='binary_crossentropy',
          optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
          metrics=['accuracy'])

annotations_file = '/content/balloon-data.csv'
annotations = pd.read_csv(annotations_file)

image_paths = []
labels = []
for i, row in annotations.iterrows():
    if row['num_balloons'] > 0:
        image_path = 'path/to/image/{}'.format(row['fname'])
        image_paths.append(image_path)
        labels.append(1)
    else:
        image_path = 'path/to/image/{}'.format(row['fname'])
        image_paths.append(image_path)
        labels.append(0)

dataset = tf.data.Dataset.from_tensor_slices((image_paths, labels))

def preprocess_image(image_path, label):
    image = tf.io.read_file(image_path)
    image = tf.image.decode_jpeg(image, channels=3)
    image = tf.image.resize(image, (224, 224))
    image = image / 255.0
    return image, label

dataset = dataset.map(lambda x, y: preprocess_image(x, y)).batch(64)

train_size = int(0.8 * len(image_paths))
test_size = len(image_paths) - train_size
train_dataset = dataset.take(train_size)
test_dataset = dataset.skip(train_size)

train_dataset = train_dataset.shuffle(1024).batch(32)
test_dataset = test_dataset.batch(32)

train_dataset = train_dataset.shuffle(1024).batch(64)
test_dataset = test_dataset.batch(64)

model.fit(train_dataset, epochs=10, validation_data=test_dataset)
</code>```

Edit

Changes:

```<code>dataset = dataset.map(lambda x, y: preprocess_image(x, y)).batch(64)
#changed to
dataset = dataset.map(preprocess_image)

train_dataset = train_dataset.shuffle(1024).batch(64)
test_dataset = test_dataset.batch(64)
#Were deleted
</code>```

Body:
I am trying to create a model that can detect balloons by creating a CNN model. When I try to fit() the model I get this error:
ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 224, 224, 3), found shape=(None, None, None, 224, 224, 3)

I have tried making some changes (primarily small changes) but nothing really worked. I don't know what can cause that so anything will be helpful.

My code:

import numpy as np
import pandas as pd

import tensorflow as tf
import tensorflow_datasets as tfds
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)

model = tf.keras.Sequential([
    tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Conv2D(128, (3, 3), activation='relu'),
    tf.keras.layers.MaxPooling2D(2, 2),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

 model.compile(loss='binary_crossentropy',
          optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
          metrics=['accuracy'])

annotations_file = '/content/balloon-data.csv'
annotations = pd.read_csv(annotations_file)

image_paths = []
labels = []
for i, row in annotations.iterrows():
    if row['num_balloons'] > 0:
        image_path = 'path/to/image/{}'.format(row['fname'])
        image_paths.append(image_path)
        labels.append(1)
    else:
        image_path = 'path/to/image/{}'.format(row['fname'])
        image_paths.append(image_path)
        labels.append(0)

dataset = tf.data.Dataset.from_tensor_slices((image_paths, labels))

def preprocess_image(image_path, label):
    image = tf.io.read_file(image_path)
    image = tf.image.decode_jpeg(image, channels=3)
    image = tf.image.resize(image, (224, 224))
    image = image / 255.0
    return image, label

dataset = dataset.map(lambda x, y: preprocess_image(x, y)).batch(64)

train_size = int(0.8 * len(image_paths))
test_size = len(image_paths) - train_size
train_dataset = dataset.take(train_size)
test_dataset = dataset.skip(train_size)

train_dataset = train_dataset.shuffle(1024).batch(32)
test_dataset = test_dataset.batch(32)

train_dataset = train_dataset.shuffle(1024).batch(64)
test_dataset = test_dataset.batch(64)

model.fit(train_dataset, epochs=10, validation_data=test_dataset)

Edit

Changes:

dataset = dataset.map(lambda x, y: preprocess_image(x, y)).batch(64)
#changed to
dataset = dataset.map(preprocess_image)

train_dataset = train_dataset.shuffle(1024).batch(64)
test_dataset = test_dataset.batch(64)
#Were deleted


问:
SSE instruction addressing methods and operand types in virtual real mode / real mode / 16-bit protected mode
I'm trying to figure out some of the SSE instruction set's  operand types in virtual real mode / real mode / 16-bit protected mode.

For example let's take the following instruction:

```<code>66 0F 38 01 /r PHADDW xmm1, xmm2/m128
</code>```

The destination operand is an XMM register and the source operand is an XMM register or a 128-bit memory.

Now I couldn't find anything regarding the modes I've been mentioning in the Intel reference and the SSE instruction's operand types changing in these modes, but according to capstone this instruction's source operand suddenly became a 64-bit memory operand, not to mention that it seems capstone just dismissed the mandatory 0x66 operand size prefix for this instruction and used the addressing P and Q instead of V and W (as mentioned in the Intel ref) for the destination and source operands accordingly, and thus disassembling it as:

```<code>66 0F 38 01 58 D6    phaddw mm3, qword ptr [bx + si - 0x2a]
</code>```

with an MMX register instead of an XMM register as I would have thought.

To my understanding the correct disassembly should be:

```<code>phaddw xmm3, xmmword ptr [bx + si - 0x2a]
</code>```

using 128-bit memory as the source operand, and using an XMM register as the destination operand.

So either capstone is wrong or I'm missing something regarding SSE instructions and 16-bit mode somewhere in the Intel ref.

Clarification would be appreciated.

Body:
I'm trying to figure out some of the SSE instruction set's  operand types in virtual real mode / real mode / 16-bit protected mode.

For example let's take the following instruction:

66 0F 38 01 /r PHADDW xmm1, xmm2/m128

The destination operand is an XMM register and the source operand is an XMM register or a 128-bit memory.

Now I couldn't find anything regarding the modes I've been mentioning in the Intel reference and the SSE instruction's operand types changing in these modes, but according to capstone this instruction's source operand suddenly became a 64-bit memory operand, not to mention that it seems capstone just dismissed the mandatory 0x66 operand size prefix for this instruction and used the addressing P and Q instead of V and W (as mentioned in the Intel ref) for the destination and source operands accordingly, and thus disassembling it as:

66 0F 38 01 58 D6    phaddw mm3, qword ptr [bx + si - 0x2a]

with an MMX register instead of an XMM register as I would have thought.

To my understanding the correct disassembly should be:

phaddw xmm3, xmmword ptr [bx + si - 0x2a]

using 128-bit memory as the source operand, and using an XMM register as the destination operand.

So either capstone is wrong or I'm missing something regarding SSE instructions and 16-bit mode somewhere in the Intel ref.

Clarification would be appreciated.


问:
Programmatically Run Gradle Test Given File and Optional Test Name
I'm trying to write a Java application which is a command line tool, where part of it will run a Gradle test in your own application on invoking it. It will have the full path to the file and an optional test name at its disposal. I could shell out and run it manually e.g.:

gradlew <module>:test --tests <fullTestName>
```
<p>but I am looking for a way to use the Gradle API to do so. However, I'm not seeing any packages on Maven to have my cmd line app be able to hook into the current directory's gradle project and be able to call it's test task.</p>
<p>For example:</p>
```dependencies {
    implementation("org.gradle:gradle-core:6.8.3")
}
```

results in a 'not found' error.

Is there a way to do this?

Body:
I'm trying to write a Java application which is a command line tool, where part of it will run a Gradle test in your own application on invoking it. It will have the full path to the file and an optional test name at its disposal. I could shell out and run it manually e.g.:

gradlew <module>:test --tests <fullTestName>

but I am looking for a way to use the Gradle API to do so. However, I'm not seeing any packages on Maven to have my cmd line app be able to hook into the current directory's gradle project and be able to call it's test task.

For example:

dependencies {
    implementation("org.gradle:gradle-core:6.8.3")
}

results in a 'not found' error.

Is there a way to do this?


问:
The best choice to implement custom deleter of shared_ptr, which is a class member
I am writing a little wrapper for OpenGL shaders. Each shader after creation receives ID from OpenGL. My Shader class keeps this ID and provides some useful stuff. My class should be copyable and movable.

In destructor of my class I want to call glDeleteShader(m_rendererId). But I want to do it only for last copy of object of Shader class.

Example implementation of Shader class

```<code>class Shader
{
    public:
        Shader(ShaderType type, std::string shaderSource) { /*glCreateShader, glCompileShader*/ }
        ~Shader() { glDeleteShader(m_rendererId) }

    private:
        unsigned int m_rendererId = 0;
}
</code>```

This implementation has a big problem. If I want to use one shader in multiply shader programs and I create one shader and make its copy, when one of them is destroyed, the m_rendererId  of other will point on removed by OpenGL shader object.

So my idea is to declare m_rendererId as follow:

```<code>std::shared_ptr<unsigned int> m_rendererId
</code>```

I have 2 options to call glDeleteShader(m_rendererId) in this situation:

I can provide custom deleter, which will call glDeleteShader(m_rendererId).

I can change destructor to the follow:

```<code>~Shader() {
    if (m_rendererId.use_count() == 1)
        glDeleteShader(m_rendererId);
}
</code>```

So, what is the best choice to implement custom deleter of shared_ptr, which is a class member?

Body:
I am writing a little wrapper for OpenGL shaders. Each shader after creation receives ID from OpenGL. My Shader class keeps this ID and provides some useful stuff. My class should be copyable and movable.

In destructor of my class I want to call glDeleteShader(m_rendererId). But I want to do it only for last copy of object of Shader class.

Example implementation of Shader class

class Shader
{
    public:
        Shader(ShaderType type, std::string shaderSource) { /*glCreateShader, glCompileShader*/ }
        ~Shader() { glDeleteShader(m_rendererId) }

    private:
        unsigned int m_rendererId = 0;
}

This implementation has a big problem. If I want to use one shader in multiply shader programs and I create one shader and make its copy, when one of them is destroyed, the m_rendererId  of other will point on removed by OpenGL shader object.

So my idea is to declare m_rendererId as follow:

std::shared_ptr<unsigned int> m_rendererId

I have 2 options to call glDeleteShader(m_rendererId) in this situation:

I can provide custom deleter, which will call glDeleteShader(m_rendererId).

I can change destructor to the follow:

~Shader() {
    if (m_rendererId.use_count() == 1)
        glDeleteShader(m_rendererId);
}

So, what is the best choice to implement custom deleter of shared_ptr, which is a class member?


问:
shoutem/ui with expo fails to compile
Trying to scaffold a brand new Expo / React Native App with Shoutem/UI and I keep getting the same issue. I start by simply doing the following:

```<code>expo init myApp --template @native-base/expo-template-typescript
npm install --save shoutem/ui
npm start
</code>```

Then I edit the App.tsx to only include the react code in the UI toolkit introduction

```<code>import React, { Component } from 'react';
import { Examples } from '@shoutem/ui';

export default class App extends Component<{}> {
  render() {
    return (
      <Examples />
    );
  }
}
</code>```

Which results in the following

```<code>Invariant Violation: Native module cannot be null.
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:104:19 in reportException
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:172:19 in handleException
at node_modules/react-native/Libraries/Core/setUpErrorHandling.js:24:39 in handleError
at node_modules/@react-native/polyfills/error-guard.js:49:36 in ErrorUtils.reportFatalError
at node_modules/metro-runtime/src/polyfills/require.js:204:40 in guardedLoadModule
at http://192.168.1.232:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:211718:3 in global code
</code>```

Title: shoutem/ui with expo fails to compile

Body:
Trying to scaffold a brand new Expo / React Native App with Shoutem/UI and I keep getting the same issue. I start by simply doing the following:

expo init myApp --template @native-base/expo-template-typescript
npm install --save shoutem/ui
npm start

Then I edit the App.tsx to only include the react code in the UI toolkit introduction

import React, { Component } from 'react';
import { Examples } from '@shoutem/ui';

export default class App extends Component<{}> {
  render() {
    return (
      <Examples />
    );
  }
}

Which results in the following

Invariant Violation: Native module cannot be null.
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:104:19 in reportException
at node_modules/react-native/Libraries/Core/ExceptionsManager.js:172:19 in handleException
at node_modules/react-native/Libraries/Core/setUpErrorHandling.js:24:39 in handleError
at node_modules/@react-native/polyfills/error-guard.js:49:36 in ErrorUtils.reportFatalError
at node_modules/metro-runtime/src/polyfills/require.js:204:40 in guardedLoadModule
at http://192.168.1.232:19000/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:211718:3 in global code


问:
Is there a best practice for accessible keyboard navigation through an undirected graph
TL;DR: Is there a recommended best practice to make keyboard navigation through an undirected graph accessible for visually impaired people?

I am currently working on an HTML based application that displays an undirected graph of buttons. Buttons are all contained in one div container. The paths that connect buttons visually are in a different container and are not relevant here, but the information that they transport about adjacency, of course. Each button can be used to trigger some action. I now wonder how I could make keyboard navigation accessible for visually impaired people.

Without any special treatment, a user would simply tab through all buttons. Information about adjacent buttons could, of course, be given via ARIA descriptions, but direct navigation to a specific neighboring button would not be possible. One would need to remember the label of the button and tab until it's found. That doesn't feel too user friendly.

I have browsed common ARIA patterns and ARIA roles, but none does really seem to fit my purpose - I'd end up dynamically creating and restructuring treeviews or (tab)lists or worse with all kind of pitfalls probably.

Currently, my best idea is to simply use the application role for the buttons' div container with some custom keyboard commands to navigate. Navigation instructions would be announced via screen readers, of course. This could for instance mean: tab to enter/exit the application div and focus the entry button/previously selected button, arrow keys to cycle through the currently focused button's neighbors and the button itself announcing each label, and space/enter on the button would trigger the button's action and space/enter on a neighbor would make this the newly selected button.

That sounds feasible to me, but I wonder if there already is some best practice for this problem that I did not find myself.


问:
How to implement attention matrix from pretrained BERT uncased transformer model to analyze IMDB sentiment tasks
I was following this well-known paper and wanted to generate the attention matrices demonstrated on the last three pages of this paper.
The data and model I built are based on this extensive tutorial. However, I am having difficulty extracting one transformer block and generating an attention matrix between the words and the class tokens for some of the correctly and incorrectly predicted reviews.
Here is the part I believe needs significant modifications (even tried to get rid of a pre-trained model and manually coded one, but failed).

```<code>class BertBinaryClassifier(nn.Module):
def __init__(self, dropout=0.1):
    super(BertBinaryClassifier, self).__init__()

    self.bert = BertModel.from_pretrained('bert-base-uncased')

    self.dropout = nn.Dropout(dropout)
    self.linear = nn.Linear(768, 1)
    self.sigmoid = nn.Sigmoid()

def forward(self, tokens, masks=None):
    _, pooled_output = self.bert(tokens, attention_mask=masks, output_all_encoded_layers=False)
    dropout_output = self.dropout(pooled_output)
    linear_output = self.linear(dropout_output)
    proba = self.sigmoid(linear_output)
    return proba
</code>```

Could someone offer some guidance or insights on the implementation?

Body:
I was following this well-known paper and wanted to generate the attention matrices demonstrated on the last three pages of this paper.
The data and model I built are based on this extensive tutorial. However, I am having difficulty extracting one transformer block and generating an attention matrix between the words and the class tokens for some of the correctly and incorrectly predicted reviews.
Here is the part I believe needs significant modifications (even tried to get rid of a pre-trained model and manually coded one, but failed).

class BertBinaryClassifier(nn.Module):
def __init__(self, dropout=0.1):
    super(BertBinaryClassifier, self).__init__()

    self.bert = BertModel.from_pretrained('bert-base-uncased')

    self.dropout = nn.Dropout(dropout)
    self.linear = nn.Linear(768, 1)
    self.sigmoid = nn.Sigmoid()

def forward(self, tokens, masks=None):
    _, pooled_output = self.bert(tokens, attention_mask=masks, output_all_encoded_layers=False)
    dropout_output = self.dropout(pooled_output)
    linear_output = self.linear(dropout_output)
    proba = self.sigmoid(linear_output)
    return proba

Could someone offer some guidance or insights on the implementation?


问:
How can I detect when I've copied something new to the clipboard in Python?
I'm trying to create a basic translator program with DeepL API that automatically translates what is on the clipboard, rather than having to run it everytime I decide to copy something new.

I've tried googling a solution but all I can find is how I can paste whatever is in my clipboard, which is just half of what I need.


问:
Creating a new dataset of hidden state probabilities using a HMM results in different shapes after each run
I'm trying to create a new dataset of hidden state probabilities using a hidden Markov model. Everything works fine unless each time the output dataset comes up with different values (sometimes the same values) for hidden_states_train and hidden_states_test hence resulting a different column sizes in the columns stack/ a feature mismatch. e.g New dataset size (15261, 197) (5087, 194), New dataset size (15261, 197) (5087, 197) etc.

I can't figure out why this is happening each time I run the code. I tried to give same number of samples for both X_train_st and X_test_st but this keeps happening. If I set n_comp in range a smaller range e.g for n_comp in range(1,6) then often it results the same shapes.

Can someone shed some light to what's going on and a possible fix, please?

```<code>newX = X_train_st
newXtest = X_test_st

for n_comp in range(1,16):
    print("fitting to HMM and decoding %d ..." % n_comp , end="")
    modelHMM = GaussianHMM(n_components=n_comp, covariance_type="diag").fit(X_train_st)

    hidden_states_train = to_categorical(modelHMM.predict(X_train_st))
    hidden_states_test = to_categorical(modelHMM.predict(X_test_st))

    print("done")
    newX = np.column_stack((newX,hidden_states_train))
    newXtest = np.column_stack((newXtest,hidden_states_test))

print('New dataset size',newX.shape,newXtest.shape)
</code>```

Body:
I'm trying to create a new dataset of hidden state probabilities using a hidden Markov model. Everything works fine unless each time the output dataset comes up with different values (sometimes the same values) for hidden_states_train and hidden_states_test hence resulting a different column sizes in the columns stack/ a feature mismatch. e.g New dataset size (15261, 197) (5087, 194), New dataset size (15261, 197) (5087, 197) etc.

I can't figure out why this is happening each time I run the code. I tried to give same number of samples for both X_train_st and X_test_st but this keeps happening. If I set n_comp in range a smaller range e.g for n_comp in range(1,6) then often it results the same shapes.

Can someone shed some light to what's going on and a possible fix, please?

newX = X_train_st
newXtest = X_test_st

for n_comp in range(1,16):
    print("fitting to HMM and decoding %d ..." % n_comp , end="")
    modelHMM = GaussianHMM(n_components=n_comp, covariance_type="diag").fit(X_train_st)

    hidden_states_train = to_categorical(modelHMM.predict(X_train_st))
    hidden_states_test = to_categorical(modelHMM.predict(X_test_st))

    print("done")
    newX = np.column_stack((newX,hidden_states_train))
    newXtest = np.column_stack((newXtest,hidden_states_test))

print('New dataset size',newX.shape,newXtest.shape)


问:
simulating diffusion with cellular automata
I am trying to implement some kind of artificial life simulation with cells propagating molecule concentration between them using an 2d cellular automata.

problem is that I cannot figure out an algorithm for these diffusion processes. I first thought, "ok Minecraft did something like that with their redstone stuff it can't be this hard"..

My implementation currently iterates over 2d array of cells where each cell has a number of molecules count. then I use kind of convolution with 3x3 kernel to propagate values if saturation of cells are not fulfilled.

For example start values like this:

```<code>100, 0, 0
  0, 0, 0
  0, 0, 0
</code>```

leads to this configuration:

```<code>96,  1, 1
  1, 1, 0
  0, 0, 0
</code>```

how can the cells in the middle "know" that they must propagate further although they are already saturated?

or may is simulating diffusion just not possible that way?

The simulation does not need to be physically correct. What only matters is that the molecules will distribute more or less evenly among the cells, the total number of molecules should not change in that process. Small rounding losses are acceptable.

Body:
I am trying to implement some kind of artificial life simulation with cells propagating molecule concentration between them using an 2d cellular automata.

problem is that I cannot figure out an algorithm for these diffusion processes. I first thought, "ok Minecraft did something like that with their redstone stuff it can't be this hard"..

My implementation currently iterates over 2d array of cells where each cell has a number of molecules count. then I use kind of convolution with 3x3 kernel to propagate values if saturation of cells are not fulfilled.

For example start values like this:

100, 0, 0
  0, 0, 0
  0, 0, 0

leads to this configuration:

96,  1, 1
  1, 1, 0
  0, 0, 0

how can the cells in the middle "know" that they must propagate further although they are already saturated?

or may is simulating diffusion just not possible that way?

The simulation does not need to be physically correct. What only matters is that the molecules will distribute more or less evenly among the cells, the total number of molecules should not change in that process. Small rounding losses are acceptable.


问:
My self-signed certificate is being rejected by the client
On the backend I have a newly created node https + express server, it only have one test endpoint called /test which just logs some message. The openssl configuration file(called req.cnf) used to create the certificate and the key is:

```<code>[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
CN = www.localhost.com
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.localhost.com
DNS.2 = localhost.com
DNS.3 = localhost
</code>```

then I call this command in the same path where the config file is:

```<code>openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout cert.key -out cert.pem -config req.cnf -sha256
</code>```

On the other hand, in the frontend I have Vue calling that /test endpoint through a button.

Now in firefox I get this error:

```<code>Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource
at https://localhost:3001/test. (Reason: CORS request did not succeed). Status code: (null).
</code>```

And in Chrome:

```<code>GET https://localhost:3001/test net::ERR_CERT_AUTHORITY_INVALID
</code>```

Some notes:

I get the same errors if instead of localhost I use the local network ip.

If I change the node server from https to http then the request works just fine without errors.

The server is reading the cert and key files correctly, there is not error on that part.

What can I do to make this self signed certificate to work?

Body:
On the backend I have a newly created node https + express server, it only have one test endpoint called /test which just logs some message. The openssl configuration file(called req.cnf) used to create the certificate and the key is:

[req]
distinguished_name = req_distinguished_name
x509_extensions = v3_req
prompt = no
[req_distinguished_name]
CN = www.localhost.com
[v3_req]
keyUsage = critical, digitalSignature, keyAgreement
extendedKeyUsage = serverAuth
subjectAltName = @alt_names
[alt_names]
DNS.1 = www.localhost.com
DNS.2 = localhost.com
DNS.3 = localhost

then I call this command in the same path where the config file is:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout cert.key -out cert.pem -config req.cnf -sha256

On the other hand, in the frontend I have Vue calling that /test endpoint through a button.

Now in firefox I get this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource
at https://localhost:3001/test. (Reason: CORS request did not succeed). Status code: (null).

And in Chrome:

GET https://localhost:3001/test net::ERR_CERT_AUTHORITY_INVALID

Some notes:

I get the same errors if instead of localhost I use the local network ip.

If I change the node server from https to http then the request works just fine without errors.

The server is reading the cert and key files correctly, there is not error on that part.

What can I do to make this self signed certificate to work?


问:
ModuleNotFoundError: No module named 'pygame' spyder
I pip installed pygame and verified that it is on my system and installed correctly by running the following in the cmd and it ran the aleins games as it should.

```<code>>python -m pygame.examples.aliens
</code>```

But when I try to import pygame with Spyder, I am getting a Module Not Found Error. I have double checked to ensure that I do not have more than one version of python installed to make sure that wasn't the issue, but it isn't since I only have the 1 version installed.

Body:
I pip installed pygame and verified that it is on my system and installed correctly by running the following in the cmd and it ran the aleins games as it should.

>python -m pygame.examples.aliens

But when I try to import pygame with Spyder, I am getting a Module Not Found Error. I have double checked to ensure that I do not have more than one version of python installed to make sure that wasn't the issue, but it isn't since I only have the 1 version installed.


问:
Infinite loop by using @Binding when passing data between views

High-level description:

There is a nested view problem when a state object is being passed through views. At the end of the deepest view in the hierarchy, the app is frozen and memory consumption is increasing continuously.

Use-case

Partners list → Partner detail → (Locations list) → Location detail

Code-snippets

class PartnerViewModel: ObservableObject {
    @Published var partners: [Partner] = Partner.partners
}
```
<p>This view is loaded into a <code>TabView</code> and a <code>NavigationStack</code> components in the parent class.</p>
<pre class="lang-swift prettyprint-override"><code>struct PartnerListView: View {
    @StateObject var viewModel = PartnerViewModel()

    var body: some View {
        List($viewModel.partners, id: \.self) { $partner in
            NavigationLink {
                PartnerDetailView(partner: $partner)
            } label: {
                Text(partner.name)
            }
        }
    }
}
</code>```

struct PartnerDetailView: View {
    @Binding var partner: Partner

    var body: some View {
        Form {
            Section("Locations") {
                List($partner.locations, id: \.self) { $location in
                    NavigationLink {
                        LocationDetailView(location: $location)
                    } label: {
                        Text(location.name)
                    }
                }
            }

        }
    }
}
```
<pre class="lang-swift prettyprint-override"><code>struct LocationDetailView: View {
    @Binding var location: Location
    var body: some View {
        TextField("Name", text: $location.name)
    }
}
</code>```

The following snippets are workaround and it works but it might be temporary because I don't understand why the first attempt doesn't work and why this one does. I haven't found any resources that could give an example of this scenario.

struct PartnerDetailView: View {
    @Binding var partner: Partner

    var body: some View {
        Form {
            Section("Locations") {
                List($partner.locations, id: \.self) { $location in
                    NavigationLink {
                        LocationDetailView(partner: $partner, locationIndex: partner.locations.firstIndex(of: location) ?? 0)
                    } label: {
                        Text(location.name)
                    }
                }
            }

        }
    }
}
```
<pre class="lang-swift prettyprint-override"><code>struct LocationDetailView: View {
    @Binding var partner: Partner
    var locationIndex: Int

    var body: some View {
        TextField("Name", text: $partner.locations[locationIndex].name)
    }
}
</code>```

Is it possible that I am not passing values between views properly?

Body:
High-level description:

There is a nested view problem when a state object is being passed through views. At the end of the deepest view in the hierarchy, the app is frozen and memory consumption is increasing continuously.

Use-case

Partners list → Partner detail → (Locations list) → Location detail

Code-snippets

class PartnerViewModel: ObservableObject {
    @Published var partners: [Partner] = Partner.partners
}

This view is loaded into a TabView and a NavigationStack components in the parent class.

struct PartnerListView: View {
    @StateObject var viewModel = PartnerViewModel()

    var body: some View {
        List($viewModel.partners, id: \.self) { $partner in
            NavigationLink {
                PartnerDetailView(partner: $partner)
            } label: {
                Text(partner.name)
            }
        }
    }
}

struct PartnerDetailView: View {
    @Binding var partner: Partner

    var body: some View {
        Form {
            Section("Locations") {
                List($partner.locations, id: \.self) { $location in
                    NavigationLink {
                        LocationDetailView(location: $location)
                    } label: {
                        Text(location.name)
                    }
                }
            }

        }
    }
}

struct LocationDetailView: View {
    @Binding var location: Location
    var body: some View {
        TextField("Name", text: $location.name)
    }
}

The following snippets are workaround and it works but it might be temporary because I don't understand why the first attempt doesn't work and why this one does. I haven't found any resources that could give an example of this scenario.

struct PartnerDetailView: View {
    @Binding var partner: Partner

    var body: some View {
        Form {
            Section("Locations") {
                List($partner.locations, id: \.self) { $location in
                    NavigationLink {
                        LocationDetailView(partner: $partner, locationIndex: partner.locations.firstIndex(of: location) ?? 0)
                    } label: {
                        Text(location.name)
                    }
                }
            }

        }
    }
}

struct LocationDetailView: View {
    @Binding var partner: Partner
    var locationIndex: Int

    var body: some View {
        TextField("Name", text: $partner.locations[locationIndex].name)
    }
}

Is it possible that I am not passing values between views properly?


问:
Do AdminDirectory advanced service APIs only work for admins?
I've got the following function in an unpublished Google Apps Script

```<code>function getUserFromEmail(userEmail)
{
  return AdminDirectory.Users.get(userEmail)
}

</code>```

I've enabled the AdminDirectory advanced service in the script
As an admin, I run the script, and the default OAuth2 consent screen pops up.
I authorize, and the script runs as expected.
I share the script with a non-admin collaborator (Editor)
When the collaborator runs the script, an error is generated

GoogleJsonResponseException: API call to directory.users.get failed with error: Not Authorized to access this resource/api

Yes, I understand that the collaborator does not have the admin privileges necessary to make this call. I can explicitly give the collaborator the necessary permissions via admin console, but that is not a good solution, since I may want a group of non-admin users to run the script (you can't assign by group). Since there is no explicit way of controlling authentication from Google Apps script (aside from URLFetchApp), it appears that the Advanced Services APIs only really work for admins running the script. Creating a GCP, service account, domain-wide delegation, etc. will not help, since we cannot explicitly control authentication from GAS Advanced Services. We are forced to use the URLFetchApp knothole. Most of the questions/posts for this topic a 5-7 years old, and the landscape for the developer platform has changed substantially. Also, Google developer platform documentation is woefully out of date and refers to entities that no longer exist (like  Google APIs Console in https://developers.google.com/admin-sdk/directory/v1/guides/prerequisites)

Is this analysis correct, or have I missed something?

Tried converting project to CGP standard project, enabling Admin SDK library, service account, domain-wide delegation

Body:
I've got the following function in an unpublished Google Apps Script

function getUserFromEmail(userEmail)
{
  return AdminDirectory.Users.get(userEmail)
}

I've enabled the AdminDirectory advanced service in the script
As an admin, I run the script, and the default OAuth2 consent screen pops up.
I authorize, and the script runs as expected.
I share the script with a non-admin collaborator (Editor)
When the collaborator runs the script, an error is generated

GoogleJsonResponseException: API call to directory.users.get failed with error: Not Authorized to access this resource/api

Yes, I understand that the collaborator does not have the admin privileges necessary to make this call. I can explicitly give the collaborator the necessary permissions via admin console, but that is not a good solution, since I may want a group of non-admin users to run the script (you can't assign by group). Since there is no explicit way of controlling authentication from Google Apps script (aside from URLFetchApp), it appears that the Advanced Services APIs only really work for admins running the script. Creating a GCP, service account, domain-wide delegation, etc. will not help, since we cannot explicitly control authentication from GAS Advanced Services. We are forced to use the URLFetchApp knothole. Most of the questions/posts for this topic a 5-7 years old, and the landscape for the developer platform has changed substantially. Also, Google developer platform documentation is woefully out of date and refers to entities that no longer exist (like  Google APIs Console in https://developers.google.com/admin-sdk/directory/v1/guides/prerequisites)

Is this analysis correct, or have I missed something?

Tried converting project to CGP standard project, enabling Admin SDK library, service account, domain-wide delegation


问:
How to make electron app supports CLI, embed oclif project?
I built an CLI app using oclif, and is planning to support desktop app using electron.
I am wondering if it's possible to let electron supports CLI without opening a window.

It would be the best if I can reuse existing oclif code in the electron project.


问:
python3 selenium4: Message: session not created: No matching capabilities found when trying to open Chrome
I am trying to open chrome using selenium following here

I have added the following

```<code>options = ChromeOptions()
path = "/usr/bin/chromedriver"
driver = webdriver.Chrome(executable_path=path, chrome_options=options )
driver.get('https://www.google.com')
</code>```

When I check where chrome driver is located I get

```<code>whereis chromedriver
chromedriver: /usr/bin/chromedriver
</code>```

Both chrome driver and chrome are same versions.

What is causing this error: Message: session not created: No matching capabilities found when trying to open Chrome

Body:
I am trying to open chrome using selenium following here

I have added the following

options = ChromeOptions()
path = "/usr/bin/chromedriver"
driver = webdriver.Chrome(executable_path=path, chrome_options=options )
driver.get('https://www.google.com')

When I check where chrome driver is located I get

whereis chromedriver
chromedriver: /usr/bin/chromedriver

Both chrome driver and chrome are same versions.

What is causing this error: Message: session not created: No matching capabilities found when trying to open Chrome


问:
Cannot destructure property 'id' of 'req.params' as it is undefined
I want my middleware to check if the user is the author of the ad to allow him to edit the post.
My middleware is defined as

```<code>const asyncHandler = require("express-async-handler");
const { carSchema } = require("./schemas.js");
const Car = require("./models/car");

module.exports.isAuthor = asyncHandler(async (req, res, next, Model) => {
  const { id } = req.params;
  const document = await Model.findById(id);
  if (!document.author.equals(req.user._id)) {
    req.flash("error", "Not allowed");
    return res.redirect(`/${Model.collection.name}/${id}`);
  }
  next();
});

</code>```

Router is defined as:

```<code>const express = require("express");
const router = express.Router();
const asyncHandler = require("express-async-handler");
const Car = require("../models/car");
const { isLoggedIn, isAuthor, validateCar } = require("../middleware");

router.get(
  "/:id/edit",
  isLoggedIn,
  isAuthor.bind(null, Car),
  asyncHandler(async (req, res) => {
    const car = await Car.findById(req.params.id);
    if (!car) {
      req.flash("error", "This ad doesnt exist");
      return res.redirect("/cars");
    }
    res.render("cars/editCar", { car });
  })
);
</code>```

When trying to edit the add I'm getting the error:

```<code>Cannot destructure property 'id' of 'req.params' as it is undefined.
TypeError: Cannot destructure property 'id' of 'req.params' as it is undefined. at middleware.js:26:11 at asyncUtilWrap (node_modules\express-async-handler\index.js:3:20) at Layer.handle [as handle_request] (node_modules\express\lib\router\layer.js:95:5) at next (node_modules\express\lib\router\route.js:144:13) at module.exports.isLoggedIn (middleware.js:11:3) at Layer.handle [as handle_request] (node_modules\express\lib\router\layer.js:95:5) at next (node_modules\express\lib\router\route.js:144:13) at Route.dispatch (node_modules\express\lib\router\route.js:114:3) at Layer.handle [as handle_request] (node_modules\express\lib\router\layer.js:95:5) at node_modules\express\lib\router\index.js:284:15 >
</code>```

How to make isAuthor middleware reusable regardless of the model?

Body:
I want my middleware to check if the user is the author of the ad to allow him to edit the post.
My middleware is defined as

const asyncHandler = require("express-async-handler");
const { carSchema } = require("./schemas.js");
const Car = require("./models/car");

module.exports.isAuthor = asyncHandler(async (req, res, next, Model) => {
  const { id } = req.params;
  const document = await Model.findById(id);
  if (!document.author.equals(req.user._id)) {
    req.flash("error", "Not allowed");
    return res.redirect(`/${Model.collection.name}/${id}`);
  }
  next();
});

Router is defined as:

const express = require("express");
const router = express.Router();
const asyncHandler = require("express-async-handler");
const Car = require("../models/car");
const { isLoggedIn, isAuthor, validateCar } = require("../middleware");

router.get(
  "/:id/edit",
  isLoggedIn,
  isAuthor.bind(null, Car),
  asyncHandler(async (req, res) => {
    const car = await Car.findById(req.params.id);
    if (!car) {
      req.flash("error", "This ad doesnt exist");
      return res.redirect("/cars");
    }
    res.render("cars/editCar", { car });
  })
);

When trying to edit the add I'm getting the error:

Cannot destructure property 'id' of 'req.params' as it is undefined.
TypeError: Cannot destructure property 'id' of 'req.params' as it is undefined. at middleware.js:26:11 at asyncUtilWrap (node_modules\express-async-handler\index.js:3:20) at Layer.handle [as handle_request] (node_modules\express\lib\router\layer.js:95:5) at next (node_modules\express\lib\router\route.js:144:13) at module.exports.isLoggedIn (middleware.js:11:3) at Layer.handle [as handle_request] (node_modules\express\lib\router\layer.js:95:5) at next (node_modules\express\lib\router\route.js:144:13) at Route.dispatch (node_modules\express\lib\router\route.js:114:3) at Layer.handle [as handle_request] (node_modules\express\lib\router\layer.js:95:5) at node_modules\express\lib\router\index.js:284:15 >

How to make isAuthor middleware reusable regardless of the model?


问:
What is the best way to implement a circular socket connection between processes?
I want to run three processes (P1, P2, P3) and I would want to connect each three between them, so P1 can broadcast messages to P2 and P3, P2 to P1 and P3 to P1 and P2. All of these three processes are the same program but listening on different ports.

I'm struggling to make the initial connection of all three processes before any data is exchanged.

My first approach was to implement this:

```<code>int OWN = Integer.parseInt(args[0]);
ServerSocket ss = new ServerSocket(OWN);

int connected = 0;
ArrayList<Socket> clients = new ArrayList<>();

while (connected < 2) {
    Socket client = ss.accept();

    clients.add(client);

    System.out.println("New connection");
}

System.out.println("All connected");
</code>```

This piece of code accepts the two other processes connections. But then I figured out: Where do I actually connect to the other processes in that piece of code?

Because if I try connecting them before the loop on ss.accept(), probably it will throw an error as the other processes might not be in the ss.accept() part of the code, as well trying to connect to the other processes.

How can I properly do this?

Body:
I want to run three processes (P1, P2, P3) and I would want to connect each three between them, so P1 can broadcast messages to P2 and P3, P2 to P1 and P3 to P1 and P2. All of these three processes are the same program but listening on different ports.

I'm struggling to make the initial connection of all three processes before any data is exchanged.

My first approach was to implement this:

int OWN = Integer.parseInt(args[0]);
ServerSocket ss = new ServerSocket(OWN);

int connected = 0;
ArrayList<Socket> clients = new ArrayList<>();

while (connected < 2) {
    Socket client = ss.accept();

    clients.add(client);

    System.out.println("New connection");
}

System.out.println("All connected");

This piece of code accepts the two other processes connections. But then I figured out: Where do I actually connect to the other processes in that piece of code?

Because if I try connecting them before the loop on ss.accept(), probably it will throw an error as the other processes might not be in the ss.accept() part of the code, as well trying to connect to the other processes.

How can I properly do this?


问:
RuntimeError: Forward order differs across ranks: rank 0 is all-gathering 1 parameters while rank 2 is all-gathering 0 parameters
I am using FullyShardedDataParallel (FSDP) in pytorch to shard the model across two nodes, two GPUs per node. When I use two nodes the following error happens:

```<code>RuntimeError: Forward order differs across ranks: rank 0 is all-gathering 1 parameters while rank 2 is all-gathering 0 parameters
</code>```

But the same behaviour doesn't happen in one node. I initialized the process group using:
dist.init_process_group then initialized the FullyShardedDataParallel

Body:
I am using FullyShardedDataParallel (FSDP) in pytorch to shard the model across two nodes, two GPUs per node. When I use two nodes the following error happens:

RuntimeError: Forward order differs across ranks: rank 0 is all-gathering 1 parameters while rank 2 is all-gathering 0 parameters

But the same behaviour doesn't happen in one node. I initialized the process group using:
dist.init_process_group then initialized the FullyShardedDataParallel