问:
Driver fails to switch back to previous page after the current page closes
In my web application, when the homepage is open and I click on a link, a different webpage gets opened.
This switch is successful using switchPage('title'); however, when the opened page gets closed and I am trying to switch back to previous web page using "switchPage('title')", it fails.

This issue was fixed according to below link in Karate 1.3.0, but I am still facing it:
https://github.com/karatelabs/karate/issues/2032

Below is the code for your reference:

Can someone please assist me here?

I tried switchpage(null),(0),(-1), null and -1 worked but it failed in the next step.
Tried it in headless mode but not working.


来源: stackexchange

问:
Geojson - convert feature collection to Polygon
I am trying to upload a geojson that I generated from geojson.io (by selecting a rectangle polygon snip randomly somewhere on the globe) to Amazan Sagemaker Studio, and I am getting the following error message:

```<code>"Invalid GeoJson format Uploaded file cannot be a Feature or Feature Collection GeoJson. Please upload a GeoJson with a 'type' of 'Polygon'"
</code>```

How do I resolve this? thanks

ContentLicense: CC BY-SA 4.0

Body:
I am trying to upload a geojson that I generated from geojson.io (by selecting a rectangle polygon snip randomly somewhere on the globe) to Amazan Sagemaker Studio, and I am getting the following error message:

"Invalid GeoJson format Uploaded file cannot be a Feature or Feature Collection GeoJson. Please upload a GeoJson with a 'type' of 'Polygon'"

How do I resolve this? thanks


问:
How to define ALB redirect in Terraform Fargate module?
I'm new to Terraform and using the Terraform Fargate module to spin up a container, VPC, ALB, etc. I want the ALB to redirect TCP 80 -> 443 (with a 301) but don't see a way to define that. Right now, I'm just applying my Terraform run and fixing the ALB by hand in the AWS console. I've spent a couple days on this and can't seem to find the right keywords to draw a specific answer out of google.

Looking at lb_http_ports definition in the Fargate module, there aren't any variables defined for the redirect. The Terraform alb module does have these definitions under http_tcp_listeners (action_type, port, etc) so I know there is a way to do this using Terraform.

Is there a way to 'extend' the Fargate module to apply these missing variables? I'm really not at a point yet where I can rewrite this whole module to include the pieces I need.


问:
Flutter: Future builder get Widget by index with saving the state of other widgets
I have a Iconbutton add to favorites and there is a model that has value is_favorite. How can I change the state of the button in my future builder? According to the parameter in the model, the state changes every time the future builder is loaded, but when I click on this button in the future builder, nothing changes, I understand that the problem may be in the index, how then to change the state of the button by index and by the is_favorite parameter in the model ?

```<code>bool isFavorite = false;
  int selectedIndex = -1;
 Future addToFav(productId) async {
    var url =
        '${Constants.API_URL_DOMAIN}action=favorite_toggle&token=${Constants.USER_TOKEN}&product_id=$productId';
    http.Response response = await http.get(
      Uri.parse(url),
    );
    dynamic body = jsonDecode(response.body);
    return body['message'];
  }
late Future<List<Product>> productFuture = getProducts();
  Future<List<Product>> getProducts() async {
    var url =
        '${Constants.API_URL_DOMAIN}action=catalog&category_id=$id&page=$page&token=${Constants.USER_TOKEN}';
    print(url);
    final response = await http.get(Uri.parse(url));
    final body = jsonDecode(response.body);
    return List.from(body['data'].map((e) => Product.fromJson(e)).toList());
}
 FutureBuilder<List<Product>>(
                  future: productFuture,
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return buildGridShimmer();
                    } else if (snapshot.hasData) {
                      final catalog = snapshot.data;
                      return buildCatalog(catalog);
                    } else {
                      print(snapshot.error);
                      return const Text("No widget to build");
                    }
                  }),

Widget buildCatalog(List<Product> product) => CustomScrollView(
        controller: sController,
        slivers: [
          SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(),
            delegate: SliverChildBuilderDelegate(childCount: product.length,
                (BuildContext context, int index) {
              final media =
                  product[index].media?.map((e) => e.toJson()).toList();
              final photo = media?[0]['links']['local']['thumbnails']['350'];
              final productItem = product[index];
              isFavorite = productItem.is_favorite;
              return GestureDetector(
                onTap: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => ProductScreen(
                                name: productItem.name,
                                link: productItem.link,
                              )));
                },
                child: Container(
                  child: Column(
                    children: <Widget>[
                      InkWell(
                        child: Container(
                          child: Stack(
                            children: [
                              Center(
                                child: Image.network(),
                              ),
                              Align(
                                  alignment: Alignment.topRight,
                                  child: IconButton(
                                    icon: Icon(isFavorite ? Icons.favorite : Icons.favorite_border, color: Colors.red,),
                                    onPressed: () {
                                      var data = addToFav(productItem.id);
                                      setState(() {
                                        selectedIndex = index;
                                        isFavorite = data == 'ADDED' ? true : false;
                                      });
                                    },
                              )
                              )
                            ]
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 10.h,
                      ),
                      Text(),
                      // Spacer(),
                      SizedBox(height: 8.h),
                      Text(),
                      SizedBox(height: 5.h),
                      buildButton(index, productItem.id),
                    ],
                  ),
                ),
              )
]
);

</code>```

Body:
I have a Iconbutton add to favorites and there is a model that has value is_favorite. How can I change the state of the button in my future builder? According to the parameter in the model, the state changes every time the future builder is loaded, but when I click on this button in the future builder, nothing changes, I understand that the problem may be in the index, how then to change the state of the button by index and by the is_favorite parameter in the model ?

bool isFavorite = false;
  int selectedIndex = -1;
 Future addToFav(productId) async {
    var url =
        '${Constants.API_URL_DOMAIN}action=favorite_toggle&token=${Constants.USER_TOKEN}&product_id=$productId';
    http.Response response = await http.get(
      Uri.parse(url),
    );
    dynamic body = jsonDecode(response.body);
    return body['message'];
  }
late Future<List<Product>> productFuture = getProducts();
  Future<List<Product>> getProducts() async {
    var url =
        '${Constants.API_URL_DOMAIN}action=catalog&category_id=$id&page=$page&token=${Constants.USER_TOKEN}';
    print(url);
    final response = await http.get(Uri.parse(url));
    final body = jsonDecode(response.body);
    return List.from(body['data'].map((e) => Product.fromJson(e)).toList());
}
 FutureBuilder<List<Product>>(
                  future: productFuture,
                  builder: (context, snapshot) {
                    if (snapshot.connectionState == ConnectionState.waiting) {
                      return buildGridShimmer();
                    } else if (snapshot.hasData) {
                      final catalog = snapshot.data;
                      return buildCatalog(catalog);
                    } else {
                      print(snapshot.error);
                      return const Text("No widget to build");
                    }
                  }),

Widget buildCatalog(List<Product> product) => CustomScrollView(
        controller: sController,
        slivers: [
          SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(),
            delegate: SliverChildBuilderDelegate(childCount: product.length,
                (BuildContext context, int index) {
              final media =
                  product[index].media?.map((e) => e.toJson()).toList();
              final photo = media?[0]['links']['local']['thumbnails']['350'];
              final productItem = product[index];
              isFavorite = productItem.is_favorite;
              return GestureDetector(
                onTap: () {
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (context) => ProductScreen(
                                name: productItem.name,
                                link: productItem.link,
                              )));
                },
                child: Container(
                  child: Column(
                    children: <Widget>[
                      InkWell(
                        child: Container(
                          child: Stack(
                            children: [
                              Center(
                                child: Image.network(),
                              ),
                              Align(
                                  alignment: Alignment.topRight,
                                  child: IconButton(
                                    icon: Icon(isFavorite ? Icons.favorite : Icons.favorite_border, color: Colors.red,),
                                    onPressed: () {
                                      var data = addToFav(productItem.id);
                                      setState(() {
                                        selectedIndex = index;
                                        isFavorite = data == 'ADDED' ? true : false;
                                      });
                                    },
                              )
                              )
                            ]
                          ),
                        ),
                      ),
                      SizedBox(
                        height: 10.h,
                      ),
                      Text(),
                      // Spacer(),
                      SizedBox(height: 8.h),
                      Text(),
                      SizedBox(height: 5.h),
                      buildButton(index, productItem.id),
                    ],
                  ),
                ),
              )
]
);


问:
How to compare Shannon index between creeks with a different treatment (ungrazed versus grazed)?
```<code>Here are my data:
A) 9 different creeks.
B) 3 different treatments (Intensively grazed, Extensively grazed, Ungrazed)
C) Sampling: fish, insects, "crabs & shrimp" (let's call this group shellfish) and benthos
D) There are 3 creeks for each treatment.
E) All samples are from one event.
      a) Fish (one catch/creek).
      b) Insects (6 traps/creek).
      c) Shellfish (one catch/creek).
      d) Benthos (3 samples/creek)

I want to examine if the treatment influences the diversity for each sampled group as for the totality of all groups. I want to use the Shannon Diversity Index, abundance and richness.

What steps should I follow in R to accomplish this? I would really appreciate a step-by-step approach since I am very new to R.

Thank you for any imput!!!
</code>```

So far I only know that I will need the "BiodiversityR" package. I would need step-by-step instructions.

Body:
Here are my data:
A) 9 different creeks.
B) 3 different treatments (Intensively grazed, Extensively grazed, Ungrazed)
C) Sampling: fish, insects, "crabs & shrimp" (let's call this group shellfish) and benthos
D) There are 3 creeks for each treatment.
E) All samples are from one event.
      a) Fish (one catch/creek).
      b) Insects (6 traps/creek).
      c) Shellfish (one catch/creek).
      d) Benthos (3 samples/creek)

I want to examine if the treatment influences the diversity for each sampled group as for the totality of all groups. I want to use the Shannon Diversity Index, abundance and richness.

What steps should I follow in R to accomplish this? I would really appreciate a step-by-step approach since I am very new to R.

Thank you for any imput!!!

So far I only know that I will need the "BiodiversityR" package. I would need step-by-step instructions.


问:
No declaration can be found when updating Spring Framework into file config-servlet.xml?
I am new to Java, Spring and Eclipse and here is my problem.

I updated my diamon-config-servlet.xml file by this command

```<code>xmlns:mvc="https://www.springframework.org/schema/mvc/"
</code>```

And below this, I wrote those command

```<code><mvc:annotation-driven ></mvc:annotation-driven>
<mvc:resource mapping="/assets/**" location="/assets/" ></mvc:resource>
</code>```

I thought that I can use the annotation-driven and resource mapping library by those command, but it show me this error, as you can see in this picture

I do not know why I have this error? Because I thought that my code can get the library from the mvc above?

Here is all of my code, if you need to reference

```<code>https://github.com/nguyencuc2586/DiamonShop4.3
</code>```

Could you please give me some advice for this problem?

Body:
I am new to Java, Spring and Eclipse and here is my problem.

I updated my diamon-config-servlet.xml file by this command

xmlns:mvc="https://www.springframework.org/schema/mvc/"

And below this, I wrote those command

<mvc:annotation-driven ></mvc:annotation-driven>
<mvc:resource mapping="/assets/**" location="/assets/" ></mvc:resource>

I thought that I can use the annotation-driven and resource mapping library by those command, but it show me this error, as you can see in this picture

I do not know why I have this error? Because I thought that my code can get the library from the mvc above?

Here is all of my code, if you need to reference

https://github.com/nguyencuc2586/DiamonShop4.3

Could you please give me some advice for this problem?


问:
Needed Customized Auto_generated id -> In NestJs with Mysql
Like : GM22JA001 (company identifier+year+Month+3Digit num)

Output:
GM22JA001
GM22JA002
GM22JA003


问:
How to scrape all the ~187k datasets publicly available on Kaggle without using the API?
On kaggle's publicly available datasets listing page, you can see that they have over 187k datasets. Everything goes fine as I start scraping these datasets metadata page by page till the page no 500. All the pages post 500 show "-1 datasets".

My question is how do I bypass it to scrape all the datasets? Is there any other way without using the API?


问:
Why didn't the while-Loop become an endless one and why did the loop seem to be asynchronous?
```<code>def main():
    interval=datetime.timedelta(microseconds=250)
    for i in range(1200000,1400000):
    #for i in range(1300000,1300010):
        start=datetime.datetime.now()
        end=start+interval
        print(start)
        fetch(i)
        realend=datetime.datetime.now()
        while realend<=end:
            time.sleep(end-realend)
        i+=1
main()
</code>```

Here is the code, partial of a spider, aimed to make 4 requests per second. As you can see, the while-Loop, which is seemingly an endless loop, worked fairly well actually. It did work at the speed of 4 requests per second constantly. (I didn't even realize the issue.) I do think it very strange. The realend and end haven't been changed, why would the condition of the while statement change?
The working environment is Python3.11, HomeBrew, macOS 13.1 x64.

```<code>def main():
    interval=datetime.timedelta(microseconds=250)
    for i in range(1200000,1400000):
    #for i in range(1300000,1300010):
        start=datetime.datetime.now()
        end=start+interval
        print(start)
        fetch(i)
        while datetime.datetime.now()<=end:
            time.sleep(0.000001)
        i+=1
main()
</code>```

The original version of the code is here. It seems ridiculous to use the while here, I admit. But the result it returned was fairly interesting: the fetching speed was nearly one request per second, making me suspect Python worked in an asynchronous pattern. (It ought to be done in 0.25s but actually it done in nearly 0.5~1s in the halfway, while the pattern above to calculate the actual sleeping time worked fairly well, so I guess that Python made a lot of signals before the loop actually done, as if an asynchronous one.) That is also an issue.

fetch method is:

```<code>import datetime
import time
import requests
import bs4
import sqlite3
def wget(UA,url,tid):
    try:
        cache=requests.get(url,headers=UA,timeout=6.05)
        cache.raise_for_status()
        cache.encoding=cache.apparent_encoding
        return cache.text
    except:
        print("[DEBUG]:Failed to fetch tid %d."%tid)
        return ""
def modify(cache,tid):
    try:
        soup=bs4.BeautifulSoup(cache,"html.parser")
        result=soup.prettify()
        return result
    except:
        print("[DEBUG]:Failed to modify tid %d."%tid)
        return ""
def export(page,tid):
    database=sqlite3.connect("post-cache1.sqlite3")
    c=database.cursor()
    c.execute("CREATE TABLE IF NOT EXISTS posts(tid INT NOT NULL PRIMARY KEY, content MEDIUMTEXT NOT NULL)")
    try:
        c.execute("INSERT INTO posts VALUES (?,?)",(tid,page))
        database.commit()
        database.close()
    except:
        print("[DEBUG]:Failed in executing database for tid %d."%tid)
        database.close()
def fetch(tid):
    UA={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Safari/605.1.15"}
    url="https://****/forum.php?mod=viewthread&tid=%d"%tid
    print(url)
    origin=wget(UA,url,tid)
    mod=modify(origin,tid)
    export(mod,tid)
</code>```

So can anyone tell me why would the first one work and why did the second loop seem to be asynchronous?

Body:
def main():
    interval=datetime.timedelta(microseconds=250)
    for i in range(1200000,1400000):
    #for i in range(1300000,1300010):
        start=datetime.datetime.now()
        end=start+interval
        print(start)
        fetch(i)
        realend=datetime.datetime.now()
        while realend<=end:
            time.sleep(end-realend)
        i+=1
main()

Here is the code, partial of a spider, aimed to make 4 requests per second. As you can see, the while-Loop, which is seemingly an endless loop, worked fairly well actually. It did work at the speed of 4 requests per second constantly. (I didn't even realize the issue.) I do think it very strange. The realend and end haven't been changed, why would the condition of the while statement change?
The working environment is Python3.11, HomeBrew, macOS 13.1 x64.

def main():
    interval=datetime.timedelta(microseconds=250)
    for i in range(1200000,1400000):
    #for i in range(1300000,1300010):
        start=datetime.datetime.now()
        end=start+interval
        print(start)
        fetch(i)
        while datetime.datetime.now()<=end:
            time.sleep(0.000001)
        i+=1
main()

The original version of the code is here. It seems ridiculous to use the while here, I admit. But the result it returned was fairly interesting: the fetching speed was nearly one request per second, making me suspect Python worked in an asynchronous pattern. (It ought to be done in 0.25s but actually it done in nearly 0.5~1s in the halfway, while the pattern above to calculate the actual sleeping time worked fairly well, so I guess that Python made a lot of signals before the loop actually done, as if an asynchronous one.) That is also an issue.

fetch method is:

import datetime
import time
import requests
import bs4
import sqlite3
def wget(UA,url,tid):
    try:
        cache=requests.get(url,headers=UA,timeout=6.05)
        cache.raise_for_status()
        cache.encoding=cache.apparent_encoding
        return cache.text
    except:
        print("[DEBUG]:Failed to fetch tid %d."%tid)
        return ""
def modify(cache,tid):
    try:
        soup=bs4.BeautifulSoup(cache,"html.parser")
        result=soup.prettify()
        return result
    except:
        print("[DEBUG]:Failed to modify tid %d."%tid)
        return ""
def export(page,tid):
    database=sqlite3.connect("post-cache1.sqlite3")
    c=database.cursor()
    c.execute("CREATE TABLE IF NOT EXISTS posts(tid INT NOT NULL PRIMARY KEY, content MEDIUMTEXT NOT NULL)")
    try:
        c.execute("INSERT INTO posts VALUES (?,?)",(tid,page))
        database.commit()
        database.close()
    except:
        print("[DEBUG]:Failed in executing database for tid %d."%tid)
        database.close()
def fetch(tid):
    UA={"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.1 Safari/605.1.15"}
    url="https://****/forum.php?mod=viewthread&tid=%d"%tid
    print(url)
    origin=wget(UA,url,tid)
    mod=modify(origin,tid)
    export(mod,tid)

So can anyone tell me why would the first one work and why did the second loop seem to be asynchronous?


问:
unknown error: Chrome failed to start: exited normally. (unknown error: DevToolsActivePort file doesn't exist)
I am trying to initiate chrome through below code. I am getting below error and unable to proceed further. I tried all the options which was available in this website but nothing is working for me.</p>
```<code>System.setProperty("webdriver.chrome.driver","path\\chromedriver.exe");
        //WebDriver driver = new ChromeDriver();
        //ChromeOptions options = new ChromeOptions();
        //options.addArguments("--no-sandbox"); // Bypass OS security model
        //options.addArguments("--headless");
        //options.setExperimentalOption("useAutomationExtension", false);
        //options.addArguments("start-maximized"); // open Browser in maximized mode
        //options.addArguments("disable-infobars"); // disabling infobars
        //options.addArguments("--disable-extensions"); // disabling extensions
        //options.addArguments("--disable-gpu"); // applicable to windows os only
        //options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems

        WebDriver driver = new ChromeDriver();
        driver.get("https://www.facebook.com/");
        driver.manage().window().maximize();
        Thread.sleep(2000);

error:
``
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited normally.
  (unknown error: DevToolsActivePort file doesn't exist)
</code>```
```<code>

</code>```
```<code>System.setProperty("webdriver.chrome.driver","path\\chromedriver.exe");
        //WebDriver driver = new ChromeDriver();
        //ChromeOptions options = new ChromeOptions();
        //options.addArguments("--no-sandbox"); // Bypass OS security model
        //options.addArguments("--headless");
        //options.setExperimentalOption("useAutomationExtension", false);
        //options.addArguments("start-maximized"); // open Browser in maximized mode
        //options.addArguments("disable-infobars"); // disabling infobars
        //options.addArguments("--disable-extensions"); // disabling extensions
        //options.addArguments("--disable-gpu"); // applicable to windows os only
        //options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems

        WebDriver driver = new ChromeDriver();
        driver.get("https://www.facebook.com/");
        driver.manage().window().maximize();
        Thread.sleep(2000);
</code>```
```<code>error:
``
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited normally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location C:\Program Files\Google\Chrome\Application\chrome.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.)

</code>```

Body:
I am trying to initiate chrome through below code. I am getting below error and unable to proceed further. I tried all the options which was available in this website but nothing is working for me.

System.setProperty("webdriver.chrome.driver","path\\chromedriver.exe");
        //WebDriver driver = new ChromeDriver();
        //ChromeOptions options = new ChromeOptions();
        //options.addArguments("--no-sandbox"); // Bypass OS security model
        //options.addArguments("--headless");
        //options.setExperimentalOption("useAutomationExtension", false);
        //options.addArguments("start-maximized"); // open Browser in maximized mode
        //options.addArguments("disable-infobars"); // disabling infobars
        //options.addArguments("--disable-extensions"); // disabling extensions
        //options.addArguments("--disable-gpu"); // applicable to windows os only
        //options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems

        WebDriver driver = new ChromeDriver();
        driver.get("https://www.facebook.com/");
        driver.manage().window().maximize();
        Thread.sleep(2000);

error:
``
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited normally.
  (unknown error: DevToolsActivePort file doesn't exist)

System.setProperty("webdriver.chrome.driver","path\\chromedriver.exe");
        //WebDriver driver = new ChromeDriver();
        //ChromeOptions options = new ChromeOptions();
        //options.addArguments("--no-sandbox"); // Bypass OS security model
        //options.addArguments("--headless");
        //options.setExperimentalOption("useAutomationExtension", false);
        //options.addArguments("start-maximized"); // open Browser in maximized mode
        //options.addArguments("disable-infobars"); // disabling infobars
        //options.addArguments("--disable-extensions"); // disabling extensions
        //options.addArguments("--disable-gpu"); // applicable to windows os only
        //options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems

        WebDriver driver = new ChromeDriver();
        driver.get("https://www.facebook.com/");
        driver.manage().window().maximize();
        Thread.sleep(2000);

error:
``
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error: Chrome failed to start: exited normally.
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location C:\Program Files\Google\Chrome\Application\chrome.exe is no longer running, so ChromeDriver is assuming that Chrome has crashed.)


问:
Do we One Hot Encode (create Dummy Variables) before or after Train/Test Split?
I've seen quite a lot of conflicting views on if one-hot encoding (dummy variable creation) should be done before/after the training/test split.

Responses seem to state that one-hot encoding before leads to "data leakage".

This example states it's industry norm to do one-hot encoding on the entire data before training/test split:

Industry Example

This example from kaggle states that it should be done after the training/test split to avoid data leakage:

kaggle response - after split

My question is the following;

Do we perform one-hot encoding before or after the Train/Test Split?

Where is the data leakage occuring in the following example?

If we take the following example, we have two columns - web_views and website (non-ordinal categorical feature) (assuming we are one-hot encoding across the entire column, not dropping any dummies)

Our dataframe:

import pandas as pd
from sklearn.model_selection import train_test_split
import numpy as np

```<code>df = pd.DataFrame({'web_views': [100,200,300,400],
                  'website': ['Youtube','Facebook','Instagram', 'Google']})
</code>```

Scenario 1: One-Hot Encoding/Dummy Variables before splitting into Train/Test:

```<code>np.random.seed(123)

df_before_split = pd.concat([df.drop('website', axis = 1), pd.get_dummies(df['website'])], axis=1)

# create your X and y dataframes
X_before_split = df_before_split.drop('web_views', axis = 1)
y_before_split = df_before_split['web_views']

# perform train test split
X_train_before_split, X_test_before_split, y_train_before_split, y_test_before_split = train_test_split(X_before_split, y_before_split, test_size = 0.20)
</code>```

Now viewing the dataframes we have:

```<code># view X train dataset (this is encoding before split)
X_train_before_split
</code>```

and then for test

```<code># View X test dataset dataset (this is encoding before split)
X_test_before_split
</code>```

Scenario 2: One-Hot Encoding/Dummy Variables AFTER splitting into Train/Test:

```<code># Perform One Hot encoding after the train/test split instead

X = df.drop('web_views', axis = 1)
y = df['web_views']

# perform data split:
np.random.seed(123)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20)

# perform one hot encoding on the train and test dataset datasets:
X_train = pd.concat([X_train.drop('website', axis = 1), pd.get_dummies(X_train['website'])], axis=1)
X_test = pd.concat([X_test.drop('website', axis = 1), pd.get_dummies(X_test['website'])], axis=1)
</code>```

Viewing the X_train and X_test dataframes:

```<code># encode after train/test split - train dataframe
X_train

# encode after train/test split - test dataframe
X_test
</code>```

Performing Linear Regression Modelling

Now that we have split our data to demonstrate we will create a simple linear model:

```<code>from sklearn.linear_model import LinearRegression
</code>```

Before split linear model

```<code>regressor_before_split = LinearRegression()
regressor_before_split.fit(X_train_before_split, y_train_before_split)

y_pred_before_split = regressor_before_split.predict(X_test_before_split)
y_pred_before_split
</code>```

y_pred_before_split returns a predicting value what we would expect.

After split linear model

```<code>regressor_after_split = LinearRegression()
regressor_after_split.fit(X_train, y_train)

y_pred_after_split = regressor_after_split.predict(X_test)
y_pred_after_split
</code>```

Error message from Scenario 2:

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-92-c63978a198c8> in <module>()
      2 regressor_after_split.fit(X_train, y_train)
      3
----> 4 y_pred_after_split = regressor_after_split.predict(X_test)
      5 y_pred_after_split

C:\Anaconda3\lib\site-packages\sklearn\linear_model\base.py in predict(self, X)
    254             Returns predicted values.
    255         """
--> 256         return self._decision_function(X)
    257
    258     _preprocess_data = staticmethod(_preprocess_data)

C:\Anaconda3\lib\site-packages\sklearn\linear_model\base.py in _decision_function(self, X)
    239         X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
    240         return safe_sparse_dot(X, self.coef_.T,
--> 241                                dense_output=True) + self.intercept_
    242
    243     def predict(self, X):

C:\Anaconda3\lib\site-packages\sklearn\utils\extmath.py in safe_sparse_dot(a, b, dense_output)
    138         return ret
    139     else:
--> 140         return np.dot(a, b)
    141
    142

<__array_function__ internals> in dot(*args, **kwargs)

ValueError: shapes (1,1) and (3,) not aligned: 1 (dim 1) != 3 (dim 0)
</code>```

My thoughts:

Encoding with dummies before splitting ensures that the test data that we pass in e.g. X_test to perform the predicitions has the same shape as the training data that the model was trained on therefore understands how to predict values when it encounters these features - unlike with encoding after splitting, since the X_test data has only one feature we are using to make predicitions with whereas the X_train has 3 features

Maybe I've introduced data leakage?

I'd be happy for someone to correct me if i've got things wrong or misinterpreted anything, but i'm stuck scratching me head if you encode before or after splitting!

Body:
I've seen quite a lot of conflicting views on if one-hot encoding (dummy variable creation) should be done before/after the training/test split.

Responses seem to state that one-hot encoding before leads to "data leakage".

This example states it's industry norm to do one-hot encoding on the entire data before training/test split:

Industry Example

This example from kaggle states that it should be done after the training/test split to avoid data leakage:

kaggle response - after split

My question is the following;

Do we perform one-hot encoding before or after the Train/Test Split?

Where is the data leakage occuring in the following example?

If we take the following example, we have two columns - web_views and website (non-ordinal categorical feature) (assuming we are one-hot encoding across the entire column, not dropping any dummies)

Our dataframe:

import pandas as pd
from sklearn.model_selection import train_test_split
import numpy as np

df = pd.DataFrame({'web_views': [100,200,300,400],
                  'website': ['Youtube','Facebook','Instagram', 'Google']})

Scenario 1: One-Hot Encoding/Dummy Variables before splitting into Train/Test:

np.random.seed(123)

df_before_split = pd.concat([df.drop('website', axis = 1), pd.get_dummies(df['website'])], axis=1)

# create your X and y dataframes
X_before_split = df_before_split.drop('web_views', axis = 1)
y_before_split = df_before_split['web_views']

# perform train test split
X_train_before_split, X_test_before_split, y_train_before_split, y_test_before_split = train_test_split(X_before_split, y_before_split, test_size = 0.20)

Now viewing the dataframes we have:

# view X train dataset (this is encoding before split)
X_train_before_split

and then for test

# View X test dataset dataset (this is encoding before split)
X_test_before_split

Scenario 2: One-Hot Encoding/Dummy Variables AFTER splitting into Train/Test:

# Perform One Hot encoding after the train/test split instead

X = df.drop('web_views', axis = 1)
y = df['web_views']

# perform data split:
np.random.seed(123)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.20)

# perform one hot encoding on the train and test dataset datasets:
X_train = pd.concat([X_train.drop('website', axis = 1), pd.get_dummies(X_train['website'])], axis=1)
X_test = pd.concat([X_test.drop('website', axis = 1), pd.get_dummies(X_test['website'])], axis=1)

Viewing the X_train and X_test dataframes:

# encode after train/test split - train dataframe
X_train

# encode after train/test split - test dataframe
X_test

Performing Linear Regression Modelling

Now that we have split our data to demonstrate we will create a simple linear model:

from sklearn.linear_model import LinearRegression

Before split linear model

regressor_before_split = LinearRegression()
regressor_before_split.fit(X_train_before_split, y_train_before_split)

y_pred_before_split = regressor_before_split.predict(X_test_before_split)
y_pred_before_split

y_pred_before_split returns a predicting value what we would expect.

After split linear model

regressor_after_split = LinearRegression()
regressor_after_split.fit(X_train, y_train)

y_pred_after_split = regressor_after_split.predict(X_test)
y_pred_after_split

Error message from Scenario 2:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-92-c63978a198c8> in <module>()
      2 regressor_after_split.fit(X_train, y_train)
      3
----> 4 y_pred_after_split = regressor_after_split.predict(X_test)
      5 y_pred_after_split

C:\Anaconda3\lib\site-packages\sklearn\linear_model\base.py in predict(self, X)
    254             Returns predicted values.
    255         """
--> 256         return self._decision_function(X)
    257
    258     _preprocess_data = staticmethod(_preprocess_data)

C:\Anaconda3\lib\site-packages\sklearn\linear_model\base.py in _decision_function(self, X)
    239         X = check_array(X, accept_sparse=['csr', 'csc', 'coo'])
    240         return safe_sparse_dot(X, self.coef_.T,
--> 241                                dense_output=True) + self.intercept_
    242
    243     def predict(self, X):

C:\Anaconda3\lib\site-packages\sklearn\utils\extmath.py in safe_sparse_dot(a, b, dense_output)
    138         return ret
    139     else:
--> 140         return np.dot(a, b)
    141
    142

<__array_function__ internals> in dot(*args, **kwargs)

ValueError: shapes (1,1) and (3,) not aligned: 1 (dim 1) != 3 (dim 0)

My thoughts:

Encoding with dummies before splitting ensures that the test data that we pass in e.g. X_test to perform the predicitions has the same shape as the training data that the model was trained on therefore understands how to predict values when it encounters these features - unlike with encoding after splitting, since the X_test data has only one feature we are using to make predicitions with whereas the X_train has 3 features

Maybe I've introduced data leakage?

I'd be happy for someone to correct me if i've got things wrong or misinterpreted anything, but i'm stuck scratching me head if you encode before or after splitting!


问:
Retrieve nested MongoDB object after querying nested object
Given the following MongoDB collection groups:

```<code>[{
  _id: 'g1',
  name: 'Group 1',
  projects: [{
    _id: 'p1',
    name: 'Project 1',
    tasks: [{
      _id: 't1',
      name: 'Task 1'
    }, {
      _id: 't2',
      name: 'Task 2'
    }]
  }]
}]
</code>```

I need to find task with _id = t2 and return the whole task object:

```<code>{
  _id: 't2',
  name: 'Task 2'
}
</code>```

I'm able to find the group, either using mongodb:

```<code>db.groups.find({ 'projects.tasks._id': ObjectId('t2') })
</code>```

Or with Mongoose:

```<code>Groups.findOne({ 'projects.tasks._id': 't2' })
</code>```

But of course, this returns the entire group document, and not the task.

I've tried:

```<code>db.groups.aggregate([
  {
    $match: { 'projects.tasks._id': ObjectId('t2') }
  }, {
    $replaceRoot: {
      newRoot: '$chapters.sections'
    }
  }
])
</code>```

But this throws an error.

Body:
Given the following MongoDB collection groups:

[{
  _id: 'g1',
  name: 'Group 1',
  projects: [{
    _id: 'p1',
    name: 'Project 1',
    tasks: [{
      _id: 't1',
      name: 'Task 1'
    }, {
      _id: 't2',
      name: 'Task 2'
    }]
  }]
}]

I need to find task with _id = t2 and return the whole task object:

{
  _id: 't2',
  name: 'Task 2'
}

I'm able to find the group, either using mongodb:

db.groups.find({ 'projects.tasks._id': ObjectId('t2') })

Or with Mongoose:

Groups.findOne({ 'projects.tasks._id': 't2' })

But of course, this returns the entire group document, and not the task.

I've tried:

db.groups.aggregate([
  {
    $match: { 'projects.tasks._id': ObjectId('t2') }
  }, {
    $replaceRoot: {
      newRoot: '$chapters.sections'
    }
  }
])

But this throws an error.


问:
Pull notification from FCM
How to implement pull notification from FCM(Firebase Cloud Messaging) once in a day automatically after switched-off/network issues for android(Flutter application-Dart). Is there any option to pull notification from FCM for flutter application.
Kindly help me to implement this.

Thanks in advance...

Title: Pull notification from FCM


问:
C# roslyn - How to obtain the type information in the syntax tree

How to obtain the type information of "t"?

How to get the type name of t

```<code>
        class Test
        {
            void main()
            {
                var t = new Test();

                t.Equals(null);// object.Equals

                //How do I get the type of "t" ?
            }
        }

        private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            var invocationExpr = (InvocationExpressionSyntax)context.Node;
            var memberAccessExpr = invocationExpr.Expression as MemberAccessExpressionSyntax;
            if (memberAccessExpr == null)
                return;
            if (memberAccessExpr.Name.ToString() != nameof(object.Equals))
                return;
            var memberSymbol = context.SemanticModel.GetSymbolInfo(memberAccessExpr).Symbol as IMethodSymbol;
            if (memberSymbol == null)
                return;

            _ = memberSymbol.ContainingType.SpecialType;// Object
        }
</code>```

I don't know why, but I cannot enter the breakpoint when debugging with vs.
So I can only debug in this way, but I can't find the correct method.

```<code>var str = memberSymbol.ContainingSymbol?.Name + Environment.NewLine
                 + memberSymbol.AssociatedSymbol?.Name + Environment.NewLine
                 + memberSymbol.ContainingType?.Name + Environment.NewLine
                 + memberSymbol.ContainingType?.SpecialType + Environment.NewLine
                 + memberSymbol.ContainingType?.ContainingType?.Name + Environment.NewLine
                 + memberSymbol.ContainingType?.TypeKind + Environment.NewLine
                 + memberSymbol.ContainingType?.OriginalDefinition?.Name + Environment.NewLine
                 + memberSymbol.ContainingType?.BaseType?.Name + Environment.NewLine
                 + memberSymbol.ContainingType?.MetadataName + Environment.NewLine
                 + memberSymbol.ContainingType?.ContainingAssembly?.Name + Environment.NewLine
                 + string.Join(" ", memberSymbol.ContainingType?.MemberNames ?? Enumerable.Empty<string>()) + Environment.NewLine
                 + "***************" + Environment.NewLine
                 + invocationExpr.FullSpan.ToString() + Environment.NewLine
                ;

            File.WriteAllText(@"xxxxxxx", str);
</code>```

I want to obtain "Test" type information or type string

Body:
How to obtain the type information of "t"?

How to get the type name of t

        class Test
        {
            void main()
            {
                var t = new Test();

                t.Equals(null);// object.Equals

                //How do I get the type of "t" ?
            }
        }

        private static void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            var invocationExpr = (InvocationExpressionSyntax)context.Node;
            var memberAccessExpr = invocationExpr.Expression as MemberAccessExpressionSyntax;
            if (memberAccessExpr == null)
                return;
            if (memberAccessExpr.Name.ToString() != nameof(object.Equals))
                return;
            var memberSymbol = context.SemanticModel.GetSymbolInfo(memberAccessExpr).Symbol as IMethodSymbol;
            if (memberSymbol == null)
                return;

            _ = memberSymbol.ContainingType.SpecialType;// Object
        }

I don't know why, but I cannot enter the breakpoint when debugging with vs.
So I can only debug in this way, but I can't find the correct method.

var str = memberSymbol.ContainingSymbol?.Name + Environment.NewLine
                 + memberSymbol.AssociatedSymbol?.Name + Environment.NewLine
                 + memberSymbol.ContainingType?.Name + Environment.NewLine
                 + memberSymbol.ContainingType?.SpecialType + Environment.NewLine
                 + memberSymbol.ContainingType?.ContainingType?.Name + Environment.NewLine
                 + memberSymbol.ContainingType?.TypeKind + Environment.NewLine
                 + memberSymbol.ContainingType?.OriginalDefinition?.Name + Environment.NewLine
                 + memberSymbol.ContainingType?.BaseType?.Name + Environment.NewLine
                 + memberSymbol.ContainingType?.MetadataName + Environment.NewLine
                 + memberSymbol.ContainingType?.ContainingAssembly?.Name + Environment.NewLine
                 + string.Join(" ", memberSymbol.ContainingType?.MemberNames ?? Enumerable.Empty<string>()) + Environment.NewLine
                 + "***************" + Environment.NewLine
                 + invocationExpr.FullSpan.ToString() + Environment.NewLine
                ;

            File.WriteAllText(@"xxxxxxx", str);

I want to obtain "Test" type information or type string


问:
Infiinte loading with Next 13
I am experimenting with Next 13 and am trying to understand the best solution to create infinite loading

The first 20 items I want to be rendered in the HTML, for SEO benefits, then one the use scrolls to the end of the list it loads more items

So the initial load should be done as a server component I take it, then somehow I need to use a client component to perform the infinite requests

In next 12, rightly or wrongly I would have populated a useState with the data from the server passing in the props, then simply had a function on the client that would perform another, but I am lost with the whole server / client components at the moment

Any help as to the best direction to take will be greatly appreciated.

Title: Infiinte loading with Next 13


问:
MUI theme, styled components and typescript: How can I extend the theme that is used in styled components?
I use MUI in my app and I have constructed a custom theme. I previously added the below code to extend my theme with new properties so that Typescript would stop throwing type errors (custom.d.ts).

However, when I use a styled component, I still get the type error below, how can I resolve this?

Code that throws error

```<code>import { styled } from '@mui/material';

const AvatarWrapperSuccess = styled(Avatar)(
      ({ theme }) => `
        background-color: ${theme.colors.success.lighter};
        color:  ${theme.colors.success.main};
  `
    );
</code>```

custom.d.ts

```<code>import { Theme } from "@mui/material";
import {
  Palette as MuiPalette,
  PaletteColor,
  PaletteOptions as MuiPaletteOptions,
} from "@mui/material/styles/createPalette";

interface PaletteColorWithLighter extends PaletteColor {
  lighter: string;
}

interface Colors extends MuiPalette {
  alpha: {
    trueWhite: {
      [key: number]: string;
    };
    white: {
      [key: number]: string;
    };
    black: {
      [key: number]: string;
    };
  };

  gradients: {
    [key: string]: string;
  };

  results: {
    good: PaletteColor;
    caution: PaletteColor;
    bad: PaletteColor;
  };
}

declare module "@mui/material/styles" {
  interface Theme {
    colors: Colors;
    general: {
      reactFrameworkColor: string;
      borderRadiusSm: string;
      borderRadius: string;
      borderRadiusLg: string;
      borderRadiusXl: string;
    };
  }
  // allow configuration using `createTheme`
  interface ThemeOptions {
    colors: Colors;
    general: {
      reactFrameworkColor: string;
      borderRadiusSm: string;
      borderRadius: string;
      borderRadiusLg: string;
      borderRadiusXl: string;
    };
  }
}

declare module "@mui/styles/defaultTheme" {
  // eslint-disable-next-line @typescript-eslint/no-empty-interface (remove this line if you don't have the rule enabled)
  interface DefaultTheme extends Theme {}
}
</code>```

Body:
I use MUI in my app and I have constructed a custom theme. I previously added the below code to extend my theme with new properties so that Typescript would stop throwing type errors (custom.d.ts).

However, when I use a styled component, I still get the type error below, how can I resolve this?

Code that throws error

import { styled } from '@mui/material';

const AvatarWrapperSuccess = styled(Avatar)(
      ({ theme }) => `
        background-color: ${theme.colors.success.lighter};
        color:  ${theme.colors.success.main};
  `
    );

custom.d.ts

import { Theme } from "@mui/material";
import {
  Palette as MuiPalette,
  PaletteColor,
  PaletteOptions as MuiPaletteOptions,
} from "@mui/material/styles/createPalette";

interface PaletteColorWithLighter extends PaletteColor {
  lighter: string;
}

interface Colors extends MuiPalette {
  alpha: {
    trueWhite: {
      [key: number]: string;
    };
    white: {
      [key: number]: string;
    };
    black: {
      [key: number]: string;
    };
  };

  gradients: {
    [key: string]: string;
  };

  results: {
    good: PaletteColor;
    caution: PaletteColor;
    bad: PaletteColor;
  };
}

declare module "@mui/material/styles" {
  interface Theme {
    colors: Colors;
    general: {
      reactFrameworkColor: string;
      borderRadiusSm: string;
      borderRadius: string;
      borderRadiusLg: string;
      borderRadiusXl: string;
    };
  }
  // allow configuration using `createTheme`
  interface ThemeOptions {
    colors: Colors;
    general: {
      reactFrameworkColor: string;
      borderRadiusSm: string;
      borderRadius: string;
      borderRadiusLg: string;
      borderRadiusXl: string;
    };
  }
}

declare module "@mui/styles/defaultTheme" {
  // eslint-disable-next-line @typescript-eslint/no-empty-interface (remove this line if you don't have the rule enabled)
  interface DefaultTheme extends Theme {}
}


问:
Dynamic background change using 3 buttons - ionic
I am just learning and I got stuck. I am trying change background (ex. red, blue, green) of ion-content with three buttons. the problem is that I am not able to change it in correct way. I would like to switch between the background when I press the choosen button.

<ion-content [ngClass]="{ 'use-pink-background': pinkBackground, 'use-blue-background':blueBackground,  'use-green-background': greenBackground}">

<ion-button (click)="handleClick()">
pink

<ion-button (click)="handleClick1()">
blue
 <ion-button (click)="handleClick2()">
green

----------------------------------
```<code>public pinkBackground:any;
public blueBackground:any;
public greenBackground:any;

constructor() {}

handleClick() {
  this.pinkBackground = !this.pinkBackground;
}

handleClick1() {
  this.blueBackground = !this.blueBackground;
}

handleClick2() {
  this.greenBackground = !this.greenBackground;
}
</code>```

```<code>.use-pink-background {
  --ion-background-color: pink;
}

.use-blue-background {
  --ion-background-color: blue;
}

.use-green-background {
  --ion-background-color: green;
}
</code>```

When I click on the buttons start from first one to the last one is ok. But when I want to click random button it's not working correctly. You have to double clik on the previous one and then you can click  the button you want

Body:
I am just learning and I got stuck. I am trying change background (ex. red, blue, green) of ion-content with three buttons. the problem is that I am not able to change it in correct way. I would like to switch between the background when I press the choosen button.

<ion-content [ngClass]="{ 'use-pink-background': pinkBackground, 'use-blue-background':blueBackground,  'use-green-background': greenBackground}">

<ion-button (click)="handleClick()">
pink

<ion-button (click)="handleClick1()">
blue
 <ion-button (click)="handleClick2()">
green

----------------------------------

public pinkBackground:any;
public blueBackground:any;
public greenBackground:any;

constructor() {}

handleClick() {
  this.pinkBackground = !this.pinkBackground;
}

handleClick1() {
  this.blueBackground = !this.blueBackground;
}

handleClick2() {
  this.greenBackground = !this.greenBackground;
}

.use-pink-background {
  --ion-background-color: pink;
}

.use-blue-background {
  --ion-background-color: blue;
}

.use-green-background {
  --ion-background-color: green;
}

When I click on the buttons start from first one to the last one is ok. But when I want to click random button it's not working correctly. You have to double clik on the previous one and then you can click  the button you want


问:
How to create OneToMany relationships with reids rom
I recently working on the redis ROM to create relationship among the Client and FileSystem, where FileSystem should have many client, my rom module looks like in below,

```<code>class Client(rom.Model):
    ip = rom.String(required=True, unique=True, index=True, prefix=True, suffix=True, keygen=rom.IDENTITY)

class FileSystem(rom.Model):
    fs_name = rom.String(required=True, unique=True, index=True, prefix=True, suffix=True, keygen=rom.IDENTITY)
    fs_type = rom.String(required=True )
    fs_creation_time = rom.DateTime(required=True)
    fs_mount_point = rom.String(required=True)
    fs_is_mounted = rom.Boolean(required=True)
    fs_is_dirty = rom.Boolean(required=True)
    fs_is_deleted = rom.Boolean(required=True)
    clist_lst = rom.OneToMany(Client)
</code>```

my first question is that I want the client is optional, and I could add it later when it is exposed to the client, however, I met when trying omit the parameter

```<code>ORMError Missing foreign table <class '__main__.Client'> referenced by FileSystem.clist_lst
</code>```

my second questions gonna be the fact that I am not still met the same error even if I create the Filesystem as in below:

```<code>fs_demo = FileSystem(fs_name='LL{}'.format(i),
                        fs_type ='NFS',
                        fs_creation_time=datetime.now(),
                        fs_mount_point='/tmp{}'.format(i),
                        fs_is_mounted=random.choice([True,False]),
                        fs_is_dirty=random.choice([True,False]),
                        fs_is_deleted=random.choice([True,False]),
                        clist_lst=Client(ip='1.2.3.4'))
fs_demo.save()
</code>```

May I know any thing I am doing wrong?

Body:
I recently working on the redis ROM to create relationship among the Client and FileSystem, where FileSystem should have many client, my rom module looks like in below,

class Client(rom.Model):
    ip = rom.String(required=True, unique=True, index=True, prefix=True, suffix=True, keygen=rom.IDENTITY)

class FileSystem(rom.Model):
    fs_name = rom.String(required=True, unique=True, index=True, prefix=True, suffix=True, keygen=rom.IDENTITY)
    fs_type = rom.String(required=True )
    fs_creation_time = rom.DateTime(required=True)
    fs_mount_point = rom.String(required=True)
    fs_is_mounted = rom.Boolean(required=True)
    fs_is_dirty = rom.Boolean(required=True)
    fs_is_deleted = rom.Boolean(required=True)
    clist_lst = rom.OneToMany(Client)

my first question is that I want the client is optional, and I could add it later when it is exposed to the client, however, I met when trying omit the parameter

ORMError Missing foreign table <class '__main__.Client'> referenced by FileSystem.clist_lst

my second questions gonna be the fact that I am not still met the same error even if I create the Filesystem as in below:

fs_demo = FileSystem(fs_name='LL{}'.format(i),
                        fs_type ='NFS',
                        fs_creation_time=datetime.now(),
                        fs_mount_point='/tmp{}'.format(i),
                        fs_is_mounted=random.choice([True,False]),
                        fs_is_dirty=random.choice([True,False]),
                        fs_is_deleted=random.choice([True,False]),
                        clist_lst=Client(ip='1.2.3.4'))
fs_demo.save()

May I know any thing I am doing wrong?


问:
Is there a way to handle the error handling scenario in IBM DB2 for below concept
A cursor in a procedure selects the SQL queries, runs them, and logs the results in a table. Currently, if the SQL query contains any errors, it will exit the handler and insert the log into the log table. However, I'm attempting to concatenate the error message and the code (VSQL. CODE) into the log database. Few SQLSTATE 42703,42625,07001 error has occurred.
Current Output - Error on Procedure :  . SQLSTATE: 07001. SQLCODE: -313. MESSAGE: Number of host variables not valid.

Expected Output - Error on Procedure :  . SQLSTATE: 07001. SQLCODE: -313. MESSAGE: Number of host variables not valid. Code 102

```<code>------**Sample code snippet**----
SET REFERENCEDT = @I_BSNDT ; ---Input param

FOR VSQL AS CUR1 CURSOR FOR
SELECT CODE, SQL_QUERY,MESSAGE,col2 FROM tablename

DO

IF COALESCE ( VSQL . col2 , '' ) = '' THEN

PREPARE SQL_QUERY FROM VSQL . SQL_QUERY ;
OPEN CSR2 USING REFERENCEDT ;

IF **SQLSTATE** <>'00000'
THEN
SET @SYS_MSG = 'Validation Query Error '
|| VSQL.CODE
|| '.' ;
SIGNAL SQLSTATE '70020' SET MESSAGE_TEXT = @SYS_MSG ;
END IF;

FETCH CSR2 INTO var1 , var2 ;

WHILE SQLSTATE <> '02000'
DO

INSERT INTO table1 ( REFERENCEDATE ,CODE , ERROR_STATUS ) VALUES
(  REFERENCEDT , VSQL . CODE, VSQL . MESSAGE ) ;
FETCH CSR2 INTO var1 , var2 ;

END WHILE ;
CLOSE CSR2 ;
END FOR ;
</code>```

Body:
A cursor in a procedure selects the SQL queries, runs them, and logs the results in a table. Currently, if the SQL query contains any errors, it will exit the handler and insert the log into the log table. However, I'm attempting to concatenate the error message and the code (VSQL. CODE) into the log database. Few SQLSTATE 42703,42625,07001 error has occurred.
Current Output - Error on Procedure :  . SQLSTATE: 07001. SQLCODE: -313. MESSAGE: Number of host variables not valid.

Expected Output - Error on Procedure :  . SQLSTATE: 07001. SQLCODE: -313. MESSAGE: Number of host variables not valid. Code 102

------**Sample code snippet**----
SET REFERENCEDT = @I_BSNDT ; ---Input param

FOR VSQL AS CUR1 CURSOR FOR
SELECT CODE, SQL_QUERY,MESSAGE,col2 FROM tablename

DO

IF COALESCE ( VSQL . col2 , '' ) = '' THEN

PREPARE SQL_QUERY FROM VSQL . SQL_QUERY ;
OPEN CSR2 USING REFERENCEDT ;

IF **SQLSTATE** <>'00000'
THEN
SET @SYS_MSG = 'Validation Query Error '
|| VSQL.CODE
|| '.' ;
SIGNAL SQLSTATE '70020' SET MESSAGE_TEXT = @SYS_MSG ;
END IF;

FETCH CSR2 INTO var1 , var2 ;

WHILE SQLSTATE <> '02000'
DO

INSERT INTO table1 ( REFERENCEDATE ,CODE , ERROR_STATUS ) VALUES
(  REFERENCEDT , VSQL . CODE, VSQL . MESSAGE ) ;
FETCH CSR2 INTO var1 , var2 ;

END WHILE ;
CLOSE CSR2 ;
END FOR ;


问:
Laravel Rule exists don't work with array
This is my validation rule, but with an invalid data they allow pass.

```<code>
            'curso_inteligencia_id'  => [
                'nullable',
                'array',

                ]
                 ,
            'curso_inteligencia_id*'  => [
                'exists:curso_inteligencia,id',
                'numeric',

</code>```

This is the invalid data "asdsadsa22" (the select2 plugin allow user to manual insert value "bug").

enter image description here

I hope that  the rule returns that the data is invalid and does not allow saving.

Body:
This is my validation rule, but with an invalid data they allow pass.

            'curso_inteligencia_id'  => [
                'nullable',
                'array',

                ]
                 ,
            'curso_inteligencia_id*'  => [
                'exists:curso_inteligencia,id',
                'numeric',

This is the invalid data "asdsadsa22" (the select2 plugin allow user to manual insert value "bug").

enter image description here

I hope that  the rule returns that the data is invalid and does not allow saving.


问:
Hide Hamburger Icon on a Assign Start Destination Fragment
I wish to Assign Start Destination on my Login Fragment, and Hide the Hamburg Icon on the same Fragment. For some reason it is not possible to do both.

First I setup this piece of code in my Main class

```<code>     public void setDrawer_Locked() {
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setDisplayShowHomeEnabled(false);
}

    public void setDrawer_UnLocked() {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }
</code>```

Second I add this piece of code to the LoginFragment onCreateView:

```<code>((Main)getActivity()).setDrawer_Locked();
</code>```

When I run the app and navigate to the Login Fragment the Hamburger Icon is gone.
Next, I Assign Start Destination on my Login Fragment and run the app again.

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.ssl.app, PID: 23701
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ssl.app/com.ssl.app.Main}: android.view.InflateException: Binary XML file line #19: Error inflating class fragment
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: android.view.InflateException: Binary XML file line #19: Error inflating class fragment
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
        at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
        at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
        at com.ssl.app.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:53)
        at com.ssl.app.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:47)
        at com.ssl.app.Main.onCreate(Main.java:30)
        at android.app.Activity.performCreate(Activity.java:5990)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
        at com.ssl.app.Main.setDrawer_Locked(Main.java:63)
        at com.ssl.app.ui.login.LoginFragment.onCreateView(LoginFragment.java:52)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:3104)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:524)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
        at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1424)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2968)
        at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:2879)
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3129)
        at androidx.fragment.app.FragmentStateManager.ensureInflatedView(FragmentStateManager.java:394)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:260)
        at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:142)
        at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:136)
        at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:248)
        at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:227)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
        at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
        at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
        at com.ssl.app.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:53)
        at com.ssl.app.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:47)
        at com.ssl.app.Main.onCreate(Main.java:30)
        at android.app.Activity.performCreate(Activity.java:5990)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
</code>```

The cause is that the setDisplayHomeAsUpEnabled(boolean)' is set on a null object reference.
I think this happens because this object is not yet created, so what is the workout here?

Some extra information:

Main.class

```<code>import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import com.google.android.material.navigation.NavigationView;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.ssl.app.databinding.ActivityMainBinding;

public class Main extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    private ActivityMainBinding binding;
    private static final String Image_DIRECTORY="/signdemo";
    DrawerLayout drawer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.appBarMain.toolbar);
        drawer = binding.drawerLayout;
        NavigationView navigationView = binding.navView;
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_Stocklist, R.id.nav_Settings)
                .setOpenableLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    public void setDrawer_Locked() {
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setDisplayShowHomeEnabled(false);

        if (getSupportActionBar() != null) {
            //drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            getSupportActionBar().setDisplayHomeAsUpEnabled(false);
            getSupportActionBar().setDisplayShowHomeEnabled(false);
        }
    }

    public void setDrawer_UnLocked() {
        //drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

}
</code>```

LoginFragment

```<code>package com.ssl.app.ui.login;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.ssl.app.Main;
import com.ssl.app.databinding.FragmentLoginBinding;
import com.ssl.app.R;
import com.ssl.app.controller.AuthController;

public class LoginFragment extends Fragment {
    private FragmentLoginBinding binding;
    private EditText username, password;
    private Button btnLogin;
    private View root;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceStage) {
        binding = FragmentLoginBinding.inflate(inflater, container, false);
        root = binding.getRoot();
        btnLogin = root.findViewById(R.id.btnLogin);
        username = root.findViewById(R.id.etName);
        password = root.findViewById(R.id.etPassword);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(username.getText().toString()) || TextUtils.isEmpty(password.getText().toString())){
                    Toast.makeText(getActivity(),
                            "Username / Password Required",
                            Toast.LENGTH_LONG).show();
                } else {
                    AuthController obj = new AuthController();
                    obj.login(getActivity());
                    //HomeActivity.home(getActivity());
                }
            }
        });

       ((Main)getActivity()).setDrawer_Locked();
        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //((Main)getActivity()).setDrawer_UnLocked();
        binding = null;
    }
}
</code>```

Body:
I wish to Assign Start Destination on my Login Fragment, and Hide the Hamburg Icon on the same Fragment. For some reason it is not possible to do both.

First I setup this piece of code in my Main class

     public void setDrawer_Locked() {
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setDisplayShowHomeEnabled(false);
}

    public void setDrawer_UnLocked() {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

Second I add this piece of code to the LoginFragment onCreateView:

((Main)getActivity()).setDrawer_Locked();

When I run the app and navigate to the Login Fragment the Hamburger Icon is gone.
Next, I Assign Start Destination on my Login Fragment and run the app again.

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.ssl.app, PID: 23701
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ssl.app/com.ssl.app.Main}: android.view.InflateException: Binary XML file line #19: Error inflating class fragment
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: android.view.InflateException: Binary XML file line #19: Error inflating class fragment
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
        at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
        at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
        at com.ssl.app.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:53)
        at com.ssl.app.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:47)
        at com.ssl.app.Main.onCreate(Main.java:30)
        at android.app.Activity.performCreate(Activity.java:5990)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
        at com.ssl.app.Main.setDrawer_Locked(Main.java:63)
        at com.ssl.app.ui.login.LoginFragment.onCreateView(LoginFragment.java:52)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:3104)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:524)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
        at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:113)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1424)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2968)
        at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:2879)
        at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:3129)
        at androidx.fragment.app.FragmentStateManager.ensureInflatedView(FragmentStateManager.java:394)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:260)
        at androidx.fragment.app.FragmentLayoutInflaterFactory.onCreateView(FragmentLayoutInflaterFactory.java:142)
        at androidx.fragment.app.FragmentController.onCreateView(FragmentController.java:136)
        at androidx.fragment.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:248)
        at androidx.fragment.app.FragmentActivity.onCreateView(FragmentActivity.java:227)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
        at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
        at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
        at com.ssl.app.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:53)
        at com.ssl.app.databinding.ActivityMainBinding.inflate(ActivityMainBinding.java:47)
        at com.ssl.app.Main.onCreate(Main.java:30)
        at android.app.Activity.performCreate(Activity.java:5990)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
        at android.app.ActivityThread.access$800(ActivityThread.java:151)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5254)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

The cause is that the setDisplayHomeAsUpEnabled(boolean)' is set on a null object reference.
I think this happens because this object is not yet created, so what is the workout here?

Some extra information:

Main.class

import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import com.google.android.material.navigation.NavigationView;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import com.ssl.app.databinding.ActivityMainBinding;

public class Main extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;
    private ActivityMainBinding binding;
    private static final String Image_DIRECTORY="/signdemo";
    DrawerLayout drawer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        setSupportActionBar(binding.appBarMain.toolbar);
        drawer = binding.drawerLayout;
        NavigationView navigationView = binding.navView;
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_Stocklist, R.id.nav_Settings)
                .setOpenableLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }

    public void setDrawer_Locked() {
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        getSupportActionBar().setDisplayShowHomeEnabled(false);

        if (getSupportActionBar() != null) {
            //drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            getSupportActionBar().setDisplayHomeAsUpEnabled(false);
            getSupportActionBar().setDisplayShowHomeEnabled(false);
        }
    }

    public void setDrawer_UnLocked() {
        //drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

}

LoginFragment

package com.ssl.app.ui.login;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.ssl.app.Main;
import com.ssl.app.databinding.FragmentLoginBinding;
import com.ssl.app.R;
import com.ssl.app.controller.AuthController;

public class LoginFragment extends Fragment {
    private FragmentLoginBinding binding;
    private EditText username, password;
    private Button btnLogin;
    private View root;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceStage) {
        binding = FragmentLoginBinding.inflate(inflater, container, false);
        root = binding.getRoot();
        btnLogin = root.findViewById(R.id.btnLogin);
        username = root.findViewById(R.id.etName);
        password = root.findViewById(R.id.etPassword);

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(username.getText().toString()) || TextUtils.isEmpty(password.getText().toString())){
                    Toast.makeText(getActivity(),
                            "Username / Password Required",
                            Toast.LENGTH_LONG).show();
                } else {
                    AuthController obj = new AuthController();
                    obj.login(getActivity());
                    //HomeActivity.home(getActivity());
                }
            }
        });

       ((Main)getActivity()).setDrawer_Locked();
        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        //((Main)getActivity()).setDrawer_UnLocked();
        binding = null;
    }
}


问:
How do I verify linearity in a stratified variable?
If we look at proportional hazards, ejection_fraction doesn't meet the assumption for cox regression. I choose to stratify it within my R script.

```<code>                           chisq df     p
age                       0.05920  1 0.808
anaemia                   0.00531  1 0.942
creatinine_phosphokinase  0.98930  1 0.320
ejection_fraction         4.76495  1 0.029
serum_sodium              0.09377  1 0.759
serum_creatinine          1.67518  1 0.196
hypertension              0.00943  1 0.923
GLOBAL                   10.52084  7 0.161
</code>```

This is the code I have for checking the linearity of that same variable

```<code>X <- HF$ejection_fraction
Y <- resid(reducedMod, type = "martingale")
plot(X, Y, pch = 20, col = "darkgray",
     xlab = "Ejection Fraction", ylab = "Martingale Residual")+
abline(h = 0)+
lines(smooth.spline(X, Y, df = 7), lty = 2, lwd = 2)
</code>```

What code do I use to get the residuals for the stratified version of ejection_fraction?

... is that even something you do?

Body:
If we look at proportional hazards, ejection_fraction doesn't meet the assumption for cox regression. I choose to stratify it within my R script.

                           chisq df     p
age                       0.05920  1 0.808
anaemia                   0.00531  1 0.942
creatinine_phosphokinase  0.98930  1 0.320
ejection_fraction         4.76495  1 0.029
serum_sodium              0.09377  1 0.759
serum_creatinine          1.67518  1 0.196
hypertension              0.00943  1 0.923
GLOBAL                   10.52084  7 0.161

This is the code I have for checking the linearity of that same variable

X <- HF$ejection_fraction
Y <- resid(reducedMod, type = "martingale")
plot(X, Y, pch = 20, col = "darkgray",
     xlab = "Ejection Fraction", ylab = "Martingale Residual")+
abline(h = 0)+
lines(smooth.spline(X, Y, df = 7), lty = 2, lwd = 2)

What code do I use to get the residuals for the stratified version of ejection_fraction?

... is that even something you do?


问:
UICollectionViewCell button callback
How to implement callback for example of button tap inside UICollectionViewCell's UIContentView or better how to do it in Combine way?

Cell registration inside UICollectionView:

```<code>let cellRegistration = UICollectionView.CellRegistration<MyCell, Item> { (cell, indexPath, item) in
   cell.item = item
}

</code>```

Cell:

```<code>class MyCell: UICollectionViewCell {

    var item: Item?

    override func updateConfiguration(using state: UICellConfigurationState) {
        var newConfiguration = MyContentConfiguration().updated(for: state)
        newConfiguration.name = item?.title
        contentConfiguration = newConfiguration
    }
}
</code>```

Content configuration:

```<code>struct MyContentConfiguration: UIContentConfiguration, Hashable {

    var name: String?

    func makeContentView() -> UIView & UIContentView {
        return MyContentView(configuration: self)
    }
}
</code>```

Content view:

```<code>class MyContentView: UIView, UIContentView {

    let title = UILabel()

    private var currentConfiguration: MyContentConfiguration!
    var configuration: UIContentConfiguration {
        get {
            currentConfiguration
        }
        set {
            guard let newConfiguration = newValue as? MyContentConfiguration else {
                return
            }
            apply(configuration: newConfiguration)
        }
    }

    init(configuration: MyContentConfiguration) {
        super.init(frame: .zero)

        // Create the content view UI
        setupUI()
        apply(configuration: configuration)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

private extension MyContentView {

    private func setupUI() {
       // UI stuff
    }

    private func apply(configuration: MyContentConfiguration) {
        guard currentConfiguration != configuration else {
            return
        }

        currentConfiguration = configuration

        // Set data to UI elements
        title.text = title
        //etc..
    }
}
</code>```

Inside MyContentView there'll be a button for example. This button should be bound with item, so when it's tapped - some callback or Combine publisher should emit value, which I've got to catch inside my collection view.

How I've implemented this previously:

```<code>let cellRegistration = UICollectionView.CellRegistration<MyCell, Item> { (cell, indexPath, item) in
   cell.item = item
   //Catch value which is bound with associated item
   cell.somePublisher
                .sink { [weak self] in
                    guard let self = self else { return }

                    self.subscribePublisher.send($0)
                }
                .store(in: &self.subscriptions)
}
</code>```

Cell:

```<code>class MyCell: UICollectionViewCell {

    var item: Item?
    public private(set) var somePublisher = CurrentValueSubject<Bool?, Never>(nil)

    //UI setup, etc..

    //Emit value for a button tap gesture
    @objc func handleTap() {
       somePublisher.send(true)
    }
}
</code>```

Is it possible to implement this behavior using UIContentView & UIContentConfiguration?

Title: UICollectionViewCell button callback

Body:
How to implement callback for example of button tap inside UICollectionViewCell's UIContentView or better how to do it in Combine way?

Cell registration inside UICollectionView:

let cellRegistration = UICollectionView.CellRegistration<MyCell, Item> { (cell, indexPath, item) in
   cell.item = item
}

Cell:

class MyCell: UICollectionViewCell {

    var item: Item?

    override func updateConfiguration(using state: UICellConfigurationState) {
        var newConfiguration = MyContentConfiguration().updated(for: state)
        newConfiguration.name = item?.title
        contentConfiguration = newConfiguration
    }
}

Content configuration:

struct MyContentConfiguration: UIContentConfiguration, Hashable {

    var name: String?

    func makeContentView() -> UIView & UIContentView {
        return MyContentView(configuration: self)
    }
}

Content view:

class MyContentView: UIView, UIContentView {

    let title = UILabel()

    private var currentConfiguration: MyContentConfiguration!
    var configuration: UIContentConfiguration {
        get {
            currentConfiguration
        }
        set {
            guard let newConfiguration = newValue as? MyContentConfiguration else {
                return
            }
            apply(configuration: newConfiguration)
        }
    }

    init(configuration: MyContentConfiguration) {
        super.init(frame: .zero)

        // Create the content view UI
        setupUI()
        apply(configuration: configuration)
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}

private extension MyContentView {

    private func setupUI() {
       // UI stuff
    }

    private func apply(configuration: MyContentConfiguration) {
        guard currentConfiguration != configuration else {
            return
        }

        currentConfiguration = configuration

        // Set data to UI elements
        title.text = title
        //etc..
    }
}

Inside MyContentView there'll be a button for example. This button should be bound with item, so when it's tapped - some callback or Combine publisher should emit value, which I've got to catch inside my collection view.

How I've implemented this previously:

let cellRegistration = UICollectionView.CellRegistration<MyCell, Item> { (cell, indexPath, item) in
   cell.item = item
   //Catch value which is bound with associated item
   cell.somePublisher
                .sink { [weak self] in
                    guard let self = self else { return }

                    self.subscribePublisher.send($0)
                }
                .store(in: &self.subscriptions)
}

Cell:

class MyCell: UICollectionViewCell {

    var item: Item?
    public private(set) var somePublisher = CurrentValueSubject<Bool?, Never>(nil)

    //UI setup, etc..

    //Emit value for a button tap gesture
    @objc func handleTap() {
       somePublisher.send(true)
    }
}

Is it possible to implement this behavior using UIContentView & UIContentConfiguration?


问:
Restart from failed stage of Upstream Pipeline should restart from failed stage of Downstream Pipeline
I've a upstream pipeline say - UpstreamPipeline with stages - A -> B -> C and stage B calls downstream pipeline say - DownstreamPipeline with stages X -> Y -> Z

If I trigger UpstreamPipeline, B stage calls DownstreamPipeline and suppose it fails at stage Y due to some false failure.

As pipeline fails with false failure, I want to restart UpstreamPipeline from failed stage i.e B.

If I do so, it starts from stage B and which calls DownstreamPipeline but DownstreamPipeline starts from very first stage i.e. X.

Actually it is expected to start from stage Y as it had failed there.

Is there a way with which if upstream pipeline is triggered from failed stage, downstream pipeline should also run from its failed stage instead of starting from very first stage?


问:
Describing a data structure that supports the following actions for saving items and their prices
In carpentry, We want to introduce an data system that will store the items that are produced and their prices. for example
A table at the price of 3500, a chair at the price of 200, etc. Each item is identified by the combination of its name and price
That is, 2 cabinets at different prices are different parts. There are at most M different products in carpentry.
We need to describe a data structure to support the following actions:

```<code>init() - Initializing an empty structure. Running time O(M)
insert(x) -  Inserting an element into the system. Running time O(logn) in the worst case
updateCost(x, cost) - Update the price of element x, if the element does not exist (or if there is an element with a the same name the same price as the update price) an error message will be issued. Running time O(logn) in the worst case.
findOld(name) - Finds the first product inserted into a structure with a certain name. runtime O(logn) in the worst case.
removeMin() -  Takes out the product with the lowest price. Running time O(logn) in the worst case
</code>```

My first approach is using avl tree but i got stuck there

Body:
In carpentry, We want to introduce an data system that will store the items that are produced and their prices. for example
A table at the price of 3500, a chair at the price of 200, etc. Each item is identified by the combination of its name and price
That is, 2 cabinets at different prices are different parts. There are at most M different products in carpentry.
We need to describe a data structure to support the following actions:

init() - Initializing an empty structure. Running time O(M)
insert(x) -  Inserting an element into the system. Running time O(logn) in the worst case
updateCost(x, cost) - Update the price of element x, if the element does not exist (or if there is an element with a the same name the same price as the update price) an error message will be issued. Running time O(logn) in the worst case.
findOld(name) - Finds the first product inserted into a structure with a certain name. runtime O(logn) in the worst case.
removeMin() -  Takes out the product with the lowest price. Running time O(logn) in the worst case

My first approach is using avl tree but i got stuck there