问:
Fetch data from API, but the list is empty, it used to work 30 mins ago
Fetching from the api should be right, but it's not working since my list of "_movies" is empty. It was good looking application 2 hours ago and i dont know what i changed to do this.
It returns either nothing when itemCount:_movies.length or error "invalid value: valid value range is empty: 0. I'm stuck on this.

```<code>import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:task/models/movies.dart';
import 'package:http/http.dart' as http;

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

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

class _HomePageState extends State<HomePage> {
  List<Movie> _movies = <Movie>[];
  var moviesUrl =
      'https://raw.githubusercontent.com/FEND16/movie-json-data/master/json/movies-coming-soon.json';
  Future<List<Movie>> getMovies() async {
    http.Response res = await http.get(Uri.parse(moviesUrl));
    try {
      if (res.statusCode == 200) {
        List<dynamic> movies = json.decode(res.body);
        return movies.map((e) => Movie.fromJson(e)).toList();
      } else {
        return <Movie>[];
      }
    } catch (e) {
      // print(e);
      return <Movie>[];
    }
  }

  @override
  void initState() {
    getMovies().then((value) {
      setState(() {
        _movies.addAll(value);
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Movies"),
      ),
      body: ListView.builder(
          itemCount: _movies.length,
          itemBuilder: (context, index) {
            return Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      _movies[index].title,
                      style:
                          TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
                    ),
                    Text(
                      _movies[index].genres.toString(),
                      style: TextStyle(
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
              ),
            );
          }),
    );
  }
}
</code>```

seems like _movies.lenght is 0, but somehow it worked right 2 hours ago and i didnt change a thing

```<code>class Movie {
  String id;
  String title;
  String year;
  List genres;
  // List ratings;
  String poster; //image
  // String contentRating;
  String duration;
  // DateTime releaseDate;
  // int averageRating;
  String originalTitle;
  String storyline;
  List actors;
  // String imdbRating;
  String posterurl; //image

  Movie({
    required this.id,
    required this.title,
    required this.year,
    required this.genres,
    // required this.ratings,
    required this.poster,
    // required this.contentRating,
    required this.duration,
    // required this.releaseDate,
    // required this.averageRating,
    required this.originalTitle,
    required this.storyline,
    required this.actors,
    // required this.imdbRating,
    required this.posterurl,
  });

  factory Movie.fromJson(Map<String, dynamic> json) {
    return Movie(
        id: json["id"],
        title: json["title"],
        year: json["year"],
        genres: json["genres"],
        // ratings: json["ratnigs"],
        poster: json["poster"],
        // contentRating: json["contentRating"],
        duration: json["duration"],
        // releaseDate: json["releaseDate"],
        // averageRating: json["averageRating"],
        originalTitle: json["originalTitle"],
        storyline: json["storyline"],
        actors: json["actors"],
        // imdbRating: json["imdbRating"],
        posterurl: json["posterurl"]);
  }
}
</code>```

答:
I believe the error must be on this line:

```<code>getMovies().then((value) {
  setState(() {
    _movies.addAll(value);
  });
});
</code>```

I think dart is confused about rebuilding the _movies variable because you are modifying it instead of reassigning it. If I am right, the solution is as simple as reassigning _movies:

```<code>getMovies().then((value) {
  setState(() {
    _movies = [..._movies, ...value]
  });
});
</code>```

Body:
Fetching from the api should be right, but it's not working since my list of "_movies" is empty. It was good looking application 2 hours ago and i dont know what i changed to do this.
It returns either nothing when itemCount:_movies.length or error "invalid value: valid value range is empty: 0. I'm stuck on this.

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:task/models/movies.dart';
import 'package:http/http.dart' as http;

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

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

class _HomePageState extends State<HomePage> {
  List<Movie> _movies = <Movie>[];
  var moviesUrl =
      'https://raw.githubusercontent.com/FEND16/movie-json-data/master/json/movies-coming-soon.json';
  Future<List<Movie>> getMovies() async {
    http.Response res = await http.get(Uri.parse(moviesUrl));
    try {
      if (res.statusCode == 200) {
        List<dynamic> movies = json.decode(res.body);
        return movies.map((e) => Movie.fromJson(e)).toList();
      } else {
        return <Movie>[];
      }
    } catch (e) {
      // print(e);
      return <Movie>[];
    }
  }

  @override
  void initState() {
    getMovies().then((value) {
      setState(() {
        _movies.addAll(value);
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Movies"),
      ),
      body: ListView.builder(
          itemCount: _movies.length,
          itemBuilder: (context, index) {
            return Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      _movies[index].title,
                      style:
                          TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
                    ),
                    Text(
                      _movies[index].genres.toString(),
                      style: TextStyle(
                        fontSize: 16,
                      ),
                    ),
                  ],
                ),
              ),
            );
          }),
    );
  }
}

seems like _movies.lenght is 0, but somehow it worked right 2 hours ago and i didnt change a thing

class Movie {
  String id;
  String title;
  String year;
  List genres;
  // List ratings;
  String poster; //image
  // String contentRating;
  String duration;
  // DateTime releaseDate;
  // int averageRating;
  String originalTitle;
  String storyline;
  List actors;
  // String imdbRating;
  String posterurl; //image

  Movie({
    required this.id,
    required this.title,
    required this.year,
    required this.genres,
    // required this.ratings,
    required this.poster,
    // required this.contentRating,
    required this.duration,
    // required this.releaseDate,
    // required this.averageRating,
    required this.originalTitle,
    required this.storyline,
    required this.actors,
    // required this.imdbRating,
    required this.posterurl,
  });

  factory Movie.fromJson(Map<String, dynamic> json) {
    return Movie(
        id: json["id"],
        title: json["title"],
        year: json["year"],
        genres: json["genres"],
        // ratings: json["ratnigs"],
        poster: json["poster"],
        // contentRating: json["contentRating"],
        duration: json["duration"],
        // releaseDate: json["releaseDate"],
        // averageRating: json["averageRating"],
        originalTitle: json["originalTitle"],
        storyline: json["storyline"],
        actors: json["actors"],
        // imdbRating: json["imdbRating"],
        posterurl: json["posterurl"]);
  }
}

Body:
I believe the error must be on this line:

getMovies().then((value) {
  setState(() {
    _movies.addAll(value);
  });
});

I think dart is confused about rebuilding the _movies variable because you are modifying it instead of reassigning it. If I am right, the solution is as simple as reassigning _movies:

getMovies().then((value) {
  setState(() {
    _movies = [..._movies, ...value]
  });
});


来源: stackexchange

问:
In PowerShell, how can I get the XML inner child to populate its parents and format it in a table?
So, I have the following XML file example:

    <root>
    <row>
        <row>
            <PName>Charles</PName>
            <Company>Contoso</Company>
            <ORDERDATE>2022-01-25</ORDERDATE>
            <STREET1>FakeStreet 123</STREET1>
            <City>San Francisco</City>
            <row>
                <ORDERID>0010286731129</ORDERID>
                <row>
                    <ProjectName>Sacramento Expansion</ProjectName>
                    <Name>ProductA</Name>
                    <MBShipped>Y</MBShipped>
                    <MBSKU>100364092</MBSKU>
                    <SerialSKU/>
                    <Color>Lemon</Color>
                </row>
            </row>
            <Other>OtherData</Other>
        </row>
        <row>
            <PName>Harvey</PName>
            <Company>Specter</Company>
            <ORDERDATE>2022-01-25</ORDERDATE>
            <STREET1>NotAFake 123</STREET1>
            <City>San Diego</City>
            <row>
                <ORDERID>0010286730526</ORDERID>
                <row>
                    <ProjectName>North Dakota Expansion</ProjectName>
                    <Name>ProductA</Name>
                    <MBShipped>Y</MBShipped>
                    <MBSKU>100364092</MBSKU>
                    <SerialSKU/>
                    <Color>Red</Color>
                </row>
                <row>
                    <ProjectName>North Dakota Expansion</ProjectName>
                    <Name>ProductB</Name>
                    <MBShipped>Y</MBShipped>
                    <MBSKU>100364092</MBSKU>
                    <SerialSKU/>
                    <Color>Blue</Color>
                </row>
            </row>
            <Other>OtherData</Other>
        </row>
    </row>
    </root>
```
<p>And I would like that Powershell outputs this:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>PName</th>
<th>Company</th>
<th>ORDERDATE</th>
<th>STREET1</th>
<th>City</th>
<th>ProjectName</th>
<th>Name</th>
<th>Color</th>
<th>OtherData</th>
</tr>
</thead>
<tbody>
<tr>
<td>Charles</td>
<td>Contoso</td>
<td>2022-01-25</td>
<td>FakeStreet 123</td>
<td>San Francisco</td>
<td>Sacramento Expansion</td>
<td>ProductA</td>
<td>Lemon</td>
<td>OtherData</td>
</tr>
<tr>
<td>Harvey</td>
<td>Specter</td>
<td>2022-01-25</td>
<td>NotAFake 123</td>
<td>San Diego</td>
<td>North Dakota Expansion</td>
<td>ProductA</td>
<td>Red</td>
<td>OtherData</td>
</tr>
<tr>
<td>Harvey</td>
<td>Specter</td>
<td>2022-01-25</td>
<td>NotAFake 123</td>
<td>San Diego</td>
<td>North Dakota Expansion</td>
<td>ProductB</td>
<td>Blue</td>
<td>OtherData</td>
</tr>
</tbody>
</table>
</div>
<p>I've managed to do it with a horrible approach:</p>
```[xml]$data = Get-Content ./path/to/xml.xml
$RowsIwant = $data.root.row.row <#note the pipes for select object.#>
| Select-Object -ExpandProperty row -Property PName,Company,Orderdate,Street1,City,Other
| Select-Object -ExpandProperty row -Property PName,Company,Orderdate,Street1,City,Other
| Select-Object -Property PName,Company,OrderDate,Street1,City,ProjectName,Name,Color,OtherData

$RowsIwant | format-table
```

Is there a way to do this in a more elegant way? I feel like it's being super inefficient.
I tried with a "ForEach-Object" loop but I couldn't get it to access the "innermost" items.

Anyways, I do have a solution but I'd like to improve and get a better understanding on how to deal with the inner items, if you want to throw me a "read about this algorithm!" would be also welcome.

Thanks!

答:
Assuming you have the XML ($xml in my example) already in memory, you could parse it this way, it would require two loops and you could use [pscustomobject] or a calculated property with Select-Object as in my example.

$result = foreach($line in $xml.root.row.row)
{
    foreach($object in $line.row.row)
    {
        $line | Select-Object @(
            'PName', 'Company', 'ORDERDATE', 'STREET1', 'City'
            @{
                Name = 'ProjectName'
                Expression = { $object.ProjectName }
            }
            @{
                Name = 'Name'
                Expression = { $object.Name }
            }
            @{
                Name = 'Color'
                Expression = { $object.Color }
            }
            @{
                Name = 'OtherData'
                Expression = 'Other'
            }
        )
    }
}
```
<p>Now <code>$result | Format-Table</code> looks like what you were looking for:</p>
```PName   Company ORDERDATE  STREET1        City          ProjectName            Name     Color OtherData
-----   ------- ---------  -------        ----          -----------            ----     ----- ---------
Charles Contoso 2022-01-25 FakeStreet 123 San Francisco Sacramento Expansion   ProductA Lemon OtherData
Harvey  Specter 2022-01-25 NotAFake 123   San Diego     North Dakota Expansion ProductA Red   OtherData
Harvey  Specter 2022-01-25 NotAFake 123   San Diego     North Dakota Expansion ProductB Blue  OtherData
```

ContentLicense: CC BY-SA 4.0

Body:
So, I have the following XML file example:

    <root>
    <row>
        <row>
            <PName>Charles</PName>
            <Company>Contoso</Company>
            <ORDERDATE>2022-01-25</ORDERDATE>
            <STREET1>FakeStreet 123</STREET1>
            <City>San Francisco</City>
            <row>
                <ORDERID>0010286731129</ORDERID>
                <row>
                    <ProjectName>Sacramento Expansion</ProjectName>
                    <Name>ProductA</Name>
                    <MBShipped>Y</MBShipped>
                    <MBSKU>100364092</MBSKU>
                    <SerialSKU/>
                    <Color>Lemon</Color>
                </row>
            </row>
            <Other>OtherData</Other>
        </row>
        <row>
            <PName>Harvey</PName>
            <Company>Specter</Company>
            <ORDERDATE>2022-01-25</ORDERDATE>
            <STREET1>NotAFake 123</STREET1>
            <City>San Diego</City>
            <row>
                <ORDERID>0010286730526</ORDERID>
                <row>
                    <ProjectName>North Dakota Expansion</ProjectName>
                    <Name>ProductA</Name>
                    <MBShipped>Y</MBShipped>
                    <MBSKU>100364092</MBSKU>
                    <SerialSKU/>
                    <Color>Red</Color>
                </row>
                <row>
                    <ProjectName>North Dakota Expansion</ProjectName>
                    <Name>ProductB</Name>
                    <MBShipped>Y</MBShipped>
                    <MBSKU>100364092</MBSKU>
                    <SerialSKU/>
                    <Color>Blue</Color>
                </row>
            </row>
            <Other>OtherData</Other>
        </row>
    </row>
    </root>

And I would like that Powershell outputs this:

PName
Company
ORDERDATE
STREET1
City
ProjectName
Name
Color
OtherData

Charles
Contoso
2022-01-25
FakeStreet 123
San Francisco
Sacramento Expansion
ProductA
Lemon
OtherData

Harvey
Specter
2022-01-25
NotAFake 123
San Diego
North Dakota Expansion
ProductA
Red
OtherData

Harvey
Specter
2022-01-25
NotAFake 123
San Diego
North Dakota Expansion
ProductB
Blue
OtherData

I've managed to do it with a horrible approach:

[xml]$data = Get-Content ./path/to/xml.xml
$RowsIwant = $data.root.row.row <#note the pipes for select object.#>
| Select-Object -ExpandProperty row -Property PName,Company,Orderdate,Street1,City,Other
| Select-Object -ExpandProperty row -Property PName,Company,Orderdate,Street1,City,Other
| Select-Object -Property PName,Company,OrderDate,Street1,City,ProjectName,Name,Color,OtherData

$RowsIwant | format-table

Is there a way to do this in a more elegant way? I feel like it's being super inefficient.
I tried with a "ForEach-Object" loop but I couldn't get it to access the "innermost" items.

Anyways, I do have a solution but I'd like to improve and get a better understanding on how to deal with the inner items, if you want to throw me a "read about this algorithm!" would be also welcome.

Thanks!

Body:
Assuming you have the XML ($xml in my example) already in memory, you could parse it this way, it would require two loops and you could use [pscustomobject] or a calculated property with Select-Object as in my example.

$result = foreach($line in $xml.root.row.row)
{
    foreach($object in $line.row.row)
    {
        $line | Select-Object @(
            'PName', 'Company', 'ORDERDATE', 'STREET1', 'City'
            @{
                Name = 'ProjectName'
                Expression = { $object.ProjectName }
            }
            @{
                Name = 'Name'
                Expression = { $object.Name }
            }
            @{
                Name = 'Color'
                Expression = { $object.Color }
            }
            @{
                Name = 'OtherData'
                Expression = 'Other'
            }
        )
    }
}

Now $result | Format-Table looks like what you were looking for:

PName   Company ORDERDATE  STREET1        City          ProjectName            Name     Color OtherData
-----   ------- ---------  -------        ----          -----------            ----     ----- ---------
Charles Contoso 2022-01-25 FakeStreet 123 San Francisco Sacramento Expansion   ProductA Lemon OtherData
Harvey  Specter 2022-01-25 NotAFake 123   San Diego     North Dakota Expansion ProductA Red   OtherData
Harvey  Specter 2022-01-25 NotAFake 123   San Diego     North Dakota Expansion ProductB Blue  OtherData


问:
Code is returning wrong value for factorials
My code for factorials works fine up until n=13 where it then starts giving me the wrong answer. Does anyone know why?</p>
```<code>public class Factorial {
    public static void main(String[] args) {
        System.out.println(factorial(13));
    }

    public static int factorial(int n) {
        for (int i = n - 1; i >= 1; i--) {
            n=n*i;
        }

        return n;
    }
}
</code>```

答:
int is finite

Your problem is the 32bit integer limit.

Java's int datatype represents a signed 32bit integer meaning it can store values from -2^31 to 2^31-1 (2 147 483 647)

13! is 6 227 020 800 which is higher than that so it doesn't fit in an int.

long is bigger than int but still finite

In order to fix this, you can use long which represents a signed 64bit integer:

public static long factorial(long n) {

    for(int i=(int)n-1;i>=1;i--){
        n=n*i;
 }
    return n;
}
```
<p><code>long</code> allows ranges from -2^63 up to 2^63-1 (a number with 18 digits) which allows factorials until <code>20!</code>.</p>
<h2>Get real big with <code>BigInteger</code></h2>
<p>If you want to. go even further, you can use <code>BigInteger</code>:</p>
<pre class="lang-java prettyprint-override"><code>public static BigInteger factorial(long n) {
    BigInteger value=BigInteger.valueOf(n);
    for(int i=n-1;i>=1;i--){
        value=value.multiply(BigInteger.valueOf(i));
    }
    return value;
}
</code>```

While BigInteger also isn't infinite (ranging from -2^(2^32) until to -2^(2^32) at minimum), it should be sufficient for your purpose. This is explained in the Javadoc of BigInteger:

BigInteger must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive)

Body:
My code for factorials works fine up until n=13 where it then starts giving me the wrong answer. Does anyone know why?

public class Factorial {
    public static void main(String[] args) {
        System.out.println(factorial(13));
    }

    public static int factorial(int n) {
        for (int i = n - 1; i >= 1; i--) {
            n=n*i;
        }

        return n;
    }
}

Body:
int is finite

Your problem is the 32bit integer limit.

Java's int datatype represents a signed 32bit integer meaning it can store values from -2^31 to 2^31-1 (2 147 483 647)

13! is 6 227 020 800 which is higher than that so it doesn't fit in an int.

long is bigger than int but still finite

In order to fix this, you can use long which represents a signed 64bit integer:

public static long factorial(long n) {

    for(int i=(int)n-1;i>=1;i--){
        n=n*i;
 }
    return n;
}

long allows ranges from -2^63 up to 2^63-1 (a number with 18 digits) which allows factorials until 20!.

Get real big with BigInteger

If you want to. go even further, you can use BigInteger:

public static BigInteger factorial(long n) {
    BigInteger value=BigInteger.valueOf(n);
    for(int i=n-1;i>=1;i--){
        value=value.multiply(BigInteger.valueOf(i));
    }
    return value;
}

While BigInteger also isn't infinite (ranging from -2^(2^32) until to -2^(2^32) at minimum), it should be sufficient for your purpose. This is explained in the Javadoc of BigInteger:

BigInteger must support values in the range -2Integer.MAX_VALUE (exclusive) to +2Integer.MAX_VALUE (exclusive)


问:
What are the available UITabBarController tab icons?
How can i see all the icons available from the iOS SDK and how can i set them to my UITabBarController tabs ?</p>

答:
There may be more, but you can check out the pulldown in Interface Builder for the Tab Bar Item's "Identifier" (in the Inspector view).

Update: The full list is here:

```<code>typedef enum {
   UITabBarSystemItemMore,
   UITabBarSystemItemFavorites,
   UITabBarSystemItemFeatured,
   UITabBarSystemItemTopRated,
   UITabBarSystemItemRecents,
   UITabBarSystemItemContacts,
   UITabBarSystemItemHistory,
   UITabBarSystemItemBookmarks,
   UITabBarSystemItemSearch,
   UITabBarSystemItemDownloads,
   UITabBarSystemItemMostRecent,
   UITabBarSystemItemMostViewed,
} UITabBarSystemItem;
</code>```

Looks like it is just the ones that Interface Builder shows.

If you are looking for custom icons, take a look at this thread.

ContentLicense: CC BY-SA 3.0

Body:
There may be more, but you can check out the pulldown in Interface Builder for the Tab Bar Item's "Identifier" (in the Inspector view).

Update: The full list is here:

typedef enum {
   UITabBarSystemItemMore,
   UITabBarSystemItemFavorites,
   UITabBarSystemItemFeatured,
   UITabBarSystemItemTopRated,
   UITabBarSystemItemRecents,
   UITabBarSystemItemContacts,
   UITabBarSystemItemHistory,
   UITabBarSystemItemBookmarks,
   UITabBarSystemItemSearch,
   UITabBarSystemItemDownloads,
   UITabBarSystemItemMostRecent,
   UITabBarSystemItemMostViewed,
} UITabBarSystemItem;

Looks like it is just the ones that Interface Builder shows.

If you are looking for custom icons, take a look at this thread.


问:
Apply Same Transformation to Multiple Returned Columns in SQL
I am trying to simplify a query that has much duplication and is doing the same operations to multiple returned values. How can I apply the same d * 10000 operation to e, g, i to simplify this query?

```<code>select a, b, c, a + b + c as d,
(a + b + c) * 10000 * e as f,
(a + b + c) * 10000 * g as h,
(a + b + c) * 10000 * i as j
from mytable
</code>```

答:
You can simplify with a lateral join and values, such as

```<code>select a, b, c, a + b + c as d,
  v * e as f,
  v * g as h,
  v * i as j
from mytable t,
lateral (values((a + b + c) * 10000))x(v);
</code>```

Demo Fiddle

Body:
I am trying to simplify a query that has much duplication and is doing the same operations to multiple returned values. How can I apply the same d * 10000 operation to e, g, i to simplify this query?

select a, b, c, a + b + c as d,
(a + b + c) * 10000 * e as f,
(a + b + c) * 10000 * g as h,
(a + b + c) * 10000 * i as j
from mytable

Body:
You can simplify with a lateral join and values, such as

select a, b, c, a + b + c as d,
  v * e as f,
  v * g as h,
  v * i as j
from mytable t,
lateral (values((a + b + c) * 10000))x(v);

Demo Fiddle


问:
Javascript alert function not displaying message after clicking button
Having an issue where I can't get the alert to display after clicking the button. I've edited the code from what it previously was according to the suggestions made and still not getting the alert to display. Any other thoughts on what the issue could be? I appreciate and thank you all for the help.</p>
```<code>    <!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <link href='https://fonts.googleapis.com/css?family=Open Sans' rel='stylesheet'>
    <meta charset="utf-8">

    <title>Pizzeria</title>

    <style type="text/css">

      body {
        margin: 40px;
        font-family: 'Open Sans';
      }
      #fieldSize, #fieldCrust {
        width: 150px;
        float: left;
        border: none;
      }
       #fieldToppings {
         width: 350px;
         border: none;

       }
       fieldset {
         margin-top: 20px;
       }
      #toppings1 {
        float: left;
      }
      label {
        display: inline-block;
        width: 150px;
        margin: 7px;
        text-align: left;
      }
      input[type="text"] {
        width: 250px;
      }
      div {
        padding: 10px;
      }
      #btnOrder {
        width: auto;
        border-radius: 10px;
      }

    </style>
    <script type="text/javascript">

      function orderSubmit() {
        var name = document.getElementById("txtName").value;
        var phone = document.getElementById("txtPhone").value;
        phone = '(' + phone.substring(0,3) + ')' + phone.substring(3,6) + '-' + phone.substring(6);
        var address = document.getElementById("txtAddress").value;

        var msg = name + ", your order is being prepared. \n";
        msg+= "Your order will be delivered at " + address;
        msg+= "Your contact infromation is: " + phone "\n";
        msg+= "Order details: \n \n";

        for(var i = 0; i < document.frm1.rdoSize.length; i++) {
           if(document.frm1.rdoSize[i].checked) {
             var radioStateSize = document.frm1.rdoSize[i].value;
           }
        }
        for(var j = 0; j < document.frm1.rdoCrust.length; j++) {
           if(document.frm1.rdoCrust[j].checked) {
             var radioStateCrust = document.frm1.rdoCrust[j].value;
           }
        }
        msg+= radioStateSize + ' ' + radioStateCrust + " pizza with the following toppings: \n";

        var chkToppings = document.frm1.chkToppings;

        for(k=0; k < document.frm1.chkToppings; k++) {
           if(document.frm1.chkToppings[k].checked) {
           msg += document.frm1.chkToppings[k].value + ' ';
           }
        }
        alert(msg);
      }

    </script>

  </head>

  <body>
    <fieldset id="main">
      <legend><h2>Pizza Order!</h2></legend>

      <form name="frm1">
        <div>
          <label for="lblName">Name:</label>
          <input type="text" id="txtName">
        </div>

        <div>
          <label for="lblPhone">Phone Number:</label>
          <input type="text" id="txtPhone">
        </div>

        <div>
          <label for="lblAddress">Address:</label>
          <input type="text" id="txtAddress">
        </div>

      <fieldset id="fieldSize">
        <legend><strong>Size</strong></legend>
          <input type="radio" name="rdoSize" value="Small" id="rdoSmall"> Small <br>
          <input type="radio" name="rdoSize" value="Medium" id="rdoMedium"> Medium <br>
          <input type="radio" name="rdoSize" value="Large" id="rdoLarge"> Large <br>
      </fieldset>

      <fieldset id="fieldCrust">
        <legend><strong>Crust</strong></legend>
          <input type="radio" name="rdoCrust" value="Thin" id="rdoThin"> Small <br>
          <input type="radio" name="rdoCrust" value="HandTossed" id="rdoHandTossed"> Hand Tossed <br>
          <input type="radio" name="rdoCrust" value="GF" id="rdoGF"> Gluten Free <br>
      </fieldset>

      <fieldset id="fieldToppings">
        <legend><strong>Toppings</strong></legend>
          <div id="toppings1">
            <input type="checkbox" name="chkToppings" id="chkPepperoni" value="Pepperoni"> Pepperoni <br>
            <input type="checkbox" name="chkToppings" id="chkSausage" value="Sausage"> Sausage <br>
            <input type="checkbox" name="chkToppings" id="chkChourico" value="Chourico"> Pepperoni <br>
            <input type="checkbox" name="chkToppings" id="chkChicken" value="Chicken"> Chicken <br>
            <input type="checkbox" name="chkToppings" id="chkAnchovies" value="Anchovies"> Anchovies <br>
          </div>
          <div id="toppings2">
            <input type="checkbox" name="chkToppings" id="chkMushrooms" value="Mushrooms"> Mushrooms <br>
            <input type="checkbox" name="chkToppings" id="chkPeppers" value="Peppers"> Peppers <br>
            <input type="checkbox" name="chkToppings" id="chkFeta" value="Feta"> Feta <br>
            <input type="checkbox" name="chkToppings" id="chkOlives" value="Olives"> Olives <br>
            <input type="checkbox" name="chkToppings" id="chkOnions" value="Onions"> Onions <br>
          </div>
      </fieldset>

      <input type="button" id="btnOrder" value="Order" onclick="orderSubmit()">

      </form>
    </fieldset>
  </body>
</html>
</code>```

答:
```<code><script type="text/javascript">

  function orderSubmit(){
    var name = document.getElementById("txtName").value;
    var phone = document.getElementById("txtPhone").value;
    phone = '(' + phone.substring(0,3) + ')' + phone.substring(3,6) + '-' + phone.substring(6);
    var address = document.getElementById("txtAddress").value;

    var msg = name + ", your order is being prepared. \n";
    msg+= "Your order will be delivered at " + address;
    msg+= "Order details: \n \n";

    var radioStateSize = document.getElementsByName('rdoSize')
    radioStateSize.forEach((r)=>{
      if(r.checked){msg += r.value}
    })

    var radioStateCrust = document.getElementsByName('rdoCrust')
    radioStateCrust.forEach((r)=>{
      if(r.checked){msg += ' '+r.value+" pizza with the following toppings: \n"}
    })

    var chkToppings = document.getElementsByName('chkToppings')
    chkToppings.forEach((r)=>{
      if(r.checked){msg += ' '+r.value}
    })

    alert(msg);
  }

</script>
</code>```

Body:
Having an issue where I can't get the alert to display after clicking the button. I've edited the code from what it previously was according to the suggestions made and still not getting the alert to display. Any other thoughts on what the issue could be? I appreciate and thank you all for the help.

    <!DOCTYPE html>

    <link href='https://fonts.googleapis.com/css?family=Open Sans' rel='stylesheet'>
    <meta charset="utf-8">

    <title>Pizzeria</title>

    <fieldset id="main">
      <legend>
Pizza Order!
</legend>

      <form name="frm1">

          Name:
          <input type="text" id="txtName">

          Phone Number:
          <input type="text" id="txtPhone">

          Address:
          <input type="text" id="txtAddress">

      <fieldset id="fieldSize">
        <legend>Size</legend>
          <input type="radio" name="rdoSize" value="Small" id="rdoSmall"> Small

          <input type="radio" name="rdoSize" value="Medium" id="rdoMedium"> Medium

          <input type="radio" name="rdoSize" value="Large" id="rdoLarge"> Large

      </fieldset>

      <fieldset id="fieldCrust">
        <legend>Crust</legend>
          <input type="radio" name="rdoCrust" value="Thin" id="rdoThin"> Small

          <input type="radio" name="rdoCrust" value="HandTossed" id="rdoHandTossed"> Hand Tossed

          <input type="radio" name="rdoCrust" value="GF" id="rdoGF"> Gluten Free

      </fieldset>

      <fieldset id="fieldToppings">
        <legend>Toppings</legend>

            <input type="checkbox" name="chkToppings" id="chkPepperoni" value="Pepperoni"> Pepperoni

            <input type="checkbox" name="chkToppings" id="chkSausage" value="Sausage"> Sausage

            <input type="checkbox" name="chkToppings" id="chkChourico" value="Chourico"> Pepperoni

            <input type="checkbox" name="chkToppings" id="chkChicken" value="Chicken"> Chicken

            <input type="checkbox" name="chkToppings" id="chkAnchovies" value="Anchovies"> Anchovies

            <input type="checkbox" name="chkToppings" id="chkMushrooms" value="Mushrooms"> Mushrooms

            <input type="checkbox" name="chkToppings" id="chkPeppers" value="Peppers"> Peppers

            <input type="checkbox" name="chkToppings" id="chkFeta" value="Feta"> Feta

            <input type="checkbox" name="chkToppings" id="chkOlives" value="Olives"> Olives

            <input type="checkbox" name="chkToppings" id="chkOnions" value="Onions"> Onions

      </fieldset>

      <input type="button" id="btnOrder" value="Order" onclick="orderSubmit()">

      </form>
    </fieldset>


问:
Could not install package '--'. You are trying to install this package into a project that targets '.NETFramework,Version=v4.5'
I created this package, I need it in a project but couldn't install it, this error appears:

Could not install package 'Mshwf.NiceLinq 1.0.9'. You are trying to
  install this package into a project that targets
  '.NETFramework,Version=v4.5', but the package  does not contain any
  assembly references or content files that are compatible with that
  framework. For more information, contact the package author

I don't  know why this happen, in another project (Console) I changed the framework to 4.6 and other versions and it wasn't a problem, but this only happen in this project (MVC and Web API):

this is the nuspec file:

```<code><?xml version="1.0"?>
<package >
  <metadata>
    <id>Mshwf.NiceLinq</id>
    <version>1.0.9</version>
    <title>Nice LINQ</title>
    <authors>MShawaf</authors>
    <owners>Mshawaf</owners>
    <projectUrl>https://github.com/mshwf/NiceLinq</projectUrl>
    <iconUrl>https://raw.githubusercontent.com/mshwf/NiceLinq/master/logo.png</iconUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>See it as: WHERE ID IN (1, 2, 3, 7, 9, 22, 30, 101)</description>
    <releaseNotes>Minor changes.</releaseNotes>
    <copyright>Copyright 2016</copyright>
    <tags>LINQ IEnumerable Where Contains Search Filter</tags>
  </metadata>
</package>
</code>```

答:
In my case I tried to install Itext7 package my project .NET framework was 4.5
I changed my project .NET framework to .NET 4.6.1 by using the following  steps then I installed the package successfully :

1- right click the project and click properties

2- Under application tab change the Target framework to the required framework for your package

Body:
I created this package, I need it in a project but couldn't install it, this error appears:

Could not install package 'Mshwf.NiceLinq 1.0.9'. You are trying to
  install this package into a project that targets
  '.NETFramework,Version=v4.5', but the package  does not contain any
  assembly references or content files that are compatible with that
  framework. For more information, contact the package author

I don't  know why this happen, in another project (Console) I changed the framework to 4.6 and other versions and it wasn't a problem, but this only happen in this project (MVC and Web API):

this is the nuspec file:

<?xml version="1.0"?>
<package >
  <metadata>
    <id>Mshwf.NiceLinq</id>
    <version>1.0.9</version>
    <title>Nice LINQ</title>
    <authors>MShawaf</authors>
    <owners>Mshawaf</owners>
    <projectUrl>https://github.com/mshwf/NiceLinq</projectUrl>
    <iconUrl>https://raw.githubusercontent.com/mshwf/NiceLinq/master/logo.png</iconUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>See it as: WHERE ID IN (1, 2, 3, 7, 9, 22, 30, 101)</description>
    <releaseNotes>Minor changes.</releaseNotes>
    <copyright>Copyright 2016</copyright>
    <tags>LINQ IEnumerable Where Contains Search Filter</tags>
  </metadata>
</package>


问:
How to speed up SELECT .. LIKE queries in MySQL on multiple columns?
I have a MySQL table for which I do very frequent SELECT x, y, z FROM table WHERE x LIKE '%text%' OR y LIKE '%text%' OR z LIKE '%text%' queries. Would any kind of index help speed things up?

There are a few million records in the table. If there is anything that would speed up the search, would it seriously impact disk usage by the database files and the speed of INSERT and DELETE statements? (no UPDATE is ever performed)

Update: Quickly after posting, I have seen a lot of information and discussion about the way LIKE is used in the query; I would like to point out that the solution must use LIKE '%text%' (that is, the text I am looking for is prepended and appended with a % wildcard). The database also has to be local, for many reasons, including security.

答:
When you optimize a SELECT foo FROM bar WHERE baz LIKE 'ZOT%' query, you want the index length to at least match the number of characters in the request.

Here is a real life example from just now:

Here is the query:

EXPLAIN SELECT COUNT(*) FROM client_detail cd
JOIN client_account ca ON cd.client_acct_id = ca.client_acct_id
WHERE cd.first_name LIKE 'XX%' AND cd.last_name_index LIKE 'YY%';
```
<p>With no index:</p>
```+-------+
| rows  |
+-------+
| 13994 |
|     1 |
+-------+
```
<p>So first try a 4x index,</p>
<pre class="lang-sql prettyprint-override"><code>CREATE INDEX idx_last_first_4x4 on client_detail(last_name_index(4), first_name(4));
</code>```
```<code>+------+
| rows |
+------+
| 7035 |
|    1 |
+------+
</code>```

A bit better, but COUNT(*) shows there are only 102 results.  So lets now add a 2x index:

CREATE INDEX idx_last_first_2x2 on client_detail(last_name_index(2), first_name(2));
```
<p>yields:</p>
```+------+
| rows |
+------+
|  102 |
|    1 |
+------+
```

Both indexes are still in place at this point, and MySQL chose the latter index for this query---however it will still choose the 4x4 query if it is more efficient.

Index ordering may be useful, try the 2x2 before the 4x4 or vice-versa to see how it performs for your environment. To re-order an index you have to drop and re-create the earlier one.

Body:
When you optimize a SELECT foo FROM bar WHERE baz LIKE 'ZOT%' query, you want the index length to at least match the number of characters in the request.

Here is a real life example from just now:

Here is the query:

EXPLAIN SELECT COUNT(*) FROM client_detail cd
JOIN client_account ca ON cd.client_acct_id = ca.client_acct_id
WHERE cd.first_name LIKE 'XX%' AND cd.last_name_index LIKE 'YY%';

With no index:

+-------+
| rows  |
+-------+
| 13994 |
|     1 |
+-------+

So first try a 4x index,

CREATE INDEX idx_last_first_4x4 on client_detail(last_name_index(4), first_name(4));

+------+
| rows |
+------+
| 7035 |
|    1 |
+------+

A bit better, but COUNT(*) shows there are only 102 results.  So lets now add a 2x index:

CREATE INDEX idx_last_first_2x2 on client_detail(last_name_index(2), first_name(2));

yields:

+------+
| rows |
+------+
|  102 |
|    1 |
+------+

Both indexes are still in place at this point, and MySQL chose the latter index for this query---however it will still choose the 4x4 query if it is more efficient.

Index ordering may be useful, try the 2x2 before the 4x4 or vice-versa to see how it performs for your environment. To re-order an index you have to drop and re-create the earlier one.


问:
What are the values for, when using createTemplate in a contentByte class for iText?
I am using iText and am very new to it.  There have been several situations where I think I could have figured out the problem with my code if I knew what I was doing - I use examples without knowing the workings behind the code, and even as I look at the source I can't figure out what the programmer was thinking.

What are the values for, when using createTemple in a contentByte class for iText?

for example:

```<code>total = cb.createTemplate(100,100);
</code>```

where total is of type contentByte.

答:
It´is float width and float height of the template.
You might benefit from reading this.

http://api.itextpdf.com/itext/com/itextpdf/text/pdf/class-use/PdfTemplate.html

ContentLicense: CC BY-SA 2.5

Body:
I am using iText and am very new to it.  There have been several situations where I think I could have figured out the problem with my code if I knew what I was doing - I use examples without knowing the workings behind the code, and even as I look at the source I can't figure out what the programmer was thinking.

What are the values for, when using createTemple in a contentByte class for iText?

for example:

total = cb.createTemplate(100,100);

where total is of type contentByte.


问:
How to build a url with array of query parameters using http get request
I am trying to pass multiple values that I have selected in Supplier component and display the detail information in Supplier detail component.

I have to execute the query like below with selected vendors.

```<code> select distinct
asu.vendor_name,
asu.segment1 vendor_number,
asu.end_date_active,
asu.vendor_id
 from ap_suppliers asu, ap_supplier_sites_all ass
  where ass.org_id = 81
  and   ass.vendor_id = asu.vendor_id
  and  asu.vendor_id IN (123, 234, 456, 778)
     order by asu.vendor_name
</code>```

supplier component

```<code>supplierdetails() {
let selectedFileIds: string[] = [];
const options = {queryParams: {numbers:selectedFileIds } }
for (let item of this.selection.selected) {
  selectedFileIds.push(item.vendor_id);
}
console.log(options);
this.router.navigate(['/supplierdetails'], options);
</code>```

}

supplier Detail Component

```<code>ngAfterViewInit() {
// this.retrieveSupdetails(this.route.queryParamMap.subscribe(() =>this.numbers.getAll('options'));
 //(this.route.snapshot.paramMap.get('id'));
}
</code>```

Supplier Details Component Service

```<code>getSupdetails(vendor_id:number[]) {
  if (!this.supdetdata) {
    this.supdetdata = this.http.get(`${baseUrl}/supplierdetails?vendor_id=${vendor_id}`).pipe(
        map((data:any) => data.data),
        publishReplay(1),
        refCount()
    );
   }
   return this.supdetdata;
</code>```

}

Supplier Details Service

```<code> async function getSupplierDetails(vendor_id){

const rows = await db.query(
    `select distinct
    asu.vendor_name,
    asu.segment1 vendor_number,
    asu.end_date_active,
    asu.vendor_id
from ap_suppliers asu, ap_supplier_sites_all ass
where ass.org_id = 81
and   ass.vendor_id = asu.vendor_id
and  asu.vendor_id IN ($1)
order by asu.vendor_name`, [vendor_id]
  );

  const data = helper.emptyOrRows(rows);

  return {
    data
  }
</code>```

}

Supplier Details Router

```<code>  const express = require("express");
  const router = express.Router();
  const supplierdetails = require("../services/supplierdetails");

  router.get("/", async function (req, res, next) {
   try {
  res.json(await supplierdetails.getSupplierDetails(req.query.vendor_id));
    } catch (err) {
  console.error(`Error while getting supplier details`, err.message);
     next(err);
    }
   });

  module.exports = router;
</code>```

答:
Welcome Ramki.

To pass query params in a url through angular routing, use the queryParams property.

this.router.navigate(['supplierdetails'], {
      queryParams: { vendor_name: 'name', vendor_id: 1234 },
    });
```
<p>and in the receiving component</p>
<pre class="lang-js prettyprint-override"><code>  queryParams?: { vendor_name: string; vendor_id: number };

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    this.queryParams = { ...this.route.snapshot.queryParams } as any;
  }
</code>```

Does that answer your question?

Also, if you want to just create the url for passing to an api it's like this:

  queryParams?: { vendor_name: string; vendor_id: number };

  constructor(private route: ActivatedRoute, private router: Router) {}

  ngOnInit(): void {
    this.queryParams = { ...this.route.snapshot.queryParams } as any;
    const tree = this.router.createUrlTree([], {
      queryParams: this.queryParams,
    });
    const url = 'https://www.root.com' + this.router.serializeUrl(tree);
    // https://www.root.com/?vendor_name=name&vendor_id=1234
  }
```

Body:
I am trying to pass multiple values that I have selected in Supplier component and display the detail information in Supplier detail component.

I have to execute the query like below with selected vendors.

 select distinct
asu.vendor_name,
asu.segment1 vendor_number,
asu.end_date_active,
asu.vendor_id
 from ap_suppliers asu, ap_supplier_sites_all ass
  where ass.org_id = 81
  and   ass.vendor_id = asu.vendor_id
  and  asu.vendor_id IN (123, 234, 456, 778)
     order by asu.vendor_name

supplier component

supplierdetails() {
let selectedFileIds: string[] = [];
const options = {queryParams: {numbers:selectedFileIds } }
for (let item of this.selection.selected) {
  selectedFileIds.push(item.vendor_id);
}
console.log(options);
this.router.navigate(['/supplierdetails'], options);

}

supplier Detail Component

ngAfterViewInit() {
// this.retrieveSupdetails(this.route.queryParamMap.subscribe(() =>this.numbers.getAll('options'));
 //(this.route.snapshot.paramMap.get('id'));
}

Supplier Details Component Service

getSupdetails(vendor_id:number[]) {
  if (!this.supdetdata) {
    this.supdetdata = this.http.get(`${baseUrl}/supplierdetails?vendor_id=${vendor_id}`).pipe(
        map((data:any) => data.data),
        publishReplay(1),
        refCount()
    );
   }
   return this.supdetdata;

}

Supplier Details Service

 async function getSupplierDetails(vendor_id){

const rows = await db.query(
    `select distinct
    asu.vendor_name,
    asu.segment1 vendor_number,
    asu.end_date_active,
    asu.vendor_id
from ap_suppliers asu, ap_supplier_sites_all ass
where ass.org_id = 81
and   ass.vendor_id = asu.vendor_id
and  asu.vendor_id IN ($1)
order by asu.vendor_name`, [vendor_id]
  );

  const data = helper.emptyOrRows(rows);

  return {
    data
  }

}

Supplier Details Router

  const express = require("express");
  const router = express.Router();
  const supplierdetails = require("../services/supplierdetails");

  router.get("/", async function (req, res, next) {
   try {
  res.json(await supplierdetails.getSupplierDetails(req.query.vendor_id));
    } catch (err) {
  console.error(`Error while getting supplier details`, err.message);
     next(err);
    }
   });

  module.exports = router;

Body:
Welcome Ramki.

To pass query params in a url through angular routing, use the queryParams property.

this.router.navigate(['supplierdetails'], {
      queryParams: { vendor_name: 'name', vendor_id: 1234 },
    });

and in the receiving component

  queryParams?: { vendor_name: string; vendor_id: number };

  constructor(private route: ActivatedRoute) {}

  ngOnInit(): void {
    this.queryParams = { ...this.route.snapshot.queryParams } as any;
  }

Does that answer your question?

Also, if you want to just create the url for passing to an api it's like this:

  queryParams?: { vendor_name: string; vendor_id: number };

  constructor(private route: ActivatedRoute, private router: Router) {}

  ngOnInit(): void {
    this.queryParams = { ...this.route.snapshot.queryParams } as any;
    const tree = this.router.createUrlTree([], {
      queryParams: this.queryParams,
    });
    const url = 'https://www.root.com' + this.router.serializeUrl(tree);
    // https://www.root.com/?vendor_name=name&vendor_id=1234
  }


问:
Converting to military time works in Jupyter Notebook but not in HackerRank
My code works for all sample input hours of the day in Jupyter notebook but I get error message in HackerRank:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'(it doesn't tell me which line)

input : string of AM/PM format
output: string of military time

```<code>def timeConversion(s):
    if int(s[:2]) < 12 and s[8] == "P":
        time = int(s[:2]) + 12
        print(str(time) + s[2:8])
    elif int(s[:2]) == 12 and s[8] == "A":
        time2 = int(s[:2]) - 12
        print(str(time2) + s[2:8])

    else:
        print(str(s[0:8]))
</code>```

答:
Note that timeConversion, in its current form, prints the output and returns None (since you didn't include a return statement). I suspect that the HackerRank problem is set up to work with a timeConversion function that returns a string. With that said, I would try replacing your function with the following.

```<code>def timeConversion(s):
    if int(s[:2]) < 12 and s[8] == "P":
        time = int(s[:2]) + 12
        return str(time) + s[2:8]
    elif int(s[:2]) == 12 and s[8] == "A":
        time2 = int(s[:2]) - 12
        return str(time2) + s[2:8]

    else:
        return str(s[0:8])
</code>```

Body:
My code works for all sample input hours of the day in Jupyter notebook but I get error message in HackerRank:

TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'(it doesn't tell me which line)

input : string of AM/PM format
output: string of military time

def timeConversion(s):
    if int(s[:2]) < 12 and s[8] == "P":
        time = int(s[:2]) + 12
        print(str(time) + s[2:8])
    elif int(s[:2]) == 12 and s[8] == "A":
        time2 = int(s[:2]) - 12
        print(str(time2) + s[2:8])

    else:
        print(str(s[0:8]))

Body:
Note that timeConversion, in its current form, prints the output and returns None (since you didn't include a return statement). I suspect that the HackerRank problem is set up to work with a timeConversion function that returns a string. With that said, I would try replacing your function with the following.

def timeConversion(s):
    if int(s[:2]) < 12 and s[8] == "P":
        time = int(s[:2]) + 12
        return str(time) + s[2:8]
    elif int(s[:2]) == 12 and s[8] == "A":
        time2 = int(s[:2]) - 12
        return str(time2) + s[2:8]

    else:
        return str(s[0:8])


问:
Async/Await doesn't await
Building a node.js CLI application. Users should choose some tasks to run and based on that, tasks should work and then spinners (using ora package) should show success and stop spin.

The issue here is spinner succeed while tasks are still going on. Which means it doesn't wait.

Tried using typical Async/Await as to have an async function and await each function under condition. Didn't work.

Tried using promise.all. Didn't work.

Tried using waterfall. Same.

Here's the code of the task runner, I create an array of functions and pass it to waterfall (Async-waterfall package) or promise.all() method.

const runner = async () => {
    let tasks = [];

    spinner.start('Running tasks');

    if (syncOptions.includes('taskOne')) {
        tasks.push(taskOne);
    }

    if (syncOptions.includes('taskTwo')) {
        tasks.push(taskTwo);
    }

    if (syncOptions.includes('taskThree')) {
        tasks.push(taskThree);
    }

    if (syncOptions.includes('taskFour')) {
        tasks.push(taskFour);
    }

    // Option One
    waterfall(tasks, () => {
        spinner.succeed('Done');
    });

    // Option Two
    Promise.all(tasks).then(() => {
        spinner.succeed('Done');
    });
};
```
<p>Here's an example of one of the functions:</p>
<pre class="lang-js prettyprint-override"><code>const os = require('os');
const fs = require('fs');

const homedir = os.homedir();
const outputDir = `${homedir}/output`;
const file = `${homedir}/.file`;
const targetFile = `${outputDir}/.file`;

module.exports = async () => {
    await fs.writeFileSync(targetFile, fs.readFileSync(file));
};

</code>```

I tried searching concepts. Talked to the best 5 people I know who can write JS properly. No clue.. What am I doing wrong ?

答:
You don't show us all your code, but the first warning sign is that it doesn't appear you are actually running taskOne(), taskTwo(), etc...

You are pushing what look like functions into an array with code like:

```<code>tasks.push(taskFour);
</code>```

And, then attempting to do:

```<code>Promise.all(tasks).then(...)
</code>```

That won't do anything useful because the tasks themselves are never executed.   To use Promise.all(), you need to pass it an array of promises, not an array of functions.

So, you would use:

```<code>tasks.push(taskFour());
</code>```

and then:

```<code>Promise.all(tasks).then(...);
</code>```

And, all this assumes that taskOne(), taskTwo(), etc... are function that return a promise that resolves/rejects when their asynchronous operation is complete.

In addition, you also need to either await Promise.all(...) or return Promise.all() so that the caller will be able to know when they are all done.  Since this is the last line of your function, I'd generally  just use return Promise.all(...) and this will let the caller get the resolved results from all the tasks (if those are relevant).

Also, this doesn't make much sense:

```<code>module.exports = async () => {
    await fs.writeFileSync(targetFile, fs.readFileSync(file));
};
</code>```

You're using two synchronous file operations.  They are not asynchronous and do not use promises so there's no reason to put them in an async function or to use await with them.  You're mixing two models incorrectly.  If you want them to be synchronous, then you can just do this:

```<code>module.exports = () => {
    fs.writeFileSync(targetFile, fs.readFileSync(file));
};
</code>```

If you want them to be asynchronous and return a promise, then you can do this:

```<code>module.exports = async () => {
    return fs.promises.writeFile(targetFile, await fs.promises.readFile(file));
};
</code>```

Your implementation was attempting to be half and half.  Pick one architecture or the other (synchronous or asynchronous) and be consistent in the implementation.

FYI, the fs module now has multiple versions of fs.copyFile() so you could also use that and let it do the copying for you.  If this file was large, copyFile() would likely use less memory in doing so.

As for your use of waterfall(), it is probably not necessary here and waterfall uses a very different calling model than Promise.all() so you certainly can't use the same model with Promise.all() as you do with waterfall().  Also, waterfall() runs your functions in sequence (one after the other) and you pass it an array of functions that have their own calling convention.

So, assuming that taskOne, taskTwo, etc... are functions that return a promise that resolve/reject when their asynchronous operations are done, then you would do this:

```<code>const runner = () => {
    let tasks = [];

    spinner.start('Running tasks');

    if (syncOptions.includes('taskOne')) {
        tasks.push(taskOne());
    }

    if (syncOptions.includes('taskTwo')) {
        tasks.push(taskTwo());
    }

    if (syncOptions.includes('taskThree')) {
        tasks.push(taskThree());
    }

    if (syncOptions.includes('taskFour')) {
        tasks.push(taskFour());
    }

    return Promise.all(tasks).then(() => {
        spinner.succeed('Done');
    });
};
</code>```

This would run the tasks in parallel.

If you want to run the tasks in sequence (one after the other), then you would do this:

```<code>const runner = async () => {

    spinner.start('Running tasks');

    if (syncOptions.includes('taskOne')) {
        await taskOne();
    }

    if (syncOptions.includes('taskTwo')) {
        await taskTwo();
    }

    if (syncOptions.includes('taskThree')) {
        await taskThree();
    }

    if (syncOptions.includes('taskFour')) {
        await taskFour();
    }

    spinner.succeed('Done');
};
</code>```

Title: Async/Await doesn't await

Body:
Building a node.js CLI application. Users should choose some tasks to run and based on that, tasks should work and then spinners (using ora package) should show success and stop spin.

The issue here is spinner succeed while tasks are still going on. Which means it doesn't wait.

Tried using typical Async/Await as to have an async function and await each function under condition. Didn't work.

Tried using promise.all. Didn't work.

Tried using waterfall. Same.

Here's the code of the task runner, I create an array of functions and pass it to waterfall (Async-waterfall package) or promise.all() method.

const runner = async () => {
    let tasks = [];

    spinner.start('Running tasks');

    if (syncOptions.includes('taskOne')) {
        tasks.push(taskOne);
    }

    if (syncOptions.includes('taskTwo')) {
        tasks.push(taskTwo);
    }

    if (syncOptions.includes('taskThree')) {
        tasks.push(taskThree);
    }

    if (syncOptions.includes('taskFour')) {
        tasks.push(taskFour);
    }

    // Option One
    waterfall(tasks, () => {
        spinner.succeed('Done');
    });

    // Option Two
    Promise.all(tasks).then(() => {
        spinner.succeed('Done');
    });
};

Here's an example of one of the functions:

const os = require('os');
const fs = require('fs');

const homedir = os.homedir();
const outputDir = `${homedir}/output`;
const file = `${homedir}/.file`;
const targetFile = `${outputDir}/.file`;

module.exports = async () => {
    await fs.writeFileSync(targetFile, fs.readFileSync(file));
};

I tried searching concepts. Talked to the best 5 people I know who can write JS properly. No clue.. What am I doing wrong ?

Body:
You don't show us all your code, but the first warning sign is that it doesn't appear you are actually running taskOne(), taskTwo(), etc...

You are pushing what look like functions into an array with code like:

tasks.push(taskFour);

And, then attempting to do:

Promise.all(tasks).then(...)

That won't do anything useful because the tasks themselves are never executed.   To use Promise.all(), you need to pass it an array of promises, not an array of functions.

So, you would use:

tasks.push(taskFour());

and then:

Promise.all(tasks).then(...);

And, all this assumes that taskOne(), taskTwo(), etc... are function that return a promise that resolves/rejects when their asynchronous operation is complete.

In addition, you also need to either await Promise.all(...) or return Promise.all() so that the caller will be able to know when they are all done.  Since this is the last line of your function, I'd generally  just use return Promise.all(...) and this will let the caller get the resolved results from all the tasks (if those are relevant).

Also, this doesn't make much sense:

module.exports = async () => {
    await fs.writeFileSync(targetFile, fs.readFileSync(file));
};

You're using two synchronous file operations.  They are not asynchronous and do not use promises so there's no reason to put them in an async function or to use await with them.  You're mixing two models incorrectly.  If you want them to be synchronous, then you can just do this:

module.exports = () => {
    fs.writeFileSync(targetFile, fs.readFileSync(file));
};

If you want them to be asynchronous and return a promise, then you can do this:

module.exports = async () => {
    return fs.promises.writeFile(targetFile, await fs.promises.readFile(file));
};

Your implementation was attempting to be half and half.  Pick one architecture or the other (synchronous or asynchronous) and be consistent in the implementation.

FYI, the fs module now has multiple versions of fs.copyFile() so you could also use that and let it do the copying for you.  If this file was large, copyFile() would likely use less memory in doing so.

As for your use of waterfall(), it is probably not necessary here and waterfall uses a very different calling model than Promise.all() so you certainly can't use the same model with Promise.all() as you do with waterfall().  Also, waterfall() runs your functions in sequence (one after the other) and you pass it an array of functions that have their own calling convention.

So, assuming that taskOne, taskTwo, etc... are functions that return a promise that resolve/reject when their asynchronous operations are done, then you would do this:

const runner = () => {
    let tasks = [];

    spinner.start('Running tasks');

    if (syncOptions.includes('taskOne')) {
        tasks.push(taskOne());
    }

    if (syncOptions.includes('taskTwo')) {
        tasks.push(taskTwo());
    }

    if (syncOptions.includes('taskThree')) {
        tasks.push(taskThree());
    }

    if (syncOptions.includes('taskFour')) {
        tasks.push(taskFour());
    }

    return Promise.all(tasks).then(() => {
        spinner.succeed('Done');
    });
};

This would run the tasks in parallel.

If you want to run the tasks in sequence (one after the other), then you would do this:

const runner = async () => {

    spinner.start('Running tasks');

    if (syncOptions.includes('taskOne')) {
        await taskOne();
    }

    if (syncOptions.includes('taskTwo')) {
        await taskTwo();
    }

    if (syncOptions.includes('taskThree')) {
        await taskThree();
    }

    if (syncOptions.includes('taskFour')) {
        await taskFour();
    }

    spinner.succeed('Done');
};


问:
React Native vector icons are not shown correctly on Android
I've added Material Design Paper library by their manual.

And Gradle prints a lot of warnings as below:

```<code>> Task :app:stripDebugDebugSymbols
Execution optimizations have been disabled for task ':app:stripDebugDebugSymbols' to ensure correctness due to the following reasons:
  - Gradle detected a problem with the following location: '/app/android/app/build/intermediates/merged_native_libs/debug/out'. Reason: Task ':app:stripDebugDebugSymbols' uses this output of task ':app:copyDebugReactNativeVectorIconFonts' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. Please refer to https://docs.gradle.org/7.2/userguide/validation_problems.html#implicit_dependency for more details about this problem.
</code>```

If run my app by Android Studio it launches but icons look weirdly (not like here):

android/build.gradle:

```<code>buildscript {
    ext {
        buildToolsVersion = "32.1.0-rc1"
        minSdkVersion = 30
        compileSdkVersion = 32
        targetSdkVersion = 32
        ndkVersion = "21.4.7075529"
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath('com.android.tools.build:gradle:7.1.1')
    }
}

allprojects {
    repositories {
        maven {
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            url("$rootDir/../node_modules/jsc-android/dist")
        }
        mavenCentral {
            content {
                excludeGroup "com.facebook.react"
            }
        }
        google()
        maven { url 'https://www.jitpack.io' }
    }
}
</code>```

android/app/build.gradle:

```<code>project.ext.react = [
    enableHermes: false,
]

apply from: "../../node_modules/react-native/react.gradle"
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle")
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
applyNativeModulesAppBuildGradle(project)

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = false

def jscFlavor = 'org.webkit:android-jsc:+'

def enableHermes = project.ext.react.get("enableHermes", false)

def nativeArchitectures = project.getProperties().get("reactNativeDebugArchitectures")

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    defaultConfig {
        applicationId "com.company.app"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 4
        versionName "0.2.1"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
            if (nativeArchitectures) {
                ndk {
                    abiFilters nativeArchitectures.split(',')
                }
            }
        }
        release {
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(com.android.build.OutputFile.ABI)
            if (abi != null) {
                output.versionCodeOverride =
                        defaultConfig.versionCode * 1000 + versionCodes.get(abi)
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])

    implementation 'com.facebook.react:react-native:0.67.2'  // From node_modules

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"

    debugImplementation('com.facebook.flipper:flipper:0.131.1') {
        exclude group:'com.facebook.fbjni'
    }

    debugImplementation('com.facebook.flipper:flipper-network-plugin:0.131.1') {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation('com.facebook.flipper:flipper-fresco-plugin:0.131.1') {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/"
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}

task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.implementation
    into 'libs'
}
</code>```

android/settings.gradle:

```<code>rootProject.name = 'App'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle")
applyNativeModulesSettingsGradle(settings)
include ':app'
</code>```

Where can the problem be?

答:
Finally, I've found a solution. I was needed to copy these fonts into

android/app/src/main/assets/fonts

Although it's still weird for me because I thought this process will be completed automatically on build.

Body:
I've added Material Design Paper library by their manual.

And Gradle prints a lot of warnings as below:

> Task :app:stripDebugDebugSymbols
Execution optimizations have been disabled for task ':app:stripDebugDebugSymbols' to ensure correctness due to the following reasons:
  - Gradle detected a problem with the following location: '/app/android/app/build/intermediates/merged_native_libs/debug/out'. Reason: Task ':app:stripDebugDebugSymbols' uses this output of task ':app:copyDebugReactNativeVectorIconFonts' without declaring an explicit or implicit dependency. This can lead to incorrect results being produced, depending on what order the tasks are executed. Please refer to https://docs.gradle.org/7.2/userguide/validation_problems.html#implicit_dependency for more details about this problem.

If run my app by Android Studio it launches but icons look weirdly (not like here):

android/build.gradle:

buildscript {
    ext {
        buildToolsVersion = "32.1.0-rc1"
        minSdkVersion = 30
        compileSdkVersion = 32
        targetSdkVersion = 32
        ndkVersion = "21.4.7075529"
    }
    repositories {
        google()
        mavenCentral()
    }
    dependencies {
        classpath('com.android.tools.build:gradle:7.1.1')
    }
}

allprojects {
    repositories {
        maven {
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            url("$rootDir/../node_modules/jsc-android/dist")
        }
        mavenCentral {
            content {
                excludeGroup "com.facebook.react"
            }
        }
        google()
        maven { url 'https://www.jitpack.io' }
    }
}

android/app/build.gradle:

project.ext.react = [
    enableHermes: false,
]

apply from: "../../node_modules/react-native/react.gradle"
apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle")
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
applyNativeModulesAppBuildGradle(project)

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = false

def jscFlavor = 'org.webkit:android-jsc:+'

def enableHermes = project.ext.react.get("enableHermes", false)

def nativeArchitectures = project.getProperties().get("reactNativeDebugArchitectures")

android {
    ndkVersion rootProject.ext.ndkVersion

    compileSdkVersion rootProject.ext.compileSdkVersion

    defaultConfig {
        applicationId "com.company.app"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 4
        versionName "0.2.1"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }
    buildTypes {
        debug {
            signingConfig signingConfigs.debug
            if (nativeArchitectures) {
                ndk {
                    abiFilters nativeArchitectures.split(',')
                }
            }
        }
        release {
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }

    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
            def abi = output.getFilter(com.android.build.OutputFile.ABI)
            if (abi != null) {
                output.versionCodeOverride =
                        defaultConfig.versionCode * 1000 + versionCodes.get(abi)
            }

        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])

    implementation 'com.facebook.react:react-native:0.67.2'  // From node_modules

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.1.0"

    debugImplementation('com.facebook.flipper:flipper:0.131.1') {
        exclude group:'com.facebook.fbjni'
    }

    debugImplementation('com.facebook.flipper:flipper-network-plugin:0.131.1') {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation('com.facebook.flipper:flipper-fresco-plugin:0.131.1') {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/"
        debugImplementation files(hermesPath + "hermes-debug.aar")
        releaseImplementation files(hermesPath + "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
}

task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.implementation
    into 'libs'
}

android/settings.gradle:

rootProject.name = 'App'
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle")
applyNativeModulesSettingsGradle(settings)
include ':app'

Where can the problem be?


问:
Selecting minimum value between columns python
I have a DataFrame that looks like the below. "Name" represents a student name and values below each of the Test variables represent the test grade.

```<code>Name Test1 Test2 Test3
Ana  87    93    82
Cole 62    73    84
Sia  64    58    60
Max  93    95    99
Leah 93    90    85
Cam  76    80    83
</code>```

The desired result is the DataFrame below. Where "MinTestGrade" represents that lowest grade each student earned between the 3. "TestNumber" is the Test they got the lowest grade on.

```<code>Name TestNumber MinTestGrade
Ana  3          82
Cole 1          62
Sia  2          58
Max  1          93
Leah 3          85
Cam  1          76
</code>```

How can I do this using python?

答:
You can pass idxmin and min to agg on axis to find the minimum grade and the column name, i.e. TestNumber, that it corresponds to for each student. Then join the outcome with "Name", rename the columns and finally strip the word "Test" from "TestNumber":

```<code>out = df[['Name']].join(df.filter(like='Test').agg(['idxmin', 'min'], axis=1)).rename(columns={'idxmin':'TestNumber', 'min':'MinTestGrade'})
out['TestNumber'] = out['TestNumber'].str.lstrip('Test').astype(int)
</code>```

Output:

```<code>   Name  TestNumber MinTestGrade
0   Ana           3           82
1  Cole           1           62
2   Sia           2           58
3   Max           1           93
4  Leah           3           85
5   Cam           1           76
</code>```

Body:
I have a DataFrame that looks like the below. "Name" represents a student name and values below each of the Test variables represent the test grade.

Name Test1 Test2 Test3
Ana  87    93    82
Cole 62    73    84
Sia  64    58    60
Max  93    95    99
Leah 93    90    85
Cam  76    80    83

The desired result is the DataFrame below. Where "MinTestGrade" represents that lowest grade each student earned between the 3. "TestNumber" is the Test they got the lowest grade on.

Name TestNumber MinTestGrade
Ana  3          82
Cole 1          62
Sia  2          58
Max  1          93
Leah 3          85
Cam  1          76

How can I do this using python?

Body:
You can pass idxmin and min to agg on axis to find the minimum grade and the column name, i.e. TestNumber, that it corresponds to for each student. Then join the outcome with "Name", rename the columns and finally strip the word "Test" from "TestNumber":

out = df[['Name']].join(df.filter(like='Test').agg(['idxmin', 'min'], axis=1)).rename(columns={'idxmin':'TestNumber', 'min':'MinTestGrade'})
out['TestNumber'] = out['TestNumber'].str.lstrip('Test').astype(int)

Output:

   Name  TestNumber MinTestGrade
0   Ana           3           82
1  Cole           1           62
2   Sia           2           58
3   Max           1           93
4  Leah           3           85
5   Cam           1           76


问:
Problem after upgrading Material-ui version from 4 to 5 using component with react-number-format
I updated the material-ui version from v4 to v5, but I'm facing problems in a component that uses the react-number-format library, apparently the problem is related to Forwarding refs, but I can't solve it, can anyone help me?

Browser error: Failed prop type: Invalid prop inputComponent supplied to ForwardRef(InputBase)

Thank you for your help!

FormikTextNumber

```<code>import React from "react";
import { NumberFormatValues } from "react-number-format";
import { TextField, TextFieldProps } from "@mui/material";
import { Field, useField } from "formik";
import NumberFormatCustom from "./number-format";

type FormikTextNumberProps = TextFieldProps & {
  name: string;
  suffix: string;
  setFieldValue: any;
};

const FormikTextNumber = (props: FormikTextNumberProps): React.ReactElement => {
  const { name, prefix, suffix, setFieldValue, ...rest } = props;

  const [, { touched, value, error }, { setValue }] = useField(name);
  const isError = Boolean(error) && touched;

  const handleChange = (values: NumberFormatValues) => {
    setValue(values?.floatValue ?? "");
    if (setFieldValue) {
      setFieldValue(values?.floatValue ?? "");
    }
  };

  return (
    <Field
      {...rest}
      name={name}
      value={value}
      size="small"
      margin="dense"
      variant="outlined"
      autoComplete="off"
      as={TextField}
      onChange={null}
      error={isError}
      helperText={isError ? error : undefined}
      InputProps={{
        inputComponent: NumberFormatCustom,
        inputProps: {
          onValueChange: handleChange,
          prefix: prefix,
          suffix: suffix
        }
      }}
    />
  );
};

export default FormikTextNumber;
</code>```

NumberFormatCustom

```<code>import React from "react";
import NumberFormat, { NumberFormatProps } from "react-number-format";

interface NumberFormatCustomProps extends NumberFormatProps {
  inputRef: (instance: NumberFormat<any> | null) => void;
}

const NumberFormatCustom = (
  props: NumberFormatCustomProps
): React.ReactElement => {
  const { inputRef, ...rest } = props;
  return <NumberFormat {...rest} getInputRef={inputRef} />;
};

NumberFormatCustom.defaultProps = {
  thousandSeparator: ".",
  decimalSeparator: ",",
  allowNegative: true
};

export default NumberFormatCustom;
</code>```

Form

```<code>import React from "react";
import { Formik, Form } from "formik";
import * as Yup from "yup";

import "./styles.css";
import InputNumberNew from "./components/InputNumberNew";
import InputNumberOld from "./components/InputNumberOld";
import { Box, Grid } from "@mui/material";

const validationSchema = Yup.object({
  old: Yup.number().required("error"),
  new: Yup.number().required("error")
});

const initialValues = {
  old: 0,
  new: 0
};

export default function App() {
  return (
    <div className="App">
      <h1>Upgrade Material-ui 4 to 5 with number-format </h1>
      <Formik
        initialValues={initialValues}
        onSubmit={(e) => {
          console.log(e);
        }}
        validationSchema={validationSchema}
      >
        {({ values, touched, errors, handleChange, handleBlur }) => {
          return (
            <Form>
              <Grid container>
                <Grid item xs={12}>
                  <Box color="green" mt={2}>
                    It's work
                  </Box>
                  <Box mb={0.5} color="green">
                    Material-ui 4
                  </Box>
                  <InputNumberOld
                    label="Material-ui 4"
                    name="old"
                    prefix={"$ "}
                  />
                </Grid>
                <Grid item xs={12}>
                  <Box color="red" mt={2}>
                    It's doesn't work
                  </Box>
                  <Box mb={0.5} color="red">
                    Material-ui 5
                  </Box>
                  <InputNumberNew
                    label="Material-ui 5"
                    name="new"
                    prefix={"$ "}
                  />
                </Grid>
              </Grid>
            </Form>
          );
        }}
      </Formik>
    </div>
  );
}
</code>```

答:
Problem solved by changing the component NumberFormatCustom, as mentioned in the Material-ui migration documentation at this link.

```<code>import React from "react";
import NumberFormat, { NumberFormatProps } from "react-number-format";

interface NumberFormatCustomProps extends NumberFormatProps {
  ref: (instance: NumberFormat<any> | null) => void;
}

const NumberFormatCustom = React.forwardRef(function NumberFormatCustom(
  props: NumberFormatCustomProps,
  ref
): React.ReactElement {
  return <NumberFormat {...props} getInputRef={ref} />;
});

NumberFormatCustom.defaultProps = {
  thousandSeparator: ".",
  decimalSeparator: ",",
  allowNegative: true
};

export default NumberFormatCustom;
</code>```

Body:
I updated the material-ui version from v4 to v5, but I'm facing problems in a component that uses the react-number-format library, apparently the problem is related to Forwarding refs, but I can't solve it, can anyone help me?

Browser error: Failed prop type: Invalid prop inputComponent supplied to ForwardRef(InputBase)

Thank you for your help!

FormikTextNumber

import React from "react";
import { NumberFormatValues } from "react-number-format";
import { TextField, TextFieldProps } from "@mui/material";
import { Field, useField } from "formik";
import NumberFormatCustom from "./number-format";

type FormikTextNumberProps = TextFieldProps & {
  name: string;
  suffix: string;
  setFieldValue: any;
};

const FormikTextNumber = (props: FormikTextNumberProps): React.ReactElement => {
  const { name, prefix, suffix, setFieldValue, ...rest } = props;

  const [, { touched, value, error }, { setValue }] = useField(name);
  const isError = Boolean(error) && touched;

  const handleChange = (values: NumberFormatValues) => {
    setValue(values?.floatValue ?? "");
    if (setFieldValue) {
      setFieldValue(values?.floatValue ?? "");
    }
  };

  return (
    <Field
      {...rest}
      name={name}
      value={value}
      size="small"
      margin="dense"
      variant="outlined"
      autoComplete="off"
      as={TextField}
      onChange={null}
      error={isError}
      helperText={isError ? error : undefined}
      InputProps={{
        inputComponent: NumberFormatCustom,
        inputProps: {
          onValueChange: handleChange,
          prefix: prefix,
          suffix: suffix
        }
      }}
    />
  );
};

export default FormikTextNumber;

NumberFormatCustom

import React from "react";
import NumberFormat, { NumberFormatProps } from "react-number-format";

interface NumberFormatCustomProps extends NumberFormatProps {
  inputRef: (instance: NumberFormat<any> | null) => void;
}

const NumberFormatCustom = (
  props: NumberFormatCustomProps
): React.ReactElement => {
  const { inputRef, ...rest } = props;
  return <NumberFormat {...rest} getInputRef={inputRef} />;
};

NumberFormatCustom.defaultProps = {
  thousandSeparator: ".",
  decimalSeparator: ",",
  allowNegative: true
};

export default NumberFormatCustom;

Form

import React from "react";
import { Formik, Form } from "formik";
import * as Yup from "yup";

import "./styles.css";
import InputNumberNew from "./components/InputNumberNew";
import InputNumberOld from "./components/InputNumberOld";
import { Box, Grid } from "@mui/material";

const validationSchema = Yup.object({
  old: Yup.number().required("error"),
  new: Yup.number().required("error")
});

const initialValues = {
  old: 0,
  new: 0
};

export default function App() {
  return (

Upgrade Material-ui 4 to 5 with number-format

      <Formik
        initialValues={initialValues}
        onSubmit={(e) => {
          console.log(e);
        }}
        validationSchema={validationSchema}
      >
        {({ values, touched, errors, handleChange, handleBlur }) => {
          return (
            <Form>
              <Grid container>
                <Grid item xs={12}>
                  <Box color="green" mt={2}>
                    It's work
                  </Box>
                  <Box mb={0.5} color="green">
                    Material-ui 4
                  </Box>
                  <InputNumberOld
                    label="Material-ui 4"
                    name="old"
                    prefix={"$ "}
                  />
                </Grid>
                <Grid item xs={12}>
                  <Box color="red" mt={2}>
                    It's doesn't work
                  </Box>
                  <Box mb={0.5} color="red">
                    Material-ui 5
                  </Box>
                  <InputNumberNew
                    label="Material-ui 5"
                    name="new"
                    prefix={"$ "}
                  />
                </Grid>
              </Grid>
            </Form>
          );
        }}
      </Formik>

  );
}

Body:
Problem solved by changing the component NumberFormatCustom, as mentioned in the Material-ui migration documentation at this link.

import React from "react";
import NumberFormat, { NumberFormatProps } from "react-number-format";

interface NumberFormatCustomProps extends NumberFormatProps {
  ref: (instance: NumberFormat<any> | null) => void;
}

const NumberFormatCustom = React.forwardRef(function NumberFormatCustom(
  props: NumberFormatCustomProps,
  ref
): React.ReactElement {
  return <NumberFormat {...props} getInputRef={ref} />;
});

NumberFormatCustom.defaultProps = {
  thousandSeparator: ".",
  decimalSeparator: ",",
  allowNegative: true
};

export default NumberFormatCustom;


问:
Nested ternary operators
I have this code:

```<code>_viewModel.PhoneDefault = user == null ? "" :
    (string.IsNullOrEmpty(user.PhoneDay) ?
        (string.IsNullOrEmpty(user.PhoneEvening) ?
            (string.IsNullOrEmpty(user.Mobile) ? "" :
                user.Mobile) :
            user.PhoneEvening) :
         user.PhoneDay);
</code>```

Is there a better way to write this to make it more readable?

答:
In your case you can write a helper function, like this:

```<code>// return the first parameter that isn't null or empty
public static string CoalesceStrings(params string[] src)
{
    foreach (var str in src)
        if (!string.IsNullOrEmpty(str))
            return str;
    return "";
}
</code>```

Then just call it, like this:

```<code>_viewModel.PhoneDefault = user == null ? "" :
    CoalesceStrings(user.PhoneDay, user.PhoneEvening, user.Mobile);
</code>```

Title: Nested ternary operators

Body:
I have this code:

_viewModel.PhoneDefault = user == null ? "" :
    (string.IsNullOrEmpty(user.PhoneDay) ?
        (string.IsNullOrEmpty(user.PhoneEvening) ?
            (string.IsNullOrEmpty(user.Mobile) ? "" :
                user.Mobile) :
            user.PhoneEvening) :
         user.PhoneDay);

Is there a better way to write this to make it more readable?

Body:
In your case you can write a helper function, like this:

// return the first parameter that isn't null or empty
public static string CoalesceStrings(params string[] src)
{
    foreach (var str in src)
        if (!string.IsNullOrEmpty(str))
            return str;
    return "";
}

Then just call it, like this:

_viewModel.PhoneDefault = user == null ? "" :
    CoalesceStrings(user.PhoneDay, user.PhoneEvening, user.Mobile);


问:
Sum variable number of columns with multiple criteria on multiple columns
Looking for some help on creating a formula (ideally Google Sheets compatible) that will allow me to define criteria range for multiple columns and define how many columns to sum.

For example, in the screenshot provided, I am interested in:

Names A, B, and C

Program X and Z

Sum of the first two months (Jan and Feb)

I would expect the result to give 1050, and if I change the Months criteria to 3, it would add in March as well and total to 550

Example

Thanks!

答:
use:

```<code>=SUM(FILTER(FILTER(C2:F10, COLUMN(C1:F1)-COLUMN(C1)<C12),
 REGEXMATCH(A2:A10, TEXTJOIN("|", 1, A12:A15)),
 REGEXMATCH(B2:B10, TEXTJOIN("|", 1, B12:B15))))
</code>```

Body:
use:

=SUM(FILTER(FILTER(C2:F10, COLUMN(C1:F1)-COLUMN(C1)<C12),
 REGEXMATCH(A2:A10, TEXTJOIN("|", 1, A12:A15)),
 REGEXMATCH(B2:B10, TEXTJOIN("|", 1, B12:B15))))


问:
git difftool fails silently when file is not found
Take any git repo and run the following

```<code>git difftool -- asdfasdfasdsfawerf
</code>```

i.e. give it an invalid filename. It will return immediately showing no diff, but it also has 0 return code. Obviously it should give some sort of error because it's not that there's no diffs in my file, the file itself doesn't exist either in my working tree or in HEAD so I'm asking an invalid question.

In case you think this is a contrived example, this can be a real issue if the name of a file is mistyped. You end up thinking there's no diff in the file when actually it couldn't find the file.

Does anyone know of a way to force it to fail if the file is not found?

答:
git difftool ends up executing git diff "$@" Looking a the relevant source code at line 2713:

```<code>2713                         if (strcmp(arg, "--"))
2714                                 continue;
2715                         argv[i] = NULL;
2716                         argc = i;
</code>```

we can see that the argument list are cut short when -- is encountered.

Later on in the code, at line 2782 the file name would have been checked and an error would be have been raised, if it wasn't for the !strcmp("--", arg) above:

```<code>2781                         for (j = i; j < argc; j++)
2782                                 verify_filename(revs->prefix, argv[j], j == i);
</code>```

It seems like a bug in the revision setup, but I don't contribute to git so can't say much about the source code, I just spend a few minutes digging into it.

When calling git diff -- abc argv will contain { "diff" } after it have been cut short, and when called with git diff abc it will contain { "diff", "abc" }

Body:
Take any git repo and run the following

git difftool -- asdfasdfasdsfawerf

i.e. give it an invalid filename. It will return immediately showing no diff, but it also has 0 return code. Obviously it should give some sort of error because it's not that there's no diffs in my file, the file itself doesn't exist either in my working tree or in HEAD so I'm asking an invalid question.

In case you think this is a contrived example, this can be a real issue if the name of a file is mistyped. You end up thinking there's no diff in the file when actually it couldn't find the file.

Does anyone know of a way to force it to fail if the file is not found?

Body:
git difftool ends up executing git diff "$@" Looking a the relevant source code at line 2713:

2713                         if (strcmp(arg, "--"))
2714                                 continue;
2715                         argv[i] = NULL;
2716                         argc = i;

we can see that the argument list are cut short when -- is encountered.

Later on in the code, at line 2782 the file name would have been checked and an error would be have been raised, if it wasn't for the !strcmp("--", arg) above:

2781                         for (j = i; j < argc; j++)
2782                                 verify_filename(revs->prefix, argv[j], j == i);

It seems like a bug in the revision setup, but I don't contribute to git so can't say much about the source code, I just spend a few minutes digging into it.

When calling git diff -- abc argv will contain { "diff" } after it have been cut short, and when called with git diff abc it will contain { "diff", "abc" }


问:
Optimal way of handling NFT minting queue
I am doing a generative NFT project where the user purchases an NFT pack from (1 to 10) and there will be a service that generates up to 10 NFTs, uploads it to IPFS then returns it to the frontend. Frontend then prompts the user to approve the transaction which then mints the NFT to the user.

This flows takes some time especially at the generating part,

so I was thinking of creating a different flow that has a smart contract that holds a queue array. Instead of generating the NFT first, the user will join the queue in the smart contract, then a service that polls the queue array will start generating and minting anything in the queue.

However, if I do this flow, the service will have to be the one that pays the gas fee when minting,

so I was wondering if anyone could advise me on how to create a queue system in blockchain for this case?

答:
```<code>contract YourContract is Ownable {

uint256 public maxAmount = 10;
uint256 public price = 10 ether;

function mint(address _to, uint256 _mintAmount) public payable {
    // you can add more logic
    require(_mintAmount > 0);
    // Maybe currently user has no enough fund to mint all
    // so it mints some now, will do later, depends on your contract logic
    require(_mintAmount <= maxAmount);

    // owner() is if your contract is inheriting from Ownable
    // if you set the owner on your own inside constructor, use `owner`
    // you are forcing the callee of the function to pay this amount
    if (msg.sender != owner()) {
          require(msg.value >= price * _mintAmount);
    }

    // after callee has paid, run the minting
    for (uint256 i = 1; i <= _mintAmount; i++) {
      _safeMint(_to, i);
    }
  }
}
</code>```

this is the _safeMint in ERC721

```<code> function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }
</code>```

Body:
contract YourContract is Ownable {

uint256 public maxAmount = 10;
uint256 public price = 10 ether;

function mint(address _to, uint256 _mintAmount) public payable {
    // you can add more logic
    require(_mintAmount > 0);
    // Maybe currently user has no enough fund to mint all
    // so it mints some now, will do later, depends on your contract logic
    require(_mintAmount <= maxAmount);

    // owner() is if your contract is inheriting from Ownable
    // if you set the owner on your own inside constructor, use `owner`
    // you are forcing the callee of the function to pay this amount
    if (msg.sender != owner()) {
          require(msg.value >= price * _mintAmount);
    }

    // after callee has paid, run the minting
    for (uint256 i = 1; i <= _mintAmount; i++) {
      _safeMint(_to, i);
    }
  }
}

this is the _safeMint in ERC721

 function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }


问:
My sequence of CCActions slow down after changing action type
I am creating a sequence of actions as play back to recorded gestures. If I only pan the sequence it plays at full speed. If I only rotate, it plays at full speed. If I only scale it plays at full speed. If, however, I pan then rotate, rotate plays back about half speed. If I rotate then pan, pan runs at about half speed. Here is the play function. RecordData is just an object with the time, position, rotation, scale information.

```<code>-(void) Play
{
    int count = [m_MoveTos count];
    if (count < 2)
    {
        return;
    }

    [m_Actor stopAllActions];
    [m_Actions removeAllObjects];

    RecordData* start = [m_MoveTos objectAtIndex:0];
    m_Actor.position = start.Pos;
    m_Actor.rotation = start.Rotate;
    m_Actor.scale = start.Scale;
    NSLog(@"Starting with %d nodes.", [m_MoveTos count]);
    NSLog(@"Actor Start Position:%f, %f Rotation:%f, Scale:%f", m_Actor.position.x,     m_Actor.position.y, m_Actor.rotation, m_Actor.scale);

    float lastTime = 0;
    RecordData* lastData = start;

    //Skip start
    for(int i = 1; i < count; ++i)
    {
        bool delay = true;
        RecordData* rData = [m_MoveTos objectAtIndex:i];
        float delta = rData.Time - lastTime;

        if(rData.Pos.x != lastData.Pos.x || rData.Pos.y != lastData.Pos.y)
        {
            CCAction* moveAction = [CCMoveTo actionWithDuration:delta     position:rData.Pos];
            [m_Actions addObject:moveAction];
            delay = false;
        }

        if (rData.Rotate != lastData.Rotate)
        {
            // Put this in Record data
            float degrees = rData.Rotate;
            int sign = degrees/ABS(degrees);
            degrees = ABS(degrees);
            while (degrees > 360)
            {
                degrees -= 360;
            }
            degrees *= sign;
            NSLog(@"Rotation %f", degrees);
            CCAction* rotAction = [CCRotateTo actionWithDuration:delta     angle:degrees];
            [m_Actions addObject:rotAction];
            delay = false;
        }

        if (rData.Scale != lastData.Scale)
        {
            CCAction* scaleAction = [CCScaleTo actionWithDuration:delta     scale:rData.Scale];
            [m_Actions addObject:scaleAction];
            delay = false;
        }

        if(delay)
        {
            CCActionInterval* delayTime = [CCDelayTime     actionWithDuration:delta];
            [m_Actions addObject:delayTime];
        }

        delay = true;
        lastTime = rData.Time;
    }

    if([m_Actions count] < 2)
    {
        return;
    }

    CCAction* seq = [CCSequence actionsWithArray:[m_Actions getNSArray]];
    [m_Actor runAction:seq];
}
</code>```

Is there something I'm missing?

Thanks,
Jim

答: Mixing action types seems to be the problem. I now have a different action sequence for position, rotation, and scale. It runs fine now.</p>

Body:
I am creating a sequence of actions as play back to recorded gestures. If I only pan the sequence it plays at full speed. If I only rotate, it plays at full speed. If I only scale it plays at full speed. If, however, I pan then rotate, rotate plays back about half speed. If I rotate then pan, pan runs at about half speed. Here is the play function. RecordData is just an object with the time, position, rotation, scale information.

-(void) Play
{
    int count = [m_MoveTos count];
    if (count < 2)
    {
        return;
    }

    [m_Actor stopAllActions];
    [m_Actions removeAllObjects];

    RecordData* start = [m_MoveTos objectAtIndex:0];
    m_Actor.position = start.Pos;
    m_Actor.rotation = start.Rotate;
    m_Actor.scale = start.Scale;
    NSLog(@"Starting with %d nodes.", [m_MoveTos count]);
    NSLog(@"Actor Start Position:%f, %f Rotation:%f, Scale:%f", m_Actor.position.x,     m_Actor.position.y, m_Actor.rotation, m_Actor.scale);

    float lastTime = 0;
    RecordData* lastData = start;

    //Skip start
    for(int i = 1; i < count; ++i)
    {
        bool delay = true;
        RecordData* rData = [m_MoveTos objectAtIndex:i];
        float delta = rData.Time - lastTime;

        if(rData.Pos.x != lastData.Pos.x || rData.Pos.y != lastData.Pos.y)
        {
            CCAction* moveAction = [CCMoveTo actionWithDuration:delta     position:rData.Pos];
            [m_Actions addObject:moveAction];
            delay = false;
        }

        if (rData.Rotate != lastData.Rotate)
        {
            // Put this in Record data
            float degrees = rData.Rotate;
            int sign = degrees/ABS(degrees);
            degrees = ABS(degrees);
            while (degrees > 360)
            {
                degrees -= 360;
            }
            degrees *= sign;
            NSLog(@"Rotation %f", degrees);
            CCAction* rotAction = [CCRotateTo actionWithDuration:delta     angle:degrees];
            [m_Actions addObject:rotAction];
            delay = false;
        }

        if (rData.Scale != lastData.Scale)
        {
            CCAction* scaleAction = [CCScaleTo actionWithDuration:delta     scale:rData.Scale];
            [m_Actions addObject:scaleAction];
            delay = false;
        }

        if(delay)
        {
            CCActionInterval* delayTime = [CCDelayTime     actionWithDuration:delta];
            [m_Actions addObject:delayTime];
        }

        delay = true;
        lastTime = rData.Time;
    }

    if([m_Actions count] < 2)
    {
        return;
    }

    CCAction* seq = [CCSequence actionsWithArray:[m_Actions getNSArray]];
    [m_Actor runAction:seq];
}

Is there something I'm missing?

Thanks,
Jim