问:
LOAD DATA INFILE - Replace Comma with Dot
I have a problem loading data in to my table using LOAD DATA INFILE

My CSV file contains a lot on numeric data like: 1,22, where there is used a Comma instead of dot.

Im using PHP to run it.

Hope it makes sense, Im new here :-)

My current mysql code:

```<code>LOAD DATA LOCAL INFILE "'.$file.'"
INTO TABLE '.$table.'
FIELDS TERMINATED by \';\'
LINES TERMINATED BY \'\n\'
IGNORE 1 LINES
</code>```

CSV DATA:

```<code>Order;TAT1;TAT2
1;1,22;2,44
2;4,46;7,32
etc.
</code>```

Table:

```<code>Order: INT(11)
TAT1: decimal(10,2)
TAT2: decimal(10,2)
</code>```

But when I run the code its not loads the decimal.

```<code>Loaded looks like data:

Order - TAT1 - TAT2
1 - 1 - 2
2 - 4 - 7
etc..
</code>```

It should load it like this, where comma is replace with dot:

```<code>Order - TAT1 - TAT2
1 - 1.22 - 2.44
2 - 4.46 - 7.32
etc..
</code>```

答:
Use user variables to modify the input before it's inserted.</p>

```<code>LOAD DATA LOCAL INFILE "'.$file.'"
INTO TABLE '.$table.'
FIELDS TERMINATED by \';\'
LINES TERMINATED BY \'\n\'
IGNORE 1 LINES
(order, @tat1, @tat2)
SET tat1 = REPLACE(@tat1, \',\', \'.\'),
    tat2 = REPLACE(@tat2, \',\', \'.\')
</code>```

Body:
I have a problem loading data in to my table using LOAD DATA INFILE

My CSV file contains a lot on numeric data like: 1,22, where there is used a Comma instead of dot.

Im using PHP to run it.

Hope it makes sense, Im new here :-)

My current mysql code:

LOAD DATA LOCAL INFILE "'.$file.'"
INTO TABLE '.$table.'
FIELDS TERMINATED by \';\'
LINES TERMINATED BY \'\n\'
IGNORE 1 LINES

CSV DATA:

Order;TAT1;TAT2
1;1,22;2,44
2;4,46;7,32
etc.

Table:

Order: INT(11)
TAT1: decimal(10,2)
TAT2: decimal(10,2)

But when I run the code its not loads the decimal.

Loaded looks like data:

Order - TAT1 - TAT2
1 - 1 - 2
2 - 4 - 7
etc..

It should load it like this, where comma is replace with dot:

Order - TAT1 - TAT2
1 - 1.22 - 2.44
2 - 4.46 - 7.32
etc..

Body:
Use user variables to modify the input before it's inserted.

LOAD DATA LOCAL INFILE "'.$file.'"
INTO TABLE '.$table.'
FIELDS TERMINATED by \';\'
LINES TERMINATED BY \'\n\'
IGNORE 1 LINES
(order, @tat1, @tat2)
SET tat1 = REPLACE(@tat1, \',\', \'.\'),
    tat2 = REPLACE(@tat2, \',\', \'.\')


来源: stackexchange

问:
describe_replication_tasks filter on 'cdc' migration-type
I'm trying to use boto3 to filter replication tasks by cdc migration-type.  However, I cannot seem to find or guess correctly the different possible string Values.  Does anyone know what they are or where I can find them?

```<code>migration_type_filter = { 'Name': 'migration-type', 'Values': 'cdc' }
tasks = boto3.client('dms').describe_replication_tasks(Filters=[migration_type_filter])
</code>```

Error:  "errorMessage": "Parameter validation failed:\nInvalid type for parameter Filters[0].Values, value: cdc, type: , valid types: , "

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to use boto3 to filter replication tasks by cdc migration-type.  However, I cannot seem to find or guess correctly the different possible string Values.  Does anyone know what they are or where I can find them?

migration_type_filter = { 'Name': 'migration-type', 'Values': 'cdc' }
tasks = boto3.client('dms').describe_replication_tasks(Filters=[migration_type_filter])

Error:  "errorMessage": "Parameter validation failed:\nInvalid type for parameter Filters[0].Values, value: cdc, type: , valid types: , "

Body: 'MigrationType': 'full-load'|'cdc'|'full-load-and-cdc'


问:
jQuery not showing correctly in aspx page
I'm trying to get this function to work in an aspx page but I'm having a rotten time.  Basically it works fine in a regular HTML page but in the aspx page, when click on the button all you can see is a sliver of the top part and on occasion (every 5th+ single button click & every double click) the message shows and fades like it should.  What am I missing?  Could it be getting tied up in the postback?

FIDDLE HERE

Code using in aspx page

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="checkTest.aspx.cs" Inherits="WebApplication2.checkTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#Button1").click(function () {
                    $(".message").stop(true,true).slideToggle().fadeOut(6000);
                });
            });
        </script>
    <style type="text/css">
    .message{height:70px;display:none;}
        .noChangesMessage{width:84px;padding:8px 8px;  background:#535353; -webkit-border-radius:5px; -moz-border-radius:5px; border-radius:5px; color:white;text-align:center;}
        .tipEnd{width:0;height:0;border-left:10px solid transparent;border-right:10px solid transparent;border-top:10px solid #535353;margin:0 auto;}

    </style>
</head>
<body>
    <form id="form1" runat="server">

    <br /><br /><br />
    <div>
    <div style="width:100px">
    <div style="height:70px">
                <div style="margin-bottom:5px;" class="message">
                    <div class="noChangesMessage">No changes were made!</div>
                    <div class="tipEnd"></div>
                </div></div>
            <div style="">
                <asp:Button ID="Button1" runat="server" Text="Save Changes"  />
            </div>
            </div>

    </div>

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

my code via view source for amit_g

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>
</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
        <script type="text/javascript">
            $(function () {
                $("#Button1").click(function () {
                    $(".message").stop(true,true).slideToggle().fadeOut(6000);
                });
            });
        </script>
    <style type="text/css">.
    .message{height:70px;display:none;}
        .noChangesMessage{width:84px;padding:8px 8px;  background:#535353; -webkit-border-radius:5px; -moz-border-radius:5px; border-radius:5px; color:white;text-align:center;}
        .tipEnd{width:0;height:0;border-left:10px solid transparent;border-right:10px solid transparent;border-top:10px solid #535353;margin:0 auto;}
    </style>
</head>
<body>
    <form method="post" action="checkTest.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMjA0OTM4MTAwNGRkU+SP3bu4QJNH9S9XtdwPbEE8YODY/YlkotOt6l692s8=" />
</div>
<div class="aspNetHidden">
    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAgKroLr3AwKM54rGBtLTfCTwYmYnb6l8tnp5jtojhvORYMJ6bPzAI+qbaDlU" />
</div>
    <br /><br /><br />
    <div>
    <div style="width:100px">
    <div style="height:70px">
                <div style="margin-bottom:5px;" class="message">
                    <div class="noChangesMessage">No changes were made!</div>
                    <div class="tipEnd"></div>
                </div></div>
            <div style="">
                <input type="submit" name="Button1" value="Save Changes" id="Button1" class="Button1" /></div>
            </div>
    </div>
    </form>
</body>
</html>
</code>```

答:
The button click is triggering a postback, which causes a reload of the page.  Your animation is cancelled before it has a chance to play out (barring random delays).

ASP.NET Webforms attaches an event handler to the button click event which triggers javascript that is dynamically generated for your page.  This is the central mechanism for interactive pages in webforms.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get this function to work in an aspx page but I'm having a rotten time.  Basically it works fine in a regular HTML page but in the aspx page, when click on the button all you can see is a sliver of the top part and on occasion (every 5th+ single button click & every double click) the message shows and fades like it should.  What am I missing?  Could it be getting tied up in the postback?

FIDDLE HERE

Code using in aspx page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="checkTest.aspx.cs" Inherits="WebApplication2.checkTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title></title>

    <form id="form1" runat="server">

No changes were made!

                <asp:Button ID="Button1" runat="server" Text="Save Changes"  />

    </form>

my code via view source for amit_g

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>
</title>

    <form method="post" action="checkTest.aspx" id="form1">

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMjA0OTM4MTAwNGRkU+SP3bu4QJNH9S9XtdwPbEE8YODY/YlkotOt6l692s8=" />

    <input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="/wEWAgKroLr3AwKM54rGBtLTfCTwYmYnb6l8tnp5jtojhvORYMJ6bPzAI+qbaDlU" />

No changes were made!

                <input type="submit" name="Button1" value="Save Changes" id="Button1" class="Button1" />

    </form>


问:
Spritekit physics failing to detect second adjacent item
Kinda what the title says, I have a "wall" made out of multiple segments specifically for modular purposes. I have a contactTestBitmask that forces the player to stop moving in the direction of the wall once collided, but, if you slide along the wall to another segment, the player just rolls straight through it. I cannot do a collisionBitmask as the player runs fast enough to "phase" through the walls. I also cannot do collision as my camera and lighting are also dependent on the player's movement and position, and will not interfere with the walls (I think). If anyone could help point me in the right direction to allow me to make solid modular walls, I'd greatly appreciate it.</p>

答: Figured out the source of my problem, contact IS happening, I just have wonky flags and the system doesn't like that. I need a contact currently happening method, I guess</p>


问:
Python checking condition and safety in same if statement
I've been writing some python code where i have a condition if object is None return if its not get object property and check it.Here is an example code:

```<code>b = None
if b is None or b.property == "something":
    print("yay")
</code>```

when runned code above prints AttributeError: 'NoneType' object has no attribute 'property' code below prints the same result.

```<code>b = None
if b.property == "something" or b is None:
    print("yay")
</code>```

Question:
   Asume there is many or checks in if clause after evaluating one of them true other condisions can be bypassed becouse the result is gonna be true so its waste of #compute power.
Same can be applied to and operator too if any condition is 0 result is zero.So why the example above fires an exception?

答:
I was not able to reproduce the error.

```<code>>>> b = None
>>> b is None or b.property == 'something'
True
</code>```

However, you may be interested to know that the or keyword does not necessarily return True or False; rather, given the expression a or b it returns a if a is truthy, else it returns b, regardless of it's boolean value. We would get the error you described if the order of operations were different:

```<code>>>> b is (None or b.property) == 'something'
AttributeError: 'NoneType' object has no attribute 'property'
</code>```

Body:
I've been writing some python code where i have a condition if object is None return if its not get object property and check it.Here is an example code:

b = None
if b is None or b.property == "something":
    print("yay")

when runned code above prints AttributeError: 'NoneType' object has no attribute 'property' code below prints the same result.

b = None
if b.property == "something" or b is None:
    print("yay")

Question:
   Asume there is many or checks in if clause after evaluating one of them true other condisions can be bypassed becouse the result is gonna be true so its waste of #compute power.
Same can be applied to and operator too if any condition is 0 result is zero.So why the example above fires an exception?

Body:
I was not able to reproduce the error.

>>> b = None
>>> b is None or b.property == 'something'
True

However, you may be interested to know that the or keyword does not necessarily return True or False; rather, given the expression a or b it returns a if a is truthy, else it returns b, regardless of it's boolean value. We would get the error you described if the order of operations were different:

>>> b is (None or b.property) == 'something'
AttributeError: 'NoneType' object has no attribute 'property'


问:
Execute a URL from a command line without opening a browser in windows
So I'm putting together a batch file to run at startup that executes a small number of processes, one of them is to execute a reboot of a certain program at the end of the set of processes. I've been searching ways how to do this in the command line in windows but I need to be able to do this without opening a browser. What I need is to execute the reboot in the following url without opening a browser at all.

```<code>http://192.168.1.100/cgi-bin/reboot
</code>```

Everything that I've tried has opened a new browser window. I don't want to have to download anything to get this going in windows if that's possible. Thanks for any suggestions.

答:
To process URL response direct, from Win CMD:

```<code>powershell "Invoke-WebRequest -Uri <url>"
</code>```

To save server response to file:

```<code>powershell "Invoke-WebRequest -Uri <url> -outfile <file.ext>"
</code>```

.NET solution; from Win CMD:

```<code>powershell "[System.Net.Webclient]::new().DownloadString(\"<URL>\")"
</code>```

Body:
So I'm putting together a batch file to run at startup that executes a small number of processes, one of them is to execute a reboot of a certain program at the end of the set of processes. I've been searching ways how to do this in the command line in windows but I need to be able to do this without opening a browser. What I need is to execute the reboot in the following url without opening a browser at all.

http://192.168.1.100/cgi-bin/reboot

Everything that I've tried has opened a new browser window. I don't want to have to download anything to get this going in windows if that's possible. Thanks for any suggestions.

Body:
To process URL response direct, from Win CMD:

powershell "Invoke-WebRequest -Uri <url>"

To save server response to file:

powershell "Invoke-WebRequest -Uri <url> -outfile <file.ext>"

.NET solution; from Win CMD:

powershell "[System.Net.Webclient]::new().DownloadString(\"<URL>\")"


问:
How does angular remove whitespaces between s?
I must say that I never noticed this until last week. If you have the following HTML

```<code><div>
    <span>A</span>
    <span>B</span>
</div>
</code>```

DEMO

It is rendered as A B. However, if you render the exact same thing in Angular that space between A and B is removed. I've created a Stackblitz to demonstrate a couple of cases in Angular:

```<code><h3>With normal space</h3>
<div>
  <span>A</span>
  <span>B</span>
</div>
<br>
<h3>  With &ngsp;</h3>
<div >
  <span>A</span>&ngsp;
  <span>B</span>
</div>
<br>
<h3>With ngPreserveWhitespaces</h3>
<div ngPreserveWhitespaces>
  <span>A</span>
  <span>B</span>
</div>
</code>```

DEMO

I've tried to inspect the HTML with Chrome DevTools but I still don't understand how its done.For all cases the HTML/CSS is identical. Anyway, it's probably very simple. Any suggestions?

答:
By default display property of span is inline-block. This will create extra space between the span elements so we need to remove that by giving font-size: 0 to the parent element. And you have to give font-size to your child elements. Like here i have applied font-size:0; to parent element i.e div and applied font-size:1rem; to children span elements of div.

div{
  font-size: 0;
}
div>span{
  font-size:1rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
 <span>A</span>
 <span>B</span>
</div>

<span id="total">X</span>
<span id="max">Y</span></code>```

Title: How does angular remove whitespaces between <span>s?

Body:
I must say that I never noticed this until last week. If you have the following HTML

    A
    B

DEMO

It is rendered as A B. However, if you render the exact same thing in Angular that space between A and B is removed. I've created a Stackblitz to demonstrate a couple of cases in Angular:

With normal space

  A
  B

  With &ngsp;

  A&ngsp;
  B

With ngPreserveWhitespaces

  A
  B

DEMO

I've tried to inspect the HTML with Chrome DevTools but I still don't understand how its done.For all cases the HTML/CSS is identical. Anyway, it's probably very simple. Any suggestions?

Body:
By default display property of span is inline-block. This will create extra space between the span elements so we need to remove that by giving font-size: 0 to the parent element. And you have to give font-size to your child elements. Like here i have applied font-size:0; to parent element i.e div and applied font-size:1rem; to children span elements of div.

div{
  font-size: 0;
}
div>span{
  font-size:1rem;
}

<div>
 <span>A</span>
 <span>B</span>
</div>

<span id="total">X</span>
<span id="max">Y</span>


问:
Case insensitive filter query with Objectify + google appengine
Is there an easy way to do a case insensitive filter query with Objectify + google appengine (Java)? Essentially this is what I am trying to do except that I need the filter on email to be  case insensitive. </p>

```<code>Objectify objectifyService = ObjectifyService.begin();
objectifyService.query(AppUser.class).filter("email", email).get();
</code>```

答: You need to store your email address in a normalized (lowercase or uppercase, for instance) form in the datastore, and query on that. If you also need the original unmodified email address, you should store both separately.</p>

Body:
Is there an easy way to do a case insensitive filter query with Objectify + google appengine (Java)? Essentially this is what I am trying to do except that I need the filter on email to be  case insensitive.

Objectify objectifyService = ObjectifyService.begin();
objectifyService.query(AppUser.class).filter("email", email).get();


问:
Remove Property from Returned object in c#
I have a .net core 3.1 API that returns customer information.  In this return there is a password field.  How do I stop the password field from returning with the customer object?

```<code>// GET api/<CustomersController>/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Customer>> Get(Guid id)
        {
            var customer = await _context.Customers.FindAsync(id);
            if (customer == null)
            {
                return NotFound();
            }

            return customer;
        }
</code>```

I tried using JsonIgnore but that won't let me POST seeing as my model has a required field for password.

```<code>[Required]
[JsonIgnore]
public string Password { get; set; }
</code>```

答:
Make a DTO which doesn't contain a field for the password, and then return the DTO instead:

```<code>public class CustomerDTO
{
    // Customer's fields without the password
}
</code>```

```<code>[HttpGet("{id}")]
public async Task<ActionResult<CustomerDTO>> Get(Guid id)
{
    var customer = await _context.Customers.FindAsync(id);
    if (customer == null)
    {
        return NotFound();
    }
    var customerToReturn = MapCustomerToCustomerDTO(customer); // manually do this, or use some auto mapper
    return customerToReturn;
}
</code>```

Body:
I have a .net core 3.1 API that returns customer information.  In this return there is a password field.  How do I stop the password field from returning with the customer object?

// GET api/<CustomersController>/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Customer>> Get(Guid id)
        {
            var customer = await _context.Customers.FindAsync(id);
            if (customer == null)
            {
                return NotFound();
            }

            return customer;
        }

I tried using JsonIgnore but that won't let me POST seeing as my model has a required field for password.

[Required]
[JsonIgnore]
public string Password { get; set; }

Body:
Make a DTO which doesn't contain a field for the password, and then return the DTO instead:

public class CustomerDTO
{
    // Customer's fields without the password
}

[HttpGet("{id}")]
public async Task<ActionResult<CustomerDTO>> Get(Guid id)
{
    var customer = await _context.Customers.FindAsync(id);
    if (customer == null)
    {
        return NotFound();
    }
    var customerToReturn = MapCustomerToCustomerDTO(customer); // manually do this, or use some auto mapper
    return customerToReturn;
}


问:
How i can make welcome command and add option to set channel where it'll be sending?
I'm new discord bot developer and I wanted to add command that allows to set welcome channel in my bot, but I don't really know how to do it. I tried to find an answer, but all of them have defined id already, so it won't work on other servers. If you can help me or give me tip how to do it, please. </p>

<p>I mean I wanted to define channel id as an argument but how I can save it for server so it won't save it for all servers. </p>

答:
You'd need to set up a database and store the channel and server IDs there. If you're just starting out, try using LowDB, which isn't exactly what I'd call a "database", but should get the job done for now.

If you want to use an actual database that is still very easy to understand, give MongoDB a try.

To get your feature working, you'd need to store the server and channel IDs to the database, and check it whenever a new user joins.

Body:
I'm new discord bot developer and I wanted to add command that allows to set welcome channel in my bot, but I don't really know how to do it. I tried to find an answer, but all of them have defined id already, so it won't work on other servers. If you can help me or give me tip how to do it, please.

I mean I wanted to define channel id as an argument but how I can save it for server so it won't save it for all servers.


问:
how to get the value of foreign key in Laravel
I have a problem with Laravel model relationships. I need to let users create new trucks. However, I need to store manufacturer's field as an id, not a title. So I decided to make two tables (manufacturers and trucks) that have one to many relationship (manufacturers have multiple trucks while one truck has one manufacturer).

Here's the migrations files.
Manufacturers table:

```<code>public function up()
{
    Schema::create('manufacturers', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('manufacturer');
        $table->timestamps();
    });
}
</code>```

Trucks table:

```<code>public function up()
{
    Schema::create('trucks', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('make_id');
        $table->unsignedInteger('year');
        $table->string('owner');
        $table->unsignedInteger('owner_number')->nullable();
        $table->text('comments')->nullable();
        $table->foreign('make_id')->references('id')->on('manufacturers');

        $table->timestamps();
    });
}
</code>```

Manufacturer.php model:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Manufacturer extends Model
{
/**
 * @var string
 */
protected $table = 'manufacturers';

/**
 * @var array
 */
protected $fillable = [
    'manufacturer',
];

public function trucks(){
    return $this->hasMany(Truck::class);
}
}
</code>```

Truck.php model:

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

 class Truck extends Model
 {
 /**
 * @var string
 */
protected $table = 'trucks';

/**
 * @var array
 */
protected $fillable = [
    'make_id', 'year', 'owner', 'owner_number', 'comments',
];

public function manufacturer(){
    return $this->belongsTo(Manufacturer::class);
}
}
</code>```

Controller file:

```<code>public function index()
{
    $trucks = Truck::all();
    return view('trucks.index')->with('trucks', $trucks);
}
</code>```

index.blade.php

```<code>@foreach($trucks as $truck)
            <tbody>
            <tr>
                <td>{{$truck->make_id}}</td> //I need this one to show manufacturers title
                <td>{{$truck->year}}</td>
                <td>{{$truck->owner}}</td>
                <td>{{$truck->owner_number}}</td>
                <td>{{$truck->comments}}</td>
            </tr>
            </tbody>
            @endforeach
</code>```

This view now shows the id. What I need to do to show manufacturers title(manufacturers.manufacturer) instead of the id? Thank you all in advance!

答:
Your foreign key for manufacturer in trucks table is not manufacturer_id. In this case you need to declare it in your models:

```<code>return $this->belongsTo(Manufacturer::class, 'make_id' )
</code>```

And

```<code> return $this->hasMany(Truck::class, 'make_id' )
</code>```

Body:
I have a problem with Laravel model relationships. I need to let users create new trucks. However, I need to store manufacturer's field as an id, not a title. So I decided to make two tables (manufacturers and trucks) that have one to many relationship (manufacturers have multiple trucks while one truck has one manufacturer).

Here's the migrations files.
Manufacturers table:

public function up()
{
    Schema::create('manufacturers', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('manufacturer');
        $table->timestamps();
    });
}

Trucks table:

public function up()
{
    Schema::create('trucks', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->unsignedBigInteger('make_id');
        $table->unsignedInteger('year');
        $table->string('owner');
        $table->unsignedInteger('owner_number')->nullable();
        $table->text('comments')->nullable();
        $table->foreign('make_id')->references('id')->on('manufacturers');

        $table->timestamps();
    });
}

Manufacturer.php model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Manufacturer extends Model
{
/**
 * @var string
 */
protected $table = 'manufacturers';

/**
 * @var array
 */
protected $fillable = [
    'manufacturer',
];

public function trucks(){
    return $this->hasMany(Truck::class);
}
}

Truck.php model:

namespace App;

use Illuminate\Database\Eloquent\Model;

 class Truck extends Model
 {
 /**
 * @var string
 */
protected $table = 'trucks';

/**
 * @var array
 */
protected $fillable = [
    'make_id', 'year', 'owner', 'owner_number', 'comments',
];

public function manufacturer(){
    return $this->belongsTo(Manufacturer::class);
}
}

Controller file:

public function index()
{
    $trucks = Truck::all();
    return view('trucks.index')->with('trucks', $trucks);
}

index.blade.php

@foreach($trucks as $truck)

                {{$truck->make_id}}	 //I need this one to show manufacturers title
                {{$truck->year}}
                {{$truck->owner}}
                {{$truck->owner_number}}
                {{$truck->comments}}

            @endforeach

This view now shows the id. What I need to do to show manufacturers title(manufacturers.manufacturer) instead of the id? Thank you all in advance!

Body:
Your foreign key for manufacturer in trucks table is not manufacturer_id. In this case you need to declare it in your models:

return $this->belongsTo(Manufacturer::class, 'make_id' )

And

 return $this->hasMany(Truck::class, 'make_id' )


问:
Java : How to visualize/plot time intervals
I have a table with the following structure:

[interval_name, start_time, end_time]

I would like to visualize those time intervals over a plot with a time axis, Some thing like this but obviously much prettier.
Is there any free java library to do so? any ideas on how to visualize it by my own?

much appreciation to all :)

答:
I thought it would be interesting to create a timeline plot from scratch using Java Swing.

Here's the GUI I came up with.  You may have to right-click on the image and choose "Open link in new tab" to see the details clearly.

The first thing I did was to create an Event class.  I used LocalDateTime fields to hold the event start and event end.

I added a Color field to the Event class constructor so that the events on the plot can be drawn in different colors. In the example above, I used blue for personal time and black for work time.

Next, I created a TimeLine class to hold a List of events.

Then I created a timeline in the constructor of the main TimeLinePlot class.

Finally, I created a JFrame and a drawing JPanel.  I drew the timeline plot on the drawing JPanel.

This code is not meant to be a complete solution.  This code is meant to show the OP and others how to create a timeline plot.

```<code>import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TimeLinePlot implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new TimeLinePlot());
    }

    private final int plotWidth;
    private final int plotHeight;
    private final int margin;

    private int increment;

    private final String[] xAxis;

    private final TimeLine timeLine;

    public TimeLinePlot() {
        this.plotWidth = 1000;
        this.plotHeight = 500;
        this.margin = 50;
        this.timeLine = generateTimeLine();
        this.xAxis = createXAxis();
    }

    private TimeLine generateTimeLine() {
        TimeLine timeLine = new TimeLine();

        Event event = new Event("Breakfast", Color.BLUE,
                "5/29/2020 7:00AM", "5/29/2020 8:00AM");
        timeLine.addEvent(event);

        event = new Event("Shower", Color.BLUE,
                "5/29/2020 8:00AM", "5/29/2020 8:30AM");
        timeLine.addEvent(event);

        event = new Event("Stack Overflow", Color.BLACK,
                "5/29/2020 8:30AM", "5/29/2020 11:45AM");
        timeLine.addEvent(event);

        event = new Event("Lunch", Color.BLUE,
                "5/29/2020 11:30AM", "5/29/2020 12:30PM");
        timeLine.addEvent(event);

        event = new Event("Stack Overflow", Color.BLACK,
                "5/29/2020 12:00PM", "5/29/2020 4:30PM");
        timeLine.addEvent(event);

        return timeLine;
    }

    private String[] createXAxis() {
        LocalDateTime startDateTime =
                timeLine.getEarliestStartDate();
        LocalDateTime endDateTime =
                timeLine.getLatestEndDate();
        Duration duration = Duration.between(
                startDateTime, endDateTime);
//      System.out.println(duration);

        if (duration.toDays() > 0L) {
            // TODO Figure out a multi-day timeline
            return new String[0];
        } else {
            long minutes = duration.toMinutes();
            int hours = (int) Math.ceil(minutes / 60D);
//          System.out.println(hours);

            increment = 1;
            if (hours > 12) {
                increment = 2;
                hours /= 2;
            }

            String[] axis = new String[hours + 1];
            LocalDateTime dateTime = startDateTime;
            for (int i = 0; i <= hours; i += increment) {
                axis[i] = createTimeLabel(dateTime);
                dateTime = dateTime.plusHours(increment);
            }

//          System.out.println(Arrays.asList(axis));
            return axis;
        }
    }

    private String createTimeLabel(LocalDateTime dateTime) {
        return dateTime.format(
                DateTimeFormatter.ofPattern("h:mm a"));
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Time Line Plot");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        TimeLinePanel timeLinePanel = new TimeLinePanel(
                plotWidth, plotHeight, margin, timeLine,
                increment, xAxis);
        frame.add(timeLinePanel, BorderLayout.CENTER);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public class TimeLinePanel extends JPanel {

        private static final long serialVersionUID = 1L;

        private final int plotWidth;
        private final int plotHeight;
        private final int margin;
        private final int tickLength;
        private final int increment;

        private final String[] xAxis;

        private final TimeLine timeLine;

        public TimeLinePanel(int plotWidth, int plotHeight,
                int margin, TimeLine timeLine, int increment,
                String[] xAxis) {
            this.plotWidth = plotWidth;
            this.plotHeight = plotHeight;
            this.margin = margin;
            this.tickLength = 20;
            this.increment = increment;
            this.timeLine = timeLine;
            this.xAxis = xAxis;
            this.setPreferredSize(new Dimension(
                    plotWidth, plotHeight));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g;
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, getWidth(), getHeight());

            g2d.setFont(getFont().deriveFont(14f)
                    .deriveFont(Font.BOLD));
            createXAxis(g2d);
            createTimeLines(g2d);
        }

        private void createXAxis(Graphics2D g2d) {
            int height = plotHeight - margin;
            int width = plotWidth - margin * 4;
            int pixelGap = width / (xAxis.length - 1);

            int x = margin + margin;
            int x1 = x;
            int y = height - tickLength - 10;

            g2d.setColor(Color.BLACK);
            g2d.setStroke(new BasicStroke(3f));
            FontMetrics metrics = g2d.getFontMetrics(getFont());
            for (int i = 0; i < xAxis.length; i++) {
                g2d.drawLine(x, y, x, y + tickLength);

                int a = x - metrics.stringWidth(xAxis[i]) / 2;
                int b = y + tickLength + metrics.getHeight() / 2 +
                        metrics.getAscent();
                g2d.drawString(xAxis[i], a, b);
                x += pixelGap;
            }
            g2d.drawLine(x1, y, x - pixelGap, y);
        }

        private void createTimeLines(Graphics2D g2d) {
            LocalDateTime earliestStartTime =
                    timeLine.getEarliestStartDate();
            List<Event> events = timeLine.getEvents();

            int height = plotHeight - margin;
            int width = plotWidth - margin * 4;
            int pixelGapH = height / events.size();
            int pixelGapW = width / (xAxis.length - 1);

            int x = margin + margin;
            int y = height - tickLength - 30;

            g2d.setStroke(new BasicStroke(9f));
            FontMetrics metrics = g2d.getFontMetrics(getFont());
            for (int i = events.size() - 1; i >= 0; i--) {
                Event event = events.get(i);
                LocalDateTime startTime = event.getStartTime();
                LocalDateTime endTime = event.getEndTime();

                Duration duration1 = Duration.between(
                        earliestStartTime, startTime);
                Duration duration2 = Duration.between(
                        earliestStartTime, endTime);
                long minutes1 = duration1.toMinutes();
                long minutes2 = duration2.toMinutes();
                String text = event.getName();

                int a1 = x + (int) (Math.round((double) minutes1 *
                        pixelGapW * increment / 60D));
                int a2 = x + (int) (Math.round((double) minutes2 *
                        pixelGapW * increment / 60D));
                int a = a1 + ((a2 - a1) / 2) -
                        (metrics.stringWidth(text) / 2) - 4;
                int b = y - 8;

                g2d.setColor(event.getColor());
                g2d.drawLine(a1, y, a2, y);
                g2d.drawString(text, a, b);

                y -= pixelGapH;
            }

        }

    }

    public class TimeLine {

        private List<Event> events;

        public TimeLine() {
            this.events = new ArrayList<>();
        }

        public void addEvent(Event event) {
            this.events.add(event);
        }

        public List<Event> getEvents() {
            return events;
        }

        public LocalDateTime getEarliestStartDate() {
            LocalDateTime minimumStartDateTime = null;

            for (Event event : events) {
                if (minimumStartDateTime == null ||
                        event.getStartTime().compareTo(
                                minimumStartDateTime) < 0) {
                    minimumStartDateTime = event.getStartTime();
                }
            }

            return minimumStartDateTime;
        }

        public LocalDateTime getLatestEndDate() {
            LocalDateTime maximumEndDateTime = null;

            for (Event event : events) {
                if (maximumEndDateTime == null ||
                        event.getEndTime().compareTo(
                                maximumEndDateTime) > 0) {
                    maximumEndDateTime = event.getEndTime();
                }
            }

            return maximumEndDateTime;
        }

    }

    public class Event {

        private final DateTimeFormatter formatter =
                DateTimeFormatter.ofPattern("M/d/yyyy h:mma");

        private Color color;

        private final String name;

        private final LocalDateTime startTime;
        private final LocalDateTime endTime;

        public Event(String name, Color color, String startTimeString,
                String endTimeString) {
            this.name = name;
            this.color = color;
            this.startTime = LocalDateTime.parse(startTimeString,
                    formatter);
            this.endTime = LocalDateTime.parse(endTimeString,
                    formatter);
        }

        public String getName() {
            return name;
        }

        public Color getColor() {
            return color;
        }

        public LocalDateTime getStartTime() {
            return startTime;
        }

        public LocalDateTime getEndTime() {
            return endTime;
        }

    }

}
</code>```

Body:
I thought it would be interesting to create a timeline plot from scratch using Java Swing.

Here's the GUI I came up with.  You may have to right-click on the image and choose "Open link in new tab" to see the details clearly.

The first thing I did was to create an Event class.  I used LocalDateTime fields to hold the event start and event end.

I added a Color field to the Event class constructor so that the events on the plot can be drawn in different colors. In the example above, I used blue for personal time and black for work time.

Next, I created a TimeLine class to hold a List of events.

Then I created a timeline in the constructor of the main TimeLinePlot class.

Finally, I created a JFrame and a drawing JPanel.  I drew the timeline plot on the drawing JPanel.

This code is not meant to be a complete solution.  This code is meant to show the OP and others how to create a timeline plot.

import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class TimeLinePlot implements Runnable {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new TimeLinePlot());
    }

    private final int plotWidth;
    private final int plotHeight;
    private final int margin;

    private int increment;

    private final String[] xAxis;

    private final TimeLine timeLine;

    public TimeLinePlot() {
        this.plotWidth = 1000;
        this.plotHeight = 500;
        this.margin = 50;
        this.timeLine = generateTimeLine();
        this.xAxis = createXAxis();
    }

    private TimeLine generateTimeLine() {
        TimeLine timeLine = new TimeLine();

        Event event = new Event("Breakfast", Color.BLUE,
                "5/29/2020 7:00AM", "5/29/2020 8:00AM");
        timeLine.addEvent(event);

        event = new Event("Shower", Color.BLUE,
                "5/29/2020 8:00AM", "5/29/2020 8:30AM");
        timeLine.addEvent(event);

        event = new Event("Stack Overflow", Color.BLACK,
                "5/29/2020 8:30AM", "5/29/2020 11:45AM");
        timeLine.addEvent(event);

        event = new Event("Lunch", Color.BLUE,
                "5/29/2020 11:30AM", "5/29/2020 12:30PM");
        timeLine.addEvent(event);

        event = new Event("Stack Overflow", Color.BLACK,
                "5/29/2020 12:00PM", "5/29/2020 4:30PM");
        timeLine.addEvent(event);

        return timeLine;
    }

    private String[] createXAxis() {
        LocalDateTime startDateTime =
                timeLine.getEarliestStartDate();
        LocalDateTime endDateTime =
                timeLine.getLatestEndDate();
        Duration duration = Duration.between(
                startDateTime, endDateTime);
//      System.out.println(duration);

        if (duration.toDays() > 0L) {
            // TODO Figure out a multi-day timeline
            return new String[0];
        } else {
            long minutes = duration.toMinutes();
            int hours = (int) Math.ceil(minutes / 60D);
//          System.out.println(hours);

            increment = 1;
            if (hours > 12) {
                increment = 2;
                hours /= 2;
            }

            String[] axis = new String[hours + 1];
            LocalDateTime dateTime = startDateTime;
            for (int i = 0; i <= hours; i += increment) {
                axis[i] = createTimeLabel(dateTime);
                dateTime = dateTime.plusHours(increment);
            }

//          System.out.println(Arrays.asList(axis));
            return axis;
        }
    }

    private String createTimeLabel(LocalDateTime dateTime) {
        return dateTime.format(
                DateTimeFormatter.ofPattern("h:mm a"));
    }

    @Override
    public void run() {
        JFrame frame = new JFrame("Time Line Plot");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        TimeLinePanel timeLinePanel = new TimeLinePanel(
                plotWidth, plotHeight, margin, timeLine,
                increment, xAxis);
        frame.add(timeLinePanel, BorderLayout.CENTER);

        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public class TimeLinePanel extends JPanel {

        private static final long serialVersionUID = 1L;

        private final int plotWidth;
        private final int plotHeight;
        private final int margin;
        private final int tickLength;
        private final int increment;

        private final String[] xAxis;

        private final TimeLine timeLine;

        public TimeLinePanel(int plotWidth, int plotHeight,
                int margin, TimeLine timeLine, int increment,
                String[] xAxis) {
            this.plotWidth = plotWidth;
            this.plotHeight = plotHeight;
            this.margin = margin;
            this.tickLength = 20;
            this.increment = increment;
            this.timeLine = timeLine;
            this.xAxis = xAxis;
            this.setPreferredSize(new Dimension(
                    plotWidth, plotHeight));
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);

            Graphics2D g2d = (Graphics2D) g;
            g2d.setColor(Color.WHITE);
            g2d.fillRect(0, 0, getWidth(), getHeight());

            g2d.setFont(getFont().deriveFont(14f)
                    .deriveFont(Font.BOLD));
            createXAxis(g2d);
            createTimeLines(g2d);
        }

        private void createXAxis(Graphics2D g2d) {
            int height = plotHeight - margin;
            int width = plotWidth - margin * 4;
            int pixelGap = width / (xAxis.length - 1);

            int x = margin + margin;
            int x1 = x;
            int y = height - tickLength - 10;

            g2d.setColor(Color.BLACK);
            g2d.setStroke(new BasicStroke(3f));
            FontMetrics metrics = g2d.getFontMetrics(getFont());
            for (int i = 0; i < xAxis.length; i++) {
                g2d.drawLine(x, y, x, y + tickLength);

                int a = x - metrics.stringWidth(xAxis[i]) / 2;
                int b = y + tickLength + metrics.getHeight() / 2 +
                        metrics.getAscent();
                g2d.drawString(xAxis[i], a, b);
                x += pixelGap;
            }
            g2d.drawLine(x1, y, x - pixelGap, y);
        }

        private void createTimeLines(Graphics2D g2d) {
            LocalDateTime earliestStartTime =
                    timeLine.getEarliestStartDate();
            List<Event> events = timeLine.getEvents();

            int height = plotHeight - margin;
            int width = plotWidth - margin * 4;
            int pixelGapH = height / events.size();
            int pixelGapW = width / (xAxis.length - 1);

            int x = margin + margin;
            int y = height - tickLength - 30;

            g2d.setStroke(new BasicStroke(9f));
            FontMetrics metrics = g2d.getFontMetrics(getFont());
            for (int i = events.size() - 1; i >= 0; i--) {
                Event event = events.get(i);
                LocalDateTime startTime = event.getStartTime();
                LocalDateTime endTime = event.getEndTime();

                Duration duration1 = Duration.between(
                        earliestStartTime, startTime);
                Duration duration2 = Duration.between(
                        earliestStartTime, endTime);
                long minutes1 = duration1.toMinutes();
                long minutes2 = duration2.toMinutes();
                String text = event.getName();

                int a1 = x + (int) (Math.round((double) minutes1 *
                        pixelGapW * increment / 60D));
                int a2 = x + (int) (Math.round((double) minutes2 *
                        pixelGapW * increment / 60D));
                int a = a1 + ((a2 - a1) / 2) -
                        (metrics.stringWidth(text) / 2) - 4;
                int b = y - 8;

                g2d.setColor(event.getColor());
                g2d.drawLine(a1, y, a2, y);
                g2d.drawString(text, a, b);

                y -= pixelGapH;
            }

        }

    }

    public class TimeLine {

        private List<Event> events;

        public TimeLine() {
            this.events = new ArrayList<>();
        }

        public void addEvent(Event event) {
            this.events.add(event);
        }

        public List<Event> getEvents() {
            return events;
        }

        public LocalDateTime getEarliestStartDate() {
            LocalDateTime minimumStartDateTime = null;

            for (Event event : events) {
                if (minimumStartDateTime == null ||
                        event.getStartTime().compareTo(
                                minimumStartDateTime) < 0) {
                    minimumStartDateTime = event.getStartTime();
                }
            }

            return minimumStartDateTime;
        }

        public LocalDateTime getLatestEndDate() {
            LocalDateTime maximumEndDateTime = null;

            for (Event event : events) {
                if (maximumEndDateTime == null ||
                        event.getEndTime().compareTo(
                                maximumEndDateTime) > 0) {
                    maximumEndDateTime = event.getEndTime();
                }
            }

            return maximumEndDateTime;
        }

    }

    public class Event {

        private final DateTimeFormatter formatter =
                DateTimeFormatter.ofPattern("M/d/yyyy h:mma");

        private Color color;

        private final String name;

        private final LocalDateTime startTime;
        private final LocalDateTime endTime;

        public Event(String name, Color color, String startTimeString,
                String endTimeString) {
            this.name = name;
            this.color = color;
            this.startTime = LocalDateTime.parse(startTimeString,
                    formatter);
            this.endTime = LocalDateTime.parse(endTimeString,
                    formatter);
        }

        public String getName() {
            return name;
        }

        public Color getColor() {
            return color;
        }

        public LocalDateTime getStartTime() {
            return startTime;
        }

        public LocalDateTime getEndTime() {
            return endTime;
        }

    }

}


问:
How to display a function defined message after a successful login or failure
I have a function in my functions.php that uses session to display message whenever record is inserted or could not. My problem is that after the insertion the message does not display even though I started the session in my header.php which is included on the employees.php page and I have also called the message on the same page after setting it in my logic. Below are the codes:</p>

```<code>else{
//Query to Insert/Add Employees in employees Table
$db->query('INSERT INTO employees(id, firstName, lastName, username, email, password, employeeId, joiningDate, phone, role)VALUES(NULL, :fname, :lname, :username, :email, :password, :employeeId, :joiningDate, :phone, :role)');

//Bind Values to Query Parameters
$db->bindValue(':fname', $c_fname, PDO::PARAM_STR);
$db->bindValue(':lname', $c_lname, PDO::PARAM_STR);
$db->bindValue(':username', $c_username, PDO::PARAM_STR);
$db->bindValue(':email', $c_email, PDO::PARAM_STR);
$db->bindValue(':password', $Hashed_Pass, PDO::PARAM_STR);
$db->bindValue(':employeeId', $c_employId, PDO::PARAM_STR);
$db->bindValue(':joiningDate', $c_jdate, PDO::PARAM_STR);
$db->bindValue(':phone', $c_phone, PDO::PARAM_INT);
$db->bindValue(':role', $c_role, PDO::PARAM_STR);

//Query to Check whether Staff Already Exist using Email

//Run Query
$run_employee    = $db->execute();

if($run_employee){

    redirect('employees.php');
    //Closeable Alert Message
    keepmsg('<div class="alert alert-success text-center">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
        <strong>Success!</strong> Employee Registered Successfully.
        </div>');
}else{
    //Closeable Alert Message
    keepmsg('<div class="alert alert-danger text-center">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
        <strong>Not Successful!</strong> Employee Was Not Registered.
        </div>');
    }

}
</code>```

答:
Looks like you are calling

```<code>redirect('employees.php');
</code>```

before setting/displaying the message.

Body:
I have a function in my functions.php that uses session to display message whenever record is inserted or could not. My problem is that after the insertion the message does not display even though I started the session in my header.php which is included on the employees.php page and I have also called the message on the same page after setting it in my logic. Below are the codes:

else{
//Query to Insert/Add Employees in employees Table
$db->query('INSERT INTO employees(id, firstName, lastName, username, email, password, employeeId, joiningDate, phone, role)VALUES(NULL, :fname, :lname, :username, :email, :password, :employeeId, :joiningDate, :phone, :role)');

//Bind Values to Query Parameters
$db->bindValue(':fname', $c_fname, PDO::PARAM_STR);
$db->bindValue(':lname', $c_lname, PDO::PARAM_STR);
$db->bindValue(':username', $c_username, PDO::PARAM_STR);
$db->bindValue(':email', $c_email, PDO::PARAM_STR);
$db->bindValue(':password', $Hashed_Pass, PDO::PARAM_STR);
$db->bindValue(':employeeId', $c_employId, PDO::PARAM_STR);
$db->bindValue(':joiningDate', $c_jdate, PDO::PARAM_STR);
$db->bindValue(':phone', $c_phone, PDO::PARAM_INT);
$db->bindValue(':role', $c_role, PDO::PARAM_STR);

//Query to Check whether Staff Already Exist using Email

//Run Query
$run_employee    = $db->execute();

if($run_employee){

    redirect('employees.php');
    //Closeable Alert Message
    keepmsg('

        ×
        Success! Employee Registered Successfully.

');
}else{
    //Closeable Alert Message
    keepmsg('

        ×
        Not Successful! Employee Was Not Registered.

');
    }

}

Body:
Looks like you are calling

redirect('employees.php');

before setting/displaying the message.


问:
Android Retrofit - Models are GSON arrays from API
When receiving data from an open weather API I am receiving nulls. I am using retroFit2 within android to get the data. Here is the message from the log:

```<code> onResponse: server response Response{protocol=http/1.1, code=200, message=OK,
 onResponse: WeatherResponse{weather=com.weatherapp.models.Weather@197d237}
</code>```

Here is the GSON:

```<code> {
"coord": {
    "lon": -5.93,
    "lat": 54.58
},
"weather": [
    {
        "id": 804,
        "main": "Clouds",
        "description": "overcast clouds",
        "icon": "04d"
    }
],
"base": "stations",
"main": {
    "temp": 293.15,
    "feels_like": 288.01,
    "temp_min": 293.15,
    "temp_max": 293.15,
    "pressure": 1024,
    "humidity": 37
},
"visibility": 10000,
"wind": {
    "speed": 5.7,
    "deg": 160
},
"clouds": {
    "all": 96
},
"dt": 1590770221,
"sys": {
    "type": 1,
    "id": 1376,
    "country": "GB",
    "sunrise": 1590724667,
    "sunset": 1590785095
},
</code>```

MODEL

```<code>@SerializedName("coord")
@Expose
private CoOrdinateModel coOrdinateModel;

@SerializedName("weather")
@Expose
private WeatherModel[] weatherModel;

@SerializedName("main")
@Expose
private MainModel main;

@SerializedName("visibility")
@Expose
private String visibility;

@SerializedName("wind")
@Expose
private WindModel wind;
</code>```

RESPONSE

```<code> public class WeatherResponse {

@SerializedName("coord")
@Expose()
private Weather weather;

public Weather getWeather() {
    return weather;
}

@Override
public String toString() {
    return "WeatherResponse{" +
            "weather=" + weather +
            '}';
}
}
</code>```

API

```<code>  @GET("/data/2.5/weather")
Call<WeatherResponse> getWeather(
        @Query("id") String ID,
        @Query("APPID") String API_KEY
);
</code>```

I ideally need almost all the data from the GSON to parse through into java objects within the android app. I've done this before with simpler GSON, but this one has arrays inside and I'm not sure if my MODEL class is done correctly to accommodate this.

Any help in identifying the root cause of the nulls would be greatly appreciated

答:
Those "arrays" you're talking about aren't arrays, they're nested objects (well, weather is an array of objects, but still). In order to handle this, you need to create nested classes on your model class to handle the nested object types, like so:

```<code>public class Weather {
    public class Coordinate {
        @SerializedName("lat")
        @Expose
        public float lat;

        @SerializedName("long")
        @Expose
        public float long;
    }

    // ...

    @SerializedName("coord")
    @Expose
    public Coordinate coOrd;

    // repeat for every nested object type
}
</code>```

For the weather key specifically, remember that that is an array of objects, and as such the field on your model should be declared as:

```<code>public WeatherData[] weather; // or whatever you name the nested class as
                              // I wouldn't recommend Weather, since you've
                              // already named your model that
</code>```

Body:
When receiving data from an open weather API I am receiving nulls. I am using retroFit2 within android to get the data. Here is the message from the log:

 onResponse: server response Response{protocol=http/1.1, code=200, message=OK,
 onResponse: WeatherResponse{weather=com.weatherapp.models.Weather@197d237}

Here is the GSON:

 {
"coord": {
    "lon": -5.93,
    "lat": 54.58
},
"weather": [
    {
        "id": 804,
        "main": "Clouds",
        "description": "overcast clouds",
        "icon": "04d"
    }
],
"base": "stations",
"main": {
    "temp": 293.15,
    "feels_like": 288.01,
    "temp_min": 293.15,
    "temp_max": 293.15,
    "pressure": 1024,
    "humidity": 37
},
"visibility": 10000,
"wind": {
    "speed": 5.7,
    "deg": 160
},
"clouds": {
    "all": 96
},
"dt": 1590770221,
"sys": {
    "type": 1,
    "id": 1376,
    "country": "GB",
    "sunrise": 1590724667,
    "sunset": 1590785095
},

MODEL

@SerializedName("coord")
@Expose
private CoOrdinateModel coOrdinateModel;

@SerializedName("weather")
@Expose
private WeatherModel[] weatherModel;

@SerializedName("main")
@Expose
private MainModel main;

@SerializedName("visibility")
@Expose
private String visibility;

@SerializedName("wind")
@Expose
private WindModel wind;

RESPONSE

 public class WeatherResponse {

@SerializedName("coord")
@Expose()
private Weather weather;

public Weather getWeather() {
    return weather;
}

@Override
public String toString() {
    return "WeatherResponse{" +
            "weather=" + weather +
            '}';
}
}

API

  @GET("/data/2.5/weather")
Call<WeatherResponse> getWeather(
        @Query("id") String ID,
        @Query("APPID") String API_KEY
);

I ideally need almost all the data from the GSON to parse through into java objects within the android app. I've done this before with simpler GSON, but this one has arrays inside and I'm not sure if my MODEL class is done correctly to accommodate this.

Any help in identifying the root cause of the nulls would be greatly appreciated

Body:
Those "arrays" you're talking about aren't arrays, they're nested objects (well, weather is an array of objects, but still). In order to handle this, you need to create nested classes on your model class to handle the nested object types, like so:

public class Weather {
    public class Coordinate {
        @SerializedName("lat")
        @Expose
        public float lat;

        @SerializedName("long")
        @Expose
        public float long;
    }

    // ...

    @SerializedName("coord")
    @Expose
    public Coordinate coOrd;

    // repeat for every nested object type
}

For the weather key specifically, remember that that is an array of objects, and as such the field on your model should be declared as:

public WeatherData[] weather; // or whatever you name the nested class as
                              // I wouldn't recommend Weather, since you've
                              // already named your model that


问:
jQuery: binding a single event listener that can handle events of its children
I encountered a question to which I didn't know the solution for.

Suppose I have this HTML markup (dynamically generated by the server or simply a static file):

```<code><ul class="myList">
<li><a href="page1.html">Page 1</a></li>
<li><a href="page2.html">Page 2</a></li>
<li><a href="page3.html">Page 3</a></li>
<li><a href="page4.html">Page 4</a></li>
<li><a href="page5.html">Page 5</a></li>
<li><a href="page6.html">Page 6</a></li>
<!-- ... -->
<li><a href="page1000.html">Page 1000</a></li>
</ul>
</code>```

I want to bind a click event handler to the  tag.  Normally, I would write out

```<code>$('.myList').find('a').click(function() {});  /* Or something similar */
</code>```

which would perform implicit iteration on all the anchor tags to bind a click event to each of them.  However, I was told that this is an expensive operation.

I was asked if there was some way to attach only one event listener (on the ul tag) and use event bubbling to figure out which anchor tag was clicked.  I have never encountered something like this, so I didn't know the answer.  Apparently, there is an answer.  Does anybody know how to place a single event listener on an element and have it figure out which child element was clicked?  (I still need to use event.preventDefault() to prevent the default click event.)

答:
The function you attach will have an event parameter that contains the object which is clicked in event.target.

```<code> $(.....).click(function(event){  ....  });
</code>```

Another solution, more complex, but more flexible too, although you won't need it in this situation, is to use the .bind method and specify a data object

```<code>$(.....).bind('click', {whateverproperty: whatevervalue}, function(event){ ... });
</code>```

In that case, you can reach event.data.whateverproperty, thus retrieving the value whatevervalue, allowing you to make more complex decisions.

Body:
I encountered a question to which I didn't know the solution for.

Suppose I have this HTML markup (dynamically generated by the server or simply a static file):

Page 1

Page 2

Page 3

Page 4

Page 5

Page 6

Page 1000

I want to bind a click event handler to the  tag.  Normally, I would write out

$('.myList').find('a').click(function() {});  /* Or something similar */

which would perform implicit iteration on all the anchor tags to bind a click event to each of them.  However, I was told that this is an expensive operation.

I was asked if there was some way to attach only one event listener (on the ul tag) and use event bubbling to figure out which anchor tag was clicked.  I have never encountered something like this, so I didn't know the answer.  Apparently, there is an answer.  Does anybody know how to place a single event listener on an element and have it figure out which child element was clicked?  (I still need to use event.preventDefault() to prevent the default click event.)

Body:
The function you attach will have an event parameter that contains the object which is clicked in event.target.

 $(.....).click(function(event){  ....  });

Another solution, more complex, but more flexible too, although you won't need it in this situation, is to use the .bind method and specify a data object

$(.....).bind('click', {whateverproperty: whatevervalue}, function(event){ ... });

In that case, you can reach event.data.whateverproperty, thus retrieving the value whatevervalue, allowing you to make more complex decisions.


问:
This code work for only 4 or 5 iteration, how is this possible?
my code is genetic algorithm and its only works for 4-5 times and after 4-5. work, suddenly stops and gives error "IndexError: index 22 is out of bounds for axis 0 with size 22" ,I paid attention to making "-1" to avoid index error, but the code still insists on stopping. It's genetic algorithm code, and its solving traveling salesman problem, its gives error when crossOver time.

```<code># -*- coding: utf-8 -*-
"""

"""
import numpy as np
import copy
coord=[]
coord = np.array([[11, 47, 62],
       [31, 37, 69],
       [32, 38, 46],
       [33, 46, 10],
       [34, 61, 33],
       [35, 62, 63],
       [36, 63, 69],
       [37, 32, 22],
       [38, 45, 35],
       [39, 59, 15],
       [40, 5, 6],
       [41, 10, 17],
       [42, 21, 10],
       [43, 5, 64],
       [44, 30, 15],
       [45, 39, 10],
       [46, 32, 39],
       [47, 25, 32],
       [48, 25, 55],
       [49, 48, 28],
       [50, 56, 37],
       [61, 40, 50]],dtype=np.int)
city=len(coord)
best_solution=[]
best_fitness=100000000
pop_size=1000
CR=0.5 # %YÜZDE 90 OLASILIKLA CAPRAZLANIYOR.
# MR=0.5
MR=5

MaxIter=5000

# distance = np.zeros((coord.shape[0], coord.shape[0]))
distance = np.zeros([city,city])

for i in range(city):
    for j in range(city):
        distance[i][j] = np.sqrt((coord[i][1] - coord[j][1]) ** 2 + (coord[i][2] - coord[j][2]) ** 2)

population=np.zeros([pop_size,city],dtype=np.int)
for i in range(pop_size):
    population[i][:]=np.random.permutation(city)

fitness=np.zeros([1,pop_size])

for i in range(pop_size):
    fitness[0][i]=0
    for j in range(city-1):
        # fitness[0][i]=fitness[0][i]+distance[[population[i][j]][population[i][j+1]]]
        fitness[0][i]=fitness[0][i]+ distance[population[i][j]][population[i][j+1]]
    fitness[0][i]=fitness[0][i]+ distance[population[i][city-1]][population[i][1]]
    if best_fitness > fitness[0][i]:
        best_solution=population[i][:]
        best_fitness=fitness[0][i]
        denemeFit= best_fitness

b=np.min(fitness) # there is no lower than this value but it gives 13 or 20.

   # while dongusu gelecek*/*/*/*/*/*/*/*/*/*
iteration=0;
fitness=1000./fitness
while iteration<MaxIter:
    total=np.sum(fitness)
    n_fitness=fitness/total
    c_fitness=np.zeros([1,pop_size])
    c_fitness[0][0]=n_fitness[0][0]
    for i in range(1,pop_size):
          c_fitness[0][i]=n_fitness[0][0]+c_fitness[0][i-1]
    c_count=-1
    c_pop=np.zeros([pop_size,city],dtype=np.int)

    while c_count < pop_size-1: # while dongusu gelecek*/*/*/*/*/*/*/*/*/*
                 r=np.random.rand()
                 for i in range(pop_size-1):
                    if c_fitness[0][i] >= r:
                        p1=i
                        break

                 p2=p1
                 while p2==p1:
                    r=np.random.rand()
                    for i in range(pop_size-1):
                        if c_fitness[0][i] >= r:
                            p2=i
                            break

                 r1=np.random.rand()
                 if r1 < CR:
                    parent1=population[p1][:]
                    parent2=population[p2][:]
                    point1=np.random.randint(city-1)
                    point2=point1
                    while abs(point1-point2)<4:
                        point2=np.random.randint(city-1)
                    if point2<point1:
                                deepo=point2
                                point2=point1
                                point1=deepo

                    child1=copy.copy(parent1)
                    child2=copy.copy(parent2)

                    # copy_list = org_list[:]

                    counter=point1
                    for i in range(city-1):
                        for j in range(point1+1,point2):
                            if parent2[i]==parent1[j]:
                                counter=counter+1
                                child1[counter]=parent2[i]
                    counter=point1
                    for i in range(city-1):
                        for j in range(point1+1,point2):
                            if parent1[i]==parent2[j]:
                                counter=counter+1
                                child2[counter]=parent1[i]

                    c_count=c_count+2
                    c_pop[c_count-1][:]=child1
                    c_pop[c_count][:]=child2

    c_fitness=np.zeros([1,pop_size])
    for i in range(pop_size):
        c_fitness[0][i]=0
        for j in range(city-1):
            # fitness[0][i]=fitness[0][i]+distance[[population[i][j]][population[i][j+1]]]
            c_fitness[0][i]=c_fitness[0][i]+ distance[c_pop[i][j]][c_pop[i][j+1]]
        c_fitness[0][i]=c_fitness[0][i]+ distance[c_pop[i][city-1]][c_pop[i][1]]
        if best_fitness > c_fitness[0][i]:
            best_solution=c_pop[i][:]
            best_fitness=c_fitness[0][i]

    m_pop=copy.copy(c_pop)
    for i in range(pop_size):
        r2=np.random.rand()
        if r2 <= MR:
            city1=np.random.randint(city-1)
            city2=city1
            while city2==city1:
                city2=np.random.randint(city-1)

            deepo=m_pop[i][city1]
            m_pop[i][city1]=m_pop[i][city2]
            m_pop[i][city2]=deepo

    m_fitness=np.zeros([1,pop_size])
    for i in range(pop_size):
        m_fitness[0][i]=0
        for j in range(city-1):
            # fitness[0][i]=fitness[0][i]+distance[[population[i][j]][population[i][j+1]]]
            m_fitness[0][i]=m_fitness[0][i]+ distance[m_pop[i][j]][m_pop[i][j+1]]
        m_fitness[0][i]=m_fitness[0][i]+ distance[m_pop[i][city-1]][m_pop[i][1]]
        if best_fitness > m_fitness[0][i]:
            best_solution=m_pop[i][:]
            best_fitness=m_fitness[0][i]

    population=copy.copy(m_pop)
    fitness=copy.copy(m_fitness)
    population[1][:]=best_solution
    fitness[0][1]=best_fitness
    iteration=iteration+1
    print(iteration)
    print(best_fitness)
    # print(best_solution)

</code>```

it returns this:

```<code>Traceback (most recent call last):

  File "C:\Users\\Google Drive\python\untitled0.py", line 135, in <module>
    child2[counter]=parent1[i]

IndexError: index 22 is out of bounds for axis 0 with size 22
</code>```

答:
OK found the problem. In the following loops counter can indeed end up >21

```<code>counter=point1
for i in range(city-1):
    for j in range(point1+1,point2):
        if parent2[i]==parent1[j]:
            counter=counter+1
            child1[counter]=parent2[i]

counter=point1
for i in range(city-1):
    for j in range(point1+1,point2):
        if parent1[i]==parent2[j]:
            counter=counter+1
            child2[counter]=parent1[i]
</code>```

Consider the case when for every iteration of j that if parent2[i]==parent1[j]: is True then counter is incremented by j times multiplied by city-1 times which can easily by above 21 as city-1 = 21

To remedy it you need to reset counter for each iteration of the i loop,

```<code>for i in range(city-1):
    counter=point1
    for j in range(point1+1,point2):
        if parent2[i]==parent1[j]:
            counter=counter+1
            child1[counter]=parent2[i]

for i in range(city-1):
    counter=point1
    for j in range(point1+1,point2):
        if parent1[i]==parent2[j]:
            counter=counter+1
            child2[counter]=parent1[i]
</code>```

Body:
my code is genetic algorithm and its only works for 4-5 times and after 4-5. work, suddenly stops and gives error "IndexError: index 22 is out of bounds for axis 0 with size 22" ,I paid attention to making "-1" to avoid index error, but the code still insists on stopping. It's genetic algorithm code, and its solving traveling salesman problem, its gives error when crossOver time.

# -*- coding: utf-8 -*-
"""

"""
import numpy as np
import copy
coord=[]
coord = np.array([[11, 47, 62],
       [31, 37, 69],
       [32, 38, 46],
       [33, 46, 10],
       [34, 61, 33],
       [35, 62, 63],
       [36, 63, 69],
       [37, 32, 22],
       [38, 45, 35],
       [39, 59, 15],
       [40, 5, 6],
       [41, 10, 17],
       [42, 21, 10],
       [43, 5, 64],
       [44, 30, 15],
       [45, 39, 10],
       [46, 32, 39],
       [47, 25, 32],
       [48, 25, 55],
       [49, 48, 28],
       [50, 56, 37],
       [61, 40, 50]],dtype=np.int)
city=len(coord)
best_solution=[]
best_fitness=100000000
pop_size=1000
CR=0.5 # %YÜZDE 90 OLASILIKLA CAPRAZLANIYOR.
# MR=0.5
MR=5

MaxIter=5000

# distance = np.zeros((coord.shape[0], coord.shape[0]))
distance = np.zeros([city,city])

for i in range(city):
    for j in range(city):
        distance[i][j] = np.sqrt((coord[i][1] - coord[j][1]) ** 2 + (coord[i][2] - coord[j][2]) ** 2)

population=np.zeros([pop_size,city],dtype=np.int)
for i in range(pop_size):
    population[i][:]=np.random.permutation(city)

fitness=np.zeros([1,pop_size])

for i in range(pop_size):
    fitness[0][i]=0
    for j in range(city-1):
        # fitness[0][i]=fitness[0][i]+distance[[population[i][j]][population[i][j+1]]]
        fitness[0][i]=fitness[0][i]+ distance[population[i][j]][population[i][j+1]]
    fitness[0][i]=fitness[0][i]+ distance[population[i][city-1]][population[i][1]]
    if best_fitness > fitness[0][i]:
        best_solution=population[i][:]
        best_fitness=fitness[0][i]
        denemeFit= best_fitness

b=np.min(fitness) # there is no lower than this value but it gives 13 or 20.

   # while dongusu gelecek*/*/*/*/*/*/*/*/*/*
iteration=0;
fitness=1000./fitness
while iteration<MaxIter:
    total=np.sum(fitness)
    n_fitness=fitness/total
    c_fitness=np.zeros([1,pop_size])
    c_fitness[0][0]=n_fitness[0][0]
    for i in range(1,pop_size):
          c_fitness[0][i]=n_fitness[0][0]+c_fitness[0][i-1]
    c_count=-1
    c_pop=np.zeros([pop_size,city],dtype=np.int)

    while c_count < pop_size-1: # while dongusu gelecek*/*/*/*/*/*/*/*/*/*
                 r=np.random.rand()
                 for i in range(pop_size-1):
                    if c_fitness[0][i] >= r:
                        p1=i
                        break

                 p2=p1
                 while p2==p1:
                    r=np.random.rand()
                    for i in range(pop_size-1):
                        if c_fitness[0][i] >= r:
                            p2=i
                            break

                 r1=np.random.rand()
                 if r1 < CR:
                    parent1=population[p1][:]
                    parent2=population[p2][:]
                    point1=np.random.randint(city-1)
                    point2=point1
                    while abs(point1-point2)<4:
                        point2=np.random.randint(city-1)
                    if point2<point1:
                                deepo=point2
                                point2=point1
                                point1=deepo

                    child1=copy.copy(parent1)
                    child2=copy.copy(parent2)

                    # copy_list = org_list[:]

                    counter=point1
                    for i in range(city-1):
                        for j in range(point1+1,point2):
                            if parent2[i]==parent1[j]:
                                counter=counter+1
                                child1[counter]=parent2[i]
                    counter=point1
                    for i in range(city-1):
                        for j in range(point1+1,point2):
                            if parent1[i]==parent2[j]:
                                counter=counter+1
                                child2[counter]=parent1[i]

                    c_count=c_count+2
                    c_pop[c_count-1][:]=child1
                    c_pop[c_count][:]=child2

    c_fitness=np.zeros([1,pop_size])
    for i in range(pop_size):
        c_fitness[0][i]=0
        for j in range(city-1):
            # fitness[0][i]=fitness[0][i]+distance[[population[i][j]][population[i][j+1]]]
            c_fitness[0][i]=c_fitness[0][i]+ distance[c_pop[i][j]][c_pop[i][j+1]]
        c_fitness[0][i]=c_fitness[0][i]+ distance[c_pop[i][city-1]][c_pop[i][1]]
        if best_fitness > c_fitness[0][i]:
            best_solution=c_pop[i][:]
            best_fitness=c_fitness[0][i]

    m_pop=copy.copy(c_pop)
    for i in range(pop_size):
        r2=np.random.rand()
        if r2 <= MR:
            city1=np.random.randint(city-1)
            city2=city1
            while city2==city1:
                city2=np.random.randint(city-1)

            deepo=m_pop[i][city1]
            m_pop[i][city1]=m_pop[i][city2]
            m_pop[i][city2]=deepo

    m_fitness=np.zeros([1,pop_size])
    for i in range(pop_size):
        m_fitness[0][i]=0
        for j in range(city-1):
            # fitness[0][i]=fitness[0][i]+distance[[population[i][j]][population[i][j+1]]]
            m_fitness[0][i]=m_fitness[0][i]+ distance[m_pop[i][j]][m_pop[i][j+1]]
        m_fitness[0][i]=m_fitness[0][i]+ distance[m_pop[i][city-1]][m_pop[i][1]]
        if best_fitness > m_fitness[0][i]:
            best_solution=m_pop[i][:]
            best_fitness=m_fitness[0][i]

    population=copy.copy(m_pop)
    fitness=copy.copy(m_fitness)
    population[1][:]=best_solution
    fitness[0][1]=best_fitness
    iteration=iteration+1
    print(iteration)
    print(best_fitness)
    # print(best_solution)

it returns this:

Traceback (most recent call last):

  File "C:\Users\\Google Drive\python\untitled0.py", line 135, in <module>
    child2[counter]=parent1[i]

IndexError: index 22 is out of bounds for axis 0 with size 22

Body:
OK found the problem. In the following loops counter can indeed end up >21

counter=point1
for i in range(city-1):
    for j in range(point1+1,point2):
        if parent2[i]==parent1[j]:
            counter=counter+1
            child1[counter]=parent2[i]

counter=point1
for i in range(city-1):
    for j in range(point1+1,point2):
        if parent1[i]==parent2[j]:
            counter=counter+1
            child2[counter]=parent1[i]

Consider the case when for every iteration of j that if parent2[i]==parent1[j]: is True then counter is incremented by j times multiplied by city-1 times which can easily by above 21 as city-1 = 21

To remedy it you need to reset counter for each iteration of the i loop,

for i in range(city-1):
    counter=point1
    for j in range(point1+1,point2):
        if parent2[i]==parent1[j]:
            counter=counter+1
            child1[counter]=parent2[i]

for i in range(city-1):
    counter=point1
    for j in range(point1+1,point2):
        if parent1[i]==parent2[j]:
            counter=counter+1
            child2[counter]=parent1[i]


问:
locale library with Plotly/python dataframe works with jupyter but not with Flask/dash
I am using Jupyter notebook working on COVID data wherein I converted date format with my locale language which worked fine. i used the following code and was able to add a column with a locale date.

```<code>import locale
locale.setlocale(locale.LC_TIME, "ta_TA.utf8")
df_state = res[res['state']=='Tamil Nadu']
df_state_ser = df_state.copy()
df_state_ser.drop(['district'],axis=1,inplace=True)
df_state_ser.reset_index(inplace=True)
df_state_ser.drop(['active'],axis=1,inplace=True)
df_state_ser.drop(['notes'],axis=1,inplace=True)
df_state_ser.drop(['index'],axis=1,inplace=True)
#df_state_ser.drop(['state'],axis=1,inplace=True)
df_state_ser.sort_values(by='date', ascending = False)
df_state_ser = df_state_ser.groupby(['date']).sum().reset_index()
df_state_ser['date'] = pd.to_datetime(df_state_ser['date'])
df_state_ser['tamil'] = df_state_ser['date'].dt.strftime("%d %b %y")
#df_state_ser.rename(columns={df_state_ser.columns[0]:'தேதி'}, inplace=True)
df_state_ser.rename(columns={df_state_ser.columns[1]:'உறுதிச்செய்யப்பட்டவை'}, inplace=True)
df_state_ser.rename(columns={df_state_ser.columns[3]:'குணமடைந்தவர்கள்'}, inplace=True)
df_state_ser.rename(columns={df_state_ser.columns[2]:'இறந்தவர்கள்'}, inplace=True)
df_state_ser.rename(columns={df_state_ser.columns[4]:'தேதி'}, inplace=True)
df_state_ser
</code>```

the attached pic gives the output of data frame. highlighted first date column was converted to locale date format as per the last column

I am able to use the data frame and get the plotly graph with my locale date format which worked fine too.

```<code>import plotly.graph_objs as go
import plotly.express as px
df_long_TN=pd.melt(df_state_ser, id_vars=['தேதி'], value_vars=['உறுதிச்செய்யப்பட்டவை','இறந்தவர்கள்','குணமடைந்தவர்கள்'])
fig = px.scatter( df_long_TN,x='தேதி', y="value", color="variable")
fig.update_traces(hovertemplate=None)
fig.update_layout(height=500, width= 605,font=dict(size=10,color="white"),xaxis_title="தேதி",paper_bgcolor= "#2D2D2D",plot_bgcolor="#2D2D2D",
         yaxis=dict(tickformat=".f"),     xaxis=dict(tickangle=270),      legend=dict(x=0,y=1.3,traceorder="normal",font=dict(family="sans-serif",size=12)),
        xaxis_showgrid=False, yaxis_showgrid=False,  legend_title_text= 'மொத்தம்')
fig.show()
</code>```

made changes to the code as per the below picture and able to get the graph with locale date without any issues.

if I use the same code above and run in flask application I am not getting the locale date in the graph. I am getting the output as mentioned below.

need your inputs/pointer to fix the same in flask app.

答:
changing from locale.setlocale(locale.LC_TIME, "ta_TA.utf8") this to
locale.setlocale(category=locale.LC_ALL,locale="Tamil") fixed the issue with flask</p>

Body:
I am using Jupyter notebook working on COVID data wherein I converted date format with my locale language which worked fine. i used the following code and was able to add a column with a locale date.

import locale
locale.setlocale(locale.LC_TIME, "ta_TA.utf8")
df_state = res[res['state']=='Tamil Nadu']
df_state_ser = df_state.copy()
df_state_ser.drop(['district'],axis=1,inplace=True)
df_state_ser.reset_index(inplace=True)
df_state_ser.drop(['active'],axis=1,inplace=True)
df_state_ser.drop(['notes'],axis=1,inplace=True)
df_state_ser.drop(['index'],axis=1,inplace=True)
#df_state_ser.drop(['state'],axis=1,inplace=True)
df_state_ser.sort_values(by='date', ascending = False)
df_state_ser = df_state_ser.groupby(['date']).sum().reset_index()
df_state_ser['date'] = pd.to_datetime(df_state_ser['date'])
df_state_ser['tamil'] = df_state_ser['date'].dt.strftime("%d %b %y")
#df_state_ser.rename(columns={df_state_ser.columns[0]:'தேதி'}, inplace=True)
df_state_ser.rename(columns={df_state_ser.columns[1]:'உறுதிச்செய்யப்பட்டவை'}, inplace=True)
df_state_ser.rename(columns={df_state_ser.columns[3]:'குணமடைந்தவர்கள்'}, inplace=True)
df_state_ser.rename(columns={df_state_ser.columns[2]:'இறந்தவர்கள்'}, inplace=True)
df_state_ser.rename(columns={df_state_ser.columns[4]:'தேதி'}, inplace=True)
df_state_ser

the attached pic gives the output of data frame. highlighted first date column was converted to locale date format as per the last column

I am able to use the data frame and get the plotly graph with my locale date format which worked fine too.

import plotly.graph_objs as go
import plotly.express as px
df_long_TN=pd.melt(df_state_ser, id_vars=['தேதி'], value_vars=['உறுதிச்செய்யப்பட்டவை','இறந்தவர்கள்','குணமடைந்தவர்கள்'])
fig = px.scatter( df_long_TN,x='தேதி', y="value", color="variable")
fig.update_traces(hovertemplate=None)
fig.update_layout(height=500, width= 605,font=dict(size=10,color="white"),xaxis_title="தேதி",paper_bgcolor= "#2D2D2D",plot_bgcolor="#2D2D2D",
         yaxis=dict(tickformat=".f"),     xaxis=dict(tickangle=270),      legend=dict(x=0,y=1.3,traceorder="normal",font=dict(family="sans-serif",size=12)),
        xaxis_showgrid=False, yaxis_showgrid=False,  legend_title_text= 'மொத்தம்')
fig.show()

made changes to the code as per the below picture and able to get the graph with locale date without any issues.

if I use the same code above and run in flask application I am not getting the locale date in the graph. I am getting the output as mentioned below.

need your inputs/pointer to fix the same in flask app.


问:
JavaFX Tableview sort java.sql.Date column with null at bottom on ascending order
I have a column that contains java.sql.Date and I want it to put nulls at the bottom in ascending order:

Right now, they end up on top.

```<code> followupCol.setCellFactory((TableColumn<DisabilityCase, Date> p) ->
        {
            TableCell<DisabilityCase, Date> cell = new TableCell<DisabilityCase, Date>()
            {
                @Override
                protected void updateItem(Date item, boolean empty)
                {
                    super.updateItem(item, empty);
                    if (item == null || empty)
                    {
                        setText(null);
                    } else
                    {
                        if (!LocalDate.now().isBefore(item.toLocalDate()))
                        {
                            setTextFill(Color.RED);
                        } else
                        {
                            setTextFill(Color.BLACK);
                        }

                        setText(new SimpleDateFormat(DATE_FORMAT).format(item));
                    }
                }

            };

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

答:
Since java.sql.Date is already Comparable, you can use

```<code>followupCol.setComparator(Comparator.nullsLast(Comparator.naturalOrder()));
</code>```

Body:
I have a column that contains java.sql.Date and I want it to put nulls at the bottom in ascending order:

Right now, they end up on top.

 followupCol.setCellFactory((TableColumn<DisabilityCase, Date> p) ->
        {
            TableCell<DisabilityCase, Date> cell = new TableCell<DisabilityCase, Date>()
            {
                @Override
                protected void updateItem(Date item, boolean empty)
                {
                    super.updateItem(item, empty);
                    if (item == null || empty)
                    {
                        setText(null);
                    } else
                    {
                        if (!LocalDate.now().isBefore(item.toLocalDate()))
                        {
                            setTextFill(Color.RED);
                        } else
                        {
                            setTextFill(Color.BLACK);
                        }

                        setText(new SimpleDateFormat(DATE_FORMAT).format(item));
                    }
                }

            };

            return cell;
        });

Body:
Since java.sql.Date is already Comparable, you can use

followupCol.setComparator(Comparator.nullsLast(Comparator.naturalOrder()));


问:
ANGULAR - How the EventEmitter Service below, works exactly?
On my work, we've been using this service below to subscribe and emit notifications right and fourth. As a junior developer I already understand Input and Outputs of Angular and sort of how Emitters work.

But this service simplys confuse me. The dev who made this service already left the company and since this code is almost a boilerplate for all projects, I cannot ask him how exactly it works.

specifically this line: private static emitters: { [notificationName: string]: EventEmitter } = {}

```<code>import { Injectable } from '@angular/core';
import { EventEmitter } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class EventEmitterService {

    private static emitters: { [notificationName: string]: EventEmitter<any> } = {}

    static get(notificationName: string): EventEmitter<any> {
        if (!this.emitters[notificationName])
            this.emitters[notificationName] = new EventEmitter<any>();
        return this.emitters[notificationName];
    }
}

/**
to SUBSCRIBE:

private subscriptions = new Subscription();
constructor(){
    this.subscriptions.add( EventEmitterService.get("notification_name").subscribe(payload => this.notificationHandler(payload)) );
}

TO EMIT:

EventEmitterService.get("notificationName").emit(payload);

to UNSUBSCRIBE:

ngOnDestroy(){
    this.subscriptions.unsubscribe();
}
*/
</code>```

Following instructions from the user Michael D, I've change the code

```<code>import { Subject } from 'rxjs';

private emitters: { [notificationName: string]: Subject<any> } = { };
</code>```

and got this error:

The error was caused because the return of static get(notificationName: string): was not changed to Observable<any>

So the final form of service, updated according to MichaelD comment :

```<code>import { Injectable } from '@angular/core';
import { EventEmitter } from '@angular/core';
import { Subject, Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class EventEmitterService {

    // private static emitters: { [notificationName: string]: EventEmitter<any> } = {}
    private  emitters: { [notificationName: string]: Subject<any> } = {};

    get(notificationName: string): Observable<any>{
        if (!this.emitters[notificationName])
            this.emitters[notificationName] = new EventEmitter<any>();
        return this.emitters[notificationName];
    }
}
</code>```

答: Event Emitter model basically follows the observable pattern. In above code I we created a static emitter means we can call it without an instance of class. So this will five us a behavior like utility. You need to understand only one thing. Emitters are constantly listening to the Events and as the event happens they emit the response regardless of success or failure. This response is pretty similar to the interrupt generated by hardware in our OS which make the CPU to listen that specific interrupt instead of doing other tasks. So when we have an update in out Event EventEmitter will broadcast that change and our listeners will detect it on that specific Event</p>

Body:
On my work, we've been using this service below to subscribe and emit notifications right and fourth. As a junior developer I already understand Input and Outputs of Angular and sort of how Emitters work.

But this service simplys confuse me. The dev who made this service already left the company and since this code is almost a boilerplate for all projects, I cannot ask him how exactly it works.

specifically this line: private static emitters: { [notificationName: string]: EventEmitter } = {}

import { Injectable } from '@angular/core';
import { EventEmitter } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class EventEmitterService {

    private static emitters: { [notificationName: string]: EventEmitter<any> } = {}

    static get(notificationName: string): EventEmitter<any> {
        if (!this.emitters[notificationName])
            this.emitters[notificationName] = new EventEmitter<any>();
        return this.emitters[notificationName];
    }
}

/**
to SUBSCRIBE:

private subscriptions = new Subscription();
constructor(){
    this.subscriptions.add( EventEmitterService.get("notification_name").subscribe(payload => this.notificationHandler(payload)) );
}

TO EMIT:

EventEmitterService.get("notificationName").emit(payload);

to UNSUBSCRIBE:

ngOnDestroy(){
    this.subscriptions.unsubscribe();
}
*/

Following instructions from the user Michael D, I've change the code

import { Subject } from 'rxjs';

private emitters: { [notificationName: string]: Subject<any> } = { };

and got this error:

The error was caused because the return of static get(notificationName: string): was not changed to Observable<any>

So the final form of service, updated according to MichaelD comment :

import { Injectable } from '@angular/core';
import { EventEmitter } from '@angular/core';
import { Subject, Observable } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class EventEmitterService {

    // private static emitters: { [notificationName: string]: EventEmitter<any> } = {}
    private  emitters: { [notificationName: string]: Subject<any> } = {};

    get(notificationName: string): Observable<any>{
        if (!this.emitters[notificationName])
            this.emitters[notificationName] = new EventEmitter<any>();
        return this.emitters[notificationName];
    }
}


问:
python 3.6 bug or i am nuts
checks if items in a list are consecutive.

```<code>[True for x in lst[:-1] for y in lst[1:] if x + 1 == y]
</code>```

so list [1, 2, 3, 4, 5]
returns [True, True, True, True] meaning that list is consecutive.

list [1,2,3,4,4]
returns [True, True, True, True] meaning that list is consecutive, but it's not.

doing for each statement proves that

```<code>lst = [1,2,3,4,4]

def consecutive(lst):
    lst.sort()
    return [True for x in lst[:-1] for y in lst[1:] if x + 1 == y]

print(consecutive(lst))

some_list = []
for i,j in zip(lst[:-1], lst[1:]):
    if i+1 == j:
        some_list.append(True)
    else:
        some_list.append(False)

print(some_list)
</code>```

What am i missing here?

答:
You really only need ONE iteration to accomplish this

See Code Below:

def consecutive(list_):
    n = len(list_)
    list_.sort()
    ans = [True if list_[i-1]+1 == list_[i] else False for i in range(1,n)]
    return ans
```

<pre class="lang-py prettyprint-override"><code>list_ = [2,5,1,2,6,3,7,7]
print(consecutive(list_))
</code>```

```<code>[True, False, True, False, True, True, False]
</code>```

Title: python 3.6 bug or i am nuts

Body:
checks if items in a list are consecutive.

[True for x in lst[:-1] for y in lst[1:] if x + 1 == y]

so list [1, 2, 3, 4, 5]
returns [True, True, True, True] meaning that list is consecutive.

list [1,2,3,4,4]
returns [True, True, True, True] meaning that list is consecutive, but it's not.

doing for each statement proves that

lst = [1,2,3,4,4]

def consecutive(lst):
    lst.sort()
    return [True for x in lst[:-1] for y in lst[1:] if x + 1 == y]

print(consecutive(lst))

some_list = []
for i,j in zip(lst[:-1], lst[1:]):
    if i+1 == j:
        some_list.append(True)
    else:
        some_list.append(False)

print(some_list)

What am i missing here?

Body:
You really only need ONE iteration to accomplish this

See Code Below:

def consecutive(list_):
    n = len(list_)
    list_.sort()
    ans = [True if list_[i-1]+1 == list_[i] else False for i in range(1,n)]
    return ans

list_ = [2,5,1,2,6,3,7,7]
print(consecutive(list_))

[True, False, True, False, True, True, False]


问:
EVP_MD_CTX "error: storage size of ‘ctx’ isn’t known"
My system is Ubuntu16.04 LTS. when I use the OpenSSL EVP_MD_CTX, this error appeared. Can anyone help me?

CODE:

```<code>#include <stdio.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
int main()
{
    int ret,inlen,outlen=0;
    unsigned long e=RSA_3;
    char data[100],out[500];
    EVP_MD_CTX md_ctx, md_ctx2;
    ...
}
</code>```

ERROR:

```<code>root@ubuntu:/work/test# gcc evp_openssl_test.c -I/usr/local/include -L/usr/local/lib -lssl -lcrypto -o
evptestevp_openssl_test.c: In function ‘main’:
evp_openssl_test.c:13:19: error: storage size of ‘md_ctx’ isn’t known
    EVP_MD_CTX md_ctx,md_ctx2;
</code>```

答:
I had a similar error but with EVP_CIPHER_CTX

```<code>error: storage size of ‘ctx’ isn’t known
       EVP_CIPHER_CTX ctx;
</code>```

I solved with this:

```<code>EVP_CIPHER_CTX *ctx;
ctx = EVP_CIPHER_CTX_new();
</code>```

I hope this helps somebody with the same problem I had.

Body:
My system is Ubuntu16.04 LTS. when I use the OpenSSL EVP_MD_CTX, this error appeared. Can anyone help me?

CODE:

#include <stdio.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
int main()
{
    int ret,inlen,outlen=0;
    unsigned long e=RSA_3;
    char data[100],out[500];
    EVP_MD_CTX md_ctx, md_ctx2;
    ...
}

ERROR:

root@ubuntu:/work/test# gcc evp_openssl_test.c -I/usr/local/include -L/usr/local/lib -lssl -lcrypto -o
evptestevp_openssl_test.c: In function ‘main’:
evp_openssl_test.c:13:19: error: storage size of ‘md_ctx’ isn’t known
    EVP_MD_CTX md_ctx,md_ctx2;

Body:
I had a similar error but with EVP_CIPHER_CTX

error: storage size of ‘ctx’ isn’t known
       EVP_CIPHER_CTX ctx;

I solved with this:

EVP_CIPHER_CTX *ctx;
ctx = EVP_CIPHER_CTX_new();

I hope this helps somebody with the same problem I had.


问:
Django css background-image
My css file is working but i can't add bacgorund image. I try 3 way but don't work.

This is my style.css

```<code>.first-info{
    width: 100%;
    height: 300px;
    background-image: url( "{% static 'img/bg.jpg' %}");
}
</code>```

This is my base.html ( img is working)

```<code>{% load static %}
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{% block title %}VPW{% endblock %}</title>

    <link href="{% static 'css/style.css' %}" rel="stylesheet">
    <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">
    <link href="{% static 'css/font-awesome.css' %}" rel="stylesheet">
    <script href="{% static 'js/bootstrap.js' %}"></script>

    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container-fluid">
    <div class="row head">
        <div class="col-md-12">
            <div class="col-md-4">
            </div>
            <div class="col-md-4 logo">
                <img src="{% static 'img/logo1.png' %}">
            </div>
            <div class="col-md-4">
            </div>
        </div>
    </div>
</div>
<div id="content">
{% block content %}
{% endblock %}
</div>
</body>
</html>
</code>```

And this is my main.html where i have class first-info.

```<code>{% extends "shop/base.html" %}
{% load static %}

{% block title %}VPW{% endblock %}

{% block content %}
    <div class="container-fluid">
    <div class="row first-info">
        <div class="col-md-4">
            <div class="box">
                Lorem Ipsum
            </div>
        </div>
        <div class="col-md-4">
            <div class="box">

            </div>
        </div>
        <div class="col-md-4">
            <div class="box">

            </div>
        </div>
    </div>
    </div>

{% endblock %}
</code>```

I try change in css background-image: url( "{% static 'img/bg.jpg' %}"); to background-image: url( "img/bg.jpg"); but don't work it

答:
Images must be in static/app/images/ and .css files must be located in static/app/content/.

Further in the .css file write like this:

#home {
  background: url(../images/1.jpg);
}
```

Title: Django css background-image

Body:
My css file is working but i can't add bacgorund image. I try 3 way but don't work.

This is my style.css

.first-info{
    width: 100%;
    height: 300px;
    background-image: url( "{% static 'img/bg.jpg' %}");
}

This is my base.html ( img is working)

{% load static %}
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>{% block title %}VPW{% endblock %}</title>

    <link href="{% static 'css/style.css' %}" rel="stylesheet">
    <link href="{% static 'css/bootstrap.css' %}" rel="stylesheet">
    <link href="{% static 'css/font-awesome.css' %}" rel="stylesheet">

    <meta name="viewport" content="width=device-width, initial-scale=1">

{% block content %}
{% endblock %}

And this is my main.html where i have class first-info.

{% extends "shop/base.html" %}
{% load static %}

{% block title %}VPW{% endblock %}

{% block content %}

                Lorem Ipsum

{% endblock %}

I try change in css background-image: url( "{% static 'img/bg.jpg' %}"); to background-image: url( "img/bg.jpg"); but don't work it