问:
PyQt: Pop previous commands from UndoStack during current command's undo
I'm in a situation in which I have several commands of the same class pushed onto a QUndoStack and depending on user input another command of a different class might be pushed on top of those. What I would now like to achieve is to remove a fixed number of these previous commands of the first type from the undo stack (either by undoing them or just removing them, doesn't matter in my case) when the topmost command's undo is executed. E.g. like this:

```<code>class CommandA(QUndoCommand):
    # ...

class CommandB(QUndoCommand):
    def undo(self):
        # ...
        # somehow remove last N commands of class A from undostack

stack = QUndoStack()

stack.push(CommandA())
# ...
stack.push(CommandA())

stack.push(CommandB())
</code>```

Just removing the last N commands regardless of which class they belong to would also be helpful as a starting point. This seems to me like it would be a common requirement but I don't see if/how this would be possible.

答:
In PyQt5, commands on the QUndoStack are stored by index and accessed via the command function. You can loop over the commands in the stack using the count method:

for ndx in range(stack.count()):
    command = stack.command(ndx)
```
<p>The <code>command</code> will have the type of your specific <code>QUndoCommand</code> class (i.e. either <code>CommandA</code> or <code>CommandB</code>), so you can use <code>isinstance</code> to check which one it is.</p>
<p>Hence, you can make a <code>QWidget</code> (e.g. a <code>QtWidgets.QPushButton</code>) or <code>QAction</code> whose <code>triggered</code> signal is connected to a function (slot) that undoes the last <code>n</code> <code>CommandA</code> commands:</p>
<pre class="lang-py prettyprint-override"><code>def undo_last_n_CommandAs(n):
    for ndx in range(stack.count()):
        command = stack.command(ndx)
        if n > 0 and isinstance(command, 'CommandA'):
            command.undo()
            n -= 1
</code>```

Body:
I'm in a situation in which I have several commands of the same class pushed onto a QUndoStack and depending on user input another command of a different class might be pushed on top of those. What I would now like to achieve is to remove a fixed number of these previous commands of the first type from the undo stack (either by undoing them or just removing them, doesn't matter in my case) when the topmost command's undo is executed. E.g. like this:

class CommandA(QUndoCommand):
    # ...

class CommandB(QUndoCommand):
    def undo(self):
        # ...
        # somehow remove last N commands of class A from undostack

stack = QUndoStack()

stack.push(CommandA())
# ...
stack.push(CommandA())

stack.push(CommandB())

Just removing the last N commands regardless of which class they belong to would also be helpful as a starting point. This seems to me like it would be a common requirement but I don't see if/how this would be possible.

Body:
In PyQt5, commands on the QUndoStack are stored by index and accessed via the command function. You can loop over the commands in the stack using the count method:

for ndx in range(stack.count()):
    command = stack.command(ndx)

The command will have the type of your specific QUndoCommand class (i.e. either CommandA or CommandB), so you can use isinstance to check which one it is.

Hence, you can make a QWidget (e.g. a QtWidgets.QPushButton) or QAction whose triggered signal is connected to a function (slot) that undoes the last n CommandA commands:

def undo_last_n_CommandAs(n):
    for ndx in range(stack.count()):
        command = stack.command(ndx)
        if n > 0 and isinstance(command, 'CommandA'):
            command.undo()
            n -= 1


来源: stackexchange

问:
Count child nodes on XDocument
Is there a way to count child nodes on an XDocument?

I looked for a count method or property and could not find one.

Thanks
Leo

答:
```<code>var doc = XDocument.Load(fileName);
int descendantsCount = doc.Descendants().Count(); // counts ALL descendants elements
int childrenCount = doc.Root.Elements().Count(); // counts direct children of the root element
</code>```

ContentLicense: CC BY-SA 3.0

Title: Count child nodes on XDocument


问:
How reduce code repitition in the given code?
```<code>class TransactionAccess
{
    public static void GetTransactions()
    {
        string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
        using (var connection = new NpgsqlConnection(connString))
        {
            var transactions = connection.Query<TransactionView>(@"SELECT t.transaction_id,t.account_id,a.account_name, a.type,t.note, t.amount, t.date
                                                               FROM account AS a
                                                               INNER JOIN transaction AS t ON a.account_id = t.account_id");
            transactions.Dump();
        }
    }

    public static void GetTransactionInfo(int id)
    {
        string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
        using (var connection = new NpgsqlConnection(connString))
        {
            var transactionInfo = connection.Query<TransactionView>(@"SELECT a.account_name, a.type, DATE(t.date), t.amount, t.note, t.transaction_id
                                                                  FROM transaction AS t
                                                                  INNER JOIN account AS a ON t.account_id = a.account_id
                                                                  WHERE t.transaction_id = @id", new { id });
            transactionInfo.Dump();
        }
    }
</code>```

}

In the above code, I am using connString and connection many times in every function sepeartely.
How to reduce and that and use only one connection and connString?

答: You're already seeing that you have code duplication (that's the commonly used term) inside your class. You are now storing them in each method seperately. How about storing them inside your class?</p>

ContentLicense: CC BY-SA 4.0

Body:
class TransactionAccess
{
    public static void GetTransactions()
    {
        string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
        using (var connection = new NpgsqlConnection(connString))
        {
            var transactions = connection.Query<TransactionView>(@"SELECT t.transaction_id,t.account_id,a.account_name, a.type,t.note, t.amount, t.date
                                                               FROM account AS a
                                                               INNER JOIN transaction AS t ON a.account_id = t.account_id");
            transactions.Dump();
        }
    }

    public static void GetTransactionInfo(int id)
    {
        string connString = "Host=localhost;Username=postgres;Password=1234;Database=ExpenseManagerDB";
        using (var connection = new NpgsqlConnection(connString))
        {
            var transactionInfo = connection.Query<TransactionView>(@"SELECT a.account_name, a.type, DATE(t.date), t.amount, t.note, t.transaction_id
                                                                  FROM transaction AS t
                                                                  INNER JOIN account AS a ON t.account_id = a.account_id
                                                                  WHERE t.transaction_id = @id", new { id });
            transactionInfo.Dump();
        }
    }

}

In the above code, I am using connString and connection many times in every function sepeartely.
How to reduce and that and use only one connection and connString?


问:
Why the following code use String and StringBuffer in the same line?
```<code>set.add(new String(s) + (ch == 0 ? "" : ch) + new StringBuffer(new String(s)).reverse());
</code>```

I encountered this code from written by someone. It is java code.
s is a char[].
set is a String set.
So why does he use String and then StringBuffer?

答:
Let's split the 3 parts on 3 lines to compare:

```<code>set.add(
  new String(s)
+ (ch == 0 ? "" : ch)
+ new StringBuffer(new String(s)).reverse()
);
</code>```

Rewritten

It is equivalent with

```<code>String trimZero = ch == 0 ? "" : String.valueOf(ch);
set.add(String.valueOf(s) + trimZero + StringUtils.reverse(s));
</code>```

Well, using Apache's StringUtils.reverse().

If s is a String it can simply added as is, for example, in an alternative way (to emphasize the different structures):

```<code>if (ch == 0) {
   set.add(s + StringUtils.reverse(s));
} else {
   set.add(s + String.valueOf(ch) + StringUtils.reverse(s));
}
</code>```

Output wise

For example:

alphabet  gets added as alphabet8tebahpla (for coincidence ch is a non-zero integer).

an gets added as anna (given that ch == 0)

Abbreviations and naming-conventions

When guessing the types I would say:

ch probably is a primitive char, array of that, or CharSequece

s most-likely is a String (rather than the rarely used short integer)

Usually abbreviations in symbols/names are ambiguous and can be considered a code-smell.

However there seems to be a historical and accepted convention or habit, especially for temporary / looping variables like:

int i

String s

char ch

The Java Pocket Guide, 4th Edition by Robert Liguori, Patricia Liguori, Chapter 1. Naming Conventions assorted them in a table:

Temporary variable names may be single letters such as i, j, k, m, and n for integers and c, d, and e for characters. Temporary and looping variables may be one-character names as shown in Table 1-1.

Even core Java methods have such (ambiguous) abbreviated parameter-names

if the method-context is obvious enough

that the contents and purpose of the parameter is self-explaining

E.g. String.contains(CharSequence s)

Body:
set.add(new String(s) + (ch == 0 ? "" : ch) + new StringBuffer(new String(s)).reverse());

I encountered this code from written by someone. It is java code.
s is a char[].
set is a String set.
So why does he use String and then StringBuffer?

Body:
Let's split the 3 parts on 3 lines to compare:

set.add(
  new String(s)
+ (ch == 0 ? "" : ch)
+ new StringBuffer(new String(s)).reverse()
);

Rewritten

It is equivalent with

String trimZero = ch == 0 ? "" : String.valueOf(ch);
set.add(String.valueOf(s) + trimZero + StringUtils.reverse(s));

Well, using Apache's StringUtils.reverse().

If s is a String it can simply added as is, for example, in an alternative way (to emphasize the different structures):

if (ch == 0) {
   set.add(s + StringUtils.reverse(s));
} else {
   set.add(s + String.valueOf(ch) + StringUtils.reverse(s));
}

Output wise

For example:

alphabet  gets added as alphabet8tebahpla (for coincidence ch is a non-zero integer).

an gets added as anna (given that ch == 0)

Abbreviations and naming-conventions

When guessing the types I would say:

ch probably is a primitive char, array of that, or CharSequece

s most-likely is a String (rather than the rarely used short integer)

Usually abbreviations in symbols/names are ambiguous and can be considered a code-smell.

However there seems to be a historical and accepted convention or habit, especially for temporary / looping variables like:

int i

String s

char ch

The Java Pocket Guide, 4th Edition by Robert Liguori, Patricia Liguori, Chapter 1. Naming Conventions assorted them in a table:

Temporary variable names may be single letters such as i, j, k, m, and n for integers and c, d, and e for characters. Temporary and looping variables may be one-character names as shown in Table 1-1.

Even core Java methods have such (ambiguous) abbreviated parameter-names

if the method-context is obvious enough

that the contents and purpose of the parameter is self-explaining

E.g. String.contains(CharSequence s)


问:
jQuery keep checkbox checked while any others are checked
I have more than fifteen checkbox inputs all with the same class, looking something like below:

I want to have only the first input be checked and stay checked when any other input with the same class is checked. If only the first input is checked you should be able to check and uncheck it freely. Only the first one has the ID, #SR01201. The rest only have the class check-12.

Right now, I can freely uncheck and check the first input, and it will get checked if any other inputs with the class check-12 are checked. But once any other input (besides the first one) is checked, it can't be unchecked.

$('.check-12:not(#SR01201)').on('change', function() {
  var $this = $(this);
  var SRTwelveOne = $("#SR01201");
  if ($this.prop('checked', true)) {
    SRTwelveOne.prop('checked', true)
  } else if ($this.prop('checked', false) && $this.siblings().prop('checked', false)) {
    SRTwelveOne.prop('checked', false);
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="SR-012-01" value="SR-12-01" class="check-12" id="SR01201">
<input type="checkbox" name="SR-012-02" value="SR-12-02" class="check-12">
<input type="checkbox" name="SR-012-03" value="SR-12-03" class="check-12"></code>```

答:
The $this.prop('checked', true) in if ($this.prop('checked', true)) is setting the checkbox to true, not checking if it's true. For that you want to use if ($this.prop('checked')). But I think your issue can be reduced to the following:

$('.check-12:not(#SR01201)').on('change', function() {
  $("#SR01201").prop('checked', $('.check-12:not(#SR01201):checked').length > 0);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="SR-012-01" value="SR-12-01" class="check-12" id="SR01201">
<input type="checkbox" name="SR-012-02" value="SR-12-02" class="check-12">
<input type="checkbox" name="SR-012-03" value="SR-12-03" class="check-12"></code>```

The first line selects your checkboxes with the class you specified, but not the first one. Upon changing any of them, the checkbox with the ID SR01201 changes its checked property depending on how many of the other checkboxes are checked. 1 or more? check it, otherwise uncheck it. The result of $('.check-12:not(#SR01201):checked').length > 0 will be true or false.

Body:
I have more than fifteen checkbox inputs all with the same class, looking something like below:

I want to have only the first input be checked and stay checked when any other input with the same class is checked. If only the first input is checked you should be able to check and uncheck it freely. Only the first one has the ID, #SR01201. The rest only have the class check-12.

Right now, I can freely uncheck and check the first input, and it will get checked if any other inputs with the class check-12 are checked. But once any other input (besides the first one) is checked, it can't be unchecked.

$('.check-12:not(#SR01201)').on('change', function() {
  var $this = $(this);
  var SRTwelveOne = $("#SR01201");
  if ($this.prop('checked', true)) {
    SRTwelveOne.prop('checked', true)
  } else if ($this.prop('checked', false) && $this.siblings().prop('checked', false)) {
    SRTwelveOne.prop('checked', false);
  }
});

<input type="checkbox" name="SR-012-01" value="SR-12-01" class="check-12" id="SR01201">
<input type="checkbox" name="SR-012-02" value="SR-12-02" class="check-12">
<input type="checkbox" name="SR-012-03" value="SR-12-03" class="check-12">

Body:
The $this.prop('checked', true) in if ($this.prop('checked', true)) is setting the checkbox to true, not checking if it's true. For that you want to use if ($this.prop('checked')). But I think your issue can be reduced to the following:

$('.check-12:not(#SR01201)').on('change', function() {
  $("#SR01201").prop('checked', $('.check-12:not(#SR01201):checked').length > 0);
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="SR-012-01" value="SR-12-01" class="check-12" id="SR01201">
<input type="checkbox" name="SR-012-02" value="SR-12-02" class="check-12">
<input type="checkbox" name="SR-012-03" value="SR-12-03" class="check-12">

The first line selects your checkboxes with the class you specified, but not the first one. Upon changing any of them, the checkbox with the ID SR01201 changes its checked property depending on how many of the other checkboxes are checked. 1 or more? check it, otherwise uncheck it. The result of $('.check-12:not(#SR01201):checked').length > 0 will be true or false.


问:
How to extract mesh from a data stream?
For research purposes (not related to CG and I have no prior experience working with meshes), I'm using an open source program (3DWorld) which is part python and part Unity. only the python part is open source and the two are connected thru zmq. documentation says that the python api asks the Unity build to fetch meshes from an amazon server. So I have got this mesh data (lists of two items which are both bytes), but I don't know how to save it as fbx file. I contacted the devs and they responded that it's possible to extract the mesh data and convert it to FBX. Although they said that they haven't written the converter, and they just mentioned that I can do it and didn't mention how. Here I have a pickled list which is supposed to be a "aaa_battery": pickled list link

Please show me how to extract mesh from this list. I will appreciate any help.

答:
Only the first item from your list is probably useful. It has what I suppose to be vertex indices chunk and vertex data chunk. All integers seem to be little endian.

Vertex indices chunk starts with its size at 0x3c and the actual data starting at 0x40. Indices come in triplets of 4-byte integer values.

Vertex data chunk starts with its size at 0x4ed0 and the data starting at 0x4ed4. 12 bytes for each vertex, probably 3 floats for X, Y and Z.

I am not sure if this is some well known format but it looks pretty straightforward, should be easy to write a converter even if you wouldn't be able to figure out what's it called.

Title: How to extract mesh from a data stream?


问:
vercel published sveltekit where vite fails to register serviceworker placed in src folder
This question will need someone from vercel team or sveltekit team as it is related to pwa app that I published to vercel:
1- I placed a minifest1.js file in the "static" folder
2- I placed testserviceworker.js file in the "SRC" folder.

When I run my app locally using my laptop by "npm run build" and "npm run preview", vite registers my serviceworker, my cache is populated and the app is installable as pwa.

When I deploy the same code to vercel, vite fails to register the serviceworker. To experiment I added the serviceworker file to the static folder and added a register button in index.svelte to register the file manully when I press the button.

When I press the button, the serviceworker is registered, I'm able to verify it in dev tools, application tab, cache and able to install my app but my lighthouse report showing pwa part as failed.

So my question is regarding vite registering serviceworker by default upon starting the site. Do I need to add a function in load or onMount with "navigator.serviceWorker.register('testserviceworker.js" or there is some kind of magic configuration in vercel or svelte.config.js to point vite to where the serviceworker.js so it register it upon starting the app?

I added the files for manifest and serviceworker here but I don't think they're relative to my question as it is a configuration issue not code issue:

manifest file:

```<code>{
  "name": "PWATEST",
  "short_name": "PWATESTSHORTNAME",
  "start_url": "/",
  "scope" : "/",
  "background_color": "#1b4079",
  "theme_color": "#d62828",
  "display": "fullscreen",
  "icons": [
    {
      "src": "/512svelte-welcome.png",
      "sizes": "512x512",
      "type": "image/png",
      "purpose" : "any maskable"
    }
  ]
}
</code>```

My testserviceworker.js

```<code>console.log("*****hello from testserviceworker.js inside static folder********")

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open('v3').then((cache) => {
       cache.add(
          './favicon.png'
       );
    })
  );
});

self.addEventListener('activate', function(event) {
   console.log("serviceworker activate fn :", event)
});

self.addEventListener('fetch', function(event) {
 console.log("fetch fn inside serviceworker.js")
})
</code>```

Here is the LINK to vercel app  running with step by step to test this setup in the home page.

Is there any vercel team member or Sveltekit ninja warriors who can guide me to fix this problem? No one is building websites anymore. Installing pwa is the way to go and Sapper used to include a serviceworker and manifest file by default. For some mysterious reason, vite got involved and that ability disappeared and now after deploying, vite is not able to locate the serviceworker to register it as stated in the sveltekit doc:

Doc-serviceworkers
it's often worth using service workers to speed up navigation by precaching your built JS and CSS.

In SvelteKit, if you have a src/service-worker.js file (or src/service-worker.ts, or src/service-worker/index.js, etc) it will be built with Vite and automatically registered.

In conclusion :

1-How to let vite knows about the serviceworker file in specific location like static folder or scoped to a different part of the app?

2-How to fix vite registering the serviceworker if I place the serviceworker.js in src folder?

Hopefully we will get someone from vercel team or sveltekit team to look into this issue. I found this issue and I can disable it but how to register the serviceworker without pressing a button? Put the code in load or onMount?

The published vercel app link is here again for your convenience.

答:
I ended with registeration in the onMount. Now when the app is loaded, the serviceworker is registered and pwa is installable. It passed the lighthouse checks. All green.

Here is the code for onMount:

```<code>import { onMount } from 'svelte';

    onMount(async () => {

        if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('testserviceworker.js', { scope: '/' }).then(function(reg) {
    // registration worked
    console.log('Registration succeeded. Scope is ' + reg.scope);
  }).catch(function(error) {
    // registration failed
    console.log('Registration failed with ' + error);
  });
};

    });
</code>```

To recap:
When you publish to vercel -accordning to the sveltekit docs - vite suppose to register the serviceworker for you.
1- Place your serviceworker.js file in the static folder.
2- Add onMount fn and register the serviceworker there.
3- No need to disable vite auto registeration in the svelte.config.js as
instructed in the docs as I didn't disable it and it didn't cause any
issues.

Hopefully sveltekit 1.0 will be released soon. I'm sure majority of these bugs will be ironed out by then.

Body:
This question will need someone from vercel team or sveltekit team as it is related to pwa app that I published to vercel:
1- I placed a minifest1.js file in the "static" folder
2- I placed testserviceworker.js file in the "SRC" folder.

When I run my app locally using my laptop by "npm run build" and "npm run preview", vite registers my serviceworker, my cache is populated and the app is installable as pwa.

When I deploy the same code to vercel, vite fails to register the serviceworker. To experiment I added the serviceworker file to the static folder and added a register button in index.svelte to register the file manully when I press the button.

When I press the button, the serviceworker is registered, I'm able to verify it in dev tools, application tab, cache and able to install my app but my lighthouse report showing pwa part as failed.

So my question is regarding vite registering serviceworker by default upon starting the site. Do I need to add a function in load or onMount with "navigator.serviceWorker.register('testserviceworker.js" or there is some kind of magic configuration in vercel or svelte.config.js to point vite to where the serviceworker.js so it register it upon starting the app?

I added the files for manifest and serviceworker here but I don't think they're relative to my question as it is a configuration issue not code issue:

manifest file:

{
  "name": "PWATEST",
  "short_name": "PWATESTSHORTNAME",
  "start_url": "/",
  "scope" : "/",
  "background_color": "#1b4079",
  "theme_color": "#d62828",
  "display": "fullscreen",
  "icons": [
    {
      "src": "/512svelte-welcome.png",
      "sizes": "512x512",
      "type": "image/png",
      "purpose" : "any maskable"
    }
  ]
}

My testserviceworker.js

console.log("*****hello from testserviceworker.js inside static folder********")

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open('v3').then((cache) => {
       cache.add(
          './favicon.png'
       );
    })
  );
});

self.addEventListener('activate', function(event) {
   console.log("serviceworker activate fn :", event)
});

self.addEventListener('fetch', function(event) {
 console.log("fetch fn inside serviceworker.js")
})

Here is the LINK to vercel app  running with step by step to test this setup in the home page.

Is there any vercel team member or Sveltekit ninja warriors who can guide me to fix this problem? No one is building websites anymore. Installing pwa is the way to go and Sapper used to include a serviceworker and manifest file by default. For some mysterious reason, vite got involved and that ability disappeared and now after deploying, vite is not able to locate the serviceworker to register it as stated in the sveltekit doc:

Doc-serviceworkers
it's often worth using service workers to speed up navigation by precaching your built JS and CSS.

In SvelteKit, if you have a src/service-worker.js file (or src/service-worker.ts, or src/service-worker/index.js, etc) it will be built with Vite and automatically registered.

In conclusion :

1-How to let vite knows about the serviceworker file in specific location like static folder or scoped to a different part of the app?

2-How to fix vite registering the serviceworker if I place the serviceworker.js in src folder?

Hopefully we will get someone from vercel team or sveltekit team to look into this issue. I found this issue and I can disable it but how to register the serviceworker without pressing a button? Put the code in load or onMount?

The published vercel app link is here again for your convenience.

Body:
I ended with registeration in the onMount. Now when the app is loaded, the serviceworker is registered and pwa is installable. It passed the lighthouse checks. All green.

Here is the code for onMount:

import { onMount } from 'svelte';

    onMount(async () => {

        if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('testserviceworker.js', { scope: '/' }).then(function(reg) {
    // registration worked
    console.log('Registration succeeded. Scope is ' + reg.scope);
  }).catch(function(error) {
    // registration failed
    console.log('Registration failed with ' + error);
  });
};

    });

To recap:
When you publish to vercel -accordning to the sveltekit docs - vite suppose to register the serviceworker for you.
1- Place your serviceworker.js file in the static folder.
2- Add onMount fn and register the serviceworker there.
3- No need to disable vite auto registeration in the svelte.config.js as
instructed in the docs as I didn't disable it and it didn't cause any
issues.

Hopefully sveltekit 1.0 will be released soon. I'm sure majority of these bugs will be ironed out by then.


问:
jquery - traverse up tree and find elements with specified class
I thought that the closest() function would do this for me, but seemingly not. I have the following markup and I want to add a class to all parent anchors with the class trigger:

```<code>    <ul>
    <li class="selected">
      <a class="trigger" href=""></a>
      <a href=""></a>
      <ul>
        <li class="selected">
          <a class="trigger" href=""></a>
          <a href="" id = "my_target"></a>
        </li>
      </ul>
    </li>
  </ul>
</code>```

I want to select my target - in this example, the deepest anchor, then add a class to each a.trigger in its ascendants. What would be the best way to do this? Thanks.

答:
parents Is used for traversing up.

I believe this should work:

```<code>$('#my_target').parents('.trigger').addClass('myclass');
</code>```

However for siblings you'll need to use siblings instead of parents
For example the anchor tag that is with the #my_target anchor is considered a sibling.

Body:
I thought that the closest() function would do this for me, but seemingly not. I have the following markup and I want to add a class to all parent anchors with the class trigger:

I want to select my target - in this example, the deepest anchor, then add a class to each a.trigger in its ascendants. What would be the best way to do this? Thanks.

Body:
parents Is used for traversing up.

I believe this should work:

$('#my_target').parents('.trigger').addClass('myclass');

However for siblings you'll need to use siblings instead of parents
For example the anchor tag that is with the #my_target anchor is considered a sibling.


问:
Splash screen is woking on debug apk and is showing blank page on Release apk in flutter
I'm working on a flutter mobile application, while testing the mobile application on the Debug APK it shows the Splash screen perfectly when I created a Release APK the splash screen was not working perfectly. Here I'm showing the codes of the Splash screen.

```<code>import 'package:calculator_vault/globals.dart' as globals;
import 'package:calculator_vault/views/category.dart';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';

class LoadingPage extends StatefulWidget {
  const LoadingPage({Key? key}) : super(key: key);

  @override
  _LoadingPageState createState() => _LoadingPageState();
}

class _LoadingPageState extends State<LoadingPage> {
  double value = 0;
  void downloadData() {
    new Timer.periodic(Duration(milliseconds: 50), (Timer timer) {
      if (globals.loadNow) {
        print('loading now');
        setState(() {
          if (value >= 1) {
            timer.cancel();

            Navigator.pushReplacement(
                context, MaterialPageRoute(builder: (context) => MainPage()));
          } else {
            value = value + 0.015;

          }
        });
      }
    });
  }

  @override
  void initState() {
    super.initState();
    downloadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(18.0),
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [
            Positioned(
                bottom: MediaQuery.of(context).size.height / 22,
                child: Container(
                    height: 70,
                    width: 70,
                    child: Lottie.asset('assets/animations/loader.json'))
                    ),
            Positioned(
              bottom: 0,
              child: Text(
                'Version 2.7.3',
                style: TextStyle(fontSize: 10),
                textAlign: TextAlign.center,
              ),
            ),
            Center(
              child: Padding(
                padding: const EdgeInsets.only(bottom: 10.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Positioned(
                      child: Container(
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20),
                              border: Border.all(
                                  width: 1.0, color: Color(0xffE8E3E3))),
                          width: 90,
                          height: 90,
                          child: ClipRRect(
                              borderRadius: BorderRadius.circular(20.0),
                              child: Image.asset(
                                  'assets/app_icons/app_icon_0.png'))),
                    ),
                    SizedBox(
                      height: 25,
                    ),
                    Positioned(
                      bottom: MediaQuery.of(context).size.height / 2.9,
                      child: Text(
                        'Calculator Lock',
                        style: TextStyle(fontSize: 25),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

I've no clue why is it happening, please let me know.

"HERE IS MY FLUTTER LOGS"

```<code>W/FlutterActivityAndFragmentDelegate( 9172): A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration steps.
I/flutter ( 9172): Observatory listening on http://127.0.0.1:44415/EJIiR5NchMU=/
I/flutter ( 9172): Ad IDS: /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_BANNER_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_BANNER_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_BANNER_AD ca-app-pub-5709217593772841/6100863205 ca-app-pub-5709217593772841/6100863205 /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD
I/flutter ( 9172): AppOpenAd failed to load: LoadAdError(code: 3, domain: com.google.android.gms.ads, message: No ad config., responseInfo: ResponseInfo(responseId: null, mediationAdapterClassName: , adapterResponses: []))
I/flutter ( 9172): Result : InterstitialAdResult.ERROR {error_message: No fill. We are not able to serve ads to this person. Please refer to https://developers.facebook.com/docs/audience-network/faq#a12. If you are integrating Audience Network for the first time, you can use test ads https://developers.facebook.com/docs/audience-network/testing., error_code: 1001, invalidated: true, placement_id: 3752483214787237_3752491351453090}
I/flutter ( 9172): 1 /storage/emulated/0/.CalculatorVault/hideFiles
I/flutter ( 9172): true
I/flutter ( 9172): ad is loaded
I/flutter ( 9172): Title Text :
</code>```

答: You might have better luck using https://pub.dev/packages/flutter_native_splash. With your current implementation, there will be a white screen shown before your splash screen loads. Using a native splash avoids this white screen and may solve your release problem, too.  Full disclosure: I maintain this package.</p>

Body:
I'm working on a flutter mobile application, while testing the mobile application on the Debug APK it shows the Splash screen perfectly when I created a Release APK the splash screen was not working perfectly. Here I'm showing the codes of the Splash screen.

import 'package:calculator_vault/globals.dart' as globals;
import 'package:calculator_vault/views/category.dart';
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';

class LoadingPage extends StatefulWidget {
  const LoadingPage({Key? key}) : super(key: key);

  @override
  _LoadingPageState createState() => _LoadingPageState();
}

class _LoadingPageState extends State<LoadingPage> {
  double value = 0;
  void downloadData() {
    new Timer.periodic(Duration(milliseconds: 50), (Timer timer) {
      if (globals.loadNow) {
        print('loading now');
        setState(() {
          if (value >= 1) {
            timer.cancel();

            Navigator.pushReplacement(
                context, MaterialPageRoute(builder: (context) => MainPage()));
          } else {
            value = value + 0.015;

          }
        });
      }
    });
  }

  @override
  void initState() {
    super.initState();
    downloadData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(18.0),
        child: Stack(
          alignment: AlignmentDirectional.center,
          children: [
            Positioned(
                bottom: MediaQuery.of(context).size.height / 22,
                child: Container(
                    height: 70,
                    width: 70,
                    child: Lottie.asset('assets/animations/loader.json'))
                    ),
            Positioned(
              bottom: 0,
              child: Text(
                'Version 2.7.3',
                style: TextStyle(fontSize: 10),
                textAlign: TextAlign.center,
              ),
            ),
            Center(
              child: Padding(
                padding: const EdgeInsets.only(bottom: 10.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Positioned(
                      child: Container(
                          decoration: BoxDecoration(
                              borderRadius: BorderRadius.circular(20),
                              border: Border.all(
                                  width: 1.0, color: Color(0xffE8E3E3))),
                          width: 90,
                          height: 90,
                          child: ClipRRect(
                              borderRadius: BorderRadius.circular(20.0),
                              child: Image.asset(
                                  'assets/app_icons/app_icon_0.png'))),
                    ),
                    SizedBox(
                      height: 25,
                    ),
                    Positioned(
                      bottom: MediaQuery.of(context).size.height / 2.9,
                      child: Text(
                        'Calculator Lock',
                        style: TextStyle(fontSize: 25),
                        textAlign: TextAlign.center,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

I've no clue why is it happening, please let me know.

"HERE IS MY FLUTTER LOGS"

W/FlutterActivityAndFragmentDelegate( 9172): A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration steps.
I/flutter ( 9172): Observatory listening on http://127.0.0.1:44415/EJIiR5NchMU=/
I/flutter ( 9172): Ad IDS: /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_BANNER_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_BANNER_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_BANNER_AD ca-app-pub-5709217593772841/6100863205 ca-app-pub-5709217593772841/6100863205 /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD /21952429235,22639636745/TTS_CALCULATORLOCKCALCULATOR_NATIVE_AD
I/flutter ( 9172): AppOpenAd failed to load: LoadAdError(code: 3, domain: com.google.android.gms.ads, message: No ad config., responseInfo: ResponseInfo(responseId: null, mediationAdapterClassName: , adapterResponses: []))
I/flutter ( 9172): Result : InterstitialAdResult.ERROR {error_message: No fill. We are not able to serve ads to this person. Please refer to https://developers.facebook.com/docs/audience-network/faq#a12. If you are integrating Audience Network for the first time, you can use test ads https://developers.facebook.com/docs/audience-network/testing., error_code: 1001, invalidated: true, placement_id: 3752483214787237_3752491351453090}
I/flutter ( 9172): 1 /storage/emulated/0/.CalculatorVault/hideFiles
I/flutter ( 9172): true
I/flutter ( 9172): ad is loaded
I/flutter ( 9172): Title Text :


问:
How long does Microsoft Office Graph API refresh token lives?
We've configured an AAD multi-tenant app and we are aquiring tokens from following endpoint: https://login.microsoftonline.com/common/oauth2/v2.0/token using the code we've got from user authorisation.

Endpoint provides no information about the refresh token lifetime.

This document states it should always have a default value of 90 days: https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-configurable-token-lifetimes#refresh-and-session-token-lifetime-policy-properties

Is it always 90 days, can we be sure it'll live that long or it still depends on the user's organization configuration?

答: Yes, per the document unless you specify otherwise via conditional access the token lifetime is 90 days.</p>


问:
How to loop within a loop in Python?
I need to count how many times two groups of strings appear in a sentence. Yet, whenever a negation precedes the string in group A, I want the count to be added to group B.

To do so, I wrote a code which works fine. Let me start by showing you the dataframe and the group of strings:

```<code># Dataframe
df = pd.DataFrame({'X': ['Ciao, I would like to count the number of occurrences in this text considering negations that can change the meaning of the sentence',
                    "Hello, not number of negations, in this case we need to take care of the negation.",
                    "Hello world, don't number is another case in which where we need to consider negations."]})

# Group of words to look into text
a = pd.DataFrame(['number','ciao','text','care'], columns = ['A'])
d = pd.DataFrame(['need'], columns = ['D'])

</code>```

This is then the code that does the job:

res0 = []
res1 = []

for i in range(len(df)):

    if df['X'][i].find('not') < df['X'][i].find('number') and df['X'][i].find('not') > 0 and abs(
            df['X'][i].find('not') - df['X'][i].find('number')) < 15:
        pattern0 = '|'.join(a[a.A != 'number'].A)
        text = df['X'][i]
        count0 = len(re.findall(pattern0, text))
        res0.append(count0)

        pattern1 = '|'.join(d.append({'D': 'number'}, ignore_index=True).D)
        count1 = len(re.findall(pattern1, text))
        res1.append(count1)

    else:
        pattern2 = '|'.join(a.A)
        text = df['X'][i]
        count2 = len(re.findall(pattern2, text))
        res0.append(count2)

        pattern3 = '|'.join(d.D)
        count3 = len(re.findall(pattern3, text))
        res1.append(count3)

pd.Series(res0)  # [2,1,1]
pd.Series(res1)  # [0,2,1]
```
<p>What is the issue then? The problem is that I consider <em>only</em> one negation ('not') and only one word in <code>a</code> ('number'). What I would like to do is to extend the code to loop over every negation <code>neg</code> (see below) and over every element of <code>a</code>. However, when I try to do that, I get wrong results. Find my attempt below:</p>
```neg = ['not','dont',"wasnt"]

res0=[]
res1=[]

for i in range(len(df)):
    for j in range(len(neg)):
        for k in range(len(a)):
            if df['X'][i].find(neg[j]) < df['X'][i].find(a.A[k]) and df['X'][i].find(neg[j]) > 0 and abs(df['X'][i].find(neg[j]) - df['X'][i].find(a.A[k])) < 15:
                pattern0 = '|'.join(a[a.A != a.A[k]].A)
                text = df['X'][i]
                count0 = len(re.findall(pattern0, text))
                res0.append(count0)

                pattern1 = '|'.join(d.append({'D': a.A[k]}, ignore_index = True).D)
                count1 = len(re.findall(pattern1, text))
                res1.append(count1)

            else:
                pattern2 = '|'.join(a.A)
                text = df['X'][i]
                count2 = len(re.findall(pattern2, text))
                res0.append(count2)

                pattern3 = '|'.join(d.D)
                count3 = len(re.findall(pattern3, text))
                res1.append(count3)

pd.Series(res0)    # non sense
pd.Series(res1)    # non sense

# results should remain a 3x1 vector

```

What am I doing wrong?

Thanks for your help!

答:
You can check negation with a positive look behind:

```<code>pattern = r"(?:(?<=not)|(?<=don't)|(?<=wasn't))\s+(?:number|other|words)"

df['neg_count'] = df['X'].str.findall(pattern).str.len()
print(df)

# Output
                                                   X  neg_count
0  Ciao, I would like to count the number of occu...          0
1  Hello, not number of negations, in this case w...          1
2  Hello world, don't number is another case in w...          1
</code>```

Regex101

Title: How to loop within a loop in Python?

Body:
I need to count how many times two groups of strings appear in a sentence. Yet, whenever a negation precedes the string in group A, I want the count to be added to group B.

To do so, I wrote a code which works fine. Let me start by showing you the dataframe and the group of strings:

# Dataframe
df = pd.DataFrame({'X': ['Ciao, I would like to count the number of occurrences in this text considering negations that can change the meaning of the sentence',
                    "Hello, not number of negations, in this case we need to take care of the negation.",
                    "Hello world, don't number is another case in which where we need to consider negations."]})

# Group of words to look into text
a = pd.DataFrame(['number','ciao','text','care'], columns = ['A'])
d = pd.DataFrame(['need'], columns = ['D'])

This is then the code that does the job:

res0 = []
res1 = []

for i in range(len(df)):

    if df['X'][i].find('not') < df['X'][i].find('number') and df['X'][i].find('not') > 0 and abs(
            df['X'][i].find('not') - df['X'][i].find('number')) < 15:
        pattern0 = '|'.join(a[a.A != 'number'].A)
        text = df['X'][i]
        count0 = len(re.findall(pattern0, text))
        res0.append(count0)

        pattern1 = '|'.join(d.append({'D': 'number'}, ignore_index=True).D)
        count1 = len(re.findall(pattern1, text))
        res1.append(count1)

    else:
        pattern2 = '|'.join(a.A)
        text = df['X'][i]
        count2 = len(re.findall(pattern2, text))
        res0.append(count2)

        pattern3 = '|'.join(d.D)
        count3 = len(re.findall(pattern3, text))
        res1.append(count3)

pd.Series(res0)  # [2,1,1]
pd.Series(res1)  # [0,2,1]

What is the issue then? The problem is that I consider only one negation ('not') and only one word in a ('number'). What I would like to do is to extend the code to loop over every negation neg (see below) and over every element of a. However, when I try to do that, I get wrong results. Find my attempt below:

neg = ['not','dont',"wasnt"]

res0=[]
res1=[]

for i in range(len(df)):
    for j in range(len(neg)):
        for k in range(len(a)):
            if df['X'][i].find(neg[j]) < df['X'][i].find(a.A[k]) and df['X'][i].find(neg[j]) > 0 and abs(df['X'][i].find(neg[j]) - df['X'][i].find(a.A[k])) < 15:
                pattern0 = '|'.join(a[a.A != a.A[k]].A)
                text = df['X'][i]
                count0 = len(re.findall(pattern0, text))
                res0.append(count0)

                pattern1 = '|'.join(d.append({'D': a.A[k]}, ignore_index = True).D)
                count1 = len(re.findall(pattern1, text))
                res1.append(count1)

            else:
                pattern2 = '|'.join(a.A)
                text = df['X'][i]
                count2 = len(re.findall(pattern2, text))
                res0.append(count2)

                pattern3 = '|'.join(d.D)
                count3 = len(re.findall(pattern3, text))
                res1.append(count3)

pd.Series(res0)    # non sense
pd.Series(res1)    # non sense

# results should remain a 3x1 vector

What am I doing wrong?

Thanks for your help!

Body:
You can check negation with a positive look behind:

pattern = r"(?:(?<=not)|(?<=don't)|(?<=wasn't))\s+(?:number|other|words)"

df['neg_count'] = df['X'].str.findall(pattern).str.len()
print(df)

# Output
                                                   X  neg_count
0  Ciao, I would like to count the number of occu...          0
1  Hello, not number of negations, in this case w...          1
2  Hello world, don't number is another case in w...          1

Regex101


问:
rock paper scissors lizrd spock game issue?
When I run my program my inputs do not print at all so I cannot enter my choice for the game.(Python)
There are no syntax error or anything from what I can see but I still cannot input which moves I want to enter.
I have defined player1 and player2 and have issued the correct parameters but nothing seems to be printing or being able to be input</p>
```<code>while 1 == 1:
    print("\n1.ROCK 2.PAPER 3.SCISSORS 4.LIZARD 5.SPOCK 6.EXIT")
    player1 = int(input("\nEnter Player1's move (1-6): "))
    if player1 == 6:
        print("Player1 has left the game")
        break
    player2 = int(input("Enter Player2's move (1-6)"))
    if player2 == 6:
        print("Player2 has left the game")
        break
        move = ("ROCK", "PAPER", "SCISSORS", "LIZARD", "SPOCK")
        victor = winner(player1, player2)
        if victor == 1:
            print(move[player1-1], "beats ", move[player2-1], ": PLAYER1 WON")
        elif victor == 2:
            print(move[player2-1], "beats", move[player1-1], ": PLAYER2 WON")
        else:
            print("Same moves! :", move[player1-1], "and ", move[player2-1])
            break
</code>```

答:
Currently, a part of your code is after the break for player 2, which means it doesn't run.

Remove one indent for this section:

```<code>        move = ("ROCK", "PAPER", "SCISSORS", "LIZARD", "SPOCK")
        victor = winner(player1, player2)
        if victor == 1:
            print(move[player1-1], "beats ", move[player2-1], ": PLAYER1 WON")
        elif victor == 2:
            print(move[player2-1], "beats", move[player1-1], ": PLAYER2 WON")
        else:
            print("Same moves! :", move[player1-1], "and ", move[player2-1])
            break
</code>```

Body:
When I run my program my inputs do not print at all so I cannot enter my choice for the game.(Python)
There are no syntax error or anything from what I can see but I still cannot input which moves I want to enter.
I have defined player1 and player2 and have issued the correct parameters but nothing seems to be printing or being able to be input

while 1 == 1:
    print("\n1.ROCK 2.PAPER 3.SCISSORS 4.LIZARD 5.SPOCK 6.EXIT")
    player1 = int(input("\nEnter Player1's move (1-6): "))
    if player1 == 6:
        print("Player1 has left the game")
        break
    player2 = int(input("Enter Player2's move (1-6)"))
    if player2 == 6:
        print("Player2 has left the game")
        break
        move = ("ROCK", "PAPER", "SCISSORS", "LIZARD", "SPOCK")
        victor = winner(player1, player2)
        if victor == 1:
            print(move[player1-1], "beats ", move[player2-1], ": PLAYER1 WON")
        elif victor == 2:
            print(move[player2-1], "beats", move[player1-1], ": PLAYER2 WON")
        else:
            print("Same moves! :", move[player1-1], "and ", move[player2-1])
            break

Body:
Currently, a part of your code is after the break for player 2, which means it doesn't run.

Remove one indent for this section:

        move = ("ROCK", "PAPER", "SCISSORS", "LIZARD", "SPOCK")
        victor = winner(player1, player2)
        if victor == 1:
            print(move[player1-1], "beats ", move[player2-1], ": PLAYER1 WON")
        elif victor == 2:
            print(move[player2-1], "beats", move[player1-1], ": PLAYER2 WON")
        else:
            print("Same moves! :", move[player1-1], "and ", move[player2-1])
            break


问:
How to filter inherited Doctrine objects?
Each Product is "owned" by a given Tenant (i.e. user) and requires a color which could be either a standard Color available to all tenants or a proprietary TenantOwnedColor which was created by a given tenant and only available to that tenant.

#[ORM\Entity]
class Product implements BelongsToTenantInterface
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private int $id;

    #[ORM\Column(type: 'string', length: 180)]
    private string $name;

    #[ORM\ManyToOne(targetEntity: Color::class)]
    #[ORM\JoinColumn(nullable: false)]
    private ?Color $color;

    #[ORM\ManyToOne(targetEntity: Tenant::class)]
    #[ORM\JoinColumn(nullable: false)]
    private ?Tenant $tenant;
}
```
<pre class="lang-php prettyprint-override"><code>#[ORM\Entity]
#[ORM\InheritanceType(value: 'JOINED')]
#[ORM\DiscriminatorColumn(name: 'type', type: 'string')]
#[ORM\DiscriminatorMap(value: ['open' => Color::class, 'proprietary' => TenantOwnedColor::class])]
class Color
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private int $id;

    #[ORM\Column(type: 'string', length: 180)]
    private string $name;

    #[ORM\Column(type: 'string', length: 255)]
    private string $colorCode;
}
</code>```

#[ORM\Entity]
class TenantOwnedColor extends Color implements BelongsToTenantInterface
{
    #[ORM\ManyToOne(targetEntity: Tenant::class)]
    #[ORM\JoinColumn(nullable: false)]
    private ?Tenant $tenant;
}
```
<p>In order to filter all entities that implement <code>BelongsToTenantInterface</code> and limit them to the <code>Tenant</code> that the logged on user belongs to, a listener adds a doctrine filter.</p>
<pre class="lang-php prettyprint-override"><code>namespace App\EventListener;

use Doctrine\ORM\EntityManager;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTAuthenticatedEvent;
use App\Entity\MultiTenenacy\BelongsToTenantInterface;

final class AuthenticatedTenantEntityListener
{
    public function __construct(private EntityManager $entityManager)
    {
    }

    public function onJWTAuthenticated(JWTAuthenticatedEvent $jwtAuthenticatedEvent): void
    {
        $user = $jwtAuthenticatedEvent->getToken()->getUser();
        if (!$user instanceof BelongsToTenantInterface) {
            return;
        }

        $this->entityManager
        ->getFilters()
        ->enable('tenant_filter')
        ->setParameter('tenantId', $user->getTenant()->getId());
    }
}
</code>```

namespace App\Doctrine;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query\Filter\SQLFilter;
use App\Entity\MultiTenenacy\BelongsToTenantInterface;

final class TenantFilter extends SQLFilter
{
    public function addFilterConstraint(ClassMetadata $classMetadata, $targetTableAlias): string
    {
        if ($classMetadata->getReflectionClass()->implementsInterface(BelongsToTenantInterface::class)) {
            return sprintf('%s.tenant_id = %s', $targetTableAlias, $this->getParameter('tenantId'));
        }
        return '';
    }
}
```

My approach works for Product but not for TenantOwnedColor. When troubleshooting, I discovered that TenantFilter::addFilterConstraint() is being passed the parent class (i.e. Color) metadata which doesn't implement BelongsToTenantInterface and thus I now know why it isn't filtering.

I also found the following in Doctrine's documentation so evidently it is by design:

In the case of joined or single table inheritance, you always get
passed the ClassMetadata of the inheritance root. This is necessary to
avoid edge cases that would break the SQL when applying the filters.

Are there other ways to implement this in order to overcome this shortcoming?

答:
It seems that this topic has been brought up by the community some times now. There does not seem to be an official workaround, due to innestability provoked by those famous edge cases, although some people have made their changes/hacks/workarounds to the problem so it is not impossible.

Links that might help, with some workarounds mentioned in them, I hope you find them useful enough, sorry that I cannot be of more help:

https://github.com/doctrine/orm/issues/7504#issuecomment-568569307

https://github.com/doctrine/orm/issues/6329

https://github.com/doctrine/orm/issues/6329#issuecomment-538854316

https://www.doctrine-project.org/projects/doctrine-orm/en/2.11/reference/php-mapping.html#classmetadata-api

Body:
Each Product is "owned" by a given Tenant (i.e. user) and requires a color which could be either a standard Color available to all tenants or a proprietary TenantOwnedColor which was created by a given tenant and only available to that tenant.

#[ORM\Entity]
class Product implements BelongsToTenantInterface
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private int $id;

    #[ORM\Column(type: 'string', length: 180)]
    private string $name;

    #[ORM\ManyToOne(targetEntity: Color::class)]
    #[ORM\JoinColumn(nullable: false)]
    private ?Color $color;

    #[ORM\ManyToOne(targetEntity: Tenant::class)]
    #[ORM\JoinColumn(nullable: false)]
    private ?Tenant $tenant;
}

#[ORM\Entity]
#[ORM\InheritanceType(value: 'JOINED')]
#[ORM\DiscriminatorColumn(name: 'type', type: 'string')]
#[ORM\DiscriminatorMap(value: ['open' => Color::class, 'proprietary' => TenantOwnedColor::class])]
class Color
{
    #[ORM\Id]
    #[ORM\GeneratedValue]
    #[ORM\Column(type: 'integer')]
    private int $id;

    #[ORM\Column(type: 'string', length: 180)]
    private string $name;

    #[ORM\Column(type: 'string', length: 255)]
    private string $colorCode;
}

#[ORM\Entity]
class TenantOwnedColor extends Color implements BelongsToTenantInterface
{
    #[ORM\ManyToOne(targetEntity: Tenant::class)]
    #[ORM\JoinColumn(nullable: false)]
    private ?Tenant $tenant;
}

In order to filter all entities that implement BelongsToTenantInterface and limit them to the Tenant that the logged on user belongs to, a listener adds a doctrine filter.

namespace App\EventListener;

use Doctrine\ORM\EntityManager;
use Lexik\Bundle\JWTAuthenticationBundle\Event\JWTAuthenticatedEvent;
use App\Entity\MultiTenenacy\BelongsToTenantInterface;

final class AuthenticatedTenantEntityListener
{
    public function __construct(private EntityManager $entityManager)
    {
    }

    public function onJWTAuthenticated(JWTAuthenticatedEvent $jwtAuthenticatedEvent): void
    {
        $user = $jwtAuthenticatedEvent->getToken()->getUser();
        if (!$user instanceof BelongsToTenantInterface) {
            return;
        }

        $this->entityManager
        ->getFilters()
        ->enable('tenant_filter')
        ->setParameter('tenantId', $user->getTenant()->getId());
    }
}

namespace App\Doctrine;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query\Filter\SQLFilter;
use App\Entity\MultiTenenacy\BelongsToTenantInterface;

final class TenantFilter extends SQLFilter
{
    public function addFilterConstraint(ClassMetadata $classMetadata, $targetTableAlias): string
    {
        if ($classMetadata->getReflectionClass()->implementsInterface(BelongsToTenantInterface::class)) {
            return sprintf('%s.tenant_id = %s', $targetTableAlias, $this->getParameter('tenantId'));
        }
        return '';
    }
}

My approach works for Product but not for TenantOwnedColor. When troubleshooting, I discovered that TenantFilter::addFilterConstraint() is being passed the parent class (i.e. Color) metadata which doesn't implement BelongsToTenantInterface and thus I now know why it isn't filtering.

I also found the following in Doctrine's documentation so evidently it is by design:

In the case of joined or single table inheritance, you always get
passed the ClassMetadata of the inheritance root. This is necessary to
avoid edge cases that would break the SQL when applying the filters.

Are there other ways to implement this in order to overcome this shortcoming?


问:
Stop music from in flash from javascript event
I am attempting to stop the music inside of my flash swf that I have loaded in the page

```<code><object id="FlashControl1" type="application/x-shockwave-flash"
data="Flash/Preloader%20-%20Splash.swf" width="980px" height="316px">
<param name="movie" value="Flash/Preloader%20-%20Splash.swf" />
<param name="wmode" value="Transparent" />
<param name="quality" value="High" />
<param name="play" value="True" />
<param name="loop" value="False" />
<param name="menu" value="False" />
<param name="scale" value="Exactfit" />
<param name="flashvars" value="name="FlashControl1"" />
<img src="Images/Banner/Main_Banner.jpg" alt="" width="980px" height="316px" />
</object>
</code>```

I have a button that loads a modal popup with a silverlight video and I would like the audio to stop by execuding the SoundMixer.stop(); command.

I have yet to find a solution on google

答:
```<code>function test() {
movie = document.getElementById('FlashControl1');
movie.stopSound();}
</code>```

this worked :)

OwnerDisplayName: Mitchell

ContentLicense: CC BY-SA 2.5

Body:
I am attempting to stop the music inside of my flash swf that I have loaded in the page

<object id="FlashControl1" type="application/x-shockwave-flash"
data="Flash/Preloader%20-%20Splash.swf" width="980px" height="316px">
<param name="movie" value="Flash/Preloader%20-%20Splash.swf" />
<param name="wmode" value="Transparent" />
<param name="quality" value="High" />
<param name="play" value="True" />
<param name="loop" value="False" />
<param name="menu" value="False" />
<param name="scale" value="Exactfit" />
<param name="flashvars" value="name="FlashControl1"" />

</object>

I have a button that loads a modal popup with a silverlight video and I would like the audio to stop by execuding the SoundMixer.stop(); command.

I have yet to find a solution on google

Body:
function test() {
movie = document.getElementById('FlashControl1');
movie.stopSound();}

this worked :)


问:
grep matches exact string or with wildcard
I want to search the content of a file that could contain for example:

```<code>name1
name2
name3
...
...
name10
name11
...
...
</code>```

the search should match the string if it doesn't have a wildcard (*). for example :

```<code>grep -w name1 filename
</code>```

it returns exactly what I want:

```<code>file1   #ignores file10 & file11 as no wildcard used
</code>```

but when I use the same command but with wildcard (*), as follows:

```<code>grep -w name1* filename
</code>```

it also returns file1 only. without file10 and file11. How can I match the string exactly as the first case and when a (*) is used it should include the others?

Note: I have seen some answers suggested using .* instead of * it
worked but for my application the input is coming always in the form
of * not .*

thank you in advance.

答:
grep uses regex for pattern matching. grep -w 'name1*' would make it match zero or more 1s, so name1 and name11 would match.

If it only matches name1 for you it's because you have a file named name1 in the directory and the unquoted name1* will be interpreted by the shell (globbing). Always use quotes around your arguments that contain special characters. If you use a variable, always put " around it.

To make it match any name starting with name1, make it

```<code>grep -w 'name1.*' filename
</code>```

. means "any character"

.* means "any character, zero or more times".

If the input comes from some external source where * is used as a wildcard, you need to change that string before calling grep.

Example:

search_str='name1*'
new_search_str="$(sed 's/\*/.*/g' <<< "$search_str")"
grep -w "$new_search_str" filename
```

Body:
I want to search the content of a file that could contain for example:

name1
name2
name3
...
...
name10
name11
...
...

the search should match the string if it doesn't have a wildcard (*). for example :

grep -w name1 filename

it returns exactly what I want:

file1   #ignores file10 & file11 as no wildcard used

but when I use the same command but with wildcard (*), as follows:

grep -w name1* filename

it also returns file1 only. without file10 and file11. How can I match the string exactly as the first case and when a (*) is used it should include the others?

Note: I have seen some answers suggested using .* instead of * it
worked but for my application the input is coming always in the form
of * not .*

thank you in advance.

Body:
grep uses regex for pattern matching. grep -w 'name1*' would make it match zero or more 1s, so name1 and name11 would match.

If it only matches name1 for you it's because you have a file named name1 in the directory and the unquoted name1* will be interpreted by the shell (globbing). Always use quotes around your arguments that contain special characters. If you use a variable, always put " around it.

To make it match any name starting with name1, make it

grep -w 'name1.*' filename

. means "any character"

.* means "any character, zero or more times".

If the input comes from some external source where * is used as a wildcard, you need to change that string before calling grep.

Example:

search_str='name1*'
new_search_str="$(sed 's/\*/.*/g' <<< "$search_str")"
grep -w "$new_search_str" filename


问:
How to filter a list of words as likely candidates for a secret word, given that I know certain letters
So I've been really struggling with this problem. First of all let's lay-out the basic rules that this Python program must follow:

Lingo is a popular word-guessing game show on television. The number
of letters of a target word to be guessed is given, and often also the
first letter. Players then make guesses subject to these restrictions
(number of letters and possibly also first letter), and the game tells
them which letters are correct and in the correct place, marked by a
red square (X), and which letters are correct but not in the correct
place, marked by a yellow circle (O). We do not use superfluous yellow
circles, i.e. a letter is marked correct at most as often as it
appears in the target word. If not all occurrences of the same letter
can get a yellow circle this way, priority is given from left to right
(but of course red squares have priority over yellow circles).

First I needed to create a function compare that compares a guessed word with a target word. The two inputs are string of the same length that entirely consist of lowercase ASCII letters. The output is a string of the same length consisting of the symbols X, O and -, where X represent a red square, O represents a yellow circle and - represents nothing.

Examples:

compare("health", "teethe") must return "OX--O-",

compare("rhythm", "teethe") must return "---XX-",

compare("mutate", "teethe") must return "--O-OX",

compare("teethe", "mutate") must return "O--O-X",

Now I've already successfully solved this part, but the next part is where I am stuck.

A function filter_targets(targets, guess_results) must be implemented.

This function must satisfy the following:

● targets is a list (or any other iterable) of possible target words; all words in targets must be of the same length.

● guess_results is a dictionary. Its keys are guessed words (which need not be in the target list) whose associated values are their compare results with a possible target.

● It must return a list of target words in targets that actually do satisfy all
the comparisons appearing in guess_results .

Examples:

Suppose targets contains all English 6-letter words obtained using the aforementioned word list and load function. Let guess_results contain the results of the first two guesses in the example given:

guess_results = {"health": "OX--O-", "rhythm": "---XX-"}

Then based on these results, we can see which words are still possible:

filter_targets(targets, guess_results) will return the following list:

["depths", "peitho", "seethe", "teethe", "tenths"]

Now my current program looks like this, it is very dirty code in my opinion and I would really love to see some implementations that are right. This code also still doesn't do what I want it to.

My reasoning was that if I convert the word or words in guess_results (it must also be able to take a single input, as my code hereunder is taking with the mem_list function) to the "XO-" format, then store all permutations of this format in a list, I can convert the words in wordlist to the format too. I would then check for every permutation in the list if it matches the "XO-" format of any word in the wordlist I am looping through, then store all matches in a separate list. I would then return that list as an answer.

I thought I was getting very close with this logic, but I now can't seem to permutate in a way the leaves some characters in place. And my current implementation would only work for a single word input.

```<code>from itertools import permutations

def load_words(file):
    result = set()
    with open(file) as f:
      for line in f.readlines():
        word = line.strip().lower()
        if word.isalpha() and word.isascii():
          result.add(word)
    return sorted(result)

english_words = load_words("words.txt")
dutch_words = load_words("wordlist.txt")

english_10 = [word for word in dutch_words if len(word) == 10]

    def filter_targets(targets, guess_results):
        mem_list = ["-" for x in range(len("kasgelden"))]
        perm_list = mem_list

    # Checking X
    for guess in guess_results.keys():
        for idx in range(len(guess)):
            if guess_results[guess][idx] == 'X':
                mem_list[idx] = guess[idx]

    o_list = []

    # Checking O
    for guess in guess_results.keys():
        for idx in range(len(guess)):
            if guess_results[guess][idx] == 'O':
                mem_var = guess[idx]
                o_list.append(mem_var)

    add_list = mem_list

    o_min = 0
    o_max = len(o_list)
    y = 0

    # Adding the "O"
    for element in add_list:
        if element == "-" and o_min < o_max:
            add_list[y] = o_list[o_min]
            o_min += 1
            y += 1
        else:
            y += 1

    check_list = list(permutations(add_list))

guess_results = {"kasgelden": "--O--OOX-"}
d6 = [word for word in dutch_words if len(word) == 9]

filter_targets(d6, guess_results)
</code>```

In this single world example: filter_targets(dw9, {"kasgelden": "--O--OOX-"}) should return ["doorspoel", "doublures", "hoofdstel", "moordspel",
"schildjes", "slurfdier", "thuisduel", "woordspel"] . With dw9 being all the words with a length of 9.

This problem is driving me completely crazy and has consumed three days of free time already, I hope someone can nudge me in the right direction here!

English wordlist I am using: https://raw.githubusercontent.com/dwyl/english-words/master/words.txt

Dutch wordlist I am using: https://raw.githubusercontent.com/OpenTaal/opentaal-wordlist/master/wordlist.txt

答:
The guess results tell you two types of things:

For each position, is the guessed letter required or excluded.

For each guessed letter, does it appear in the correct answer.

You can track the first thing by maintaining a regex.
You can track the second thing with two strings, one containing needed characters, one containing forbidden ones.

You can build those as follows:

```<code>regex = ["[^^]"]*wordlen
required = restricted = ''
for guess,result in guess_results:
    needs = never = ''
    for i,score in enumerate(result):
        letter = guess[i]
        if score == 'X':
            regex[i]=letter
            needs += letter
        elif score == 'O':
            regex[i] = regex[i].replace(']',letter+']')
            needs += letter
        else:
            regex[i] = regex[i].replace(']',letter+']')
            never += letter
        # don't reject a '-' found on doubled letter if one was needed.
        restricted += ''.join(c for c in never if c not in needs)
        # track the correct number of required letters.
        required = ''.join([c*max(required.count(c),needs.count(c)) for c in set(required)] +
                   [c for c in needs if c not in required])
</code>```

Then filtering the wordlist becomes

```<code>valid = [w for w in wordlist if (
    re.match(''.join(regex), w) and
    all(w.count(c)>=required.count(c) for c in required) and
    not any(c in w for c in restricted) )]
</code>```

Body:
So I've been really struggling with this problem. First of all let's lay-out the basic rules that this Python program must follow:

Lingo is a popular word-guessing game show on television. The number
of letters of a target word to be guessed is given, and often also the
first letter. Players then make guesses subject to these restrictions
(number of letters and possibly also first letter), and the game tells
them which letters are correct and in the correct place, marked by a
red square (X), and which letters are correct but not in the correct
place, marked by a yellow circle (O). We do not use superfluous yellow
circles, i.e. a letter is marked correct at most as often as it
appears in the target word. If not all occurrences of the same letter
can get a yellow circle this way, priority is given from left to right
(but of course red squares have priority over yellow circles).

First I needed to create a function compare that compares a guessed word with a target word. The two inputs are string of the same length that entirely consist of lowercase ASCII letters. The output is a string of the same length consisting of the symbols X, O and -, where X represent a red square, O represents a yellow circle and - represents nothing.

Examples:

compare("health", "teethe") must return "OX--O-",

compare("rhythm", "teethe") must return "---XX-",

compare("mutate", "teethe") must return "--O-OX",

compare("teethe", "mutate") must return "O--O-X",

Now I've already successfully solved this part, but the next part is where I am stuck.

A function filter_targets(targets, guess_results) must be implemented.

This function must satisfy the following:

● targets is a list (or any other iterable) of possible target words; all words in targets must be of the same length.

● guess_results is a dictionary. Its keys are guessed words (which need not be in the target list) whose associated values are their compare results with a possible target.

● It must return a list of target words in targets that actually do satisfy all
the comparisons appearing in guess_results .

Examples:

Suppose targets contains all English 6-letter words obtained using the aforementioned word list and load function. Let guess_results contain the results of the first two guesses in the example given:

guess_results = {"health": "OX--O-", "rhythm": "---XX-"}

Then based on these results, we can see which words are still possible:

filter_targets(targets, guess_results) will return the following list:

["depths", "peitho", "seethe", "teethe", "tenths"]

Now my current program looks like this, it is very dirty code in my opinion and I would really love to see some implementations that are right. This code also still doesn't do what I want it to.

My reasoning was that if I convert the word or words in guess_results (it must also be able to take a single input, as my code hereunder is taking with the mem_list function) to the "XO-" format, then store all permutations of this format in a list, I can convert the words in wordlist to the format too. I would then check for every permutation in the list if it matches the "XO-" format of any word in the wordlist I am looping through, then store all matches in a separate list. I would then return that list as an answer.

I thought I was getting very close with this logic, but I now can't seem to permutate in a way the leaves some characters in place. And my current implementation would only work for a single word input.

from itertools import permutations

def load_words(file):
    result = set()
    with open(file) as f:
      for line in f.readlines():
        word = line.strip().lower()
        if word.isalpha() and word.isascii():
          result.add(word)
    return sorted(result)

english_words = load_words("words.txt")
dutch_words = load_words("wordlist.txt")

english_10 = [word for word in dutch_words if len(word) == 10]

    def filter_targets(targets, guess_results):
        mem_list = ["-" for x in range(len("kasgelden"))]
        perm_list = mem_list

    # Checking X
    for guess in guess_results.keys():
        for idx in range(len(guess)):
            if guess_results[guess][idx] == 'X':
                mem_list[idx] = guess[idx]

    o_list = []

    # Checking O
    for guess in guess_results.keys():
        for idx in range(len(guess)):
            if guess_results[guess][idx] == 'O':
                mem_var = guess[idx]
                o_list.append(mem_var)

    add_list = mem_list

    o_min = 0
    o_max = len(o_list)
    y = 0

    # Adding the "O"
    for element in add_list:
        if element == "-" and o_min < o_max:
            add_list[y] = o_list[o_min]
            o_min += 1
            y += 1
        else:
            y += 1

    check_list = list(permutations(add_list))

guess_results = {"kasgelden": "--O--OOX-"}
d6 = [word for word in dutch_words if len(word) == 9]

filter_targets(d6, guess_results)

In this single world example: filter_targets(dw9, {"kasgelden": "--O--OOX-"}) should return ["doorspoel", "doublures", "hoofdstel", "moordspel",
"schildjes", "slurfdier", "thuisduel", "woordspel"] . With dw9 being all the words with a length of 9.

This problem is driving me completely crazy and has consumed three days of free time already, I hope someone can nudge me in the right direction here!

English wordlist I am using: https://raw.githubusercontent.com/dwyl/english-words/master/words.txt

Dutch wordlist I am using: https://raw.githubusercontent.com/OpenTaal/opentaal-wordlist/master/wordlist.txt

Body:
The guess results tell you two types of things:

For each position, is the guessed letter required or excluded.

For each guessed letter, does it appear in the correct answer.

You can track the first thing by maintaining a regex.
You can track the second thing with two strings, one containing needed characters, one containing forbidden ones.

You can build those as follows:

regex = ["[^^]"]*wordlen
required = restricted = ''
for guess,result in guess_results:
    needs = never = ''
    for i,score in enumerate(result):
        letter = guess[i]
        if score == 'X':
            regex[i]=letter
            needs += letter
        elif score == 'O':
            regex[i] = regex[i].replace(']',letter+']')
            needs += letter
        else:
            regex[i] = regex[i].replace(']',letter+']')
            never += letter
        # don't reject a '-' found on doubled letter if one was needed.
        restricted += ''.join(c for c in never if c not in needs)
        # track the correct number of required letters.
        required = ''.join([c*max(required.count(c),needs.count(c)) for c in set(required)] +
                   [c for c in needs if c not in required])

Then filtering the wordlist becomes

valid = [w for w in wordlist if (
    re.match(''.join(regex), w) and
    all(w.count(c)>=required.count(c) for c in required) and
    not any(c in w for c in restricted) )]


问:
How to take updates from Master into Branch in TortoiseGit
I have created a branch in Git repository 10 days before and worked on some changes in the created branch. Now I need to update my branch with master updates (ie commits done over the master after the branch taken) and need to merge with master.

help me how to achieve this in TortoiseGit.

Guide me with TortoiseGit not through Git bash or Git CLI etc.

Thanks,

答: Right click on the branch folder and do a Pull from main. It will show files in conflict and let you resolve them in the process. This was the easiest way I found to do it.</p>


问:
Allow Azure function app access to AWS EC2 instance port
My company has an Azure function app that accesses a service on an AWS EC2 instance.
We use an AWS security group to only allow access to the service's port by the 7 possible outbound IP addresses used by the Azure function app. We find these listed in Azure portal.
However when the function app "scales" apparently it can be executed from a list of ~600 CIDR ranges of possible Azure IP addresses, from AzureCloud.eastus2 in my case.
The function app fails to access the needed web service in these cases and fails.
AWS security groups only allow 60 inbound rules so I couldn't set 600 even if I wanted.
Is there a better approach to opening an AWS instance's port to an Azure function app?</p>

答: Just like using a NAT Gateway with AWS Lambda functions to provide a static outbound IP, it appears you can do the same thing in Azure Functions with a Virtual network NAT gateway. That appears to be your best option.</p>


问:
Why does my for loop preemptively break when attempting to display a Pandas dataframe data in a NetworkX graph?
I'm attempting to connect information gathered about hashes to their various C2 servers, and am reading it from a CSV file into a dataframe, and then adding the nodes which are the headers (the hashes) and then in their individual columns are several IPs/URLs (not a set amount). When outputting this to a graph, it only displays the first row of information though, which makes me think my for loop setting the nodes and edges up is broken somehow, but I can't figure out how, as the logic seems like it should be okay for different numbers of rows per column, but at the same time the issue may be dropping the NaN from the dataframe.

```<code>import networkx as nx
from networkx.drawing.nx_agraph import write_dot
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure
from pyparsing import col, with_attribute
import pandas as pd

files = 'exampleCSV.csv'
df = pd.read_csv(files)
df = df._convert(numeric=True)
df = df.drop('sampleHash', 1)
df = df.dropna()

headerList = list(df.columns.values)
print(headerList)

g = nx.Graph()

for i in range(len(headerList)):
    g.add_node(headerList[i])
    valueList = df[headerList[i]].tolist()

    for x in range(len(valueList)):
        g.add_node(valueList[x])
        g.add_edge(headerList[i], valueList[x])
</code>```

I've included photos of the outputted graph and the CSV file it is pulling information from. I also tried directly doing the dataframe to networkx conversion function, and it broke everything really badly, so individually adding and linking them in a loop is the best way I've found to do this so far.

Outputted Graph:

CSV File:

答:
Thanks to @Barmar for his tips, it was an issue with my logic, and dropping NaN caused some issues as well. Aside from some bad coding practices of mine, here is the initial fix that worked out:

```<code>files = 'exampleCSV.csv'
df = pd.read_csv(files)
df = df._convert(numeric=True)
df = df.drop('sampleHash', 1)

headerList = list(df.columns.values)

g = nx.Graph()

for i in range(len(headerList)):
    g.add_node(headerList[i])

    valueList = df[headerList[i]].tolist()

    for x in range(len(valueList)):
        try:
            result = math.isnan(valueList[x])
        except:
            result = False
        if result == False:
            g.add_node(valueList[x])
            print(valueList[x])
            g.add_edge(headerList[i], valueList[x])

</code>```

NaN was keeping it iterating as the max row of some of the values was only one row, so the for loop was most likely unable to continue on. The NaNs from Pandas in the open spots in the lists made iteration easier, so adding them in and just filtering them out when creating the graph solved the issue.

I'm sure there is a cleaner way of doing this, but it does what it's supposed to now. Thanks for the help!

Body:
I'm attempting to connect information gathered about hashes to their various C2 servers, and am reading it from a CSV file into a dataframe, and then adding the nodes which are the headers (the hashes) and then in their individual columns are several IPs/URLs (not a set amount). When outputting this to a graph, it only displays the first row of information though, which makes me think my for loop setting the nodes and edges up is broken somehow, but I can't figure out how, as the logic seems like it should be okay for different numbers of rows per column, but at the same time the issue may be dropping the NaN from the dataframe.

import networkx as nx
from networkx.drawing.nx_agraph import write_dot
from matplotlib import pyplot as plt
from matplotlib.pyplot import figure
from pyparsing import col, with_attribute
import pandas as pd

files = 'exampleCSV.csv'
df = pd.read_csv(files)
df = df._convert(numeric=True)
df = df.drop('sampleHash', 1)
df = df.dropna()

headerList = list(df.columns.values)
print(headerList)

g = nx.Graph()

for i in range(len(headerList)):
    g.add_node(headerList[i])
    valueList = df[headerList[i]].tolist()

    for x in range(len(valueList)):
        g.add_node(valueList[x])
        g.add_edge(headerList[i], valueList[x])

I've included photos of the outputted graph and the CSV file it is pulling information from. I also tried directly doing the dataframe to networkx conversion function, and it broke everything really badly, so individually adding and linking them in a loop is the best way I've found to do this so far.

Outputted Graph:

CSV File:

Body:
Thanks to @Barmar for his tips, it was an issue with my logic, and dropping NaN caused some issues as well. Aside from some bad coding practices of mine, here is the initial fix that worked out:

files = 'exampleCSV.csv'
df = pd.read_csv(files)
df = df._convert(numeric=True)
df = df.drop('sampleHash', 1)

headerList = list(df.columns.values)

g = nx.Graph()

for i in range(len(headerList)):
    g.add_node(headerList[i])

    valueList = df[headerList[i]].tolist()

    for x in range(len(valueList)):
        try:
            result = math.isnan(valueList[x])
        except:
            result = False
        if result == False:
            g.add_node(valueList[x])
            print(valueList[x])
            g.add_edge(headerList[i], valueList[x])

NaN was keeping it iterating as the max row of some of the values was only one row, so the for loop was most likely unable to continue on. The NaNs from Pandas in the open spots in the lists made iteration easier, so adding them in and just filtering them out when creating the graph solved the issue.

I'm sure there is a cleaner way of doing this, but it does what it's supposed to now. Thanks for the help!


问:
Typescript thinks indexed access type T[EventKeys<T>] isn't a MyEvent
I have an interface for custom event listeners, so that classes can provide events which others can listen to:

```<code>interface MyEvent<F extends (...args: any[]) => void> {
    listen(callback: F): void;
}

class Foo {
    declare numberEvent: MyEvent<(x: number) => void>;
    declare stringEvent: MyEvent<(x: string) => void>;
    declare somethingElse: number;
}
</code>```

I am writing a function which listens to multiple events belonging to the same object, which should be called like this:

```<code>listenAll(foo, {
    numberEvent: x => console.log(x + 1),
    stringEvent: x => console.log(x.charAt(0)),
});
</code>```

To make this work, I have the following two utility types: EventKeys gets the keys corresponding to events declared in a class, and CallbacksFor defines an object containing the appropriate callbacks for each event in a class.

```<code>type EventKeys<T> = {[K in keyof T]: T[K] extends MyEvent<any> ? K : never}[keyof T]
type CallbacksFor<T> = {[K in EventKeys<T>]: T[K] extends MyEvent<infer F> ? F : never}
</code>```

The problem is writing the listenAll function:

```<code>function listenAll<T>(obj: T, callbacks: CallbacksFor<T>): void {
    const keys = Object.keys(callbacks) as (EventKeys<T>)[];

    for(const key of keys) {
        const e = obj[key];
        const f = callbacks[key];
        // error: Property 'listen' does not exist on type 'T[EventKeys<T>]'.
        e.listen(f);
    }
}
</code>```

Playground Link

The problem is, Typescript doesn't realise that the indexed access type T[EventKeys<T>] must be a MyEvent. Even using a type assertion const e = obj[key] as MyEvent<any>; gives a compilation error, because Typescript thinks these types are completely unrelated. But EventKeys<T> is defined as the subset of keys of T whose values are assignable to MyEvent<any>, so logically obj[key] must be a MyEvent.

I don't mind the type assertion when using Object.keys, but I'd like to know if this function can be written without something like e = obj[key] as unknown as MyEvent<any>;, which uses another two type assertions.

I did find a way to make the listenAll function type-check, by changing its generic type parameters like below, but unfortunately this doesn't solve the problem because K can't be inferred from context at the call-site.

```<code>function listenAll<K extends PropertyKey, T extends Record<K, MyEvent<any>>>(/* ... */): void {
    // ...
}
</code>```

Playground Link

答:
The solution is to give T a self-referential upper bound Record<EventKeys<T>, MyEvent<any>>:

```<code>function listenAll<T extends Record<EventKeys<T>, MyEvent<any>>>(obj: T, callbacks: CallbacksFor<T>): void {
    // ...
}
</code>```

Playground Link

This upper bound should be a tautology, since EventKeys<T> is defined as precisely those keys whose values are of type MyEvent<any>. The problem was that Typescript couldn't figure that out for itself, but specifying it in the upper bound allows Typescript to infer that obj[key] has type MyEvent<...> when key has type EventKeys<T>, as required.

The upper bound will be checked at the call-site, where T is realised as a concrete type; although Typescript can't figure out that the constraint is satisfied for all types, Typescript can at least confirm that it is satisfied for whatever concrete type is provided, and so there is no type error at the call-site.

Body:
I have an interface for custom event listeners, so that classes can provide events which others can listen to:

interface MyEvent<F extends (...args: any[]) => void> {
    listen(callback: F): void;
}

class Foo {
    declare numberEvent: MyEvent<(x: number) => void>;
    declare stringEvent: MyEvent<(x: string) => void>;
    declare somethingElse: number;
}

I am writing a function which listens to multiple events belonging to the same object, which should be called like this:

listenAll(foo, {
    numberEvent: x => console.log(x + 1),
    stringEvent: x => console.log(x.charAt(0)),
});

To make this work, I have the following two utility types: EventKeys gets the keys corresponding to events declared in a class, and CallbacksFor defines an object containing the appropriate callbacks for each event in a class.

type EventKeys<T> = {[K in keyof T]: T[K] extends MyEvent<any> ? K : never}[keyof T]
type CallbacksFor<T> = {[K in EventKeys<T>]: T[K] extends MyEvent<infer F> ? F : never}

The problem is writing the listenAll function:

function listenAll<T>(obj: T, callbacks: CallbacksFor<T>): void {
    const keys = Object.keys(callbacks) as (EventKeys<T>)[];

    for(const key of keys) {
        const e = obj[key];
        const f = callbacks[key];
        // error: Property 'listen' does not exist on type 'T[EventKeys<T>]'.
        e.listen(f);
    }
}

<a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgLIE8CiA3C4A8AYshAB6QgAmAzsgBQB0TcUA5tQFzJwjoDaAXQCUyALwA+ZNgD2wSpIDeAWABQydcgA2wahToI4mzQCNEAay6EhXGXIDcqgL6rVYdAAcUOPGADSEdGp8ABVJUWQFPl9kUGQzAOkYZGCBLmCogRJyPBo0LFwCHnRJAH5kaK4QCFwoRz549ETkgVcPFABhQxNzakJpKBCwiKiYkGRvcH9AwdTkjKyKXIwJsHxQGGhkQlKt5Erq6GcVVRgAVxAEMGBpMe1dPABBI0G6aWMAKzSAGmQDI1MEGZOMhOv8en0BqFrFJZJQIqoNL8bro4gFaOEAPIfCCXBgNaj6LoAoEiOC0OgrKZBKGCBzHNQaGD9fTIsCo9DIJr4kTKBmI9QIVkkMScj71AICOn8jSCkAopLhP7dQHUcXoSUI6XIAD02pIUCg-S4AAVDZ4oG5kAByO4UK3ISjSCC0EDSNlkHRsm7INyea3pSlomZWhia6UQBi2vB0GBCKUaI5HVQITRk2h9aTwvkOnGpqAoECnAC2xmgKy4ywKqzopEqxdLUBEEhhcnE8fUlFzLBQuigoFY5byK3wNa4vf7Tcktnk7ZzKe7yGo0iLEDAAAt+5hNNQIHWS9A6UmVLL5dJM+EqgB3LZnuhx1RRkBPTQxs8-XmIwv7qCD0hiSQntImgRpo0isDWyAANTIAAjEIXxhouYB9iAA5Vlwf7NoBwGRmBNYMAga4sA8YB0AADEI8FOPeKhAA" rel="nofollow noreferrer">Playground Link

The problem is, Typescript doesn't realise that the indexed access type T[EventKeys<T>] must be a MyEvent. Even using a type assertion const e = obj[key] as MyEvent<any>; gives a compilation error, because Typescript thinks these types are completely unrelated. But EventKeys<T> is defined as the subset of keys of T whose values are assignable to MyEvent<any>, so logically obj[key] must be a MyEvent.

I don't mind the type assertion when using Object.keys, but I'd like to know if this function can be written without something like e = obj[key] as unknown as MyEvent<any>;, which uses another two type assertions.

I did find a way to make the listenAll function type-check, by changing its generic type parameters like below, but unfortunately this doesn't solve the problem because K can't be inferred from context at the call-site.

function listenAll<K extends PropertyKey, T extends Record<K, MyEvent<any>>>(/* ... */): void {
    // ...
}

<a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgLIE8CiA3C4A8AYshAB6QgAmAzsgBQB0TcUA5tQFzJwjoDaAXQCUyALwA+ZNgD2wSpIDeAWABQydcgA2wahToI4mzQCNEAay6EhXGXIDcqgL6rVYdAAcUOPGADSEdGp8ABVJUWQFPl9kUGQzAOkYZGCBLmCogRJyPBo0LFwCHnRJAH5kaK4QCFwoRz549ETkgVcPFABhQxNzakJpKBCwiKiYkGRvcH9AwdTkjKyKXIwJsHxQGGhkQlKt5Erq6GcVVRgAVxAEMGBpMe1dPABBI3xoskXaAAUoaU8oNymADTJBY5WgAJQgCH6lBeQOWBVWRXEyLo0mMACs0kCDEZTAgzJxkJ1cT0+gNQtYpLJKBFVBpkFCQLo4gFaOEAPIYyFgBgNaj6Lp4gkiOC0OgrKZBCmCBzHNQaGD9fQ3ZkNZBNPkiZTy+nqRnMlDhNHo+oBASy3UafVgZBJcI47r46im9DmumW5AAek9yBA0hIUG+UGQAAtoCg-QB3d2WiAMO56GBCC0aI5HVQITSi2h9f3a+mUSFZqAR04AW2M0BWXHhPnwdFIlXLlagIgkVLk4hT6kLmZYKF0UFArGreRW9cbyEHw7bkls8m7yF7xYH0jLEDAIeHmE01AgTYr0Fl6ZU1tt0n94Sqka2F7oydU3uQxlONqjyE34ZitB4AaDofDDhHx9B42HLHx1SSNxPGQAByXNYO-X1pBtbNgFYEA4GMTQUDAf13BYOB10gYMmmglBYIhKEoBhL4fmgf4AjhfI6yRcRYIYZBVATR4jDoRVpCBfMNBAZsqwRLhSDESR9WkHD42kVgG2QABqZAAEYhABGMpzAIcQBHCTkCk9tZPkzRFIbBgEBDFgHjAOgAAYhC0pwHxUIA" rel="nofollow noreferrer">Playground Link

Body:
The solution is to give T a self-referential upper bound Record<EventKeys<T>, MyEvent<any>>:

function listenAll<T extends Record<EventKeys<T>, MyEvent<any>>>(obj: T, callbacks: CallbacksFor<T>): void {
    // ...
}

<a href="https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgLIE8CiA3C4A8AYshAB6QgAmAzsgBQB0TcUA5tQFzJwjoDaAXQCUyALwA+ZNgD2wSpIDeAWABQydcgA2wahToI4mzQCNEAay6EhXGXIDcqgL6rVYdAAcUOPGADSEdGp8ABVJUWQFPl9kUGQzAOkYZGCBLmCogRJyPBo0LFwCHnRJAH5kaK4QCFwoRz549ETkgVcPFABhQxNzakJpKBCwiKiYkGRvcH9AwdTkjKyKXIwJsHxQGGhkQlKt5Erq6GcVVRgAVxAEMGBpMe1dPABBIxCFnNoAJQgEfsp8FamgqEADR5Fb4IriSF0aTGABWaRBBiMpgQZk4yE6yJ6fQGoWsUlklAiqg0yG+IF0cQCtHCAHk4V8wAwGtR9F0UWiRHBaHR-tTBkJBA5jmoNDB+vobpSGsgmiyRMpRaT1OTKShwjDYfUAgJhcqNKqwMgkuEkd1UdRtehdST9SQGHc9DAhHqNEcjqoEJpubQ+tJiUrkJQvt6oCgQKcALbGaArLjLAqrOikSpRmNQEQSAlycSu9TBr0sFC6KCgVhx0GJ-DJrglsuZyS2eR5oMhovIajSSMQMAACzLmE01Agqej0GFHpUhuN0n94SqAHctrO6C7VI7HkY6OLpCDFaSI2OoBXSGJJKrpJoIA7pKxk8gANTIACMQiBtvUdZA5cTXFPWYvK8bzvUgGAQXsWAeMA6AABiEN8nDXFQgA" rel="nofollow noreferrer">Playground Link

This upper bound should be a tautology, since EventKeys<T> is defined as precisely those keys whose values are of type MyEvent<any>. The problem was that Typescript couldn't figure that out for itself, but specifying it in the upper bound allows Typescript to infer that obj[key] has type MyEvent<...> when key has type EventKeys<T>, as required.

The upper bound will be checked at the call-site, where T is realised as a concrete type; although Typescript can't figure out that the constraint is satisfied for all types, Typescript can at least confirm that it is satisfied for whatever concrete type is provided, and so there is no type error at the call-site.


答:
Here's an example using a combination of jQuery.parents() (to get the containing
 tags) and then jQuery.children() to get the  tags with a class of trigger:

```<code>$(document).ready( function() {
    $('#my_target').click( function(e) {
        $(this).parents('li.selected').children('a.trigger').addClass('myclass');
        e.preventDefault();
    });
});
</code>```

jsfiddle example

EDIT:

Note $().parents() traverses all the way up the tree, but $().children() only traverses down one level. To gather all descendents of an element use $().find().

Title: jquery - traverse up tree and find elements with specified class

Body:
I thought that the closest() function would do this for me, but seemingly not. I have the following markup and I want to add a class to all parent anchors with the class trigger:

I want to select my target - in this example, the deepest anchor, then add a class to each a.trigger in its ascendants. What would be the best way to do this? Thanks.

Body:
Here's an example using a combination of jQuery.parents() (to get the containing <li> tags) and then jQuery.children() to get the <a> tags with a class of trigger:

$(document).ready( function() {
    $('#my_target').click( function(e) {
        $(this).parents('li.selected').children('a.trigger').addClass('myclass');
        e.preventDefault();
    });
});

jsfiddle example

EDIT:

Note $().parents() traverses all the way up the tree, but $().children() only traverses down one level. To gather all descendents of an element use $().find().


问:
How can I download a pre-trained model from Tensorflow's Object Detection Model Zoo?
I am attempting to train an object detection model using Tensorflow's Object Detection API 2 and Tensorflow 2.3.0. I have largely been using this article as a resource in preparing the data and training the model.

Most articles which use the Object Detection API download a pre-trained model from the Tensorflow model zoo prior to fine-tuning.

The Tensorflow Model Zoo is a set of links on a Github page set up by the Object Detection team. When I click one such link (using Google Chrome), a new tab opens briefly as if a download is starting, then immediately closes and a download does not occur. Hyperlinks to other models I have found in articles also have not worked.

To anyone who has worked with fine-tuning using the Object Detection API: What method did you use to download a pre-trained model? Did the model zoo links work? If not, what resource did you use instead?

Any help is much appreciated.

答: In Google Chrome, you can copy the link of the model from Readme file and then paste that into another tab. The download will start automatically.</p>