问:
How to use 2 models in 1 View
I have a Booking model and I create a list of all it's elements in the BookingController. There I managed to export the list as .json, however when I want to import a file I can't manage to use my custom validation to see if it's only .json. The problem is that in my Index for Booking I have a IEnumerable model for Booking and I use a BookingsUpload model to upload the file. So how can I access this BookingsUpload model inside the Index or how could i change it ? (could I combine what i do in BookingsUpload with my Booking model ?

Booking Model:

```<code>public class Booking
{
    [Required]
    [Display(Name = "Ladestand")]
    [Range(0, 100)]
    public double chargeState { get; set; }

    [Required]
    [Display(Name = "Benötigte Fahrstrecke")]
    [Range(1, 1000)]
    public double distance { get; set; }

    [Required]
    [Display(Name = "Beginn")]
    public DateTime startTime { get; set; }

    [Required]
    [Display(Name = "Ende")]
    public DateTime endTime { get; set; }

    [Required]
    [Display(Name = "Anschlusstyp")]
    [EnumDataType(typeof(ConnectorType))]
    [JsonConverter(typeof(StringEnumConverter))]
    public ConnectorType connectorType { get; set; }
}

public class BookingList
        {
            public List<Booking> BookingListObj { get; set; }
        }
</code>```

BookingsUpload Model:

```<code>public class BookingsUpload
{
    [Required(ErrorMessage = "Please select a file.")]
    [DataType(DataType.Upload)]
    [MaxFileSize(1024 * 1024)]
    [AllowedExtensions(new string[] { ".json" })]
    public IFormFile File { get; set; }
}
</code>```

** NEW UPDATE **:
Now Controller doesn't work as intended. Cannot add elements to List (or maybe they are added just can't display it in the View not sure):
Controller:

```<code>public class BookingController : Controller
{
    private IMemoryCache _cache;
    private string bookingsKey = "bookingsList";
    public BookingController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

    public IActionResult Index()
    {
        List<Booking> bookigsList;
        _cache.TryGetValue<List<Booking>>(bookingsKey, out bookigsList);
        return View(bookigsList);
    }

    /* MVVC fucking failed :(
    public IActionResult Index()
    {
        BookingList bookingsList;
        //_cache.TryGetValue(bookingsKey, out bookingList);

        bookingsList = new BookingList();
        bookingsList.BookingListObj = new List<Booking>();

        bookingsList.BookingListObj.Add(new Booking() { chargeState = 30, distance = 150, startTime = new DateTime(2020, 8, 13, 13, 45, 0), endTime = new DateTime(2020, 8, 13, 17, 0, 0) });
        _cache.Set<List<Booking>>(bookingsKey, bookingsList.BookingListObj);

        BookingViewModel bookingViewModel = new BookingViewModel()
        {
            Bookings = bookingsList.BookingListObj
        };

        return View(bookingViewModel);
    }*/

    [HttpGet]
    public IActionResult Create()
    {
        Booking booking = new Booking();
        return View("Create", booking);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Booking booking)
    {
        List<Booking> bookingsList;

        //BookingList bookingsList;
        /*_cache.TryGetValue(bookingsKey, out bookingsList);
        BookingViewModel bookingViewModel = new BookingViewModel()
        {
            BookingList = bookingsList
        };*/

        if (!ModelState.IsValid)
        {
            return View("Create", booking);
        }
        if (!_cache.TryGetValue(bookingsKey, out bookingsList))
        {
            bookingsList = new List<Booking>();
        }

        bookingsList.Add(booking);
        _cache.Set<List<Booking>>(bookingsKey, bookingsList);

        /*BookingViewModel bookingViewModel = new BookingViewModel()
        {
            BookingList = bookingsList
        };*/

        return RedirectToAction("Index", "Booking");
    }
</code>```

BookingViewModel:

```<code>public class BookingViewModel
{
    public Booking Booking { get; set; }
    public BookingList BookingList { get; set; }
    public IEnumerable<Booking> Bookings { get; set; }
    public BookingsUpload BookingsUpload { get; set; }

    public BookingViewModel()
    {
        Booking = new Booking();
        Bookings = new List<Booking>();
        BookingsUpload = new BookingsUpload();
    }
}
</code>```

Booking Index:

```<code>    @model WebApplication.ViewModels.BookingViewModel

@{
    ViewData["Title"] = "Index";
}

<br />
<div class="container row p-0 m-0">
    <div class="container col 6">
        <h1 class="text-info">Übersicht aller Buchungen</h1>
    </div>
    <div class="container col-3">
        <div class="m-1">
            <a asp-controller="Booking" asp-action="Create" class="btn btn-info form-control text-white">Erstelle Buchung</a>
        </div>
        <div class="d-flex flex-row">
            <div class="w-100 m-1">
                <a asp-controller="Booking" asp-action="Export" class="btn btn-info form-control text-white">Export</a>
            </div>
            <div class="w-100 m-1">
                <form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">
                    <div class="form-group">
                        <label class="custom-file-upload">
                            <input type="file" name="file" onchange="this.form.submit()" />
                            Import/validation_bc_fuck_MVC
                        </label>
                        <span asp-validation-for="BookingsUpload.File" class="text-danger"></span>
                    </div>
                </form>
                <a asp-controller="Booking" asp-action="Import" class="btn btn-info form-control text-white">Import + validation</a>
            </div>
        </div>
    </div>

    <div class="col-12">
        @if (Model.Booking != null)
        {
            <table class="table table-striped table-borderless table-hover">
                <thead class="thead-dark">

                    <tr>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.chargeState) %
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.distance) (km)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.connectorType)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.startTime)
                        </th>
                        <th>
                            @Html.DisplayNameFor(model => Model.Booking.endTime)
                        </th>
                    </tr>
                </thead>
                <tbody>
                    @foreach (var item in Model.Bookings)
                    {
                        <tr>
                            <td>
                                @Html.DisplayFor(modelItem => item.chargeState)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.distance)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.connectorType)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.startTime)
                            </td>
                            <td>
                                @Html.DisplayFor(modelItem => item.endTime)
                            </td>
                        </tr>
                    }
                </tbody>
            </table>
        }
        else
        {
            <p>Es sind keine Buchungen vorhanden</p>
        }
    </div>
</div>

<style>
    input[type="file"] {
        display: none;
    }

    .custom-file-upload {
        color: #fff !important;
        background-color: #17a2b8;
        border-color: #17a2b8;
        /*text display: inline-block;*/
        cursor: pointer;
        font-weight: 400;
        text-align: center;
        vertical-align: middle;
        user-select: none;
        border: 1px solid transparent;
        padding: 6px 12px;
        font-size: 1rem;
        line-height: 1.5;
        border-radius: .25rem;
        transition: color .15s;
        width: 100%;
        height: calc(1.5em + .75rem + 2px);
    }

    .custom-file-upload:hover {
        background-color: #138496;
        border-color: #117a8b;
    }
</style>
</code>```

So the Import label is the problem because I cant access the File from BookingsUpload to make the span asp-validation-for="File" but with the Import button I managed to go to a different View with only this code below and there the validation works because there I can use the BookingsUpload model:

```<code>    @model WebApplication.Models.BookingsUpload;

@{
    ViewData["Title"] = "Import";
}

<h1>Import</h1>

<form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label class="custom-file-upload">
            <input asp-for="File" type="file" name="file" onchange="this.form.submit()" />
            Import
        </label>
        <span asp-validation-for="File" class="text-danger"></span>
    </div>
</form>
</code>```

答:
Add a Constructor to your class where you initialize your objects so it wont be null</p>

```<code>public class BookingViewModel
{
    public BookingViewModel()
    {
        Booking = new Booking();
        Bookings = new IEnumerable<Booking>();
        BookingsUpload = new BookingsUpload();
    }
    public Booking Booking { get; set; }
    public IEnumerable<Booking> Bookings { get; set; }
    public BookingsUpload BookingsUpload { get; set; }
}
</code>```

Title: How to use 2 models in 1 View

Body:
I have a Booking model and I create a list of all it's elements in the BookingController. There I managed to export the list as .json, however when I want to import a file I can't manage to use my custom validation to see if it's only .json. The problem is that in my Index for Booking I have a IEnumerable model for Booking and I use a BookingsUpload model to upload the file. So how can I access this BookingsUpload model inside the Index or how could i change it ? (could I combine what i do in BookingsUpload with my Booking model ?

Booking Model:

public class Booking
{
    [Required]
    [Display(Name = "Ladestand")]
    [Range(0, 100)]
    public double chargeState { get; set; }

    [Required]
    [Display(Name = "Benötigte Fahrstrecke")]
    [Range(1, 1000)]
    public double distance { get; set; }

    [Required]
    [Display(Name = "Beginn")]
    public DateTime startTime { get; set; }

    [Required]
    [Display(Name = "Ende")]
    public DateTime endTime { get; set; }

    [Required]
    [Display(Name = "Anschlusstyp")]
    [EnumDataType(typeof(ConnectorType))]
    [JsonConverter(typeof(StringEnumConverter))]
    public ConnectorType connectorType { get; set; }
}

public class BookingList
        {
            public List<Booking> BookingListObj { get; set; }
        }

BookingsUpload Model:

public class BookingsUpload
{
    [Required(ErrorMessage = "Please select a file.")]
    [DataType(DataType.Upload)]
    [MaxFileSize(1024 * 1024)]
    [AllowedExtensions(new string[] { ".json" })]
    public IFormFile File { get; set; }
}

** NEW UPDATE **:
Now Controller doesn't work as intended. Cannot add elements to List (or maybe they are added just can't display it in the View not sure):
Controller:

public class BookingController : Controller
{
    private IMemoryCache _cache;
    private string bookingsKey = "bookingsList";
    public BookingController(IMemoryCache memoryCache)
    {
        _cache = memoryCache;
    }

    public IActionResult Index()
    {
        List<Booking> bookigsList;
        _cache.TryGetValue<List<Booking>>(bookingsKey, out bookigsList);
        return View(bookigsList);
    }

    /* MVVC fucking failed :(
    public IActionResult Index()
    {
        BookingList bookingsList;
        //_cache.TryGetValue(bookingsKey, out bookingList);

        bookingsList = new BookingList();
        bookingsList.BookingListObj = new List<Booking>();

        bookingsList.BookingListObj.Add(new Booking() { chargeState = 30, distance = 150, startTime = new DateTime(2020, 8, 13, 13, 45, 0), endTime = new DateTime(2020, 8, 13, 17, 0, 0) });
        _cache.Set<List<Booking>>(bookingsKey, bookingsList.BookingListObj);

        BookingViewModel bookingViewModel = new BookingViewModel()
        {
            Bookings = bookingsList.BookingListObj
        };

        return View(bookingViewModel);
    }*/

    [HttpGet]
    public IActionResult Create()
    {
        Booking booking = new Booking();
        return View("Create", booking);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Booking booking)
    {
        List<Booking> bookingsList;

        //BookingList bookingsList;
        /*_cache.TryGetValue(bookingsKey, out bookingsList);
        BookingViewModel bookingViewModel = new BookingViewModel()
        {
            BookingList = bookingsList
        };*/

        if (!ModelState.IsValid)
        {
            return View("Create", booking);
        }
        if (!_cache.TryGetValue(bookingsKey, out bookingsList))
        {
            bookingsList = new List<Booking>();
        }

        bookingsList.Add(booking);
        _cache.Set<List<Booking>>(bookingsKey, bookingsList);

        /*BookingViewModel bookingViewModel = new BookingViewModel()
        {
            BookingList = bookingsList
        };*/

        return RedirectToAction("Index", "Booking");
    }

BookingViewModel:

public class BookingViewModel
{
    public Booking Booking { get; set; }
    public BookingList BookingList { get; set; }
    public IEnumerable<Booking> Bookings { get; set; }
    public BookingsUpload BookingsUpload { get; set; }

    public BookingViewModel()
    {
        Booking = new Booking();
        Bookings = new List<Booking>();
        BookingsUpload = new BookingsUpload();
    }
}

Booking Index:

    @model WebApplication.ViewModels.BookingViewModel

@{
    ViewData["Title"] = "Index";
}

Übersicht aller Buchungen

            Erstelle Buchung

                Export

                <form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">

                            <input type="file" name="file" onchange="this.form.submit()" />
                            Import/validation_bc_fuck_MVC

                </form>
                Import + validation

        @if (Model.Booking != null)
        {

                            @Html.DisplayNameFor(model => Model.Booking.chargeState) %

                            @Html.DisplayNameFor(model => Model.Booking.distance) (km)

                            @Html.DisplayNameFor(model => Model.Booking.connectorType)

                            @Html.DisplayNameFor(model => Model.Booking.startTime)

                            @Html.DisplayNameFor(model => Model.Booking.endTime)

                    @foreach (var item in Model.Bookings)
                    {

                                @Html.DisplayFor(modelItem => item.chargeState)

                                @Html.DisplayFor(modelItem => item.distance)

                                @Html.DisplayFor(modelItem => item.connectorType)

                                @Html.DisplayFor(modelItem => item.startTime)

                                @Html.DisplayFor(modelItem => item.endTime)

                    }

        }
        else
        {

Es sind keine Buchungen vorhanden

        }

So the Import label is the problem because I cant access the File from BookingsUpload to make the span asp-validation-for="File" but with the Import button I managed to go to a different View with only this code below and there the validation works because there I can use the BookingsUpload model:

    @model WebApplication.Models.BookingsUpload;

@{
    ViewData["Title"] = "Import";
}

Import

<form asp-controller="Booking" asp-action="Import" method="post" enctype="multipart/form-data">

            <input asp-for="File" type="file" name="file" onchange="this.form.submit()" />
            Import

</form>

Body:
Add a Constructor to your class where you initialize your objects so it wont be null

public class BookingViewModel
{
    public BookingViewModel()
    {
        Booking = new Booking();
        Bookings = new IEnumerable<Booking>();
        BookingsUpload = new BookingsUpload();
    }
    public Booking Booking { get; set; }
    public IEnumerable<Booking> Bookings { get; set; }
    public BookingsUpload BookingsUpload { get; set; }
}


来源: stackexchange

问:
python. combine two lists in the same lenth
The problem is to build extended lists out of using two same length lists.
for example, there is

```<code>qq=['a','b','c']
ww=['d','e','f']

my_function(qq,ww)

#I want to see output like:
output = [['a','b','c'],['a','b','f'],['a','e','c'],['a','e','f'],['d','e','f'],['d','e','c'],['d','b','f'],['d','b','c']]
</code>```

all the combinations of making the same length list with a constraint of:

if a is chosen then d cannot be chosen,
same logic,

if b is chosen then e cannot be chosen,

if c is chosen then f cannot be chosen.

The important thing is the elements' position in the list.

so the function takes two same length list of strings. and returns the list of the combinations.
How should I write this?

答:
Here's a recursive solution.

The base case is of course when each list has just one item and we take each list as possible output. For longer lists, you find all the possible arrangements of the lists not counting the first items, and then return those items with each of the first items.

def solve(list1, list2):
     if len(list1) != len(list2):
         throw ValueError("Lists should be same length")
     if len(list1) == 0:
         return []
     if len(list1) == 1:
         return [[list1[0], list2[0]]
     children = solve(list1[1:], list2[1:])
     return [[list1[0]] + child for child in children] + [[list2[0]] + child for child in children]]

```

ContentLicense: CC BY-SA 4.0

Body:
The problem is to build extended lists out of using two same length lists.
for example, there is

qq=['a','b','c']
ww=['d','e','f']

my_function(qq,ww)

#I want to see output like:
output = [['a','b','c'],['a','b','f'],['a','e','c'],['a','e','f'],['d','e','f'],['d','e','c'],['d','b','f'],['d','b','c']]

all the combinations of making the same length list with a constraint of:

if a is chosen then d cannot be chosen,
same logic,

if b is chosen then e cannot be chosen,

if c is chosen then f cannot be chosen.

The important thing is the elements' position in the list.

so the function takes two same length list of strings. and returns the list of the combinations.
How should I write this?


问:
mysqli, OOP vs Procedural
I just saw this for the first time.   I had no idea you can instantiate a mysqli class by doing something like

```<code>new mysqli( $host, $username, $password, $db );
</code>```

This is brand new to me...Every tutorial I have seen online or in books when connecting to database does something like this:

```<code>$conn = mysqli_connect( $host, $username, $password, $db );

if ( !$conn ) {
    die( 'Sorry, could not connect');
}
</code>```

Is there a reason why most tutorials do it the procedural way?  Even in tutorials I have seen on creating a separate database class, tell me to use the procedural style code...

What's the difference with mysqli procedural vs oop? Is there any?  Do I have to install any extensions of some kind or can I just start using in my code?  Total newb here, so not really sure.

Also, when is it a good idea to use PDO vs mysqli?  Is PDO used most commonly by developers that work on large scale Enterprise applications?  Or is simply a matter of preference.

Thanks for any help...

learning php has quickly become addictive...I just want to know more and more.

答:
Most mysqli_* functions are aliases of the object methods (PHP internally allows that easily with an C macro, so many extensions use that approach). But the availability is also for familiarity, so users of the old mysql functions have an easier time adopting to the new interface. Using the OOP or procedural interface is really just style/preference.

PDO is generally preferred nowadays, but it doesn't provide many mysql-specific features. So there might still be some use cases for the mysqli extension.

ContentLicense: CC BY-SA 3.0

Title: mysqli, OOP vs Procedural

Body:
I just saw this for the first time.   I had no idea you can instantiate a mysqli class by doing something like

new mysqli( $host, $username, $password, $db );

This is brand new to me...Every tutorial I have seen online or in books when connecting to database does something like this:

$conn = mysqli_connect( $host, $username, $password, $db );

if ( !$conn ) {
    die( 'Sorry, could not connect');
}

Is there a reason why most tutorials do it the procedural way?  Even in tutorials I have seen on creating a separate database class, tell me to use the procedural style code...

What's the difference with mysqli procedural vs oop? Is there any?  Do I have to install any extensions of some kind or can I just start using in my code?  Total newb here, so not really sure.

Also, when is it a good idea to use PDO vs mysqli?  Is PDO used most commonly by developers that work on large scale Enterprise applications?  Or is simply a matter of preference.

Thanks for any help...

learning php has quickly become addictive...I just want to know more and more.


问:
How do I configure AWS application load balancers to go beyond the 25 SSL certificate limit
AWS Application load balancers have a 25 SSL certificate installation limit.

I want to configure my elastic beanstalk environment, possibly with multiple load balancers so that I can go beyond this limit and install more certificates, 25 per load balancer. I believe this is a useful question for most SaaS developers.

Has anyone produced a configuration that allows for more than 25 SSL certificates / domains?

One way might be such that for hosts that are not installed on the HTTPS listener on port 443, I might create a rule that forwards to e.g. say port 40443, however, I would need to add a rule for each new SSL certificate/host/tenant. Furthermore, I am unsure whether the browser clients will notice the port change and go to domain.com:40443 rather than hide the port.

Anyway, if you have other solutions I would love to hear.

The limit is per "listener" so I tried to create a new listener on the same port 443 but this is not allowed.

Here is the reference for limits page: https://docs.aws.amazon.com/elasticloadbalancing/latest/application/load-balancer-limits.html

答:
I don't think there is a way to increase the limit right now.

This author did suggest a work around by using multiple ALBs talking to a NLB.

https://cloudonaut.io/more-than-25-ssl-certificates-with-ecs/


答:
Both the above answers are wrong, the first one will fail on

```<code>start 2020-05-27 19:15:13.738000 end 2020-05-27 20:07:14.969000 ticketid 414
</code>```

The second one will fail on many things. Here was my working solution:

```<code>WITH interal_periods AS (
    WITH intervals AS (
        ...
    )
    SELECT t.start_time,
           t.end_time,
           t.ticketid,
           t.validitybegin,
           t.validityend,
           LEAST(extract(EPOCH FROM t.end_time - validitybegin) / 60, 60) AS minutes_after_start_of_hour,
           CASE
               WHEN extract(EPOCH FROM t.end_time - validityend) / 60 > 0
                   THEN extract(EPOCH FROM t.end_time - validityend) / 60
               ELSE 0
               END                                                        AS minutes_before_end_of_hour
    FROM (
             SELECT i.*, generate_series AS start_time, generate_series + INTERVAL '1 hour' AS end_time
             FROM intervals i
                      CROSS JOIN generate_series
                 (date_trunc('hour', i.validitybegin::timestamp)
                 , date_trunc('hour', i.validityend::timestamp)
                 , '1 hour'::interval)
         ) t
)
SELECT start_time,
       end_time,
       ticketid,
       validitybegin,
       validityend,
       minutes_after_start_of_hour - minutes_before_end_of_hour as overlap
FROM interal_periods
</code>```

Title: SQL: Split time interval into intersects of one hour

Body:
I am new to SQL, where I am trying to split time intervals into multiple rows of one hour, together with an indicator of how many minutes the interval overlaps each hour.

My data:

    validitybegin    |     validityend     |     ticketid     |
---------------------+---------------------+------------------+
 2017-08-31 12:22:04 | 2017-08-31 13:08:56 |       ID1        |
 2017-08-31 13:09:02 | 2017-08-31 16:46:51 |       ID2        |
 2017-08-31 13:09:10 | 2017-08-31 14:09:10 |       ID3        |

What I would like:

       start         |        end          |   overlap   |     ticketid     |
---------------------+---------------------+-------------+------------------+
 2017-08-31 12:00:00 | 2017-08-31 13:00:00 |     38      |       ID1        |
 2017-08-31 13:00:00 | 2017-08-31 14:00:00 |      9      |       ID1        |
 2017-08-31 13:00:00 | 2017-08-31 14:00:00 |     51      |       ID2        |
 2017-08-31 14:00:00 | 2017-08-31 15:00:00 |     60      |       ID2        |
 2017-08-31 15:00:00 | 2017-08-31 16:00:00 |     60      |       ID2        |
 2017-08-31 16:00:00 | 2017-08-31 17:00:00 |     47      |       ID2        |
 2017-08-31 13:00:00 | 2017-08-31 14:00:00 |     51      |       ID3        |
 2017-08-31 14:00:00 | 2017-08-31 15:00:00 |      9      |       ID3        |

What would be the easiest/fastest way to do this?

Body:
Both the above answers are wrong, the first one will fail on

start 2020-05-27 19:15:13.738000 end 2020-05-27 20:07:14.969000 ticketid 414

The second one will fail on many things. Here was my working solution:

WITH interal_periods AS (
    WITH intervals AS (
        ...
    )
    SELECT t.start_time,
           t.end_time,
           t.ticketid,
           t.validitybegin,
           t.validityend,
           LEAST(extract(EPOCH FROM t.end_time - validitybegin) / 60, 60) AS minutes_after_start_of_hour,
           CASE
               WHEN extract(EPOCH FROM t.end_time - validityend) / 60 > 0
                   THEN extract(EPOCH FROM t.end_time - validityend) / 60
               ELSE 0
               END                                                        AS minutes_before_end_of_hour
    FROM (
             SELECT i.*, generate_series AS start_time, generate_series + INTERVAL '1 hour' AS end_time
             FROM intervals i
                      CROSS JOIN generate_series
                 (date_trunc('hour', i.validitybegin::timestamp)
                 , date_trunc('hour', i.validityend::timestamp)
                 , '1 hour'::interval)
         ) t
)
SELECT start_time,
       end_time,
       ticketid,
       validitybegin,
       validityend,
       minutes_after_start_of_hour - minutes_before_end_of_hour as overlap
FROM interal_periods


答:
You want, from your 2 lists, to do the product of the pairs [a,d] * [b,e] * [c,f]. Using zip to pair, and product to combine them all makes the whole to

take just one element of each pair, so one element per indice, with zip

build all the combinations betwween the pairs, with product

```<code>from itertools import product
def custom_product(valuesA, valuesB):
    return list(product(*zip(valuesA, valuesB))) # return list of tuple

def custom_product(valuesA, valuesB):
    return list(map(list, product(*zip(valuesA, valuesB)))) # return list of list
</code>```

CODE DEMO

Title: python. combine two lists in the same lenth

Body:
You want, from your 2 lists, to do the product of the pairs [a,d] * [b,e] * [c,f]. Using zip to pair, and product to combine them all makes the whole to

take just one element of each pair, so one element per indice, with zip

build all the combinations betwween the pairs, with product

from itertools import product
def custom_product(valuesA, valuesB):
    return list(product(*zip(valuesA, valuesB))) # return list of tuple

def custom_product(valuesA, valuesB):
    return list(map(list, product(*zip(valuesA, valuesB)))) # return list of list

CODE DEMO


问:
Java based Microcontrollers?
I have been looking into micro-controllers and was wondering if the majority of them are C/C++ based? I am quite proficient in java and want to ask you guys if anyone knows of a good cost efficient, java-based micro-controller I could look into.

All answers are appreciated!

答:
You can look at Java on a Chip (JoC Module) is the java programmable controller-module

JoC have a reference Board Javaino for easy development

Also Demmel iLCD product have the Java VM on board, it's a smart display with JVM

Title: Java based Microcontrollers?


问:
How to apply a .fillna() to a filtered dataframe?
I am learning pandas using a dataset of players from the womans world cup.

I want to apply a .fillna() on the results of the following filter of the main dataframe:

```<code>df[(df["pos"] == "GK") & (df["goals"].isnull())]
</code>```

How can I apply:

```<code>fillna(0, inplace=True)
</code>```

To the above filter, , on the 'goals' column.

I did use the below code but when I apply it, it runs but doesn't seem to work:

```<code>df.loc[df["pos"] == "GK"].loc[df["goals"].isnull()].loc[:,"goals"].fillna(0, inplace=True)
</code>```

答:
The first line selects the index and you know the column, so just use one loc and it should be fine:

df.loc[(df["pos"] == "GK") & (df["goals"].isnull()), 'goals'].fillna(0, inplace=True)

update:

So it seems pandas returns a copy and inplace doesn't really do anything there. However, you don't want to assign it to all of your dataframe.
Since you are already filtering for nan values, an easier way is to just assign the value directly.
df.loc[(df["pos"] == "GK") & (df["goals"].isnull()), 'goals'] = 0
This worked fine on my computer, hope it solves your problem.

Body:
I am learning pandas using a dataset of players from the womans world cup.

I want to apply a .fillna() on the results of the following filter of the main dataframe:

df[(df["pos"] == "GK") & (df["goals"].isnull())]

How can I apply:

fillna(0, inplace=True)

To the above filter, , on the 'goals' column.

I did use the below code but when I apply it, it runs but doesn't seem to work:

df.loc[df["pos"] == "GK"].loc[df["goals"].isnull()].loc[:,"goals"].fillna(0, inplace=True)


问:
Predicting with lmer: errors and missing p-values
In an experiment, female fish were exposed to two levels of photoperiod (Ambient & Compressed), two levels of temperature (4 & 7). They were in four tanks (two tanks for each photoperiod, one tank for each temperature within photoperiod). There were nine samplings denoted by time_date in the data. Among other responses is "k". My interest is on the effects of photoperiod, temperature and time_date on "k".
Challenges faced: Unbalanced design (one photoperiod or temperature level not sampled during a sampling), pseudo-replication (each tank is a treatment (temperature masked within photoperiod)). with some reading, I came across the mixed models. I have tried with lmer (more importantly: I am not sure if am right) and fell into warnings and outputs with no p-values. I appreciate your help. Thank you in advance.

Here is the sample data

```<code>fem.fish <- structure(list(time_date = structure(c(8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 10L, 10L, 10L, 10L, 11L, 11L, 11L, 11L, 11L, 11L, 11L,
11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L,
12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L,
12L, 12L, 12L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 13L, 13L,
13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L,
13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L,
14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L,
14L, 14L, 14L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L,
15L, 15L, 15L, 15L, 15L, 15L, 16L, 16L, 16L, 16L, 16L, 16L, 16L,
16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L), .Label = c("30-Jan-18",
"11-Apr-18", "13-Jun-18", "07-Aug-18", "19-Sep-18", "30-Oct-18",
"28-Nov-18", "03-Jan-19", "17-Jan-19", "31-Jan-19", "14-Feb-19",
"28-Feb-19", "14-Mar-19", "27-Mar-19", "10-Apr-19", "24-Apr-19"
), class = "factor"), photo = structure(c(1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Ambient",
"Compress"), class = "factor"), temp = structure(c(2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("4",
"7"), class = "factor"), tank = structure(c(2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("T1",
"T2", "T3", "T4"), class = "factor"), k = c(5.041791145, 5.408503999,
5.535282299, 5.346402317, 5.376649977, 5.072021484, 6.097412109,
4.390658006, 5.13676712, 4.472827193, 5.381892125, 4.882544582,
4.655393586, 5.435528121, 4.985185185, 4.548431822, 5.041791145,
5.408503999, 5.535282299, 5.346402317, 5.376649977, 5.072021484,
6.097412109, 4.390658006, 5.13676712, 4.472827193, 5.381892125,
4.882544582, 4.655393586, 5.435528121, 4.985185185, 4.548431822,
5.517125816, 4.772205603, 5.928149807, 4.152323266, 4.666037968,
4.638984928, 4.044444444, 4.720296599, 5.315500686, 4.967790359,
3.520804755, 4.722326417, 5.051895044, 4.807450844, 5.096461818,
5.28703008, 5.653368614, 6.357164944, 3.979492188, 3.928861374,
5.632685221, 5.264668498, 5.281464786, 5.387205387, 4.332381668,
5.250388878, 4.580237638, 4.650926114, 5.65951009, 4.401587625,
5.194587481, 4.184813255, 4.44738449, 5.829977261, 4.331985587,
4.827988338, 4.022222222, 3.672891297, 5.148148148, 4.068381688,
5.71922963, 4.566763848, 5.330442907, 2.422536369, 5.346580575,
4.971865289, 5.018922289, 5.513702624, 4.432146456, 5.692296224,
4.738120151, 4.896057489, 5.50365439, 5.249023438, 5.737818961,
4.260276996, 5.242507722, 4.580758017, 5.021888504, 5.013662642,
4.308286338, 5.50840192, 4.732342764, 4.672289386, 5.715557782,
3.827088497, 4.632069971, 4.935541824, 4.008746356, 4.963859809,
4.836806618, 4.46244856, 4.839677641, 4.498269896, 4.88357943,
4.984069185, 4.596844478, 5.196200195, 5.165529005, 14.74622771,
5.397084548, 7.983198678, 5.691090246, 5.707491082, 5.187172012,
6.297376093, 4.647178889, 4.282407407, 4.333496094, 4.773656052,
4.770999725, 4.092207407, 3.917638484, 5.193905817, 3.704833984,
5.571239611, 4.226680384, 3.65230095, 4.78515625, 5.603027344,
4.159218067, 4.719370009, 4.437016946, 4.407713499, 4.284050303,
4.676783265, 4.311689337, 4.540625, 4.864470022, 4.668176455,
5.221193416, 4.997084123, 4.112752873, 5.587217586, 6.045051626,
4.605417744, 4.35030714, 5.185252617, 4.752696927, 4.446670562,
4.268256569, 4.30372087, 4.025205761, 5.696474074, 4.068342788,
3.5212701, 4.544646911, 5.212620027, 5.31978738, 4.879910442,
4.606482493, 4.33502906, 5.294067215, 5.770262391, 4.264308136,
4.501028807, 2.944958848, 4.180638577, 4.120435057, 3.833076111,
4.496793003, 4.232167131, 3.783896334, 5.070553936, 4.825776352,
4.643534043, 6.318587106, 5.66205358, 5.194631597, 4.72557037,
4.195096521, 4.956238551, 3.503093444, 5.24857851, 4.792524005,
4.44229595, 5.285131195, 4.335878892, 4.170953361, 4.045779268
)), row.names = c(NA, -192L), class = "data.frame")
</code>```

What I tried and the first warning

```<code>    fit1 <- lmer(k ~ 0 + photo*temp*time_date + (1|tank), data = fem.fish, REML = FALSE)

fixed-effect model matrix is rank deficient so dropping 12 columns / coefficients
boundary (singular) fit: see ?isSingular
</code>```

My summary and another warning on correlation matrix

```<code>summary(fit1)
Linear mixed model fit by maximum likelihood  ['lmerMod']
Formula: k ~ 0 + photo * temp * time_date + (1 | tank)
   Data: fem.fish

     AIC      BIC   logLik deviance df.resid
   551.2    635.9   -249.6    499.2      166

Scaled residuals:
    Min      1Q  Median      3Q     Max
-2.7467 -0.4380 -0.0447  0.3663  9.7226

Random effects:
 Groups   Name        Variance Std.Dev.
 tank     (Intercept) 0.0000   0.0000
 Residual             0.7883   0.8879
Number of obs: 192, groups:  tank, 4

Fixed effects:
                                         Estimate Std. Error t value
photoAmbient                            5.284e+00  3.139e-01  16.832
photoCompress                           4.937e+00  3.139e-01  15.728
temp7                                  -1.218e-14  4.439e-01   0.000
time_date17-Jan-19                     -9.116e-02  4.439e-01  -0.205
time_date31-Jan-19                     -9.798e-02  4.439e-01  -0.221
time_date14-Feb-19                      1.264e-01  4.439e-01   0.285
time_date28-Feb-19                     -3.986e-01  4.439e-01  -0.898
time_date14-Mar-19                      3.655e-01  4.439e-01   0.823
time_date27-Mar-19                     -3.979e-01  4.439e-01  -0.896
time_date10-Apr-19                     -4.122e-01  4.439e-01  -0.929
time_date24-Apr-19                     -2.184e-01  4.439e-01  -0.492
photoCompress:temp7                     8.874e-15  6.278e-01   0.000
photoCompress:time_date31-Jan-19       -2.957e-01  6.278e-01  -0.471
photoCompress:time_date28-Feb-19        1.575e+00  6.278e-01   2.509
photoCompress:time_date14-Mar-19       -6.073e-01  6.278e-01  -0.967
temp7:time_date17-Jan-19               -4.121e-02  6.278e-01  -0.066
temp7:time_date31-Jan-19                2.382e-01  6.278e-01   0.379
temp7:time_date14-Feb-19               -2.024e-01  6.278e-01  -0.322
temp7:time_date28-Feb-19               -1.441e+00  6.278e-01  -2.295
temp7:time_date14-Mar-19               -1.104e+00  6.278e-01  -1.759
temp7:time_date27-Mar-19               -4.306e-01  6.278e-01  -0.686
temp7:time_date10-Apr-19               -7.885e-01  6.278e-01  -1.256
temp7:time_date24-Apr-19               -5.872e-01  6.278e-01  -0.935
photoCompress:temp7:time_date14-Mar-19  9.077e-01  8.879e-01   1.022

Correlation matrix not shown by default, as p = 24 > 12.
Use print(x, correlation=TRUE)  or
    vcov(x)        if you need it

fit warnings:
fixed-effect model matrix is rank deficient so dropping 12 columns / coefficients
convergence code: 0
boundary (singular) fit: see ?isSingular
</code>```

My understanding on t-values is not good at all, so I cannot establish whether there are significant effects or even whether the interactions are significant or not.

I will appreciate your suggestions on the modelling (Fitting the right model?) and more of what you find useful

Thank you so much all.

答:
I have used your data for the following example. I think due to the fact that all your terms are categorical, you get the rank deficient model. I'd suggest you use time as continuous predictor, thereby you get rid of the rank-deficiency warning.

library(lme4)
library(parameters)
library(performance)

levels(fem.fish$time_date) <- 1:nlevels(fem.fish$time_date)
fem.fish$time_date <- as.numeric(fem.fish$time_date)

fit1 <- lmer(
  k ~ 1 + photo * temp * time_date + (1 | tank),
  data = fem.fish,
  REML = FALSE
)
#> boundary (singular) fit: see ?isSingular
```

<p>The second warning about the singular fit (now the first, and only warning) is because you literally have no variability in your outcome across the different groups (indicated by <code>tank</code>). This means that the random effects model here gives you not much more benefit than a simple linear model.</p>

<pre class="lang-r prettyprint-override"><code>ranef(fit1)
#> $tank
#>    (Intercept)
#> T1           0
#> T2           0
#> T3           0
#> T4           0
#>
#> with conditional variances for "tank"
</code>```

Finally, you could use the packages parameters and performance to get comprehensive model summaries (including different p-value approximations like Satterthwaite or Kenward-Roger, standardized parameters or (cluster) robust standard errors) or model fit indices (like r2).

parameters::model_parameters(fit1)
#> Parameter                                 | Coefficient |   SE |        95% CI |     t |  df |      p
#> -----------------------------------------------------------------------------------------------------
#> (Intercept)                               |        5.56 | 0.61 | [ 4.36, 6.76] |  9.06 | 182 | < .001
#> photo [Compress]                          |       -1.46 | 1.04 | [-3.50, 0.58] | -1.41 | 182 | 0.160
#> temp [7]                                  |        0.69 | 0.94 | [-1.16, 2.53] |  0.73 | 182 | 0.467
#> time_date                                 |       -0.04 | 0.05 | [-0.13, 0.06] | -0.74 | 182 | 0.461
#> photo [Compress] * temp [7]               |        0.73 | 1.52 | [-2.24, 3.70] |  0.48 | 182 | 0.631
#> photo [Compress] * time_date              |        0.12 | 0.09 | [-0.06, 0.31] |  1.35 | 182 | 0.178
#> temp [7] * time_date                      |       -0.09 | 0.07 | [-0.23, 0.05] | -1.29 | 182 | 0.198
#> (photo [Compress] * temp [7]) * time_date |       -0.07 | 0.13 | [-0.33, 0.19] | -0.52 | 182 | 0.604

performance::r2(fit1)
#> Warning: Can't compute random effect variances. Some variance components equal zero.
#>   Solution: Respecify random structure!
#> Random effect variances not available. Returned R2 does not account for random effects.
#> # R2 for Mixed Models
#>
#>   Conditional R2: NA
#>      Marginal R2: 0.088
```

<p>Now that your time variable is continuous, you may think about a non-linear relationship of the time trend. You could use the <em>spline</em> package to model this, and ggeffects to get effects plots. This works, of course, for the model with linear time trend as well as other curvilinear time trends.</p>

<pre class="lang-r prettyprint-override"><code>library(ggeffects)
pr <- ggpredict(fit1, c("time_date", "photo", "temp"))
plot(pr)
</code>```

library(splines)
fit2 <- lmer(
  k ~ 1 + photo * temp * bs(time_date) + (1 | tank),
  data = fem.fish,
  REML = FALSE
)
#> boundary (singular) fit: see ?isSingular

pr <- ggpredict(fit2, c("time_date [all]", "photo", "temp"))
plot(pr)
```

Hope that helps!

Body:
In an experiment, female fish were exposed to two levels of photoperiod (Ambient & Compressed), two levels of temperature (4 & 7). They were in four tanks (two tanks for each photoperiod, one tank for each temperature within photoperiod). There were nine samplings denoted by time_date in the data. Among other responses is "k". My interest is on the effects of photoperiod, temperature and time_date on "k".
Challenges faced: Unbalanced design (one photoperiod or temperature level not sampled during a sampling), pseudo-replication (each tank is a treatment (temperature masked within photoperiod)). with some reading, I came across the mixed models. I have tried with lmer (more importantly: I am not sure if am right) and fell into warnings and outputs with no p-values. I appreciate your help. Thank you in advance.

Here is the sample data

fem.fish <- structure(list(time_date = structure(c(8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 10L, 10L, 10L, 10L, 11L, 11L, 11L, 11L, 11L, 11L, 11L,
11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 11L, 12L, 12L, 12L, 12L,
12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L, 12L,
12L, 12L, 12L, 12L, 12L, 12L, 12L, 13L, 13L, 13L, 13L, 13L, 13L,
13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L,
13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L, 13L,
14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L, 14L,
14L, 14L, 14L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L, 15L,
15L, 15L, 15L, 15L, 15L, 15L, 16L, 16L, 16L, 16L, 16L, 16L, 16L,
16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L, 16L), .Label = c("30-Jan-18",
"11-Apr-18", "13-Jun-18", "07-Aug-18", "19-Sep-18", "30-Oct-18",
"28-Nov-18", "03-Jan-19", "17-Jan-19", "31-Jan-19", "14-Feb-19",
"28-Feb-19", "14-Mar-19", "27-Mar-19", "10-Apr-19", "24-Apr-19"
), class = "factor"), photo = structure(c(1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Ambient",
"Compress"), class = "factor"), temp = structure(c(2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("4",
"7"), class = "factor"), tank = structure(c(2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L), .Label = c("T1",
"T2", "T3", "T4"), class = "factor"), k = c(5.041791145, 5.408503999,
5.535282299, 5.346402317, 5.376649977, 5.072021484, 6.097412109,
4.390658006, 5.13676712, 4.472827193, 5.381892125, 4.882544582,
4.655393586, 5.435528121, 4.985185185, 4.548431822, 5.041791145,
5.408503999, 5.535282299, 5.346402317, 5.376649977, 5.072021484,
6.097412109, 4.390658006, 5.13676712, 4.472827193, 5.381892125,
4.882544582, 4.655393586, 5.435528121, 4.985185185, 4.548431822,
5.517125816, 4.772205603, 5.928149807, 4.152323266, 4.666037968,
4.638984928, 4.044444444, 4.720296599, 5.315500686, 4.967790359,
3.520804755, 4.722326417, 5.051895044, 4.807450844, 5.096461818,
5.28703008, 5.653368614, 6.357164944, 3.979492188, 3.928861374,
5.632685221, 5.264668498, 5.281464786, 5.387205387, 4.332381668,
5.250388878, 4.580237638, 4.650926114, 5.65951009, 4.401587625,
5.194587481, 4.184813255, 4.44738449, 5.829977261, 4.331985587,
4.827988338, 4.022222222, 3.672891297, 5.148148148, 4.068381688,
5.71922963, 4.566763848, 5.330442907, 2.422536369, 5.346580575,
4.971865289, 5.018922289, 5.513702624, 4.432146456, 5.692296224,
4.738120151, 4.896057489, 5.50365439, 5.249023438, 5.737818961,
4.260276996, 5.242507722, 4.580758017, 5.021888504, 5.013662642,
4.308286338, 5.50840192, 4.732342764, 4.672289386, 5.715557782,
3.827088497, 4.632069971, 4.935541824, 4.008746356, 4.963859809,
4.836806618, 4.46244856, 4.839677641, 4.498269896, 4.88357943,
4.984069185, 4.596844478, 5.196200195, 5.165529005, 14.74622771,
5.397084548, 7.983198678, 5.691090246, 5.707491082, 5.187172012,
6.297376093, 4.647178889, 4.282407407, 4.333496094, 4.773656052,
4.770999725, 4.092207407, 3.917638484, 5.193905817, 3.704833984,
5.571239611, 4.226680384, 3.65230095, 4.78515625, 5.603027344,
4.159218067, 4.719370009, 4.437016946, 4.407713499, 4.284050303,
4.676783265, 4.311689337, 4.540625, 4.864470022, 4.668176455,
5.221193416, 4.997084123, 4.112752873, 5.587217586, 6.045051626,
4.605417744, 4.35030714, 5.185252617, 4.752696927, 4.446670562,
4.268256569, 4.30372087, 4.025205761, 5.696474074, 4.068342788,
3.5212701, 4.544646911, 5.212620027, 5.31978738, 4.879910442,
4.606482493, 4.33502906, 5.294067215, 5.770262391, 4.264308136,
4.501028807, 2.944958848, 4.180638577, 4.120435057, 3.833076111,
4.496793003, 4.232167131, 3.783896334, 5.070553936, 4.825776352,
4.643534043, 6.318587106, 5.66205358, 5.194631597, 4.72557037,
4.195096521, 4.956238551, 3.503093444, 5.24857851, 4.792524005,
4.44229595, 5.285131195, 4.335878892, 4.170953361, 4.045779268
)), row.names = c(NA, -192L), class = "data.frame")

What I tried and the first warning

    fit1 <- lmer(k ~ 0 + photo*temp*time_date + (1|tank), data = fem.fish, REML = FALSE)

fixed-effect model matrix is rank deficient so dropping 12 columns / coefficients
boundary (singular) fit: see ?isSingular

My summary and another warning on correlation matrix

summary(fit1)
Linear mixed model fit by maximum likelihood  ['lmerMod']
Formula: k ~ 0 + photo * temp * time_date + (1 | tank)
   Data: fem.fish

     AIC      BIC   logLik deviance df.resid
   551.2    635.9   -249.6    499.2      166

Scaled residuals:
    Min      1Q  Median      3Q     Max
-2.7467 -0.4380 -0.0447  0.3663  9.7226

Random effects:
 Groups   Name        Variance Std.Dev.
 tank     (Intercept) 0.0000   0.0000
 Residual             0.7883   0.8879
Number of obs: 192, groups:  tank, 4

Fixed effects:
                                         Estimate Std. Error t value
photoAmbient                            5.284e+00  3.139e-01  16.832
photoCompress                           4.937e+00  3.139e-01  15.728
temp7                                  -1.218e-14  4.439e-01   0.000
time_date17-Jan-19                     -9.116e-02  4.439e-01  -0.205
time_date31-Jan-19                     -9.798e-02  4.439e-01  -0.221
time_date14-Feb-19                      1.264e-01  4.439e-01   0.285
time_date28-Feb-19                     -3.986e-01  4.439e-01  -0.898
time_date14-Mar-19                      3.655e-01  4.439e-01   0.823
time_date27-Mar-19                     -3.979e-01  4.439e-01  -0.896
time_date10-Apr-19                     -4.122e-01  4.439e-01  -0.929
time_date24-Apr-19                     -2.184e-01  4.439e-01  -0.492
photoCompress:temp7                     8.874e-15  6.278e-01   0.000
photoCompress:time_date31-Jan-19       -2.957e-01  6.278e-01  -0.471
photoCompress:time_date28-Feb-19        1.575e+00  6.278e-01   2.509
photoCompress:time_date14-Mar-19       -6.073e-01  6.278e-01  -0.967
temp7:time_date17-Jan-19               -4.121e-02  6.278e-01  -0.066
temp7:time_date31-Jan-19                2.382e-01  6.278e-01   0.379
temp7:time_date14-Feb-19               -2.024e-01  6.278e-01  -0.322
temp7:time_date28-Feb-19               -1.441e+00  6.278e-01  -2.295
temp7:time_date14-Mar-19               -1.104e+00  6.278e-01  -1.759
temp7:time_date27-Mar-19               -4.306e-01  6.278e-01  -0.686
temp7:time_date10-Apr-19               -7.885e-01  6.278e-01  -1.256
temp7:time_date24-Apr-19               -5.872e-01  6.278e-01  -0.935
photoCompress:temp7:time_date14-Mar-19  9.077e-01  8.879e-01   1.022

Correlation matrix not shown by default, as p = 24 > 12.
Use print(x, correlation=TRUE)  or
    vcov(x)        if you need it

fit warnings:
fixed-effect model matrix is rank deficient so dropping 12 columns / coefficients
convergence code: 0
boundary (singular) fit: see ?isSingular

My understanding on t-values is not good at all, so I cannot establish whether there are significant effects or even whether the interactions are significant or not.

I will appreciate your suggestions on the modelling (Fitting the right model?) and more of what you find useful

Thank you so much all.

Body:
I have used your data for the following example. I think due to the fact that all your terms are categorical, you get the rank deficient model. I'd suggest you use time as continuous predictor, thereby you get rid of the rank-deficiency warning.

library(lme4)
library(parameters)
library(performance)

levels(fem.fish$time_date) <- 1:nlevels(fem.fish$time_date)
fem.fish$time_date <- as.numeric(fem.fish$time_date)

fit1 <- lmer(
  k ~ 1 + photo * temp * time_date + (1 | tank),
  data = fem.fish,
  REML = FALSE
)
#> boundary (singular) fit: see ?isSingular

The second warning about the singular fit (now the first, and only warning) is because you literally have no variability in your outcome across the different groups (indicated by tank). This means that the random effects model here gives you not much more benefit than a simple linear model.

ranef(fit1)
#> $tank
#>    (Intercept)
#> T1           0
#> T2           0
#> T3           0
#> T4           0
#>
#> with conditional variances for "tank"

Finally, you could use the packages parameters and performance to get comprehensive model summaries (including different p-value approximations like Satterthwaite or Kenward-Roger, standardized parameters or (cluster) robust standard errors) or model fit indices (like r2).

parameters::model_parameters(fit1)
#> Parameter                                 | Coefficient |   SE |        95% CI |     t |  df |      p
#> -----------------------------------------------------------------------------------------------------
#> (Intercept)                               |        5.56 | 0.61 | [ 4.36, 6.76] |  9.06 | 182 | < .001
#> photo [Compress]                          |       -1.46 | 1.04 | [-3.50, 0.58] | -1.41 | 182 | 0.160
#> temp [7]                                  |        0.69 | 0.94 | [-1.16, 2.53] |  0.73 | 182 | 0.467
#> time_date                                 |       -0.04 | 0.05 | [-0.13, 0.06] | -0.74 | 182 | 0.461
#> photo [Compress] * temp [7]               |        0.73 | 1.52 | [-2.24, 3.70] |  0.48 | 182 | 0.631
#> photo [Compress] * time_date              |        0.12 | 0.09 | [-0.06, 0.31] |  1.35 | 182 | 0.178
#> temp [7] * time_date                      |       -0.09 | 0.07 | [-0.23, 0.05] | -1.29 | 182 | 0.198
#> (photo [Compress] * temp [7]) * time_date |       -0.07 | 0.13 | [-0.33, 0.19] | -0.52 | 182 | 0.604

performance::r2(fit1)
#> Warning: Can't compute random effect variances. Some variance components equal zero.
#>   Solution: Respecify random structure!
#> Random effect variances not available. Returned R2 does not account for random effects.
#> # R2 for Mixed Models
#>
#>   Conditional R2: NA
#>      Marginal R2: 0.088

Now that your time variable is continuous, you may think about a non-linear relationship of the time trend. You could use the spline package to model this, and ggeffects to get effects plots. This works, of course, for the model with linear time trend as well as other curvilinear time trends.

library(ggeffects)
pr <- ggpredict(fit1, c("time_date", "photo", "temp"))
plot(pr)

library(splines)
fit2 <- lmer(
  k ~ 1 + photo * temp * bs(time_date) + (1 | tank),
  data = fem.fish,
  REML = FALSE
)
#> boundary (singular) fit: see ?isSingular

pr <- ggpredict(fit2, c("time_date [all]", "photo", "temp"))
plot(pr)

Hope that helps!


问:
Why is this gif not showing up? (html)
So I would like to have the background of the body be one gif that fills the entire thing. It won't show up.</p>

```<code><style type="text/css">
    body{
        width:100vw;
        height:100vh;
        background-image: url("The More You Know1.gif");
        background-size: cover;
    }
</style>
</code>```

答:
Spaces don't work in the title of assets. Replace all spaces in the image name with %20 in your CSS, or change the file name to feature underscores or hyphens in the place of each space.

Fix #1

```<code>background-image: url("The%20More%20You%20Know1.gif");
</code>```

Fix #2

Change the file name to TheMoreYouKnow.gif and update your CSS accordingly.

If the file still doesn't load, check your file structure to make sure that your GIF is located in the same directory as your index.html file. If it isn't, you need to navigate to it in your css like this:

```<code>background-image: url("/images/The%20More%20You%20Know1.gif");
</code>```

Title: Why is this gif not showing up? (html)

Body:
Spaces don't work in the title of assets. Replace all spaces in the image name with %20 in your CSS, or change the file name to feature underscores or hyphens in the place of each space.

Fix #1

background-image: url("The%20More%20You%20Know1.gif");

Fix #2

Change the file name to TheMoreYouKnow.gif and update your CSS accordingly.

If the file still doesn't load, check your file structure to make sure that your GIF is located in the same directory as your index.html file. If it isn't, you need to navigate to it in your css like this:

background-image: url("/images/The%20More%20You%20Know1.gif");


问:
Combinging a PHP script with another PHP file, jQuery and HTML
I have a PHP search suggestion script which uses a MySQL database as its' back-end and jQuery to push the content to the search box page. The PHP is currently in suggest.php and my search box is on index.php. I want to put the PHP script from suggest.php into the index.php script code but it doesn't seem to work. Why could this be?

Here is my code for suggest.php:

```<code><?php

$database=new mysqli('localhost','username','password','database');

if(isset($_POST['query'])){
$query=$database->real_escape_string($_POST['query']);
            if(strlen($query)>0){
                $suggestions=$database->query("SELECT name, value FROM search WHERE name LIKE '%".$query."%' ORDER BY value DESC LIMIT 5");
                if($suggestions){
                    echo '<ul id="suggest">';
                    while($result=$suggestions->fetch_object()){
                        echo '<li>'.$result->name.'</li>';
                    }
                    echo '</ul>';
                }
            }
        }
?>
</code>```

Here is my code for index.php:

```<code><script type='text/javascript' src='js/jquery.js'></script>
<script type='text/javascript'>function lookup(a){if (a.length==0){$("#suggestions").hide();} else {$.post("suggest.php",{query:"" + a + ""},function (b){$("#suggestions").html(b).show();})}};</script>

<form id='search' method='post'>
<input type='text' id='query' onkeyup='lookup(this.value);'>
<div id='suggestions'></div>
</form>
</code>```

答:
It looks like index.php creates the interface your users use, but suggest.php returns the lookup suggestions.  You don't want another copy of the interface coming back when you're trying to get the lookup suggestions, so you can't call index.php in place of suggest.php

Also, index.php is not really a php file, at least from what you've posted.  It might as well be index.html

Body:
I have a PHP search suggestion script which uses a MySQL database as its' back-end and jQuery to push the content to the search box page. The PHP is currently in suggest.php and my search box is on index.php. I want to put the PHP script from suggest.php into the index.php script code but it doesn't seem to work. Why could this be?

Here is my code for suggest.php:

<?php

$database=new mysqli('localhost','username','password','database');

if(isset($_POST['query'])){
$query=$database->real_escape_string($_POST['query']);
            if(strlen($query)>0){
                $suggestions=$database->query("SELECT name, value FROM search WHERE name LIKE '%".$query."%' ORDER BY value DESC LIMIT 5");
                if($suggestions){
                    echo '
';
                    while($result=$suggestions->fetch_object()){
                        echo '
'.$result->name.'
';
                    }
                    echo '
';
                }
            }
        }
?>

Here is my code for index.php:

<form id='search' method='post'>
<input type='text' id='query' onkeyup='lookup(this.value);'>

</form>


问:
Plotting Categorical by Color
I am plotting a segmentation, and running into an issue where my categorical values are only showing up one color. Any advice? </p>

```<code>    [![fig = plt.figure(figsize = (20,10))
ax = fig.add_subplot(1,1,1)
ax.set_xlabel('Sentiment Score', fontsize = 15)
ax.set_ylabel('Star Review', fontsize = 15)
ax.set_title('Heinz Segmentation', fontsize = 20)

targets = \['Sugar/ Healthy Positives', 'Sugar/ Healthy Negatives', 'Price/ Value Positives', 'Price/ Value Negatives', 'Purists Positives', 'Purists Negatives'\]
colors = \['r', 'g', 'b', 'c', 'm', 'y'\]
for target, color in zip(targets,colors):
    ax.scatter(df.Compound,df.StarsInt
               , c = color
               , s = 200
              ,alpha = .5)
ax.legend(targets, prop={'size': 14})
ax.grid()][1]][1]
</code>```

答:
IIUC, you have a problem in the legends. You forgot to pass the legend while plotting</p>

```<code>for target, color in zip(targets,colors):
    ax.scatter(df.Compound,df.StarsInt, c=color,
               s = 200,alpha = .5,
               label=target) # <--- pass the label to show in legend
</code>```

Title: Plotting Categorical by Color

Body:
I am plotting a segmentation, and running into an issue where my categorical values are only showing up one color. Any advice?

    [![fig = plt.figure(figsize = (20,10))
ax = fig.add_subplot(1,1,1)
ax.set_xlabel('Sentiment Score', fontsize = 15)
ax.set_ylabel('Star Review', fontsize = 15)
ax.set_title('Heinz Segmentation', fontsize = 20)

targets = \['Sugar/ Healthy Positives', 'Sugar/ Healthy Negatives', 'Price/ Value Positives', 'Price/ Value Negatives', 'Purists Positives', 'Purists Negatives'\]
colors = \['r', 'g', 'b', 'c', 'm', 'y'\]
for target, color in zip(targets,colors):
    ax.scatter(df.Compound,df.StarsInt
               , c = color
               , s = 200
              ,alpha = .5)
ax.legend(targets, prop={'size': 14})
ax.grid()][1]][1]

Body:
IIUC, you have a problem in the legends. You forgot to pass the legend while plotting

for target, color in zip(targets,colors):
    ax.scatter(df.Compound,df.StarsInt, c=color,
               s = 200,alpha = .5,
               label=target) # <--- pass the label to show in legend


问:
Error with plotting graphs using matplotlib
I have the following command:

```<code>#plot data
ax = plt.gca()
datamax.plot(kind='line',x='Date',y='Data_Value',color='red',ax=ax)
datamin.plot(kind='line',x='Date',y='Data_Value', color='blue',ax=ax)
datamax.plot(kind='scatter',x='Date',y='breakup',color='red',ax=ax)
datamin.plot(kind='scatter',x='Date',y='breakdown', color='blue',ax=ax)
plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),
          fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
plt.show()
</code>```

However, I keep getting the error: KeyError: 'Date'

The dataframe datamax looks like this:

```<code>   Date           ID Element  Data_Value  datamax  breakup
0     2005-01-01  USW00094889    TMAX         156     11.0      NaN
1     2005-01-02  USW00094889    TMAX         139     39.0      NaN
2     2005-01-03  USW00094889    TMAX         133     39.0      NaN
3     2005-01-04  USW00094889    TMAX          39     44.0     44.0
4     2005-01-05  USW00094889    TMAX          33     28.0      NaN
5     2005-01-06  USW00094889    TMAX           0     33.0     33.0
6     2005-01-07  USW00094889    TMAX           6    -67.0      NaN
7     2005-01-08  USW00094889    TMAX          17    -82.0      NaN
8     2005-01-09  USW00094889    TMAX          28    -66.0      NaN
9     2005-01-10  USW00094889    TMAX          44    -71.0      NaN
10    2005-01-11  USW00094889    TMAX          44      6.0      NaN
11    2005-01-12  USW00094889    TMAX         139      6.0      NaN
12    2005-01-13  USW00094889    TMAX         161      0.0      NaN
13    2005-01-14  USW00094889    TMAX         150    -56.0      NaN
14    2005-01-15  USW00094889    TMAX         -33     -5.0     -5.0
15    2005-01-16  USW00094889    TMAX         -33      6.0      6.0
16    2005-01-17  USW00094889    TMAX         -50     78.0     78.0
17    2005-01-18  USW00094889    TMAX         -33     83.0     83.0
18    2005-01-19  USW00094889    TMAX          11     67.0     67.0
19    2005-01-20  USW00094889    TMAX          11     39.0     39.0
20    2005-01-21  USW00094889    TMAX         -39     22.0     22.0
21    2005-01-22  USW00094889    TMAX         -72     -5.0     -5.0
22    2005-01-23  USW00094889    TMAX         -44     11.0     11.0
23    2005-01-24  USW00094889    TMAX          11     44.0     44.0
24    2005-01-25  USW00094889    TMAX          28     33.0     33.0
25    2005-01-26  USW00094889    TMAX          28     28.0      NaN
26    2005-01-27  USW00094889    TMAX           6     -5.0      NaN
27    2005-01-28  USW00094889    TMAX         -11      6.0      6.0
28    2005-01-29  USW00094889    TMAX          17     39.0     39.0
29    2005-01-30  USW00094889    TMAX          28     28.0      NaN
...          ...          ...     ...         ...      ...      ...
3603  2014-11-13  USW00094889    TMAX          39      NaN      NaN
3604  2014-11-14  USW00094889    TMAX          33      NaN      NaN
3605  2014-11-15  USW00094889    TMAX          28      NaN      NaN
3606  2014-11-16  USW00094889    TMAX          28      NaN      NaN
3607  2014-11-17  USW00094889    TMAX          17      NaN      NaN
3608  2014-11-18  USW00094889    TMAX          11      NaN      NaN
3609  2014-11-19  USW00094889    TMAX          11      NaN      NaN
3610  2014-11-20  USW00094889    TMAX           6      NaN      NaN
3611  2014-11-21  USW00094889    TMAX         -10      NaN      NaN
3612  2014-11-22  USW00094889    TMAX         106      NaN      NaN
3613  2014-11-23  USW00094889    TMAX         156      NaN      NaN
3614  2014-11-24  USW00094889    TMAX         172      NaN      NaN
3615  2014-11-25  USW00094889    TMAX         172      NaN      NaN
3616  2014-11-26  USW00094889    TMAX          28      NaN      NaN
3617  2014-11-27  USW00094889    TMAX          39      NaN      NaN
3618  2014-11-28  USW00094889    TMAX          22      NaN      NaN
3619  2014-11-29  USW00094889    TMAX         117      NaN      NaN
3620  2014-11-30  USW00094889    TMAX         178      NaN      NaN
3621  2014-12-01  USW00094889    TMAX         172      NaN      NaN
3622  2014-12-02  USW00094889    TMAX          33      NaN      NaN
3623  2014-12-03  USW00094889    TMAX          61      NaN      NaN
3624  2014-12-04  USW00094889    TMAX          50      NaN      NaN
3625  2014-12-05  USW00094889    TMAX          50      NaN      NaN
3626  2014-12-06  USW00094889    TMAX          67      NaN      NaN
3627  2014-12-07  USW00094889    TMAX          67      NaN      NaN
3628  2014-12-08  USW00094889    TMAX          72      NaN      NaN
3629  2014-12-09  USW00094889    TMAX          56      NaN      NaN
3630  2014-12-10  USW00094889    TMAX          50      NaN      NaN
3631  2014-12-11  USW00094889    TMAX          61      NaN      NaN
3632  2014-12-12  USW00094889    TMAX          50      NaN      NaN

[3631 rows x 6 columns]
</code>```

The dataframe datamin looks like this:

```<code>Date           ID Element  Data_Value  datamin  breakdown
0     2005-01-01  USC00200032    TMIN         -56   -133.0     -133.0
1     2005-01-02  USC00200032    TMIN         -56   -122.0     -122.0
2     2005-01-03  USC00200032    TMIN           0    -67.0      -67.0
3     2005-01-04  USC00200032    TMIN         -39    -88.0      -88.0
4     2005-01-05  USC00200032    TMIN         -94   -155.0     -155.0
5     2005-01-06  USC00200032    TMIN        -106   -182.0     -182.0
6     2005-01-07  USC00200032    TMIN        -111   -182.0     -182.0
7     2005-01-08  USC00200032    TMIN        -100   -211.0     -211.0
8     2005-01-09  USC00200032    TMIN         -67   -206.0     -206.0
9     2005-01-10  USC00200032    TMIN         -56   -206.0     -206.0
10    2005-01-11  USC00200032    TMIN         -22   -200.0     -200.0
11    2005-01-12  USC00200032    TMIN         -17   -117.0     -117.0
12    2005-01-13  USC00200032    TMIN         -83   -216.0     -216.0
13    2005-01-14  USC00200032    TMIN        -128   -244.0     -244.0
14    2005-01-15  USC00200032    TMIN        -144   -200.0     -200.0
15    2005-01-16  USC00200032    TMIN        -150   -167.0     -167.0
16    2005-01-17  USC00200032    TMIN        -189   -117.0        NaN
17    2005-01-18  USC00200032    TMIN        -217   -100.0        NaN
18    2005-01-19  USC00200228    TMIN        -300    -17.0        NaN
19    2005-01-20  USC00200032    TMIN        -156    -33.0        NaN
20    2005-01-21  USC00200032    TMIN        -178    -61.0        NaN
21    2005-01-22  USC00200032    TMIN        -178    -67.0        NaN
22    2005-01-23  USC00200032    TMIN        -250   -100.0        NaN
23    2005-01-24  USC00200032    TMIN        -267    -61.0        NaN
24    2005-01-25  USC00200032    TMIN        -228    -88.0        NaN
25    2005-01-26  USC00200032    TMIN        -206   -150.0        NaN
26    2005-01-27  USC00200032    TMIN        -239   -161.0        NaN
27    2005-01-28  USC00200032    TMIN        -250   -172.0        NaN
28    2005-01-29  USC00200032    TMIN        -222   -167.0        NaN
29    2005-01-30  USC00200228    TMIN        -217   -143.0        NaN
...          ...          ...     ...         ...      ...        ...
3603  2014-11-13  USC00200032    TMIN         -71      NaN        NaN
3604  2014-11-14  USC00200032    TMIN         -78      NaN        NaN
3605  2014-11-15  USC00200032    TMIN         -94      NaN        NaN
3606  2014-11-16  USC00200032    TMIN         -72      NaN        NaN
3607  2014-11-17  USC00200032    TMIN        -106      NaN        NaN
3608  2014-11-18  USC00200032    TMIN        -144      NaN        NaN
3609  2014-11-19  USC00200032    TMIN        -128      NaN        NaN
3610  2014-11-20  USC00200032    TMIN        -122      NaN        NaN
3611  2014-11-21  USC00200032    TMIN        -182      NaN        NaN
3612  2014-11-22  USC00200032    TMIN        -172      NaN        NaN
3613  2014-11-23  USC00200032    TMIN        -100      NaN        NaN
3614  2014-11-24  USC00200032    TMIN          -5      NaN        NaN
3615  2014-11-25  USC00200032    TMIN         -33      NaN        NaN
3616  2014-11-26  USC00200032    TMIN         -67      NaN        NaN
3617  2014-11-27  USC00200032    TMIN         -82      NaN        NaN
3618  2014-11-28  USC00200032    TMIN        -133      NaN        NaN
3619  2014-11-29  USC00200032    TMIN        -106      NaN        NaN
3620  2014-11-30  USC00200032    TMIN         -56      NaN        NaN
3621  2014-12-01  USC00200032    TMIN         -88      NaN        NaN
3622  2014-12-02  USC00200032    TMIN         -99      NaN        NaN
3623  2014-12-03  USC00200032    TMIN         -71      NaN        NaN
3624  2014-12-04  USC00200032    TMIN         -77      NaN        NaN
3625  2014-12-05  USC00200032    TMIN         -61      NaN        NaN
3626  2014-12-06  USC00200032    TMIN         -50      NaN        NaN
3627  2014-12-07  USC00200032    TMIN         -78      NaN        NaN
3628  2014-12-08  USC00200032    TMIN         -78      NaN        NaN
3629  2014-12-09  USC00200032    TMIN         -39      NaN        NaN
3630  2014-12-10  USC00200032    TMIN         -72      NaN        NaN
3631  2014-12-11  USC00200032    TMIN         -88      NaN        NaN
3632  2014-12-12  USC00200032    TMIN         -78      NaN        NaN

[3631 rows x 6 columns]
</code>```

I can't understand why I am getting these errors.

The line giving me the error is:

```<code>datamax.plot(kind='scatter',x=datamax['Date'],y='breakup',color='red',ax=ax)
</code>```

I am trying to plot 2 line graphs and 2 scatter plots on a single figure. However, my code is not letting me do this.

The data comes from here:

```<code>#organise data 2005-2014
data = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')
newdata = data[(data['Date'] >= '2005-01-01') & (data['Date'] <= '2014-12-12')]
#time = pd.date_range('2005-01-01','2014-12-12',freq='D').strftime('%Y-%m-%d')
datamax = newdata[newdata['Element']=='TMAX']
datamin = newdata[newdata['Element']=='TMIN']
datamax = datamax.groupby('Date').max()
datamin = datamin.groupby('Date').min()
datamax = datamax.reset_index()
datamin = datamin.reset_index()
datamax = datamax[~datamax['Date'].str.contains("02-29")]
datamin = datamin[~datamin['Date'].str.contains("02-29")]

#2015 data
breakoutdata = data[(data['Date']  > '2014-12-31')]
datamax2015 = breakoutdata[breakoutdata['Element']=='TMAX']
datamin2015 = breakoutdata[breakoutdata['Element']=='TMIN']
datamax2015 = datamax2015.groupby('Date').max()
datamin2015 = datamin2015.groupby('Date').min()
datamax2015 = datamax2015.reset_index()
datamin2015 = datamin2015.reset_index()
datamax2015 = datamax2015[~datamax2015['Date'].str.contains("02-29")]
datamin2015 = datamin2015[~datamin2015['Date'].str.contains("02-29")]

#filtering out breakthroughs as scatterplot
datamax['datamax'] = datamax2015['Data_Value']
datamin['datamin'] = datamin2015['Data_Value']
datamax['breakup'] = datamax['datamax'][datamax['datamax']>datamax['Data_Value']]
datamin['breakdown'] = datamin['datamin'][datamin['datamin']<datamin['Data_Value']]
</code>```

答:
Use your own code with this line:

```<code>datamax.plot(kind='scatter',x='Date',y='breakup',color='red',ax=ax)
</code>```

and not

```<code>datamax.plot(kind='scatter',x=datamax['Date'],y='breakup',color='red',ax=ax)
</code>```

Body:
I have the following command:

#plot data
ax = plt.gca()
datamax.plot(kind='line',x='Date',y='Data_Value',color='red',ax=ax)
datamin.plot(kind='line',x='Date',y='Data_Value', color='blue',ax=ax)
datamax.plot(kind='scatter',x='Date',y='breakup',color='red',ax=ax)
datamin.plot(kind='scatter',x='Date',y='breakdown', color='blue',ax=ax)
plt.ylabel("Temperature (degrees C)",color='navy')
plt.xlabel("Date",color='navy',labelpad=15)
plt.title('Record high and low temperatures by day (2005-2014)', alpha=1.0,color='brown',y=1.08)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.35),
          fancybox=False,labels=['Record high','Record low'])
plt.xticks(rotation=30)
plt.fill_between(range(len(datamax['Date'])), datamax['Data_Value'], datamin['Data_Value'],color='yellow',alpha=0.8)
plt.show()

However, I keep getting the error: KeyError: 'Date'

The dataframe datamax looks like this:

   Date           ID Element  Data_Value  datamax  breakup
0     2005-01-01  USW00094889    TMAX         156     11.0      NaN
1     2005-01-02  USW00094889    TMAX         139     39.0      NaN
2     2005-01-03  USW00094889    TMAX         133     39.0      NaN
3     2005-01-04  USW00094889    TMAX          39     44.0     44.0
4     2005-01-05  USW00094889    TMAX          33     28.0      NaN
5     2005-01-06  USW00094889    TMAX           0     33.0     33.0
6     2005-01-07  USW00094889    TMAX           6    -67.0      NaN
7     2005-01-08  USW00094889    TMAX          17    -82.0      NaN
8     2005-01-09  USW00094889    TMAX          28    -66.0      NaN
9     2005-01-10  USW00094889    TMAX          44    -71.0      NaN
10    2005-01-11  USW00094889    TMAX          44      6.0      NaN
11    2005-01-12  USW00094889    TMAX         139      6.0      NaN
12    2005-01-13  USW00094889    TMAX         161      0.0      NaN
13    2005-01-14  USW00094889    TMAX         150    -56.0      NaN
14    2005-01-15  USW00094889    TMAX         -33     -5.0     -5.0
15    2005-01-16  USW00094889    TMAX         -33      6.0      6.0
16    2005-01-17  USW00094889    TMAX         -50     78.0     78.0
17    2005-01-18  USW00094889    TMAX         -33     83.0     83.0
18    2005-01-19  USW00094889    TMAX          11     67.0     67.0
19    2005-01-20  USW00094889    TMAX          11     39.0     39.0
20    2005-01-21  USW00094889    TMAX         -39     22.0     22.0
21    2005-01-22  USW00094889    TMAX         -72     -5.0     -5.0
22    2005-01-23  USW00094889    TMAX         -44     11.0     11.0
23    2005-01-24  USW00094889    TMAX          11     44.0     44.0
24    2005-01-25  USW00094889    TMAX          28     33.0     33.0
25    2005-01-26  USW00094889    TMAX          28     28.0      NaN
26    2005-01-27  USW00094889    TMAX           6     -5.0      NaN
27    2005-01-28  USW00094889    TMAX         -11      6.0      6.0
28    2005-01-29  USW00094889    TMAX          17     39.0     39.0
29    2005-01-30  USW00094889    TMAX          28     28.0      NaN
...          ...          ...     ...         ...      ...      ...
3603  2014-11-13  USW00094889    TMAX          39      NaN      NaN
3604  2014-11-14  USW00094889    TMAX          33      NaN      NaN
3605  2014-11-15  USW00094889    TMAX          28      NaN      NaN
3606  2014-11-16  USW00094889    TMAX          28      NaN      NaN
3607  2014-11-17  USW00094889    TMAX          17      NaN      NaN
3608  2014-11-18  USW00094889    TMAX          11      NaN      NaN
3609  2014-11-19  USW00094889    TMAX          11      NaN      NaN
3610  2014-11-20  USW00094889    TMAX           6      NaN      NaN
3611  2014-11-21  USW00094889    TMAX         -10      NaN      NaN
3612  2014-11-22  USW00094889    TMAX         106      NaN      NaN
3613  2014-11-23  USW00094889    TMAX         156      NaN      NaN
3614  2014-11-24  USW00094889    TMAX         172      NaN      NaN
3615  2014-11-25  USW00094889    TMAX         172      NaN      NaN
3616  2014-11-26  USW00094889    TMAX          28      NaN      NaN
3617  2014-11-27  USW00094889    TMAX          39      NaN      NaN
3618  2014-11-28  USW00094889    TMAX          22      NaN      NaN
3619  2014-11-29  USW00094889    TMAX         117      NaN      NaN
3620  2014-11-30  USW00094889    TMAX         178      NaN      NaN
3621  2014-12-01  USW00094889    TMAX         172      NaN      NaN
3622  2014-12-02  USW00094889    TMAX          33      NaN      NaN
3623  2014-12-03  USW00094889    TMAX          61      NaN      NaN
3624  2014-12-04  USW00094889    TMAX          50      NaN      NaN
3625  2014-12-05  USW00094889    TMAX          50      NaN      NaN
3626  2014-12-06  USW00094889    TMAX          67      NaN      NaN
3627  2014-12-07  USW00094889    TMAX          67      NaN      NaN
3628  2014-12-08  USW00094889    TMAX          72      NaN      NaN
3629  2014-12-09  USW00094889    TMAX          56      NaN      NaN
3630  2014-12-10  USW00094889    TMAX          50      NaN      NaN
3631  2014-12-11  USW00094889    TMAX          61      NaN      NaN
3632  2014-12-12  USW00094889    TMAX          50      NaN      NaN

[3631 rows x 6 columns]

The dataframe datamin looks like this:

Date           ID Element  Data_Value  datamin  breakdown
0     2005-01-01  USC00200032    TMIN         -56   -133.0     -133.0
1     2005-01-02  USC00200032    TMIN         -56   -122.0     -122.0
2     2005-01-03  USC00200032    TMIN           0    -67.0      -67.0
3     2005-01-04  USC00200032    TMIN         -39    -88.0      -88.0
4     2005-01-05  USC00200032    TMIN         -94   -155.0     -155.0
5     2005-01-06  USC00200032    TMIN        -106   -182.0     -182.0
6     2005-01-07  USC00200032    TMIN        -111   -182.0     -182.0
7     2005-01-08  USC00200032    TMIN        -100   -211.0     -211.0
8     2005-01-09  USC00200032    TMIN         -67   -206.0     -206.0
9     2005-01-10  USC00200032    TMIN         -56   -206.0     -206.0
10    2005-01-11  USC00200032    TMIN         -22   -200.0     -200.0
11    2005-01-12  USC00200032    TMIN         -17   -117.0     -117.0
12    2005-01-13  USC00200032    TMIN         -83   -216.0     -216.0
13    2005-01-14  USC00200032    TMIN        -128   -244.0     -244.0
14    2005-01-15  USC00200032    TMIN        -144   -200.0     -200.0
15    2005-01-16  USC00200032    TMIN        -150   -167.0     -167.0
16    2005-01-17  USC00200032    TMIN        -189   -117.0        NaN
17    2005-01-18  USC00200032    TMIN        -217   -100.0        NaN
18    2005-01-19  USC00200228    TMIN        -300    -17.0        NaN
19    2005-01-20  USC00200032    TMIN        -156    -33.0        NaN
20    2005-01-21  USC00200032    TMIN        -178    -61.0        NaN
21    2005-01-22  USC00200032    TMIN        -178    -67.0        NaN
22    2005-01-23  USC00200032    TMIN        -250   -100.0        NaN
23    2005-01-24  USC00200032    TMIN        -267    -61.0        NaN
24    2005-01-25  USC00200032    TMIN        -228    -88.0        NaN
25    2005-01-26  USC00200032    TMIN        -206   -150.0        NaN
26    2005-01-27  USC00200032    TMIN        -239   -161.0        NaN
27    2005-01-28  USC00200032    TMIN        -250   -172.0        NaN
28    2005-01-29  USC00200032    TMIN        -222   -167.0        NaN
29    2005-01-30  USC00200228    TMIN        -217   -143.0        NaN
...          ...          ...     ...         ...      ...        ...
3603  2014-11-13  USC00200032    TMIN         -71      NaN        NaN
3604  2014-11-14  USC00200032    TMIN         -78      NaN        NaN
3605  2014-11-15  USC00200032    TMIN         -94      NaN        NaN
3606  2014-11-16  USC00200032    TMIN         -72      NaN        NaN
3607  2014-11-17  USC00200032    TMIN        -106      NaN        NaN
3608  2014-11-18  USC00200032    TMIN        -144      NaN        NaN
3609  2014-11-19  USC00200032    TMIN        -128      NaN        NaN
3610  2014-11-20  USC00200032    TMIN        -122      NaN        NaN
3611  2014-11-21  USC00200032    TMIN        -182      NaN        NaN
3612  2014-11-22  USC00200032    TMIN        -172      NaN        NaN
3613  2014-11-23  USC00200032    TMIN        -100      NaN        NaN
3614  2014-11-24  USC00200032    TMIN          -5      NaN        NaN
3615  2014-11-25  USC00200032    TMIN         -33      NaN        NaN
3616  2014-11-26  USC00200032    TMIN         -67      NaN        NaN
3617  2014-11-27  USC00200032    TMIN         -82      NaN        NaN
3618  2014-11-28  USC00200032    TMIN        -133      NaN        NaN
3619  2014-11-29  USC00200032    TMIN        -106      NaN        NaN
3620  2014-11-30  USC00200032    TMIN         -56      NaN        NaN
3621  2014-12-01  USC00200032    TMIN         -88      NaN        NaN
3622  2014-12-02  USC00200032    TMIN         -99      NaN        NaN
3623  2014-12-03  USC00200032    TMIN         -71      NaN        NaN
3624  2014-12-04  USC00200032    TMIN         -77      NaN        NaN
3625  2014-12-05  USC00200032    TMIN         -61      NaN        NaN
3626  2014-12-06  USC00200032    TMIN         -50      NaN        NaN
3627  2014-12-07  USC00200032    TMIN         -78      NaN        NaN
3628  2014-12-08  USC00200032    TMIN         -78      NaN        NaN
3629  2014-12-09  USC00200032    TMIN         -39      NaN        NaN
3630  2014-12-10  USC00200032    TMIN         -72      NaN        NaN
3631  2014-12-11  USC00200032    TMIN         -88      NaN        NaN
3632  2014-12-12  USC00200032    TMIN         -78      NaN        NaN

[3631 rows x 6 columns]

I can't understand why I am getting these errors.

The line giving me the error is:

datamax.plot(kind='scatter',x=datamax['Date'],y='breakup',color='red',ax=ax)

I am trying to plot 2 line graphs and 2 scatter plots on a single figure. However, my code is not letting me do this.

The data comes from here:

#organise data 2005-2014
data = pd.read_csv('data/C2A2_data/BinnedCsvs_d400/fb441e62df2d58994928907a91895ec62c2c42e6cd075c2700843b89.csv')
newdata = data[(data['Date'] >= '2005-01-01') & (data['Date'] <= '2014-12-12')]
#time = pd.date_range('2005-01-01','2014-12-12',freq='D').strftime('%Y-%m-%d')
datamax = newdata[newdata['Element']=='TMAX']
datamin = newdata[newdata['Element']=='TMIN']
datamax = datamax.groupby('Date').max()
datamin = datamin.groupby('Date').min()
datamax = datamax.reset_index()
datamin = datamin.reset_index()
datamax = datamax[~datamax['Date'].str.contains("02-29")]
datamin = datamin[~datamin['Date'].str.contains("02-29")]

#2015 data
breakoutdata = data[(data['Date']  > '2014-12-31')]
datamax2015 = breakoutdata[breakoutdata['Element']=='TMAX']
datamin2015 = breakoutdata[breakoutdata['Element']=='TMIN']
datamax2015 = datamax2015.groupby('Date').max()
datamin2015 = datamin2015.groupby('Date').min()
datamax2015 = datamax2015.reset_index()
datamin2015 = datamin2015.reset_index()
datamax2015 = datamax2015[~datamax2015['Date'].str.contains("02-29")]
datamin2015 = datamin2015[~datamin2015['Date'].str.contains("02-29")]

#filtering out breakthroughs as scatterplot
datamax['datamax'] = datamax2015['Data_Value']
datamin['datamin'] = datamin2015['Data_Value']
datamax['breakup'] = datamax['datamax'][datamax['datamax']>datamax['Data_Value']]
datamin['breakdown'] = datamin['datamin'][datamin['datamin']<datamin['Data_Value']]

Body:
Use your own code with this line:

datamax.plot(kind='scatter',x='Date',y='breakup',color='red',ax=ax)

and not

datamax.plot(kind='scatter',x=datamax['Date'],y='breakup',color='red',ax=ax)


问:
Yii2: Bootstrap Modal Form Validation (Ajax) - any insight on strange behavior?
I've been working on having forms in modal windows in Yii2, and I've been having an issue where the standard Yii form ajax validation is not working when the form is inside a bootstrap modal window.

To be clear, the ajax form validation is triggered for each field when the filed looses focus. This is the standard Yii form validation, so I'm testing the form in the modal by clicking into a required field, and then clicking out of the field.  This triggers the Yii ajax validation and should display a red error message under the field that states the "'field' cannot be blank."

Again, my issue is that sometimes the ajax validation works and sometimes it does not.

I managed to trap the issue to being related to where the modal code is placed on the page, but it makes no sense to me how the following would affect the ajax validation behavior of the form in the modal.

First I'll show you the code that works properly.  The Yii form validation works as expected on the form in the modal window.

```<code><?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\grid\GridView;
use yii\bootstrap\Modal;
?>
<div class="category-index">

    <h1><?= Html::encode($this->title) ?></h1>

    <?= Html::button('Create Category', [
        'class' => 'btn btn-success btn-ajax-modal',
        'value' => Url::to('/category/create'),
        'data-target' => '#modal_category',
    ]); ?>

    <?php
    Modal::begin([
        'id' => 'modal_category',
        'header' => '<h4>Category</h4>',
    ]);
    echo '<div class="modal-content"></div>';
    Modal::end();
    ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            'id',
            'title',
            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>
</div>
</code>```

Things to note in the code above:

1) This is my category/index view, so it has a create button, the bootstrap modal code, and then the Yii gridview of categories.

2) The create button has the btn-ajax-modal class.  This class is identified by a JS function that uses the other button attributes to display the modal widow and load the form content in the modal.  The button value attribute identifies the model and form that should be loaded.

Here is the JS function that handles showing the modal and loading the form:

```<code>$('.btn-ajax-modal').click(function (){
    var elm = $(this),
        target = elm.attr('data-target'),
        ajax_body = elm.attr('value');

    $(target).modal('show')
        .find('.modal-content')
        .load(ajax_body);
});
</code>```

So, all of the above code works perfectly, and my hope is that this will help others!

BUT... if I make some very simple changes to the above code, the ajax form validation no longer works, and I have no idea why.

First change:

1) Move the bootstrap modal code below the gridview code, and the ajax validation no longer works.

```<code><div class="category-index">

    <h1><?= Html::encode($this->title) ?></h1>

    <?= Html::button('Create Category', [
        'class' => 'btn btn-success btn-ajax-modal',
        'value' => Url::to('/category/create'),
        'data-target' => '#modal_category',
    ]); ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            'id',
            'title',
            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

    <?php //*** SEE MODAL CODE IS NOW BELOW GRIDVIEW CODE
    Modal::begin([
        'id' => 'modal_category',
        'header' => '<h4>Category</h4>',
    ]);
    echo '<div id="modalContent"></div>';
    Modal::end();
    ?>

</div>
</code>```

It makes no sense to me why moving the modal code below the gridview code would break the ajax form validation.  The modal still displays and loads the proper form, but the ajax form validation does not trigger when I give and remove focus to a required field.

And it gets even more bizarre ...

Second change:

2) Instead of moving the modal code below the gridview code, just delete the gridview entirely, including use yii\grid\GridView;.

```<code><?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\Modal;
?>
<div class="category-index">

    <h1><?= Html::encode($this->title) ?></h1>

    <?= Html::button('Create Category', [
        'class' => 'btn btn-success btn-ajax-modal',
        'value' => Url::to('/category/create'),
        'data-target' => '#modal_category',
    ]); ?>

    <?php
    Modal::begin([
        'id' => 'modal_category',
        'header' => '<h4>Category</h4>',
    ]);
    echo '<div class="modal-content"></div>';
    Modal::end();
    ?>

</div>
</code>```

This change also causes the ajax form validation for the form in the modal to stop working.

WHAT ON EARTH?  How can removing the gridview, which has absolutely nothing to do with the modal/form setup cause the ajax form validation to stop working?

I'm seeing no errors in the browser console, no errors in the Yii debug module.  But for some reason, the ajax field validation is not displaying.

Sorry for such a long post, but I wanted to be as clear and specific as possible.  I'm not sure if this is some strange Yii2 bug, if I'm loosing my mind, or if there is a logical explanation for this.

If anyone has any ideas, answers or suggestions, please share!  And thank you for brainstorming with me!

答:
Ajax validation will not work without an id attribute. Open category/_form.php and set an id for the ActiveForm as below:

```<code><div class="category-form">
    <?php $form = ActiveForm::begin(['id' => 'create-update-category-form']); ?
</code>```

Body:
I've been working on having forms in modal windows in Yii2, and I've been having an issue where the standard Yii form ajax validation is not working when the form is inside a bootstrap modal window.

To be clear, the ajax form validation is triggered for each field when the filed looses focus. This is the standard Yii form validation, so I'm testing the form in the modal by clicking into a required field, and then clicking out of the field.  This triggers the Yii ajax validation and should display a red error message under the field that states the "'field' cannot be blank."

Again, my issue is that sometimes the ajax validation works and sometimes it does not.

I managed to trap the issue to being related to where the modal code is placed on the page, but it makes no sense to me how the following would affect the ajax validation behavior of the form in the modal.

First I'll show you the code that works properly.  The Yii form validation works as expected on the form in the modal window.

<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\grid\GridView;
use yii\bootstrap\Modal;
?>

<?= Html::encode($this->title) ?>

    <?= Html::button('Create Category', [
        'class' => 'btn btn-success btn-ajax-modal',
        'value' => Url::to('/category/create'),
        'data-target' => '#modal_category',
    ]); ?>

    <?php
    Modal::begin([
        'id' => 'modal_category',
        'header' => '
Category
',
    ]);
    echo '

';
    Modal::end();
    ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            'id',
            'title',
            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

Things to note in the code above:

1) This is my category/index view, so it has a create button, the bootstrap modal code, and then the Yii gridview of categories.

2) The create button has the btn-ajax-modal class.  This class is identified by a JS function that uses the other button attributes to display the modal widow and load the form content in the modal.  The button value attribute identifies the model and form that should be loaded.

Here is the JS function that handles showing the modal and loading the form:

$('.btn-ajax-modal').click(function (){
    var elm = $(this),
        target = elm.attr('data-target'),
        ajax_body = elm.attr('value');

    $(target).modal('show')
        .find('.modal-content')
        .load(ajax_body);
});

So, all of the above code works perfectly, and my hope is that this will help others!

BUT... if I make some very simple changes to the above code, the ajax form validation no longer works, and I have no idea why.

First change:

1) Move the bootstrap modal code below the gridview code, and the ajax validation no longer works.

<?= Html::encode($this->title) ?>

    <?= Html::button('Create Category', [
        'class' => 'btn btn-success btn-ajax-modal',
        'value' => Url::to('/category/create'),
        'data-target' => '#modal_category',
    ]); ?>

    <?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            'id',
            'title',
            ['class' => 'yii\grid\ActionColumn'],
        ],
    ]); ?>

    <?php //*** SEE MODAL CODE IS NOW BELOW GRIDVIEW CODE
    Modal::begin([
        'id' => 'modal_category',
        'header' => '
Category
',
    ]);
    echo '

';
    Modal::end();
    ?>

It makes no sense to me why moving the modal code below the gridview code would break the ajax form validation.  The modal still displays and loads the proper form, but the ajax form validation does not trigger when I give and remove focus to a required field.

And it gets even more bizarre ...

Second change:

2) Instead of moving the modal code below the gridview code, just delete the gridview entirely, including use yii\grid\GridView;.

<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\bootstrap\Modal;
?>

<?= Html::encode($this->title) ?>

    <?= Html::button('Create Category', [
        'class' => 'btn btn-success btn-ajax-modal',
        'value' => Url::to('/category/create'),
        'data-target' => '#modal_category',
    ]); ?>

    <?php
    Modal::begin([
        'id' => 'modal_category',
        'header' => '
Category
',
    ]);
    echo '

';
    Modal::end();
    ?>

This change also causes the ajax form validation for the form in the modal to stop working.

WHAT ON EARTH?  How can removing the gridview, which has absolutely nothing to do with the modal/form setup cause the ajax form validation to stop working?

I'm seeing no errors in the browser console, no errors in the Yii debug module.  But for some reason, the ajax field validation is not displaying.

Sorry for such a long post, but I wanted to be as clear and specific as possible.  I'm not sure if this is some strange Yii2 bug, if I'm loosing my mind, or if there is a logical explanation for this.

If anyone has any ideas, answers or suggestions, please share!  And thank you for brainstorming with me!

Body:
Ajax validation will not work without an id attribute. Open category/_form.php and set an id for the ActiveForm as below:

<div class="category-form">
    <?php $form = ActiveForm::begin(['id' => 'create-update-category-form']); ?