问:
matplotlib plotting multiple lines
Consider the following code:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from regressors import stats
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

def read_data() -> pd.DataFrame:
    data = pd.read_csv(filepath_or_buffer='./Boston.csv')
    data = data.dropna()

    df = pd.DataFrame(data)
    df.drop(columns=df.columns[0], inplace=True)

    return df

BOSTON: pd.DataFrame = read_data()

def part_a(plot: bool = False) -> None:
    X: np.ndarray = BOSTON[['dis']].values
    y: np.ndarray = BOSTON['nox']

    poly: PolynomialFeatures = PolynomialFeatures(degree=3, include_bias=False)
    X_poly: np.ndarray = poly.fit_transform(X=X)

    model: LinearRegression = LinearRegression()
    model.fit(X=X_poly, y=y)

    stats.summary(clf=model, X=X_poly, y=y, xlabels=poly.get_feature_names_out(input_features=['dis']))

    if plot:
        y_pred = model.predict(X=X_poly)

        plt.title('nox vs. dis')
        plt.scatter(x=X, y=y, color='blue', marker='o', facecolors='none', label='Observed')
        plt.plot(X, y_pred, color='red')
        plt.xlabel('dis')
        plt.ylabel('nox')
        plt.legend()
        plt.show()

part_a(plot=True)
```

It plots the following:

Why are there multiple red lines?

Title: matplotlib plotting multiple lines

Body:
Consider the following code:

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from regressors import stats
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

def read_data() -> pd.DataFrame:
    data = pd.read_csv(filepath_or_buffer='./Boston.csv')
    data = data.dropna()

    df = pd.DataFrame(data)
    df.drop(columns=df.columns[0], inplace=True)

    return df

BOSTON: pd.DataFrame = read_data()

def part_a(plot: bool = False) -> None:
    X: np.ndarray = BOSTON[['dis']].values
    y: np.ndarray = BOSTON['nox']

    poly: PolynomialFeatures = PolynomialFeatures(degree=3, include_bias=False)
    X_poly: np.ndarray = poly.fit_transform(X=X)

    model: LinearRegression = LinearRegression()
    model.fit(X=X_poly, y=y)

    stats.summary(clf=model, X=X_poly, y=y, xlabels=poly.get_feature_names_out(input_features=['dis']))

    if plot:
        y_pred = model.predict(X=X_poly)

        plt.title('nox vs. dis')
        plt.scatter(x=X, y=y, color='blue', marker='o', facecolors='none', label='Observed')
        plt.plot(X, y_pred, color='red')
        plt.xlabel('dis')
        plt.ylabel('nox')
        plt.legend()
        plt.show()

part_a(plot=True)

It plots the following:

Why are there multiple red lines?


来源: stackexchange

问:
What are the downsides of using IPv6 Multicast for all communication?
Given IPv6 Multicast allows for a sub-pub communication model, it seems like a no-brainer for the vast majority of communication, but its very rarely used beyond video streaming, and I'd like to know if this is because its only efficient for large groups or if its just because its not well understood and Unicast/Anycast are easier to implement?

Unicast addresses are still needed to send to the Multicast group addresses, but even for groups of 2, Multicast seems like it would theoretically be more efficient and flexible because either party can leave the group at any time.

One issue may be the state requirements needed to maintain the sets of subscribers, but so long as packet duplication is performed at the edge of the network if required, I don't see how this adds that much overhead?

I also understand there are some current limitations with regard to support for globally scoped IPv6 Multicast, but this question is more about the theory and trade-offs with using IPv6 Multicast in place of Unicast.

Please let me know what I'm missing or provide some links to material I can read to get a better understanding of what would be required and what the trade-offs are

Thank you

I've implemented IPv6 multicast on my local network and sent packets globally between my home and my office, and it works fantastically well, so I'm wondering what the drawbacks are for using it in most contexts

ContentLicense: CC BY-SA 4.0


问:
Customise QuickInfo from IntelliSense
i want to extend the QuickInfo in IntelliSense.
When i type my variable and the type ".", IntelliSense shows me all Method, Properties and Fields inside the Object.
Wen i move the Curser via Keyboard and wait a second... an Quick info will be shown with Method, Property or Field informations.
Now i want to extend this Informations from Attributes there are on it.

For exsample...
I have an Class with Properties:

When i select this in IntelliCode like this:

Iwant to insert in the red marked QuickInfo my "TranslationItem" Attribute informations.

The Final will look like this:

For Mouse-Move-Actions i am finished.

I hope anybody can help me.

Title: Customise QuickInfo from IntelliSense


问:
Rust build (cargo build) using Powershell causes error but builds file
rust 1.65.0
I have a rust build where I just do a Cargo Build. Everything seems fine (including the build) but at the top of the output has an error about updating crates.io index. No other place has in the output shows an error. However, this error causes my ADO pipeline to fail.

My call from ADO Task (Inline Powershell):

Set-Location "$(Build.SourcesDirectory)\src\avmh\avmh"
cargo build --release
```
<p>Start of output:</p>
<pre class="lang-none prettyprint-override"><code>"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\a\_temp\c3cde96b-7741-41cd-a0f8-bf936f4b9d7d.ps1'"
##[error]Updating crates.io index
 Downloading crates ...
  Downloaded anyhow v1.0.66
  Downloaded hmac v0.12.1
  Downloaded proc-macro-error v1.0.4
  Downloaded regex-automata v0.1.10
.
.
.
   Compiling avmh v0.4.0 (D:\a\1\s\src\avmh\avmh)
    Finished release [optimized] target(s) in 10m 08s
Finishing: Build AVMH
</code>```

Body:
rust 1.65.0
I have a rust build where I just do a Cargo Build. Everything seems fine (including the build) but at the top of the output has an error about updating crates.io index. No other place has in the output shows an error. However, this error causes my ADO pipeline to fail.

My call from ADO Task (Inline Powershell):

Set-Location "$(Build.SourcesDirectory)\src\avmh\avmh"
cargo build --release

Start of output:

"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\a\_temp\c3cde96b-7741-41cd-a0f8-bf936f4b9d7d.ps1'"
##[error]Updating crates.io index
 Downloading crates ...
  Downloaded anyhow v1.0.66
  Downloaded hmac v0.12.1
  Downloaded proc-macro-error v1.0.4
  Downloaded regex-automata v0.1.10
.
.
.
   Compiling avmh v0.4.0 (D:\a\1\s\src\avmh\avmh)
    Finished release [optimized] target(s) in 10m 08s
Finishing: Build AVMH


问:
How do I get all of the tracks released in a specific year using Spotify's API?
I am attempting to get all of the tracks release on Spotify for a given year (e.g. all tracks release in 2018)?  I've been looking through their APIs and various projects posted by others, but have not been able to find a solution for this one. One particular issue is the limit on 50 API calls, so as part of a solution, I am looking for a way that I could get the thousands of songs released in a year all at once.

I have tried looking at Spotify API documentation, Spotipy library documentation, and various projects related to this topic, but have not seen anyone tackle this particular issue.


问:
one query I need to use multiple transaction blocks inside a single jdbc batch, how to do that any example?
Because I have insert statement which should be happen only if update statement executed fine, otherwise proceed to other set of insert and update query inside batch and do the same</p>


问:
extract file from zip file in python
I have a zip file that contain many folders and each folder again contain many folders. I want to extract the specific file from the last folder in zip file and I need help to do that in python. the chart of zip file is:

zip file---(folder1, folder2, folder3)
-----folder1 (folder11,folder12)
---folder11(folder111)-----file1.kmz
-----folder2 (folder21,folder22)
---folder21(folder211)-----file2.kmz
-----folder3 (folder31,folder32)
---folder31(folder311)-----file3.kmz
I want to extract the file1.kmz, file2.kmz and file3.kmz in the single folder.

Title: extract file from zip file in python


问:
PyAutoGUI was unable to import pygetwindow
I'm writing a program in R that calls a script from python

```<code>py_run_file("Screen Record.py")
</code>```

I have tested the python file on its own and it works fine. The problem happens when I call it from the R script. Specifically this line (which is the first instance of pyautogui being run):

```<code>w = pyautogui.getWindowsWithTitle(windowName)[0]
</code>```

The error that occurs is:

```<code>Error in py_run_file_impl(file, local, convert) :
  pyautogui.PyAutoGUIException: PyAutoGUI was unable to import pygetwindow. Please install this module to enable the function you tried to call.
</code>```

However I don't run into that error when I import it earlier on in the file:

```<code>import pygetwindow
import pyautogui
</code>```

Which if it wasn't installed should give me an error like this:

```<code>Error in py_run_file_impl(file, local, convert) :
  ModuleNotFoundError: No module named 'madeup'

</code>```

I have also tested a pygetwindow function and that works fine. Any help would be appreciated.

Body:
I'm writing a program in R that calls a script from python

py_run_file("Screen Record.py")

I have tested the python file on its own and it works fine. The problem happens when I call it from the R script. Specifically this line (which is the first instance of pyautogui being run):

w = pyautogui.getWindowsWithTitle(windowName)[0]

The error that occurs is:

Error in py_run_file_impl(file, local, convert) :
  pyautogui.PyAutoGUIException: PyAutoGUI was unable to import pygetwindow. Please install this module to enable the function you tried to call.

However I don't run into that error when I import it earlier on in the file:

import pygetwindow
import pyautogui

Which if it wasn't installed should give me an error like this:

Error in py_run_file_impl(file, local, convert) :
  ModuleNotFoundError: No module named 'madeup'

I have also tested a pygetwindow function and that works fine. Any help would be appreciated.


问:
How to jump lines with the cursor going through the ";" in Visual Studio Code? CSS
In Sublimetext when i end to write CSS values still before the ";" and i want to jump to the next line, the cursor goes through the ";" without it coming down too. like:

```<code>header .cont {
    color: #fff;
    padding: 20px;

}
</code>```

But in VSC the ";" comes down:

```<code>header .cont {
    color: #fff;
    padding: 20px
;
}
</code>```

I couldn't find anything about it on the VSC setting, it is a really handy feature to work more fluently while writting on sublimetext

Body:
In Sublimetext when i end to write CSS values still before the ";" and i want to jump to the next line, the cursor goes through the ";" without it coming down too. like:

header .cont {
    color: #fff;
    padding: 20px;

}

But in VSC the ";" comes down:

header .cont {
    color: #fff;
    padding: 20px
;
}

I couldn't find anything about it on the VSC setting, it is a really handy feature to work more fluently while writting on sublimetext


问:
Vue3 and Supabase when connecting via Remote device I get "WebSocket connection to 'ws://localhost:4000/ws' failed: "
I am using a Nuxt3 server currently running in develop mode that uses a Supabase Database and when I try to connect to the server from a diffrent device then my localhost I get a constant error of "WebSocket connection to 'ws://localhost:4000/ws' failed: " in the develop console.

I want this error to stop because I have a diffrent problem and want to rule out this error as a source for problems.

So far I didnt really try much because I just dont know where to start. I guess that it has something to do with Supabases Postgres database, but I am quite new to Vue3 and Supabase so I dont know if a URL needs to be configured diffrently.

Appreciate it if someone with more knowlede could help me!

Update:
This is how the error looks on a remote device

And this is how it looks on the local device

For Nuxt my Package.json looks like this

And my nuxt.config.ts looks like this

Additional information that might be usefull:
I store the supabase url and key in a .env file and when I use supabase I do it with:

```<code>const user = useSupabaseUser()
const client = useSupabaseClient()
</code>```

The error always occures when I try to access the website by using the Network URL provided by the yarn dev command. It happens on mobile devices aswell as other computers

Body:
I am using a Nuxt3 server currently running in develop mode that uses a Supabase Database and when I try to connect to the server from a diffrent device then my localhost I get a constant error of "WebSocket connection to 'ws://localhost:4000/ws' failed: " in the develop console.

I want this error to stop because I have a diffrent problem and want to rule out this error as a source for problems.

So far I didnt really try much because I just dont know where to start. I guess that it has something to do with Supabases Postgres database, but I am quite new to Vue3 and Supabase so I dont know if a URL needs to be configured diffrently.

Appreciate it if someone with more knowlede could help me!

Update:
This is how the error looks on a remote device

And this is how it looks on the local device

For Nuxt my Package.json looks like this

And my nuxt.config.ts looks like this

Additional information that might be usefull:
I store the supabase url and key in a .env file and when I use supabase I do it with:

const user = useSupabaseUser()
const client = useSupabaseClient()

The error always occures when I try to access the website by using the Network URL provided by the yarn dev command. It happens on mobile devices aswell as other computers


问:
Error: Package path is not valid. Valid system image paths are: system-images;android-21;default;x86_64 null
I am trying to create an Android emulator for my VS Code on Ubuntu 2022LTS. I have installed platform_tools, build_toolsand installed proper image, all located in sdk_manager directory. It seems the following command should work but I don't know why do I get the error:

avdmanager create avd -n AndroidDevice01 -k “system-images;android-21;default;x86_64" --device "Pixel_6”

The error:

[=======================================] 100% Fetch remote repository...        Error: Package path is not valid. Valid system image paths are: system-images;android-21;default;x86_64 null android-21: command not found Command 'default' not found, did you mean: command 'defaults' from deb gnustep-base-runtime (1.28.0-4build1) Try: sudo apt install <deb name> x86_64 --device Pixel_6”: command not found

This is the flutter doctor command result:

```<code>>
> Doctor summary (to see all details, run flutter doctor -v):
> Flutter (Channel stable, 3.3.9, on Ubuntu 22.04.1 LTS 5.15.0-56-generic,
> locale en_US.UTF-8)
> Android toolchain - develop for Android devices (Android SDK version 33.0.1)
> Chrome - develop for the web
> Linux toolchain - develop for Linux desktop
> Android Studio (not installed)
> VS Code (version 1.73.1)
> Connected device (2 available)
> HTTP Host Availability
>
> Doctor found issues in 1 category.
>
>
</code>```

I searched through the internet and tried different commands but they didn't work as well!

```<code></code>```

Body:
I am trying to create an Android emulator for my VS Code on Ubuntu 2022LTS. I have installed platform_tools, build_toolsand installed proper image, all located in sdk_manager directory. It seems the following command should work but I don't know why do I get the error:

avdmanager create avd -n AndroidDevice01 -k “system-images;android-21;default;x86_64" --device "Pixel_6”

The error:

[=======================================] 100% Fetch remote repository...        Error: Package path is not valid. Valid system image paths are: system-images;android-21;default;x86_64 null android-21: command not found Command 'default' not found, did you mean: command 'defaults' from deb gnustep-base-runtime (1.28.0-4build1) Try: sudo apt install <deb name> x86_64 --device Pixel_6”: command not found

This is the flutter doctor command result:

>
> Doctor summary (to see all details, run flutter doctor -v):
> Flutter (Channel stable, 3.3.9, on Ubuntu 22.04.1 LTS 5.15.0-56-generic,
> locale en_US.UTF-8)
> Android toolchain - develop for Android devices (Android SDK version 33.0.1)
> Chrome - develop for the web
> Linux toolchain - develop for Linux desktop
> Android Studio (not installed)
> VS Code (version 1.73.1)
> Connected device (2 available)
> HTTP Host Availability
>
> Doctor found issues in 1 category.
>
>

I searched through the internet and tried different commands but they didn't work as well!


问:
How to copy DB from disk to memory with IronPython2

I'm trying to figure out how to copy an existing database file on disk to memory to make queries on it faster. I know how to do this in CPython3 with:

import sqlite3
db_path = r"C:\path to\database.db"
db_disk = sqlite3.connect(db_path)
db_memory = sqlite3.connect(':memory:')
db_disk.backup(db_memory)
```
<p>but the <code>.backup()</code> function doesn't exist in IronPython2 (SQLite library version 3.7.7).</p>
<p>Through various researching, I've tried:</p>
<pre class="lang-python prettyprint-override"><code>import clr
clr.AddReference('IronPython.SQLite.dll')
import sqlite3

db_path = r"C:\path to\database.db"
db_disk = sqlite3.connect(db_path)
db_memory = sqlite3.connect(':memory:')
script = ''.join(db_server.iterdump())
db_memory.executescript(script)
</code>```

and

db_server = sqlite3.connect(db_path)
db_memory = sqlite3.connect(':memory:')
script = "".join(line for line in db_server.iterdump())
db_memory.executescript(script)
```
<p>But I keep getting an error at the line <code>script = ''.join(db_server.iterdump())</code> or <code>script = "".join(line for line in db_server.iterdump())</code>:</p>
<pre class="lang-none prettyprint-override"><code>Warning: IronPythonEvaluator.EvaluateIronPythonScript operation failed.
Traceback (most recent call last):
  File "<string>", line 72, in <module>
NotImplementedError: Not supported with C#-sqlite for unknown reasons.
</code>```

The code above came from seeing these posts:

Post 1

Post 2

Post 3

I was going to try the solution in this post, but I don't have apsw and I can't load any packages.

I was also going to try the solition in post 1 above, but again, I can't get pandas.io.sql or sqlalchemy.

Can anyone point me to a snippet of code that accomplishes this or correct my current code?
Thanks.

Body:
I'm trying to figure out how to copy an existing database file on disk to memory to make queries on it faster. I know how to do this in CPython3 with:

import sqlite3
db_path = r"C:\path to\database.db"
db_disk = sqlite3.connect(db_path)
db_memory = sqlite3.connect(':memory:')
db_disk.backup(db_memory)

but the .backup() function doesn't exist in IronPython2 (SQLite library version 3.7.7).

Through various researching, I've tried:

import clr
clr.AddReference('IronPython.SQLite.dll')
import sqlite3

db_path = r"C:\path to\database.db"
db_disk = sqlite3.connect(db_path)
db_memory = sqlite3.connect(':memory:')
script = ''.join(db_server.iterdump())
db_memory.executescript(script)

and

db_server = sqlite3.connect(db_path)
db_memory = sqlite3.connect(':memory:')
script = "".join(line for line in db_server.iterdump())
db_memory.executescript(script)

But I keep getting an error at the line script = ''.join(db_server.iterdump()) or script = "".join(line for line in db_server.iterdump()):

Warning: IronPythonEvaluator.EvaluateIronPythonScript operation failed.
Traceback (most recent call last):
  File "<string>", line 72, in <module>
NotImplementedError: Not supported with C#-sqlite for unknown reasons.

The code above came from seeing these posts:

Post 1

Post 2

Post 3

I was going to try the solution in this post, but I don't have apsw and I can't load any packages.

I was also going to try the solition in post 1 above, but again, I can't get pandas.io.sql or sqlalchemy.

Can anyone point me to a snippet of code that accomplishes this or correct my current code?
Thanks.


问:
Auto height adjustment not working for Google Forms embedding
Non software developer/programmer here.

I am trying to embed a Google Form into my website (hosted by Pixieset). I can get the width to automatically adjust by using width="100%", but height has a mind of its own and no matter what I try, it seems to always show two vertical scroll bars. I've attached the embed code below for reference. Anyone have crazy insights on how to fix this (if there is a way)?

Things I think might be helpful:

I'm only wanting to have the website scroll and not the embedded contact form

Most people will fill this form out on their phone, so that's the main goal

I'm using a website format from Pixieset so that may be problematic

Loading…

Thanks!

Things I've tried to change for height:

"auto"

"100%"

"100vh"

"please work"

Found a script that uses contentWindow


问:
How to get a full list of referenced assemblies and their target framework versions?
I have an ASP.NET MVC project which references a whole bunch of assemblies - some of it are targeting .NET standard while the rest are on .NET framework.

Is there an easy way to get a list of all my referenced assemblies and the .NET version they target? (I already know how to check them one-by-one - but is a productivity killer)

Perhaps a tool/script could look into the bin folder where all the dlls are and figure this out?

I do have dotPeek, but not sure if it helps.

This SO question is using a PS script to do this on a specific dll - can it be extended to all the dlls in a folder?


问:
What type of R graph can I use to display frequency on the x axis and length on y?
I have a dataset of length values for plants sampled in a number of specific square areas

eg., not actual data - just a representation

I want to create a graph in R that has the number of plants per plot (per area squared) on the x axis and the average length on the y axis - effectively exploring the effect of density per plot on length as pictured below.

Just wondering what the best function/package would be to do this in

Thanks


问:
Can I install Python, Django and other packages on a USB device and and run a server from this USB?
I would like to have a Django server on a Windows machine which is not connected to Internet.

For that, would it be possible to install, from another Windows machine connected to Internet, Python, PyCharm, Django and other packages to a USB device that I will then connect to the other Windows machine in order to start the application ?

Would it work without problems ?
Thanks !

-


问:
Change the color of the node when it is clicked on in Pyvis
I'm creating a network visualization in python using Pyvis. I know Pyvis is just a Java interpreter but still I'm not very familiar with Java so I'm trying to get as much as I can done with Python. I can create the graph as I want with no problem, but when I output the html file I want the nodes to change colors when I click on them. I've tried a lot of things and nothing seems to work. The data I'm using has the following structure but with a lot more nodes than this:

```<code>import pandas as pd
from pyvis.network import Network

data = [['A','B', 1], ['A','C', 4], ['B','A', 1],
        ['D','E', 5], ['D','F', 1], ['G','J', 7],
        ['A','J', 4], ['G','F', 14], ['C','L', 4],
        ['A','F', 2], ['E','H', 12], ['I','E', 2],
        ['I','K', 4], ['L','H', 21]]

df = pd.DataFrame(data, columns=['source', 'target', 'feature_count']

# Step 1: Initialize Network
graph = Network(height='750px', width='100%', directed=True)

# Step 2: Get sources, targets and weights
sources = df['source']
targets = df['targets']
weights = df['feature_count']

edge_data = zip(sources, targets, weights)

# Step 3: Create the graph adding each node individually.
for edge in edge_data:
    source_name = edge[0]
    target_name = edge[1]
    weight = edge[2]

    graph.add_node(n_id=source_name, label=source_name, labelHighlightBold=True)
    graph.add_node(n_id=target_name, label=target_name, labelHighlightBold=True)
    graph.add_edge(source_name, target_name, value=weight, title=weight, arrowStrikethrough=False)

# Step 4: Use the options (Java) to specify that I want the color of the note to change to red when clicked on
options = {
    "configure": {
         "enabled": True
     },
    "interaction": {
        "hover": True
    },
    "nodes": {
         "borderWidth": 2,
         "borderWidthSelected": 4,
         "chosen" : True,
         "color": { "highlight": { "border": "#FF4040",
                                   "background": "#EE3B3B"
                     },
                    "hover": { "border": "#DEB887",
                               "background": "#FFD39B"
                     }
         }
     }
}

# Step 5: Define the options
graph.options = options

# Step 6: Visualize the Network
graph.show('graph.html')
</code>```

So this code generates the network graph perfectly, but still the color of the nodes don't change when I click on them. Here is a picture of the html file that results from this:

And the weirdest thing is that even the buttons of the html file don't work neither for changing the colors, BUT THEY DO WORK FOR CHANGING ANYTHING ELSE LIKE THE FONT SIZE OR SOMETHING LIKE THAT.

I'd really appreciate the help.

Thanks!

Body:
I'm creating a network visualization in python using Pyvis. I know Pyvis is just a Java interpreter but still I'm not very familiar with Java so I'm trying to get as much as I can done with Python. I can create the graph as I want with no problem, but when I output the html file I want the nodes to change colors when I click on them. I've tried a lot of things and nothing seems to work. The data I'm using has the following structure but with a lot more nodes than this:

import pandas as pd
from pyvis.network import Network

data = [['A','B', 1], ['A','C', 4], ['B','A', 1],
        ['D','E', 5], ['D','F', 1], ['G','J', 7],
        ['A','J', 4], ['G','F', 14], ['C','L', 4],
        ['A','F', 2], ['E','H', 12], ['I','E', 2],
        ['I','K', 4], ['L','H', 21]]

df = pd.DataFrame(data, columns=['source', 'target', 'feature_count']

# Step 1: Initialize Network
graph = Network(height='750px', width='100%', directed=True)

# Step 2: Get sources, targets and weights
sources = df['source']
targets = df['targets']
weights = df['feature_count']

edge_data = zip(sources, targets, weights)

# Step 3: Create the graph adding each node individually.
for edge in edge_data:
    source_name = edge[0]
    target_name = edge[1]
    weight = edge[2]

    graph.add_node(n_id=source_name, label=source_name, labelHighlightBold=True)
    graph.add_node(n_id=target_name, label=target_name, labelHighlightBold=True)
    graph.add_edge(source_name, target_name, value=weight, title=weight, arrowStrikethrough=False)

# Step 4: Use the options (Java) to specify that I want the color of the note to change to red when clicked on
options = {
    "configure": {
         "enabled": True
     },
    "interaction": {
        "hover": True
    },
    "nodes": {
         "borderWidth": 2,
         "borderWidthSelected": 4,
         "chosen" : True,
         "color": { "highlight": { "border": "#FF4040",
                                   "background": "#EE3B3B"
                     },
                    "hover": { "border": "#DEB887",
                               "background": "#FFD39B"
                     }
         }
     }
}

# Step 5: Define the options
graph.options = options

# Step 6: Visualize the Network
graph.show('graph.html')

So this code generates the network graph perfectly, but still the color of the nodes don't change when I click on them. Here is a picture of the html file that results from this:

And the weirdest thing is that even the buttons of the html file don't work neither for changing the colors, BUT THEY DO WORK FOR CHANGING ANYTHING ELSE LIKE THE FONT SIZE OR SOMETHING LIKE THAT.

I'd really appreciate the help.

Thanks!


问:
java.lang.IllegalArgumentException: android.view.View.onRestoreInstanceState
I'm getting this generic error on Android Vitals, the log doesn't report the activity.

```<code>Exception java.lang.IllegalArgumentException:
  at android.view.View.onRestoreInstanceState (View.java:20879)
  at android.view.View.dispatchRestoreInstanceState (View.java:20851)
  at android.view.ViewGroup.dispatchRestoreInstanceState (ViewGroup.java:4067)
  at android.view.View.restoreHierarchyState (View.java:20829)
  at androidx.fragment.app.Fragment.restoreViewState (Fragment.java:689)
  at androidx.fragment.app.Fragment.restoreViewState (Fragment.java:3151)
  at androidx.fragment.app.Fragment.performActivityCreated (Fragment.java:3142)
  at androidx.fragment.app.FragmentStateManager.activityCreated (FragmentStateManager.java:579)
  at androidx.fragment.app.FragmentStateManager.moveToExpectedState (FragmentStateManager.java:264)
  at androidx.fragment.app.FragmentStore.moveToExpectedState (FragmentStore.java:113)
  at androidx.fragment.app.FragmentManager.moveToState (FragmentManager.java:1433)
  at androidx.fragment.app.FragmentManager.dispatchStateChange (FragmentManager.java:2977)
  at androidx.fragment.app.FragmentManager.dispatchActivityCreated (FragmentManager.java:2895)
  at androidx.fragment.app.FragmentController.dispatchActivityCreated (FragmentController.java:263)
  at androidx.fragment.app.FragmentActivity.onStart (FragmentActivity.java:351)
  at androidx.appcompat.app.AppCompatActivity.onStart (AppCompatActivity.java:246)
  at android.app.Instrumentation.callActivityOnStart (Instrumentation.java:1435)
  at android.app.Activity.performStart (Activity.java:8097)
  at android.app.ActivityThread.handleStartActivity (ActivityThread.java:3571)
  at android.app.servertransaction.TransactionExecutor.performLifecycleSequence (TransactionExecutor.java:221)
  at android.app.servertransaction.TransactionExecutor.cycleToPath (TransactionExecutor.java:201)
  at android.app.servertransaction.TransactionExecutor.executeLifecycleState (TransactionExecutor.java:173)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:97)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2144)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loop (Looper.java:240)
  at android.app.ActivityThread.main (ActivityThread.java:8000)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:603)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:947)
</code>```

The error happens on devices on Android 11 and Android 12. Has anyone encountered this error or can you see where the error might be happening?

Body:
I'm getting this generic error on Android Vitals, the log doesn't report the activity.

Exception java.lang.IllegalArgumentException:
  at android.view.View.onRestoreInstanceState (View.java:20879)
  at android.view.View.dispatchRestoreInstanceState (View.java:20851)
  at android.view.ViewGroup.dispatchRestoreInstanceState (ViewGroup.java:4067)
  at android.view.View.restoreHierarchyState (View.java:20829)
  at androidx.fragment.app.Fragment.restoreViewState (Fragment.java:689)
  at androidx.fragment.app.Fragment.restoreViewState (Fragment.java:3151)
  at androidx.fragment.app.Fragment.performActivityCreated (Fragment.java:3142)
  at androidx.fragment.app.FragmentStateManager.activityCreated (FragmentStateManager.java:579)
  at androidx.fragment.app.FragmentStateManager.moveToExpectedState (FragmentStateManager.java:264)
  at androidx.fragment.app.FragmentStore.moveToExpectedState (FragmentStore.java:113)
  at androidx.fragment.app.FragmentManager.moveToState (FragmentManager.java:1433)
  at androidx.fragment.app.FragmentManager.dispatchStateChange (FragmentManager.java:2977)
  at androidx.fragment.app.FragmentManager.dispatchActivityCreated (FragmentManager.java:2895)
  at androidx.fragment.app.FragmentController.dispatchActivityCreated (FragmentController.java:263)
  at androidx.fragment.app.FragmentActivity.onStart (FragmentActivity.java:351)
  at androidx.appcompat.app.AppCompatActivity.onStart (AppCompatActivity.java:246)
  at android.app.Instrumentation.callActivityOnStart (Instrumentation.java:1435)
  at android.app.Activity.performStart (Activity.java:8097)
  at android.app.ActivityThread.handleStartActivity (ActivityThread.java:3571)
  at android.app.servertransaction.TransactionExecutor.performLifecycleSequence (TransactionExecutor.java:221)
  at android.app.servertransaction.TransactionExecutor.cycleToPath (TransactionExecutor.java:201)
  at android.app.servertransaction.TransactionExecutor.executeLifecycleState (TransactionExecutor.java:173)
  at android.app.servertransaction.TransactionExecutor.execute (TransactionExecutor.java:97)
  at android.app.ActivityThread$H.handleMessage (ActivityThread.java:2144)
  at android.os.Handler.dispatchMessage (Handler.java:106)
  at android.os.Looper.loop (Looper.java:240)
  at android.app.ActivityThread.main (ActivityThread.java:8000)
  at java.lang.reflect.Method.invoke (Method.java)
  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run (RuntimeInit.java:603)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:947)

The error happens on devices on Android 11 and Android 12. Has anyone encountered this error or can you see where the error might be happening?


问:
ASP.Net Core Web application docker image failing with error -An error was encountered while handling the remote login
I am trying to test my ASP.Net core Web Application Docker Image locally but getting below error when trying docker run locally

```<code>warn: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[15]   '.AspNetCore.Correlation.AzureADOpenID.qCkwXxlpGF5ynTfvNW2Igg90nqvtstBG9eqgOeGn7Os' cookie not found.
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
     An unhandled exception has occurred while executing the request.
System.Exception: An error was encountered while handling the remote login.
---> System.Exception: Correlation failed.
  --- End of inner exception stack trace ---
  at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
  at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
  at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)
</code>```

I am using Https URL. Below is the app settings section:

```<code>   "Instance": "https://login.microsoftonline.com/",
   "Domain": "xxxxx",
   "TenantId": "xxxxx",
   "ClientId": "xxxxx",
   "CallbackPath": "/signin-oidc",
   "ClientSecret": "xxxxx"
 },
</code>```

When I run the docker from Visual Studio Debugger it seems logs still show this error but the page is not redirecting to signin-oidc and opening correctly .I tried commenting the CallbackPath section but still the site redirects to signin-oidc page and error out .

Here is the Startup.cs code

```<code>  public static ConnectionMultiplexer _redis;
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                    .AddAzureAD(options => Configuration.Bind("AzureAd", options));

                services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, (OpenIdConnectOptions options) =>
                {
                    options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                    options.Events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;

                });

                var redisConnectionString = Environment.GetEnvironmentVariable("CacheConnection");

                if (string.IsNullOrEmpty(redisConnectionString))
                {
                    throw new Exception($"App setting RTC:CacheConnection is either empty or missing");
                }

                _redis = ConnectionMultiplexer.Connect(redisConnectionString);
                services.AddHttpContextAccessor();
                services.AddControllersWithViews(options =>
                {
                    var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                    options.Filters.Add(new AuthorizeFilter(policy));
                }).AddJsonOptions(jsonOptions => jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null);

                // Add the Kendo UI services to the services container.
                services.AddKendo();
                services.AddRazorPages();
                services.AddScoped<ICacheService, CacheService>();
                services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_CONNECTIONSTRING"]);
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");

                app.UseHsts();
            }
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseHttpsRedirection();

            app.UseRouting();
            // Configure Kendo UI
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                endpoints.MapControllerRoute(name: "Ins",
                pattern: "Ins/{*Manage}",
                defaults: new { controller = "Ins", action = "Manage" });
            });s
        }
        private async static Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext ctx)
        {
            var claims = new ClaimsPrincipal();
            const string AZUREADGRAPH_RESOURCE = @"https://graph.windows.net/";
            var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);

            string userId = ctx.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
            var cache = new adowebhub.Controllers.RedisTokenCache(ctx.Options.ClientId, userId);
            var authContext = new AuthenticationContext(ctx.Options.Authority, cache);
            var result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                ctx.ProtocolMessage.Code, new Uri(ctx.TokenEndpointRequest.RedirectUri), credential, resource: AZUREADGRAPH_RESOURCE);
            ctx.HandleCodeRedemption(result.AccessToken, result.IdToken);
        }
</code>```

Below is the docker run command I use

```<code>docker run --env-file envFileWeb.txt -v c:/temp/aa/:/app/aa  -it --rm -p 8543:8080 --name aspnetcore_sample xxxxx.azurecr.io/xxxx:latest
</code>```

Please suggest how can I resolve this error .

Body:
I am trying to test my ASP.Net core Web Application Docker Image locally but getting below error when trying docker run locally

warn: Microsoft.AspNetCore.Authentication.OpenIdConnect.OpenIdConnectHandler[15]   '.AspNetCore.Correlation.AzureADOpenID.qCkwXxlpGF5ynTfvNW2Igg90nqvtstBG9eqgOeGn7Os' cookie not found.
fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[1]
     An unhandled exception has occurred while executing the request.
System.Exception: An error was encountered while handling the remote login.
---> System.Exception: Correlation failed.
  --- End of inner exception stack trace ---
  at Microsoft.AspNetCore.Authentication.RemoteAuthenticationHandler`1.HandleRequestAsync()
  at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
  at Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware.<Invoke>g__Awaited|6_0(ExceptionHandlerMiddleware middleware, HttpContext context, Task task)

I am using Https URL. Below is the app settings section:

   "Instance": "https://login.microsoftonline.com/",
   "Domain": "xxxxx",
   "TenantId": "xxxxx",
   "ClientId": "xxxxx",
   "CallbackPath": "/signin-oidc",
   "ClientSecret": "xxxxx"
 },

When I run the docker from Visual Studio Debugger it seems logs still show this error but the page is not redirecting to signin-oidc and opening correctly .I tried commenting the CallbackPath section but still the site redirects to signin-oidc page and error out .

Here is the Startup.cs code

  public static ConnectionMultiplexer _redis;
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            try
            {
                services.AddAuthentication(AzureADDefaults.AuthenticationScheme)
                    .AddAzureAD(options => Configuration.Bind("AzureAd", options));

                services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, (OpenIdConnectOptions options) =>
                {
                    options.ResponseType = OpenIdConnectResponseType.CodeIdToken;
                    options.Events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;

                });

                var redisConnectionString = Environment.GetEnvironmentVariable("CacheConnection");

                if (string.IsNullOrEmpty(redisConnectionString))
                {
                    throw new Exception($"App setting RTC:CacheConnection is either empty or missing");
                }

                _redis = ConnectionMultiplexer.Connect(redisConnectionString);
                services.AddHttpContextAccessor();
                services.AddControllersWithViews(options =>
                {
                    var policy = new AuthorizationPolicyBuilder()
                    .RequireAuthenticatedUser()
                    .Build();
                    options.Filters.Add(new AuthorizeFilter(policy));
                }).AddJsonOptions(jsonOptions => jsonOptions.JsonSerializerOptions.PropertyNamingPolicy = null);

                // Add the Kendo UI services to the services container.
                services.AddKendo();
                services.AddRazorPages();
                services.AddScoped<ICacheService, CacheService>();
                services.AddApplicationInsightsTelemetry(Configuration["APPINSIGHTS_CONNECTIONSTRING"]);
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");

                app.UseHsts();
            }
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseHttpsRedirection();

            app.UseRouting();
            // Configure Kendo UI
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                endpoints.MapRazorPages();
                endpoints.MapControllerRoute(name: "Ins",
                pattern: "Ins/{*Manage}",
                defaults: new { controller = "Ins", action = "Manage" });
            });s
        }
        private async static Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext ctx)
        {
            var claims = new ClaimsPrincipal();
            const string AZUREADGRAPH_RESOURCE = @"https://graph.windows.net/";
            var credential = new ClientCredential(ctx.Options.ClientId, ctx.Options.ClientSecret);

            string userId = ctx.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
            var cache = new adowebhub.Controllers.RedisTokenCache(ctx.Options.ClientId, userId);
            var authContext = new AuthenticationContext(ctx.Options.Authority, cache);
            var result = await authContext.AcquireTokenByAuthorizationCodeAsync(
                ctx.ProtocolMessage.Code, new Uri(ctx.TokenEndpointRequest.RedirectUri), credential, resource: AZUREADGRAPH_RESOURCE);
            ctx.HandleCodeRedemption(result.AccessToken, result.IdToken);
        }

Below is the docker run command I use

docker run --env-file envFileWeb.txt -v c:/temp/aa/:/app/aa  -it --rm -p 8543:8080 --name aspnetcore_sample xxxxx.azurecr.io/xxxx:latest

Please suggest how can I resolve this error .


问:
Convert blank node in URI in sparql
I would like to convert blank nodes into URIs using a SPARQL query. Imagine something like:

```<code>_:N58f332639cbd46d6a5ec9410e5d875a7 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.org/WebSite> .
_:N3b2eed756126458582bba185ab0fdb0b <http://schema.org/name> "Chefkoch.de" .
_:N3b2eed756126458582bba185ab0fdb0b <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.org/Organization> .
</code>```

then I would like a query like:

```<code>SELECT (func(?s) as ?s1) ?p ?o where {
    ?s ?p ?o
}
</code>```

and func should convert the blank nodes in some URIs.

I find it quite a frequent use case but could not find a solution ....

Title: Convert blank node in URI in sparql

Body:
I would like to convert blank nodes into URIs using a SPARQL query. Imagine something like:

_:N58f332639cbd46d6a5ec9410e5d875a7 <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.org/WebSite> .
_:N3b2eed756126458582bba185ab0fdb0b <http://schema.org/name> "Chefkoch.de" .
_:N3b2eed756126458582bba185ab0fdb0b <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://schema.org/Organization> .

then I would like a query like:

SELECT (func(?s) as ?s1) ?p ?o where {
    ?s ?p ?o
}

and func should convert the blank nodes in some URIs.

I find it quite a frequent use case but could not find a solution ....


问:
Launching a second window upon a button press - tkinter
Im trying to set up a log in window in a simple app i´m making. On this app you have a username and a password to access to your profile, however, i cant manage to get the profile window to be opened.
More specifically i have a sign in button coded as:

```<code>register_button = Button(center_frame, padx=7, pady=2, text="Log In", font=(typeface, 10), bg=light_grey, fg="black", command =log)
</code>```

log_in is my well log in function which checks the password and username to see if they are already registered and to pull up their user data:

```<code>def log():
    uname = entrylogun.get()
    log_pass = entrylogpa.get()
    hash1 = pbkdf2_sha256.hash(str(log_pass), rounds=1, salt_size=0)
    log_pass = 0
    log_complete = False
    with open("users.txt", "r") as users:
        if (uname + "" + hash1 + "") not in users.read():
            tkinter.messagebox.showinfo("Verification Error",
                                        "The Password and Username combination "
                                        "\nentered is not valid, please try again")
        else:
            log_complete = True
</code>```

then, i have later on:

```<code>if log_complete :
    profile_logged = open("" + uname + ".txt", "r")
    root1 = Tk()
    user = str(entrylogun.get())
    profile = open("" + uname + ".txt", "r+")
    root1.title("FedApp")
</code>```

and it continues on and on...

but this wont open my second window upon pressing the log in button.

I have managed to get the second profile window to open but only by placing all the set up code for it inside the function and i feel that placing that much code inside a function is not propper.

basically im stuck at coding everything about the window there in the function, such as:

```<code>def log():
    global uname, log_pass, hash1, profile_logged, log_complete
    uname = entrylogun.get()
    log_pass = entrylogpa.get()
    hash1 = pbkdf2_sha256.hash(str(log_pass), rounds=1, salt_size=0)
    log_pass = 0
    log_complete = False
    with open("users.txt", "r") as users:
        if (uname + "" + hash1 + "") not in users.read():
            tkinter.messagebox.showinfo("Verification Error",
                                        "The Password and Username combination "
                                        "\nentered is not valid, please try again")
        else:
            log_complete = True
            profile_logged = open("" + uname + ".txt", "r")
            root1 = Tk()
            user = str(entrylogun.get())
            profile = open("" + uname + ".txt", "r+")
            root1.title("FedApp")
            root1.geometry("600x600+534+70")
</code>```

any ideas?

ive set up a minimum reproducible example:

working as it should (click on the small button):

```<code>from tkinter import *
import tkinter.messagebox
from passlib.hash import pbkdf2_sha256

ventalalog = Tk()
ventalalog.title("FedeApp")
ventalalog.geometry("300x530+534+70")
background_color = "#36454F"
ventalalog.configure(bg=background_color)

log_complete = None
log_in_launch = None

def log():
    global profile_logged, log_complete
    log_complete = True
    if log_complete == False:
        tkinter.messagebox.showinfo("Verification Error",
                                    "The Password and Username combination "
                                    "\nentered is not valid, please try again")
    else:
        root1 = Tk()
        root1.title("FedApp")
        root1.geometry("600x600+534+70")

register_button = Button(command=log)
register_button.pack()

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

NOT working as it should:

```<code>from tkinter import *
import tkinter.messagebox

ventalalog = Tk()
ventalalog.title("FedeApp")
ventalalog.geometry("300x530+534+70")
background_color = "#36454F"
ventalalog.configure(bg=background_color)

log_complete = None
log_in_launch = None

def log():
    global log_complete, log_in_launch
    log_complete = True
    if log_complete == False :
        tkinter.messagebox.showinfo("Verification Error",
                                        "The Password and Username combination "
                                        "\nentered is not valid, please try again")
    else:
        log_in_launch = True

register_button = Button(command =log)
register_button.pack()

if log_in_launch :
    root1 = Tk()
    root1.title("FedApp")
    root1.geometry("600x600+534+70")

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

Body:
Im trying to set up a log in window in a simple app i´m making. On this app you have a username and a password to access to your profile, however, i cant manage to get the profile window to be opened.
More specifically i have a sign in button coded as:

register_button = Button(center_frame, padx=7, pady=2, text="Log In", font=(typeface, 10), bg=light_grey, fg="black", command =log)

log_in is my well log in function which checks the password and username to see if they are already registered and to pull up their user data:

def log():
    uname = entrylogun.get()
    log_pass = entrylogpa.get()
    hash1 = pbkdf2_sha256.hash(str(log_pass), rounds=1, salt_size=0)
    log_pass = 0
    log_complete = False
    with open("users.txt", "r") as users:
        if (uname + "" + hash1 + "") not in users.read():
            tkinter.messagebox.showinfo("Verification Error",
                                        "The Password and Username combination "
                                        "\nentered is not valid, please try again")
        else:
            log_complete = True

then, i have later on:

if log_complete :
    profile_logged = open("" + uname + ".txt", "r")
    root1 = Tk()
    user = str(entrylogun.get())
    profile = open("" + uname + ".txt", "r+")
    root1.title("FedApp")

and it continues on and on...

but this wont open my second window upon pressing the log in button.

I have managed to get the second profile window to open but only by placing all the set up code for it inside the function and i feel that placing that much code inside a function is not propper.

basically im stuck at coding everything about the window there in the function, such as:

def log():
    global uname, log_pass, hash1, profile_logged, log_complete
    uname = entrylogun.get()
    log_pass = entrylogpa.get()
    hash1 = pbkdf2_sha256.hash(str(log_pass), rounds=1, salt_size=0)
    log_pass = 0
    log_complete = False
    with open("users.txt", "r") as users:
        if (uname + "" + hash1 + "") not in users.read():
            tkinter.messagebox.showinfo("Verification Error",
                                        "The Password and Username combination "
                                        "\nentered is not valid, please try again")
        else:
            log_complete = True
            profile_logged = open("" + uname + ".txt", "r")
            root1 = Tk()
            user = str(entrylogun.get())
            profile = open("" + uname + ".txt", "r+")
            root1.title("FedApp")
            root1.geometry("600x600+534+70")

any ideas?

ive set up a minimum reproducible example:

working as it should (click on the small button):

from tkinter import *
import tkinter.messagebox
from passlib.hash import pbkdf2_sha256

ventalalog = Tk()
ventalalog.title("FedeApp")
ventalalog.geometry("300x530+534+70")
background_color = "#36454F"
ventalalog.configure(bg=background_color)

log_complete = None
log_in_launch = None

def log():
    global profile_logged, log_complete
    log_complete = True
    if log_complete == False:
        tkinter.messagebox.showinfo("Verification Error",
                                    "The Password and Username combination "
                                    "\nentered is not valid, please try again")
    else:
        root1 = Tk()
        root1.title("FedApp")
        root1.geometry("600x600+534+70")

register_button = Button(command=log)
register_button.pack()

ventalalog.mainloop()

NOT working as it should:

from tkinter import *
import tkinter.messagebox

ventalalog = Tk()
ventalalog.title("FedeApp")
ventalalog.geometry("300x530+534+70")
background_color = "#36454F"
ventalalog.configure(bg=background_color)

log_complete = None
log_in_launch = None

def log():
    global log_complete, log_in_launch
    log_complete = True
    if log_complete == False :
        tkinter.messagebox.showinfo("Verification Error",
                                        "The Password and Username combination "
                                        "\nentered is not valid, please try again")
    else:
        log_in_launch = True

register_button = Button(command =log)
register_button.pack()

if log_in_launch :
    root1 = Tk()
    root1.title("FedApp")
    root1.geometry("600x600+534+70")

ventalalog.mainloop()


问:
Loading iframe component and it's font causing layout shift
I need a help with iframe's font is causing FOUT.
I have a web page with a font (a) and fallback font(b). This web page also has a custom component loaded via iframe with a font (a). Both website and th iframe component share the same font (a).

When the website is loaded with its fallback font(b) it causes FOUT when it loads the iframe component and downloads the font (a). Shifting all the text on the website to its original font (a).
network requests

I have tried solving the problem using font-display properties but it did not fix the problem.

Is there any way I can prevent the browser from reloading the font for the entire page and only applying that font to the iframe component?


问:
WebSocketServer on ESP32 DevkitC V4 Issue
I'm developing a simple mobile robot controlled by a custom web application hosted on ESP32. The communication protocol that is used is WebSocket. I had a code that was working but after some break, I can't make it run properly again... most likely I changed something accidentally or I don't understand some code parts. The logs in SerialPort suggest that the program connects to the WiFi, it gets data (HTML files) from Flash memory and the server is started under some particular IP. However, when I try to access the server IP nothing is given in response. I pasted my .ino code down below, I can also add HTML and .js files if needed. The data folder is ofc uploaded to the flash memory. For now I just want to host that page on a server and access it, the code is not supposed to do anything else for now. I'm going crazy because of that issue. Does anyone see some mistake or misconception?

```<code>#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "SPIFFS.h"
#include <Arduino_JSON.h>

// Network credentials
const char *ssid = "mySSID";
const char *password = "myCredentials";

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

// Create a WebSocket object
AsyncWebSocket ws("/ws");

// Placeholder for messages from the clients
String message = "";

void initFS()
{
  if (!SPIFFS.begin())
  {
    Serial.println("An error has occurred while mounting SPIFFS");
  }
  else
  {
    Serial.println("SPIFFS mounted successfully");
  }
}

// Initialise WiFi
void initWiFi()
{
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

void handleWebSocketMessage(void *arg, uint8_t *data, size_t len)
{
  AwsFrameInfo *info = (AwsFrameInfo *)arg;
  if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT)
  {
    data[len] = 0;
    message = (char *)data;
  }
}

void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len)
{
  switch (type)
  {
  case WS_EVT_CONNECT:
    Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
    break;
  case WS_EVT_DISCONNECT:
    Serial.printf("WebSocket client #%u disconnected\n", client->id());
    break;
  case WS_EVT_DATA:
    handleWebSocketMessage(arg, data, len);
    break;
  case WS_EVT_PONG:
  case WS_EVT_ERROR:
    break;
  }
}

void initWebSocket()
{
  Serial.println("I'm Inside!");
  ws.onEvent(onEvent);
  server.addHandler(&ws);
}

void setup()
{
  Serial.begin(115200);

  Serial.println("Initialising SPIFFS");
  initFS();

  Serial.println("Initialising WiFi");
  initWiFi();

  Serial.println("Initialising WebSocket");
  initWebSocket();

  // Web Server Root URL
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
            { request->send(SPIFFS, "/index.html", "text/html"); });

  server.serveStatic("/", SPIFFS, "/");

  // Start server
  server.begin();

  Serial.println("Starting Server");
}

void loop()
{
  ws.cleanupClients();
}
</code>```

Update:
I created a different, very simple sketch just to have a look if it might work and it doesn't. It connects to the WiFi according to the logs but I'm getting timed out when I try to access the server IP address Down below is the code that I used for the second sketch:

```<code>#include <WiFi.h>
#include <WebServer.h>

//SSID and Password to the local WiFi
const char* ssid = "ssid";
const char* password = "password";

WebServer server(80);

String webpage = "<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>Document</title></head><body> <h1> Test! </h1></body></html>";

//Function to initialise the connection with local WiFi
void InitWiFi()
{
  WiFi.begin(ssid, password);
  Serial.println("Trying to connect to the WiFi with SSID: " + String(ssid) + "..");

  while(WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
}
  Serial.println("Connected to the WiFi with the IP address: ");
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);
  InitWiFi();

  //Initialising WebServer
  server.on("/", []() {
  server.send(200, "text\html", webpage);
  });

  delay(1000);
  server.begin();
  Serial.println("Server started");

}

void loop() {
  server.handleClient();
}
</code>```

Body:
I'm developing a simple mobile robot controlled by a custom web application hosted on ESP32. The communication protocol that is used is WebSocket. I had a code that was working but after some break, I can't make it run properly again... most likely I changed something accidentally or I don't understand some code parts. The logs in SerialPort suggest that the program connects to the WiFi, it gets data (HTML files) from Flash memory and the server is started under some particular IP. However, when I try to access the server IP nothing is given in response. I pasted my .ino code down below, I can also add HTML and .js files if needed. The data folder is ofc uploaded to the flash memory. For now I just want to host that page on a server and access it, the code is not supposed to do anything else for now. I'm going crazy because of that issue. Does anyone see some mistake or misconception?

#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "SPIFFS.h"
#include <Arduino_JSON.h>

// Network credentials
const char *ssid = "mySSID";
const char *password = "myCredentials";

// Create AsyncWebServer object on port 80
AsyncWebServer server(80);

// Create a WebSocket object
AsyncWebSocket ws("/ws");

// Placeholder for messages from the clients
String message = "";

void initFS()
{
  if (!SPIFFS.begin())
  {
    Serial.println("An error has occurred while mounting SPIFFS");
  }
  else
  {
    Serial.println("SPIFFS mounted successfully");
  }
}

// Initialise WiFi
void initWiFi()
{
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.print("Connecting to WiFi ..");
  while (WiFi.status() != WL_CONNECTED)
  {
    Serial.print('.');
    delay(1000);
  }
  Serial.println(WiFi.localIP());
}

void handleWebSocketMessage(void *arg, uint8_t *data, size_t len)
{
  AwsFrameInfo *info = (AwsFrameInfo *)arg;
  if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT)
  {
    data[len] = 0;
    message = (char *)data;
  }
}

void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len)
{
  switch (type)
  {
  case WS_EVT_CONNECT:
    Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
    break;
  case WS_EVT_DISCONNECT:
    Serial.printf("WebSocket client #%u disconnected\n", client->id());
    break;
  case WS_EVT_DATA:
    handleWebSocketMessage(arg, data, len);
    break;
  case WS_EVT_PONG:
  case WS_EVT_ERROR:
    break;
  }
}

void initWebSocket()
{
  Serial.println("I'm Inside!");
  ws.onEvent(onEvent);
  server.addHandler(&ws);
}

void setup()
{
  Serial.begin(115200);

  Serial.println("Initialising SPIFFS");
  initFS();

  Serial.println("Initialising WiFi");
  initWiFi();

  Serial.println("Initialising WebSocket");
  initWebSocket();

  // Web Server Root URL
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
            { request->send(SPIFFS, "/index.html", "text/html"); });

  server.serveStatic("/", SPIFFS, "/");

  // Start server
  server.begin();

  Serial.println("Starting Server");
}

void loop()
{
  ws.cleanupClients();
}

Update:
I created a different, very simple sketch just to have a look if it might work and it doesn't. It connects to the WiFi according to the logs but I'm getting timed out when I try to access the server IP address Down below is the code that I used for the second sketch:

#include <WiFi.h>
#include <WebServer.h>

//SSID and Password to the local WiFi
const char* ssid = "ssid";
const char* password = "password";

WebServer server(80);

String webpage = "<!DOCTYPE html> <meta charset='UTF-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>Document</title>
 Test!
";

//Function to initialise the connection with local WiFi
void InitWiFi()
{
  WiFi.begin(ssid, password);
  Serial.println("Trying to connect to the WiFi with SSID: " + String(ssid) + "..");

  while(WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
}
  Serial.println("Connected to the WiFi with the IP address: ");
  Serial.println(WiFi.localIP());
}

void setup() {
  Serial.begin(115200);
  InitWiFi();

  //Initialising WebServer
  server.on("/", []() {
  server.send(200, "text\html", webpage);
  });

  delay(1000);
  server.begin();
  Serial.println("Server started");

}

void loop() {
  server.handleClient();
}


问:
How can I add another source to java_test_suite?
This is how I'm using the java_test_suite:

(https://github.com/bazel-contrib/rules_jvm#java_test_suite)

```<code>java_test_suite(
name = "everything-tests",
srcs = glob(["src/test/java/**/*.java"]),
runner = "junit5",
test_suffixes = ["Tests.java"],
runtime_deps = JUNIT5_DEPS,
deps = [
    ":everything",
    ...
] + deps,
)
</code>```

However, what it is doing is that java_test_suite is iterating over each srcs and creating a java_test for it. The problem becomes when one of my tests has a dependency on another test class.

For example, I have a test class which extends another abstract test class like so:

```<code>public class CustomTimerTests extends BaseTimerTests
</code>```

But CustomTimerTests is failing as it is not able to find BaseTimerTests because java_test_suite does not let me add BaseTimerTests as one of the sources for CustomTimerTests.

Anyone knows how to fix it?

Body:
This is how I'm using the java_test_suite:

(https://github.com/bazel-contrib/rules_jvm#java_test_suite)

java_test_suite(
name = "everything-tests",
srcs = glob(["src/test/java/**/*.java"]),
runner = "junit5",
test_suffixes = ["Tests.java"],
runtime_deps = JUNIT5_DEPS,
deps = [
    ":everything",
    ...
] + deps,
)

However, what it is doing is that java_test_suite is iterating over each srcs and creating a java_test for it. The problem becomes when one of my tests has a dependency on another test class.

For example, I have a test class which extends another abstract test class like so:

public class CustomTimerTests extends BaseTimerTests

But CustomTimerTests is failing as it is not able to find BaseTimerTests because java_test_suite does not let me add BaseTimerTests as one of the sources for CustomTimerTests.

Anyone knows how to fix it?


问:
High Spool Issue
When I run this Update SQL statement it causes a load on the system query taking a High Spool of 2.5TB. PJI is also high, I have already collected stats on it.</p>
```<code>UPDATE  PMP_CBS.RPT_BILLING_DETAIL_FINAL
    FROM
(
    SEL ACCT_ID,
        Media_type_cd
        FROM PMP_VEW_CBS.RPT_BILLING_DETAIL_FINAL A LEFT JOIN PMP_AVEW.FCT_SUBS_ACCT  B  -- PMP_AVEW.FCT_SUBS_ACCT .. This DB and Table doesnt exist
ON CAST(A.ACCT_ID AS VARCHAR(50))=CAST(B.BILLING_ACCT_ID AS VARCHAR(50))
        WHERE BILLING_MONTH = ADD_MONTHS(CURRENT_DATE - EXTRACT(DAY
        FROM CURRENT_DATE), 0 )(FORMAT 'YYYYMM')(CHAR(06))
            AND  Media_type_cd IS NOT NULL
QUALIFY ROW_NUMBER() OVER (PARTITION BY ACCT_ID
        ORDER BY ACCT_ID)=1
        GROUP BY 1,
            2
) A
SET Media_type =A.Media_type_cd
    WHERE PMP_VEW_CBS.RPT_BILLING_DETAIL_FINAL.ACCT_ID=A.ACCT_ID
        AND  PMP_VEW_CBS.RPT_BILLING_DETAIL_FINAL.BILLING_MONTH = ADD_MONTHS(CURRENT_DATE - EXTRACT(DAY
    FROM CURRENT_DATE), 0 )(FORMAT 'YYYYMM')(CHAR(06));
</code>```

Title: High Spool Issue

Body:
When I run this Update SQL statement it causes a load on the system query taking a High Spool of 2.5TB. PJI is also high, I have already collected stats on it.

UPDATE  PMP_CBS.RPT_BILLING_DETAIL_FINAL
    FROM
(
    SEL ACCT_ID,
        Media_type_cd
        FROM PMP_VEW_CBS.RPT_BILLING_DETAIL_FINAL A LEFT JOIN PMP_AVEW.FCT_SUBS_ACCT  B  -- PMP_AVEW.FCT_SUBS_ACCT .. This DB and Table doesnt exist
ON CAST(A.ACCT_ID AS VARCHAR(50))=CAST(B.BILLING_ACCT_ID AS VARCHAR(50))
        WHERE BILLING_MONTH = ADD_MONTHS(CURRENT_DATE - EXTRACT(DAY
        FROM CURRENT_DATE), 0 )(FORMAT 'YYYYMM')(CHAR(06))
            AND  Media_type_cd IS NOT NULL
QUALIFY ROW_NUMBER() OVER (PARTITION BY ACCT_ID
        ORDER BY ACCT_ID)=1
        GROUP BY 1,
            2
) A
SET Media_type =A.Media_type_cd
    WHERE PMP_VEW_CBS.RPT_BILLING_DETAIL_FINAL.ACCT_ID=A.ACCT_ID
        AND  PMP_VEW_CBS.RPT_BILLING_DETAIL_FINAL.BILLING_MONTH = ADD_MONTHS(CURRENT_DATE - EXTRACT(DAY
    FROM CURRENT_DATE), 0 )(FORMAT 'YYYYMM')(CHAR(06));


问:
VBA Run-time Error 52 popping up inconsistently
So, the below code works just fine on my end.  But, if I send the excel file containing the code below to a different person, they get the Run-time Error 52.  I've tried several different iterations of the code below, but all keep coming up with the same error.

UPDATE: Error 52 Resolved, but error 1004 now occurs when reading the line containing the objConnection.Refresh statement.

I'm curious to learn what situations would cause something to work fine on my end but not on someone else's PC, and how best to circumvent this issue.  Code below:

```<code>Sub Download_CSV()

Dim myURL As String
Dim PathExcel As String
Dim csvfilenamefull As String

PathExcel = Application.ActiveWorkbook.Path
csvfilenamefull = PathExcel & "\SharepointData.xlsx"

'Remove File if already there
If Dir(csvfilenamefull) <> "" Then
  VBA.SetAttr csvfilenamefull, vbNormal ' remove any file attributes (e.g. read-only) that would block the kill command
  VBA.Kill csvfilenamefull ' delete the file
End If

myURL = "https://company.sharepoint.com/sites/Shared%20Documents/Data.xlsx"

Workbooks.Open (myURL)

ActiveWorkbook.SaveAs filename:=csvfilenamefull, _
        FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

'Run check to ensure the opened file has finished connect to online database
    For Each objConnection In ActiveWorkbook.Connections
        'Get current background-refresh value
        bBackground = objConnection.OLEDBConnection.BackgroundQuery

        'Temporarily disable background-refresh
        objConnection.OLEDBConnection.BackgroundQuery = False

        'Refresh this connection
        objConnection.Refresh

        'Set background-refresh value back to original value
        objConnection.OLEDBConnection.BackgroundQuery = bBackground
    Next

End Sub
</code>```

I simply tried various bits of code from different recommendations on this site (all of which worked successfully on my computer), but continue to give the other party the Run Time Error 52.

Body:
So, the below code works just fine on my end.  But, if I send the excel file containing the code below to a different person, they get the Run-time Error 52.  I've tried several different iterations of the code below, but all keep coming up with the same error.

UPDATE: Error 52 Resolved, but error 1004 now occurs when reading the line containing the objConnection.Refresh statement.

I'm curious to learn what situations would cause something to work fine on my end but not on someone else's PC, and how best to circumvent this issue.  Code below:

Sub Download_CSV()

Dim myURL As String
Dim PathExcel As String
Dim csvfilenamefull As String

PathExcel = Application.ActiveWorkbook.Path
csvfilenamefull = PathExcel & "\SharepointData.xlsx"

'Remove File if already there
If Dir(csvfilenamefull) <> "" Then
  VBA.SetAttr csvfilenamefull, vbNormal ' remove any file attributes (e.g. read-only) that would block the kill command
  VBA.Kill csvfilenamefull ' delete the file
End If

myURL = "https://company.sharepoint.com/sites/Shared%20Documents/Data.xlsx"

Workbooks.Open (myURL)

ActiveWorkbook.SaveAs filename:=csvfilenamefull, _
        FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False

'Run check to ensure the opened file has finished connect to online database
    For Each objConnection In ActiveWorkbook.Connections
        'Get current background-refresh value
        bBackground = objConnection.OLEDBConnection.BackgroundQuery

        'Temporarily disable background-refresh
        objConnection.OLEDBConnection.BackgroundQuery = False

        'Refresh this connection
        objConnection.Refresh

        'Set background-refresh value back to original value
        objConnection.OLEDBConnection.BackgroundQuery = bBackground
    Next

End Sub

I simply tried various bits of code from different recommendations on this site (all of which worked successfully on my computer), but continue to give the other party the Run Time Error 52.


问:
How change the url of an image within an html page in a django project?
I'm new to Django. I have 2 images, one for NP environment and one for Production environment. I have to make each image stay in its given environment. This is to be done in an html page within Django.
This html page is the body of an email.

can you help me?

The image looks like below. And I want to control her link according to the environment she is in

```<code><td bgcolor="#fff" align="right" style="padding: 21px 19px 18px">
                            <img alt="Teste"
                                src="https://.../mail/logo.png"
                                width="210px" />
</td>
</code>```


问:
How to speed up Function in powershell
I am getting object ids from function. where $objects has 1000 entries. Below is part of main script. Just to get object ids for 1000 OBJECTS running for hours. If $objects count under 10 it runs quick. Is there way I can speed up below function to process 1000 $objects ???

```<code>function get_nodes($obj){

        if($obj.protectionSource.name -eq $objectName){
            $global:_object_id = $obj.protectionSource.id
            $global:object = $obj.protectionSource.name
            #break
        }
        if($obj.name -eq $objectName){
            $global:_object_id = $obj.id
            $global:object = $obj.name
           # break
        }
        if($obj.PSObject.Properties['nodes']){
            foreach($node in $obj.nodes){
                if($null -eq $global:_object_id){
                    get_nodes $node
                }
            }
        }
        if($obj.PSObject.Properties['applicationNodes']){
            foreach($node in $obj.applicationNodes){
                if($null -eq $global:_object_id){
                    get_nodes $node
                }
            }
        }
    }

    foreach($source in $sources){
        if($null -eq $global:_object_id){
            get_nodes $source
        }
    }
    return $global:_object_id
}

foreach($object in $objects){   ###2
# get object ID
$objectId = getObjectId $object
                            }
</code>```

$sources may have 1000 or more entries. below is one entry. $objects are literally server names ( server1 , server2 etc).

```<code> PS C:\anil\scripts> $sources[0]|ConvertTo-Json
{
    "nodes":  [
                  {
                      "nodes":  "                    ",
                      "protectionSource":  "@{id=2; parentId=1; name=Datacenters; environment=kVMware; vmWareProtectionSource=}",
                      "protectedSourcesSummary":  "",
                      "unprotectedSourcesSummary":  "",
                      "logicalSize":  0
                  }
              ],
    "protectionSource":  {
                             "id":  1,
                             "name":  "wpc1uv00vvc.ent.ad.ntrs.com",
                             "environment":  "kVMware",
                             "vmWareProtectionSource":  {
                                                            "type":  "kVCenter",
                                                            "name":  "wpc1uv00vvc.ent.ad.ntrs.com",
                                                            "id":  "@{uuid=683FECB1-A27E-447A-8037-0E1B8DA4BE7A}",
                                                            "version":  "VMware vCenter Server 6.0.0 build-7462484",
                                                            "isVmcEntity":  false
                                                        }
                         },
    "protectedSourcesSummary":  [
                                    {
                                        "environment":  "kVMware"
                                    }
                                ],
    "unprotectedSourcesSummary":  [
                                      {
                                          "environment":  "kVMware",
                                          "leavesCount":  24,
                                          "totalLogicalSize":  1224065679360
                                      }
                                  ],
    "registrationInfo":  {
                             "accessInfo":  {
                                                "id":  3953,
                                                "version":  0,
                                                "environment":  "kVMware",
                                                "endpoint":  "wpc1uv00vvc"
                                            },
                             "throttlingPolicy":  {
                                                      "isEnabled":  false,
                                                      "enforceMaxStreams":  false
                                                  },
                             "registrationTimeUsecs":  1585846901734416,
                             "refreshTimeUsecs":  1670355941177325,
                             "refreshErrorMessage":  "Failed to connect to wpc1uv00vvc. Error: SOAP 1.1 fault: SOAP-ENV:Client[no subcode] \"System error\" Detail: getadd
rinfo failed in tcp_connect(). Connectivity status: Connection to wpc1uv00vvc:443 resulted in : Failed to resolve server name with error: System error",
                             "authenticationStatus":  "kFinished",
                             "username":  "ent\\sys-poc-cohesity"
                         }
}

PS C:\anil\scripts>
</code>```

Title: How to speed up Function in powershell

Body:
I am getting object ids from function. where $objects has 1000 entries. Below is part of main script. Just to get object ids for 1000 OBJECTS running for hours. If $objects count under 10 it runs quick. Is there way I can speed up below function to process 1000 $objects ???

function get_nodes($obj){

        if($obj.protectionSource.name -eq $objectName){
            $global:_object_id = $obj.protectionSource.id
            $global:object = $obj.protectionSource.name
            #break
        }
        if($obj.name -eq $objectName){
            $global:_object_id = $obj.id
            $global:object = $obj.name
           # break
        }
        if($obj.PSObject.Properties['nodes']){
            foreach($node in $obj.nodes){
                if($null -eq $global:_object_id){
                    get_nodes $node
                }
            }
        }
        if($obj.PSObject.Properties['applicationNodes']){
            foreach($node in $obj.applicationNodes){
                if($null -eq $global:_object_id){
                    get_nodes $node
                }
            }
        }
    }

    foreach($source in $sources){
        if($null -eq $global:_object_id){
            get_nodes $source
        }
    }
    return $global:_object_id
}

foreach($object in $objects){   ###2
# get object ID
$objectId = getObjectId $object
                            }

$sources may have 1000 or more entries. below is one entry. $objects are literally server names ( server1 , server2 etc).

 PS C:\anil\scripts> $sources[0]|ConvertTo-Json
{
    "nodes":  [
                  {
                      "nodes":  "                    ",
                      "protectionSource":  "@{id=2; parentId=1; name=Datacenters; environment=kVMware; vmWareProtectionSource=}",
                      "protectedSourcesSummary":  "",
                      "unprotectedSourcesSummary":  "",
                      "logicalSize":  0
                  }
              ],
    "protectionSource":  {
                             "id":  1,
                             "name":  "wpc1uv00vvc.ent.ad.ntrs.com",
                             "environment":  "kVMware",
                             "vmWareProtectionSource":  {
                                                            "type":  "kVCenter",
                                                            "name":  "wpc1uv00vvc.ent.ad.ntrs.com",
                                                            "id":  "@{uuid=683FECB1-A27E-447A-8037-0E1B8DA4BE7A}",
                                                            "version":  "VMware vCenter Server 6.0.0 build-7462484",
                                                            "isVmcEntity":  false
                                                        }
                         },
    "protectedSourcesSummary":  [
                                    {
                                        "environment":  "kVMware"
                                    }
                                ],
    "unprotectedSourcesSummary":  [
                                      {
                                          "environment":  "kVMware",
                                          "leavesCount":  24,
                                          "totalLogicalSize":  1224065679360
                                      }
                                  ],
    "registrationInfo":  {
                             "accessInfo":  {
                                                "id":  3953,
                                                "version":  0,
                                                "environment":  "kVMware",
                                                "endpoint":  "wpc1uv00vvc"
                                            },
                             "throttlingPolicy":  {
                                                      "isEnabled":  false,
                                                      "enforceMaxStreams":  false
                                                  },
                             "registrationTimeUsecs":  1585846901734416,
                             "refreshTimeUsecs":  1670355941177325,
                             "refreshErrorMessage":  "Failed to connect to wpc1uv00vvc. Error: SOAP 1.1 fault: SOAP-ENV:Client[no subcode] \"System error\" Detail: getadd
rinfo failed in tcp_connect(). Connectivity status: Connection to wpc1uv00vvc:443 resulted in : Failed to resolve server name with error: System error",
                             "authenticationStatus":  "kFinished",
                             "username":  "ent\\sys-poc-cohesity"
                         }
}

PS C:\anil\scripts>


问:
Get url for aws ecs cluster
I’m trying to deploy a docker compose mern stack app with aws ecs.
I finally got the cluster active with 3 services (node backend, react front and mongodb) using the docker compose interface with

```<code>docker context use myecscontext
docker compose up
</code>```

Now how do I view the front end via a url?
I want to be proficient in deploying websites for freelance work, is this the way it's done?
I noticed there is  a way to define an ip adress in docker-compose.yaml, would that be the way? basically like this:

```<code>x-aws-loadbalancer:
   IpAddressType: "ipv4"
   VpcId: "vpc-123456"
   LoadBalancerArn: "arn:aws:elasticloadbalancing:us-east-
   1:1234567890:loadbalancer/app/myloadbalancer/123abcd456"
   DNSName: "myloadbalancer-123456.us-east-
   1.elb.amazonaws.com"
</code>```

where the DNSName is the url?
*edit i found the dns name in load balancer page on aws console but it won't load, this is my docker-compose.ymal maybe something is wrong here

```<code> version: "3.7"

 services:
   server:
       build:
       context: ./server
       dockerfile: Dockerfile
     image: anthonyss09/thebikeshop:bike-server
     container_name: myapp-node-server
     logging:
       driver: awslogs
       options:
         awslogs-region: us-east-1
         awslogs-group: bike-server-container
     command: /usr/src/app/node_modules/.bin/nodemon server.js
     volumes:
       - my-data:/user/src/app
     ports:
       - "5000:5000"
     depends_on:
       - mongo
     env_file: ./server/.env
     environment:
       - NODE_ENV=development
     networks:
       - app-network
   mongo:
     image: anthonyss09/thebikeshop:bike-mongo
     volumes:
       - my-data:/data/db
     ports:
       - "27017:27017"
     networks:
       - app-network
   client:
     build:
       context: ./client
       dockerfile: Dockerfile
     image: anthonyss09/thebikeshop:bike-client
     container_name: myapp-react-client
     logging:
       driver: awslogs
       options:
         awslogs-region: us-east-1
         awslogs-group: bike-client-container
     command: npm run build
     volumes:
       - my-data:/user/app
     depends_on:
       - server
     ports:
       - "80:80"
     networks:
       - app-network

 networks:
   app-network:
     driver: bridge

 volumes:
   my-data:
   node_modules:
   web-root:
     driver: local
</code>```

Title: Get url for aws ecs cluster

Body:
I’m trying to deploy a docker compose mern stack app with aws ecs.
I finally got the cluster active with 3 services (node backend, react front and mongodb) using the docker compose interface with

docker context use myecscontext
docker compose up

Now how do I view the front end via a url?
I want to be proficient in deploying websites for freelance work, is this the way it's done?
I noticed there is  a way to define an ip adress in docker-compose.yaml, would that be the way? basically like this:

x-aws-loadbalancer:
   IpAddressType: "ipv4"
   VpcId: "vpc-123456"
   LoadBalancerArn: "arn:aws:elasticloadbalancing:us-east-
   1:1234567890:loadbalancer/app/myloadbalancer/123abcd456"
   DNSName: "myloadbalancer-123456.us-east-
   1.elb.amazonaws.com"

where the DNSName is the url?
*edit i found the dns name in load balancer page on aws console but it won't load, this is my docker-compose.ymal maybe something is wrong here

 version: "3.7"

 services:
   server:
       build:
       context: ./server
       dockerfile: Dockerfile
     image: anthonyss09/thebikeshop:bike-server
     container_name: myapp-node-server
     logging:
       driver: awslogs
       options:
         awslogs-region: us-east-1
         awslogs-group: bike-server-container
     command: /usr/src/app/node_modules/.bin/nodemon server.js
     volumes:
       - my-data:/user/src/app
     ports:
       - "5000:5000"
     depends_on:
       - mongo
     env_file: ./server/.env
     environment:
       - NODE_ENV=development
     networks:
       - app-network
   mongo:
     image: anthonyss09/thebikeshop:bike-mongo
     volumes:
       - my-data:/data/db
     ports:
       - "27017:27017"
     networks:
       - app-network
   client:
     build:
       context: ./client
       dockerfile: Dockerfile
     image: anthonyss09/thebikeshop:bike-client
     container_name: myapp-react-client
     logging:
       driver: awslogs
       options:
         awslogs-region: us-east-1
         awslogs-group: bike-client-container
     command: npm run build
     volumes:
       - my-data:/user/app
     depends_on:
       - server
     ports:
       - "80:80"
     networks:
       - app-network

 networks:
   app-network:
     driver: bridge

 volumes:
   my-data:
   node_modules:
   web-root:
     driver: local


问:
Addressable Directory and Addressable Loading Logic
I have a question about how Addressables deal with Addressable directories I hope you could help me with.

Let's say I have bunch of assets (prefabs or sprites) inside a directory (let's call it "mydirectory") which I want to load dynamically at runtime using Addressables; Instead of marking each of the assets as Addressable, I make the containing directory (i.e. "mydirectory") as addressable. Loading assets using Addressables API works without any problems this way.

The question however is: When I load one specific asset from the assets in "mydirectory" using Addressables.LoadAssetAsync(".../mydirectory/asset1"), will other addressable assets in the directory gets loaded in the memory because they are in the same directory and under the same addressable entry in the addressable group? Or Addressables deal with each asset in that directory as if they are a separate entry in the addressable group?


问:
python pygame code how to handle and control animation in for loop correctly?
I am not sure if it is my code, or my IDE issue.
Vscode windows will always become unresponsive and frozen when it plays the following animation/code mid-way.

It wont complete the whole animation as it crashes at around
go("3", 255, 0, 0,  8)

The code are actually running fine in the background as the frame is still counting in the terminal.

I am curious as to how this can be fixed, is this software issue or my code was wrongly written that caused memory leak.

```<code>

def go(t, x, y, z, s):

    if FRAME_NUM == s*FPS:
        txt = t
        showtext = pygame.font.SysFont(None, int(WIDTH/12))
        showtext = showtext.render(txt, True, (100,100,100))
        screen.fill((x, y, z))
        screen.blit(showtext, (int(WIDTH/8), int(WIDTH/8)))

def main():
    pygame.init()

    while True:
        pygame.event.pump()
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.display.quit()
                pygame.quit()
                exit()

        for i in range(0, 20*FPS):
            #screen.fill((0, 0, 0))
            go("1", 255, 255, 255, 2)
            go("2", 255, 255, 0, 4)
            go("3", 255, 0, 0,  8)
            go("4", 255, 255, 255, 12)
            go("5", 255, 255, 0, 16)

            pygame.display.update()
            global FRAME_NUM
            FRAME_NUM += 1
            print(FRAME_NUM)
            clock.tick(FPS)

        pygame.display.quit()
        pygame.quit()
        exit()

</code>```

Body:
I am not sure if it is my code, or my IDE issue.
Vscode windows will always become unresponsive and frozen when it plays the following animation/code mid-way.

It wont complete the whole animation as it crashes at around
go("3", 255, 0, 0,  8)

The code are actually running fine in the background as the frame is still counting in the terminal.

I am curious as to how this can be fixed, is this software issue or my code was wrongly written that caused memory leak.

def go(t, x, y, z, s):

    if FRAME_NUM == s*FPS:
        txt = t
        showtext = pygame.font.SysFont(None, int(WIDTH/12))
        showtext = showtext.render(txt, True, (100,100,100))
        screen.fill((x, y, z))
        screen.blit(showtext, (int(WIDTH/8), int(WIDTH/8)))

def main():
    pygame.init()

    while True:
        pygame.event.pump()
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.display.quit()
                pygame.quit()
                exit()

        for i in range(0, 20*FPS):
            #screen.fill((0, 0, 0))
            go("1", 255, 255, 255, 2)
            go("2", 255, 255, 0, 4)
            go("3", 255, 0, 0,  8)
            go("4", 255, 255, 255, 12)
            go("5", 255, 255, 0, 16)

            pygame.display.update()
            global FRAME_NUM
            FRAME_NUM += 1
            print(FRAME_NUM)
            clock.tick(FPS)

        pygame.display.quit()
        pygame.quit()
        exit()