问:
how to append text to file in specific location in python3?
i'm trying to append text to file in specific location.
i want to create program which takes input from user(name, image, id) and adds them to this file

```<code>names = []
images = []
id = 0
url = ['https://somewebsiteUsingId10.com',
       'https://somewebsiteUsingId20.com']
if id == 5:
    names.append("Testing Names")
    images.append("Testing Images")
elif id == 0:
    names.append("Testing one names")
    images.append("Testing one Images")
</code>```

I want modified file to be like this:

```<code>names = []
images = []
id = 0
url = ['https://somewebsiteUsingId20.com',
       'https://somewebsiteUsingId10.com',
       'https://somewebsiteUsingId50.com']
if id == 5:
    names.append("Testing Names")
    images.append("Testing Images")
elif id == 0:
    names.append("Testing one names")
    images.append("Testing one Images")
elif id == 50:
    names.append("User input")
    images.append("User Input")

</code>```

Thanks!

答:
In cases like this, a good course of action is to put the variable data in a configuration file.

On start-up, your program reads the configuration file and processes it.

Another program can update the configuration file.

Python has the json module in its standard library. This supports lists and dicts, so it is a good match for Python data structures.

Say you write a file urls.json, looking like this:

```<code>[
    "https://somewebsiteUsingId20.com",
    "https://somewebsiteUsingId10.com",
    "https://somewebsiteUsingId50.com"
]
</code>```

In your program you can then do:

```<code>import json

with open("urls.json") as f:
    urls = json.load(f)
</code>```

The variable urls now points to a list containing the aforementioned URLs.

Writing the config data goes about the same:

```<code>urls = [
    "https://www.parrot.org",
    "https://www.ministryofsillywalks.org",
    "https://www.cheese.net",
]

with open("newurls.json", "w") as f:
    json.dump(urls, f, indent=4)
</code>```

The file newurls.json now contains:

```<code>[
    "https://www.parrot.org",
    "https://www.ministryofsillywalks.org",
    "https://www.cheese.net"
]
</code>```

Note that JSON is pretty flexible, you are not limited to strings:

```<code>import datetime

config = {
    'directories': ["https://www.parrot.org", "https://www.ministryofsillywalks.org"],
    'saved': str(datetime.datetime.now()),
    'count': 12
}

with open("configuration.json", "w") as cf:
    json.dump(config, cf, indent=4)
</code>```

This would result in something like:

```<code>{
    "directories": [
        "https://www.parrot.org",
        "https://www.ministryofsillywalks.org"
    ],
    "saved": "2022-02-07 21:21:14.787420",
    "count": 12
}
</code>```

(You'd get another date/time, of course.)

The only major downside to JSON files is that they don't allow comments. If you need comments, use another format like the configparser module.

Note that there are other methods like shelve and read&eval but those have potential safety issues.

Body:
i'm trying to append text to file in specific location.
i want to create program which takes input from user(name, image, id) and adds them to this file

names = []
images = []
id = 0
url = ['https://somewebsiteUsingId10.com',
       'https://somewebsiteUsingId20.com']
if id == 5:
    names.append("Testing Names")
    images.append("Testing Images")
elif id == 0:
    names.append("Testing one names")
    images.append("Testing one Images")

I want modified file to be like this:

names = []
images = []
id = 0
url = ['https://somewebsiteUsingId20.com',
       'https://somewebsiteUsingId10.com',
       'https://somewebsiteUsingId50.com']
if id == 5:
    names.append("Testing Names")
    images.append("Testing Images")
elif id == 0:
    names.append("Testing one names")
    images.append("Testing one Images")
elif id == 50:
    names.append("User input")
    images.append("User Input")

Thanks!

Body:
In cases like this, a good course of action is to put the variable data in a configuration file.

On start-up, your program reads the configuration file and processes it.

Another program can update the configuration file.

Python has the json module in its standard library. This supports lists and dicts, so it is a good match for Python data structures.

Say you write a file urls.json, looking like this:

[
    "https://somewebsiteUsingId20.com",
    "https://somewebsiteUsingId10.com",
    "https://somewebsiteUsingId50.com"
]

In your program you can then do:

import json

with open("urls.json") as f:
    urls = json.load(f)

The variable urls now points to a list containing the aforementioned URLs.

Writing the config data goes about the same:

urls = [
    "https://www.parrot.org",
    "https://www.ministryofsillywalks.org",
    "https://www.cheese.net",
]

with open("newurls.json", "w") as f:
    json.dump(urls, f, indent=4)

The file newurls.json now contains:

[
    "https://www.parrot.org",
    "https://www.ministryofsillywalks.org",
    "https://www.cheese.net"
]

Note that JSON is pretty flexible, you are not limited to strings:

import datetime

config = {
    'directories': ["https://www.parrot.org", "https://www.ministryofsillywalks.org"],
    'saved': str(datetime.datetime.now()),
    'count': 12
}

with open("configuration.json", "w") as cf:
    json.dump(config, cf, indent=4)

This would result in something like:

{
    "directories": [
        "https://www.parrot.org",
        "https://www.ministryofsillywalks.org"
    ],
    "saved": "2022-02-07 21:21:14.787420",
    "count": 12
}

(You'd get another date/time, of course.)

The only major downside to JSON files is that they don't allow comments. If you need comments, use another format like the configparser module.

Note that there are other methods like shelve and read&eval but those have potential safety issues.


来源: stackexchange

问:
Cypress: check if new opened tab has correct URL
If I have a link in my website. Eg. go to Google and I want to make a test:

GIVEN link (html tag a)

WHEN click the link

THEN browser opens new tab and URL of this tab includes 'google.com'

I know that this does not work:

cy.get('a').click();
cy.url().should('include', 'google.com');
```

答:
You can use removeAttr to remove target and then click the link and assert. Something like:

cy.get('a').invoke('removeAttr', 'target').click()
cy.url().should('include', 'google.com')
```

ContentLicense: CC BY-SA 4.0


问:
How to reinstall VSCode without losing extensions and user settings
After being updated to 1.9.0, some features of the editor just stopped working here. I tried to run with --disable-extensions option and the problem persisted.

Now I want to reinstall to check if the installation is corrupted but I don't want to lose my preferences.

How can I reinstall VSCode keeping my extensions and user settings?

答:
Use the plugin Settings Sync. Saves every config & setting & workspace & keybinding.

https://marketplace.visualstudio.com/items?itemName=Shan.code-settings-sync

ContentLicense: CC BY-SA 3.0


问:
Remove all but the first four characters on each line
So I have a text file in Vscode that contains several lines of text like so:

1801: Joseph Marie Jacquard, a French merchant and inventor invent a loom that uses punched wooden cards to automatically weave fabric designs. Early computers would use similar punch cards.

So now I'm trying to isolate the year number/the first 4 characters of each line. I'm new to regex, and I know how to get the first 4 characters (I used ^.{4}) but how would I be able to find all EXCEPT for the first 4 characters so that I can replace them with nothing and be left with just the year numbers?

答:
You can

Find:       ^(.{4}).+

Replace: $1

See the regex demo. Details:

^ - start of a line (in Visual Studio Code, ^ matches any line start)

(.{4}) - capturing group #1 that captures any four chars other than line break chars

.+ - one or more chars other than line break chars, as many as possible.

The $1 backreference in the replacement pattern replaces the match with Group 1 value.


问:
Chrome Javascript Extension - How do I open a page in a new tab w/o actually going to that tab?
I'm currently writing an extension for Chrome (the way you can integrate jQuery etc is pretty awesome, just like greasemonkey) however I have stumbled upon a problem:

I would like to open a page in a new tab without actually focusing that tab (so stay on the same page)

Thanks!

答:
Try to blur and focus the window.</p>

```<code>var winPop = window.open("blah.html");
winPop.blur();
window.focus();
</code>```

Body:
Try to blur and focus the window.

var winPop = window.open("blah.html");
winPop.blur();
window.focus();


问:
Problems with accessing protected static List using Reflection
I'm trying to mod Planetbase and I have to access protected static List<Character> mCharacters = new List<Character>(); inside public abstract class Character in Planetbase namespace. Here is my code:

```<code>FieldInfo characters = typeof(Character).GetField("mCharacters", BindingFlags.NonPublic | BindingFlags.Instance);
carriedResources = Character.characters.Where(x => x.getLoadedResource() != null)
                .ToDictionary(y => y, x => x.getLoadedResource()); // Get all carried resources across all characters
</code>```

However I'm getting the "Character does not contain the definition for characters" error despite writing a method to access it. No idea what I'm doing wrong.

答:
The BindingFlags you are using are not correct. What you need is BindingFlags.NonPublic | BindingFlags.Static. You can find out more about this enumeration here.

These are some of the most used binding flags when one would search for any type member (field, property, method, etc.):

BindingFlags.Public specifies that public members are to be included in the search.

BindingFlags.NonPublic specifies that non-public members are to be included in the search.

BindingFlags.Instance specifies that instance members are to be included in the search.

BindingFlags.Static specifies that static members are to be included in the search.

Update:
I just noticed that you are not accessing the field information appropriately. After you have the field info, you can access the underlying value like this:

```<code>FieldInfo field = typeof(Character).GetField("mCharacters", BindingFlags.NonPublic | BindingFlags.Instance);
var value = field.GetValue(__character_instance__);
</code>```

The retrieved value will be of type object so you have to safely convert it to the appropriate type.

So if I have this class:

```<code>public class Person
{
    private readonly string _name;

    public Person(string name)
    {
        this._name = name;
    }
}
</code>```

I can access the field data like this:

```<code>var person = new Person("Tony Troeff");
var field = typeof(Person).GetField("_name", BindingFlags.NonPublic | BindingFlags.Instance);
var fieldValue = field.GetValue(person) as string;
</code>```

Body:
I'm trying to mod Planetbase and I have to access protected static List<Character> mCharacters = new List<Character>(); inside public abstract class Character in Planetbase namespace. Here is my code:

FieldInfo characters = typeof(Character).GetField("mCharacters", BindingFlags.NonPublic | BindingFlags.Instance);
carriedResources = Character.characters.Where(x => x.getLoadedResource() != null)
                .ToDictionary(y => y, x => x.getLoadedResource()); // Get all carried resources across all characters

However I'm getting the "Character does not contain the definition for characters" error despite writing a method to access it. No idea what I'm doing wrong.

Body:
The BindingFlags you are using are not correct. What you need is BindingFlags.NonPublic | BindingFlags.Static. You can find out more about this enumeration here.

These are some of the most used binding flags when one would search for any type member (field, property, method, etc.):

BindingFlags.Public specifies that public members are to be included in the search.

BindingFlags.NonPublic specifies that non-public members are to be included in the search.

BindingFlags.Instance specifies that instance members are to be included in the search.

BindingFlags.Static specifies that static members are to be included in the search.

Update:
I just noticed that you are not accessing the field information appropriately. After you have the field info, you can access the underlying value like this:

FieldInfo field = typeof(Character).GetField("mCharacters", BindingFlags.NonPublic | BindingFlags.Instance);
var value = field.GetValue(__character_instance__);

The retrieved value will be of type object so you have to safely convert it to the appropriate type.

So if I have this class:

public class Person
{
    private readonly string _name;

    public Person(string name)
    {
        this._name = name;
    }
}

I can access the field data like this:

var person = new Person("Tony Troeff");
var field = typeof(Person).GetField("_name", BindingFlags.NonPublic | BindingFlags.Instance);
var fieldValue = field.GetValue(person) as string;


问:
Return multiple values python flask
I am trying to return a file and changing the template in Flask.

```<code>return send_file(myfile, as_attachment=True), return render_template("template.html")
</code>```

But it gives me an error.
If I try to make 2 returns like this:

```<code>return send_file(myfile, as_attachment=True)
return render_template("template.html")
</code>```

or

```<code>return render_template("template.html")
return send_file(myfile, as_attachment=True)
</code>```

It doesn't work eitherway.
How do I fix this?

Thanks

答:
You only get one response per request. You can either send a file, or send a new page.

Bear the above in mind by @Tim Roberts.

How do I send the file and then send the new page?.

A long possible ride I suggest you do something like this (Note you use another view for sending the file too).

```<code>    # ...
    if request.GET.get("send", None):
        return send_file(myfile, as_attachment=True)
    return render_template("template.html")
</code>```

In the template use ajax to make GET request to the view

```<code>ajax.get({
    "/the-view-url/?send=file",
    success: function(data) {
    // do whatever you want with data (file)
    }
</code>```

Tada !! you can now return a response or a file.

I suggest you consider this:

It seems like you need to learn Python's fundamentals. –
mac13k

Title: Return multiple values python flask

Body:
I am trying to return a file and changing the template in Flask.

return send_file(myfile, as_attachment=True), return render_template("template.html")

But it gives me an error.
If I try to make 2 returns like this:

return send_file(myfile, as_attachment=True)
return render_template("template.html")

or

return render_template("template.html")
return send_file(myfile, as_attachment=True)

It doesn't work eitherway.
How do I fix this?

Thanks

Body:
You only get one response per request. You can either send a file, or send a new page.

Bear the above in mind by @Tim Roberts.

How do I send the file and then send the new page?.

A long possible ride I suggest you do something like this (Note you use another view for sending the file too).

    # ...
    if request.GET.get("send", None):
        return send_file(myfile, as_attachment=True)
    return render_template("template.html")

In the template use ajax to make GET request to the view

ajax.get({
    "/the-view-url/?send=file",
    success: function(data) {
    // do whatever you want with data (file)
    }

Tada !! you can now return a response or a file.

I suggest you consider this:

It seems like you need to learn Python's fundamentals. –
mac13k


问:
What is the full form of xdmp ? Context - XDMP function in Marklogic Server
Can anyone please let me know the full form of XDMP in XDMP function, which is used in Marklogic?</p>

答:
XDMP is an acronym for MarkLogic XML Database Management Platform.

The XDMP built-in functions are bound to the namespace: http://marklogic.com/xdmp. They are a set of MarkLogic custom functions that provide extra utility functions and MarkLogic database specific actions.

https://docs.marklogic.com/xdmp


问:
What does `total` mean in the field `mode` of `closeness` definition in `igraph` package?
What does total mean in the field mode of closeness definition in igraph package?

```<code>closeness(
  graph,
  vids = V(graph),
  mode = c("out", "in", "all", "total"),
  weights = NULL,
  normalized = FALSE
)
</code>```

答: "total" is an alias for "all", i.e. for ignoring edge directions.

Body:
What does total mean in the field mode of closeness definition in igraph package?

closeness(
  graph,
  vids = V(graph),
  mode = c("out", "in", "all", "total"),
  weights = NULL,
  normalized = FALSE
)


问:
Spark cannot find SQL server jdbc driver even if both the mssql.jar and the .dll are present in the path
I am trying to connect Spark to a SQL server using this:
#Myscript.py
from pyspark.sql import SparkSession

```<code>spark = SparkSession \
    .builder \
    .appName("Python Spark SQL basic example").config("spark.driver.extraClassPath","/home/mssql-jdbc-9.2.1.jre15.jar:/home/sqljdbc_auth.dll")\
    .getOrCreate()

sqldb = spark.read \
    .format("jdbc") \
    .option("url", "jdbc:sqlserver://server:5150;databaseName=testdb;integratedSecurity=true") \
    .option("dbtable", "test_tbl") \
    .option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver") \
    .load()
sqldb.select('coldate').show()
</code>```

I have made sure that both the .dll and the .jar is under /home folder. I call it like so:

```<code>spark-submit --jars /home/sqljdbc41.jar MyScript.py

py4j.protocol.Py4JJavaError: An error occurred while calling o51.load.
: com.microsoft.sqlserver.jdbc.SQLServerException: This driver is not configured for integrated authentication. ClientConnectionId:3462d79d-c165-4607-9790-67a2c786a9cf
</code>```

Seems like it cannot find the .dll file? I ahve verified it exists under /home.

答:
This error was resolved when I placed the sqljdbc_auth.dll file in "C:\Windows\System32" folder.

For those who want to know where to find this dll file, you may:

Download the JDBC Driver for SQL Server (sqljdbc_6.0.8112.200_enu.exe) from the Microsoft website below:

https://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=11774

Unzip it and navigate as follows:

\Microsoft JDBC Driver 6.0 for SQL Server\sqljdbc_6.0\enu\auth\x64

Body:
I am trying to connect Spark to a SQL server using this:
#Myscript.py
from pyspark.sql import SparkSession

spark = SparkSession \
    .builder \
    .appName("Python Spark SQL basic example").config("spark.driver.extraClassPath","/home/mssql-jdbc-9.2.1.jre15.jar:/home/sqljdbc_auth.dll")\
    .getOrCreate()

sqldb = spark.read \
    .format("jdbc") \
    .option("url", "jdbc:sqlserver://server:5150;databaseName=testdb;integratedSecurity=true") \
    .option("dbtable", "test_tbl") \
    .option("driver", "com.microsoft.sqlserver.jdbc.SQLServerDriver") \
    .load()
sqldb.select('coldate').show()

I have made sure that both the .dll and the .jar is under /home folder. I call it like so:

spark-submit --jars /home/sqljdbc41.jar MyScript.py

py4j.protocol.Py4JJavaError: An error occurred while calling o51.load.
: com.microsoft.sqlserver.jdbc.SQLServerException: This driver is not configured for integrated authentication. ClientConnectionId:3462d79d-c165-4607-9790-67a2c786a9cf

Seems like it cannot find the .dll file? I ahve verified it exists under /home.


问:
PHP formula needed to calculate a simple format
I am trying to take an amount and convert it to a units type format...

For example:

( note: don't worry about the dollar sign )

Total is $400

I need to display it as 4 * 100

Another Example

Total is $450

I need to display it as 4 * 100 |  50 * 1

So another words there are only 100 and 1 units.

I was thinking for 3 hours already and nothing seems to come to mind...Perhaps someone out there has done something similar and already know the answer?

答:
Here's a simple solution which will only show the units present, you can get rid of the array/join stuff if you always need to show both units:</p>

```<code>$total = 400;

$out = array();
$hundreds = floor($total / 100);
if ($hundreds) {
    $out[] = $hundreds . ' * 100';
}

$ones = $total % 100;
if ($ones) {
    $out[] = $ones . ' * 1';
}

echo join(' | ', $out);
</code>```

Body:
Here's a simple solution which will only show the units present, you can get rid of the array/join stuff if you always need to show both units:

$total = 400;

$out = array();
$hundreds = floor($total / 100);
if ($hundreds) {
    $out[] = $hundreds . ' * 100';
}

$ones = $total % 100;
if ($ones) {
    $out[] = $ones . ' * 1';
}

echo join(' | ', $out);


问:
Date conversion error - MS Access front end querying sql back end
I am getting a date conversion error when trying to execute SQL from and an Access database against a SQL database.  Our machines are all running windows 7 with office 2010.  The front end is an accde.

There is a search form in the database and all the fields work fine, except the two date fields.

The query's where clause looks like this in the front ends VB code

```<code>"WHERE DrawnDate BETWEEN #" & Format(FromDate, "yyyy-mm-dd") & "# AND #" & _
    Format(ToDate, "yyyy-mm-dd") & "#"
</code>```

Based on some research, I have also tried date formats of dd-mon-yyyy and dd-mm-yyyy with no change in outcome.

The expression On Click you entered as the event property setting produced the following error: ODBC -- call failed.

The error received is:

[Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when converting date and/ or time from character string. (#241)

The other problem is that this only happens on one PC so far and not on mine or others that I have tested.

答: I was able to solve this by simply de-compiling my application then compact and repair.</p>

Body:
I am getting a date conversion error when trying to execute SQL from and an Access database against a SQL database.  Our machines are all running windows 7 with office 2010.  The front end is an accde.

There is a search form in the database and all the fields work fine, except the two date fields.

The query's where clause looks like this in the front ends VB code

"WHERE DrawnDate BETWEEN #" & Format(FromDate, "yyyy-mm-dd") & "# AND #" & _
    Format(ToDate, "yyyy-mm-dd") & "#"

Based on some research, I have also tried date formats of dd-mon-yyyy and dd-mm-yyyy with no change in outcome.

The expression On Click you entered as the event property setting produced the following error: ODBC -- call failed.

The error received is:

[Microsoft][ODBC SQL Server Driver][SQL Server]Conversion failed when converting date and/ or time from character string. (#241)

The other problem is that this only happens on one PC so far and not on mine or others that I have tested.


问:
Swift UI - Toggle Not Hiding Text Elements
I have a simple app with two tab pages - preferences page and directory page. Directory page shows the name, address and other basic info about people (mock data) and preferences page displays toggles which should determine which fields about a person should be shown.

Disabling the toggles does not hide the disabled properties (e.g., name, address) shown on the directory page, and even logs a warning in the console: invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.

ContentView (Root View of App - points to the two pages)

```<code>struct ContentView: View {
    var body: some View {
        TabView {
            DirectoryView()
                .tabItem {
                    Text("Directory")
                    Image(systemName: "list.bullet.rectangle.portrait")
                }
            PreferencesView()
                .tabItem {
                    Text("Preferences")
                    Image(systemName: "gear")
                }
        }
        .environmentObject(PreferencesModel())
    }
}
</code>```

DirectoryView (Displays people's info)

```<code>struct DirectoryView : View {
    @EnvironmentObject var preferencesModel:PreferencesModel
    let personModel = PersonModel()

    var body: some View {
        ScrollView {
            ForEach(personModel.people) { person in
                VStack(alignment: .leading) {
                    if preferencesModel.displayName {
                        HStack {
                            Text("Name: ")
                                .font(.body)
                                .fontWeight(.bold)
                            Text(person.name)
                        }
                        .frame(width: UIScreen.main.bounds.size.width, height: 20, alignment: .leading)
                    }
                    if preferencesModel.displayAddress {
                        HStack {
                            Text("Address: ")
                                .font(.body)
                                .fontWeight(.bold)
                            Text(person.address)
                        }
                        .frame(width: UIScreen.main.bounds.size.width, height: 20, alignment: .leading)
                    }
                    if preferencesModel.displayCompany {
                        HStack {
                            Text("Company: ")
                                .font(.body)
                                .fontWeight(.bold)
                            Text(person.company)
                        }
                        .frame(width: UIScreen.main.bounds.size.width, height: 20, alignment: .leading)
                    }
                    if preferencesModel.displayExperience {
                        HStack {
                            Text("Years of Experience: ")
                                .font(.body)
                                .fontWeight(.bold)
                            Text(String(person.yearsOfExperience))
                        }
                        .frame(width: UIScreen.main.bounds.size.width, height: 20, alignment: .leading)
                    }
                }
                .padding()
                Divider()
            }
        }
    }
}
</code>```

PreferencesModel (ViewModel storing preferences around which fields to display)

```<code>class PreferencesModel: ObservableObject {
    var displayName = true
    var displayAddress = true
    var displayCompany = true
    var displayExperience = true
}
</code>```

PreferencesView (View with the toggles)

```<code>struct PreferencesView: View {
    @EnvironmentObject var preferencesModel:PreferencesModel

    var body: some View {
        ScrollView {
            VStack {
                Toggle("Name", isOn: $preferencesModel.displayName)
                Toggle("Address", isOn: $preferencesModel.displayAddress)
                Toggle("Company", isOn: $preferencesModel.displayCompany)
                Toggle("Years of experience", isOn: $preferencesModel.displayExperience)
            }
        }
    }
}
</code>```

答: You are missing @Published on the ObservableObject variables. You should also put the initial PreferenceModel in an @StateObject in the ContentView to protect it from re-creating.

Body:
I have a simple app with two tab pages - preferences page and directory page. Directory page shows the name, address and other basic info about people (mock data) and preferences page displays toggles which should determine which fields about a person should be shown.

Disabling the toggles does not hide the disabled properties (e.g., name, address) shown on the directory page, and even logs a warning in the console: invalid mode 'kCFRunLoopCommonModes' provided to CFRunLoopRunSpecific - break on _CFRunLoopError_RunCalledWithInvalidMode to debug. This message will only appear once per execution.

ContentView (Root View of App - points to the two pages)

struct ContentView: View {
    var body: some View {
        TabView {
            DirectoryView()
                .tabItem {
                    Text("Directory")
                    Image(systemName: "list.bullet.rectangle.portrait")
                }
            PreferencesView()
                .tabItem {
                    Text("Preferences")
                    Image(systemName: "gear")
                }
        }
        .environmentObject(PreferencesModel())
    }
}

DirectoryView (Displays people's info)

struct DirectoryView : View {
    @EnvironmentObject var preferencesModel:PreferencesModel
    let personModel = PersonModel()

    var body: some View {
        ScrollView {
            ForEach(personModel.people) { person in
                VStack(alignment: .leading) {
                    if preferencesModel.displayName {
                        HStack {
                            Text("Name: ")
                                .font(.body)
                                .fontWeight(.bold)
                            Text(person.name)
                        }
                        .frame(width: UIScreen.main.bounds.size.width, height: 20, alignment: .leading)
                    }
                    if preferencesModel.displayAddress {
                        HStack {
                            Text("Address: ")
                                .font(.body)
                                .fontWeight(.bold)
                            Text(person.address)
                        }
                        .frame(width: UIScreen.main.bounds.size.width, height: 20, alignment: .leading)
                    }
                    if preferencesModel.displayCompany {
                        HStack {
                            Text("Company: ")
                                .font(.body)
                                .fontWeight(.bold)
                            Text(person.company)
                        }
                        .frame(width: UIScreen.main.bounds.size.width, height: 20, alignment: .leading)
                    }
                    if preferencesModel.displayExperience {
                        HStack {
                            Text("Years of Experience: ")
                                .font(.body)
                                .fontWeight(.bold)
                            Text(String(person.yearsOfExperience))
                        }
                        .frame(width: UIScreen.main.bounds.size.width, height: 20, alignment: .leading)
                    }
                }
                .padding()
                Divider()
            }
        }
    }
}

PreferencesModel (ViewModel storing preferences around which fields to display)

class PreferencesModel: ObservableObject {
    var displayName = true
    var displayAddress = true
    var displayCompany = true
    var displayExperience = true
}

PreferencesView (View with the toggles)

struct PreferencesView: View {
    @EnvironmentObject var preferencesModel:PreferencesModel

    var body: some View {
        ScrollView {
            VStack {
                Toggle("Name", isOn: $preferencesModel.displayName)
                Toggle("Address", isOn: $preferencesModel.displayAddress)
                Toggle("Company", isOn: $preferencesModel.displayCompany)
                Toggle("Years of experience", isOn: $preferencesModel.displayExperience)
            }
        }
    }
}


问:
Javascript get Index of Key which contains value
I was wondering if there is a better way to get the Index of Key whose values contain the given value, otherwise it returns Null. In the example below it does what i need, but wasn't sure not sure if there was a simpler way of writing it. I know javascript's syntax is quite powerful and I'm not as familiar with it as others may be.

const sets = {
  "Set 1": [2, 3],
  "Set 2": [4, 5],
  "Set 3": [6]
}

function getValueSetIndex(val) {
let count = 0
  for (const [key, values] of Object.entries(sets)) {
    if (values.includes(val)) {
        return count;
    }
    count += 1
  }
  return null
}

console.log(getValueSetIndex(4))
console.log(getValueSetIndex(20))```

答:
```<code>const sets = {
  "Set 1": [2, 3],
  "Set 2": [4, 5],
  "Set 3": [6]
}
const needle = 5;
Object.values(sets).findIndex(a => a.find(b => b === needle))
</code>```

returns position number or -1

Body:
const sets = {
  "Set 1": [2, 3],
  "Set 2": [4, 5],
  "Set 3": [6]
}
const needle = 5;
Object.values(sets).findIndex(a => a.find(b => b === needle))

returns position number or -1


问:
Is there a way to declare a type for a value that possibly extends some other type?
In Typescript, can we create a type Possibly<T> that only accepts values that maybe, but not necessarily, extend T? Or in other words, values that could be asserted as T without a "neither type sufficiently overlaps with the other" error?

Alternative ways of constraining the parameter that are not describable as a utility type are also fine. However, they must work at compile time (this is a Typescript question after all, not Javascript).

```<code>// NOTE: AliveCat and DeadCat are examples, not actual types that can be modified.
//       Assume that asserting (casting) a DeadCat to AliveCat is a compile error.
declare const garfield: AliveCat;
declare const tom: DeadCat;
declare const schrodingersCat: AliveCat | DeadCat;

function feed(cat: Possibly<AliveCat>) {
    if (unspecifiedAliveCheck(cat)) {
        unspecifiedCastOrUnwrap(cat).food++;
    } else {
        throw new Error(" :( ");
    }
}

garfield as Alive; // obviously works, probably warns about being useless
feed(garfield); // so should also work

schrodingersCat as AliveCat; // compiles
feed(schrodingersCat); // so should also compile

tom as AliveCat; // doesn't compile: "neither type sufficiently overlaps with the other"
feed(tom); // so should not compile either
</code>```

Not solutions, because they accept a DeadCat:

```<code>declare function feed(cat: AliveCat | DeadCat);
declare function feed(cat: unknown);
declare function feed(cat: any); // yuk!
</code>```

Or for a more mundane example:

```<code>// NOTE: the type guard return type is nice to have but optional
function isArray(a: Possibly<any[]>): a is any[] { ... }
isArray([]); // well yeah, but okay, double-checking is fine
isArray(true); // of course not!
isArray(... as true | number); // let's see and find out!
</code>```

答:
A specific type that "maybe, but not necessarily extends T" would, almost by necessity, become unknown.  If a value of type AliveCat | SomethingElse should be a valid Possibly<AliveCat> no matter what SomethingElse is, you pretty quickly widen Possibly to unknown or any.  And if you want AliveCat | SomethingElse to be accepted but just SomethingElse to be rejected, then there is no type in the type system that acts that way.  The way union types work is that you can assign a value of type AliveCat | SomethingElse to Possibly<AliveCat> then you can also assign a value of type SomethingElse to Possibly<AliveCat>.  So, on the face of it, Possibly<V> is not a type.

It seems more like you want Possibly<V> to act as a constraint on a candidate type T. That is, instead of T extends Possibly<V>, you want T extends Possibly<V, T>.  It sounds like you're asking for T extends Possibly<V, T> to be true when reading a value of type T might give you a value of type V.  If so, you're just saying that the intersection of T and V should not be the never type.  You can express that like this:

```<code>type Possibly<V, T> = (V & T) extends never ? V : unknown
</code>```

But unfortunately this will only prevent calls of feed(someCat) if typeof someCat absolutely is known to the compiler as definitely not being an AliveCat.  And even with the following  completely unrelated versions of AliveCat and DeadCat:

```<code>declare class AliveCat { food: number; }
declare class DeadCat { dead: true; }
</code>```

the compiler sees that an AliveCat & DeadCat may indeed exist:

```<code>const zombieCat: AliveCat & DeadCat = { dead: true, food: -10 };
feed(zombieCat); // okay
</code>```

and so tom is also accepted:

```<code>feed(tom); // no error
</code>```

If you can change AliveCat and DeadCat to form distinct members of a discriminated union then things start working:

```<code>declare class AliveCat { food: number; alive: true }
declare class DeadCat { dead: true; alive: false }
// alive property discriminates

feed(tom); // error as desired
</code>```

But I will assume you can't do that.

Backing up, you're looking for the compiler to accept the same types that are accepted when you do a type assertion.  To a rough approximation, you can write x as T if (typeof x) extends T or if T extends (typeof x). If that's what you want, then really we're saying T extends Possibly<V, T> if and only if T extends V or V extends T.  That could be expressed as:

```<code>type Possibly<V, T> = [V] extends [T] ? unknown : V;
</code>```

And then even with your non-discriminated DeadCat and AliveCat, things start working:

```<code>function feed<T extends Possibly<AliveCat, T>>(cat: T): asserts cat is T & AliveCat {
    if (cat instanceof AliveCat) {
        cat.food++;
    } else {
        throw new Error(" :( ");
    }
}
</code>```

Let's make sure

```<code>schrodingersCat as AliveCat; // okay
feed<AliveCat | DeadCat>(schrodingersCat); // okay
schrodingersCat.food++; // AliveCat

tom as AliveCat; // error
feed(tom); // error

const zombieCat: AliveCat & DeadCat = { dead: true, food: -10 };
zombieCat as AliveCat; // okay
feed(zombieCat); // okay
</code>```

Looks good!

Note that you wanted feed() to be an assertion function that returns cat is AliveCat. But since typeof cat might already be narrower than AliveCat, this is not allowed.  Instead we can just write cat is typeof cat & AliveCat or rather cat is T & AliveCat, so that whatever type cat starts off as, T & AliveCat is a subtype of it.

Playground link to code

Body:
In Typescript, can we create a type Possibly<T> that only accepts values that maybe, but not necessarily, extend T? Or in other words, values that could be asserted as T without a "neither type sufficiently overlaps with the other" error?

Alternative ways of constraining the parameter that are not describable as a utility type are also fine. However, they must work at compile time (this is a Typescript question after all, not Javascript).

// NOTE: AliveCat and DeadCat are examples, not actual types that can be modified.
//       Assume that asserting (casting) a DeadCat to AliveCat is a compile error.
declare const garfield: AliveCat;
declare const tom: DeadCat;
declare const schrodingersCat: AliveCat | DeadCat;

function feed(cat: Possibly<AliveCat>) {
    if (unspecifiedAliveCheck(cat)) {
        unspecifiedCastOrUnwrap(cat).food++;
    } else {
        throw new Error(" :( ");
    }
}

garfield as Alive; // obviously works, probably warns about being useless
feed(garfield); // so should also work

schrodingersCat as AliveCat; // compiles
feed(schrodingersCat); // so should also compile

tom as AliveCat; // doesn't compile: "neither type sufficiently overlaps with the other"
feed(tom); // so should not compile either

Not solutions, because they accept a DeadCat:

declare function feed(cat: AliveCat | DeadCat);
declare function feed(cat: unknown);
declare function feed(cat: any); // yuk!

Or for a more mundane example:

// NOTE: the type guard return type is nice to have but optional
function isArray(a: Possibly<any[]>): a is any[] { ... }
isArray([]); // well yeah, but okay, double-checking is fine
isArray(true); // of course not!
isArray(... as true | number); // let's see and find out!

Body:
A specific type that "maybe, but not necessarily extends T" would, almost by necessity, become unknown.  If a value of type AliveCat | SomethingElse should be a valid Possibly<AliveCat> no matter what SomethingElse is, you pretty quickly widen Possibly to unknown or any.  And if you want AliveCat | SomethingElse to be accepted but just SomethingElse to be rejected, then there is no type in the type system that acts that way.  The way union types work is that you can assign a value of type AliveCat | SomethingElse to Possibly<AliveCat> then you can also assign a value of type SomethingElse to Possibly<AliveCat>.  So, on the face of it, Possibly<V> is not a type.

It seems more like you want Possibly<V> to act as a constraint on a candidate type T. That is, instead of T extends Possibly<V>, you want T extends Possibly<V, T>.  It sounds like you're asking for T extends Possibly<V, T> to be true when reading a value of type T might give you a value of type V.  If so, you're just saying that the intersection of T and V should not be the never type.  You can express that like this:

type Possibly<V, T> = (V & T) extends never ? V : unknown

But unfortunately this will only prevent calls of feed(someCat) if typeof someCat absolutely is known to the compiler as definitely not being an AliveCat.  And even with the following  completely unrelated versions of AliveCat and DeadCat:

declare class AliveCat { food: number; }
declare class DeadCat { dead: true; }

the compiler sees that an AliveCat & DeadCat may indeed exist:

const zombieCat: AliveCat & DeadCat = { dead: true, food: -10 };
feed(zombieCat); // okay

and so tom is also accepted:

feed(tom); // no error

If you can change AliveCat and DeadCat to form distinct members of a discriminated union then things start working:

declare class AliveCat { food: number; alive: true }
declare class DeadCat { dead: true; alive: false }
// alive property discriminates

feed(tom); // error as desired

But I will assume you can't do that.

Backing up, you're looking for the compiler to accept the same types that are accepted when you do a type assertion.  To a rough approximation, you can write x as T if (typeof x) extends T or if T extends (typeof x). If that's what you want, then really we're saying T extends Possibly<V, T> if and only if T extends V or V extends T.  That could be expressed as:

type Possibly<V, T> = [V] extends [T] ? unknown : V;

And then even with your non-discriminated DeadCat and AliveCat, things start working:

function feed<T extends Possibly<AliveCat, T>>(cat: T): asserts cat is T & AliveCat {
    if (cat instanceof AliveCat) {
        cat.food++;
    } else {
        throw new Error(" :( ");
    }
}

Let's make sure

schrodingersCat as AliveCat; // okay
feed<AliveCat | DeadCat>(schrodingersCat); // okay
schrodingersCat.food++; // AliveCat

tom as AliveCat; // error
feed(tom); // error

const zombieCat: AliveCat & DeadCat = { dead: true, food: -10 };
zombieCat as AliveCat; // okay
feed(zombieCat); // okay

Looks good!

Note that you wanted feed() to be an assertion function that returns cat is AliveCat. But since typeof cat might already be narrower than AliveCat, this is not allowed.  Instead we can just write cat is typeof cat & AliveCat or rather cat is T & AliveCat, so that whatever type cat starts off as, T & AliveCat is a subtype of it.

<a href="https://www.typescriptlang.org/play?#code/HYQwtgpgzgDiDGEAEBlA9pAksALhATlBPDgJZrACiAHqVDlEgN4BQLSHSAJsQDYj5k8flEYBBXqQBuEAMIgczJADM0aLgC4kwAK5gARgQDcSAL7tOPYQKEjGAEQggu8xU25PNSHPh3JznB7WgkjwFPRIAOYCyqQQvF4S0nIKRhYcVvwhYcAROBhajs6uaYGZNqHhilDwABb46qTAkQRQrlpJMq5IAD5IRS6pbIE4AJ4wyAAKaKKk+ryjADwAagA0SAAqAHxIALxIABTLSABkmwCUSBDUeMBcjMAQMvhIAPxIx1o6wADWwGgAd2Aw04ym+JHIwBUEAgXEWGyuNwgd0Y01m8yWnRSOHW2y2B3gCi0G3OWhAogIDFCCiQdE2pyQWO6rECgVIykOhMUTXoIGAiDQHKZCkuLNZ4q5ADpVOoANSy0risxXXhEZjpJUcHD1QHaCAApCUfANfAHABESA0ByQZvOivFAU45g1NR1XCaLUI3XJjMkXVSSAA9IHKmAYKReNANcoYXDhYo+gNXPjXQ13c1Wq47UGQ1BamgdAlQ+HIy66mmPZmFNK1Fx5SZg77kq4QVqMEgffGGyGCCbo7GDvkwNnG-8rsa0PhW5VcooAF4YfRxdpN-2KM5Jmn7dw8ZxaHx+dYyrwAWgAjAAGMz26Gwg4LgzLkXdpBoH4gUZsFjO0CQWAIZB0CwXBWmIMgKBoOgGAAJnVDVymyOxV2xJRjy0XQDGMDs-QgfdfH8eC+AqaxRH6TxmQ8PdvHwkwQBwrRlDotVHQyIjsiqKIYjiBIOhwkpCOCIQOKHQpyKGMo2KE2ckFTRoMy9IlkO6RMxJwNINTGCYkDRKA5gWFZcR2fYjgZElEVue49WeN4PktJBvj+QFgWjcFwKhGNYXhczkUsnS9MxPiFEM-EuWJUkOwpfAqS5WlGARM543VTV2U5GkeRwPkBSFQKcFFDVNSlY963yp0VTVMVNS1HUDUeA0jRNc1LWtW0b0CFizGnWT009NoaU7HKXzCMMIyjQIPLjHLejI4oFBTcs5J6rMXzzAsiyGksIDLN1KwUnAazlBUcyUhRpyHCLjrUo7e0nfs7yHEcewnKcvx-cBoDgRBUB0CZ8BQHR9DgiTBNCJDEvcNDtD0Qx8BMdqENsckHFUpRdy8A8CKBrIpIiaJ8FieJEgGgSsZnPICmmwY1OJ4iOK6nbepwXjmxpFSZqpjTximGZdIxAzNiMpAAG1lgAXW8lEhY2MX3gc-4gTs5Z1LG1zIVvOEEWuCzUW5-zFnjYKCUUkkyUi6K0rihkwZKjgUsN7lZ0yiBBQuvLKs4Qra2KzVTDK5AKsq7UGhq-VDSexqrRtO1rY6trOvm7qq0Ufrmcuxt1pGqBbomlOps3HA5u2+SGYemT80LLhixGraKyL1x9rrQ7G3jU722TtcX2ul5OCzwcMBLzvpxyCIHyXbEmbXBk872FHPDww8VFrLRzyvUwbxHp8k-EAajrfD8e-X7ES93z82HMIA" rel="nofollow noreferrer">Playground link to code


问:
Why do I keep on getting username is take?
I keep on getting username is taken, and my database is empty..

This is my functions file, everything I have written there

```<code>
function invalidUid($username) {
    $result;
    if (!preg_match("/^[a-zA-Z0-9_]+$/", $username)) {
        $result = true;
    }
    else {
        $result = false;
    }
    return $result;
}

function uidExists($conn, $username, $email) {
    $sql = "SELECT * FROM users WHERE usersUid = ? OR usersEmail = ?;";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)) {
        header("Location: ../index.php?error=stmtfailed");
        exit();
    }

    mysqli_stmt_bind_param($stmt, "ss", $username, $email);
    mysqli_stmt_execute($stmt);

    $resultData = mysqli_stmt_get_result($stmt);

    if ($row = mysqli_fetch_assoc($resultData)) { //creating a variable while checking if its true or false
        return $row;
    }
    else {
        $result = false;
        return $result;
    }

    mysqli_stmt_close($stmt);
}

function createUser($conn, $name, $email, $username, $pwd) { //this will create the USER or data into the database

    $sql = "INSERT INTO users (usersName, usersEmail, usersUid. usersPwd) VALUES (?, ?, ?, ?);";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)) {
        header("Location: ../index.php?error=stmtproblemo");
        exit();
    }

    $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);

    mysqli_stmt_bind_param($stmt, "ssss", $name, $email, $username, $pwd, $hashedPwd); //the ss is how many data you have like for insert we have 4 now so 4 S
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
    header("location: ../signup.php?error=none");
    exit();
}
</code>```

And this is some of the code of my signup authentication

```<code>if (isset($_POST["submit"])) {
        $name = $_POST["name"];
        $email = $_POST["email"];
        $username = $_POST["uid"];
        $pwd = $_POST["pwd"];
        $pwdRepeat = $_POST["pwdrepeat"];

        if (invalidUid($username) !== false) {
            header("Location: ../index.php?error=invaliduid");
            exit();
        }
        if (invalidEmail($email) !== false) {
            header("Location: ../index.php?error=invalidemail");
            exit();
        }
        if (pswMatch($pwd, $pwdRepeat) !== false) {
            header("Location: ../index.php?error=passworddoesntmatch");
            exit();
        }
        if (uidExists($conn, $username, $email) !== false) {
            header("location: ../index.php?error=usernametaken");
            exit();
        }

        createUser($conn, $name, $email, $username, $pwd);

    }
    else {
        header("Location: ../index.php");
        exit();
    }

</code>```

What am I doing wrong? I have tried to add (!preg_match("/^[a-zA-Z0-9_]+$/",$_POST['username']  but it was giving me the invalidUid. If you have any other comments on other parts of this code please let me know.

答:
Start by thinking what must be happening. If you're getting the 'username already taken' error, it means your uidExists() function is the one to look at, and that it is not returning false as expected.  So, stepping through that code, how could that happen?

```<code>if ($row = mysqli_fetch_assoc($resultData)) {
</code>```

What happens here if there is no matching row?  Checking the docs (emphasis mine):

Return Values.

Returns an associative array representing the fetched row, where each key in the array represents the name of one of the result set's columns, null if there are no more rows in the result set, or false on failure.

So $row is going to be null, and uidExists() returns null in that case.  But your code is not testing for null:

```<code>if (uidExists($conn, $username, $email) !== false) {
</code>```

This test will always evaluate to true, because null is not false, so you always get username is taken.

The quickest fix is to just change your test to check for null, which is what you get when there are no matching records:

```<code>if (uidExists($conn, $username, $email) !== null) {
</code>```

But bear in mind this means you have no error checking - if your query is broken or something is wrong, you will never know.  You should consider adding separate checks for query errors, and do something about them, eg log them or return an error to your user.

Body:
I keep on getting username is taken, and my database is empty..

This is my functions file, everything I have written there

function invalidUid($username) {
    $result;
    if (!preg_match("/^[a-zA-Z0-9_]+$/", $username)) {
        $result = true;
    }
    else {
        $result = false;
    }
    return $result;
}

function uidExists($conn, $username, $email) {
    $sql = "SELECT * FROM users WHERE usersUid = ? OR usersEmail = ?;";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)) {
        header("Location: ../index.php?error=stmtfailed");
        exit();
    }

    mysqli_stmt_bind_param($stmt, "ss", $username, $email);
    mysqli_stmt_execute($stmt);

    $resultData = mysqli_stmt_get_result($stmt);

    if ($row = mysqli_fetch_assoc($resultData)) { //creating a variable while checking if its true or false
        return $row;
    }
    else {
        $result = false;
        return $result;
    }

    mysqli_stmt_close($stmt);
}

function createUser($conn, $name, $email, $username, $pwd) { //this will create the USER or data into the database

    $sql = "INSERT INTO users (usersName, usersEmail, usersUid. usersPwd) VALUES (?, ?, ?, ?);";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)) {
        header("Location: ../index.php?error=stmtproblemo");
        exit();
    }

    $hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);

    mysqli_stmt_bind_param($stmt, "ssss", $name, $email, $username, $pwd, $hashedPwd); //the ss is how many data you have like for insert we have 4 now so 4 S
    mysqli_stmt_execute($stmt);
    mysqli_stmt_close($stmt);
    header("location: ../signup.php?error=none");
    exit();
}

And this is some of the code of my signup authentication

if (isset($_POST["submit"])) {
        $name = $_POST["name"];
        $email = $_POST["email"];
        $username = $_POST["uid"];
        $pwd = $_POST["pwd"];
        $pwdRepeat = $_POST["pwdrepeat"];

        if (invalidUid($username) !== false) {
            header("Location: ../index.php?error=invaliduid");
            exit();
        }
        if (invalidEmail($email) !== false) {
            header("Location: ../index.php?error=invalidemail");
            exit();
        }
        if (pswMatch($pwd, $pwdRepeat) !== false) {
            header("Location: ../index.php?error=passworddoesntmatch");
            exit();
        }
        if (uidExists($conn, $username, $email) !== false) {
            header("location: ../index.php?error=usernametaken");
            exit();
        }

        createUser($conn, $name, $email, $username, $pwd);

    }
    else {
        header("Location: ../index.php");
        exit();
    }

What am I doing wrong? I have tried to add (!preg_match("/^[a-zA-Z0-9_]+$/",$_POST['username']  but it was giving me the invalidUid. If you have any other comments on other parts of this code please let me know.

Body:
Start by thinking what must be happening. If you're getting the 'username already taken' error, it means your uidExists() function is the one to look at, and that it is not returning false as expected.  So, stepping through that code, how could that happen?

if ($row = mysqli_fetch_assoc($resultData)) {

What happens here if there is no matching row?  Checking the docs (emphasis mine):

Return Values.

Returns an associative array representing the fetched row, where each key in the array represents the name of one of the result set's columns, null if there are no more rows in the result set, or false on failure.

So $row is going to be null, and uidExists() returns null in that case.  But your code is not testing for null:

if (uidExists($conn, $username, $email) !== false) {

This test will always evaluate to true, because null is not false, so you always get username is taken.

The quickest fix is to just change your test to check for null, which is what you get when there are no matching records:

if (uidExists($conn, $username, $email) !== null) {

But bear in mind this means you have no error checking - if your query is broken or something is wrong, you will never know.  You should consider adding separate checks for query errors, and do something about them, eg log them or return an error to your user.


问:
Pointer still able to call member function, after it was set to NULL and delete being called on it
```<code>#include<stdio.h>

class test2
{
    public:

    void testFunc()
    {
        printf("test");
    }

    test2(){}
   ~test2(){}

};

class test1 : test2
{
    public:

    test1(){
        link = new test2();}
    ~test1(){
        delete link;
        link = NULL;
    }

   test2* link = NULL;
    private:

};

int main()
{
  test1 *ptr = new test1();
  delete ptr;

  ptr->link->testFunc();

    return 0;
}
</code>```

I want to delete the test2 object after calling the deconstructor of test1. Yet, Im still able, after calling delete and setting link to NULL, to call the member function "testFunc" and print "test" with the link pointer.
Why is this possible?

答: If a program accesses an object outside of its lifetime, then the behaviour of the program is undefined. Your program accesses an object outside of its lifetime. The behaviour of your program is undefined. The behaviour that you observed is because the behaviour is undefined. You could have observed any other behaviour because it is undefined, but you didn't observe other behaviour because it's undefined.</p>

Body:
#include<stdio.h>

class test2
{
    public:

    void testFunc()
    {
        printf("test");
    }

    test2(){}
   ~test2(){}

};

class test1 : test2
{
    public:

    test1(){
        link = new test2();}
    ~test1(){
        delete link;
        link = NULL;
    }

   test2* link = NULL;
    private:

};

int main()
{
  test1 *ptr = new test1();
  delete ptr;

  ptr->link->testFunc();

    return 0;
}

I want to delete the test2 object after calling the deconstructor of test1. Yet, Im still able, after calling delete and setting link to NULL, to call the member function "testFunc" and print "test" with the link pointer.
Why is this possible?


问:
Can Exception stack trace ever be null?
I found out that if I am catching an Exception e, e.innerException could possibly be null.

Is it also possible that e.StackTrace could also be null in any possible circumstance in a catch block?

```<code>try {

}
catch(Exception e)
{
//can e.StackTrace be null here?
}
</code>```

答:
I encountered a case where the exception had a Message, but the mere access of StackTrace threw an exception!

This worth repeating: Just accessing the StackTrace threw an exception, i.e. without even calling a method upon it (like ex.StackTrace.ToString()).

This happened when working with COM libraries.

Specifically, it happened when a .NET Framework dll referenced an interop dll. For some reason the clr couldn't find and load that interop dll, and the exception thrown was a normal System.IO.FileNotFoundException, which had a Message.

But, accessing its StackTrace itself threw an exception with the following stack trace:

```<code>System.Signature.GetSignature(Void* pCorSig, Int32 cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType)\r\n   at
System.Reflection.RuntimeMethodInfo.FetchNonReturnParameters()\r\n   at
System.Reflection.RuntimeMethodInfo.GetParameters()\r\n   at
System.Diagnostics.StackTrace.ToString(TraceFormat traceFormat)\r\n   at
System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)\r\n   at
System.Exception.GetStackTrace(Boolean needFileInfo)\r\n   at
System.Exception.get_StackTrace()
</code>```

Title: Can Exception stack trace ever be null?

Body:
I found out that if I am catching an Exception e, e.innerException could possibly be null.

Is it also possible that e.StackTrace could also be null in any possible circumstance in a catch block?

try {

}
catch(Exception e)
{
//can e.StackTrace be null here?
}

Body:
I encountered a case where the exception had a Message, but the mere access of StackTrace threw an exception!

This worth repeating: Just accessing the StackTrace threw an exception, i.e. without even calling a method upon it (like ex.StackTrace.ToString()).

This happened when working with COM libraries.

Specifically, it happened when a .NET Framework dll referenced an interop dll. For some reason the clr couldn't find and load that interop dll, and the exception thrown was a normal System.IO.FileNotFoundException, which had a Message.

But, accessing its StackTrace itself threw an exception with the following stack trace:

System.Signature.GetSignature(Void* pCorSig, Int32 cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType)\r\n   at
System.Reflection.RuntimeMethodInfo.FetchNonReturnParameters()\r\n   at
System.Reflection.RuntimeMethodInfo.GetParameters()\r\n   at
System.Diagnostics.StackTrace.ToString(TraceFormat traceFormat)\r\n   at
System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)\r\n   at
System.Exception.GetStackTrace(Boolean needFileInfo)\r\n   at
System.Exception.get_StackTrace()


问:
Create-react-app 137 vulnerabilities (123 moderate, 13 high, 1 critical)
I'm totally new to REACT and trying to follow a tutorial on YouTube. When I ran "npx create-react-app toDo" I get a bunch of vulnerability error. Following the instructs and ran "npm audit fix --force". This gave me more vulnerabilities then the initial vulnerability list.

I'm runing node.js v16.13.2 and npm v8.1.2. Someone please point me in the right direction please!

137 vulnerabilities (123 moderate, 13 high, 1 critical)

To address issues that do not require attention, run:   npm audit fix

To address all issues possible (including breaking changes), run:

npm audit fix --force

Some issues need review, and may require choosing a different
dependency.

答:
It's a lot of false positive or non important errors, I encourage you to read the following article: https://overreacted.io/npm-audit-broken-by-design/
It has been written by Dan Abramov, co-author of Redux and Create React App.</p>


问:
Why is my website's grid collapsing the first time it's loaded?
I'm sorry for dropping so much code here, but I've been playing with this for over a week and I just can't figure it out.

So I am working on my personal website, and the problem is that the images in the the body's grid system overlap sometimes on the first load of the site. If you refresh it, it seems to work ok (most of the time). You can try yourself: tylerteacher.com . The strange thing is that the site works in the compatibility viewers in chrome and firefox.

I have tried adding margins and using the 'space-between' function in the css. I have double checked the html to make sure everything is properly linked to the css page, and I have also played with Javascript page and the slides per view functions.

I really appreciate the help!

let toggle = document.querySelector("#header .toggle-button");
let collapse = document.querySelectorAll("#header .collapse");

toggle.addEventListener('click' , function(){
    collapse.forEach(col => col.classList.toggle("collapse-toggle"));
})

// with masonry
new Masonry("#posts .grid", {
    itemSelector : '.grid-item',
    gutter : 20
});

// swiper libray initialization
new Swiper('.swiper-container', {
    direction : 'horizontal',
    loop : true,
    slidesPerView : 6,
    autoplay : {
        delay : 0
    },
    // responsive breakpoints
    breakpoints : {
        '@0' : {
            slidesPerView : 2

        },
        // 888px
        '@1.00' : {
            slidesPerView : 3
        },
        // 1110px
        '@1.25' : {
            slidesPerView : 4
        },
        // 1330px
        '@1.50' : {
            slidesPerView: 5
        }
    }
})

// Sticky Navigation
window.onscroll = function(){ myFunction()};

// get the current value
let navbar = document.getElementById("header");

// get the navbar position
let sticky = navbar.offsetTop;

// sticky function
function myFunction(){
    if(window.pageYOffset >= sticky){
        navbar.classList.add("sticky");
    }else{
        navbar.classList.remove("sticky");
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('https://fonts.googleapis.com/css2?family=DM+Sans&family=Poppins&family=Roboto&display=swap');

/* root styling */

:root{
    --light : #f8f9fa;
    --secondary: #adb5bd;
    --dark: #343a40;
    --primary-color: #f15bb5;
    --secondary-color: #2ec4b6;
    --border : #e9ecef;
}

body{
    font-family: 'Roboto', sans-serif;
    padding: 0;
    margin: 0;
}

a{
    text-decoration: none;

}

* > *{
    box-sizing: border-box;
}

/* global styling */
.text-light{
    color: var(--light);
}

.text-secondary{
    color: var(--secondary);
}

.text-dark{
    color: var(--dark);
}

.text-primary{
    color: var(--primary-color);
}

.bg-light{
    background-color: var(--light);
}

.container{
    max-width: 1200px;
    padding: 0 15px;
    margin: auto;
}

.img-fluid{
    width: 100%;
}

.text-title{
    font-family: 'DM Sans', sans-serif;
    font-weight: bold;
}

.secondary-title{
    font-family: 'Poppins' , sans-serif;
}

.display-1{
    font-size: 22px;
}

.display-2{
    font-size: 16px;
}

.display-3{
    font-size: 14px;
}

.text-center{
    text-align: center;
}

.text-right{
    text-align: right;
}

.btn{
    padding: 15px 20px;
    border: none;
}

.btn-primary{
    border-radius: 4px;
    background-color: var(--secondary-color);
}

.object-fit{
    max-height: 120px;
    height: 80px;
    width: 80px;
    object-fit: fill;
    justify-content: space-between;
}

.d-flex{
    display: flex;
}

.flex-wrap{
    flex-wrap: wrap;
}

.justify-content-center{
    justify-content: center;
}

.justify-content-between{
    justify-content: space-between;
}

.mt-2{
    margin-top: 10px;
}

.mt-3{
    margin-top: 50px;
}

.mb-3{
    margin-bottom: 30px;
}

.m-0{
    margin: 0;
}

.px-1{
    padding-left: 5px;
    padding-right: 5px;
}

.px-2{
    padding-left: 20px;
    padding-right: 20px;
}

.py-1{
    padding-top: 10px;
    padding-bottom: 10px;
}

.py-2{
    padding-top: 20px;
    padding-bottom: 20px;
}

.py-3{
    padding-top: 30px;
    padding-bottom: 30px;
}

.thumbnail{
    width: 100%;
    height: 500px;
    object-fit: cover;
}

.rounded{
    height: 120px;
    width: 120px;
    object-fit: fill;
    border-radius: 99px;
}

.shadow{
    box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
}

/* section styling */

/* ------- Navigation Menu ---------- */
.navbar{
    position: relative;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 10px;
}

.nav-brand{
    font-family: 'DM Sans', sans-serif;
    font-weight: bold;
    align-self: center;
    font-size: 32px;
}

.collapse{
    align-self: center;
}

.nav-link{
    font-size: 18px;
    margin: 12px;
    color: var(--dark);
    font-family: 'Poppins', sans-serif;
}

.nav-link:hover{
    color: var(--primary-color);
}

.search-box{
    display: inline;
    border-right: 1px solid var(--secondary);
    padding-right: 12px;
    margin-right: 10px;
}

.toggle-button{
    font-size: 21px;
    background-color: transparent;
    border: none;
    position: absolute;
    right: 0;
    margin: 8px 10px;
    display: none;
}

.toggle-button:focus{
    outline: none;
}

/* ------- .Navigation Menu ---------- */

/* ----------- Main Section ---------- */

#site-main{
    margin-top: 4em;
}

#posts{
    margin-bottom: 5em;

}

.grid{
    margin: 1 auto;
    row-gap: 20px;
}

.grid .grid-item{
    width: calc(33.3333% - 20px);
    margin-bottom: 3em;

}

/* ----------- .Main Section ---------- */

/* ----------- sticky ------- */

.sticky{
    position: fixed;
    top: 0;
    z-index: 99;
    width: 100%;
}

.sticky + .content{
    padding-top: 60px;
}

/* ----------- .sticky ------- */

/* Media Query */

.row{
    display: flex;

}

.col-3{
    flex: 0 0 33.3333%;
    max-width: 33.3333%;
    padding-right: 35px;
}

.col-8{
    flex: 0 0 70%;
    max-width: 70%;
}

.col-4{
    flex: 0 0 30%;
    max-width: 30%;
}

@media (max-width : 1024px){
    .row{
       flex-wrap: wrap;
    }

    .col-3{
        flex: 0 0 50%;
        max-width: 50%;
    }

    .col-8{
        flex: 0 0 100%;
        max-width: 100%;
    }

    .col-4{
        flex: 0 0 100%;
        max-width: 100%;
    }

}

@media (max-width : 992px){
    .navbar{
        flex-direction: column;
    }

    #site-main{
        margin-top: 14em;
    }

}

@media (max-width : 768px){
    .grid .grid-item{
        width: calc(50% - 20px);
        border-top: 1px solid #dfdfdf;

    }

    .col-3{
        flex: 0 0 100%;
        max-width: calc(100% - 50px);
        padding-top: 40px;
    }
}

@media (max-width : 574px){
    .toggle-button{
        display: initial;
    }

    .collapse{
        max-height: 0;
        overflow: hidden;
        transition: all 0.8s cubic-bezier(0.51,-0.15, 0, 0.98);
    }

    .collapse .nav-link{
        display: block;
        text-align: center;
    }

    .search-box{
        border-right: none;
    }

    .collapse-toggle{
        max-height: 500px;
    }

    .grid .grid-item{
        width: calc(100% - 20px);
        border-top: 1px solid #dfdfdf;

    }

    #site-main{
        margin-top: 6em;
        justify-content: space-around;
    }

}</code>```

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TylerTeacher</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"
        integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w=="
        crossorigin="anonymous" />

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/6.4.5/swiper-bundle.min.css"
        integrity="sha512-m3pAvNriL711NMlhkZHK6K4Tu2/RjtrzyjxZU8mlAbxxoDoURy27KajN1LGTLeEEPvaN12mKAgSCrYEwF9y0jA=="
        crossorigin="anonymous" />

    <link rel="stylesheet" href="style.css">

                TylerTeacher

            <button class="toggle-button">

            </button>

                    Home
                    Resources
                    Classes
                    Testimonials
                    Contact

                                        Welcome to TylerTeacher.com

                                         Clock Wed 02, 2021
                                         12

                                        Why online education is the future

                                         Clock Wed 02, 2021
                                         12

                                        How to overcome language anxiety

                                         Clock Wed 02, 2021
                                         12

                                        Podcasts are a great tool for language learners

                                         Clock Wed 02, 2021
                                         12

                                        What makes some people better at learning languages?

                                         Clock Wed 02, 2021
                                         12

                                        Tips for becoming a more confident communicator in English

                                         Clock Wed 02, 2021
                                         12

                                        How listening can make you better at speaking English

                                         Clock Wed 02, 2021
                                         12

                                        How to use online classes effectively

                                         Clock Wed 02, 2021
                                         12

                                        Coming soon

                                         Clock Wed 02, 2021
                                         12

                    <button class="btn btn-primary secondary-title text-light">Load More Posts...</button>

```

答:
It is caused by the Masonry. You have to let the page finish loading before you initialize it. This worked for me

```<code>window.addEventListener('load', function(){
    new Masonry("#posts .grid", {
        itemSelector : '.grid-item',
        gutter : 20
    });
    // remove preload if added
});
</code>```

Optional: Whiles the page loads, you can add a preloader to hide the page's disorganised stucture.

Body:
I'm sorry for dropping so much code here, but I've been playing with this for over a week and I just can't figure it out.

So I am working on my personal website, and the problem is that the images in the the body's grid system overlap sometimes on the first load of the site. If you refresh it, it seems to work ok (most of the time). You can try yourself: tylerteacher.com . The strange thing is that the site works in the compatibility viewers in chrome and firefox.

I have tried adding margins and using the 'space-between' function in the css. I have double checked the html to make sure everything is properly linked to the css page, and I have also played with Javascript page and the slides per view functions.

I really appreciate the help!

let toggle = document.querySelector("#header .toggle-button");
let collapse = document.querySelectorAll("#header .collapse");

toggle.addEventListener('click' , function(){
    collapse.forEach(col => col.classList.toggle("collapse-toggle"));
})

// with masonry
new Masonry("#posts .grid", {
    itemSelector : '.grid-item',
    gutter : 20
});

// swiper libray initialization
new Swiper('.swiper-container', {
    direction : 'horizontal',
    loop : true,
    slidesPerView : 6,
    autoplay : {
        delay : 0
    },
    // responsive breakpoints
    breakpoints : {
        '@0' : {
            slidesPerView : 2

        },
        // 888px
        '@1.00' : {
            slidesPerView : 3
        },
        // 1110px
        '@1.25' : {
            slidesPerView : 4
        },
        // 1330px
        '@1.50' : {
            slidesPerView: 5
        }
    }
})

// Sticky Navigation
window.onscroll = function(){ myFunction()};

// get the current value
let navbar = document.getElementById("header");

// get the navbar position
let sticky = navbar.offsetTop;

// sticky function
function myFunction(){
    if(window.pageYOffset >= sticky){
        navbar.classList.add("sticky");
    }else{
        navbar.classList.remove("sticky");
    }
}

@import url('https://fonts.googleapis.com/css2?family=DM+Sans&family=Poppins&family=Roboto&display=swap');

/* root styling */

:root{
    --light : #f8f9fa;
    --secondary: #adb5bd;
    --dark: #343a40;
    --primary-color: #f15bb5;
    --secondary-color: #2ec4b6;
    --border : #e9ecef;
}

body{
    font-family: 'Roboto', sans-serif;
    padding: 0;
    margin: 0;
}

a{
    text-decoration: none;

}

* > *{
    box-sizing: border-box;
}

/* global styling */
.text-light{
    color: var(--light);
}

.text-secondary{
    color: var(--secondary);
}

.text-dark{
    color: var(--dark);
}

.text-primary{
    color: var(--primary-color);
}

.bg-light{
    background-color: var(--light);
}

.container{
    max-width: 1200px;
    padding: 0 15px;
    margin: auto;
}

.img-fluid{
    width: 100%;
}

.text-title{
    font-family: 'DM Sans', sans-serif;
    font-weight: bold;
}

.secondary-title{
    font-family: 'Poppins' , sans-serif;
}

.display-1{
    font-size: 22px;
}

.display-2{
    font-size: 16px;
}

.display-3{
    font-size: 14px;
}

.text-center{
    text-align: center;
}

.text-right{
    text-align: right;
}

.btn{
    padding: 15px 20px;
    border: none;
}

.btn-primary{
    border-radius: 4px;
    background-color: var(--secondary-color);
}

.object-fit{
    max-height: 120px;
    height: 80px;
    width: 80px;
    object-fit: fill;
    justify-content: space-between;
}

.d-flex{
    display: flex;
}

.flex-wrap{
    flex-wrap: wrap;
}

.justify-content-center{
    justify-content: center;
}

.justify-content-between{
    justify-content: space-between;
}

.mt-2{
    margin-top: 10px;
}

.mt-3{
    margin-top: 50px;
}

.mb-3{
    margin-bottom: 30px;
}

.m-0{
    margin: 0;
}

.px-1{
    padding-left: 5px;
    padding-right: 5px;
}

.px-2{
    padding-left: 20px;
    padding-right: 20px;
}

.py-1{
    padding-top: 10px;
    padding-bottom: 10px;
}

.py-2{
    padding-top: 20px;
    padding-bottom: 20px;
}

.py-3{
    padding-top: 30px;
    padding-bottom: 30px;
}

.thumbnail{
    width: 100%;
    height: 500px;
    object-fit: cover;
}

.rounded{
    height: 120px;
    width: 120px;
    object-fit: fill;
    border-radius: 99px;
}

.shadow{
    box-shadow: rgba(149, 157, 165, 0.2) 0px 8px 24px;
}

/* section styling */

/* ------- Navigation Menu ---------- */
.navbar{
    position: relative;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 10px;
}

.nav-brand{
    font-family: 'DM Sans', sans-serif;
    font-weight: bold;
    align-self: center;
    font-size: 32px;
}

.collapse{
    align-self: center;
}

.nav-link{
    font-size: 18px;
    margin: 12px;
    color: var(--dark);
    font-family: 'Poppins', sans-serif;
}

.nav-link:hover{
    color: var(--primary-color);
}

.search-box{
    display: inline;
    border-right: 1px solid var(--secondary);
    padding-right: 12px;
    margin-right: 10px;
}

.toggle-button{
    font-size: 21px;
    background-color: transparent;
    border: none;
    position: absolute;
    right: 0;
    margin: 8px 10px;
    display: none;
}

.toggle-button:focus{
    outline: none;
}

/* ------- .Navigation Menu ---------- */

/* ----------- Main Section ---------- */

#site-main{
    margin-top: 4em;
}

#posts{
    margin-bottom: 5em;

}

.grid{
    margin: 1 auto;
    row-gap: 20px;
}

.grid .grid-item{
    width: calc(33.3333% - 20px);
    margin-bottom: 3em;

}

/* ----------- .Main Section ---------- */

/* ----------- sticky ------- */

.sticky{
    position: fixed;
    top: 0;
    z-index: 99;
    width: 100%;
}

.sticky + .content{
    padding-top: 60px;
}

/* ----------- .sticky ------- */

/* Media Query */

.row{
    display: flex;

}

.col-3{
    flex: 0 0 33.3333%;
    max-width: 33.3333%;
    padding-right: 35px;
}

.col-8{
    flex: 0 0 70%;
    max-width: 70%;
}

.col-4{
    flex: 0 0 30%;
    max-width: 30%;
}

@media (max-width : 1024px){
    .row{
       flex-wrap: wrap;
    }

    .col-3{
        flex: 0 0 50%;
        max-width: 50%;
    }

    .col-8{
        flex: 0 0 100%;
        max-width: 100%;
    }

    .col-4{
        flex: 0 0 100%;
        max-width: 100%;
    }

}

@media (max-width : 992px){
    .navbar{
        flex-direction: column;
    }

    #site-main{
        margin-top: 14em;
    }

}

@media (max-width : 768px){
    .grid .grid-item{
        width: calc(50% - 20px);
        border-top: 1px solid #dfdfdf;

    }

    .col-3{
        flex: 0 0 100%;
        max-width: calc(100% - 50px);
        padding-top: 40px;
    }
}

@media (max-width : 574px){
    .toggle-button{
        display: initial;
    }

    .collapse{
        max-height: 0;
        overflow: hidden;
        transition: all 0.8s cubic-bezier(0.51,-0.15, 0, 0.98);
    }

    .collapse .nav-link{
        display: block;
        text-align: center;
    }

    .search-box{
        border-right: none;
    }

    .collapse-toggle{
        max-height: 500px;
    }

    .grid .grid-item{
        width: calc(100% - 20px);
        border-top: 1px solid #dfdfdf;

    }

    #site-main{
        margin-top: 6em;
        justify-content: space-around;
    }

}

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TylerTeacher</title>

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"
        integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w=="
        crossorigin="anonymous" />

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/6.4.5/swiper-bundle.min.css"
        integrity="sha512-m3pAvNriL711NMlhkZHK6K4Tu2/RjtrzyjxZU8mlAbxxoDoURy27KajN1LGTLeEEPvaN12mKAgSCrYEwF9y0jA=="
        crossorigin="anonymous" />

    <link rel="stylesheet" href="style.css">

                TylerTeacher

            <button class="toggle-button">

            </button>

                    Home
                    Resources
                    Classes
                    Testimonials
                    Contact

                                        Welcome to TylerTeacher.com

                                         Clock Wed 02, 2021
                                         12

                                        Why online education is the future

                                         Clock Wed 02, 2021
                                         12

                                        How to overcome language anxiety

                                         Clock Wed 02, 2021
                                         12

                                        Podcasts are a great tool for language learners

                                         Clock Wed 02, 2021
                                         12

                                        What makes some people better at learning languages?

                                         Clock Wed 02, 2021
                                         12

                                        Tips for becoming a more confident communicator in English

                                         Clock Wed 02, 2021
                                         12

                                        How listening can make you better at speaking English

                                         Clock Wed 02, 2021
                                         12

                                        How to use online classes effectively

                                         Clock Wed 02, 2021
                                         12

                                        Coming soon

                                         Clock Wed 02, 2021
                                         12

                    <button class="btn btn-primary secondary-title text-light">Load More Posts...</button>

Body:
It is caused by the Masonry. You have to let the page finish loading before you initialize it. This worked for me

window.addEventListener('load', function(){
    new Masonry("#posts .grid", {
        itemSelector : '.grid-item',
        gutter : 20
    });
    // remove preload if added
});

Optional: Whiles the page loads, you can add a preloader to hide the page's disorganised stucture.


问:
How can i apply style only to the clicked element [React]
I'm trying to apply conditional styles in React. I need to apply an animation when use click on delete button but this is applied to every element from the array

Component

```<code>import React, { useState } from 'react';

import './styles.css';

const Element = () => {
  const [onDelete, setOnDelete] = useState(false);
  const list = [
    {
      name: 'Jhon',
      age: '20',
    },
    {
      name: 'Maria',
      age: '25',
    },
  ];

  return (
    <>
      {list.map((item) => (
        <ul className={onDelete ? 'onDelete-apply' : ''}>
          <li>{item.name}</li>
          <li>{item.age}</li>
          <button onClick={() => setOnDelete(true)}>
            Delete
          </button>
        </ul>
      ))}
    </>
  );
};

export default Element;
</code>```

Styles

```<code>.onDelete-apply {
  background-color: red;
}
</code>```

*For example in this component i want to apply red background only to the clicked  element *

答:
You should be traking the element that it is clicked by its index, insted of true or false, on click you set the index of the clicked item in the state and then check if that index is the same as the index of the element when rendered</p>
```<code>import React, { useState } from 'react';

import './styles.css';

const Element = () => {
const [deletedIndex, setDeletedIndex] = useState(false);
      const list = [
        {
          name: 'Jhon',
          age: '20',
        },
        {
          name: 'Maria',
          age: '25',
        },
      ];

      return (
        <>
          {list.map((item, i) => (
            <ul key={i} className={deletedIndex === i ? 'onDelete-apply' : ''}>
              <li>{item.name}</li>
              <li>{item.age}</li>
              <button onClick={() => setDeletedIndex(i)}>Delete</button>
            </ul>
          ))}
        </>
      );
export default Element;
</code>```

Body:
I'm trying to apply conditional styles in React. I need to apply an animation when use click on delete button but this is applied to every element from the array

Component

import React, { useState } from 'react';

import './styles.css';

const Element = () => {
  const [onDelete, setOnDelete] = useState(false);
  const list = [
    {
      name: 'Jhon',
      age: '20',
    },
    {
      name: 'Maria',
      age: '25',
    },
  ];

  return (
    <>
      {list.map((item) => (

{item.name}

{item.age}

          <button onClick={() => setOnDelete(true)}>
            Delete
          </button>

      ))}
    </>
  );
};

export default Element;

Styles

.onDelete-apply {
  background-color: red;
}

*For example in this component i want to apply red background only to the clicked  element *

Body:
You should be traking the element that it is clicked by its index, insted of true or false, on click you set the index of the clicked item in the state and then check if that index is the same as the index of the element when rendered

import React, { useState } from 'react';

import './styles.css';

const Element = () => {
const [deletedIndex, setDeletedIndex] = useState(false);
      const list = [
        {
          name: 'Jhon',
          age: '20',
        },
        {
          name: 'Maria',
          age: '25',
        },
      ];

      return (
        <>
          {list.map((item, i) => (
            <ul key={i} className={deletedIndex === i ? 'onDelete-apply' : ''}>
              <li>{item.name}</li>
              <li>{item.age}</li>
              <button onClick={() => setDeletedIndex(i)}>Delete</button>
            </ul>
          ))}
        </>
      );
export default Element;


问:
Creat ReadStream object from JSON object
I am using jira-client npm to deal with jira rest API , and I am trying to add an attachment to a ticket using addAttachmentOnIssue method, this method requires the key of the issue as a string parameter and also requires ReadStream as the second parameter, I am able to attach a file to a ticket if I followed these steps:

```<code>var jiraAPI = require('jira-client');
var jira = new JiraApi({
protocol: "https",
host:"myJiraInstance",
username:"myUserName",
password: "MyToken",
apiVersion: "2",
strictSSL: true,})
</code>```

then

```<code>const fileStream = fs.createReadStream(filePath);
jira.addAttachmentOnIssue(tickeID,fileStream);
</code>```

As you can see I have the filepath and I attached it but I that is not what I want, I want to create a file from JSON object, without writing this file on the system and then send it

is that possible ?

by using:

```<code>var stream = require('stream');
var readable = new stream.Readable(); // new empty stream.Readable
readable.push('some data');
readable.push(null);
jira.addAttachmentOnIssue(tciketID,readable)
</code>```

I am getting:

```<code>Processing of multipart/form-data request failed. Stream ended unexpectedly
</code>```

答:
the problem is that the required file related information such as filename, knownLength etc. is missing, which is why it fails parsing the stream.

you need to provide file related information manually

as jira-client is using postman-request, you can do that by providing a custom file object like described here:
multipart/form-data (Multipart Form Uploads)

Try this:

```<code>var JiraApi = require('jira-client');
var jira = new JiraApi({
    protocol: "https",
    host: "myJiraInstance",
    username: "myUserName",
    password: "MyToken",
    apiVersion: "2",
    strictSSL: true
})

const inputData = JSON.stringify({
    someProp: 'some data'
});

var stream = require('stream');
var readable = new stream.Readable();
readable.push(inputData);
readable._read = () => {};
readable.push(null);

// https://www.npmjs.com/package/postman-request#forms
// Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
// Use case: for some types of streams, you'll need to provide "file"-related information manually.
// See the `form-data` README for more information about options: https://github.com/form-data/form-data
const myStreamFile = {
    value: readable,
    options: {
        filename: 'json.json',
        contentType: 'application/json',
        knownLength: inputData.length
    }
}

jira.addAttachmentOnIssue(tciketID, myStreamFile)
</code>```

Body:
I am using jira-client npm to deal with jira rest API , and I am trying to add an attachment to a ticket using addAttachmentOnIssue method, this method requires the key of the issue as a string parameter and also requires ReadStream as the second parameter, I am able to attach a file to a ticket if I followed these steps:

var jiraAPI = require('jira-client');
var jira = new JiraApi({
protocol: "https",
host:"myJiraInstance",
username:"myUserName",
password: "MyToken",
apiVersion: "2",
strictSSL: true,})

then

const fileStream = fs.createReadStream(filePath);
jira.addAttachmentOnIssue(tickeID,fileStream);

As you can see I have the filepath and I attached it but I that is not what I want, I want to create a file from JSON object, without writing this file on the system and then send it

is that possible ?

by using:

var stream = require('stream');
var readable = new stream.Readable(); // new empty stream.Readable
readable.push('some data');
readable.push(null);
jira.addAttachmentOnIssue(tciketID,readable)

I am getting:

Processing of multipart/form-data request failed. Stream ended unexpectedly

Body:
the problem is that the required file related information such as filename, knownLength etc. is missing, which is why it fails parsing the stream.

you need to provide file related information manually

as jira-client is using postman-request, you can do that by providing a custom file object like described here:
multipart/form-data (Multipart Form Uploads)

Try this:

var JiraApi = require('jira-client');
var jira = new JiraApi({
    protocol: "https",
    host: "myJiraInstance",
    username: "myUserName",
    password: "MyToken",
    apiVersion: "2",
    strictSSL: true
})

const inputData = JSON.stringify({
    someProp: 'some data'
});

var stream = require('stream');
var readable = new stream.Readable();
readable.push(inputData);
readable._read = () => {};
readable.push(null);

// https://www.npmjs.com/package/postman-request#forms
// Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS}
// Use case: for some types of streams, you'll need to provide "file"-related information manually.
// See the `form-data` README for more information about options: https://github.com/form-data/form-data
const myStreamFile = {
    value: readable,
    options: {
        filename: 'json.json',
        contentType: 'application/json',
        knownLength: inputData.length
    }
}

jira.addAttachmentOnIssue(tciketID, myStreamFile)


问:
How to increase the spacing between bar plot and bar labels?
The space between the plot and the values (204 kwh, 604 kwh, 60 kwh) is too little. How can I move these values a bit higher and increase the spacing?

What I have:

What I want:

Code:

```<code>x_name = ['Average\nneighborhood\u00b9', 'Your\nconsumption', 'Efficient\nneighborhood\u00b2']
plt.figure(facecolor='#E2EBF3')
fig = plt.figure(figsize=(12,10))
plt.bar(x_name, val, color =['cornflowerblue', 'saddlebrown', '#196553'],width = .8)
plt.margins(x = .1 , y = 0.25)

plt.xticks(fontsize=25)
plt.yticks([])

hfont = {'fontfamily':'serif'}

for index, value in enumerate(np.round(val,2)):
  plt.text(index,value, str(value)+" kWh",fontsize=25, ha='center', va = 'bottom',**hfont)
</code>```

答:
As of matplotlib 3.4.0, it's simplest to auto-label the bars with plt.bar_label:

Set padding to increase the distance between bars and labels (e.g., padding=20)

Set fmt to define the format string (e.g., fmt='%g kWh' adds "kWh" suffix)

```<code>bars = plt.bar(x_name, val)                   # store the bar container
plt.bar_label(bars, padding=20, fmt='%g kWh') # auto-label with padding and fmt
</code>```

Note that there is an ax.bar_label counterpart, which is particularly useful for stacked/grouped bar charts because we can iterate all the containers via ax.containers:

```<code>fig, ax = plt.subplots()
ax.bar(x_name, val1, label='Group 1')
ax.bar(x_name, val2, label='Group 2', bottom=val1)
ax.bar(x_name, val3, label='Group 3', bottom=val2)

# auto-label all 3 bar containers
for c in ax.containers:
    ax.bar_label(c)
</code>```

Body:
The space between the plot and the values (204 kwh, 604 kwh, 60 kwh) is too little. How can I move these values a bit higher and increase the spacing?

What I have:

What I want:

Code:

x_name = ['Average\nneighborhood\u00b9', 'Your\nconsumption', 'Efficient\nneighborhood\u00b2']
plt.figure(facecolor='#E2EBF3')
fig = plt.figure(figsize=(12,10))
plt.bar(x_name, val, color =['cornflowerblue', 'saddlebrown', '#196553'],width = .8)
plt.margins(x = .1 , y = 0.25)

plt.xticks(fontsize=25)
plt.yticks([])

hfont = {'fontfamily':'serif'}

for index, value in enumerate(np.round(val,2)):
  plt.text(index,value, str(value)+" kWh",fontsize=25, ha='center', va = 'bottom',**hfont)

Body:
As of matplotlib 3.4.0, it's simplest to auto-label the bars with plt.bar_label:

Set padding to increase the distance between bars and labels (e.g., padding=20)

Set fmt to define the format string (e.g., fmt='%g kWh' adds "kWh" suffix)

bars = plt.bar(x_name, val)                   # store the bar container
plt.bar_label(bars, padding=20, fmt='%g kWh') # auto-label with padding and fmt

Note that there is an ax.bar_label counterpart, which is particularly useful for stacked/grouped bar charts because we can iterate all the containers via ax.containers:

fig, ax = plt.subplots()
ax.bar(x_name, val1, label='Group 1')
ax.bar(x_name, val2, label='Group 2', bottom=val1)
ax.bar(x_name, val3, label='Group 3', bottom=val2)

# auto-label all 3 bar containers
for c in ax.containers:
    ax.bar_label(c)


问:
Cosmos DB "Partial Update"/Patch, cant set new property value to null
I'm trying out the Cosmos DB SDK's new Patch/Partial Update-functionality (for .NET)

When adding a new property I use

```<code> var patchOperations = new List<PatchOperation>(){
       PatchOperation.Add<string>("/FavoriteColor", **null**)
 };

 await container.PatchItemAsync<T>(
                          id: myId,
                          partitionKey: new PartitionKey(myPk),
                          patchOperations: patchOperations);
</code>```

The problem is, that it throws at the PatchOperation-Add() if I set second parameter to null (with message "Value cannot be null"). I can set any non-null string and it works well. I just wonder if this isn't supported yet or if I missed something.

答:
Thanks to github user rvdvelden (source), this work around appears to work perfectly:

```<code>private JToken NullValue { get { return new JProperty("nullValue", null).Value; } }
</code>```

Used in this way:

```<code>operations.Add(PatchOperation.Set("\customer", value ?? NullValue));
</code>```

Body:
I'm trying out the Cosmos DB SDK's new Patch/Partial Update-functionality (for .NET)

When adding a new property I use

 var patchOperations = new List<PatchOperation>(){
       PatchOperation.Add<string>("/FavoriteColor", **null**)
 };

 await container.PatchItemAsync<T>(
                          id: myId,
                          partitionKey: new PartitionKey(myPk),
                          patchOperations: patchOperations);

The problem is, that it throws at the PatchOperation-Add() if I set second parameter to null (with message "Value cannot be null"). I can set any non-null string and it works well. I just wonder if this isn't supported yet or if I missed something.

Body:
Thanks to github user rvdvelden (source), this work around appears to work perfectly:

private JToken NullValue { get { return new JProperty("nullValue", null).Value; } }

Used in this way:

operations.Add(PatchOperation.Set("\customer", value ?? NullValue));