问:
p5.js Change Image on Click and Issue with blinking character
The goal is to create a game of bug squishing. There is a count and a timer. The issues are 1) the bugs are blinking, when they should not be, and 2) when each bug is clicked, there is supposed to be an image of the bug squished, which I have saved as image name: sprite_bug7.png. I am unsure how to resolve both issues and have been working all day to figure it out!</p>

```<code>var bug = [];
var count = 10;
let timer = 30;
var counter = 0;
var score = 0;`enter code here`
var squish;

function preload(){
    for(var i = 0; i < count; i++){
        bug[i] = new Crawler("bugs.png", random(610), random(400),
        random(-1,1));
        squish = loadImage('sprite_bug7.png');
      }
}
  function setup() {
    createCanvas(640,480);
    imageMode(CENTER)
  }

function draw(){
  background(255);
  for(var i = 0; i < count; i++){
    bug[i].draw();
  }
  text("Score: " + score, 20, 30);
  text("Time Left: " + timer, 20, 45);
  if ((frameCount % 60 == 0) && (timer > 0)){
    timer--;
  }
  if (timer == 0){
    text("GAME OVER", 300, 250);
    text("You scored: " + score, 300, 265)
  }
}

function mouseClicked() {
  for (var i = 0; i < count; i++){
    bug[i].kill(mouseX, mouseY);
  }
}

function Crawler(imageName, x, y, moving){
    this.spriteSheet = loadImage(imageName);
    this.frame = 0;
    this.x = x;
    this.y = y;
    this.moving = moving;
    this.facing = moving;

    this.kill = function(x,y){
      if((this.x-30<x && x < this.x+30 && this.y-30<y && y<this.y+30)||
        (timer==0)){
        this.moving = 0;
        score = score + 1;
        this.bug = squish;
        }
        if (this.alive == 1){
          this.alive = 0;
        }
    }

    this.draw = function(){
        push();
        translate(this.x,this.y);
        if (this.facing < 0){
            scale(-1.0, 1.0);
         }
        if (this.moving == 0){
          image(this.spriteSheet, 0, 0, 100, 100, 100, 0, 100, 100);//size,size,start,start,end,end
         }
        else{
            if (this.frame == 0){
            image(this.spriteSheet, 0, 0, 100, 100, 200, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 1){
            image(this.spriteSheet, 0, 0, 100, 100, 300, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 2){
            image(this.spriteSheet, 0, 0, 100, 100, 400, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 3){
            image(this.spriteSheet, 0, 0, 100, 100, 500, 0, 100, 100100);//size,size,start,start,end,end
            }
            if (this.frame == 4){
            image(this.spriteSheet, 0, 0, 100, 100, 600, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 5){
            image(this.spriteSheet, 0, 0, 100, 100, 700, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 6){
            image(this.spriteSheet, 0, 0, 100, 100, 800, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 7){
            image(this.spriteSheet, this.x, this.y, 100, 100, 800, 0, 100, 100);//size,size,start,start,end,end
            }
            if (frameCount % 4 == 0){
            this.frame = (this.frame+1)%8;
            this.x = this.x + this.moving *6;
            }
            if(this.x < 30){
                this.moving = +1;
                this.facing = +1;
            }
            if(this.x> width-30){
                this.moving = -1;
                this.facing = -1;
            }
          }
         pop();
       }
  }
</code>```

答:
1) The bugs are blinking because of the coordinates you're using to draw the image in the 'last' frame. You're already using translate, so when you use this.x and this.y in the last frame, the image 'jumps' and produces the blinking effect.

2) The bug isn't displaying the squished image because it isn't actually being drawn at any point. You have the line this.bug = squish but never use it inside the image method.

I don't have access to your images so I made some assumptions so I could create a snippet:

let timer = 30;
var counter = 0;
var score = 0;`enter code here`
var squish;

const count = 3
let bug = new Array(3)

function preload(){

    for(var i = 0; i < count; i++){
        //bug[i] = new Crawler("bugs.png", random(610), random(400),
        bug[i] = new Crawler("https://picsum.photos/800/100", random(610), random(400),
        random(-1,1));
        // squish = loadImage('sprite_bug7.png');
        squish = createGraphics(100, 100)
        squish.background('green')
      }
}
  function setup() {
    createCanvas(640,480);
    imageMode(CENTER)
  }

function draw(){
  background(255);
  for(var i = 0; i < count; i++){
    bug[i].draw();
  }
  text("Score: " + score, 20, 30);
  text("Time Left: " + timer, 20, 45);
  if ((frameCount % 60 == 0) && (timer > 0)){
    timer--;
  }
  if (timer == 0){
    text("GAME OVER", 300, 250);
    text("You scored: " + score, 300, 265)
  }
}

function mouseClicked() {
  for (var i = 0; i < count; i++){
    bug[i].kill(mouseX, mouseY);
  }
}

function Crawler(imageName, x, y, moving){
    this.spriteSheet = loadImage(imageName);
    this.frame = 0;
    this.x = x;
    this.y = y;
    this.moving = moving;
    this.facing = moving;

    this.kill = function(x,y){
      if((this.x-30<x && x < this.x+30 && this.y-30<y && y<this.y+30)||
        (timer==0)){
        this.moving = 0;
        score = score + 1;
        // this.bug = squish;
        this.spriteSheet = squish;
        }
        if (this.alive == 1){
          this.alive = 0;
        }
    }

    this.draw = function(){
        push();
        translate(this.x,this.y);
        if (this.facing < 0){
            scale(-1.0, 1.0);
         }
        if (this.moving == 0){
          /* Made some changes to the coordinates */
          image(this.spriteSheet, 0, 0, 100, 100, 0, 0, 100, 100);//size,size,start,start,end,end
         }
        else{
            if (this.frame == 0){
            image(this.spriteSheet, 0, 0, 100, 100, 0, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 1){
            image(this.spriteSheet, 0, 0, 100, 100, 100, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 2){
            image(this.spriteSheet, 0, 0, 100, 100, 200, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 3){
            image(this.spriteSheet, 0, 0, 100, 100, 300, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 4){
            image(this.spriteSheet, 0, 0, 100, 100, 400, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 5){
            image(this.spriteSheet, 0, 0, 100, 100, 500, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 6){
            image(this.spriteSheet, 0, 0, 100, 100, 600, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 7){
            // image(this.spriteSheet, this.x, this.y, 100, 100, 800, 0, 100, 100);
            image(this.spriteSheet, 0, 0, 100, 100, 700, 0, 100, 100);//size,size,start,start,end,end
            }
            if (frameCount % 4 == 0){
            this.frame = (this.frame+1)%8;
            this.x = this.x + this.moving *6;
            }
            if(this.x < 30){
                this.moving = +1;
                this.facing = +1;
            }
            if(this.x> width-30){
                this.moving = -1;
                this.facing = -1;
            }
          }
         pop();
       }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.min.js"></script></code>```

Body:
The goal is to create a game of bug squishing. There is a count and a timer. The issues are 1) the bugs are blinking, when they should not be, and 2) when each bug is clicked, there is supposed to be an image of the bug squished, which I have saved as image name: sprite_bug7.png. I am unsure how to resolve both issues and have been working all day to figure it out!

var bug = [];
var count = 10;
let timer = 30;
var counter = 0;
var score = 0;`enter code here`
var squish;

function preload(){
    for(var i = 0; i < count; i++){
        bug[i] = new Crawler("bugs.png", random(610), random(400),
        random(-1,1));
        squish = loadImage('sprite_bug7.png');
      }
}
  function setup() {
    createCanvas(640,480);
    imageMode(CENTER)
  }

function draw(){
  background(255);
  for(var i = 0; i < count; i++){
    bug[i].draw();
  }
  text("Score: " + score, 20, 30);
  text("Time Left: " + timer, 20, 45);
  if ((frameCount % 60 == 0) && (timer > 0)){
    timer--;
  }
  if (timer == 0){
    text("GAME OVER", 300, 250);
    text("You scored: " + score, 300, 265)
  }
}

function mouseClicked() {
  for (var i = 0; i < count; i++){
    bug[i].kill(mouseX, mouseY);
  }
}

function Crawler(imageName, x, y, moving){
    this.spriteSheet = loadImage(imageName);
    this.frame = 0;
    this.x = x;
    this.y = y;
    this.moving = moving;
    this.facing = moving;

    this.kill = function(x,y){
      if((this.x-30<x && x < this.x+30 && this.y-30<y && y<this.y+30)||
        (timer==0)){
        this.moving = 0;
        score = score + 1;
        this.bug = squish;
        }
        if (this.alive == 1){
          this.alive = 0;
        }
    }

    this.draw = function(){
        push();
        translate(this.x,this.y);
        if (this.facing < 0){
            scale(-1.0, 1.0);
         }
        if (this.moving == 0){
          image(this.spriteSheet, 0, 0, 100, 100, 100, 0, 100, 100);//size,size,start,start,end,end
         }
        else{
            if (this.frame == 0){
            image(this.spriteSheet, 0, 0, 100, 100, 200, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 1){
            image(this.spriteSheet, 0, 0, 100, 100, 300, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 2){
            image(this.spriteSheet, 0, 0, 100, 100, 400, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 3){
            image(this.spriteSheet, 0, 0, 100, 100, 500, 0, 100, 100100);//size,size,start,start,end,end
            }
            if (this.frame == 4){
            image(this.spriteSheet, 0, 0, 100, 100, 600, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 5){
            image(this.spriteSheet, 0, 0, 100, 100, 700, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 6){
            image(this.spriteSheet, 0, 0, 100, 100, 800, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 7){
            image(this.spriteSheet, this.x, this.y, 100, 100, 800, 0, 100, 100);//size,size,start,start,end,end
            }
            if (frameCount % 4 == 0){
            this.frame = (this.frame+1)%8;
            this.x = this.x + this.moving *6;
            }
            if(this.x < 30){
                this.moving = +1;
                this.facing = +1;
            }
            if(this.x> width-30){
                this.moving = -1;
                this.facing = -1;
            }
          }
         pop();
       }
  }

Body:
1) The bugs are blinking because of the coordinates you're using to draw the image in the 'last' frame. You're already using translate, so when you use this.x and this.y in the last frame, the image 'jumps' and produces the blinking effect.

2) The bug isn't displaying the squished image because it isn't actually being drawn at any point. You have the line this.bug = squish but never use it inside the image method.

I don't have access to your images so I made some assumptions so I could create a snippet:

let timer = 30;
var counter = 0;
var score = 0;`enter code here`
var squish;

const count = 3
let bug = new Array(3)

function preload(){

    for(var i = 0; i < count; i++){
        //bug[i] = new Crawler("bugs.png", random(610), random(400),
        bug[i] = new Crawler("https://picsum.photos/800/100", random(610), random(400),
        random(-1,1));
        // squish = loadImage('sprite_bug7.png');
        squish = createGraphics(100, 100)
        squish.background('green')
      }
}
  function setup() {
    createCanvas(640,480);
    imageMode(CENTER)
  }

function draw(){
  background(255);
  for(var i = 0; i < count; i++){
    bug[i].draw();
  }
  text("Score: " + score, 20, 30);
  text("Time Left: " + timer, 20, 45);
  if ((frameCount % 60 == 0) && (timer > 0)){
    timer--;
  }
  if (timer == 0){
    text("GAME OVER", 300, 250);
    text("You scored: " + score, 300, 265)
  }
}

function mouseClicked() {
  for (var i = 0; i < count; i++){
    bug[i].kill(mouseX, mouseY);
  }
}

function Crawler(imageName, x, y, moving){
    this.spriteSheet = loadImage(imageName);
    this.frame = 0;
    this.x = x;
    this.y = y;
    this.moving = moving;
    this.facing = moving;

    this.kill = function(x,y){
      if((this.x-30<x && x < this.x+30 && this.y-30<y && y<this.y+30)||
        (timer==0)){
        this.moving = 0;
        score = score + 1;
        // this.bug = squish;
        this.spriteSheet = squish;
        }
        if (this.alive == 1){
          this.alive = 0;
        }
    }

    this.draw = function(){
        push();
        translate(this.x,this.y);
        if (this.facing < 0){
            scale(-1.0, 1.0);
         }
        if (this.moving == 0){
          /* Made some changes to the coordinates */
          image(this.spriteSheet, 0, 0, 100, 100, 0, 0, 100, 100);//size,size,start,start,end,end
         }
        else{
            if (this.frame == 0){
            image(this.spriteSheet, 0, 0, 100, 100, 0, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 1){
            image(this.spriteSheet, 0, 0, 100, 100, 100, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 2){
            image(this.spriteSheet, 0, 0, 100, 100, 200, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 3){
            image(this.spriteSheet, 0, 0, 100, 100, 300, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 4){
            image(this.spriteSheet, 0, 0, 100, 100, 400, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 5){
            image(this.spriteSheet, 0, 0, 100, 100, 500, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 6){
            image(this.spriteSheet, 0, 0, 100, 100, 600, 0, 100, 100);//size,size,start,start,end,end
            }
            if (this.frame == 7){
            // image(this.spriteSheet, this.x, this.y, 100, 100, 800, 0, 100, 100);
            image(this.spriteSheet, 0, 0, 100, 100, 700, 0, 100, 100);//size,size,start,start,end,end
            }
            if (frameCount % 4 == 0){
            this.frame = (this.frame+1)%8;
            this.x = this.x + this.moving *6;
            }
            if(this.x < 30){
                this.moving = +1;
                this.facing = +1;
            }
            if(this.x> width-30){
                this.moving = -1;
                this.facing = -1;
            }
          }
         pop();
       }
  }

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.10.2/p5.min.js"></script>


来源: stackexchange

问:
Laravel Using two models relationships to create another model object
Have a user and design model, user model has many preorders model and design model also has many preorders model. and preorders belongs to user and designs. (Designs also belogns to users )when creating preo orders using auth()->user()->designs()->preorders()->create displays that preorders is undefined.

user model

design model

preorder model

error

preorder controller

答:
Since a user can have many designs, it's not possible for Laravel to know which design_id should be associated with the preorder to be created.

auth()->user()->designs()->preorders()->create([]); // Can't work because user has many designs. Which one should be used to create the preorder?
```

<p>Instead, you should chain the preorder create method on a design:</p>

<pre class="lang-php prettyprint-override"><code>$design->preorders()->create(['user_id' => auth()->id()]); // One design and one user specified: preorder can be created.
</code>```

or on $user:

auth()->user()->preorders()->create(['design_id' => auth()->id()]); // One design and one user specified: preorder can be created.
```

ContentLicense: CC BY-SA 4.0

Body:
Since a user can have many designs, it's not possible for Laravel to know which design_id should be associated with the preorder to be created.

auth()->user()->designs()->preorders()->create([]); // Can't work because user has many designs. Which one should be used to create the preorder?

Instead, you should chain the preorder create method on a design:

$design->preorders()->create(['user_id' => auth()->id()]); // One design and one user specified: preorder can be created.

or on $user:

auth()->user()->preorders()->create(['design_id' => auth()->id()]); // One design and one user specified: preorder can be created.


问:
Сocoapods trunk URL couldn't be downloaded
I am getting this error when I try to pod repo update and pod install

CDN: trunk URL couldn't be downloaded:
https://cdn.cocoapods.org/deprecated_podspecs.txt, error: Failed to
open TCP connection to cdn.cocoapods.org:443 (No route to host -
connect(2) for "cdn.cocoapods.org" port 443)

Does somebody know how to fix this problem?

答: I spend hours by uninstalling and reinstalling pods, Connecting and disconnecting wifi, and trying out different solutions I could find from the internet. And nothing worked. Finally I decided to restart my Macbook and the problem solved. So before trying the solutions given above, I would strongly recommend you to try restarting your system. </p>


问:
How to display two data table in one php?? But it ony come out a table record
I'm trying to put two table record into one PHP, but it only views one of the records when including both PHP file?
another file when echo will become an undefined index.

Main.php

```<code><?php
include"Location.php";
include"Fullname.php";
 ?>
<html>
<head>
<table id ="table">
<tr>
<th>Customer Name</th>
<th>Location From</th>
<th>Location To</th>
<th>Departure Date</th>
<th>Return Date</th>
<th>Travel</th>
</tr>
<?php
if(isset($result ) && !empty($result )){
    while($row = $result->fetch_assoc()){
        echo "
    <tr>
    <td>{$row['Fullname']}</td>}}
    <td>{$row['LocationFrom']}</td>
    <td>{$row['LocationTo']}</td>
    </tr>\n";
    }
}
 ?>
 </table>
 </body>
 </html>
</code>```

Location.php

```<code><?php

$user=filter_input(INPUT_POST,'user');
$fn=filter_input(INPUT_POST,'fn');
$email=filter_input(INPUT_POST,'email');
$ps=filter_input(INPUT_POST,'ps');
$rps=filter_input(INPUT_POST,'rps');
$from=filter_input(INPUT_POST,'from');
$to=filter_input(INPUT_POST,'to');
$departure=filter_input(INPUT_POST,'departure');
$return=filter_input(INPUT_POST,'return');
$flight=filter_input(INPUT_POST,'flight');

$servername="localhost";
$dbusername="root";
$dbpassword="";
$dbname="register";

$conn=new mysqli($servername,$dbusername,$dbpassword,$dbname);

if(mysqli_connect_errno()){

die('Connection Error('. mysqli_connect_errno() .')'. mysqli_connect_error());
}
else{

$sql = "SELECT * FROM booking";
$result = mysqli_query($conn,$sql);

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

Fullname.php

```<code><?php

$user=filter_input(INPUT_POST,'user');
$fn=filter_input(INPUT_POST,'fn');
$email=filter_input(INPUT_POST,'email');
$ps=filter_input(INPUT_POST,'ps');
$rps=filter_input(INPUT_POST,'rps');
$from=filter_input(INPUT_POST,'from');
$to=filter_input(INPUT_POST,'to');
$departure=filter_input(INPUT_POST,'departure');
$return=filter_input(INPUT_POST,'return');
$flight=filter_input(INPUT_POST,'flight');

$servername="localhost";
$dbusername="root";
$dbpassword="";
$dbname="register";

 $conn=new mysqli($servername,$dbusername,$dbpassword,$dbname);

 if(mysqli_connect_errno()){

die('Connection Error('. mysqli_connect_errno() .')'. mysqli_connect_error());
}
else{

$sql = "SELECT Fullname FROM useraccount";
 $result = mysqli_query($conn,$sql);

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

Why it comes out the data only one table?? When have include "FullName.php" and included "Location.php", it only displays fullname.php data only.
Picture with only one record

答:
It is only showing one table because you are overridding the value.
for example, This is what you are doing
file1.php

```<code>a = 3
</code>```

file2.php

```<code>a = 4
</code>```

So when you include both files. file2.php will override the value of file1.php
so what you need to do is set file2.php's a variable to a different name. So ...

```<code>b = 4
</code>```

And now you will have both values 3 and 4 just in different variables.
In your case just do this

Main.php

```<code><?php
result = []
include"Location.php";
include"Fullname.php";
 ?>
<html>
<head>
<table id ="table">
<tr>
<th>Customer Name</th>
<th>Location From</th>
<th>Location To</th>
<th>Departure Date</th>
<th>Return Date</th>
<th>Travel</th>
</tr>
<?php
if(isset($result ) && !empty($result )){
    while($location_row = $result[0]->fetch_assoc() and $fullname_row = $result[1]->fetch_assoc()){
        echo "
    <tr>
    <td>{$fullname_row['Fullname']}</td>}}
    <td>{$location_row['LocationFrom']}</td>
    <td>{$location_row['LocationTo']}</td>
    </tr>\n";
    }
}
 ?>
 </table>
 </body>
 </html>
</code>```

Location.php

```<code><?php

$user=filter_input(INPUT_POST,'user');
$fn=filter_input(INPUT_POST,'fn');
$email=filter_input(INPUT_POST,'email');
$ps=filter_input(INPUT_POST,'ps');
$rps=filter_input(INPUT_POST,'rps');
$from=filter_input(INPUT_POST,'from');
$to=filter_input(INPUT_POST,'to');
$departure=filter_input(INPUT_POST,'departure');
$return=filter_input(INPUT_POST,'return');
$flight=filter_input(INPUT_POST,'flight');

$servername="localhost";
$dbusername="root";
$dbpassword="";
$dbname="register";

$conn=new mysqli($servername,$dbusername,$dbpassword,$dbname);

if(mysqli_connect_errno()){

die('Connection Error('. mysqli_connect_errno() .')'. mysqli_connect_error());
}
else{

$sql = "SELECT * FROM booking";
array_push($result, mysqli_query($conn,$sql));

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

Fullname.php

```<code><?php

$user=filter_input(INPUT_POST,'user');
$fn=filter_input(INPUT_POST,'fn');
$email=filter_input(INPUT_POST,'email');
$ps=filter_input(INPUT_POST,'ps');
$rps=filter_input(INPUT_POST,'rps');
$from=filter_input(INPUT_POST,'from');
$to=filter_input(INPUT_POST,'to');
$departure=filter_input(INPUT_POST,'departure');
$return=filter_input(INPUT_POST,'return');
$flight=filter_input(INPUT_POST,'flight');

$servername="localhost";
$dbusername="root";
$dbpassword="";
$dbname="register";

 $conn=new mysqli($servername,$dbusername,$dbpassword,$dbname);

 if(mysqli_connect_errno()){

die('Connection Error('. mysqli_connect_errno() .')'. mysqli_connect_error());
}
else{

$sql = "SELECT Fullname FROM useraccount";
 array_push($result, mysqli_query($conn,$sql));

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

Basically I fixed the second problem by looping through the rows of both location and full name at the same time. So every row in full name database is associated with the row in location that has the same index. It is a bad way to structure you database, but I assume you are new so it works for your needs

Body:
I'm trying to put two table record into one PHP, but it only views one of the records when including both PHP file?
another file when echo will become an undefined index.

Main.php

<?php
include"Location.php";
include"Fullname.php";
 ?>

Customer Name
Location From
Location To
Departure Date
Return Date
Travel

<?php
if(isset($result ) && !empty($result )){
    while($row = $result->fetch_assoc()){
        echo "

    {$row['Fullname']}	}}
    {$row['LocationFrom']}
    {$row['LocationTo']}

\n";
    }
}
 ?>

Location.php

<?php

$user=filter_input(INPUT_POST,'user');
$fn=filter_input(INPUT_POST,'fn');
$email=filter_input(INPUT_POST,'email');
$ps=filter_input(INPUT_POST,'ps');
$rps=filter_input(INPUT_POST,'rps');
$from=filter_input(INPUT_POST,'from');
$to=filter_input(INPUT_POST,'to');
$departure=filter_input(INPUT_POST,'departure');
$return=filter_input(INPUT_POST,'return');
$flight=filter_input(INPUT_POST,'flight');

$servername="localhost";
$dbusername="root";
$dbpassword="";
$dbname="register";

$conn=new mysqli($servername,$dbusername,$dbpassword,$dbname);

if(mysqli_connect_errno()){

die('Connection Error('. mysqli_connect_errno() .')'. mysqli_connect_error());
}
else{

$sql = "SELECT * FROM booking";
$result = mysqli_query($conn,$sql);

mysqli_close($conn);
}
?>

Fullname.php

<?php

$user=filter_input(INPUT_POST,'user');
$fn=filter_input(INPUT_POST,'fn');
$email=filter_input(INPUT_POST,'email');
$ps=filter_input(INPUT_POST,'ps');
$rps=filter_input(INPUT_POST,'rps');
$from=filter_input(INPUT_POST,'from');
$to=filter_input(INPUT_POST,'to');
$departure=filter_input(INPUT_POST,'departure');
$return=filter_input(INPUT_POST,'return');
$flight=filter_input(INPUT_POST,'flight');

$servername="localhost";
$dbusername="root";
$dbpassword="";
$dbname="register";

 $conn=new mysqli($servername,$dbusername,$dbpassword,$dbname);

 if(mysqli_connect_errno()){

die('Connection Error('. mysqli_connect_errno() .')'. mysqli_connect_error());
}
else{

$sql = "SELECT Fullname FROM useraccount";
 $result = mysqli_query($conn,$sql);

mysqli_close($conn);
 }
?>

Why it comes out the data only one table?? When have include "FullName.php" and included "Location.php", it only displays fullname.php data only.
Picture with only one record

Body:
It is only showing one table because you are overridding the value.
for example, This is what you are doing
file1.php

a = 3

file2.php

a = 4

So when you include both files. file2.php will override the value of file1.php
so what you need to do is set file2.php's a variable to a different name. So ...

b = 4

And now you will have both values 3 and 4 just in different variables.
In your case just do this

Main.php

<?php
result = []
include"Location.php";
include"Fullname.php";
 ?>
<html>
<head>
<table id ="table">
<tr>
<th>Customer Name</th>
<th>Location From</th>
<th>Location To</th>
<th>Departure Date</th>
<th>Return Date</th>
<th>Travel</th>
</tr>
<?php
if(isset($result ) && !empty($result )){
    while($location_row = $result[0]->fetch_assoc() and $fullname_row = $result[1]->fetch_assoc()){
        echo "
    <tr>
    <td>{$fullname_row['Fullname']}</td>}}
    <td>{$location_row['LocationFrom']}</td>
    <td>{$location_row['LocationTo']}</td>
    </tr>\n";
    }
}
 ?>
 </table>
 </body>
 </html>

Location.php

<?php

$user=filter_input(INPUT_POST,'user');
$fn=filter_input(INPUT_POST,'fn');
$email=filter_input(INPUT_POST,'email');
$ps=filter_input(INPUT_POST,'ps');
$rps=filter_input(INPUT_POST,'rps');
$from=filter_input(INPUT_POST,'from');
$to=filter_input(INPUT_POST,'to');
$departure=filter_input(INPUT_POST,'departure');
$return=filter_input(INPUT_POST,'return');
$flight=filter_input(INPUT_POST,'flight');

$servername="localhost";
$dbusername="root";
$dbpassword="";
$dbname="register";

$conn=new mysqli($servername,$dbusername,$dbpassword,$dbname);

if(mysqli_connect_errno()){

die('Connection Error('. mysqli_connect_errno() .')'. mysqli_connect_error());
}
else{

$sql = "SELECT * FROM booking";
array_push($result, mysqli_query($conn,$sql));

mysqli_close($conn);
}
?>

Fullname.php

<?php

$user=filter_input(INPUT_POST,'user');
$fn=filter_input(INPUT_POST,'fn');
$email=filter_input(INPUT_POST,'email');
$ps=filter_input(INPUT_POST,'ps');
$rps=filter_input(INPUT_POST,'rps');
$from=filter_input(INPUT_POST,'from');
$to=filter_input(INPUT_POST,'to');
$departure=filter_input(INPUT_POST,'departure');
$return=filter_input(INPUT_POST,'return');
$flight=filter_input(INPUT_POST,'flight');

$servername="localhost";
$dbusername="root";
$dbpassword="";
$dbname="register";

 $conn=new mysqli($servername,$dbusername,$dbpassword,$dbname);

 if(mysqli_connect_errno()){

die('Connection Error('. mysqli_connect_errno() .')'. mysqli_connect_error());
}
else{

$sql = "SELECT Fullname FROM useraccount";
 array_push($result, mysqli_query($conn,$sql));

mysqli_close($conn);
 }
?>

Basically I fixed the second problem by looping through the rows of both location and full name at the same time. So every row in full name database is associated with the row in location that has the same index. It is a bad way to structure you database, but I assume you are new so it works for your needs


问:
Can't delete php set cookie
I've set a cookie through this call in php

```<code>setcookie('alert_msg', 'you have the add badge');
</code>```

I have tried unsetting it this way

```<code>setcookie('alert_msg', '');
setcookie('alert_msg', false);
setcookie('alert_msg', false, 1);
setcookie('alert_msg', false, time()-3600);
setcookie('alert_msg', '', 1, '/');
</code>```

and it still won't unset the cookie value in $_COOKIE['alert_msg'].

I have tried in both Firefox and Chrome

Code sample:

```<code>if (isset($_COOKIE['alert_msg'])) {
    $this->set('alert_msg', $_COOKIE['alert_msg']);
    unset($_COOKIE['alert_msg']);
    setcookie('alert_msg', '', 1, '/');
}
</code>```

答:
2020 - Google brought me here when I couldnt delete  cookies reliably.

Sometimes, as per your app design you have to set some cookie details ( for example the path to be something other than / ). Deleting the cookie RELIABLY only works if you can identify that cookie clearly ( everything that you set in it ) for deletion.

Use the code below for reliable deletion;

```<code>$params = session_get_cookie_params();              // extract cookie details
unset( $_COOKIE[session_name()] );                  // unset the cookie
setcookie(session_name(), " " , 1 ,
          $params["path"], $params["domain"],
          $params["secure"], $params["httponly"] ); // and also expire the cookie
</code>```

Note1: Set time to expire to 1 sec past unix epoch time. No need to worry that the user's machine  has time correctly set.

Note2: setcookie takes max 7 parameters, so we leave out $params["lifetime"].

The other params are the main ones.

ContentLicense: CC BY-SA 3.0

Title: Can't delete php set cookie

Body:
I've set a cookie through this call in php

setcookie('alert_msg', 'you have the add badge');

I have tried unsetting it this way

setcookie('alert_msg', '');
setcookie('alert_msg', false);
setcookie('alert_msg', false, 1);
setcookie('alert_msg', false, time()-3600);
setcookie('alert_msg', '', 1, '/');

and it still won't unset the cookie value in $_COOKIE['alert_msg'].

I have tried in both Firefox and Chrome

Code sample:

if (isset($_COOKIE['alert_msg'])) {
    $this->set('alert_msg', $_COOKIE['alert_msg']);
    unset($_COOKIE['alert_msg']);
    setcookie('alert_msg', '', 1, '/');
}

Body:
2020 - Google brought me here when I couldnt delete  cookies reliably.

Sometimes, as per your app design you have to set some cookie details ( for example the path to be something other than / ). Deleting the cookie RELIABLY only works if you can identify that cookie clearly ( everything that you set in it ) for deletion.

Use the code below for reliable deletion;

$params = session_get_cookie_params();              // extract cookie details
unset( $_COOKIE[session_name()] );                  // unset the cookie
setcookie(session_name(), " " , 1 ,
          $params["path"], $params["domain"],
          $params["secure"], $params["httponly"] ); // and also expire the cookie

Note1: Set time to expire to 1 sec past unix epoch time. No need to worry that the user's machine  has time correctly set.

Note2: setcookie takes max 7 parameters, so we leave out $params["lifetime"].

The other params are the main ones.


问:
Unpack tuple within SQL statement
I am using Python and PyMySQL. I want to fetch a number of items from a  MySQL database according to their ids:

```<code>items_ids = tuple([3, 2])
sql = f"SELECT * FROM items WHERE item_id IN {items_ids};"
</code>```

I am using the formatted string literals (f" ", https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498) to evaluate the tuple inside the SQL statement.

However,I want to get back the items in the order specified by the tuple so firstly the item with item_id = 3 and then the item with item_id = 2. To accomplish this I have to use the ORDER BY FIELD clause (see also here: Ordering by the order of values in a SQL IN() clause).

But if I write something like this:

```<code>items_ids = tuple([3, 2])
sql = f"SELECT * FROM items WHERE item_id IN {items_ids} ORDER BY FIELD{(item_id,) + items_ids};"
</code>```

then item_id in the ORDER BY FIELD clause is considered as an undeclared python variable

and if I write something like this:

```<code>items_ids = tuple([3, 2])
sql = f"SELECT * FROM items WHERE item_id IN {items_ids} ORDER BY FIELD{('item_id',) + items_ids};"
</code>```

then item_id in the ORDER BY FIELD clause is considered as a string and not as a SQL variable and in this case ORDER BY FIELD does not do anything.

How can I evaluate the tuple (item_id,) + items_ids in the SQL statement by maintaining item_id as a SQL variable in the ORDER BY FIELD clause?

Obviously I can sort the items after they have returned from the database according to items_ids and without bothering so much with MySQL but I was just wondering how to do this.

答:
Another simpler way to resolve this single element tuple problem is by checking the length of the element by keeping it into list and keeping it as a list rather than passing it as a tuple to cursor param:

eg:

```<code> if (len(get_version_list[1])==1):
                port_id=str(port_id[0])
                port_id = '(' + "'" + port_id + "'" + ')'

            else:
                port_id=tuple(port_id)

pd.read_sql(sql=get_version_str.format(port_id,src_cd), con=conn)
</code>```

By using above code simply you won't get (item_id,) this error in sql further:)

Title: Unpack tuple within SQL statement

Body:
I am using Python and PyMySQL. I want to fetch a number of items from a  MySQL database according to their ids:

items_ids = tuple([3, 2])
sql = f"SELECT * FROM items WHERE item_id IN {items_ids};"

I am using the formatted string literals (f" ", https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498) to evaluate the tuple inside the SQL statement.

However,I want to get back the items in the order specified by the tuple so firstly the item with item_id = 3 and then the item with item_id = 2. To accomplish this I have to use the ORDER BY FIELD clause (see also here: Ordering by the order of values in a SQL IN() clause).

But if I write something like this:

items_ids = tuple([3, 2])
sql = f"SELECT * FROM items WHERE item_id IN {items_ids} ORDER BY FIELD{(item_id,) + items_ids};"

then item_id in the ORDER BY FIELD clause is considered as an undeclared python variable

and if I write something like this:

items_ids = tuple([3, 2])
sql = f"SELECT * FROM items WHERE item_id IN {items_ids} ORDER BY FIELD{('item_id',) + items_ids};"

then item_id in the ORDER BY FIELD clause is considered as a string and not as a SQL variable and in this case ORDER BY FIELD does not do anything.

How can I evaluate the tuple (item_id,) + items_ids in the SQL statement by maintaining item_id as a SQL variable in the ORDER BY FIELD clause?

Obviously I can sort the items after they have returned from the database according to items_ids and without bothering so much with MySQL but I was just wondering how to do this.

Body:
Another simpler way to resolve this single element tuple problem is by checking the length of the element by keeping it into list and keeping it as a list rather than passing it as a tuple to cursor param:

eg:

 if (len(get_version_list[1])==1):
                port_id=str(port_id[0])
                port_id = '(' + "'" + port_id + "'" + ')'

            else:
                port_id=tuple(port_id)

pd.read_sql(sql=get_version_str.format(port_id,src_cd), con=conn)

By using above code simply you won't get (item_id,) this error in sql further:)


问:
Arquillian Maven configuration
I am using Arquillian for Ejb unit test. I am using jboss-eap-5.1. Can anyone please tell me what is the configuration in maven for Arquillian  which uses jboss-eap-5.1</p>

答:
From the docs:

https://docs.jboss.org/author/display/ARQ/JBoss+AS+5.1+-+Remote

Title: Arquillian Maven configuration


问:
Force Dlib python to install with CPU support only; on a GPU machine with Cuda and everything
I have searched it over the internet and all I can find is that people having trouble with installation of Dlib with Cuda.
I have exact opposite problem. I can successfully install Dlib with Cuda and GPU support on Ubuntu (Google Colab). But I don't want that.
I want to force Dlib to use CPU since when I change the runtime to TPU, there will be no GPU. But Dlib finds CUDA while installation and add support of CUDA while installation even though runtime is set to "NOT GPU".

```<code>pip install Dlib
</code>```

this will by default install Dlib with cuda, since I am unaware of any flags to disable Cuda.
But even if I try to build Dlib from source like:

```<code>!git clone https://github.com/davisking/dlib.git
%cd dlib
!mkdir build
%cd build
!cmake .. -DDLIB_USE_CUDA=0 -DUSE_AVX_INSTRUCTIONS=1
!cmake --build .
# !sudo make install
# !sudo ldconfig
%cd ..
# !python setup.py build --no DLIB_USE_CUDA
!python setup.py install --no DLIB_USE_CUDA
</code>```

I can successfully do

```<code>import Dlib
</code>```

But when I used "face_recogntion" which calls Dlib at backend

```<code>!pip install face_recognition
import dlib
import face_recognition
</code>```

it throws an error:

```<code>---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-52-c42385b122ec> in <module>()
      2 get_ipython().system('pip install face_recognition')
      3 import dlib
----> 4 import face_recognition

1 frames
/usr/local/lib/python3.6/dist-packages/face_recognition/api.py in <module>()
     21
     22 cnn_face_detection_model = face_recognition_models.cnn_face_detector_model_location()
---> 23 cnn_face_detector = dlib.cnn_face_detection_model_v1(cnn_face_detection_model)
     24
     25 face_recognition_model = face_recognition_models.face_recognition_model_location()

RuntimeError: Error while calling cudaGetDevice(&the_device_id) in file /tmp/pip-install-9p_kkgzg/dlib/dlib/cuda/gpu_data.cpp:178. code: 38, reason: no CUDA-capable device is detected
</code>```

Now I am unable to understand what I am missing.
What Flag should I set in order to Force DLIB to use CPU and not even look for GPU even when there is one.

答: In Google Colab Go to Toolbar > RunTime > Change runtime type> Set Hardware Accelerator> GPU</p>

Body:
I have searched it over the internet and all I can find is that people having trouble with installation of Dlib with Cuda.
I have exact opposite problem. I can successfully install Dlib with Cuda and GPU support on Ubuntu (Google Colab). But I don't want that.
I want to force Dlib to use CPU since when I change the runtime to TPU, there will be no GPU. But Dlib finds CUDA while installation and add support of CUDA while installation even though runtime is set to "NOT GPU".

pip install Dlib

this will by default install Dlib with cuda, since I am unaware of any flags to disable Cuda.
But even if I try to build Dlib from source like:

!git clone https://github.com/davisking/dlib.git
%cd dlib
!mkdir build
%cd build
!cmake .. -DDLIB_USE_CUDA=0 -DUSE_AVX_INSTRUCTIONS=1
!cmake --build .
# !sudo make install
# !sudo ldconfig
%cd ..
# !python setup.py build --no DLIB_USE_CUDA
!python setup.py install --no DLIB_USE_CUDA

I can successfully do

import Dlib

But when I used "face_recogntion" which calls Dlib at backend

!pip install face_recognition
import dlib
import face_recognition

it throws an error:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-52-c42385b122ec> in <module>()
      2 get_ipython().system('pip install face_recognition')
      3 import dlib
----> 4 import face_recognition

1 frames
/usr/local/lib/python3.6/dist-packages/face_recognition/api.py in <module>()
     21
     22 cnn_face_detection_model = face_recognition_models.cnn_face_detector_model_location()
---> 23 cnn_face_detector = dlib.cnn_face_detection_model_v1(cnn_face_detection_model)
     24
     25 face_recognition_model = face_recognition_models.face_recognition_model_location()

RuntimeError: Error while calling cudaGetDevice(&the_device_id) in file /tmp/pip-install-9p_kkgzg/dlib/dlib/cuda/gpu_data.cpp:178. code: 38, reason: no CUDA-capable device is detected

Now I am unable to understand what I am missing.
What Flag should I set in order to Force DLIB to use CPU and not even look for GPU even when there is one.


问:
Getting click event from parent container except certain children
Expected behavior: When I click on the .parent class, an item detail modal will be shown but the modal won't be shown if I click on the .dropdown or any of it's option.

```<code><div class="parent click-for-item-detail">

  <div class="dropdown">
    <a href="#" class="dropdown-toggle " data-toggle="dropdown">Options</a>
    <ul class="dropdown-menu">
      <li><a href="#">option-1</a></li>
      <li><a href="#">option-2</a></li>
    </ul>
  </div>

  <div class="item-image"><img class="click-for-item-detail" src="image.jpg></div>

  <div class="info">
    <a href="#" class="click-for-item-detail">Item title</a>
    <div class="click-for-item-detail"> item subtitle</div>
  </div>

</div>
</code>```

So far:

```<code>$(".click-for-item-detail").on("click",function(e){

        // show the modal if the target itself has been clicked
        if(e.target === this) {
            $('#itemDetailModal').modal('toggle');
        }
    });
</code>```

I have added click-for-item-detail class in every element that should trigger the item detail modal. Is there a better way to achieve this?

答:
You can specify some selectors to be able to trigger.

Read the following post to have a better understanding.

Event listener for multiple elements - jQuery

$(".info, .item-image").on("click", function(){
  console.log("Trigger");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent click-for-item-detail">

  <div class="dropdown">
    Options
    <ul class="dropdown-menu">
      <li>option-1</li>
      <li>option-2</li>
    </ul>
  </div>

  <div class="item-image"><img class="click-for-item-detail" src="image.jpg"></div>

  <div class="info">
    Item title
    <div class="click-for-item-detail"> item subtitle</div>
  </div>

</div></code>```

Body:
Expected behavior: When I click on the .parent class, an item detail modal will be shown but the modal won't be shown if I click on the .dropdown or any of it's option.

    Options

option-1

option-2

    Item title

 item subtitle

So far:

$(".click-for-item-detail").on("click",function(e){

        // show the modal if the target itself has been clicked
        if(e.target === this) {
            $('#itemDetailModal').modal('toggle');
        }
    });

I have added click-for-item-detail class in every element that should trigger the item detail modal. Is there a better way to achieve this?

Body:
You can specify some selectors to be able to trigger.

Read the following post to have a better understanding.

Event listener for multiple elements - jQuery

$(".info, .item-image").on("click", function(){
  console.log("Trigger");
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="parent click-for-item-detail">

  <div class="dropdown">
    <a href="#" class="dropdown-toggle " data-toggle="dropdown">Options</a>
    <ul class="dropdown-menu">
      <li><a href="#" class="dropdown-menu-item">option-1</a></li>
      <li><a href="#" class="dropdown-menu-item">option-2</a></li>
    </ul>
  </div>

  <div class="item-image"><img class="click-for-item-detail" src="image.jpg"></div>

  <div class="info">
    <a href="#" class="click-for-item-detail">Item title</a>
    <div class="click-for-item-detail"> item subtitle</div>
  </div>

</div>


问:
CNN Keras is not accepting 1 channel for Black and white images
I have converted my images to black and white using the below code

```<code>image_file = Image.open('colored.png') # open colour image
    image_file = image_file.convert('1') # convert image to black and white
    image_file.save('black_white.png')
</code>```

When I am feeding the resulted pictures to my CNN network in Keras, it gives me the following

ValueError: Error when checking input: expected conv2d_1_input to have shape (200, 200, 1) but got array with shape (200, 200, 3)

Below is my Keras CNN code, am I missing something?

```<code>from keras.models import Sequential
from keras.layers import Conv2D,Activation,MaxPooling2D,Dense,Flatten,Dropout
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from IPython.display import display
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.metrics import classification_report, confusion_matrix
import keras
from keras.layers import BatchNormalization
from keras.optimizers import Adam

classifier = Sequential()
classifier.add(Conv2D(32,(3,3),input_shape=(200,200,1)))
classifier.add(Activation('relu'))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Conv2D(32,(3,3)))
classifier.add(Activation('relu'))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Conv2D(64,(3,3)))
classifier.add(Activation('relu'))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Flatten())
classifier.add(Dense(128))
classifier.add(Activation('relu'))
classifier.add(Dropout(0.5))
classifier.add(Dense(8))
classifier.add(Activation('softmax'))
classifier.summary()
classifier.compile(optimizer ='adam',
                   loss ='categorical_crossentropy',
                   metrics =['accuracy'])
train_datagen = ImageDataGenerator(rescale =1./255,
                                   shear_range =0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip =True)
test_datagen = ImageDataGenerator(rescale = 1./255)

batchsize=10
training_set = train_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/Journal_Paper/Train_grey/',
                                                target_size=(200,200),
                                                batch_size= batchsize,
                                                class_mode='categorical')

test_set = test_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/Journal_Paper/Test_grey/',
                                           target_size = (200,200),
                                           batch_size = batchsize,
                       shuffle=False,
                                           class_mode ='categorical')
history=classifier.fit_generator(training_set,
                        steps_per_epoch = 3067 // batchsize,
                        epochs = 30,
                        validation_data =test_set,
                        validation_steps = 769 // batchsize)

Y_pred = classifier.predict_generator(test_set, steps= 769 // batchsize + 1)
y_pred = np.argmax(Y_pred, axis=1)
print('Confusion Matrix')
print(confusion_matrix(test_set.classes, y_pred))
print('Classification Report')
target_names = test_set.classes
class_labels = list(test_set.class_indices.keys())
target_names = ['coinhive','emotent','fareit', 'flystudio', 'gafgyt','gamarue', 'mirai','razy']
report = classification_report(test_set.classes, y_pred, target_names=class_labels)
print(report)

# summarize history for accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
</code>```

答:
You are missing the "color_mode" parameter in your flow_from_directory() call; even if you manually convert the photos to grayscale in the function above, behind the curtains flow_from_directory() loads them and converts them back to RGB because of the default 'color_mode=rgb'.

Use it like:

```<code> train_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/Journal_Paper/Train_grey/',
                                                target_size=(200,200),
                                                color_mode='grayscale',
                                                batch_size= batchsize,
                                                class_mode='categorical')
</code>```

Body:
I have converted my images to black and white using the below code

image_file = Image.open('colored.png') # open colour image
    image_file = image_file.convert('1') # convert image to black and white
    image_file.save('black_white.png')

When I am feeding the resulted pictures to my CNN network in Keras, it gives me the following

ValueError: Error when checking input: expected conv2d_1_input to have shape (200, 200, 1) but got array with shape (200, 200, 3)

Below is my Keras CNN code, am I missing something?

from keras.models import Sequential
from keras.layers import Conv2D,Activation,MaxPooling2D,Dense,Flatten,Dropout
import numpy as np
from keras.preprocessing.image import ImageDataGenerator
from IPython.display import display
import matplotlib.pyplot as plt
from PIL import Image
from sklearn.metrics import classification_report, confusion_matrix
import keras
from keras.layers import BatchNormalization
from keras.optimizers import Adam

classifier = Sequential()
classifier.add(Conv2D(32,(3,3),input_shape=(200,200,1)))
classifier.add(Activation('relu'))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Conv2D(32,(3,3)))
classifier.add(Activation('relu'))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Conv2D(64,(3,3)))
classifier.add(Activation('relu'))
classifier.add(BatchNormalization())
classifier.add(MaxPooling2D(pool_size =(2,2)))
classifier.add(Flatten())
classifier.add(Dense(128))
classifier.add(Activation('relu'))
classifier.add(Dropout(0.5))
classifier.add(Dense(8))
classifier.add(Activation('softmax'))
classifier.summary()
classifier.compile(optimizer ='adam',
                   loss ='categorical_crossentropy',
                   metrics =['accuracy'])
train_datagen = ImageDataGenerator(rescale =1./255,
                                   shear_range =0.2,
                                   zoom_range = 0.2,
                                   horizontal_flip =True)
test_datagen = ImageDataGenerator(rescale = 1./255)

batchsize=10
training_set = train_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/Journal_Paper/Train_grey/',
                                                target_size=(200,200),
                                                batch_size= batchsize,
                                                class_mode='categorical')

test_set = test_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/Journal_Paper/Test_grey/',
                                           target_size = (200,200),
                                           batch_size = batchsize,
                       shuffle=False,
                                           class_mode ='categorical')
history=classifier.fit_generator(training_set,
                        steps_per_epoch = 3067 // batchsize,
                        epochs = 30,
                        validation_data =test_set,
                        validation_steps = 769 // batchsize)

Y_pred = classifier.predict_generator(test_set, steps= 769 // batchsize + 1)
y_pred = np.argmax(Y_pred, axis=1)
print('Confusion Matrix')
print(confusion_matrix(test_set.classes, y_pred))
print('Classification Report')
target_names = test_set.classes
class_labels = list(test_set.class_indices.keys())
target_names = ['coinhive','emotent','fareit', 'flystudio', 'gafgyt','gamarue', 'mirai','razy']
report = classification_report(test_set.classes, y_pred, target_names=class_labels)
print(report)

# summarize history for accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()

Body:
You are missing the "color_mode" parameter in your flow_from_directory() call; even if you manually convert the photos to grayscale in the function above, behind the curtains flow_from_directory() loads them and converts them back to RGB because of the default 'color_mode=rgb'.

Use it like:

 train_datagen.flow_from_directory('/home/osboxes/Downloads/Downloads/Journal_Paper/Train_grey/',
                                                target_size=(200,200),
                                                color_mode='grayscale',
                                                batch_size= batchsize,
                                                class_mode='categorical')


问:
To fetch parent and its children connected thru one attribute
Query to fetch the SEC_CODE of parent its child and all grand children. Children are connected through PREV_SEC value.

According to above image,
1. Here if sec_code is 1 then the query should return 1, 3, 4 7, 8
2. if sec_code is 2 then query return 2.
3. if sec_code is 4 then query return 4,7,8

答:
You can use recursive CTE to get the desired output like following query.

```<code>WITH CTE2 (SEC_CODE,SEC_NAME,PREV_SEC)
AS (
    SELECT SEC_CODE,SEC_NAME,PREV_SEC
    FROM YOURTABLE
    WHERE SEC_CODE = 1

    UNION ALL

    SELECT C1.SEC_CODE,C1.SEC_NAME,C1.PREV_SEC
    FROM YOURTABLE C1
    INNER JOIN CTE2 C2 ON C1.PREV_SEC = C2.SEC_CODE
    )
SELECT *
FROM CTE2
</code>```

Note: Replace YOURTABLE with the actual table name in above query.

Body:
You can use recursive CTE to get the desired output like following query.

WITH CTE2 (SEC_CODE,SEC_NAME,PREV_SEC)
AS (
    SELECT SEC_CODE,SEC_NAME,PREV_SEC
    FROM YOURTABLE
    WHERE SEC_CODE = 1

    UNION ALL

    SELECT C1.SEC_CODE,C1.SEC_NAME,C1.PREV_SEC
    FROM YOURTABLE C1
    INNER JOIN CTE2 C2 ON C1.PREV_SEC = C2.SEC_CODE
    )
SELECT *
FROM CTE2

Note: Replace YOURTABLE with the actual table name in above query.


问:
Trying to fit a response surface with R's formula notation
I have a set of a couple of dozen numeric variables and am trying to figure out how to compactly express a quadratic form in those variables. I also want to include the variables themselves. The idea here is that we are fitting a response surface, rather than interacting a group of treatments, as the standard R formula notation seems to assume. I am trying to get appropriate expressions turned into an R formula, suitable for estimation by different techniques, with different data sets, or over different periods.

If there is an explicit statement of how R's formula notation works, anywhere, I have not been able to find it. There is an ancient paper from which R supposedly copied the notation, but it is by no means identical to current R usage. Every other description I have found just gives examples, that do not cover every case -- not even close to every case.

So, just as an example, here I try to construct a quadratic form in three variables, without writing out all the pairs by hand with an I() around each pair.

```<code>library(tidyverse)
A <- B <- C <- 1:10
LHS <- 1:10 * 600
tb <- tibble(LHS, A, B, C)
my_eq <- as.formula(LHS ~ I(A + B + C)*I(A + B + C))
</code>```

I have not found any way to tell if I have succeded
Neither
my_form_eq  nor

```<code>terms(my_form_eq)
</code>```

seem at all enlightening.

For example, can one predict whether

identical(as.formula(LHS ~ I(A + B + C)*I(A + B + C)), as.formula(LHS ~ I((A + B + C)*(A + B + C)))

is true or false? I can not even guess. Or to take an even simpler case, is ~ A * I(A) equal to A, I(A^2), or something else? And how would you know?

To restate my question, I would like either a full statement of how R's formula notation works, adequate to cover every case and predict what each would mean, or, failing that, a straightforward way of producing an expansion of any existing formula into all the atomic terms for which coefficients will be estimated.

答:
This may not answer your question, but I'll post this anyway since I think it may help a little.

The I function inhibits the interpretation of operators such as "+", so your formula is probably not going to do what you expect it to do. For example, the results of lm(my_eq) will be the same as the results of doing the following:

```<code>D <- A + B + C
lm(LHS ~ D * D)
</code>```

And then you may as well just do lm(LHS ~ D).

For your question, I believe John Maindonald wrote a good book that explains R formulas for many situations. But it's in my office and today is a Sunday.

Edit: For the expansion, I believe you have to fit the model and then look at the call or the terms:

```<code>> my_eq <- as.formula(LHS ~ (A + B + C) * (A + B + C))
> my_formula <- lm(my_eq)
> attr(terms(my_formula), "term.labels")
[1] "A"   "B"   "C"   "A:B" "A:C" "B:C"
</code>```

Body:
I have a set of a couple of dozen numeric variables and am trying to figure out how to compactly express a quadratic form in those variables. I also want to include the variables themselves. The idea here is that we are fitting a response surface, rather than interacting a group of treatments, as the standard R formula notation seems to assume. I am trying to get appropriate expressions turned into an R formula, suitable for estimation by different techniques, with different data sets, or over different periods.

If there is an explicit statement of how R's formula notation works, anywhere, I have not been able to find it. There is an ancient paper from which R supposedly copied the notation, but it is by no means identical to current R usage. Every other description I have found just gives examples, that do not cover every case -- not even close to every case.

So, just as an example, here I try to construct a quadratic form in three variables, without writing out all the pairs by hand with an I() around each pair.

library(tidyverse)
A <- B <- C <- 1:10
LHS <- 1:10 * 600
tb <- tibble(LHS, A, B, C)
my_eq <- as.formula(LHS ~ I(A + B + C)*I(A + B + C))

I have not found any way to tell if I have succeded
Neither
my_form_eq  nor

terms(my_form_eq)

seem at all enlightening.

For example, can one predict whether

identical(as.formula(LHS ~ I(A + B + C)*I(A + B + C)), as.formula(LHS ~ I((A + B + C)*(A + B + C)))

is true or false? I can not even guess. Or to take an even simpler case, is ~ A * I(A) equal to A, I(A^2), or something else? And how would you know?

To restate my question, I would like either a full statement of how R's formula notation works, adequate to cover every case and predict what each would mean, or, failing that, a straightforward way of producing an expansion of any existing formula into all the atomic terms for which coefficients will be estimated.

Body:
This may not answer your question, but I'll post this anyway since I think it may help a little.

The I function inhibits the interpretation of operators such as "+", so your formula is probably not going to do what you expect it to do. For example, the results of lm(my_eq) will be the same as the results of doing the following:

D <- A + B + C
lm(LHS ~ D * D)

And then you may as well just do lm(LHS ~ D).

For your question, I believe John Maindonald wrote a good book that explains R formulas for many situations. But it's in my office and today is a Sunday.

Edit: For the expansion, I believe you have to fit the model and then look at the call or the terms:

> my_eq <- as.formula(LHS ~ (A + B + C) * (A + B + C))
> my_formula <- lm(my_eq)
> attr(terms(my_formula), "term.labels")
[1] "A"   "B"   "C"   "A:B" "A:C" "B:C"


问:
Why isn't my Kafka load being balanced among brokers?
I have a consumer group reading from a topic with ten partitions:

```<code>[root@kafka01 kafka]# ./bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group ssIncomingGroup --describe

GROUP           TOPIC           PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                                                        HOST            CLIENT-ID
ssIncomingGroup ssIncoming      3          13688           13987           299             ssTS@influx01 (github.com/segmentio/kafka-go)-f1c5b4c7-9cf0-4132-902a-db9d0429d520 /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      7          13484           13868           384             ssTS@influx01 (github.com/segmentio/kafka-go)-f1c5b4c7-9cf0-4132-902a-db9d0429d520 /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      2          13322           13698           376             ssTS@influx01 (github.com/segmentio/kafka-go)-20ee82a9-825d-4d9a-9f20-f4610c21f171 /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      8          13612           13899           287             ssTS@influx01 (github.com/segmentio/kafka-go)-20ee82a9-825d-4d9a-9f20-f4610c21f171 /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      1          13568           13932           364             ssTS@influx01 (github.com/segmentio/kafka-go)-df68ca85-d722-47ef-82c2-2fd60e186fac /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      6          13651           13950           299             ssTS@influx01 (github.com/segmentio/kafka-go)-df68ca85-d722-47ef-82c2-2fd60e186fac /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      0          13609           13896           287             ssTS@influx01 (github.com/segmentio/kafka-go)-10b7f10f-9535-4338-9851-f583a9a7c935 /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      5          13646           13945           299             ssTS@influx01 (github.com/segmentio/kafka-go)-10b7f10f-9535-4338-9851-f583a9a7c935 /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      4          13543           13843           300             ssTS@influx01 (github.com/segmentio/kafka-go)-3c847add-172f-4007-adf2-ce486686dd7c /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      9          13652           13951           299             ssTS@influx01 (github.com/segmentio/kafka-go)-3c847add-172f-4007-adf2-ce486686dd7c /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
</code>```

I am using the Segment.io Kaka library for Go: "github.com/segmentio/kafka-go".

My Kafka writer looks like this:

```<code>kafkaWriter := kafka.NewWriter(kafka.WriterConfig{
    Async:         false,
    Brokers:       config.KafkaHosts,  // a string slice of 4 Kafka hosts
    QueueCapacity: kafkaQueueCapacity,
    Topic:         kafkaTopic,
    Balancer: &kafka.LeastBytes{},  // Same result with the default round-robin balancer
})
</code>```

My Kafka reader looks like this:

```<code>    kafkaReader := kafka.NewReader(kafka.ReaderConfig{
        Brokers: config.KafkaHosts,  // same as above
        GroupID: config.KafkaGroup,
        Topic:   config.KafkaTopic,  // same as above
    })
</code>```

The topic was initially created like this:

```<code>conn.CreateTopics(kafka.TopicConfig{
    NumPartitions:     config.KafkaPartitions,  // == 10
    ReplicationFactor: config.KafkaReplication,  // == 1
    Topic:             kafkaTopic,  // same as above
})
</code>```

When I run my program and watch host and network load, I see that almost all load / network activity is on one of the four Kafka brokers.  When I du the log directories for the Kafka hosts, that same host has much more Kafka data on the FS than the others (for example, 150M as opposed to 15M).

What I want and expect to happen is to have the load distributed among all four Kafka servers, so that one does not become a bottleneck (from CPU or network).  Why isn't this happening?

Edit (adding requested command output):

```<code>[root@kafka01 kafka]# bin/kafka-topics.sh --describe --bootstrap-server localhost:9092
Topic: ssIncoming       PartitionCount: 10      ReplicationFactor: 1    Configs: flush.ms=1000,segment.bytes=536870912,flush.messages=10000,retention.bytes=1073741824
        Topic: ssIncoming       Partition: 0    Leader: 4       Replicas: 4     Isr: 4
        Topic: ssIncoming       Partition: 1    Leader: 2       Replicas: 2     Isr: 2
        Topic: ssIncoming       Partition: 2    Leader: 3       Replicas: 3     Isr: 3
        Topic: ssIncoming       Partition: 3    Leader: 1       Replicas: 1     Isr: 1
        Topic: ssIncoming       Partition: 4    Leader: 4       Replicas: 4     Isr: 4
        Topic: ssIncoming       Partition: 5    Leader: 2       Replicas: 2     Isr: 2
        Topic: ssIncoming       Partition: 6    Leader: 3       Replicas: 3     Isr: 3
        Topic: ssIncoming       Partition: 7    Leader: 1       Replicas: 1     Isr: 1
        Topic: ssIncoming       Partition: 8    Leader: 4       Replicas: 4     Isr: 4
        Topic: ssIncoming       Partition: 9    Leader: 2       Replicas: 2     Isr: 2
Topic: __consumer_offsets       PartitionCount: 50      ReplicationFactor: 1    Configs: compression.type=producer,cleanup.policy=compact,flush.ms=1000,segment.bytes=104857600,flush.messages=10000,retention.bytes=1073$41824
        Topic: __consumer_offsets       Partition: 0    Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 1    Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 2    Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 3    Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 4    Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 5    Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 6    Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 7    Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 8    Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 9    Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 10   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 11   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 12   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 13   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 14   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 15   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 16   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 17   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 18   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 19   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 20   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 21   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 22   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 23   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 24   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 25   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 26   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 27   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 28   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 29   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 30   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 31   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 32   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 33   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 34   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 35   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 36   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 37   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 38   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 39   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 40   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 41   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 42   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 43   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 44   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 45   Leader: 1       Replicas: 1     Isr: 1
    Topic: __consumer_offsets       Partition: 46   Leader: 2       Replicas: 2     Isr: 2
    Topic: __consumer_offsets       Partition: 47   Leader: 3       Replicas: 3     Isr: 3
    Topic: __consumer_offsets       Partition: 48   Leader: 4       Replicas: 4     Isr: 4
    Topic: __consumer_offsets       Partition: 49   Leader: 1       Replicas: 1     Isr: 1
</code>```

(Edit 2): Here are the variables I use in generating the Kafka configuration files.  They're the same for each of the 4 brokers.

```<code>scala_version: 2.12
kafka_config_broker_id: 0
kafka_config_log_dirs: "/tmp/kafka_logs"
kafka_config_log_flush_interval_messages: 10000
kafka_config_log_flush_interval_ms: 1000
kafka_config_log_retention_bytes: 1073741824
kafka_config_log_retention_check_interval: 60000
kafka_config_log_retention_hours: 168
kafka_config_log_segment_bytes: 536870912
kafka_config_num_io_threads: 4
kafka_config_num_network_threads: 2
kafka_config_num_partitions: 2
kafka_config_offsets_topic_replication_factor: 1
kafka_config_receive_buffer_bytes: 1048576
kafka_config_request_max_bytes: 104857600
kafka_config_send_buffer_bytes: 1048576
kafka_config_zookeeper_connection_timeout_ms: 1000000
kafka_config_zookeeper_servers:
    - consul01
    - consul02
    - consul03
kafka_exporter_version: 1.2.0
kafka_port: 9092
kafka_version: 2.4.0
</code>```

This data is used in an Ansible template.  The generated kafka confs look like this:

```<code>broker.id=1
port=9092
num.network.threads=2
num.io.threads=4
socket.send.buffer.bytes=1048576
socket.receive.buffer.bytes=1048576
socket.request.max.bytes=104857600
log.dirs=/tmp/kafka_logs
num.partitions=2
log.flush.interval.messages=10000
log.flush.interval.ms=1000
log.retention.hours=168
log.retention.bytes=1073741824
log.segment.bytes=536870912
log.retention.check.interval.ms=60000

# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction.
log.cleaner.enable=false

offsets.topic.replication.factor=1

zookeeper.connect=consul01:2181,consul02:2181,consul03:2181
zookeeper.connection.timeout.ms=1000000

delete.topic.enable=true
</code>```

Note that this is for development and these are being respun frequently (several times per day).  The issue persists after each respin.

答:
It seems load is balanced very well now:

Partition leaders are distributed between brokers in the best balanced way possible

Broker 1 is the leader of partitions 3,7

Broker 2 is the leader of partitions 1,5,9

Broker 3 is the leader of partitions 2,6

Broker 4 is the leader of partitions 0,4,8

Partitions are also assigned to consumers evenly (2 partitions per consumer)

Number of offsets are nearly the same in the partitions (so it seems you are producing messages to partitions evenly)

When I du the log directories for the Kafka hosts, that same host has
  much more Kafka data on the FS than the others (for example, 150M as
  opposed to 15M).

Log offsets in partitions are almost the same. But of course, broker 2 and 4 must have much more data because they deal with one more partition as you see. Also network traffic must be much more because they deal with 3 partitions. (poll requests from consumers and also send requests of producer)

But still 10 times much more data in one broker is not sensible. IMHO at some point one or more broker were unhealthy (cannot send heartbeat to Zookeeper or down) and Controller assigned partitions to healthy broker(s) and for a while some broker(s) were taking care of much more partitions. (btw auto.leader.rebalance.enable must be true for this scneario)

Note: I assume that your broker configs (especially the configs about log.retention has important role for data stored in brokers) and system resources of the brokers are the same. If they are not, you should specify it.

By the way, if you are not happy with the current assignment of partitions to brokers. You can manually change it by using kafka-reassign-partitions.sh tool. You just need to create a json file which specifies replicas of the partitions.

For example:

```<code>{"version":1,
  "partitions":[
     {"topic":"ssIncoming","partition":0,"replicas":[1]},
     {"topic":"ssIncoming","partition":1,"replicas":[1]},
     {"topic":"ssIncoming","partition":2,"replicas":[1]},
     {"topic":"ssIncoming","partition":3,"replicas":[2]},
     {"topic":"ssIncoming","partition":4,"replicas":[2]},
     {"topic":"ssIncoming","partition":5,"replicas":[3]},
     {"topic":"ssIncoming","partition":6,"replicas":[3]},
     {"topic":"ssIncoming","partition":7,"replicas":[3]},
     {"topic":"ssIncoming","partition":8,"replicas":[4]},
     {"topic":"ssIncoming","partition":9,"replicas":[4]}
]}
</code>```

Then you just need to run this command:

```<code>./bin/kafka-reassign-partitions.sh --zookeeper localhost:2181 --reassignment-json-file change-replicas.json --execute
</code>```

Body:
I have a consumer group reading from a topic with ten partitions:

[root@kafka01 kafka]# ./bin/kafka-consumer-groups.sh --bootstrap-server localhost:9092 --group ssIncomingGroup --describe

GROUP           TOPIC           PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                                                        HOST            CLIENT-ID
ssIncomingGroup ssIncoming      3          13688           13987           299             ssTS@influx01 (github.com/segmentio/kafka-go)-f1c5b4c7-9cf0-4132-902a-db9d0429d520 /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      7          13484           13868           384             ssTS@influx01 (github.com/segmentio/kafka-go)-f1c5b4c7-9cf0-4132-902a-db9d0429d520 /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      2          13322           13698           376             ssTS@influx01 (github.com/segmentio/kafka-go)-20ee82a9-825d-4d9a-9f20-f4610c21f171 /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      8          13612           13899           287             ssTS@influx01 (github.com/segmentio/kafka-go)-20ee82a9-825d-4d9a-9f20-f4610c21f171 /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      1          13568           13932           364             ssTS@influx01 (github.com/segmentio/kafka-go)-df68ca85-d722-47ef-82c2-2fd60e186fac /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      6          13651           13950           299             ssTS@influx01 (github.com/segmentio/kafka-go)-df68ca85-d722-47ef-82c2-2fd60e186fac /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      0          13609           13896           287             ssTS@influx01 (github.com/segmentio/kafka-go)-10b7f10f-9535-4338-9851-f583a9a7c935 /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      5          13646           13945           299             ssTS@influx01 (github.com/segmentio/kafka-go)-10b7f10f-9535-4338-9851-f583a9a7c935 /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      4          13543           13843           300             ssTS@influx01 (github.com/segmentio/kafka-go)-3c847add-172f-4007-adf2-ce486686dd7c /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)
ssIncomingGroup ssIncoming      9          13652           13951           299             ssTS@influx01 (github.com/segmentio/kafka-go)-3c847add-172f-4007-adf2-ce486686dd7c /192.168.33.10  ssTS@influx01 (github.com/segmentio/kafka-go)

I am using the Segment.io Kaka library for Go: "github.com/segmentio/kafka-go".

My Kafka writer looks like this:

kafkaWriter := kafka.NewWriter(kafka.WriterConfig{
    Async:         false,
    Brokers:       config.KafkaHosts,  // a string slice of 4 Kafka hosts
    QueueCapacity: kafkaQueueCapacity,
    Topic:         kafkaTopic,
    Balancer: &kafka.LeastBytes{},  // Same result with the default round-robin balancer
})

My Kafka reader looks like this:

    kafkaReader := kafka.NewReader(kafka.ReaderConfig{
        Brokers: config.KafkaHosts,  // same as above
        GroupID: config.KafkaGroup,
        Topic:   config.KafkaTopic,  // same as above
    })

The topic was initially created like this:

conn.CreateTopics(kafka.TopicConfig{
    NumPartitions:     config.KafkaPartitions,  // == 10
    ReplicationFactor: config.KafkaReplication,  // == 1
    Topic:             kafkaTopic,  // same as above
})

When I run my program and watch host and network load, I see that almost all load / network activity is on one of the four Kafka brokers.  When I du the log directories for the Kafka hosts, that same host has much more Kafka data on the FS than the others (for example, 150M as opposed to 15M).

What I want and expect to happen is to have the load distributed among all four Kafka servers, so that one does not become a bottleneck (from CPU or network).  Why isn't this happening?

Edit (adding requested command output):

[root@kafka01 kafka]# bin/kafka-topics.sh --describe --bootstrap-server localhost:9092
Topic: ssIncoming       PartitionCount: 10      ReplicationFactor: 1    Configs: flush.ms=1000,segment.bytes=536870912,flush.messages=10000,retention.bytes=1073741824
        Topic: ssIncoming       Partition: 0    Leader: 4       Replicas: 4     Isr: 4
        Topic: ssIncoming       Partition: 1    Leader: 2       Replicas: 2     Isr: 2
        Topic: ssIncoming       Partition: 2    Leader: 3       Replicas: 3     Isr: 3
        Topic: ssIncoming       Partition: 3    Leader: 1       Replicas: 1     Isr: 1
        Topic: ssIncoming       Partition: 4    Leader: 4       Replicas: 4     Isr: 4
        Topic: ssIncoming       Partition: 5    Leader: 2       Replicas: 2     Isr: 2
        Topic: ssIncoming       Partition: 6    Leader: 3       Replicas: 3     Isr: 3
        Topic: ssIncoming       Partition: 7    Leader: 1       Replicas: 1     Isr: 1
        Topic: ssIncoming       Partition: 8    Leader: 4       Replicas: 4     Isr: 4
        Topic: ssIncoming       Partition: 9    Leader: 2       Replicas: 2     Isr: 2
Topic: __consumer_offsets       PartitionCount: 50      ReplicationFactor: 1    Configs: compression.type=producer,cleanup.policy=compact,flush.ms=1000,segment.bytes=104857600,flush.messages=10000,retention.bytes=1073$41824
        Topic: __consumer_offsets       Partition: 0    Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 1    Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 2    Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 3    Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 4    Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 5    Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 6    Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 7    Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 8    Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 9    Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 10   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 11   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 12   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 13   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 14   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 15   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 16   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 17   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 18   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 19   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 20   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 21   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 22   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 23   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 24   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 25   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 26   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 27   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 28   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 29   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 30   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 31   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 32   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 33   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 34   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 35   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 36   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 37   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 38   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 39   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 40   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 41   Leader: 1       Replicas: 1     Isr: 1
        Topic: __consumer_offsets       Partition: 42   Leader: 2       Replicas: 2     Isr: 2
        Topic: __consumer_offsets       Partition: 43   Leader: 3       Replicas: 3     Isr: 3
        Topic: __consumer_offsets       Partition: 44   Leader: 4       Replicas: 4     Isr: 4
        Topic: __consumer_offsets       Partition: 45   Leader: 1       Replicas: 1     Isr: 1
    Topic: __consumer_offsets       Partition: 46   Leader: 2       Replicas: 2     Isr: 2
    Topic: __consumer_offsets       Partition: 47   Leader: 3       Replicas: 3     Isr: 3
    Topic: __consumer_offsets       Partition: 48   Leader: 4       Replicas: 4     Isr: 4
    Topic: __consumer_offsets       Partition: 49   Leader: 1       Replicas: 1     Isr: 1

(Edit 2): Here are the variables I use in generating the Kafka configuration files.  They're the same for each of the 4 brokers.

scala_version: 2.12
kafka_config_broker_id: 0
kafka_config_log_dirs: "/tmp/kafka_logs"
kafka_config_log_flush_interval_messages: 10000
kafka_config_log_flush_interval_ms: 1000
kafka_config_log_retention_bytes: 1073741824
kafka_config_log_retention_check_interval: 60000
kafka_config_log_retention_hours: 168
kafka_config_log_segment_bytes: 536870912
kafka_config_num_io_threads: 4
kafka_config_num_network_threads: 2
kafka_config_num_partitions: 2
kafka_config_offsets_topic_replication_factor: 1
kafka_config_receive_buffer_bytes: 1048576
kafka_config_request_max_bytes: 104857600
kafka_config_send_buffer_bytes: 1048576
kafka_config_zookeeper_connection_timeout_ms: 1000000
kafka_config_zookeeper_servers:
    - consul01
    - consul02
    - consul03
kafka_exporter_version: 1.2.0
kafka_port: 9092
kafka_version: 2.4.0

This data is used in an Ansible template.  The generated kafka confs look like this:

broker.id=1
port=9092
num.network.threads=2
num.io.threads=4
socket.send.buffer.bytes=1048576
socket.receive.buffer.bytes=1048576
socket.request.max.bytes=104857600
log.dirs=/tmp/kafka_logs
num.partitions=2
log.flush.interval.messages=10000
log.flush.interval.ms=1000
log.retention.hours=168
log.retention.bytes=1073741824
log.segment.bytes=536870912
log.retention.check.interval.ms=60000

# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction.
log.cleaner.enable=false

offsets.topic.replication.factor=1

zookeeper.connect=consul01:2181,consul02:2181,consul03:2181
zookeeper.connection.timeout.ms=1000000

delete.topic.enable=true

Note that this is for development and these are being respun frequently (several times per day).  The issue persists after each respin.

Body:
It seems load is balanced very well now:

Partition leaders are distributed between brokers in the best balanced way possible

Broker 1 is the leader of partitions 3,7

Broker 2 is the leader of partitions 1,5,9

Broker 3 is the leader of partitions 2,6

Broker 4 is the leader of partitions 0,4,8

Partitions are also assigned to consumers evenly (2 partitions per consumer)

Number of offsets are nearly the same in the partitions (so it seems you are producing messages to partitions evenly)

When I du the log directories for the Kafka hosts, that same host has
  much more Kafka data on the FS than the others (for example, 150M as
  opposed to 15M).

Log offsets in partitions are almost the same. But of course, broker 2 and 4 must have much more data because they deal with one more partition as you see. Also network traffic must be much more because they deal with 3 partitions. (poll requests from consumers and also send requests of producer)

But still 10 times much more data in one broker is not sensible. IMHO at some point one or more broker were unhealthy (cannot send heartbeat to Zookeeper or down) and Controller assigned partitions to healthy broker(s) and for a while some broker(s) were taking care of much more partitions. (btw auto.leader.rebalance.enable must be true for this scneario)

Note: I assume that your broker configs (especially the configs about log.retention has important role for data stored in brokers) and system resources of the brokers are the same. If they are not, you should specify it.

By the way, if you are not happy with the current assignment of partitions to brokers. You can manually change it by using kafka-reassign-partitions.sh tool. You just need to create a json file which specifies replicas of the partitions.

For example:

{"version":1,
  "partitions":[
     {"topic":"ssIncoming","partition":0,"replicas":[1]},
     {"topic":"ssIncoming","partition":1,"replicas":[1]},
     {"topic":"ssIncoming","partition":2,"replicas":[1]},
     {"topic":"ssIncoming","partition":3,"replicas":[2]},
     {"topic":"ssIncoming","partition":4,"replicas":[2]},
     {"topic":"ssIncoming","partition":5,"replicas":[3]},
     {"topic":"ssIncoming","partition":6,"replicas":[3]},
     {"topic":"ssIncoming","partition":7,"replicas":[3]},
     {"topic":"ssIncoming","partition":8,"replicas":[4]},
     {"topic":"ssIncoming","partition":9,"replicas":[4]}
]}

Then you just need to run this command:

./bin/kafka-reassign-partitions.sh --zookeeper localhost:2181 --reassignment-json-file change-replicas.json --execute


问:
Sending embeds through discord.py
I've been doing a lot of work creating discord bots with the discord api through javascript with discord.js.

I am trying to create my first discord bot with python using the discord api through discord.py and with requests through requests.py.

My goal is to check status code on a site, and when a message is sent that contains "status code," it will reply with the site's status code in an embed.

Here is my code to do so:

```<code>import discord
import requests
r = requests.get('redactedurl')
test = r.status_code
class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

    async def on_message(self, message):
        if (message.channel.id == redacted):
                if "status code" in message.content:
                    print('Message from {0.author}: {0.content}'.format(message))

                    embed = discord.Embed(color=0x00ff00)
                    embed.title = "test"
                    embed.description = '**Status Code:** {r.status_code}'
                    await message.channel.send(embed=embed)

client = MyClient()
client.run('redacted')
</code>```

The following is a list of questions I hope anybody can answer to help me out :)

As you see here: https://gyazo.com/f6ae7082486cade72389534a05655fec, this just sends "{r.status_code}" in the embed, instead of the actual status code, what am I doing wrong?

What does it mean when i see 0 in the curly brackets. For example, can somebody explain "('Logged on as {0}!'.format(self.user))" to me? Since I'm new to python and discord.py, I am confused about this whole line. I know what the outcome is, but forgive my ignorance, is it all necessary?

In "send(embed=embed)", why can't i just put send(embed)?

Finally, is there anything else that i can do to improve the code?

Thank you so much if you're able to help!

答:
Okay working down your list of questions:

You're not formatting {r.status_code} but just sending it as a string which is why it shows up as just that. To fix it, all you have to do is add 1 "f".

```<code>embed.description = f'**Status Code:** {r.status_code}'
</code>```

or, if you want to use a consistent way of formatting your strings:

```<code>embed.description = '**Status Code:** {0}'.format(r.status_code)
</code>```

In Python, the curly brackets '{}' in a string can be used for formatting. This can be done in multiple ways including how you're doing it in your code. str.format() can take multiple arguments if you want to format different values in your string. The 0 is just an index for which argument you want to use.

I'm not too familiar with the discord library but having taken a quick look at the documentation it would seem that if you did that it would take your embed variable and pass it into send as the content variable. Thereby sending it as a normal message instead of embedding it.

I personally like f-strings more for formatting because it makes your code more easily readable. I can't really comment on your use of the discord library but besides that your code looks fine! Purely for aesthetics/readability I would put an empty line between your imports and defining your variables, and between your variables and your class.

Title: Sending embeds through discord.py

Body:
I've been doing a lot of work creating discord bots with the discord api through javascript with discord.js.

I am trying to create my first discord bot with python using the discord api through discord.py and with requests through requests.py.

My goal is to check status code on a site, and when a message is sent that contains "status code," it will reply with the site's status code in an embed.

Here is my code to do so:

import discord
import requests
r = requests.get('redactedurl')
test = r.status_code
class MyClient(discord.Client):
    async def on_ready(self):
        print('Logged on as {0}!'.format(self.user))

    async def on_message(self, message):
        if (message.channel.id == redacted):
                if "status code" in message.content:
                    print('Message from {0.author}: {0.content}'.format(message))

                    embed = discord.Embed(color=0x00ff00)
                    embed.title = "test"
                    embed.description = '**Status Code:** {r.status_code}'
                    await message.channel.send(embed=embed)

client = MyClient()
client.run('redacted')

The following is a list of questions I hope anybody can answer to help me out :)

As you see here: https://gyazo.com/f6ae7082486cade72389534a05655fec, this just sends "{r.status_code}" in the embed, instead of the actual status code, what am I doing wrong?

What does it mean when i see 0 in the curly brackets. For example, can somebody explain "('Logged on as {0}!'.format(self.user))" to me? Since I'm new to python and discord.py, I am confused about this whole line. I know what the outcome is, but forgive my ignorance, is it all necessary?

In "send(embed=embed)", why can't i just put send(embed)?

Finally, is there anything else that i can do to improve the code?

Thank you so much if you're able to help!

Body:
Okay working down your list of questions:

You're not formatting {r.status_code} but just sending it as a string which is why it shows up as just that. To fix it, all you have to do is add 1 "f".

embed.description = f'**Status Code:** {r.status_code}'

or, if you want to use a consistent way of formatting your strings:

embed.description = '**Status Code:** {0}'.format(r.status_code)

In Python, the curly brackets '{}' in a string can be used for formatting. This can be done in multiple ways including how you're doing it in your code. str.format() can take multiple arguments if you want to format different values in your string. The 0 is just an index for which argument you want to use.

I'm not too familiar with the discord library but having taken a quick look at the documentation it would seem that if you did that it would take your embed variable and pass it into send as the content variable. Thereby sending it as a normal message instead of embedding it.

I personally like f-strings more for formatting because it makes your code more easily readable. I can't really comment on your use of the discord library but besides that your code looks fine! Purely for aesthetics/readability I would put an empty line between your imports and defining your variables, and between your variables and your class.


问:
Tensorflow imports cause Heroku timeout (Django Python)
I'm using Heroku (free) to try to deploy a relatively simple neural network I made using Django. The problem is that when I import tensorflow to load the saved model, tf takes longer than 30 seconds to import, causing my single web worker to timeout and kill the page load.

Looking around on the internet, I found that using another worker thread might help with my slow import and model loading IO. However, I'm not sure what the best way to do this is, as the import chain from simply loading the page view spreads down to the tensorflow import. Trying to use basic Python threading within my app to put the imports and model loading in a different thread didn't help heroku load.

答: It turns out that using python threading DID help get past the R12 heroku timeout, but I then had a confounding error: my Django ALLOWED_HOSTS setting did not have the correct localhost url listed to run the site.