问:
Get real value or None from a HashMap
I have a struct that I would like to fill based on a potentially incomplete hash map:

```<code>#[derive(Debug)]
struct Sue {
    children: Option<u8>,
    cats: Option<u8>,
    samoyeds: Option<u8>,
    pomeranians: Option<u8>,
    akitas: Option<u8>,
    vizslas: Option<u8>,
    goldfish: Option<u8>,
    trees: Option<u8>,
    cars: Option<u8>,
    perfumes: Option<u8>,
}

impl Sue {
    fn from_line(line: &str) -> Sue {
        let data: Vec<&str> = line.split(" ").collect();

        let items: HashMap<String, u8> = data[2..data.len()]
            .chunks(2)
            .map(|item| {
                (
                    String::from(item[0].trim_end_matches(":")),
                    String::from(item[1].trim_end_matches(",")).parse().unwrap(),
                )
            })
            .collect();

        println!("{:?}\n", items);

        Sue {
            // children: match items.get("children"){
                // Some(val) => Some(*val),
                // None => None,
            // },
            children: *items.get("children"),
            // cats: Some(0),
            // samoyeds: Some(0),
            // pomeranians: Some(0),
            // akitas: Some(0),
            // vizslas: Some(0),
            // goldfish: Some(0),
            // trees: Some(0),
            // cars: Some(0),
            // perfumes: Some(0),
        }
    }
}
</code>```

In the snippet above, the items hash map may or may not contain a key for each field of the Sue struct. My idea was to build a hash map with the input, and then for each field of the struct, try to access the corresponding key of the hashmap. If the key is in the hashmap, return the dereferenced value. If the key isn't in the hashmap, return None.

I know I can do that with a match (there is a couple of lines commented showing how I would do this), but I was wondering if there is a more efficient way to do this (it's a lot of boilerplate; one match for each field).

If I run the code above, I'll get:

```<code>error[E0614]: type `Option<&u8>` cannot be dereferenced
</code>```

Any idea? I do want to keep None if the key isn't found. Also for reference, this snippet is for advent of code 2015 day 16.

答:
For u8, either of the methods John Kugelman mentioned work great. However, there are some types that are neither Copy nor cheaply cloneable (maybe they don't implement Clone at all, or they do but it is costly).

A third option is to remove the item from the map:

struct ExpensiveClone(u8);

impl Clone for ExpensiveClone {
    fn clone(&self) -> Self {
        std::thread::sleep(Duration::from_secs(1));
        Self(self.0)
    }
}
```
<p>In this case, cloning would likely be prohibitively expensive. Instead, if you have owned or mutable access to the map, you can remove it, transferring ownership of the value from the map to your function, without needing to clone the data:</p>
<pre class="lang-rust prettyprint-override"><code>let mut map = HashMap::new();
map.insert(1, ExpensiveClone(1));
let expensive_clone = map.remove(&1).unwrap();
assert_eq!(expensive_clone.0, 1);
</code>```

It goes without saying that this only works if you can modify the map though

Title: Get real value or None from a HashMap

Body:
I have a struct that I would like to fill based on a potentially incomplete hash map:

#[derive(Debug)]
struct Sue {
    children: Option<u8>,
    cats: Option<u8>,
    samoyeds: Option<u8>,
    pomeranians: Option<u8>,
    akitas: Option<u8>,
    vizslas: Option<u8>,
    goldfish: Option<u8>,
    trees: Option<u8>,
    cars: Option<u8>,
    perfumes: Option<u8>,
}

impl Sue {
    fn from_line(line: &str) -> Sue {
        let data: Vec<&str> = line.split(" ").collect();

        let items: HashMap<String, u8> = data[2..data.len()]
            .chunks(2)
            .map(|item| {
                (
                    String::from(item[0].trim_end_matches(":")),
                    String::from(item[1].trim_end_matches(",")).parse().unwrap(),
                )
            })
            .collect();

        println!("{:?}\n", items);

        Sue {
            // children: match items.get("children"){
                // Some(val) => Some(*val),
                // None => None,
            // },
            children: *items.get("children"),
            // cats: Some(0),
            // samoyeds: Some(0),
            // pomeranians: Some(0),
            // akitas: Some(0),
            // vizslas: Some(0),
            // goldfish: Some(0),
            // trees: Some(0),
            // cars: Some(0),
            // perfumes: Some(0),
        }
    }
}

In the snippet above, the items hash map may or may not contain a key for each field of the Sue struct. My idea was to build a hash map with the input, and then for each field of the struct, try to access the corresponding key of the hashmap. If the key is in the hashmap, return the dereferenced value. If the key isn't in the hashmap, return None.

I know I can do that with a match (there is a couple of lines commented showing how I would do this), but I was wondering if there is a more efficient way to do this (it's a lot of boilerplate; one match for each field).

If I run the code above, I'll get:

error[E0614]: type `Option<&u8>` cannot be dereferenced

Any idea? I do want to keep None if the key isn't found. Also for reference, this snippet is for advent of code 2015 day 16.

Body:
For u8, either of the methods John Kugelman mentioned work great. However, there are some types that are neither Copy nor cheaply cloneable (maybe they don't implement Clone at all, or they do but it is costly).

A third option is to remove the item from the map:

struct ExpensiveClone(u8);

impl Clone for ExpensiveClone {
    fn clone(&self) -> Self {
        std::thread::sleep(Duration::from_secs(1));
        Self(self.0)
    }
}

In this case, cloning would likely be prohibitively expensive. Instead, if you have owned or mutable access to the map, you can remove it, transferring ownership of the value from the map to your function, without needing to clone the data:

let mut map = HashMap::new();
map.insert(1, ExpensiveClone(1));
let expensive_clone = map.remove(&1).unwrap();
assert_eq!(expensive_clone.0, 1);

It goes without saying that this only works if you can modify the map though


来源: stackexchange

问:
How to extract a colormap from a colorbar image and use it in a heatmap
I have a requirement to produce color scale based on the threshold values as shown below:

At present, I'm only able to populate color scale as shown below:

def create_png(a_group,req_df):
    import matplotlib.pyplot as plt
    plt.figure(figsize=(15, 8))
    heat_plot = sns.heatmap(req_df, vmin=-120, vmax=-80, cmap="viridis", yticklabels=False,square=True,linecolor='black',linewidths=.5)
    fig = heat_plot.get_figure()
```

答:
You can create a ListedColormap from a list of colors.  The following approach reads the image from the colormap and extracts the 45 colors of the centers of the colored rectangles. Note that the quality would be a bit better if the original image were saved ax png without passing through jpeg. As jpeg mixes the colors a bit, they might be slightly different from the originals.

import matplotlib.pyplot as plt
import numpy as np

img = plt.imread('desired_colormap.jpg')
# x and y positions of the rectangle centers are found via an image editor
xpos = 12
ypos_124 = 768
ypos_80 = 22
val_min = -124
val_max = -80
# extract the color from each of 45 rectangles
colors = [img[int(ypos), xpos] / 255
          for ypos in np.linspace(ypos_124, ypos_80, val_max - val_min + 1)]
```
<p>You can then use this list of colors to create a colormap and use it in seaborn. It looks a bit psychedelic.</p>
<pre class="lang-py prettyprint-override"><code>import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns
import numpy as np
from scipy.ndimage import gaussian_filter

# colors were read from image

# create some smooth test data, with the given range of values
data = gaussian_filter(np.random.rand(1000, 1000), 20)
data -= data.min()
data *= (val_max - val_min) / data.max()
data += val_min

fig, ax = plt.subplots(figsize=(12, 10))
sns.set_style('white')
sns.heatmap(data=data, xticklabels=[], yticklabels=[],
            cmap=ListedColormap(colors), vmin=val_min - 0.5, vmax=val_max + 0.5,
            cbar_kws={'ticks': np.arange(val_min, val_max + 1)}, ax=ax)
plt.tight_layout()
plt.show()
</code>```

PS: If you want to save the list for multiple use, you can convert the colors to hex (matplotlib.color.to_hex). The list would then be

colors = ['#000000', '#000000', '#68696b', '#00008c', '#0001cd', '#0102fa', '#4467e5', '#6296ea', '#4683b2',
          '#4981b4', '#007f85', '#2d8a5d', '#619ca2', '#65cdaa', '#0afafb', '#02f99e', '#74fc02', '#adff31',
          '#f6fbd2', '#f0e7ac', '#f1e68a', '#fbff0a', '#fdda00', '#dba51e', '#f9a608', '#ff8a06', '#d16920',
          '#8d4312', '#fe804e', '#fe5945', '#fd4900', '#fe0300', '#fcb2c1', '#f0807c', '#fd6ba9', '#fc02f9',
          '#dd9ee4', '#ba55d7', '#9202d6', '#85038b', '#7f017c', '#480181', '#4c0084', '#4b007f', '#480185']
```

ContentLicense: CC BY-SA 4.0

Body:
You can create a ListedColormap from a list of colors.  The following approach reads the image from the colormap and extracts the 45 colors of the centers of the colored rectangles. Note that the quality would be a bit better if the original image were saved ax png without passing through jpeg. As jpeg mixes the colors a bit, they might be slightly different from the originals.

import matplotlib.pyplot as plt
import numpy as np

img = plt.imread('desired_colormap.jpg')
# x and y positions of the rectangle centers are found via an image editor
xpos = 12
ypos_124 = 768
ypos_80 = 22
val_min = -124
val_max = -80
# extract the color from each of 45 rectangles
colors = [img[int(ypos), xpos] / 255
          for ypos in np.linspace(ypos_124, ypos_80, val_max - val_min + 1)]

You can then use this list of colors to create a colormap and use it in seaborn. It looks a bit psychedelic.

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import seaborn as sns
import numpy as np
from scipy.ndimage import gaussian_filter

# colors were read from image

# create some smooth test data, with the given range of values
data = gaussian_filter(np.random.rand(1000, 1000), 20)
data -= data.min()
data *= (val_max - val_min) / data.max()
data += val_min

fig, ax = plt.subplots(figsize=(12, 10))
sns.set_style('white')
sns.heatmap(data=data, xticklabels=[], yticklabels=[],
            cmap=ListedColormap(colors), vmin=val_min - 0.5, vmax=val_max + 0.5,
            cbar_kws={'ticks': np.arange(val_min, val_max + 1)}, ax=ax)
plt.tight_layout()
plt.show()

PS: If you want to save the list for multiple use, you can convert the colors to hex (matplotlib.color.to_hex). The list would then be

colors = ['#000000', '#000000', '#68696b', '#00008c', '#0001cd', '#0102fa', '#4467e5', '#6296ea', '#4683b2',
          '#4981b4', '#007f85', '#2d8a5d', '#619ca2', '#65cdaa', '#0afafb', '#02f99e', '#74fc02', '#adff31',
          '#f6fbd2', '#f0e7ac', '#f1e68a', '#fbff0a', '#fdda00', '#dba51e', '#f9a608', '#ff8a06', '#d16920',
          '#8d4312', '#fe804e', '#fe5945', '#fd4900', '#fe0300', '#fcb2c1', '#f0807c', '#fd6ba9', '#fc02f9',
          '#dd9ee4', '#ba55d7', '#9202d6', '#85038b', '#7f017c', '#480181', '#4c0084', '#4b007f', '#480185']


问:
How to run several js files at once?
I've created simple tool that I would like to work daily to get new data everyday. I have few js files that I would like to run at once. Instead of manually typing in terminal:

```<code>node news.js
node main.js
node weather.js
</code>```

Can I automate it somehow to type one command and everything runs automatically when previous file finished task?

Thanks

答:
Chain the commands:

```<code>node news.js && node main.js && node weather.js
</code>```

By using the && operator you are instructing the system to wait for the end of the first command to run the second. The second command will only run if the first ends with status code 0 and the third will only run if the second also ends with status 0.

Exit status 0 indicates the command finished successfully.

If you don't need the first command to finish successfully you could replace the '&&' with ';' to continue anyway despite error status. If you are on Windows the ; operator doesn't work on command prompt but it does with Powershell.

If you rather want to run them in parallel you could also use:

```<code>node news.js & node main.js & node weather.js
</code>```

Title: How to run several js files at once?

Body:
I've created simple tool that I would like to work daily to get new data everyday. I have few js files that I would like to run at once. Instead of manually typing in terminal:

node news.js
node main.js
node weather.js

Can I automate it somehow to type one command and everything runs automatically when previous file finished task?

Thanks

Body:
Chain the commands:

node news.js && node main.js && node weather.js

By using the && operator you are instructing the system to wait for the end of the first command to run the second. The second command will only run if the first ends with status code 0 and the third will only run if the second also ends with status 0.

Exit status 0 indicates the command finished successfully.

If you don't need the first command to finish successfully you could replace the '&&' with ';' to continue anyway despite error status. If you are on Windows the ; operator doesn't work on command prompt but it does with Powershell.

If you rather want to run them in parallel you could also use:

node news.js & node main.js & node weather.js


问:
Using public static void main(String args[]) to get output from child class JAVA
I am trying to understand the issue here, it stated the command execution failed, but I cannot seem to find the issue here but I do get it that one of the reasons is public static void main(String args{}) is not functioning as I hope so.

My code is down below:

```<code>import java.util.*;

public class Children {
    public static void main(String args[]) {
       public String name;
       public int friends;

       public Children(String name) {
           this.name = name;
           friends = 0;
       }
       public void getFriend(Children k) {
           friends++;
       }

       public int numFriends() {
           return friends;
       }

       public String playsalong() {
           return "joy";
       }

       public String toString() {
           return "a child named "+name;
       }
   }
}

class Girl extends Children {
   public static void main(String args[]) {
       public Girl(String name) {
           super(name);
        friends = 1;
       }

       public void getFriend(Children k) {
           if (k instanceof Girl)
           friends += k.numFriends( );
           else
           friends++;
       }

       public String toString( ) {
           return "a girl named "+ name;
       }
   }
}

class Boy extends Children {
   public static void main(String args[]) {
       public Boy(String name) {
           super(name);
       }

       public String toString() {
           return "a boy named " +name;
       }
   }
}
</code>```

答:
the access modifiers are applied in instance variable, it can not be applied inside local scope what ever is static field or not, it's for describing the access level for other object, object of classes look at instance membres.

another issue you are trying to define a constructor of class Girl inside the main method and outside the class Girls itself, which is not allowed class consructor should be inside that class and in instance scope not in any other method static or not static.

constructor should be defined in an instance scope of it's class not in other class

so

```<code>public Girl(String name) {
       super(name);
    friends = 1;
   }
</code>```

this code should be defined in Girl class and be sure that is defined inside instance scope not static or local scope.

for other methods you just need an curly brace "}" to end the main method the other methods will be defined speratly.

for the class Children same thing appilied

constructor of class Boy should be replaced by Children constructor and defined outside main method.

method toString is really fine just need curly brace } befor it to encolse the main method, because here you are defining it inside main method.

here is the valid Children class:

```<code>public class Children {
   public String name;
   public int friends;

   public Children(String name) {
        super()// this optional because parent class define only no-
                     // argument constructor
       this.name = name;
       friends = 0;
   }

public static void main(String args[]) {

       Children children = new Children();
             children.getFriend();
             children.numFriends();
             children.playsalong();
             children.toString() ;

  }

   public void getFriend(Children k) {
       friends++;
   }

   public int numFriends() {
       return friends;
   }

   public String playsalong() {
       return "joy";
   }

   public String toString() {
       return "a child named "+name;
   }

</code>```

}

and here the Girl class definition

```<code>class Girl extends Children {
      public Children(String name) {
   // super(name); /*here superclass do not define any constructor
                  with String argument so this will not compile*/
       super()// this is what required and it optional as said before

       friends = 1;
   }
 public static void main(String args[]) {

            Girls girl = new Girl();

      }

   public void getFriend(Children k) {
       if (k instanceof Girl)
       friends += k.numFriends( );
       else
       friends++;
   }

   public String toString( ) {
       return "a girl named "+ name;
   }
</code>```

}

the boy class definition

```<code>class Boy extends Children {
  public Boy(String name) {
     super(name);/* this is fine and it mendatory since parent class
          Children has a constructor with String parameter, it should
          be called like this or code will not compile */
    }
   public static void main(String args[]) {

      Boy boy = new Boy("Alex");
   }
</code>```

Body:
I am trying to understand the issue here, it stated the command execution failed, but I cannot seem to find the issue here but I do get it that one of the reasons is public static void main(String args{}) is not functioning as I hope so.

My code is down below:

import java.util.*;

public class Children {
    public static void main(String args[]) {
       public String name;
       public int friends;

       public Children(String name) {
           this.name = name;
           friends = 0;
       }
       public void getFriend(Children k) {
           friends++;
       }

       public int numFriends() {
           return friends;
       }

       public String playsalong() {
           return "joy";
       }

       public String toString() {
           return "a child named "+name;
       }
   }
}

class Girl extends Children {
   public static void main(String args[]) {
       public Girl(String name) {
           super(name);
        friends = 1;
       }

       public void getFriend(Children k) {
           if (k instanceof Girl)
           friends += k.numFriends( );
           else
           friends++;
       }

       public String toString( ) {
           return "a girl named "+ name;
       }
   }
}

class Boy extends Children {
   public static void main(String args[]) {
       public Boy(String name) {
           super(name);
       }

       public String toString() {
           return "a boy named " +name;
       }
   }
}

Body:
the access modifiers are applied in instance variable, it can not be applied inside local scope what ever is static field or not, it's for describing the access level for other object, object of classes look at instance membres.

another issue you are trying to define a constructor of class Girl inside the main method and outside the class Girls itself, which is not allowed class consructor should be inside that class and in instance scope not in any other method static or not static.

constructor should be defined in an instance scope of it's class not in other class

so

public Girl(String name) {
       super(name);
    friends = 1;
   }

this code should be defined in Girl class and be sure that is defined inside instance scope not static or local scope.

for other methods you just need an curly brace "}" to end the main method the other methods will be defined speratly.

for the class Children same thing appilied

constructor of class Boy should be replaced by Children constructor and defined outside main method.

method toString is really fine just need curly brace } befor it to encolse the main method, because here you are defining it inside main method.

here is the valid Children class:

public class Children {
   public String name;
   public int friends;

   public Children(String name) {
        super()// this optional because parent class define only no-
                     // argument constructor
       this.name = name;
       friends = 0;
   }

public static void main(String args[]) {

       Children children = new Children();
             children.getFriend();
             children.numFriends();
             children.playsalong();
             children.toString() ;

  }

   public void getFriend(Children k) {
       friends++;
   }

   public int numFriends() {
       return friends;
   }

   public String playsalong() {
       return "joy";
   }

   public String toString() {
       return "a child named "+name;
   }

}

and here the Girl class definition

class Girl extends Children {
      public Children(String name) {
   // super(name); /*here superclass do not define any constructor
                  with String argument so this will not compile*/
       super()// this is what required and it optional as said before

       friends = 1;
   }
 public static void main(String args[]) {

            Girls girl = new Girl();

      }

   public void getFriend(Children k) {
       if (k instanceof Girl)
       friends += k.numFriends( );
       else
       friends++;
   }

   public String toString( ) {
       return "a girl named "+ name;
   }

}

the boy class definition

class Boy extends Children {
  public Boy(String name) {
     super(name);/* this is fine and it mendatory since parent class
          Children has a constructor with String parameter, it should
          be called like this or code will not compile */
    }
   public static void main(String args[]) {

      Boy boy = new Boy("Alex");
   }


问:
Python Pandas: How I can determine the distribution of my dataset?
This is my dataset with two columns of NS and count.

```<code>    NS                                                count
0   ns18.dnsdhs.com.                                  1494
1   ns0.relaix.net.                                   1835
2   ns2.techlineindia.com.                            383
3   ns2.microwebsys.com.                              1263
4   ns2.holy-grail-body-transformation-program.com.   1
5   ns2.chavano.com.                                  1
6   ns1.x10host.ml.                                   17
7   ns1.amwebaz.info.                                 48
8   ns2.guacirachocolates.com.br.                     1
9   ns1.clicktodollars.com.                           2
</code>```

Now I would like to see how many NSs have the same count by plotting it. My own guess is that I can use histogram to see that but I am not sure how. Can anyone help?

答:
```<code>#Distribution of count
plt.figure(figsize=(6,6))
sns.distplot(Dataset['Count'])
plt.title('Count Distribution')
plt.show()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
This is my dataset with two columns of NS and count.

    NS                                                count
0   ns18.dnsdhs.com.                                  1494
1   ns0.relaix.net.                                   1835
2   ns2.techlineindia.com.                            383
3   ns2.microwebsys.com.                              1263
4   ns2.holy-grail-body-transformation-program.com.   1
5   ns2.chavano.com.                                  1
6   ns1.x10host.ml.                                   17
7   ns1.amwebaz.info.                                 48
8   ns2.guacirachocolates.com.br.                     1
9   ns1.clicktodollars.com.                           2

Now I would like to see how many NSs have the same count by plotting it. My own guess is that I can use histogram to see that but I am not sure how. Can anyone help?


问:
Cannot fetch JSON data using GET method: resJSON is not defined error
I'm trying to get data from backend server usin this fetch function:

```<code> let users = []
  const fetchUsers = () => {
    fetch(baseUrl + "/users/", {
      method: "GET",
    })
      .then((res) => res.json())
      .then((data) => (resJSON = data))
      .then((resJSON) => {
          users = resJSON;
      })
      .catch((err) => {
        console.log("error in json", err);
        users = [];

      });
  };
</code>```

But I get

```<code>error in json ReferenceError: resJSON is not defined
</code>```

error happens in this line: .then((data) => (resJSON = data))

The wierd thing is that I see in the backend that the json is created. Also I'm using very similar fetch request for POST data on another endpoint without any issues. So I'm wondering what could be wrong here?

答:
You are having an assignment in your return statement. Additionally, this assignment is scoped to the current callback, so in the next .then block resJSON is not available. It is also not required to try to do an extra assignment.

let users = []
fetch(/* ... */)
   .then((res) => {
        // res is the raw response.
        // res.json returns a new promise
        // that when sucefully fulfilled,
        // will return the decoded body
        return res.json()
    })
   .then((data) => {
     // data refers to the json decoded
     // bytes of the response body
     // assign it directly to user
     users = data
   })
   .catch(console.warn)
```
<p>This may be still problematic, as you never know when the users are assigned or not. Depending on your code, you should shift additional work to the callback itself.</p>
<pre class="lang-js prettyprint-override"><code>const useUserdata = (users) =>
    console.log("do something with the user", users)

fetch(/* ... */)
   .then(raw => raw.json())
   .then(useUserdata)
   .catch(console.warn)
</code>```

Body:
I'm trying to get data from backend server usin this fetch function:

 let users = []
  const fetchUsers = () => {
    fetch(baseUrl + "/users/", {
      method: "GET",
    })
      .then((res) => res.json())
      .then((data) => (resJSON = data))
      .then((resJSON) => {
          users = resJSON;
      })
      .catch((err) => {
        console.log("error in json", err);
        users = [];

      });
  };

But I get

error in json ReferenceError: resJSON is not defined

error happens in this line: .then((data) => (resJSON = data))

The wierd thing is that I see in the backend that the json is created. Also I'm using very similar fetch request for POST data on another endpoint without any issues. So I'm wondering what could be wrong here?

Body:
You are having an assignment in your return statement. Additionally, this assignment is scoped to the current callback, so in the next .then block resJSON is not available. It is also not required to try to do an extra assignment.

let users = []
fetch(/* ... */)
   .then((res) => {
        // res is the raw response.
        // res.json returns a new promise
        // that when sucefully fulfilled,
        // will return the decoded body
        return res.json()
    })
   .then((data) => {
     // data refers to the json decoded
     // bytes of the response body
     // assign it directly to user
     users = data
   })
   .catch(console.warn)

This may be still problematic, as you never know when the users are assigned or not. Depending on your code, you should shift additional work to the callback itself.

const useUserdata = (users) =>
    console.log("do something with the user", users)

fetch(/* ... */)
   .then(raw => raw.json())
   .then(useUserdata)
   .catch(console.warn)


问:
Flutter screen not refreshing after updating sqflite
I am new to flutter and I am  trying sqflite. When updating database the screen not refreshing. I tried setState but not working. After hot reloading in vs code, values are changing, but when  updating automatically not refreshing. Please help with best solution.</p>
```<code>class _UpdateStudentsState extends State<UpdateStudents> {
  DateTime? dateTime;
 @override
  Widget build(BuildContext context) {
    final _nameUpdateController = TextEditingController(text: widget.name);
    final _addressUpdateController =
        TextEditingController(text: widget.address);
    final _mobileUpdateController = TextEditingController(text: widget.phone);
    final _emailUpdateController = TextEditingController(text: widget.email);
    return Scaffold(
      appBar: AppBar(
        title:Text('Update Student'),
      ),
      body: Padding(
        padding:EdgeInsets.all(10.0),
        child: SingleChildScrollView(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextFormField(
                    controller: _nameUpdateController,
                  ),DateOfBirth(
                    onSelectedDate: (date) {
                      dateTime = date;
                    },
                  ),
                  TextFormField(
                controller: _addressUpdateController,
                  ),TextFormField(
                  controller: _mobileUpdateController,
                    ),
                  ),TextFormField(
                   controller: _emailUpdateController,
                  ),SizedBox(
                    child: ElevatedButton(
                      child:Text('Update'),
                      onPressed: () { setState(
                          () {
                            DataBaseHelper.instance.updateStudent(
                              StudentDetails(
                                name: _nameUpdateController.text,
                                dob:
                                    '${dateTime!.day}/${dateTime!.month}/${dateTime!.year}',
                                address: _addressUpdateController.text,
                                phone: _mobileUpdateController.text,
                                email: _emailUpdateController.text,
                                id: widget.id,
                              ),
                            );
                            Navigator.of(context).pop();
                          },
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
    );
  }
}
</code>```

答:
did you put your screen/widget inside a FutureBuilder?

Accessing database is an asynchronous action, you need future builder to handle the data from the database

The video below may help you a bit about the FutureBuilder

https://www.youtube.com/watch?v=OTS-ap9_aXc&list=PLjxrf2q8roU2HdJQDjJzOeO6J3FoFLWr2&index=15

Body:
I am new to flutter and I am  trying sqflite. When updating database the screen not refreshing. I tried setState but not working. After hot reloading in vs code, values are changing, but when  updating automatically not refreshing. Please help with best solution.

class _UpdateStudentsState extends State<UpdateStudents> {
  DateTime? dateTime;
 @override
  Widget build(BuildContext context) {
    final _nameUpdateController = TextEditingController(text: widget.name);
    final _addressUpdateController =
        TextEditingController(text: widget.address);
    final _mobileUpdateController = TextEditingController(text: widget.phone);
    final _emailUpdateController = TextEditingController(text: widget.email);
    return Scaffold(
      appBar: AppBar(
        title:Text('Update Student'),
      ),
      body: Padding(
        padding:EdgeInsets.all(10.0),
        child: SingleChildScrollView(
            child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextFormField(
                    controller: _nameUpdateController,
                  ),DateOfBirth(
                    onSelectedDate: (date) {
                      dateTime = date;
                    },
                  ),
                  TextFormField(
                controller: _addressUpdateController,
                  ),TextFormField(
                  controller: _mobileUpdateController,
                    ),
                  ),TextFormField(
                   controller: _emailUpdateController,
                  ),SizedBox(
                    child: ElevatedButton(
                      child:Text('Update'),
                      onPressed: () { setState(
                          () {
                            DataBaseHelper.instance.updateStudent(
                              StudentDetails(
                                name: _nameUpdateController.text,
                                dob:
                                    '${dateTime!.day}/${dateTime!.month}/${dateTime!.year}',
                                address: _addressUpdateController.text,
                                phone: _mobileUpdateController.text,
                                email: _emailUpdateController.text,
                                id: widget.id,
                              ),
                            );
                            Navigator.of(context).pop();
                          },
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          ),
    );
  }
}


答:
The problem is that resJSON = data is assigning to an identifier that isn't declared anywhere. Apparently your code is running in strict mode (good!), so assigning to an undeclared identifier is an error.

But there's no need for resJSON, it doesn't do anything useful in that code. You could combine the two then handlers and do users = data. But, that's generally poor practice, because you're setting yourself up for this problem where you try to use users before it's filled in. (Your code is also falling prey to the fetch API footgun I describe in this post on my anemic old blog: You need to check ok before you call json().)

But fundamentally, having fetchUsers directly assign to a users variable declared outside of it is asking for trouble. Instead, have fetchUsers return a promise of the users array. Here in 2022 you can do that with an async function:

```<code>const fetchUsers = async () => {
    const response = await fetch(baseUrl + "/users/", {
        method: "GET",
    });
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    return await response.json();
};
</code>```

(If you want to hide errors from the calling code (which is poor practice), wrap it in a try/catch and return an empty array from the catch.)

Then have the code that needs to fill in users do let users = await fetchUser(); (note that that code will also need to be in a async function, or at the top level of a module).

If for some reason you can't use an async function, you can do it the old way:

```<code>const fetchUsers = () => {
    return fetch(baseUrl + "/users/", {
        method: "GET",
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error ${response.status}`);
        }
        return response.json();
    });
};
</code>```

Title: Cannot fetch JSON data using GET method: resJSON is not defined error

Body:
The problem is that resJSON = data is assigning to an identifier that isn't declared anywhere. Apparently your code is running in strict mode (good!), so assigning to an undeclared identifier is an error.

But there's no need for resJSON, it doesn't do anything useful in that code. You could combine the two then handlers and do users = data. But, that's generally poor practice, because you're setting yourself up for this problem where you try to use users before it's filled in. (Your code is also falling prey to the fetch API footgun I describe in this post on my anemic old blog: You need to check ok before you call json().)

But fundamentally, having fetchUsers directly assign to a users variable declared outside of it is asking for trouble. Instead, have fetchUsers return a promise of the users array. Here in 2022 you can do that with an async function:

const fetchUsers = async () => {
    const response = await fetch(baseUrl + "/users/", {
        method: "GET",
    });
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    return await response.json();
};

(If you want to hide errors from the calling code (which is poor practice), wrap it in a try/catch and return an empty array from the catch.)

Then have the code that needs to fill in users do let users = await fetchUser(); (note that that code will also need to be in a async function, or at the top level of a module).

If for some reason you can't use an async function, you can do it the old way:

const fetchUsers = () => {
    return fetch(baseUrl + "/users/", {
        method: "GET",
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error ${response.status}`);
        }
        return response.json();
    });
};


问:
R: I try to build my own pipeline. How can I paste steps as function?
so I try to build my own pipeline in R that will flow like this

```<code>steps <- c("encode_label()",
       "standard_scale()")
steps <- noquote(steps)
head(trainSet %>% steps[1])
</code>```

but the output is,

```<code>> head(trainSet %>% steps[1])
[1] NA NA
</code>```

where,

```<code>> steps[1]
[1] encode_label()
</code>```

it is different with,

```<code>> head(trainSet %>% encode_label(), 2)
X mpg cylinders displacement horsepower weight acceleration model.year origin car_name
2 4  16         8          304        150   3433         12.0         70      1       11
3 5  17         8          302        140   3449         10.5         70      1      128
</code>```

答:
You could define the steps by starting a magrittr pipe sequence with a .:

library(magrittr)

steps <- . %>%
  mean() %>%
  format(nsmall = 3)

steps
#> Functional sequence with the following components:
#>
#>  1. mean(.)
#>  2. format(., nsmall = 3)
#>
#> Use 'functions' to extract the individual functions.
```
<p>And then the application:</p>
<pre class="lang-r prettyprint-override"><code># All at once
1:5 %>% steps()
#> [1] "3.000"

# One-by-one
1:5 %>% steps[[1]]() %>% steps[[2]]()
#> [1] "3.000"
</code>```

If you want to keep the interface of specifying the steps as a character
vector, I think you’d need to delve into some more advanced metaprogramming
to make that work.

Body:
so I try to build my own pipeline in R that will flow like this

steps <- c("encode_label()",
       "standard_scale()")
steps <- noquote(steps)
head(trainSet %>% steps[1])

but the output is,

> head(trainSet %>% steps[1])
[1] NA NA

where,

> steps[1]
[1] encode_label()

it is different with,

> head(trainSet %>% encode_label(), 2)
X mpg cylinders displacement horsepower weight acceleration model.year origin car_name
2 4  16         8          304        150   3433         12.0         70      1       11
3 5  17         8          302        140   3449         10.5         70      1      128

Body:
You could define the steps by starting a magrittr pipe sequence with a .:

library(magrittr)

steps <- . %>%
  mean() %>%
  format(nsmall = 3)

steps
#> Functional sequence with the following components:
#>
#>  1. mean(.)
#>  2. format(., nsmall = 3)
#>
#> Use 'functions' to extract the individual functions.

And then the application:

# All at once
1:5 %>% steps()
#> [1] "3.000"

# One-by-one
1:5 %>% steps[[1]]() %>% steps[[2]]()
#> [1] "3.000"

If you want to keep the interface of specifying the steps as a character
vector, I think you’d need to delve into some more advanced metaprogramming
to make that work.


问:
Error: Trying to access array offset on value of type null in my PHP code
I have limited knowledge of PHP. I am getting this error on this code in the forloop part.

Trying to access array offset on value of type null on line ...

I am seeing this in a local environment as well as online when I enabled debugging in a Wordpress project. I think is related to the nested forloop but I am not sure what the exact problem is.

The error is thrown on the line starting with the if condition after the try block. I have removed some of the code inside the if condition and replace them with ... What am I missing in the forloop or variable declaration code?

```<code>public function render_element_css( $code, $id ){

        global $kc;

        $css_code = '';
        $css_any_code = '';
        $css_desktop_code = '';
        $pro_maps = array(
            'margin' => array('margin-top','margin-right','margin-bottom','margin-left'),
            'padding' => array('padding-top','padding-right','padding-bottom','padding-left'),
            'border-radius' => array('border-top-left-radius','border-top-right-radius','border-bottom-right-radius','border-bottom-left-radius')
        );

        try{
            $screens = json_decode( str_replace( '`', '"', $code ), true );
            if (is_array( $screens['kc-css']))
            {
                kc_screen_sort ($screens['kc-css']);

                foreach ($screens['kc-css'] as $screen => $groups)
                {
                ...

                }

            }

        }catch( Exception $e ){
             echo "\n\n/*Caught exception: ",  $e->getMessage(), "*/\n\n";
        };

        return kc_images_filter($css_any_code.$css_code);

    }
</code>```

答:
Problem

This line:

```<code>$screens = json_decode( str_replace( '`', '"', $code ), true );
</code>```

will make the json invalid before you're trying to decode it.

Imagine you have a string like this:

```<code>$json = '{"foo": "lorem `bar` ipsum"}';
</code>```

If you run your current str_replace() on it before trying to decode the string, it will become:

```<code>$json = '{"foo": "lorem "bar" ipsum"}';
</code>```

See the issues with the quotes? If you try to decode that using json_decode(), it will fail and return null, which means that $screens['kc-css'] will throw the error message you're getting.

Solution

You need to escape the double quote with a backslash: \" if you want to use a literal double quote inside a double quoted string.

Change it to:

```<code>$screens = json_decode( str_replace( '`', '\"', $code ), true );
</code>```

and it should work.

Here's a demo

Body:
I have limited knowledge of PHP. I am getting this error on this code in the forloop part.

Trying to access array offset on value of type null on line ...

I am seeing this in a local environment as well as online when I enabled debugging in a Wordpress project. I think is related to the nested forloop but I am not sure what the exact problem is.

The error is thrown on the line starting with the if condition after the try block. I have removed some of the code inside the if condition and replace them with ... What am I missing in the forloop or variable declaration code?

public function render_element_css( $code, $id ){

        global $kc;

        $css_code = '';
        $css_any_code = '';
        $css_desktop_code = '';
        $pro_maps = array(
            'margin' => array('margin-top','margin-right','margin-bottom','margin-left'),
            'padding' => array('padding-top','padding-right','padding-bottom','padding-left'),
            'border-radius' => array('border-top-left-radius','border-top-right-radius','border-bottom-right-radius','border-bottom-left-radius')
        );

        try{
            $screens = json_decode( str_replace( '`', '"', $code ), true );
            if (is_array( $screens['kc-css']))
            {
                kc_screen_sort ($screens['kc-css']);

                foreach ($screens['kc-css'] as $screen => $groups)
                {
                ...

                }

            }

        }catch( Exception $e ){
             echo "\n\n/*Caught exception: ",  $e->getMessage(), "*/\n\n";
        };

        return kc_images_filter($css_any_code.$css_code);

    }

Body:
Problem

This line:

$screens = json_decode( str_replace( '`', '"', $code ), true );

will make the json invalid before you're trying to decode it.

Imagine you have a string like this:

$json = '{"foo": "lorem `bar` ipsum"}';

If you run your current str_replace() on it before trying to decode the string, it will become:

$json = '{"foo": "lorem "bar" ipsum"}';

See the issues with the quotes? If you try to decode that using json_decode(), it will fail and return null, which means that $screens['kc-css'] will throw the error message you're getting.

Solution

You need to escape the double quote with a backslash: \" if you want to use a literal double quote inside a double quoted string.

Change it to:

$screens = json_decode( str_replace( '`', '\"', $code ), true );

and it should work.

Here's a demo


问:
Which one is more efficient on saving rendering? (React)
I am wondering two cases, which is better for writing?

case 1

```<code>import * as React from 'react';

const TestComponent:React.FC = () => {
    const [count, setCount] = React.useState<number>(0)

    const increment = () => {
        setCount(count + 1)
    }

    console.log("rendering...")

    return <div>
        <div><span>{count}</span></div>
        <button onClick={increment}>click</button>
        </div>
}

export default TestComponent
</code>```

case 2

```<code>import * as React from 'react';

const TestComponent:React.FC = () => {
    const [count, setCount] = React.useState<number>(0)

    const increment = () => {
        setCount(count + 1)
    }

    console.log("rendering...")

    return <div>
        <div><span>{count}</span></div>
        <button onClick={_ => increment()}>click</button>
        </div>
}

export default TestComponent
</code>```

For case 2, I am the following double.
Is the arrow function recreated on each render phase?

```<code> onClick={_ => increment()}
</code>```

答:
Yes, your onClick is recreated on every render.

However the same applies to the increment function:

```<code>const increment = () => {
  setCount(count + 1)
}
</code>```

since the whole body of your component runs every time. You can see this by watching "rendering..." logged in each counter change.

So in the 1st example you have one function reacreating in every render while in the 2nd you recreate 2 functions in each render.

That said you should go with the 1st one.
If you want to avoid recreation you should use useCallback to memoize it.
For example if you pass that onClick callback as a prop to an 'expensive' component, you need to pass the same reference each time to avoid expensive updates.

Body:
I am wondering two cases, which is better for writing?

case 1

import * as React from 'react';

const TestComponent:React.FC = () => {
    const [count, setCount] = React.useState<number>(0)

    const increment = () => {
        setCount(count + 1)
    }

    console.log("rendering...")

    return

{count}

        <button onClick={increment}>click</button>

}

export default TestComponent

case 2

import * as React from 'react';

const TestComponent:React.FC = () => {
    const [count, setCount] = React.useState<number>(0)

    const increment = () => {
        setCount(count + 1)
    }

    console.log("rendering...")

    return

{count}

        <button onClick={_ => increment()}>click</button>

}

export default TestComponent

For case 2, I am the following double.
Is the arrow function recreated on each render phase?

 onClick={_ => increment()}

Body:
Yes, your onClick is recreated on every render.

However the same applies to the increment function:

const increment = () => {
  setCount(count + 1)
}

since the whole body of your component runs every time. You can see this by watching "rendering..." logged in each counter change.

So in the 1st example you have one function reacreating in every render while in the 2nd you recreate 2 functions in each render.

That said you should go with the 1st one.
If you want to avoid recreation you should use useCallback to memoize it.
For example if you pass that onClick callback as a prop to an 'expensive' component, you need to pass the same reference each time to avoid expensive updates.


问:
questions re: current state of GUI programming with Python
I recently did some work modifying a Python gui app that was using wxPython widgets.  I've experimented with Python in fits and starts over last six or seven years, but this was the first time I did any work with a gui.  I was pretty disappointed at what seems to be the current state of gui programming with Python.  I like the Python language itself a lot, it's a fun change from the Delphi/ObjectPascal programming I'm used to, definitely a big productivity increase for general purpose programming tasks.   I'd like to move to Python for everything.

But wxPython is a huge step backwards from something like Delphi's VCL or .NET's WinForms.  While Python itself offers nice productivity gains from generally programming a higher level of abstraction, wxPython is used at a way lower level of abstraction than the VCL.  For example, I wasted a lot fo time trying to get a wxPython list object to behave the way I wanted it to.  Just to add sortable columns involved several code-intensive steps, one to create and maintain a shadow-data-structure that provided the actual sort order, another to make it possible to show graphic-sort-direction-triangles in the column header, and there were a couple more I don't remember.  All of these error prone steps could be accomplished simply by setting a property value using my Delphi grid component.

My conclusion: while Python provides big productivity gains by raising level of abstraction for a lot of general purpose coding, wxPython is several levels of abstraction lower than the gui tools available for Delphi.   Net result:  gui programming with Delphi is way faster than gui programming with Python, and the resulting ui with Delphi is still more polished and full-featured.  It doesn't seem to me like it's exaggerating to say that Delphi gui programming was more advanced back in 1995 than python gui programming with wxPython is in 2009.

I did some investigating of other python gui frameworks and it didn't look like any were substantially better than wxPython.  I also did some minimal investigation of gui formbuilders for wxPython, which would have made things a little bit better.  But by most reports those solutions are buggy and even a great formbuilder wouldn't address my main complaints about wxPython, which are simply that it has fewer features and generally requires you to do gui programming at a much lower level of abstraction than I'm used to with Delphi's VCL.  Some quick investigating into suggested python gui-dev solutions ( http://wiki.python.org/moin/GuiProgramming ) is honestly somewhat depressing for someone used to Delphi or .NET.

Finally, I've got a couple of questions.

First, am I missing something?  Is there some gui-development solution for Python that can compare with VCL or WinForms programming?   I don't necessarily care if it doesn't quite measure up to Delphi's VCL.  I'm just looking for something that's in the same league.

Second, could IronPython be the direction to go?  I've mostly tried to avoid drinking the .NET koolaid, but maybe IronPython gives me a reason to finally give in.  Even then, does IronPython fully integrate with WinForms, or would I need to have the forms themselves be backed by c# or vb.net?  It looks to me like that definitely is the case with SharpDevelop and MonoDevelop (i.e, IronPython can't be used to do design-time gui building).  Does VS.NET fully integrate IronPython with gui-building?

It really seems to me like Python could "take over the world" in a way similar to the way that Visual Basic did back in the early 1990's, if some wonderful new gui-building solution came out for Python.    Only this time with Python we'd have a whole new paradigm of fast, cross platform, and  open source gui programming.  Wouldn't corporations eat that up?  Yeah, I know, web apps are the main focus of things these days, so a great Python-gui solution wouldn't create same revolution that VB once did.  But I don't see gui programming disappearing and I'd like a nice modern, open source, high level solution.

答: There is Wax, whose purpose was to create a more pythonic interface to wxWidgets, but it seems its development has stalled.</p>

OwnerDisplayName: Herbert Sitz

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: bedwyr

OwnerDisplayName: ΤΖΩΤΖΙΟΥ


问:
Bootstrap 4.0.0 pen multi item carousel slider not working with bootstrap 4.5.3
I finally found a multi item carousel for bootstrap 4 that fits my requierements:

Is responsive (it shows only 1 item in small screens)

It has animations

```<code><div class="container-fluid">
  <div id="carouselExample" class="carousel slide" data-ride="carousel" data-interval="9000">
    <div class="carousel-inner row w-100 mx-auto" role="listbox">
      <div class="carousel-item col-md-4 active">
        <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400/000/fff?text=1" alt="slide 1">
      </div>
      <div class="carousel-item col-md-4">
        <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=2" alt="slide 2">
      </div>
      <div class="carousel-item col-md-4">
        <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=3" alt="slide 3">
      </div>
      <div class="carousel-item col-md-4">
        <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=4" alt="slide 4">
      </div>
      <div class="carousel-item col-md-4">
        <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=5" alt="slide 5">
      </div>
      <div class="carousel-item col-md-4">
        <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=6" alt="slide 6">
      </div>
      <div class="carousel-item col-md-4">
        <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=7" alt="slide 7">
      </div>
      <div class="carousel-item col-md-4">
        <img class="img-fluid mx-auto d-block" src="//placehold.it/600x400?text=8" alt="slide 7">
      </div>
    </div>
    <a class="carousel-control-prev" href="#carouselExample" role="button" data-slide="prev">
      <i class="fa fa-chevron-left fa-lg text-muted"></i>
      <span class="sr-only">Previous</span>
    </a>
    <a class="carousel-control-next text-faded" href="#carouselExample" role="button" data-slide="next">
      <i class="fa fa-chevron-right fa-lg text-muted"></i>
      <span class="sr-only">Next</span>
    </a>
  </div>
</div>
</code>```

See it working here:

https://codepen.io/WebDevWaw/pen/zPvaJy

The problem with that one is that it seems to work with bootstrap 4.0.0-beta but I am using 4.5.3 in my project. When changing the css link from 4.0.0-beta to 4.5.3 then only 1 item is shown as you can see in the following pen:

https://codepen.io/soyxan/pen/ZEaywvw

It should be easy to adapt but I have no clue.

答:
in the link that doesn't work you are using different versions for css file and js file, may  it is the problem

```<code>bootstrap@4.5.3/dist/css/bootstrap.min.css
</code>```

and

```<code>twitter-bootstrap/4.0.0-beta/js/bootstrap.min.js
</code>```

Body:
I finally found a multi item carousel for bootstrap 4 that fits my requierements:

Is responsive (it shows only 1 item in small screens)

It has animations

      Previous

      Next

See it working here:

https://codepen.io/WebDevWaw/pen/zPvaJy

The problem with that one is that it seems to work with bootstrap 4.0.0-beta but I am using 4.5.3 in my project. When changing the css link from 4.0.0-beta to 4.5.3 then only 1 item is shown as you can see in the following pen:

https://codepen.io/soyxan/pen/ZEaywvw

It should be easy to adapt but I have no clue.

Body:
in the link that doesn't work you are using different versions for css file and js file, may  it is the problem

bootstrap@4.5.3/dist/css/bootstrap.min.css

and

twitter-bootstrap/4.0.0-beta/js/bootstrap.min.js


问:
Why is the value of n equal to 5 in the first iteration?
I have a question that why is the value of n being used in the first iteration is 5 and not 6. I checked it on stackeoverflow and there many of them said that in the first iteration the value of n is used and then it is decreased by 1 and used in the next iteration.</p>
```<code>#include <stdio.h>

int main()
{
    int ans = 1, n = 6;

    while (n--)
    {
        printf("n = %d\n", n);

        if (n != 0)
        {
            ans *= n;
        }
    }

    printf("ans = %d", ans);

    return 0;
}

Output:
n = 5
n = 4
n = 3
n = 2
n = 1
n = 0
ans = 120
</code>```

答:
Given

```<code>int n, x;
</code>```

Post-decrement:
Same as:

n = 6;
n = 6;

x = n--;
x = n;

n = n - 1;

Which results in x == 6 and n == 5.

Pre-decrement:
Same as:

n = 6;
n = 6;

x = --n;
n = n - 1;

x = n;

Which results in x == 5, and again, n == 5.

So, what pre- and post-decrement have in common is that the value of n is decreased by one, which is why you do not see 6 inside the loop.

If you want to loop from 6 to 1 (inclusive), it's simpler to use a for-loop:

```<code>for(n = 6; n; --n) {
    printf("n = %d\n", n);
    ans *= n;
}
</code>```

which is similar to

```<code>n = 6;
while(n) {
    printf("n = %d\n", n);
    ans *= n;
    --n;
}
</code>```

Body:
I have a question that why is the value of n being used in the first iteration is 5 and not 6. I checked it on stackeoverflow and there many of them said that in the first iteration the value of n is used and then it is decreased by 1 and used in the next iteration.

#include <stdio.h>

int main()
{
    int ans = 1, n = 6;

    while (n--)
    {
        printf("n = %d\n", n);

        if (n != 0)
        {
            ans *= n;
        }
    }

    printf("ans = %d", ans);

    return 0;
}

Output:
n = 5
n = 4
n = 3
n = 2
n = 1
n = 0
ans = 120

Body:
Given

int n, x;

Post-decrement:
Same as:

n = 6;
n = 6;

x = n--;
x = n;

n = n - 1;

Which results in x == 6 and n == 5.

Pre-decrement:
Same as:

n = 6;
n = 6;

x = --n;
n = n - 1;

x = n;

Which results in x == 5, and again, n == 5.

So, what pre- and post-decrement have in common is that the value of n is decreased by one, which is why you do not see 6 inside the loop.

If you want to loop from 6 to 1 (inclusive), it's simpler to use a for-loop:

for(n = 6; n; --n) {
    printf("n = %d\n", n);
    ans *= n;
}

which is similar to

n = 6;
while(n) {
    printf("n = %d\n", n);
    ans *= n;
    --n;
}


问:
Inserting streaming data into an Amazon Redshift cluster
I am trying to direct insert sparkstream data into an Amazon Redshift cluster but am not able to find right way.

Below is the code that i got but its first inserting into S3 then copying to Redshift:.

```<code>#REDSHIFT_JDBC_URL = "jdbc:redshift://%s:5439/%s" % (REDSHIFT_SERVER, DATABASE)

df.write \
    .format("com.databricks.spark.redshift") \
    .option("url", REDSHIFT_JDBC_URL) \
    .option("dbtable", TABLE_NAME) \
    .option("tempdir", "s3n://%s:%s@%s" % (ACCESS_KEY, SECRET, S3_BUCKET_PATH)) \
    .mode("overwrite") \
    .save()
</code>```

Does it impact streaming or insertion performance?

Or any other way to do it?

答:
AWS Redshift now support streaming insert natively through Kinesis Data Streams. No need of intermediate S3 staging. Feature is now in public preview

https://aws.amazon.com/about-aws/whats-new/2022/02/amazon-redshift-public-preview-streaming-ingestion-kinesis-data-streams/

Body:
I am trying to direct insert sparkstream data into an Amazon Redshift cluster but am not able to find right way.

Below is the code that i got but its first inserting into S3 then copying to Redshift:.

#REDSHIFT_JDBC_URL = "jdbc:redshift://%s:5439/%s" % (REDSHIFT_SERVER, DATABASE)

df.write \
    .format("com.databricks.spark.redshift") \
    .option("url", REDSHIFT_JDBC_URL) \
    .option("dbtable", TABLE_NAME) \
    .option("tempdir", "s3n://%s:%s@%s" % (ACCESS_KEY, SECRET, S3_BUCKET_PATH)) \
    .mode("overwrite") \
    .save()

Does it impact streaming or insertion performance?

Or any other way to do it?


问:
Upgrade from Jetpack Compose 1.0.5 to 1.1.0: Error launching app
I have just upgraded a fully functional Jetpack compose mobile app from Compose 1.0.5 to 1.1.0. It builds with no errors and no warnings. However, it does not launch anymore.

Problems Tab in Android Studio indicates that are 104 problems related with Choreographer.java ~/Android/Sdk/sources/android-31/android/view

build.gradle (:app)

```<code>plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "XXXXXXXXXXXXXXX"
        minSdk 24
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion '1.1.0'
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'
    implementation 'androidx.activity:activity-compose:1.4.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"

    // Room libraries
    implementation "androidx.room:room-runtime:2.4.1"
    kapt "androidx.room:room-compiler:2.4.1"
    implementation "androidx.room:room-ktx:2.4.1"

    // DataStore Preferences
    implementation "androidx.datastore:datastore-preferences:1.0.0"

    // Hilt dependencies
    implementation "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
    kapt 'androidx.hilt:hilt-compiler:1.0.0'

    // Navigation dependency
    // implementation "androidx.navigation:navigation-compose:2.4.0-alpha10"

    // Accompanist Jetpack Navigation Compose Animation
    implementation "com.google.accompanist:accompanist-navigation-animation:0.19.0"

}
</code>```

build.gradle (project):

```<code>buildscript {
    ext {
        // https://developer.android.com/jetpack/androidx/releases/compose-kotlin
        kotlin_version = '1.6.10'
        compose_version = '1.1.0'
        hilt_version = '2.40.5'
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.1.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
    }
}

</code>```

答:
As mentioned by @PhilipDukhov the problem was in the Accompanist version which for Compose 1.1.0 is 0.23.0. In fact, there are multiple versions of Accompanist for the different versions of Compose, you can find it here.

Important to note that Android Studio does not alert us to newer versions of some libraries (namely, Accompanist), so we must be aware of this fact.

Body:
I have just upgraded a fully functional Jetpack compose mobile app from Compose 1.0.5 to 1.1.0. It builds with no errors and no warnings. However, it does not launch anymore.

Problems Tab in Android Studio indicates that are 104 problems related with Choreographer.java ~/Android/Sdk/sources/android-31/android/view

build.gradle (:app)

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'kotlin-kapt'
    id 'dagger.hilt.android.plugin'
}

android {
    compileSdk 31

    defaultConfig {
        applicationId "XXXXXXXXXXXXXXX"
        minSdk 24
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables {
            useSupportLibrary true
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
        useIR = true
    }
    buildFeatures {
        compose true
    }
    composeOptions {
        kotlinCompilerExtensionVersion '1.1.0'
    }
    packagingOptions {
        resources {
            excludes += '/META-INF/{AL2.0,LGPL2.1}'
        }
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.4.1'
    implementation 'com.google.android.material:material:1.5.0'
    implementation "androidx.compose.ui:ui:$compose_version"
    implementation "androidx.compose.material:material:$compose_version"
    implementation "androidx.compose.ui:ui-tooling-preview:$compose_version"
    implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'
    implementation 'androidx.activity:activity-compose:1.4.0'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
    debugImplementation "androidx.compose.ui:ui-tooling:$compose_version"

    // Room libraries
    implementation "androidx.room:room-runtime:2.4.1"
    kapt "androidx.room:room-compiler:2.4.1"
    implementation "androidx.room:room-ktx:2.4.1"

    // DataStore Preferences
    implementation "androidx.datastore:datastore-preferences:1.0.0"

    // Hilt dependencies
    implementation "com.google.dagger:hilt-android:$hilt_version"
    kapt "com.google.dagger:hilt-android-compiler:$hilt_version"
    kapt 'androidx.hilt:hilt-compiler:1.0.0'

    // Navigation dependency
    // implementation "androidx.navigation:navigation-compose:2.4.0-alpha10"

    // Accompanist Jetpack Navigation Compose Animation
    implementation "com.google.accompanist:accompanist-navigation-animation:0.19.0"

}

build.gradle (project):

buildscript {
    ext {
        // https://developer.android.com/jetpack/androidx/releases/compose-kotlin
        kotlin_version = '1.6.10'
        compose_version = '1.1.0'
        hilt_version = '2.40.5'
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:7.1.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
    }
}


问:
PrimeNG calendar won't show popup
I'm trying to open the calendar with PrimeNG label but everytime I click on the label won't open the calendar, here my code:
import {CalendarModule} from 'primeng/calendar';

```<code>@NgModule({
  declarations: [
    AppComponent,
    StoreMenuComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ButtonModule,
    InputTextModule,
    FormsModule,
    InputNumberModule,
    CalendarModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

component.ts

```<code>@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
      myDate1!: Date;
myEvent(evt: any)
{
console.warn(evt)
}
}
</code>```

component.html

```<code> </div>
                    <div class="field col-12 md:col-4">
                        <label for="icon">Icon</label>
                        <p-calendar [(ngModel)]="myDate1" [showIcon]="true" inputId="icon"></p-calendar>
                    </div>
</code>```

every other primeNG component working I have a problem with just this, thanks who gonna answer me

答:
At the ended I resolved by adding:

```<code>import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
</code>```

in the module

Title: PrimeNG calendar won't show popup

Body:
I'm trying to open the calendar with PrimeNG label but everytime I click on the label won't open the calendar, here my code:
import {CalendarModule} from 'primeng/calendar';

@NgModule({
  declarations: [
    AppComponent,
    StoreMenuComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ButtonModule,
    InputTextModule,
    FormsModule,
    InputNumberModule,
    CalendarModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

component.ts

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
      myDate1!: Date;
myEvent(evt: any)
{
console.warn(evt)
}
}

component.html

                        Icon

every other primeNG component working I have a problem with just this, thanks who gonna answer me

Body:
At the ended I resolved by adding:

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

in the module


问:
Rinkeby etherscan verification pending but never happens
I am trying to upload my FundMe.sol contract to Etherscan.io but when I run brownie run scripts/deploy.py --network rinkeby on the terminal it waits for rinkeby etherscan to process and verify the contract.
But the problem is it gets stuck in the verification process
gets stuck here
I kept it running and it has been 4 hours and it's still pending.
any solutions to this would be nice

答: Make sure that in the line of code that says wait() - if you have one, you have 1 in it and not another number. This is because the 1 means it waits for 1 block. If you don't have a wait() line in your code, add your deploy.py script to this post so I (or other people) can get a more detailed look of your issue.</p>


问:
Conditioning VS Code settings property on preferred system color theme
I want to set a property in VS Code settings such that it conditions on the system's preferred color theme.

VS Code allows you to detect color scheme by setting workbench.autoDetectColorScheme to true. Then you can set color themes for the properties - workbench.preferredLightColorTheme and
workbench.preferredDarkColorTheme.

Is there any way to set properties like terminal.background such that they change along with the workbench color theme?

答:
Following @rioV8's suggestion I was able to solve this as follows:

{
  "window.autoDetectColorScheme": true,
  "workbench.preferredLightColorTheme": "Small Aperture",
  "workbench.preferredDarkColorTheme": "Large Aperture",
  "workbench.colorCustomizations": {
    "[Small Aperture]": {
      "terminal.background": "#F2F7F2",
      //...
    },
    "[Large Aperture]": {
      "terminal.background": "#141414",
      //...
    },
  },
}
```

Similar to a CSS media query, you can set different properties for different color themes by using their name inside square brackets.

Unfortunately, you'll have to add sections for all the themes you regularly use.

Body:
Following @rioV8's suggestion I was able to solve this as follows:

{
  "window.autoDetectColorScheme": true,
  "workbench.preferredLightColorTheme": "Small Aperture",
  "workbench.preferredDarkColorTheme": "Large Aperture",
  "workbench.colorCustomizations": {
    "[Small Aperture]": {
      "terminal.background": "#F2F7F2",
      //...
    },
    "[Large Aperture]": {
      "terminal.background": "#141414",
      //...
    },
  },
}

Similar to a CSS media query, you can set different properties for different color themes by using their name inside square brackets.

Unfortunately, you'll have to add sections for all the themes you regularly use.


问:
I am migrating my Gatsby site from v2 to v3 and I have updated my npm packages but I am getting errors
I am migrating from gatsby v2 to v3 so that I can use Gatsby Incremental build in my website without using Gatsby cloud services but on updating gatsby version and updating every outdated npm packages I am getting errors for this Mini Extract css,

I am having webpack version 5 and node version above 12 and after updating every oudated npm I am not able to solve this mini css extract issue

I am getting this error while running locally :

```<code>Module build failed (from
./node_modules/gatsby/node_modules/mini-css-extract-plugin/dist/loader.js):
ValidationError: Invalid options object. Mini CSS Extract Plugin Loader has been initialized using
an options object that does not match the API schema.
 - options has an unknown property 'hmr'. These properties are valid:
   object { publicPath?, emit?, esModule?, layer?, modules? }
    at validate
</code>```

I have setup a webpack.config.js file and here is code of this file can anyone suggest what I am missing that I am getting this hmr error:

```<code>const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css",
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  optimization: {
    minimizer: [
      // For webpack@5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
      // `...`,
      new CssMinimizerPlugin(),
    ],
    minimize: true,
  },
};
</code>```

答:
CSS modules in Gatsby v3 onwards needs to be imported as ES modules, so your:

```<code>import styles from './related-products.modules.css'
</code>```

Should be:

```<code>import * as styles from './related-products.modules.css'
</code>```

Keep in mind that this is not the recommended way of importing CSS modules, since you are not allowing webpack to treeshake your styles. Ideally, you should import the needed named modules like:

```<code>import { style1, style2, style3 } from './related-products.modules.css'
</code>```

Regarding the new issue:

I am getting this error while running locally :      Module build failed (from ./node_modules/gatsby/node_modules/mini-css-extract-plugin/dist/loader.js): ValidationError: Invalid options object. Mini CSS Extract Plugin Loader has been initialized using an options object that does not match the API schema.

Try adding the (dev)dependencies:

```<code>yarn add --dev css-loader@^5.0.0 postcss@^8.1.10 postcss-import@^13.0.0 postcss-loader@^4.1.0 postcss-url@^10.1.1
</code>```

Or the equivalence in npm.

Body:
I am migrating from gatsby v2 to v3 so that I can use Gatsby Incremental build in my website without using Gatsby cloud services but on updating gatsby version and updating every outdated npm packages I am getting errors for this Mini Extract css,

I am having webpack version 5 and node version above 12 and after updating every oudated npm I am not able to solve this mini css extract issue

I am getting this error while running locally :

Module build failed (from
./node_modules/gatsby/node_modules/mini-css-extract-plugin/dist/loader.js):
ValidationError: Invalid options object. Mini CSS Extract Plugin Loader has been initialized using
an options object that does not match the API schema.
 - options has an unknown property 'hmr'. These properties are valid:
   object { publicPath?, emit?, esModule?, layer?, modules? }
    at validate

I have setup a webpack.config.js file and here is code of this file can anyone suggest what I am missing that I am getting this hmr error:

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");

module.exports = {
  plugins: [
    new MiniCssExtractPlugin({
      filename: "[name].css",
      chunkFilename: "[id].css",
    }),
  ],
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [MiniCssExtractPlugin.loader, "css-loader"],
      },
    ],
  },
  optimization: {
    minimizer: [
      // For webpack@5 you can use the `...` syntax to extend existing minimizers (i.e. `terser-webpack-plugin`), uncomment the next line
      // `...`,
      new CssMinimizerPlugin(),
    ],
    minimize: true,
  },
};

Body:
CSS modules in Gatsby v3 onwards needs to be imported as ES modules, so your:

import styles from './related-products.modules.css'

Should be:

import * as styles from './related-products.modules.css'

Keep in mind that this is not the recommended way of importing CSS modules, since you are not allowing webpack to treeshake your styles. Ideally, you should import the needed named modules like:

import { style1, style2, style3 } from './related-products.modules.css'

Regarding the new issue:

I am getting this error while running locally :      Module build failed (from ./node_modules/gatsby/node_modules/mini-css-extract-plugin/dist/loader.js): ValidationError: Invalid options object. Mini CSS Extract Plugin Loader has been initialized using an options object that does not match the API schema.

Try adding the (dev)dependencies:

yarn add --dev css-loader@^5.0.0 postcss@^8.1.10 postcss-import@^13.0.0 postcss-loader@^4.1.0 postcss-url@^10.1.1

Or the equivalence in npm.


问:
Is it possible to change the colour of a single character in Shiny Dashboard title?
Could you please help suggest a way to style (change colour) a specific character in Shiny Dashboard title?-Thanks I would like to highlight letter "R" in the title. E.g. in red/bold font style.</p>

```<code>ui <- dashboardPage(dashboardHeader(title="Process MineR"),
                    dashboardSidebar(tags$head(tags$style("tfoot{display: table-header-group;}")),tags$head(tags$style(HTML(".shiny-notification {
                                         height: 50px;
                                         width: 300px;
                                         position:fixed;
                                         top: 40%;;
                                         left: 40%;;}"))),

     ....
</code>```

答:
I have used the code below in a bs4Dash dashboard. The key is to use htmlOutput instead of textOutput.

```<code>header = dashboardHeader(
        title = dashboardBrand(
          title = htmlOutput('outpt_title'),
          color = "primary",
          href = "https://adminlte.io/themes/v3",
          image = 'inst/app/www/image.png'
        )
)

output$outpt_title <- renderText({

  paste0(
    paste0("<font color=\"#990303\"><b>",'R', "</b></font>")
    , paste0("<font color=\"#9c053c\"><b>",'I', "</b></font>")
    , paste0("<font color=\"#46f0a6\"><b>",'P', "</b></font>")
  )

})
</code>```

Body:
Could you please help suggest a way to style (change colour) a specific character in Shiny Dashboard title?-Thanks I would like to highlight letter "R" in the title. E.g. in red/bold font style.

ui <- dashboardPage(dashboardHeader(title="Process MineR"),
                    dashboardSidebar(tags$head(tags$style("tfoot{display: table-header-group;}")),tags$head(tags$style(HTML(".shiny-notification {
                                         height: 50px;
                                         width: 300px;
                                         position:fixed;
                                         top: 40%;;
                                         left: 40%;;}"))),

     ....

Body:
I have used the code below in a bs4Dash dashboard. The key is to use htmlOutput instead of textOutput.

header = dashboardHeader(
        title = dashboardBrand(
          title = htmlOutput('outpt_title'),
          color = "primary",
          href = "https://adminlte.io/themes/v3",
          image = 'inst/app/www/image.png'
        )
)

output$outpt_title <- renderText({

  paste0(
    paste0("<font color=\"#990303\"><b>",'R', "</b></font>")
    , paste0("<font color=\"#9c053c\"><b>",'I', "</b></font>")
    , paste0("<font color=\"#46f0a6\"><b>",'P', "</b></font>")
  )

})