问:
header location not working in my php code
i have this code,why my header location not working?
its a form of updating and editing and deleting some pages in my control panel...and i have an index.php file in the same folder of form.php...any help please?()i tryed to put the header after the editing and deleting...and still go to the form page not the index...

```<code><?php
include "../../includes/site_includes.php";
//send
if ((isset($_POST["send"])) && ($_POST["send"] == 1)) {
    $pageid = $_POST["page_id"];
    $pagetitle = $_POST["page_title"];
    $nameinmenu = $_POST["page_menu_name"];
    $nameinurl = $_POST["page_name_url"];
    $link = $_POST["page_link"];
    $picture = $_POST["page_pic"];
    $desc = $_POST["page_desc"];
    $content = $_POST["page_content"];
}
if ((isset($_POST["act"])) && ($_POST["act"] == "add")) {
    $sql = insertpage();
    if ($result = $mysqli->prepare($sql)) {
        $result->bind_param("sssssss", $pagetitle, $nameinmenu, $nameinurl, $link, $picture, $desc, $content);
        $result->execute();
        $result->store_result();
        $rows = $result->num_rows;
    }
}
////edit
if ((isset($_GET["act"])) && ($_GET["act"] == "edit")) {
    $sql = getfrompages();
    if ($result = $mysqli->prepare($sql)) {
        $rekza = $_GET["id"];
        $result->bind_param("i", $rekza);
        $result->execute();
        $result->store_result();
        $rowsZ = $result->num_rows;
    }
    if ($rowsZ > 0) {
        $row = fetch($result);
        $pageid = $row[0]["page_id"];
        $pagetitle = $row[0]["page_title"];
        $nameinmenu = $row[0]["page_menu_name"];
        $nameinurl = $row[0]["page_name_url"];
        $link = $row[0]["page_link"];
        $picture = $row[0]["page_pic"];
        $desc = $row[0]["page_desc"];
        $content = $row[0]["page_content"];
    }
}
if ((isset($_GET["act"])) && ($_GET["act"] == "delete")) {
    $thedelid = $_GET["id"];
    $sql2 = delpage();
    if ($result2 = $mysqli->prepare($sql2)) {
        $result2->bind_param("i", $thedelid);
        $result2->execute();
        $result2->store_result();
        $rowsZ2 = $result2->num_rows;
    }
}
header('location: index.php');
exit();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> pages add </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
 </head>

 <body>
<form method="post" action="">
        <table>
            <tr>
                <td style="font-weight:bold;">title</td>
                <td><input type="text" name="page_title" value="<?=$pagetitle?>" /></td>
            </tr>
            <tr>
                <td style="font-weight:bold;">name in menu</td>
                <td><input type="text" name="page_menu_name" value="<?=$nameinmenu?>" /></td>
            </tr>
            <tr>
                <td style="font-weight:bold;">name in url</td>
                <td><input type="text" name="page_name_url" value="<?=$nameinurl?>" /></td>
            </tr>
            <tr>
                <td style="font-weight:bold;">link</td>
                <td><input type="text" name="page_link" value="<?=$link?>" /></td>
            </tr>
            <tr>
                <td style="font-weight:bold;">picture</td>
                <td><input type="text" name="page_pic" value="<?=$picture?>" /></td>
            </tr>
            <tr>
                <td style="font-weight:bold;">description</td>
                <td><textarea name="page_desc"><?=$desc?></textarea></td>
            </tr>
            <tr>
                <td style="font-weight:bold;">content</td>
                <td><textarea name="page_content"><?=$content?></textarea></td>
            </tr>
            <tr>
                <td colspan="2">
                <input type="hidden" name="send" value="1" />
                <input type="hidden" name="act" value="<?=$_GET["act"]?>" />
                <input type="hidden" name="page_id" value="<?=$pageid?>" />
                <input type="submit" value="add" /></td>
            </tr>
        </table>
</form>
 </body>
</html>
</code>```

solved:
with @ Mihai Iorga code i added ob_start();

答:
Check if below are enabled </p>

<p>bz, mbstring, intl, ioncube_loader and Json extension. </p>

Body:
i have this code,why my header location not working?
its a form of updating and editing and deleting some pages in my control panel...and i have an index.php file in the same folder of form.php...any help please?()i tryed to put the header after the editing and deleting...and still go to the form page not the index...

<?php
include "../../includes/site_includes.php";
//send
if ((isset($_POST["send"])) && ($_POST["send"] == 1)) {
    $pageid = $_POST["page_id"];
    $pagetitle = $_POST["page_title"];
    $nameinmenu = $_POST["page_menu_name"];
    $nameinurl = $_POST["page_name_url"];
    $link = $_POST["page_link"];
    $picture = $_POST["page_pic"];
    $desc = $_POST["page_desc"];
    $content = $_POST["page_content"];
}
if ((isset($_POST["act"])) && ($_POST["act"] == "add")) {
    $sql = insertpage();
    if ($result = $mysqli->prepare($sql)) {
        $result->bind_param("sssssss", $pagetitle, $nameinmenu, $nameinurl, $link, $picture, $desc, $content);
        $result->execute();
        $result->store_result();
        $rows = $result->num_rows;
    }
}
////edit
if ((isset($_GET["act"])) && ($_GET["act"] == "edit")) {
    $sql = getfrompages();
    if ($result = $mysqli->prepare($sql)) {
        $rekza = $_GET["id"];
        $result->bind_param("i", $rekza);
        $result->execute();
        $result->store_result();
        $rowsZ = $result->num_rows;
    }
    if ($rowsZ > 0) {
        $row = fetch($result);
        $pageid = $row[0]["page_id"];
        $pagetitle = $row[0]["page_title"];
        $nameinmenu = $row[0]["page_menu_name"];
        $nameinurl = $row[0]["page_name_url"];
        $link = $row[0]["page_link"];
        $picture = $row[0]["page_pic"];
        $desc = $row[0]["page_desc"];
        $content = $row[0]["page_content"];
    }
}
if ((isset($_GET["act"])) && ($_GET["act"] == "delete")) {
    $thedelid = $_GET["id"];
    $sql2 = delpage();
    if ($result2 = $mysqli->prepare($sql2)) {
        $result2->bind_param("i", $thedelid);
        $result2->execute();
        $result2->store_result();
        $rowsZ2 = $result2->num_rows;
    }
}
header('location: index.php');
exit();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <title> pages add </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">

<form method="post" action="">

                title
                <input type="text" name="page_title" value="<?=$pagetitle?>" />

                name in menu
                <input type="text" name="page_menu_name" value="<?=$nameinmenu?>" />

                name in url
                <input type="text" name="page_name_url" value="<?=$nameinurl?>" />

                link
                <input type="text" name="page_link" value="<?=$link?>" />

                picture
                <input type="text" name="page_pic" value="<?=$picture?>" />

                description
                <textarea name="page_desc"><?=$desc?></textarea>

                content
                <textarea name="page_content"><?=$content?></textarea>

                <input type="hidden" name="send" value="1" />
                <input type="hidden" name="act" value="<?=$_GET["act"]?>" />
                <input type="hidden" name="page_id" value="<?=$pageid?>" />
                <input type="submit" value="add" />

</form>

solved:
with @ Mihai Iorga code i added ob_start();

Body:
Check if below are enabled

bz, mbstring, intl, ioncube_loader and Json extension.


来源: stackexchange

问:
Get date and time when photo was taken from EXIF data using PIL
I can get the EXIF data from an image using PIL, but how can I get the date and time that the photo was taken?</p>

答:
ExifTags.TAGS is a mapping from tag to tag name. You can use it to create a map of tag names to values.

On this particular picture, there are a few different "date" properties (DateTime, DateTimeOriginal, DateTimeDigitized) that could be used.

import json
from PIL import Image, ExifTags
from datetime import datetime

def main(filename):
    image_exif = Image.open(filename)._getexif()
    if image_exif:
        # Make a map with tag names
        exif = { ExifTags.TAGS[k]: v for k, v in image_exif.items() if k in ExifTags.TAGS and type(v) is not bytes }
        print(json.dumps(exif, indent=4))
        # Grab the date
        date_obj = datetime.strptime(exif['DateTimeOriginal'], '%Y:%m:%d %H:%M:%S')
        print(date_obj)
    else:
        print('Unable to get date from exif for %s' % filename)
```

<p>Output:</p>

```{
    "DateTimeOriginal": "2008:11:15 19:36:24",
    "DateTimeDigitized": "2008:11:15 19:36:24",
    "ColorSpace": 1,
    "ExifImageWidth": 3088,
    "SceneCaptureType": 0,
    "ExifImageHeight": 2320,
    "SubjectDistanceRange": 2,
    "ImageDescription": "               ",
    "Make": "Hewlett-Packard                ",
    "Model": "HP Photosmart R740             ",
    "Orientation": 1,
    "DateTime": "2008:11:15 19:36:24",
    ...
}
2008-11-15 19:36:24
```

ContentLicense: CC BY-SA 3.0

Body:
ExifTags.TAGS is a mapping from tag to tag name. You can use it to create a map of tag names to values.

On this particular picture, there are a few different "date" properties (DateTime, DateTimeOriginal, DateTimeDigitized) that could be used.

import json
from PIL import Image, ExifTags
from datetime import datetime

def main(filename):
    image_exif = Image.open(filename)._getexif()
    if image_exif:
        # Make a map with tag names
        exif = { ExifTags.TAGS[k]: v for k, v in image_exif.items() if k in ExifTags.TAGS and type(v) is not bytes }
        print(json.dumps(exif, indent=4))
        # Grab the date
        date_obj = datetime.strptime(exif['DateTimeOriginal'], '%Y:%m:%d %H:%M:%S')
        print(date_obj)
    else:
        print('Unable to get date from exif for %s' % filename)

Output:

{
    "DateTimeOriginal": "2008:11:15 19:36:24",
    "DateTimeDigitized": "2008:11:15 19:36:24",
    "ColorSpace": 1,
    "ExifImageWidth": 3088,
    "SceneCaptureType": 0,
    "ExifImageHeight": 2320,
    "SubjectDistanceRange": 2,
    "ImageDescription": "               ",
    "Make": "Hewlett-Packard                ",
    "Model": "HP Photosmart R740             ",
    "Orientation": 1,
    "DateTime": "2008:11:15 19:36:24",
    ...
}
2008-11-15 19:36:24

ContentLicense: CC BY-SA 4.0


问:
combination of normal and cartopy subplots within the same figure
I want a plot with two subplots, one larger with a map and second smaller with a scatter plot. I am using cartopy for plotting map. I determine the fraction of height by using gridspec_kw. However, due to projection constraints, it also affects the width..

This is what I get.

```<code>import matplotlib.pyplot as plt
import cartopy as ccrs
fig, ax = plt.subplots(2,1,subplot_kw=dict(projection=ccrs.crs.PlateCarree()),gridspec_kw={'height_ratios': [4, 1]})
</code>```

One possible solution would be to use subplot_kw=dict(projection=ccrs.crs.PlateCarree() only for the upper panel. But i am not able to figure out how do this. There are ways which recommend add_subplot, but that is very manual and i don't like this. Is is possible to do with plt.subplots()?

This is what I want.

答:
my suggestion would be to use gridspec to control the subplots size and fig.add_subplot instead of plt.subplots. That way you could specify the Cartopy projection only to the first subplot.

```<code>import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import cartopy.crs as ccrs
import cartopy.feature as cfeature

fig = plt.figure()
gs = fig.add_gridspec(3, 3)

ax1 = fig.add_subplot(gs[0:2, :], projection=ccrs.PlateCarree())
ax1.set_extent([-180, 180, -90, 90], crs=ccrs.PlateCarree())
ax1.coastlines(resolution='auto', color='k')
ax1.gridlines(color='lightgrey', linestyle='-', draw_labels=True)

ax2 = fig.add_subplot(gs[2, :])
ax2.plot([1, 2], [3, 4])
</code>```

Body:
I want a plot with two subplots, one larger with a map and second smaller with a scatter plot. I am using cartopy for plotting map. I determine the fraction of height by using gridspec_kw. However, due to projection constraints, it also affects the width..

This is what I get.

import matplotlib.pyplot as plt
import cartopy as ccrs
fig, ax = plt.subplots(2,1,subplot_kw=dict(projection=ccrs.crs.PlateCarree()),gridspec_kw={'height_ratios': [4, 1]})

One possible solution would be to use subplot_kw=dict(projection=ccrs.crs.PlateCarree() only for the upper panel. But i am not able to figure out how do this. There are ways which recommend add_subplot, but that is very manual and i don't like this. Is is possible to do with plt.subplots()?

This is what I want.

Body:
my suggestion would be to use gridspec to control the subplots size and fig.add_subplot instead of plt.subplots. That way you could specify the Cartopy projection only to the first subplot.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import cartopy.crs as ccrs
import cartopy.feature as cfeature

fig = plt.figure()
gs = fig.add_gridspec(3, 3)

ax1 = fig.add_subplot(gs[0:2, :], projection=ccrs.PlateCarree())
ax1.set_extent([-180, 180, -90, 90], crs=ccrs.PlateCarree())
ax1.coastlines(resolution='auto', color='k')
ax1.gridlines(color='lightgrey', linestyle='-', draw_labels=True)

ax2 = fig.add_subplot(gs[2, :])
ax2.plot([1, 2], [3, 4])


问:
Escaping inner loop and go to the outer loop after action is done
There is a code for the BigestCountries class.

It consists of 2 arrays:

```<code>private String[][] biggestCountries; - holds country name and the continent, e.g. biggestCountries[CHINA][COUNTRY_NAME] = "China"; biggestCountries[CHINA][COUNTRY_CONTINENT] = "Asia";

private int[][] countryData; - holds populations and year founded, e.g. countryData[CHINA][COUNTRY_POPULATION] = 1433783686; countryData[CHINA][COUNTRY_AGE_FOUNDED] = 1949;
</code>```

```<code>public String[] getCountriesFoundedBetween(int min, int max){
    int countriesMatched;
    countriesMatched = 0;
    String[] countriesFoundedBetween;

    if(biggestCountries == null || biggestCountries.length == 0){
         return null;
    }

    for(int i = 0; i < biggestCountries.length; i++){
        if(countryData[i][COUNTRY_AGE_FOUNDED] >= min && countryData[i][COUNTRY_AGE_FOUNDED] <= max){

            System.out.println(String.format("%d %s", countryData[i][COUNTRY_AGE_FOUNDED], biggestCountries[i][COUNTRY_NAME]));
            countriesMatched++;
        }
    }

    if(countriesMatched > 0){
        countriesFoundedBetween = new String[countriesMatched];
    } else {
        return null;
    }

    for(int i = 0; i < biggestCountries.length; i++) { // outer loop for countries array length of NUMBER_OF_COUNTRIES

        String countryMatched = null;
        System.out.println("biggestCountries[i] " + biggestCountries[i][COUNTRY_NAME]);

        if(countryData[i][COUNTRY_AGE_FOUNDED] >= min && countryData[i][COUNTRY_AGE_FOUNDED] <= max){
            for(int j = 0; j < countriesFoundedBetween.length; j++){ // how to escape inner loop?

                countryMatched =  biggestCountries[i][COUNTRY_NAME];
                countriesFoundedBetween[j] = countryMatched;
                System.out.println("countriesFoundedBetween: " + countriesFoundedBetween[j] + "; biggestCountries[i][COUNTRY_NAME]: " + biggestCountries[i][COUNTRY_NAME]);

            }
        }
    }

    return countriesFoundedBetween;
}
</code>```

Unfortunately, It cannot escape from the inner loop and re-writes the matched country to all rows of the newly-generated array.

答:
The method getCountriesFoundedBetween() can be implemented differently, without the need for nested loops, as follows.

private static String[] getCountriesFoundedBetween(int min, int max) {
    if (max < min) {
        throw new IllegalArgumentException("'max' less than 'min'");
    }
    String[] countriesFoundedBetween;
    int countriesMatched = 0;
    int[] indexes = new int[biggestCountries.length];
    if (biggestCountries != null && biggestCountries.length > 0) {
        for (int i = 0; i < biggestCountries.length; i++) {
            if(countryData[i][COUNTRY_AGE_FOUNDED] >= min &&
               countryData[i][COUNTRY_AGE_FOUNDED] <= max) {
                indexes[countriesMatched++] = i;
            }
        }
        countriesFoundedBetween = new String[countriesMatched];
        for (int i = 0; i < countriesMatched; i++) {
            countriesFoundedBetween[i] = biggestCountries[indexes[i]][COUNTRY_NAME];
        }
    }
    else {
        countriesFoundedBetween = new String[0];
    }
    return countriesFoundedBetween;
}
```

<p>The above code also returns an empty array rather than null which is preferable for methods that return arrays.</p>

<p>Here is a complete example using population to determine the biggest countries.</p>

<pre class="lang-java prettyprint-override"><code>public class Countrys {
    private static final int  CHINA      = 0;
    private static final int  INDIA      = 1;
    private static final int  U_S_A      = 2;
    private static final int  INDONESIA  = 3;
    private static final int  PAKISTAN   = 4;
    private static final int  BRAZIL     = 5;
    private static final int  NIGERIA    = 6;
    private static final int  BANGLADESH = 7;
    private static final int  RUSSIA     = 8;
    private static final int  MEXICO     = 9;

    private static final int  COUNTRY_NAME = 0;
    private static final int  COUNTRY_CONTINENT = 1;
    private static final int  COUNTRY_POPULATION = 0;
    private static final int  COUNTRY_AGE_FOUNDED = 1;

    private static int[][] countryData = new int[][]{{1_427_647_786, 1949},
                                                     {1_352_642_280, 1950},
                                                     {  328_239_523, 1776},
                                                     {  273_523_615, 1945},
                                                     {  220_892_340, 1947},
                                                     {  210_147_125, 1889},
                                                     {  206_139_589, 1960},
                                                     {  164_689_383, 1971},
                                                     {  144_384_244, 1991},
                                                     {  128_932_753, 1810}};
    private static String[][] biggestCountries = new String[][]{{"China"     , "Asia"},
                                                                {"India"     , "Asia"},
                                                                {"U.S.A."    , "North America"},
                                                                {"Indonesia" , "Asia"},
                                                                {"Pakistan"  , "Asia"},
                                                                {"Brazil"    , "South America"},
                                                                {"Nigeria"   , "Africa"},
                                                                {"Bangladesh", "Asia"},
                                                                {"Russia"    , "Europe"},
                                                                {"Mexico"    , "North America"}};

    private static String[] getCountriesFoundedBetween(int min, int max) {
        if (max < min) {
            throw new IllegalArgumentException("'max' less than 'min'");
        }
        String[] countriesFoundedBetween;
        int countriesMatched = 0;
        int[] indexes = new int[biggestCountries.length];
        if (biggestCountries != null && biggestCountries.length > 0) {
            for (int i = 0; i < biggestCountries.length; i++) {
                if(countryData[i][COUNTRY_AGE_FOUNDED] >= min &&
                   countryData[i][COUNTRY_AGE_FOUNDED] <= max) {
                    indexes[countriesMatched++] = i;
                }
            }
            countriesFoundedBetween = new String[countriesMatched];
            for (int i = 0; i < countriesMatched; i++) {
                countriesFoundedBetween[i] = biggestCountries[indexes[i]][COUNTRY_NAME];
            }
        }
        else {
            countriesFoundedBetween = new String[0];
        }
        return countriesFoundedBetween;
    }

    public static void main(String[] args) {
        String[] result = getCountriesFoundedBetween(1950, 1980);
        System.out.println(Arrays.toString(result));
    }
}
</code>```

Running the above code produces the following output:

```<code>[India, Nigeria, Bangladesh]
</code>```

Body:
There is a code for the BigestCountries class.

It consists of 2 arrays:

private String[][] biggestCountries; - holds country name and the continent, e.g. biggestCountries[CHINA][COUNTRY_NAME] = "China"; biggestCountries[CHINA][COUNTRY_CONTINENT] = "Asia";

private int[][] countryData; - holds populations and year founded, e.g. countryData[CHINA][COUNTRY_POPULATION] = 1433783686; countryData[CHINA][COUNTRY_AGE_FOUNDED] = 1949;

public String[] getCountriesFoundedBetween(int min, int max){
    int countriesMatched;
    countriesMatched = 0;
    String[] countriesFoundedBetween;

    if(biggestCountries == null || biggestCountries.length == 0){
         return null;
    }

    for(int i = 0; i < biggestCountries.length; i++){
        if(countryData[i][COUNTRY_AGE_FOUNDED] >= min && countryData[i][COUNTRY_AGE_FOUNDED] <= max){

            System.out.println(String.format("%d %s", countryData[i][COUNTRY_AGE_FOUNDED], biggestCountries[i][COUNTRY_NAME]));
            countriesMatched++;
        }
    }

    if(countriesMatched > 0){
        countriesFoundedBetween = new String[countriesMatched];
    } else {
        return null;
    }

    for(int i = 0; i < biggestCountries.length; i++) { // outer loop for countries array length of NUMBER_OF_COUNTRIES

        String countryMatched = null;
        System.out.println("biggestCountries[i] " + biggestCountries[i][COUNTRY_NAME]);

        if(countryData[i][COUNTRY_AGE_FOUNDED] >= min && countryData[i][COUNTRY_AGE_FOUNDED] <= max){
            for(int j = 0; j < countriesFoundedBetween.length; j++){ // how to escape inner loop?

                countryMatched =  biggestCountries[i][COUNTRY_NAME];
                countriesFoundedBetween[j] = countryMatched;
                System.out.println("countriesFoundedBetween: " + countriesFoundedBetween[j] + "; biggestCountries[i][COUNTRY_NAME]: " + biggestCountries[i][COUNTRY_NAME]);

            }
        }
    }

    return countriesFoundedBetween;
}

Unfortunately, It cannot escape from the inner loop and re-writes the matched country to all rows of the newly-generated array.

Body:
The method getCountriesFoundedBetween() can be implemented differently, without the need for nested loops, as follows.

private static String[] getCountriesFoundedBetween(int min, int max) {
    if (max < min) {
        throw new IllegalArgumentException("'max' less than 'min'");
    }
    String[] countriesFoundedBetween;
    int countriesMatched = 0;
    int[] indexes = new int[biggestCountries.length];
    if (biggestCountries != null && biggestCountries.length > 0) {
        for (int i = 0; i < biggestCountries.length; i++) {
            if(countryData[i][COUNTRY_AGE_FOUNDED] >= min &&
               countryData[i][COUNTRY_AGE_FOUNDED] <= max) {
                indexes[countriesMatched++] = i;
            }
        }
        countriesFoundedBetween = new String[countriesMatched];
        for (int i = 0; i < countriesMatched; i++) {
            countriesFoundedBetween[i] = biggestCountries[indexes[i]][COUNTRY_NAME];
        }
    }
    else {
        countriesFoundedBetween = new String[0];
    }
    return countriesFoundedBetween;
}

The above code also returns an empty array rather than null which is preferable for methods that return arrays.

Here is a complete example using population to determine the biggest countries.

public class Countrys {
    private static final int  CHINA      = 0;
    private static final int  INDIA      = 1;
    private static final int  U_S_A      = 2;
    private static final int  INDONESIA  = 3;
    private static final int  PAKISTAN   = 4;
    private static final int  BRAZIL     = 5;
    private static final int  NIGERIA    = 6;
    private static final int  BANGLADESH = 7;
    private static final int  RUSSIA     = 8;
    private static final int  MEXICO     = 9;

    private static final int  COUNTRY_NAME = 0;
    private static final int  COUNTRY_CONTINENT = 1;
    private static final int  COUNTRY_POPULATION = 0;
    private static final int  COUNTRY_AGE_FOUNDED = 1;

    private static int[][] countryData = new int[][]{{1_427_647_786, 1949},
                                                     {1_352_642_280, 1950},
                                                     {  328_239_523, 1776},
                                                     {  273_523_615, 1945},
                                                     {  220_892_340, 1947},
                                                     {  210_147_125, 1889},
                                                     {  206_139_589, 1960},
                                                     {  164_689_383, 1971},
                                                     {  144_384_244, 1991},
                                                     {  128_932_753, 1810}};
    private static String[][] biggestCountries = new String[][]{{"China"     , "Asia"},
                                                                {"India"     , "Asia"},
                                                                {"U.S.A."    , "North America"},
                                                                {"Indonesia" , "Asia"},
                                                                {"Pakistan"  , "Asia"},
                                                                {"Brazil"    , "South America"},
                                                                {"Nigeria"   , "Africa"},
                                                                {"Bangladesh", "Asia"},
                                                                {"Russia"    , "Europe"},
                                                                {"Mexico"    , "North America"}};

    private static String[] getCountriesFoundedBetween(int min, int max) {
        if (max < min) {
            throw new IllegalArgumentException("'max' less than 'min'");
        }
        String[] countriesFoundedBetween;
        int countriesMatched = 0;
        int[] indexes = new int[biggestCountries.length];
        if (biggestCountries != null && biggestCountries.length > 0) {
            for (int i = 0; i < biggestCountries.length; i++) {
                if(countryData[i][COUNTRY_AGE_FOUNDED] >= min &&
                   countryData[i][COUNTRY_AGE_FOUNDED] <= max) {
                    indexes[countriesMatched++] = i;
                }
            }
            countriesFoundedBetween = new String[countriesMatched];
            for (int i = 0; i < countriesMatched; i++) {
                countriesFoundedBetween[i] = biggestCountries[indexes[i]][COUNTRY_NAME];
            }
        }
        else {
            countriesFoundedBetween = new String[0];
        }
        return countriesFoundedBetween;
    }

    public static void main(String[] args) {
        String[] result = getCountriesFoundedBetween(1950, 1980);
        System.out.println(Arrays.toString(result));
    }
}

Running the above code produces the following output:

[India, Nigeria, Bangladesh]


问:
Warning: mysqli_stmt_init() expects parameter 1 to be mysqli, null given
I'm making a chat feature for a site and am not good with PHP:

```<code><?php

if (isset($_POST['send'])) {
    require 'database.php';

    $input = $_POST['input'];
} else {
    $sql = "INSERT INTO chatsys (chat) VALUES (?)";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)) {
        header("index.html?error=sqlerror");
        exit();
    } else {
        mysqli_stmt_bind_param($stmt, "sss", $input);
        mysqli_stmt_execute($stmt);
        header("index.html?request=success");
        exit();
    }
}
{
    mysqli_stmt_close($stmt);
    mysqli_close($conn);
}
</code>```

And database code:

```<code><?php

$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "chatsys";

$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);

if (!$conn) {
    die("Connection failed: ".mysqli_connect_error());
}
?>
</code>```

This results in:

Notice: Undefined variable: conn in C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php on line 11

  Warning: mysqli_stmt_init() expects parameter 1 to be mysqli, null given in C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php on line 11

  Warning: mysqli_stmt_prepare() expects parameter 1 to be mysqli_stmt, null given in C:\Users\john doe\Desktop\server\htdocs\php\message\chat.php on line 12

What have I done wrong?

答:
First of all, don't blame PHP because it is a powerful and easy to use server side language, try to get close and you will love it.

Second you have unneccessary if else, and also passing extra parameters to bind param, while you just have only one to pass.

```<code><?php

if (isset($_POST['send'])) {
    require 'database.php';
    $input = $_POST['input'];
    $sql = "INSERT INTO chatsys (chat) VALUES (?)";
    $stmt = mysqli_stmt_init($conn);

    if (!mysqli_stmt_prepare($stmt, $sql)) {
        header("index.html?error=sqlerror");
        exit();
    }
    //No need to else here because if error happens you get back and exit.
    mysqli_stmt_bind_param($stmt, "s", $input);
    mysqli_stmt_execute($stmt);
    header("index.html?request=success");

    mysqli_stmt_close($stmt);
    mysqli_close($conn);
}
</code>```

Body:
I'm making a chat feature for a site and am not good with PHP:

<?php

if (isset($_POST['send'])) {
    require 'database.php';

    $input = $_POST['input'];
} else {
    $sql = "INSERT INTO chatsys (chat) VALUES (?)";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)) {
        header("index.html?error=sqlerror");
        exit();
    } else {
        mysqli_stmt_bind_param($stmt, "sss", $input);
        mysqli_stmt_execute($stmt);
        header("index.html?request=success");
        exit();
    }
}
{
    mysqli_stmt_close($stmt);
    mysqli_close($conn);
}

And database code:

<?php

$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "chatsys";

$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);

if (!$conn) {
    die("Connection failed: ".mysqli_connect_error());
}
?>

This results in:

Notice: Undefined variable: conn in C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php on line 11

  Warning: mysqli_stmt_init() expects parameter 1 to be mysqli, null given in C:\Users\John Doe\Desktop\server\htdocs\php\message\chat.php on line 11

  Warning: mysqli_stmt_prepare() expects parameter 1 to be mysqli_stmt, null given in C:\Users\john doe\Desktop\server\htdocs\php\message\chat.php on line 12

What have I done wrong?

Body:
First of all, don't blame PHP because it is a powerful and easy to use server side language, try to get close and you will love it.

Second you have unneccessary if else, and also passing extra parameters to bind param, while you just have only one to pass.

<?php

if (isset($_POST['send'])) {
    require 'database.php';
    $input = $_POST['input'];
    $sql = "INSERT INTO chatsys (chat) VALUES (?)";
    $stmt = mysqli_stmt_init($conn);

    if (!mysqli_stmt_prepare($stmt, $sql)) {
        header("index.html?error=sqlerror");
        exit();
    }
    //No need to else here because if error happens you get back and exit.
    mysqli_stmt_bind_param($stmt, "s", $input);
    mysqli_stmt_execute($stmt);
    header("index.html?request=success");

    mysqli_stmt_close($stmt);
    mysqli_close($conn);
}


问:
How to see C# Nuget Package's source code on Visual Studio Code?
Is there any way to see a Nuget Package's source code when we choose "Go to Definition" (or F12 or CRTL+click)?
At this time, I click (CRTL+click) on some class from Nuget Package in my code and the vscode shows me an assembly summary [metadata], where I can see only docs and methods signature.
I'd like to see all the source code from this class.
Is there some extension I need to install or I misunderstood some config?</p>

答: JetBrains Resharper provides this functionality by decompiling source in Visual Studio. I am not aware of integrated extension for VSCode.</p>


问:
Make datetime.date column in python from other year,month and day column
Im trying to make a datetime.date type column by combining the year,month and day columns.

This is what i've tried.

```<code>        df['date']= date(df['year'],df['month'],df['day'])
</code>```

It's giving me an error:

```<code>TypeError: cannot convert the series to <class 'int'>
</code>```

I tried parsing by using int() but its giving me the same error.

答:
You can convert it to a string date-time, then use to_datetime to get the series you want.
Think x[1] as month, x[0] as day, and x[2] as year.</p>

```<code>df = pd.DataFrame([[2,1,2000],[2,3,2003]])
df['new'] = pd.to_datetime(df.apply(lambda x: f"{x[1]}-{x[0]}-{x[2]}", axis=1))
</code>```

Body:
Im trying to make a datetime.date type column by combining the year,month and day columns.

This is what i've tried.

        df['date']= date(df['year'],df['month'],df['day'])

It's giving me an error:

TypeError: cannot convert the series to <class 'int'>

I tried parsing by using int() but its giving me the same error.

Body:
You can convert it to a string date-time, then use to_datetime to get the series you want.
Think x[1] as month, x[0] as day, and x[2] as year.

df = pd.DataFrame([[2,1,2000],[2,3,2003]])
df['new'] = pd.to_datetime(df.apply(lambda x: f"{x[1]}-{x[0]}-{x[2]}", axis=1))


问:
Sorting image name files in Matlab?
I have two different types of dicom(medical imaging files) in the same folder. I want to sort them into two different arrays one for the SE006 and the other for the SE014.

```<code>    MR-ST001-SE006-0001.dcm... MR-ST001-SE006-0021.dcm
    MR-ST001-SE014-0001.dcm... MR-ST001-SE014-0013.dcm
</code>```

I have been using something like this code below but it is wrong I think I have some syntax errors.

```<code>  if image == 'MR-ST001-SE006-%4.4.dcm'
      SE006(end+1) = image
  if image == 'MR-ST001-SE014-%4.4.dcm'
      SE014(end+1) = image
</code>```

Anyone have any tips to help improve this so it works?

答:
Using a combination of strfind() and isempty() with an if/else if block should sort them.

```<code> if ~isempty(strfind(yourstr,'SE006'))
     #add it to your list
 end
</code>```

Title: Sorting image name files in Matlab?

Body:
I have two different types of dicom(medical imaging files) in the same folder. I want to sort them into two different arrays one for the SE006 and the other for the SE014.

    MR-ST001-SE006-0001.dcm... MR-ST001-SE006-0021.dcm
    MR-ST001-SE014-0001.dcm... MR-ST001-SE014-0013.dcm

I have been using something like this code below but it is wrong I think I have some syntax errors.

  if image == 'MR-ST001-SE006-%4.4.dcm'
      SE006(end+1) = image
  if image == 'MR-ST001-SE014-%4.4.dcm'
      SE014(end+1) = image

Anyone have any tips to help improve this so it works?

Body:
Using a combination of strfind() and isempty() with an if/else if block should sort them.

 if ~isempty(strfind(yourstr,'SE006'))
     #add it to your list
 end


问:
How to change the InAppnitification's coming in direction?
Currently when Microsoft.Toolkit.Uwp.UI.Controls.InAppnitification shows up, it always comes from botttom to top. But it's weird when I set the InAppnitification's VerticalAlignment to Top.

So is there any example to redefine it's coming in direction.

Also, I have post a feature request on Github. If you want it, please vote.

答:
Based on the document of InAppnitification, there are two properties: HorizontalOffset and VerticalOffset. They controls the horizontal and vertical offset of the popup animation, you can change them to redefine the notification's popup direction. For example:

From Top to Bottom:

```<code><controls:InAppNotification x:Name="ExampleInAppNotification"
                            Content="This is a test message."
                            ShowDismissButton="True"
                            AnimationDuration="00:00:00.1000000"
                            VerticalOffset="-100"
                            HorizontalOffset="0"
                            StackMode="Replace" />
</code>```

From Left to Right:

```<code><controls:InAppNotification x:Name="ExampleInAppNotification"
                            Content="This is a test message."
                            ShowDismissButton="True"
                            AnimationDuration="00:00:00.1000000"
                            VerticalOffset="0"
                            HorizontalOffset="-100"
                            StackMode="Replace" />
</code>```

From Right to Left:

```<code><controls:InAppNotification x:Name="ExampleInAppNotification"
                            Content="This is a test message."
                            ShowDismissButton="True"
                            AnimationDuration="00:00:00.1000000"
                            VerticalOffset="0"
                            HorizontalOffset="100"
                            StackMode="Replace" />
</code>```

Body:
Based on the document of InAppnitification, there are two properties: HorizontalOffset and VerticalOffset. They controls the horizontal and vertical offset of the popup animation, you can change them to redefine the notification's popup direction. For example:

From Top to Bottom:

<controls:InAppNotification x:Name="ExampleInAppNotification"
                            Content="This is a test message."
                            ShowDismissButton="True"
                            AnimationDuration="00:00:00.1000000"
                            VerticalOffset="-100"
                            HorizontalOffset="0"
                            StackMode="Replace" />

From Left to Right:

<controls:InAppNotification x:Name="ExampleInAppNotification"
                            Content="This is a test message."
                            ShowDismissButton="True"
                            AnimationDuration="00:00:00.1000000"
                            VerticalOffset="0"
                            HorizontalOffset="-100"
                            StackMode="Replace" />

From Right to Left:

<controls:InAppNotification x:Name="ExampleInAppNotification"
                            Content="This is a test message."
                            ShowDismissButton="True"
                            AnimationDuration="00:00:00.1000000"
                            VerticalOffset="0"
                            HorizontalOffset="100"
                            StackMode="Replace" />


问:
get current gps location with Xamarin return 0
I try to get my current location on Android with Xamarin. I use a google Map and this following code :

```<code>using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Maps;

namespace WorldHerp
{
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        private double _latitude = 0.0;
        private double _longitude = 0.0;

        public MainPage()
        {
            InitializeComponent();
            Task.Run(async () => { await GetCurrentLocationAsync(); });
            MapView.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(_latitude, _longitude), Distance.FromKilometers(1)).WithZoom(20));
        }

        private async Task GetCurrentLocationAsync()
        {
            try
            {
                var location = await Geolocation.GetLocationAsync();

                if (location != null)
                {
                    _latitude = location.Latitude;
                    _longitude = location.Longitude;
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                await DisplayAlert("Faild", fnsEx.Message, "OK");
            }
            catch (PermissionException pEx)
            {
                await DisplayAlert("Faild", pEx.Message, "OK");
            }
            catch (Exception ex)
            {
                await DisplayAlert("Faild", ex.Message, "OK");
            }
        }
    }
}
</code>```

They just return 0 for my _latitude/_longitude variable. With a debug on my try {} it's like if he never go inside, but without show me any error.

Have you any idea?

Thanks per advance

答:
You need to have a async non empty method to await the result.

>

```<code>using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Maps;

namespace WorldHerp
{
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        protected async override void OnAppearing()
        {
            var position = await GetCurrentLocationAsync();
            MapView.MoveToRegion(MapSpan.FromCenterAndRadius((position != null ?
                                                             position :
                                                             new Position(0.0, 0.0)),
                                                             Distance.FromKilometers(1)).WithZoom(20));
            base.OnAppearing();
        }

        private async Task<Xamarin.Essentials.Location> GetCurrentLocationAsync()
        {
            try
            {
                return await Geolocation.GetLocationAsync();
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                await DisplayAlert("Faild", fnsEx.Message, "OK");
            }
            catch (PermissionException pEx)
            {
                await DisplayAlert("Faild", pEx.Message, "OK");
            }
            catch (Exception ex)
            {
                await DisplayAlert("Faild", ex.Message, "OK");
            }
        }
    }
}
</code>```

Body:
I try to get my current location on Android with Xamarin. I use a google Map and this following code :

using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Maps;

namespace WorldHerp
{
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        private double _latitude = 0.0;
        private double _longitude = 0.0;

        public MainPage()
        {
            InitializeComponent();
            Task.Run(async () => { await GetCurrentLocationAsync(); });
            MapView.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(_latitude, _longitude), Distance.FromKilometers(1)).WithZoom(20));
        }

        private async Task GetCurrentLocationAsync()
        {
            try
            {
                var location = await Geolocation.GetLocationAsync();

                if (location != null)
                {
                    _latitude = location.Latitude;
                    _longitude = location.Longitude;
                }
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                await DisplayAlert("Faild", fnsEx.Message, "OK");
            }
            catch (PermissionException pEx)
            {
                await DisplayAlert("Faild", pEx.Message, "OK");
            }
            catch (Exception ex)
            {
                await DisplayAlert("Faild", ex.Message, "OK");
            }
        }
    }
}

They just return 0 for my _latitude/_longitude variable. With a debug on my try {} it's like if he never go inside, but without show me any error.

Have you any idea?

Thanks per advance

Body:
You need to have a async non empty method to await the result.

>

using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Maps;

namespace WorldHerp
{
    [DesignTimeVisible(false)]
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        protected async override void OnAppearing()
        {
            var position = await GetCurrentLocationAsync();
            MapView.MoveToRegion(MapSpan.FromCenterAndRadius((position != null ?
                                                             position :
                                                             new Position(0.0, 0.0)),
                                                             Distance.FromKilometers(1)).WithZoom(20));
            base.OnAppearing();
        }

        private async Task<Xamarin.Essentials.Location> GetCurrentLocationAsync()
        {
            try
            {
                return await Geolocation.GetLocationAsync();
            }
            catch (FeatureNotSupportedException fnsEx)
            {
                await DisplayAlert("Faild", fnsEx.Message, "OK");
            }
            catch (PermissionException pEx)
            {
                await DisplayAlert("Faild", pEx.Message, "OK");
            }
            catch (Exception ex)
            {
                await DisplayAlert("Faild", ex.Message, "OK");
            }
        }
    }
}


问:
Should we put a timer on server or mobile?
I am working on both server side (beginning) and mobile side. There is an interesting thing but I am lack of experience to make a decision. I am appreciated any helps from you guys.

```<code>I have to send an email after 50 minutes
</code>```

1/ If we have a timer for each email on server, then 1000 users, 1000 timers?

2/ If we handle it on mobile, there is a case that everything of the app is killed by OS before sending email.

The question is: server and mobile, which one is better?

Please let me know your solution. Thank you in advanced!

答:
Use a queue system on the server. Create a queue for sending emails.

When you want to send an email just push it in the queue, with time or DateTime in your case. Then run a Cron Job to check, process and send the email.

Also, make sure to implement the retry functionality, so that even email sending was failed the Cron will take the job again and try to send for a number of times.

These Links will Help:

Managing Cron Jobs in PHP

Setting Up Cron in Ubuntu

Setting up Cron using cPanel

If you are confused about how to setup the Timings of Cron, checkout this website:

CronTab Guru

Body:
I am working on both server side (beginning) and mobile side. There is an interesting thing but I am lack of experience to make a decision. I am appreciated any helps from you guys.

I have to send an email after 50 minutes

1/ If we have a timer for each email on server, then 1000 users, 1000 timers?

2/ If we handle it on mobile, there is a case that everything of the app is killed by OS before sending email.

The question is: server and mobile, which one is better?

Please let me know your solution. Thank you in advanced!


问:
How to limit the number of Cloud Function triggers from Firebase Realtime Database
I created a function that is triggered when a new data created in Realtime Database. The problem is that the activity in the nodes could be very frequent, so the function could be called every second. Is there a way to limit the number of triggers in a period? For example, when 100 new data consecutively created in a minute, the function will be triggered only once and only by the last data created and other 99 will never be processed. I know there is a way to schedule the function to call in every minute instead of triggering it for new data in the db, but this is not efficient if some nodes have very rare activity while some have very frequent.</p>

答: There is no way to implement what you're describing.  Cloud Functions will always trigger for every matching event from the source that it tracks.  There is no way to suspend or suppress events.  If this is going to be too frequent (by whatever measure you use for frequency), you will need to change the way you write the database, or some up with some other solution.</p>


问:
Hive query: select a column based on the condition another columns values match some specific values, then create the match result as a new column
I have to some query and creat columns operations in HiveQL.

For example,

```<code>app      col1

app1     anybody love me?
app2     I hate u
app3     this hat is good
app4     I don't like this one
app5     oh my god
app6     damn you.
app7     such nice girl
app8     xxxxx
app9     pretty prefect
app10    don't love me.
app11    xxx anybody?
</code>```

I want to match a keyword list like ['anybody', 'love', 'you', 'xxx', 'don't'] and select the matched keyword result as a new column, named keyword as follows:

```<code>app      keyword

app1     anybody, love
app4     I don't like this one
app6     damn you.
app8     xxx
app10    don't, love
app11    xxx
</code>```

It seems that I have to use nested query.

The logic is kind of like selecting the matched result rows and setting a matched results which should be saved in a list or something like this as a new column.

But I am not familiar enough with the HiveQL.

Could anyone help me?

Thanks in advances.

答:
You could turn the list of words to a table and join it with your table using pattern matching:

```<code>select t.app, k.keyword
from  mytable t
inner join (values ('anybody'), ('you'), ('xxx'), ('don''t')) as k(keyword)
    on t.col1 like conca('%', k.keyword, '%')
</code>```

Note that this will duplicate app if more than one keyword matches on a phrase. You did not specify how you want to handle this use case.

In hive, you can also phrase this as:

```<code>select t.app, k.keyword
from  mytable t
inner join table(values 'anybody', 'you', 'xxx', 'don''t') as k(keyword)
    on t.col1 like conca('%', k.keyword, '%')
</code>```

Body:
I have to some query and creat columns operations in HiveQL.

For example,

app      col1

app1     anybody love me?
app2     I hate u
app3     this hat is good
app4     I don't like this one
app5     oh my god
app6     damn you.
app7     such nice girl
app8     xxxxx
app9     pretty prefect
app10    don't love me.
app11    xxx anybody?

I want to match a keyword list like ['anybody', 'love', 'you', 'xxx', 'don't'] and select the matched keyword result as a new column, named keyword as follows:

app      keyword

app1     anybody, love
app4     I don't like this one
app6     damn you.
app8     xxx
app10    don't, love
app11    xxx

It seems that I have to use nested query.

The logic is kind of like selecting the matched result rows and setting a matched results which should be saved in a list or something like this as a new column.

But I am not familiar enough with the HiveQL.

Could anyone help me?

Thanks in advances.

Body:
You could turn the list of words to a table and join it with your table using pattern matching:

select t.app, k.keyword
from  mytable t
inner join (values ('anybody'), ('you'), ('xxx'), ('don''t')) as k(keyword)
    on t.col1 like conca('%', k.keyword, '%')

Note that this will duplicate app if more than one keyword matches on a phrase. You did not specify how you want to handle this use case.

In hive, you can also phrase this as:

select t.app, k.keyword
from  mytable t
inner join table(values 'anybody', 'you', 'xxx', 'don''t') as k(keyword)
    on t.col1 like conca('%', k.keyword, '%')


问:
Current Way to Get User Input in Zig
I'm following this blog post on 'comptime' in Zig.

The following line no longer compiles in Zig 0.6.0.

```<code>const user_input = try io.readLineSlice(buf[0..]);
</code>```

Below is the full function:

```<code>fn ask_user() !i64 {
    var buf: [10]u8 = undefined;
    std.debug.warn("A number please: ");
    const user_input = try io.readLineSlice(buf[0..]);
    return fmt.parseInt(i64, user_input, 10);
}
</code>```

What is the equivalent in the current version (of getting user input)?

答:
You can use the method readUntilDelimiterOrEof of stdin instead:

const stdin = std.io.getStdIn().reader();
```
<pre class="lang-rust prettyprint-override"><code>pub fn readUntilDelimiterOrEof(self: @TypeOf(stdin), buf: []u8, delimiter: u8) !?[]u8
</code>```

So, the code can be:

fn ask_user() !i64 {
    const stdin = std.io.getStdIn().reader();
    const stdout = std.io.getStdOut().writer();

    var buf: [10]u8 = undefined;

    try stdout.print("A number please: ", .{});

    if (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |user_input| {
        return std.fmt.parseInt(i64, user_input, 10);
    } else {
        return @as(i64, 0);
    }
}
```

See also: Zig 0.7.0 documentation.

Title: Current Way to Get User Input in Zig

Body:
I'm following this blog post on 'comptime' in Zig.

The following line no longer compiles in Zig 0.6.0.

const user_input = try io.readLineSlice(buf[0..]);

Below is the full function:

fn ask_user() !i64 {
    var buf: [10]u8 = undefined;
    std.debug.warn("A number please: ");
    const user_input = try io.readLineSlice(buf[0..]);
    return fmt.parseInt(i64, user_input, 10);
}

What is the equivalent in the current version (of getting user input)?

Body:
You can use the method readUntilDelimiterOrEof of stdin instead:

const stdin = std.io.getStdIn().reader();

pub fn readUntilDelimiterOrEof(self: @TypeOf(stdin), buf: []u8, delimiter: u8) !?[]u8

So, the code can be:

fn ask_user() !i64 {
    const stdin = std.io.getStdIn().reader();
    const stdout = std.io.getStdOut().writer();

    var buf: [10]u8 = undefined;

    try stdout.print("A number please: ", .{});

    if (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |user_input| {
        return std.fmt.parseInt(i64, user_input, 10);
    } else {
        return @as(i64, 0);
    }
}

See also: Zig 0.7.0 documentation.


问:
cucumber - generating wrong missing steps
I am using cucumber and TestNG in my automation code

.feature file

```<code>Scenario Outline: Enter valid Location Setup
    When : I enter the Restaurant ID as “<setup_RestaurantID>“
    Examples:
        | setup_StoreID | setup_RestaurantID |
        | test          | 1234               |
</code>```

When I run automation script it is generating blow missing step

```<code>@When("^: I enter the Restaurant ID as “(\\d+)“$")
public void i_enter_the_Restaurant_ID_as(int arg1) throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}
</code>```

But cucumber supposed to generate missing step as follow

```<code>@When("^: I enter the Restaurant ID as \"([^\"]*)\"$")
public void i_enter_the_Restaurant_ID_as(String arg1) throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}
</code>```

Other settings:

monochrome = true

Maven dependencies:

```<code><dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-testng</artifactId>
<version>1.2.5</version>
</dependency>

<dependency>
<groupId>net.masterthought</groupId>
<artifactId>cucumber-reporting</artifactId>
<version>5.2.1</version>
</dependency>
</code>```

Can you help me to fix it? Thanks in advance.

答:
Answer: Replaced inverted commas(“) with double quotes(") for parameter.

After spending couple of hours observed that the parameter surrounded with double inverted commas instead double quotes. Actually I had received feature file from BA and he has used apple notes(smart quotes enabled) to write .feature file which  converts double quote to inverted comma.

```<code>When : I enter the Restaurant ID as "<setup_RestaurantID>"
</code>```

Body:
I am using cucumber and TestNG in my automation code

.feature file

Scenario Outline: Enter valid Location Setup
    When : I enter the Restaurant ID as “<setup_RestaurantID>“
    Examples:
        | setup_StoreID | setup_RestaurantID |
        | test          | 1234               |

When I run automation script it is generating blow missing step

@When("^: I enter the Restaurant ID as “(\\d+)“$")
public void i_enter_the_Restaurant_ID_as(int arg1) throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

But cucumber supposed to generate missing step as follow

@When("^: I enter the Restaurant ID as \"([^\"]*)\"$")
public void i_enter_the_Restaurant_ID_as(String arg1) throws Throwable {
    // Write code here that turns the phrase above into concrete actions
    throw new PendingException();
}

Other settings:

monochrome = true

Maven dependencies:

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-java</artifactId>
<version>1.2.5</version>
<scope>test</scope>
</dependency>

<dependency>
<groupId>info.cukes</groupId>
<artifactId>cucumber-testng</artifactId>
<version>1.2.5</version>
</dependency>

<dependency>
<groupId>net.masterthought</groupId>
<artifactId>cucumber-reporting</artifactId>
<version>5.2.1</version>
</dependency>

Can you help me to fix it? Thanks in advance.

Body:
Answer: Replaced inverted commas(“) with double quotes(") for parameter.

After spending couple of hours observed that the parameter surrounded with double inverted commas instead double quotes. Actually I had received feature file from BA and he has used apple notes(smart quotes enabled) to write .feature file which  converts double quote to inverted comma.

When : I enter the Restaurant ID as "<setup_RestaurantID>"


答:
For the distribution line, you can make your own line using hist and dnorm. Then you can add them using add_marker (for some reason I could not get it to work with add_lines or add_trace).

For the color of the points, you need to set the color to silver within the first add_boxplot which you have boxpoints. You had it set to silver in the second one (which does not have any points plotted), while the first one was set to black.

library (plotly)

h <- hist(df$lmean, breaks = seq(18,25.5,0.5), density = 10, col = "lightgray")
xfit <- seq(min(df$lmean), max(df$lmean), length = 40)
yfit <- dnorm(xfit, mean = mean(df$lmean), sd = sd(df$lmean))

plot_ly (type = 'box') %>%
add_boxplot (y = df$lmean, jitter = 0.5, pointpos = -1.8, boxpoints = 'all',
               marker = list(color = 'silver'), line = list(color = 'black'), name = 1) %>%
add_boxplot (y = list(20.25453, 21.32184, 21.56097, 20.91322, 19.50758, 20.63540, 21.69172,
                      20.00605, 18.33375, 20.35927, 18.95515, 20.18885, 18.02808, 21.67389,
                      18.00610),
             line = list(color = 'black'), boxpoints = FALSE, name = 2) %>%
add_boxplot (y = list(23.42700, 23.44604, 24.38043, 23.38132, 23.42772, 23.44200, 22.95047,
                      22.99269, 23.40156, 23.56823, 22.06118, 22.75578, 19.48760, 25.21417,
                      21.41917),
             line = list(color = 'black'), boxpoints = FALSE, name = 3) %>%
add_markers(x = yfit+.5, y = xfit, mode = 'lines',
            line=list(width = 2), marker = list(size=1)) %>%
layout (showlegend = FALSE,
          xaxis = list(ticktext = list("AB", "A", "B"), tickvals = list(1, 2, 3)))
```

Created on 2020-05-28 by the reprex package (v0.3.0)

Title: Change the color of boxpoints and add a distribution curve in plotly boxplot

Body:
I want to reproduce the following graphic:

For that I am using the plotly package in R with the following script:

library (plotly)

g <- plot_ly (type = 'box')

h <- g %>% add_boxplot (y = df$lmean, jitter = 0.3, pointpos = -1.8, boxpoints = 'all', marker = list (color = 'black'), line = list (color = 'black'), name = 'AB') %>% layout (showlegend = FALSE)

i <- h %>% add_boxplot (y = list (20.25453, 21.32184, 21.56097, 20.91322, 19.50758, 20.63540, 21.69172, 20.00605, 18.33375, 20.35927, 18.95515, 20.18885, 18.02808, 21.67389, 18.00610), marker = list (color = 'silver'), line = list (color = 'black'), boxpoints = FALSE, name = 'A')

j <- i %>% add_boxplot (y = list (23.42700, 23.44604, 24.38043, 23.38132, 23.42772, 23.44200, 22.95047, 22.99269, 23.40156, 23.56823, 22.06118, 22.75578, 19.48760, 25.21417, 21.41917), marker = list (color = 'silver'), line = list (color = 'black'), boxpoints = FALSE, name = 'B')

Obtaining the following result:

However, I have two questions:

1st) How do I plot the distribution curve for my points?

2nd) Although I define the command marker = list (color = 'silver') the boxplot body does not change color.

My database is:

df <- structure(list(Mean = c(14935404544, 15222448128, 38751113216,
14268438528, 14946194432, 15161123840, 9273937920, 9673856000,
14560262144, 17200879616, 3811098880, 7633272320, 290639968,
89202434048, 2005522432, 625789952, 1819531136, 2311044096, 1209199872,
296506752, 915887232, 2633880832, 488109632, 91674344, 694895872,
170653968, 586009152, 67529624, 2587323136, 66061892), type = c("gmean",
"gmean", "gmean", "gmean", "gmean", "gmean", "gmean", "gmean",
"gmean", "gmean", "gmean", "gmean", "gmean", "gmean", "gmean",
"mean", "mean", "mean", "mean", "mean", "mean", "mean", "mean",
"mean", "mean", "mean", "mean", "mean", "mean", "mean"), lmean = c(23.4270003752245,
23.4460370258537, 24.380425320488, 23.3813158390422, 23.4277225513355,
23.4420003463391, 22.9504739289101, 22.992692825977, 23.4015618839485,
23.5682263599233, 22.0611834044475, 22.7557824657935, 19.4875958357754,
25.2141741636937, 21.4191704283524, 20.2545253328222, 21.3218446872636,
21.560965248974, 20.9132247150145, 19.5075805484868, 20.6354038058895,
21.6917241970269, 20.0060505943238, 18.3337531161829, 20.3592725678438,
18.9551484853174, 20.1888459651668, 18.0280769336398, 21.673889639965,
18.0061026181465)), datalabel = "", time.stamp = " 1 May 2020 12:05", formats = c("%9s",
"%9.0g", "%9s"), types = c(5L, 254L, 5L), val.labels = c("",
"", ""), var.labels = c("Reporter.ISO", "", ""), row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30"), version = 12L, class = "data.frame")

Body:
For the distribution line, you can make your own line using hist and dnorm. Then you can add them using add_marker (for some reason I could not get it to work with add_lines or add_trace).

For the color of the points, you need to set the color to silver within the first add_boxplot which you have boxpoints. You had it set to silver in the second one (which does not have any points plotted), while the first one was set to black.

library (plotly)

h <- hist(df$lmean, breaks = seq(18,25.5,0.5), density = 10, col = "lightgray")
xfit <- seq(min(df$lmean), max(df$lmean), length = 40)
yfit <- dnorm(xfit, mean = mean(df$lmean), sd = sd(df$lmean))

plot_ly (type = 'box') %>%
add_boxplot (y = df$lmean, jitter = 0.5, pointpos = -1.8, boxpoints = 'all',
               marker = list(color = 'silver'), line = list(color = 'black'), name = 1) %>%
add_boxplot (y = list(20.25453, 21.32184, 21.56097, 20.91322, 19.50758, 20.63540, 21.69172,
                      20.00605, 18.33375, 20.35927, 18.95515, 20.18885, 18.02808, 21.67389,
                      18.00610),
             line = list(color = 'black'), boxpoints = FALSE, name = 2) %>%
add_boxplot (y = list(23.42700, 23.44604, 24.38043, 23.38132, 23.42772, 23.44200, 22.95047,
                      22.99269, 23.40156, 23.56823, 22.06118, 22.75578, 19.48760, 25.21417,
                      21.41917),
             line = list(color = 'black'), boxpoints = FALSE, name = 3) %>%
add_markers(x = yfit+.5, y = xfit, mode = 'lines',
            line=list(width = 2), marker = list(size=1)) %>%
layout (showlegend = FALSE,
          xaxis = list(ticktext = list("AB", "A", "B"), tickvals = list(1, 2, 3)))

Created on 2020-05-28 by the reprex package (v0.3.0)


问:
Node js , replacing occurrences in a nested data structure
Basically I want to replace # occurrences in a string from an object. As you can see it replace occurences in templateName , description , comments and Name but I can't replace sections header and sections questions , how will I improve my loop to apply replaceOccurrences in sections.header and sections questions array of objects? . sections headers are array of objects I also want to include that. Any idea? thank you.

Code

```<code>const replaceOccurrences = (originalString) => (typeof originalString === 'string' ? originalString.replace(/#/g, '#') : originalString);

const generateTemplate = async (data) => {

  for (const [k, v] of Object.entries(data)) { data[k] = replaceOccurrences(v); }

  return template(data);
};
</code>```

Data

```<code>data :  {
  Name: 'Rajesh',
  sections: [
    {
      questions: [Array]
    }
  ],
  templateName: 'TEMPLAT#E',
  description: 'Tes#t',
  comments: "adasdada'dfgdfgdfg 'gfddf#gdfgdf #num;## ##fsdfds gdfgdfgfd##"
}
</code>```

答:
James's answer will work if your obj is serializable, otherwise you'll need a recursive function

const removePoundSign = cur => {
  if (typeof cur === 'string') {
    return cur.replace(/#/g, '#');
  }

  if (cur == null || typeof cur !== 'object') return cur;

  if (Array.isArray(cur)) {
    return cur.map(el => removePoundSign(el));
  }

  const newObj = {};
  for (const key in cur) {
    newObj[key] = removePoundSign(cur[key]);
  }
  return newObj;
};
```

also, theres no need for the function to be async in your code!

Body:
Basically I want to replace # occurrences in a string from an object. As you can see it replace occurences in templateName , description , comments and Name but I can't replace sections header and sections questions , how will I improve my loop to apply replaceOccurrences in sections.header and sections questions array of objects? . sections headers are array of objects I also want to include that. Any idea? thank you.

Code

const replaceOccurrences = (originalString) => (typeof originalString === 'string' ? originalString.replace(/#/g, '#') : originalString);

const generateTemplate = async (data) => {

  for (const [k, v] of Object.entries(data)) { data[k] = replaceOccurrences(v); }

  return template(data);
};

Data

data :  {
  Name: 'Rajesh',
  sections: [
    {
      questions: [Array]
    }
  ],
  templateName: 'TEMPLAT#E',
  description: 'Tes#t',
  comments: "adasdada'dfgdfgdfg 'gfddf#gdfgdf #num;## ##fsdfds gdfgdfgfd##"
}

Body:
James's answer will work if your obj is serializable, otherwise you'll need a recursive function

const removePoundSign = cur => {
  if (typeof cur === 'string') {
    return cur.replace(/#/g, '&num;');
  }

  if (cur == null || typeof cur !== 'object') return cur;

  if (Array.isArray(cur)) {
    return cur.map(el => removePoundSign(el));
  }

  const newObj = {};
  for (const key in cur) {
    newObj[key] = removePoundSign(cur[key]);
  }
  return newObj;
};

also, theres no need for the function to be async in your code!


问:
Do I have to install numpy in PyCharm everytime I create a new project? (install and not import)
I installed numpy package in PyCharm, following the default way: File->Settings->Project Interpreter->Click on '+' sign->Type numpy in the search baar->Install. Now, when I am working on a new project and trying to import numpy, it says: "ModuleNotFoundError: No module named 'numpy'". Please help! Thanks in advance :)  </p>

答: I wasn't able to find support for this feature in PyCharm or in any of the available plugins, but if you're not worried about keeping different dependencies isolated, you do have the option of using the same environment for all your projects.</p>


问:
iOS - same .app name
I've uploaded several .app's the the iTunes store, where the "executable" file (ie. filename.app) is the same.

What are the repercussion's of this on an actual device, when an actual person downloads both onto their iPad/Phone/Touch , and possibly is running both?

The best answer would be that it is inconsequential since the bundleID's store the .app in different respective folders, but I do need further insight.

答:
The name you give the app is irrelevant. All that matters is the bundle ID. These must be unique. From the iTunesConnect Developer's Guide:

An identifier used by iOS and Mac OS X
  to recognize any future updates to
  your app. Your Bundle ID must be
  registered with Apple and unique to
  your app. Bundle IDs are app-type
  specific (either iOS or Mac OS X). The
  same Bundle ID cannot be used for both
  iOS and Mac OS X apps.

Think about the consequences of the alternative. If I name my app MyApp and you name your app MyApp, then a user who bought both would be in trouble. The bundle ID is the unique identifier for each app. The name of the app is unique for convenience and to avoid confusion when purchasing an app, but the bundle identifier is unique to keep products from overwriting one another.

Title: iOS - same .app name


问:
Keep changes to defaultWorkingDirectory thoughout stages within Azure build pipeline
I have a YAML file that resembles the following:

```<code>stages:
  - stage: A
    pool:
        vmImage: 'windows-2019'
    jobs:
    - job: a
      steps:
        - task: PowerShell@2
          inputs:
            targetType: 'inline'
            script: |
             #edits file "$(System.DefaultWorkingDirectory)/myfolder/myfile.json"

  - stage: B
    dependsOn: A
    pool:
        vmImage: 'windows-2019'
    jobs:
      - job: b
        steps:
        - task: PowerShell@2
          inputs:
            targetType: 'inline'
            script: |
             #uses file "$(System.DefaultWorkingDirectory)/myfolder/myfile.json"
</code>```

I have split my pipeline into two stages; A: edits a file in a repository and B: works with the edited file.

My problem is, the files seem to get reset between stages. Is there any way of keeping the changes throughout the stages, rather than resetting them?

I don't want to publish artifacts and so on as in stage b, although not in the YAML above, I am running multiple PowerShell script files that contain hardcoded file paths and it would just be a mess overwriting the file paths to point at the artifacts directory before running the stage.

An

答:
Based on my test , the cause of this issue is that the two stages run on the different Agent machines.

For example: Stage A -> Agent machine name: 'fv-az146' , Stage B -> Agent machine name: 'fv-az151'

You could check the agent information in Build log -> Initialize job.

Is there any way of keeping the changes throughout the stages, rather
  than resetting them?

Since you don't want to publish artifacts, you could try to use Self-hosted agents to run two stages.

You need to add demands to the agent to ensure that the stages run on the same Self-hosted agent.

According to this doc:

The demands keyword is supported by private pools.

We couldn't specify specific "Agent Capabilities" in Microsoft-hosted agents. So we couldn't ensure that two stages can run on the same agent

Update:

Since the two stages are running on the same agent, the "check out" step in Stage B could override the files in Stage A.

So you also need to add the - checkout: none in Stage B.

Here is the updated Yaml template:

```<code>stages:
 - stage: A
    pool:
     name: Pool name
     demands:
     - Agent.Name -equals agentname1
    jobs:
    - job: a
      steps:
        - task: PowerShell@2
          ...

  - stage: B
    dependsOn: A
    pool:
     name: Pool name
     demands:
     - Agent.Name -equals agentname1
    jobs:
      - job: b
        steps:
        - checkout: none
        - task: PowerShell@2
        ...
</code>```

The overall workflow： the Stage A edits the files and save it to $(System.DefaultWorkingDirectory).

Then Stage B could directly use the files in $(System.DefaultWorkingDirectory).

The files in $(System.DefaultWorkingDirectory) will keep changes in Stage A and B.

Body:
I have a YAML file that resembles the following:

stages:
  - stage: A
    pool:
        vmImage: 'windows-2019'
    jobs:
    - job: a
      steps:
        - task: PowerShell@2
          inputs:
            targetType: 'inline'
            script: |
             #edits file "$(System.DefaultWorkingDirectory)/myfolder/myfile.json"

  - stage: B
    dependsOn: A
    pool:
        vmImage: 'windows-2019'
    jobs:
      - job: b
        steps:
        - task: PowerShell@2
          inputs:
            targetType: 'inline'
            script: |
             #uses file "$(System.DefaultWorkingDirectory)/myfolder/myfile.json"

I have split my pipeline into two stages; A: edits a file in a repository and B: works with the edited file.

My problem is, the files seem to get reset between stages. Is there any way of keeping the changes throughout the stages, rather than resetting them?

I don't want to publish artifacts and so on as in stage b, although not in the YAML above, I am running multiple PowerShell script files that contain hardcoded file paths and it would just be a mess overwriting the file paths to point at the artifacts directory before running the stage.

An

Body:
Based on my test , the cause of this issue is that the two stages run on the different Agent machines.

For example: Stage A -> Agent machine name: 'fv-az146' , Stage B -> Agent machine name: 'fv-az151'

You could check the agent information in Build log -> Initialize job.

Is there any way of keeping the changes throughout the stages, rather
  than resetting them?

Since you don't want to publish artifacts, you could try to use Self-hosted agents to run two stages.

You need to add demands to the agent to ensure that the stages run on the same Self-hosted agent.

According to this doc:

The demands keyword is supported by private pools.

We couldn't specify specific "Agent Capabilities" in Microsoft-hosted agents. So we couldn't ensure that two stages can run on the same agent

Update:

Since the two stages are running on the same agent, the "check out" step in Stage B could override the files in Stage A.

So you also need to add the - checkout: none in Stage B.

Here is the updated Yaml template:

stages:
 - stage: A
    pool:
     name: Pool name
     demands:
     - Agent.Name -equals agentname1
    jobs:
    - job: a
      steps:
        - task: PowerShell@2
          ...

  - stage: B
    dependsOn: A
    pool:
     name: Pool name
     demands:
     - Agent.Name -equals agentname1
    jobs:
      - job: b
        steps:
        - checkout: none
        - task: PowerShell@2
        ...

The overall workflow： the Stage A edits the files and save it to $(System.DefaultWorkingDirectory).

Then Stage B could directly use the files in $(System.DefaultWorkingDirectory).

The files in $(System.DefaultWorkingDirectory) will keep changes in Stage A and B.


问:
How to generalize picking subsets of size `n` from `m` alternatives with state between picks in Haskell
I'm working on brute-forcing solutions to a maths puzzle, and am struggling to abstract my solution so that I can easily solve varying puzzle sizes.

The puzzle can be found at https://www.think-maths.co.uk/uniquedistance. Please don't read on if you want to solve the puzzle yourself without spoilers. If you just want to help me solve the Haskell programming problem at hand, you don't need to spend time on studying what the puzzle is.

What I'm trying to do in my solution shown below, is to find subsets of size n from a pool of n^2 different options, such that some binary function metric produces unique results for all pairs of options from the chosen subset.

At first I wrote a solution along the lines of

```<code>combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations _ [] = []
combinations n xs = [ a:rec | (a:as) <- tails xs, rec <- combinations (pred n) as ]
</code>```

which gave me all the possible subsets, and subsequently checked whether or not any individual subset satisfied the uniqueness requirement of the given metric for all possible pairs chosen from the subset using

```<code>import qualified Data.IntSet as IS

check :: [a] -> Bool
check = noDupes . metrics
  where metrics ps = [ metric a b | (a:bs) <- tails ps, b <- bs ]
        noDupes = go IS.empty
        go _ [] = True
        go s (x:xs) | IS.member x s = False
                    | otherwise = go (IS.insert x s) xs
</code>```

From there, filter check (combinations n) would give me correct solutions for any given n. However, to improve performance, I wanted to change my computation such that rather than first generating all subsets of size n and only then checking if my constraint holds for the full subset, it would instead discard subsets smaller than n elements earlier on, allowing me to compute the expensive metric less often.

I wasn't easily able to transform my above solution into what I wanted, but so far I've been able to come up with the following (which also includes some more concrete types and a definition of the metric, but I think you can ignore that if you don't care about the details of the puzzle):

```<code>import qualified Data.IntSet as IS
import Data.Maybe
import Control.Monad
import Data.List
import Linear.V2 (V2(..))

-- euclidean distance squared
metric :: V2 Int -> V2 Int -> Int
metric (V2 x1 y1) (V2 x2 y2) = ((x1-x2)^2) + ((y1-y2)^2)

-- metric of a new candidate point to all previous points
metrics p = map (metric p)

-- check if the previously seen set of metrics are compatible with the metrics
-- of a new candidate. Nothing if they're not, and Just the union of the
-- previous and new metrics.
checkCompatibility :: IS.IntSet -> [Int] -> Maybe IS.IntSet
checkCompatibility s [] = Just s
checkCompatibility s (x:xs) | IS.member x s = Nothing
                            | otherwise = checkCompatibility (IS.insert x s) xs

-- all combinations of choosing 1 points from the input
combinations1 :: [V2 Int] -> [[V2 Int]]
combinations1 xs = do
  (a:bs) <- tails xs
  let ret = [a]

  return ret

-- all combinations of choosing 2 points from the input
combinations2 :: [V2 Int] -> [[V2 Int]]
combinations2 xs = do
  (a:bs) <- tails xs
  let ret = [a]

  (b:cs) <- tails bs
  let sset = checkCompatibility IS.empty (metrics b ret)
  guard (maybe False (not . IS.null) sset)
  let ret' = b:ret

  return (reverse ret')

-- all combinations of choosing 3 points from the input, where the "metric" between any pair of points is unique
combinations3 :: [V2 Int] -> [[V2 Int]]
combinations3 xs = do
  (a:bs) <- tails xs
  let ret = [a]

  (b:cs) <- tails bs
  let sset = checkCompatibility IS.empty (metrics b ret)
  guard (maybe False (not . IS.null) sset)
  let ret' = b:ret

  (c:ds) <- tails cs
  let sset' = checkCompatibility (fromJust sset) (metrics c ret')
  guard (maybe False (not . IS.null) sset')
  let ret'' = c:ret'

  return (reverse ret'')

-- all combinations of choosing 4 points from the input, where the "metric" between any pair of points is unique
combinations4 :: [V2 Int] -> [[V2 Int]]
combinations4 xs = do
  (a:bs) <- tails xs
  let ret = [a]

  (b:cs) <- tails bs
  let sset = checkCompatibility IS.empty (metrics b ret)
  guard (maybe False (not . IS.null) sset)
  let ret' = b:ret

  (c:ds) <- tails cs
  let sset' = checkCompatibility (fromJust sset) (metrics c ret')
  guard (maybe False (not . IS.null) sset')
  let ret'' = c:ret'

  (d:es) <- tails ds
  let sset'' = checkCompatibility (fromJust sset') (metrics d ret'')
  guard (maybe False (not . IS.null) sset'')
  let ret''' = d:ret''

  return (reverse ret''')

combinations5 :: [V2 Int] -> [[V2 Int]]
combinations5 xs = do
  (a:bs) <- tails xs
  let ret = [a]

  (b:cs) <- tails bs
  let sset = checkCompatibility IS.empty (metrics b ret)
  guard (maybe False (not . IS.null) sset)
  let ret' = b:ret

  (c:ds) <- tails cs
  let sset' = checkCompatibility (fromJust sset) (metrics c ret')
  guard (maybe False (not . IS.null) sset')
  let ret'' = c:ret'

  (d:es) <- tails ds
  let sset'' = checkCompatibility (fromJust sset') (metrics d ret'')
  guard (maybe False (not . IS.null) sset'')
  let ret''' = d:ret''

  (e:fs) <- tails es
  let sset''' = checkCompatibility (fromJust sset'') (metrics e ret''')
  guard (maybe False (not . IS.null) sset''')
  let ret'''' = e:ret'''

  return (reverse ret'''')

combinations6 :: [V2 Int] -> [[V2 Int]]
combinations6 xs = do
  (a:bs) <- tails xs
  let ret = [a]

  (b:cs) <- tails bs
  let sset = checkCompatibility IS.empty (metrics b ret)
  guard (maybe False (not . IS.null) sset)
  let ret' = b:ret

  (c:ds) <- tails cs
  let sset' = checkCompatibility (fromJust sset) (metrics c ret')
  guard (maybe False (not . IS.null) sset')
  let ret'' = c:ret'

  (d:es) <- tails ds
  let sset'' = checkCompatibility (fromJust sset') (metrics d ret'')
  guard (maybe False (not . IS.null) sset'')
  let ret''' = d:ret''

  (e:fs) <- tails es
  let sset''' = checkCompatibility (fromJust sset'') (metrics e ret''')
  guard (maybe False (not . IS.null) sset''')
  let ret'''' = e:ret'''

  (f:gs) <- tails fs
  let sset'''' = checkCompatibility (fromJust sset''') (metrics f ret'''')
  guard (maybe False (not . IS.null) sset'''')
  let ret''''' = f:ret''''

  return (reverse ret''''')

bruteforce :: Int -> ([V2 Int] -> [[V2 Int]]) -> [[V2 Int]]
bruteforce n f = f positions
  where positions = [ V2 x y | x <- [0..pred n], y <- [0..pred n] ]
</code>```

Do note how the various implementations for different values of n are extremely similar in the same way that my original combinations function from above would've been if I hadn't written it recursively with an n parameter.

What I'm trying to work out is how to parameterize my combinations1, combinations2, combinations3, and so on functions such that I don't have to tediously write a solution for every value of n.

```<code>-- all combinations of choosing n points from the input, where the "metric" between any pair of points is unique
combinationsN :: Int -> [V2 Int] -> [[V2 Int]]
combinationsN 0 _ = [[]]
combinationsN _ [] = []
combinationsN n xs = undefined
</code>```

For educational purposes, I think I'd mainly be interested in how to accomplish this while manually stringing the state along between steps so I could later refine that to a solution using Control.Monad.State, but I'd also be interested in seeing other approaches to maintain the state between the steps.

I'd also appreciate suggestions for a better question title. Not really knowing how to do what I want, I really don't know what terms I should be using to ask about it.

Thanks!

答:
Well, you have the idea. Grow the IntSet through combinations. You can do this by adding extra parameters to combinations:

```<code>solve :: Int -> [V2 Int] -> [[V2 Int]]
solve n xs = go n xs IS.empty []
  where go :: Int -> [V2 Int] -> IntSet -> [V2 Int] -> [[V2 Int]]
        go 0 _  _       seen = [reverse seen]
        go n xs metrics seen = [ rec
                               | (a : as) <- tails xs
                               , metrics' <- maybeToList $ addMetrics a seen metrics
                               , rec <- go (pred n) as metrics' (a : seen)]
        addMetrics :: V2 Int -> [V2 Int] -> IntSet -> Maybe IntSet
        addMetrics _ [] i = Just i
        addMetrics a (b : bs) i = do
           i' <- addMetrics a bs i
           let m = metric a b
           guard $ m `IS.notMember` i'
           return $ IS.insert m i'
</code>```

This transform is very common: you keep some extra data around in some internal, probably recursive function, then throw it away when you're done. Now, to generalize: V2 Int can become a, IntSet can become s, addMetrics and IS.empty become parameters, and Maybe generalizes to [].

```<code>-- realized that it's not really "pruning" if we're allowing [s] instead of just Maybe s, but meh
pruningCombs :: s -> (a -> [a] -> s -> [s]) -> Int -> [a] -> [[a]]
pruningCombs e grow n xs = go n xs e []
    where go 0 _  _ seen = [reverse seen]
          go n xs s seen = [ rec
                           | (a : as) <- tails xs
                           , s' <- grow a seen s
                           , rec <- go (pred n) as s' (a : seen)]

solve = pruningCombs IS.empty \a -> execStateT . traverse \b -> do
    let m = metric a b
    guard =<< gets (IS.notMember m)
    modify $ IS.insert m
</code>```

This runs in about the same time as your combinations6.

Body:
I'm working on brute-forcing solutions to a maths puzzle, and am struggling to abstract my solution so that I can easily solve varying puzzle sizes.

The puzzle can be found at https://www.think-maths.co.uk/uniquedistance. Please don't read on if you want to solve the puzzle yourself without spoilers. If you just want to help me solve the Haskell programming problem at hand, you don't need to spend time on studying what the puzzle is.

What I'm trying to do in my solution shown below, is to find subsets of size n from a pool of n^2 different options, such that some binary function metric produces unique results for all pairs of options from the chosen subset.

At first I wrote a solution along the lines of

combinations :: Int -> [a] -> [[a]]
combinations 0 _ = [[]]
combinations _ [] = []
combinations n xs = [ a:rec | (a:as) <- tails xs, rec <- combinations (pred n) as ]

which gave me all the possible subsets, and subsequently checked whether or not any individual subset satisfied the uniqueness requirement of the given metric for all possible pairs chosen from the subset using

import qualified Data.IntSet as IS

check :: [a] -> Bool
check = noDupes . metrics
  where metrics ps = [ metric a b | (a:bs) <- tails ps, b <- bs ]
        noDupes = go IS.empty
        go _ [] = True
        go s (x:xs) | IS.member x s = False
                    | otherwise = go (IS.insert x s) xs

From there, filter check (combinations n) would give me correct solutions for any given n. However, to improve performance, I wanted to change my computation such that rather than first generating all subsets of size n and only then checking if my constraint holds for the full subset, it would instead discard subsets smaller than n elements earlier on, allowing me to compute the expensive metric less often.

I wasn't easily able to transform my above solution into what I wanted, but so far I've been able to come up with the following (which also includes some more concrete types and a definition of the metric, but I think you can ignore that if you don't care about the details of the puzzle):

import qualified Data.IntSet as IS
import Data.Maybe
import Control.Monad
import Data.List
import Linear.V2 (V2(..))

-- euclidean distance squared
metric :: V2 Int -> V2 Int -> Int
metric (V2 x1 y1) (V2 x2 y2) = ((x1-x2)^2) + ((y1-y2)^2)

-- metric of a new candidate point to all previous points
metrics p = map (metric p)

-- check if the previously seen set of metrics are compatible with the metrics
-- of a new candidate. Nothing if they're not, and Just the union of the
-- previous and new metrics.
checkCompatibility :: IS.IntSet -> [Int] -> Maybe IS.IntSet
checkCompatibility s [] = Just s
checkCompatibility s (x:xs) | IS.member x s = Nothing
                            | otherwise = checkCompatibility (IS.insert x s) xs

-- all combinations of choosing 1 points from the input
combinations1 :: [V2 Int] -> [[V2 Int]]
combinations1 xs = do
  (a:bs) <- tails xs
  let ret = [a]

  return ret

-- all combinations of choosing 2 points from the input
combinations2 :: [V2 Int] -> [[V2 Int]]
combinations2 xs = do
  (a:bs) <- tails xs
  let ret = [a]

  (b:cs) <- tails bs
  let sset = checkCompatibility IS.empty (metrics b ret)
  guard (maybe False (not . IS.null) sset)
  let ret' = b:ret

  return (reverse ret')

-- all combinations of choosing 3 points from the input, where the "metric" between any pair of points is unique
combinations3 :: [V2 Int] -> [[V2 Int]]
combinations3 xs = do
  (a:bs) <- tails xs
  let ret = [a]

  (b:cs) <- tails bs
  let sset = checkCompatibility IS.empty (metrics b ret)
  guard (maybe False (not . IS.null) sset)
  let ret' = b:ret

  (c:ds) <- tails cs
  let sset' = checkCompatibility (fromJust sset) (metrics c ret')
  guard (maybe False (not . IS.null) sset')
  let ret'' = c:ret'

  return (reverse ret'')

-- all combinations of choosing 4 points from the input, where the "metric" between any pair of points is unique
combinations4 :: [V2 Int] -> [[V2 Int]]
combinations4 xs = do
  (a:bs) <- tails xs
  let ret = [a]

  (b:cs) <- tails bs
  let sset = checkCompatibility IS.empty (metrics b ret)
  guard (maybe False (not . IS.null) sset)
  let ret' = b:ret

  (c:ds) <- tails cs
  let sset' = checkCompatibility (fromJust sset) (metrics c ret')
  guard (maybe False (not . IS.null) sset')
  let ret'' = c:ret'

  (d:es) <- tails ds
  let sset'' = checkCompatibility (fromJust sset') (metrics d ret'')
  guard (maybe False (not . IS.null) sset'')
  let ret''' = d:ret''

  return (reverse ret''')

combinations5 :: [V2 Int] -> [[V2 Int]]
combinations5 xs = do
  (a:bs) <- tails xs
  let ret = [a]

  (b:cs) <- tails bs
  let sset = checkCompatibility IS.empty (metrics b ret)
  guard (maybe False (not . IS.null) sset)
  let ret' = b:ret

  (c:ds) <- tails cs
  let sset' = checkCompatibility (fromJust sset) (metrics c ret')
  guard (maybe False (not . IS.null) sset')
  let ret'' = c:ret'

  (d:es) <- tails ds
  let sset'' = checkCompatibility (fromJust sset') (metrics d ret'')
  guard (maybe False (not . IS.null) sset'')
  let ret''' = d:ret''

  (e:fs) <- tails es
  let sset''' = checkCompatibility (fromJust sset'') (metrics e ret''')
  guard (maybe False (not . IS.null) sset''')
  let ret'''' = e:ret'''

  return (reverse ret'''')

combinations6 :: [V2 Int] -> [[V2 Int]]
combinations6 xs = do
  (a:bs) <- tails xs
  let ret = [a]

  (b:cs) <- tails bs
  let sset = checkCompatibility IS.empty (metrics b ret)
  guard (maybe False (not . IS.null) sset)
  let ret' = b:ret

  (c:ds) <- tails cs
  let sset' = checkCompatibility (fromJust sset) (metrics c ret')
  guard (maybe False (not . IS.null) sset')
  let ret'' = c:ret'

  (d:es) <- tails ds
  let sset'' = checkCompatibility (fromJust sset') (metrics d ret'')
  guard (maybe False (not . IS.null) sset'')
  let ret''' = d:ret''

  (e:fs) <- tails es
  let sset''' = checkCompatibility (fromJust sset'') (metrics e ret''')
  guard (maybe False (not . IS.null) sset''')
  let ret'''' = e:ret'''

  (f:gs) <- tails fs
  let sset'''' = checkCompatibility (fromJust sset''') (metrics f ret'''')
  guard (maybe False (not . IS.null) sset'''')
  let ret''''' = f:ret''''

  return (reverse ret''''')

bruteforce :: Int -> ([V2 Int] -> [[V2 Int]]) -> [[V2 Int]]
bruteforce n f = f positions
  where positions = [ V2 x y | x <- [0..pred n], y <- [0..pred n] ]

Do note how the various implementations for different values of n are extremely similar in the same way that my original combinations function from above would've been if I hadn't written it recursively with an n parameter.

What I'm trying to work out is how to parameterize my combinations1, combinations2, combinations3, and so on functions such that I don't have to tediously write a solution for every value of n.

-- all combinations of choosing n points from the input, where the "metric" between any pair of points is unique
combinationsN :: Int -> [V2 Int] -> [[V2 Int]]
combinationsN 0 _ = [[]]
combinationsN _ [] = []
combinationsN n xs = undefined

For educational purposes, I think I'd mainly be interested in how to accomplish this while manually stringing the state along between steps so I could later refine that to a solution using Control.Monad.State, but I'd also be interested in seeing other approaches to maintain the state between the steps.

I'd also appreciate suggestions for a better question title. Not really knowing how to do what I want, I really don't know what terms I should be using to ask about it.

Thanks!

Body:
Well, you have the idea. Grow the IntSet through combinations. You can do this by adding extra parameters to combinations:

solve :: Int -> [V2 Int] -> [[V2 Int]]
solve n xs = go n xs IS.empty []
  where go :: Int -> [V2 Int] -> IntSet -> [V2 Int] -> [[V2 Int]]
        go 0 _  _       seen = [reverse seen]
        go n xs metrics seen = [ rec
                               | (a : as) <- tails xs
                               , metrics' <- maybeToList $ addMetrics a seen metrics
                               , rec <- go (pred n) as metrics' (a : seen)]
        addMetrics :: V2 Int -> [V2 Int] -> IntSet -> Maybe IntSet
        addMetrics _ [] i = Just i
        addMetrics a (b : bs) i = do
           i' <- addMetrics a bs i
           let m = metric a b
           guard $ m `IS.notMember` i'
           return $ IS.insert m i'

This transform is very common: you keep some extra data around in some internal, probably recursive function, then throw it away when you're done. Now, to generalize: V2 Int can become a, IntSet can become s, addMetrics and IS.empty become parameters, and Maybe generalizes to [].

-- realized that it's not really "pruning" if we're allowing [s] instead of just Maybe s, but meh
pruningCombs :: s -> (a -> [a] -> s -> [s]) -> Int -> [a] -> [[a]]
pruningCombs e grow n xs = go n xs e []
    where go 0 _  _ seen = [reverse seen]
          go n xs s seen = [ rec
                           | (a : as) <- tails xs
                           , s' <- grow a seen s
                           , rec <- go (pred n) as s' (a : seen)]

solve = pruningCombs IS.empty \a -> execStateT . traverse \b -> do
    let m = metric a b
    guard =<< gets (IS.notMember m)
    modify $ IS.insert m

This runs in about the same time as your combinations6.


问:
Can't connect email mailable to view in laravel modules
I cant seem to connect my mailable to its blade view.
this is my markdown in the mailable build function:

->markdown('emails.exmpl');

I built the blade view inside Modules\ContactUs\Resources\Views\Emails calling it exmpl.blade.php

however i get this error:

View [emails.exmpl] not found.

答:
By default the path is resources/views/emails/exmpl but here your blade is in a different module. Might I suggest trying

->markdown('/Modules/ContactUs/Resources/Views/Emails/exmpl')

Keep me posted in the comments below.


问:
DataGrid want to display NO RECORDS
In my application i am using DataGrid,i am binding dataset to that DataGrid.So if the dataset records is zero i want to display "NO ReCORDS FOUND" in my DataGrid.

Thanks in advance.

答: You have GridView tag as well so for GridView, you can set it's EmptyDataText property to "No records found" . It's a little complicated with DataGrid.

Title: DataGrid want to display NO RECORDS


问:
AWS SAM template doesn't execute BuildMethod
I have a lambda functions that has somewhat non standard packaging. I am using a Makefile to help me package what I need and use it as my build method with sam build command. However I don't see this makefile being executed. Can't figure out why not.
Here is what I have :

sam_template.yaml:

```<code>AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  subscriptions_functions

  Sample SAM Template for subscriptions_functions

Globals:
  Function:
    Timeout: 3

Resources:
  GetSubscriptionsFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: .
      Handler: app.lambda_handler_individual_methods
      Runtime: python3.7
      Events:
        GetSubscriptions:
          Type: Api
          Properties:
            Path: /subscriptions
            Method: get
    Metadata:
      BuildMethod: makefile
    Environment:
      Variables:
        SERVICE_METHOD_NAME: 'xyz'
        REQ_CLASS_NAME: 'xyz'
        RES_CLASS_NAME: 'xyz'

</code>```

Makefile: (the name is based on some AWS examples)

```<code>
build-GetSubscriptionsFunction:
    @echo "Buliding artifacts with sls. Destination dir " $(ARTIFACTS_DIR)
    sls package --env aws
    mkdir -p $(ARTIFACTS_DIR)
    unzip .serverless/subscriptions.zip -d $(ARTIFACTS_DIR)
    cp requirements.txt $(ARTIFACTS_DIR)
    python -m pip install -r requirements.txt -t $(ARTIFACTS_DIR)
    rm -rf $(ARTIFACTS_DIR)/bin
</code>```

Build succeeded when I run sam build -t sam_template.yaml , but I can tell the Makefile didn't run (no messages printed out and it would create a .serverless directory, but it didn't)

Anyone has an idea what is wrong in this setup?

答:
so I figured it out and it wasn't anything to do with the syntax.
I was running from IntelliJ terminal. Since I was hitting a wall with this one, I started pocking around and running few other SAM commands. Running sam validate also kept failing, but with an error pointing to unset default region.
My region was properly set in both .aws/config and I even tried to export an env variable AWS_DEFAULT_REGION , but nothing worked. It kept failing with unset region.
So I started looking at my plugins in IntelliJ and turns out I had both AWS Toolkit and Debugger for AWS Lambda (by Thundera) installed.
I uninstalled the later and I'm back in business. Not clear on why this plugin was interfering with my console and cli, but it did. Getting rid of it did the trick

Body:
I have a lambda functions that has somewhat non standard packaging. I am using a Makefile to help me package what I need and use it as my build method with sam build command. However I don't see this makefile being executed. Can't figure out why not.
Here is what I have :

sam_template.yaml:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
  subscriptions_functions

  Sample SAM Template for subscriptions_functions

Globals:
  Function:
    Timeout: 3

Resources:
  GetSubscriptionsFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: .
      Handler: app.lambda_handler_individual_methods
      Runtime: python3.7
      Events:
        GetSubscriptions:
          Type: Api
          Properties:
            Path: /subscriptions
            Method: get
    Metadata:
      BuildMethod: makefile
    Environment:
      Variables:
        SERVICE_METHOD_NAME: 'xyz'
        REQ_CLASS_NAME: 'xyz'
        RES_CLASS_NAME: 'xyz'

Makefile: (the name is based on some AWS examples)

build-GetSubscriptionsFunction:
    @echo "Buliding artifacts with sls. Destination dir " $(ARTIFACTS_DIR)
    sls package --env aws
    mkdir -p $(ARTIFACTS_DIR)
    unzip .serverless/subscriptions.zip -d $(ARTIFACTS_DIR)
    cp requirements.txt $(ARTIFACTS_DIR)
    python -m pip install -r requirements.txt -t $(ARTIFACTS_DIR)
    rm -rf $(ARTIFACTS_DIR)/bin

Build succeeded when I run sam build -t sam_template.yaml , but I can tell the Makefile didn't run (no messages printed out and it would create a .serverless directory, but it didn't)

Anyone has an idea what is wrong in this setup?