问:
include PHP script in laravel
i have a PHP script that i want to include it in My laravel App.so i try to build a controller and to put on it the script.the role of the  PHP scripts is to get data from an csv file and insert it in the database.But when i run it noting happen.
so this is my Job wait controller:

```<code><?php

namespace App\Http\Controllers;
include(app_path() . '/config.php');
include(app_path() . '/CDM/entities/job_en_wait.php');
include(app_path() . '/CDM/core/job_en_waitC.php');

use App\job_en_wait;
use Illuminate\Http\Request;

class JobWaitController extends Controller
 {
 //
function dos(){

 $dir = app_path(). '/files/';

$scan = scandir($dir);

$file = fopen($dir.$scan[4], "r");

print_r($scan[4]);

echo "<br>";

$data = fgetcsv($file, 1000, ",");

while (($data = fgetcsv($file, 1000, ",")) !== FALSE)
{
    if ($data[0]!=";;;;;") {
      $liste=explode(";",$data[0]);
      //print_r($liste);

     $job_en_wait=new job_en_wait(0,$liste[0],$liste[1],$liste[2],$liste[3],$liste[4],$liste[5],$liste[6],$liste[7],$liste[8],$liste[9],$liste[10]);

      $job_en_waitController=new job_en_waitC();

      $job_en_waitController->afficherjob_en_wait($job_en_wait);
      $job_en_waitController->ajouterjob_en_wait($job_en_wait);
      //echo "<br>job_en_wait integré avec succes <br>";
    }

}

fclose($file);

  }
  }
</code>```

this is job_waitC.php:

```<code><?PHP

    class job_en_waitC {

    function afficherjob_en_wait ($job_en_wait){
    echo "id: ".$job_en_wait->getid()."<br>";
    echo "client: ".$job_en_wait->getclient()."<br>";
    echo "session: ".$job_en_wait->getsession()."<br>";
    echo "info_session: ".$job_en_wait->getinfo_session()."<br>";
    echo "UPROC: ".$job_en_wait->getUPROC()."<br>";
    echo "num_session: ".$job_en_wait->getnum_session()."<br>";
    echo "num_exec: ".$job_en_wait->getnum_exec()."<br>";

    echo "date_debut: ".$job_en_wait->getdate_debut()."<br>";
    $hd=date_create($job_en_wait->getheure_debut());
    echo "heure_debut :".date_format($hd,"g:i:s A")."<br>";

    echo "date_fin: ".$job_en_wait->getdate_fin()."<br>";
    $hf=date_create($job_en_wait->getheure_fin());
    echo "heure_fin :".date_format($hf,"g:i:s A")."<br>";
    echo "status: ".$job_en_wait->getstatus()."<br>";

   }

   function ajouterjob_en_wait($job_en_wait){
    $date_debut=$job_en_wait->getdate_debut();
    $date_fin=$job_en_wait->getdate_fin();

    /*$heure_debut=date_create($job_en_wait->getheure_debut());
    $final_heure_debut=date_format($heure_debut,"m/d/Y H:i:s");

    $heure_fin=date_create($job_en_wait->getheure_fin());
    $final_fin_debut=date_format($heure_fin,"m/d/Y H:i:s");*/
    $heure_debut=$job_en_wait->getheure_debut();
    $heure_fin=$job_en_wait->getheure_fin();
    //echo "job_en_wait->getheure_fin ".$job_en_wait->getheure_fin();
    $sql="INSERT into job_en_wait (client,session,info_session,UPROC,num_session,num_exec,date_debut,heure_debut,date_fin,heure_fin,status)
     values (:client,:session,:info_session,:UPROC,:num_session,:num_exec,STR_TO_DATE('$date_debut','%d/%m/%Y'),STR_TO_DATE('05/12/2020 $heure_debut','%d/%m/%Y %H:%i:%s'),STR_TO_DATE('$date_fin','%d/%m/%Y'),STR_TO_DATE('05/12/2020 $heure_fin','%d/%m/%Y %H:%i:%s'),:status)";
    //echo "request :".$sql."<br>";
    $db = config::getConnexion();
    try{
    $req=$db->prepare($sql);

    $client=$job_en_wait->getclient();
    $session=$job_en_wait->getsession();
    $info_session=$job_en_wait->getinfo_session();
    $UPROC=$job_en_wait->getUPROC();
    $num_session=$job_en_wait->getnum_session();
    $num_exec=$job_en_wait->getnum_exec();

    $date_debut=$job_en_wait->getdate_debut();
    $heure_debut=$job_en_wait->getheure_debut();
    $date_fin=$job_en_wait->getdate_fin();
    $heure_fin=$job_en_wait->getheure_fin();

    $status=$job_en_wait->getstatus();

    $req->bindValue(':client',$client);
    $req->bindValue(':session',$session);
    $req->bindValue(':info_session',$info_session);
    $req->bindValue(':UPROC',$UPROC);
    $req->bindValue(':num_session',$num_session);
    $req->bindValue(':num_exec',$num_exec);

    $req->bindValue(':status',$status);

        $req->execute();

    }
    catch (Exception $e){
        echo 'Erreur exec erreur: '.$e->getMessage();
    }

}

function afficherjobs_en_wait(){
    //$sql="SElECT * From job_en_wait e inner join formationphp.job_en_wait a on e.cin= a.cin";
    $sql="SElECT * From job_en_wait";
    $db = config::getConnexion();
    try{
    $liste=$db->query($sql);
    return $liste;
    }
    catch (Exception $e){
        die('Erreur: '.$e->getMessage());
    }
}

}

?>
</code>```

And this is job_en_wait.php:

```<code><?PHP
class job_en_wait{

private $id;
private $client;
private $session;
private $info_session;
private $UPROC;
private $num_session;
private $num_exec;
private $date_debut;
private $heure_debut;
private $date_fin;
private $heure_fin;
private $status;

function __construct($id,$client,$session,$info_session,$UPROC,$num_session,$num_exec,$date_debut,$heure_debut,$date_fin,$heure_fin,$status){
$this->id=$id;
$this->client=$client;
$this->session=$session;
$this->info_session=$info_session;
$this->UPROC=$UPROC;
$this->num_session=$num_session;
$this->num_exec=$num_exec;
$this->date_debut=$date_debut;
$this->heure_debut=$heure_debut;
$this->date_fin=$date_fin;
$this->heure_fin=$heure_fin;
$this->status=$status;
}
function getid(){
    return $this->id;
}
function getclient(){
    return $this->client;
}
function getsession(){
    return $this->session;
}
function getinfo_session(){
    return $this->info_session;
}
function getUPROC(){
    return $this->UPROC;
}
function getnum_session(){
    return $this->num_session;
}
function getnum_exec(){
    return $this->num_exec;
}
function getdate_debut(){
    return $this->date_debut;
}
function getheure_debut(){
    return $this->heure_debut;
}
function getdate_fin(){
    return $this->date_fin;
}
function getheure_fin(){
    return $this->heure_fin;
}
function getstatus(){
    return $this->status;
}

function setclient($client){
    $this->client=$client;
}

function setsession($session){
    $this->session=$session;
}

function setinfo_session($info_session){
    $this->info_session=$info_session;
}

function setUPROC($UPROC){
    $this->UPROC=$UPROC;
}

function setnum_session($num_session){
    $this->num_session=$num_session;
}

function setnum_exec($num_exec){
    $this->num_exec=$num_exec;
}

function setdate_debut($date_debut){
    $this->date_debut=$date_debut;
}

function setheure_debut($heure_debut){
    $this->heure_debut=$heure_debut;
}

function setdate_fin($date_fin){
    $this->date_fin=$date_fin;
  }

    function setheure_fin($heure_fin){
    $this->heure_fin=$heure_fin;
   }

   function setstatus($status){
    $this->status=$status;
  }

   }

   ?>
</code>```

答:
This goes against PSR convention. There's a much cleaner way of doing this.
There's a few code convention mistakes you've made in your application.

You should follow PSR naming for namespaces:
https://www.php-fig.org/psr/psr-2/

You should create a seperate config file. so in your laravel config
folder you  should create a config file which is accessible by
config() function.

an example of how this would like is:
1) make a folder in /app/Models
2) put JobWait as a laravel model (You don't need to do all the sql, you should use eloquent
specify the namespace of JobWait as "use App/Models;"

I'd fully suggest converting the JobWait class you are using to be a Laravel Model.
https://www.youtube.com/watch?v=zpVE5RfcuTQ

Title: include PHP script in laravel

Body:
i have a PHP script that i want to include it in My laravel App.so i try to build a controller and to put on it the script.the role of the  PHP scripts is to get data from an csv file and insert it in the database.But when i run it noting happen.
so this is my Job wait controller:

<?php

namespace App\Http\Controllers;
include(app_path() . '/config.php');
include(app_path() . '/CDM/entities/job_en_wait.php');
include(app_path() . '/CDM/core/job_en_waitC.php');

use App\job_en_wait;
use Illuminate\Http\Request;

class JobWaitController extends Controller
 {
 //
function dos(){

 $dir = app_path(). '/files/';

$scan = scandir($dir);

$file = fopen($dir.$scan[4], "r");

print_r($scan[4]);

echo "
";

$data = fgetcsv($file, 1000, ",");

while (($data = fgetcsv($file, 1000, ",")) !== FALSE)
{
    if ($data[0]!=";;;;;") {
      $liste=explode(";",$data[0]);
      //print_r($liste);

     $job_en_wait=new job_en_wait(0,$liste[0],$liste[1],$liste[2],$liste[3],$liste[4],$liste[5],$liste[6],$liste[7],$liste[8],$liste[9],$liste[10]);

      $job_en_waitController=new job_en_waitC();

      $job_en_waitController->afficherjob_en_wait($job_en_wait);
      $job_en_waitController->ajouterjob_en_wait($job_en_wait);
      //echo "
job_en_wait integré avec succes
";
    }

}

fclose($file);

  }
  }

this is job_waitC.php:

<?PHP

    class job_en_waitC {

    function afficherjob_en_wait ($job_en_wait){
    echo "id: ".$job_en_wait->getid()."
";
    echo "client: ".$job_en_wait->getclient()."
";
    echo "session: ".$job_en_wait->getsession()."
";
    echo "info_session: ".$job_en_wait->getinfo_session()."
";
    echo "UPROC: ".$job_en_wait->getUPROC()."
";
    echo "num_session: ".$job_en_wait->getnum_session()."
";
    echo "num_exec: ".$job_en_wait->getnum_exec()."
";

    echo "date_debut: ".$job_en_wait->getdate_debut()."
";
    $hd=date_create($job_en_wait->getheure_debut());
    echo "heure_debut :".date_format($hd,"g:i:s A")."
";

    echo "date_fin: ".$job_en_wait->getdate_fin()."
";
    $hf=date_create($job_en_wait->getheure_fin());
    echo "heure_fin :".date_format($hf,"g:i:s A")."
";
    echo "status: ".$job_en_wait->getstatus()."
";

   }

   function ajouterjob_en_wait($job_en_wait){
    $date_debut=$job_en_wait->getdate_debut();
    $date_fin=$job_en_wait->getdate_fin();

    /*$heure_debut=date_create($job_en_wait->getheure_debut());
    $final_heure_debut=date_format($heure_debut,"m/d/Y H:i:s");

    $heure_fin=date_create($job_en_wait->getheure_fin());
    $final_fin_debut=date_format($heure_fin,"m/d/Y H:i:s");*/
    $heure_debut=$job_en_wait->getheure_debut();
    $heure_fin=$job_en_wait->getheure_fin();
    //echo "job_en_wait->getheure_fin ".$job_en_wait->getheure_fin();
    $sql="INSERT into job_en_wait (client,session,info_session,UPROC,num_session,num_exec,date_debut,heure_debut,date_fin,heure_fin,status)
     values (:client,:session,:info_session,:UPROC,:num_session,:num_exec,STR_TO_DATE('$date_debut','%d/%m/%Y'),STR_TO_DATE('05/12/2020 $heure_debut','%d/%m/%Y %H:%i:%s'),STR_TO_DATE('$date_fin','%d/%m/%Y'),STR_TO_DATE('05/12/2020 $heure_fin','%d/%m/%Y %H:%i:%s'),:status)";
    //echo "request :".$sql."
";
    $db = config::getConnexion();
    try{
    $req=$db->prepare($sql);

    $client=$job_en_wait->getclient();
    $session=$job_en_wait->getsession();
    $info_session=$job_en_wait->getinfo_session();
    $UPROC=$job_en_wait->getUPROC();
    $num_session=$job_en_wait->getnum_session();
    $num_exec=$job_en_wait->getnum_exec();

    $date_debut=$job_en_wait->getdate_debut();
    $heure_debut=$job_en_wait->getheure_debut();
    $date_fin=$job_en_wait->getdate_fin();
    $heure_fin=$job_en_wait->getheure_fin();

    $status=$job_en_wait->getstatus();

    $req->bindValue(':client',$client);
    $req->bindValue(':session',$session);
    $req->bindValue(':info_session',$info_session);
    $req->bindValue(':UPROC',$UPROC);
    $req->bindValue(':num_session',$num_session);
    $req->bindValue(':num_exec',$num_exec);

    $req->bindValue(':status',$status);

        $req->execute();

    }
    catch (Exception $e){
        echo 'Erreur exec erreur: '.$e->getMessage();
    }

}

function afficherjobs_en_wait(){
    //$sql="SElECT * From job_en_wait e inner join formationphp.job_en_wait a on e.cin= a.cin";
    $sql="SElECT * From job_en_wait";
    $db = config::getConnexion();
    try{
    $liste=$db->query($sql);
    return $liste;
    }
    catch (Exception $e){
        die('Erreur: '.$e->getMessage());
    }
}

}

?>

And this is job_en_wait.php:

<?PHP
class job_en_wait{

private $id;
private $client;
private $session;
private $info_session;
private $UPROC;
private $num_session;
private $num_exec;
private $date_debut;
private $heure_debut;
private $date_fin;
private $heure_fin;
private $status;

function __construct($id,$client,$session,$info_session,$UPROC,$num_session,$num_exec,$date_debut,$heure_debut,$date_fin,$heure_fin,$status){
$this->id=$id;
$this->client=$client;
$this->session=$session;
$this->info_session=$info_session;
$this->UPROC=$UPROC;
$this->num_session=$num_session;
$this->num_exec=$num_exec;
$this->date_debut=$date_debut;
$this->heure_debut=$heure_debut;
$this->date_fin=$date_fin;
$this->heure_fin=$heure_fin;
$this->status=$status;
}
function getid(){
    return $this->id;
}
function getclient(){
    return $this->client;
}
function getsession(){
    return $this->session;
}
function getinfo_session(){
    return $this->info_session;
}
function getUPROC(){
    return $this->UPROC;
}
function getnum_session(){
    return $this->num_session;
}
function getnum_exec(){
    return $this->num_exec;
}
function getdate_debut(){
    return $this->date_debut;
}
function getheure_debut(){
    return $this->heure_debut;
}
function getdate_fin(){
    return $this->date_fin;
}
function getheure_fin(){
    return $this->heure_fin;
}
function getstatus(){
    return $this->status;
}

function setclient($client){
    $this->client=$client;
}

function setsession($session){
    $this->session=$session;
}

function setinfo_session($info_session){
    $this->info_session=$info_session;
}

function setUPROC($UPROC){
    $this->UPROC=$UPROC;
}

function setnum_session($num_session){
    $this->num_session=$num_session;
}

function setnum_exec($num_exec){
    $this->num_exec=$num_exec;
}

function setdate_debut($date_debut){
    $this->date_debut=$date_debut;
}

function setheure_debut($heure_debut){
    $this->heure_debut=$heure_debut;
}

function setdate_fin($date_fin){
    $this->date_fin=$date_fin;
  }

    function setheure_fin($heure_fin){
    $this->heure_fin=$heure_fin;
   }

   function setstatus($status){
    $this->status=$status;
  }

   }

   ?>


来源: stackexchange

问:
Java8 stream with nested objects
So I'm new to Java8.  I've read about streams, but most examples are very basic.  I was wondering how it'd be done with nested objects.  Here is an example from my code:

```<code>for (Gas gas : gases) {
  resourceNodes.add(gas.getRefinery().unit());
}
</code>```

It seems like I should be able to one-line this with a stream, but I can't quite figure it out.  Could someone provide an answer with a stream.  Is there a way to use :: syntax with nested methods too?

Edit:
To clarify the example, getRefinery() returns an object of type: UnitInPool, whose method unit() returns an object of type: Unit.  resourceNodes is an ArrayList of Unit.

答:
If you want only method references, you can use this:

```<code>gases.stream().map(Gas::getRefinery).map(UnitInPool::unit).map(resourceNodes::add);
or
gases.stream().map(Gas::getRefinery).map(UnitInPool::unit).forEach(resourceNodes::add);
</code>```

Otherwise, a lambda would likely be better since it's a lot shorter and more readable, and works, when you have methods that take multiple parameters or need to do multiple complex operations.

```<code>gases.stream().forEach(g -> resourceNodes.add(g.getRefinery().unit()));
</code>```

This is basically the same as your previous code, but I would suggest the for-loop.

ContentLicense: CC BY-SA 4.0

Title: Java8 stream with nested objects

Body:
So I'm new to Java8.  I've read about streams, but most examples are very basic.  I was wondering how it'd be done with nested objects.  Here is an example from my code:

for (Gas gas : gases) {
  resourceNodes.add(gas.getRefinery().unit());
}

It seems like I should be able to one-line this with a stream, but I can't quite figure it out.  Could someone provide an answer with a stream.  Is there a way to use :: syntax with nested methods too?

Edit:
To clarify the example, getRefinery() returns an object of type: UnitInPool, whose method unit() returns an object of type: Unit.  resourceNodes is an ArrayList of Unit.

Body:
If you want only method references, you can use this:

gases.stream().map(Gas::getRefinery).map(UnitInPool::unit).map(resourceNodes::add);
or
gases.stream().map(Gas::getRefinery).map(UnitInPool::unit).forEach(resourceNodes::add);

Otherwise, a lambda would likely be better since it's a lot shorter and more readable, and works, when you have methods that take multiple parameters or need to do multiple complex operations.

gases.stream().forEach(g -> resourceNodes.add(g.getRefinery().unit()));

This is basically the same as your previous code, but I would suggest the for-loop.


问:
Concatenate arrays inside of an array - Value Error: Zero dimension arrays cannot be concatenated
I'm trying to append to an existing dataframe 3 new columns which should encode dummy variables.

To do this I am creating a function to look through the array to be "dummied", and for each 'hit' to assign the corresponding value to the to a new row.

```<code>import numpy as np
import pandas as pd

iriss = np.concatenate((np.array(['setosa']*50), np.array(['versicolor']*50), np.array(['virginica']*50)), axis = 0)
</code>```

In this case I present the Iris data set's species column, with 150 equally distributed species (50 units per species).

```<code>def one_hot_coding():
    one_hot_column = np.array([], dtype = 'int8')

    for one_hot in iriss:
        #my idea here is to find the 'hit = species' and to then for each 'hit' to assign to these
        # three different np.arrays the value of one or zero
        if one_hot == 'setosa':
            one_hot_setosa = np.append(one_hot_column, 1)
            one_hot_versicolor = np.append(one_hot_column, 0)
            one_hot_virginica = np.append(one_hot_column, 0)
        elif one_hot == 'versicolor':
            one_hot_setosa = np.append(one_hot_column, 0)
            one_hot_versicolor = np.append(one_hot_column, 1)
            one_hot_virginica = np.append(one_hot_column, 0)
        else:
            one_hot_setosa = np.append(one_hot_column, 0)
            one_hot_versicolor = np.append(one_hot_column, 0)
            one_hot_virginica = np.append(one_hot_column, 1)

        one_hot_setosa = np.concatenate((one_hot_setosa), axis = 0)

        print(one_hot_setosa)
one_hot_coding()
</code>```

Results Discussion:

to make it easier I will only talk about one_hot_setosa:
when I call print on one_hot_setosa 150 lines appear where the first 50 lines are [1]'s and the latter 100 [0]'s.

```<code>[1] [1] ...48 [0] [0] ...48 [0] [0] ... 48
</code>```

From what I see here my results are 150 independent arrays inside of the array called one_hot_setosa.

When I try to concatenate them all to obtain a single array (i.e. the iriss array created to house the 150 units) I get the following error

```<code>---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-107-6f70367ed6eb> in <module>
     24
     25         print(one_hot_setosa)
---> 26 one_hot_coding()

<ipython-input-107-6f70367ed6eb> in one_hot_coding()
     21             one_hot_virginica = np.append(one_hot_column, 1)
     22
---> 23         one_hot_setosa = np.concatenate((one_hot_setosa), axis = 0)
     24
     25         print(one_hot_setosa)

<__array_function__ internals> in concatenate(*args, **kwargs)

ValueError: zero-dimensional arrays cannot be concatenated
</code>```

So this error is telling me that I don't actually have 150 arrays, or better said an array.shape = (150, 1) (which is what I want). but that actually my array contains nothing? Why is this?

答:
Okay, so I've been fighting a lot but I managed to solve the problem.

np.concatenate will add rows to the array. So I specified I wanted to add rows to the one_hot_flower. Also, as @hpaulj pointed out, square brackets are very important to consider. Since my arrays are 1d arrays I needed to add only square brackets once to the value I wanted to concatenate.

All in all the final code looks like this:

```<code>import numpy as np
import pandas as pd

iriss = np.concatenate((np.array(['setosa']*50), np.array(['versicolor']*50), np.array(['virginica']*50)), axis = 0)

one_hot_setosa = np.array([])
one_hot_versicolor = np.array([])
one_hot_virginica = np.array([])

def one_hot_coding():
    global one_hot_setosa
    global one_hot_versicolor
    global one_hot_virginica

    for one_hot in iriss:
        if one_hot == 'setosa':
            one_hot_setosa = np.concatenate((one_hot_setosa, np.array([1])), axis = 0)
            one_hot_versicolor = np.concatenate((one_hot_versicolor, np.array([0])), axis = 0)
            one_hot_virginica = np.concatenate((one_hot_virginica, np.array([0])), axis = 0)
        elif one_hot == 'versicolor':
            one_hot_setosa = np.concatenate((one_hot_setosa, np.array([0])), axis = 0)
            one_hot_versicolor = np.concatenate((one_hot_versicolor, np.array([1])), axis = 0)
            one_hot_virginica = np.concatenate((one_hot_virginica, np.array([0])), axis = 0)
        else:
            one_hot_setosa = np.concatenate((one_hot_setosa, np.array([0])), axis = 0)
            one_hot_versicolor = np.concatenate((one_hot_versicolor, np.array([0])), axis = 0)
            one_hot_virginica = np.concatenate((one_hot_virginica, np.array([1])), axis = 0)

        #one_hot_setosa = np.concatenate((one_hot_setosa), axis = 0)

    return one_hot_setosa, one_hot_versicolor, one_hot_virginica
one_hot_coding()
</code>```

```<code>[Out]:
</code>```

```<code>(array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),
 array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),
 array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]))
</code>```

Body:
I'm trying to append to an existing dataframe 3 new columns which should encode dummy variables.

To do this I am creating a function to look through the array to be "dummied", and for each 'hit' to assign the corresponding value to the to a new row.

import numpy as np
import pandas as pd

iriss = np.concatenate((np.array(['setosa']*50), np.array(['versicolor']*50), np.array(['virginica']*50)), axis = 0)

In this case I present the Iris data set's species column, with 150 equally distributed species (50 units per species).

def one_hot_coding():
    one_hot_column = np.array([], dtype = 'int8')

    for one_hot in iriss:
        #my idea here is to find the 'hit = species' and to then for each 'hit' to assign to these
        # three different np.arrays the value of one or zero
        if one_hot == 'setosa':
            one_hot_setosa = np.append(one_hot_column, 1)
            one_hot_versicolor = np.append(one_hot_column, 0)
            one_hot_virginica = np.append(one_hot_column, 0)
        elif one_hot == 'versicolor':
            one_hot_setosa = np.append(one_hot_column, 0)
            one_hot_versicolor = np.append(one_hot_column, 1)
            one_hot_virginica = np.append(one_hot_column, 0)
        else:
            one_hot_setosa = np.append(one_hot_column, 0)
            one_hot_versicolor = np.append(one_hot_column, 0)
            one_hot_virginica = np.append(one_hot_column, 1)

        one_hot_setosa = np.concatenate((one_hot_setosa), axis = 0)

        print(one_hot_setosa)
one_hot_coding()

Results Discussion:

to make it easier I will only talk about one_hot_setosa:
when I call print on one_hot_setosa 150 lines appear where the first 50 lines are [1]'s and the latter 100 [0]'s.

[1] [1] ...48 [0] [0] ...48 [0] [0] ... 48

From what I see here my results are 150 independent arrays inside of the array called one_hot_setosa.

When I try to concatenate them all to obtain a single array (i.e. the iriss array created to house the 150 units) I get the following error

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-107-6f70367ed6eb> in <module>
     24
     25         print(one_hot_setosa)
---> 26 one_hot_coding()

<ipython-input-107-6f70367ed6eb> in one_hot_coding()
     21             one_hot_virginica = np.append(one_hot_column, 1)
     22
---> 23         one_hot_setosa = np.concatenate((one_hot_setosa), axis = 0)
     24
     25         print(one_hot_setosa)

<__array_function__ internals> in concatenate(*args, **kwargs)

ValueError: zero-dimensional arrays cannot be concatenated

So this error is telling me that I don't actually have 150 arrays, or better said an array.shape = (150, 1) (which is what I want). but that actually my array contains nothing? Why is this?

Body:
Okay, so I've been fighting a lot but I managed to solve the problem.

np.concatenate will add rows to the array. So I specified I wanted to add rows to the one_hot_flower. Also, as @hpaulj pointed out, square brackets are very important to consider. Since my arrays are 1d arrays I needed to add only square brackets once to the value I wanted to concatenate.

All in all the final code looks like this:

import numpy as np
import pandas as pd

iriss = np.concatenate((np.array(['setosa']*50), np.array(['versicolor']*50), np.array(['virginica']*50)), axis = 0)

one_hot_setosa = np.array([])
one_hot_versicolor = np.array([])
one_hot_virginica = np.array([])

def one_hot_coding():
    global one_hot_setosa
    global one_hot_versicolor
    global one_hot_virginica

    for one_hot in iriss:
        if one_hot == 'setosa':
            one_hot_setosa = np.concatenate((one_hot_setosa, np.array([1])), axis = 0)
            one_hot_versicolor = np.concatenate((one_hot_versicolor, np.array([0])), axis = 0)
            one_hot_virginica = np.concatenate((one_hot_virginica, np.array([0])), axis = 0)
        elif one_hot == 'versicolor':
            one_hot_setosa = np.concatenate((one_hot_setosa, np.array([0])), axis = 0)
            one_hot_versicolor = np.concatenate((one_hot_versicolor, np.array([1])), axis = 0)
            one_hot_virginica = np.concatenate((one_hot_virginica, np.array([0])), axis = 0)
        else:
            one_hot_setosa = np.concatenate((one_hot_setosa, np.array([0])), axis = 0)
            one_hot_versicolor = np.concatenate((one_hot_versicolor, np.array([0])), axis = 0)
            one_hot_virginica = np.concatenate((one_hot_virginica, np.array([1])), axis = 0)

        #one_hot_setosa = np.concatenate((one_hot_setosa), axis = 0)

    return one_hot_setosa, one_hot_versicolor, one_hot_virginica
one_hot_coding()

[Out]:

(array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),
 array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]),
 array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
        0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
        1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.]))


问:
Start motion scene programmatically
I have a motion layout with this layoutDescription: app:layoutDescription="@xml/scene"

scene.xml

```<code><MotionScene
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:constraintSetStart="@layout/view_home_card_start"
        motion:constraintSetEnd="@layout/view_home_card_end"
        motion:duration="1000">
        <OnSwipe
            motion:touchAnchorId="@+id/button"
            motion:touchAnchorSide="left"
            motion:dragDirection="dragLeft" />
    </Transition>

</MotionScene>
</code>```

I think that the xml of view_home_card_start and view_home_card_end is irrelevant.

How can  I call this animation programatically?

答:
You can also do this in your xml with

```<code>motion:autoTransition="animateToEnd"
</code>```

and

```<code>motion:autoTransition="animateToStart"
</code>```

Title: Start motion scene programmatically

Body:
I have a motion layout with this layoutDescription: app:layoutDescription="@xml/scene"

scene.xml

<MotionScene
    xmlns:motion="http://schemas.android.com/apk/res-auto">

    <Transition
        motion:constraintSetStart="@layout/view_home_card_start"
        motion:constraintSetEnd="@layout/view_home_card_end"
        motion:duration="1000">
        <OnSwipe
            motion:touchAnchorId="@+id/button"
            motion:touchAnchorSide="left"
            motion:dragDirection="dragLeft" />
    </Transition>

</MotionScene>

I think that the xml of view_home_card_start and view_home_card_end is irrelevant.

How can  I call this animation programatically?

Body:
You can also do this in your xml with

motion:autoTransition="animateToEnd"

and

motion:autoTransition="animateToStart"


问:
How to analyze .class files using soot?
I'm trying to build a call-graph(CG) for spotbugs-4.0.2 with soot. The code is shown as follows.

```<code>public static void main(String[] args) {

    String analyzed_classes_dir = "C:\\Users\\lyu\\lll\\src\\test\\java\\com\\demo\\dir3\\spotbugs"; //contains all structured class files
    String mainclass = "edu.umd.cs.findbugs.LaunchAppropriateUI";

    //set classpath
    String javapath = System.getProperty("java.class.path");
    String jredir = System.getProperty("java.home") + "\\lib\\rt.jar";
    String libs = "C:\\Users\\liuyu\\lll\\src\\test\\java\\com\\demo\\libs\\spotbugs-4.0.2\\";
    String path = javapath + File.pathSeparator + jredir + File.pathSeparator + libs;

    Scene.v().setSootClassPath(path);

    //add an intra-procedural analysis phase to Soot
    TestCallGraphSootJar_3 analysis = new TestCallGraphSootJar_3();
    PackManager.v().getPack("wjtp").add(new Transform("wjtp.TestSootCallGraph", analysis));

    excludeJDKLibrary();

    Options.v().set_process_dir(Arrays.asList(analyzed_classes_dir));
    Options.v().set_whole_program(true);
    Options.v().set_no_bodies_for_excluded(true);
    Options.v().set_allow_phantom_refs(true);

    Scene.v().loadNecessaryClasses();
    SootClass appclass = Scene.v().getSootClass(mainclass);
    Scene.v().setMainClass(appclass); // exception here.

    enableSparkCallGraph();

    PackManager.v().runPacks();
}
</code>```

Then the exception:

```<code>Exception in thread "main" java.lang.RuntimeException: Main-class has no main method!
at soot.Scene.setMainClass(Scene.java:187)
at com.ouc.TestCallGraphSootJar_3.main(TestCallGraphSootJar_3.java:65)
</code>```

The statement "Scene.v().setMainClass(appclass);" throws the above exception.
I debugged it and found that the methodlst in the appclass is null. And appclass is phantom.
As shown in the picture.
fig. the debug information of appclass

The mainclass does exist in the specified path, and it does contain the main method.

I've submitted an issue in GitHub (https://github.com/Sable/soot/issues/1346#issuecomment-627551137) but didn't solve it. And the options manual also didn't help with this problem.

Btw, could I only analyze the call relationships in a given class? For example, I only want to get the call information inside the class C1.

```<code>Class C1{
  main(){
    m1(parm);
  }

  m1(args){
    m2(xxx);
  }

  m2(args){
    m3(xxx);
  }

  m3(args){
    ...
  }
}
</code>```

Then I only want to get the follow call relationship:

```<code>main——>m1()——>m2()——m3()
</code>```

If main or m1 or m2 or m3 calls a method in another class C2, I will ignore it, only focus on the methods in C1.

答: I'm the asker, and I've solved it. If you are interested in this question, you can read it in this issue post.</p>

Title: How to analyze .class files using soot?

Body:
I'm trying to build a call-graph(CG) for spotbugs-4.0.2 with soot. The code is shown as follows.

public static void main(String[] args) {

    String analyzed_classes_dir = "C:\\Users\\lyu\\lll\\src\\test\\java\\com\\demo\\dir3\\spotbugs"; //contains all structured class files
    String mainclass = "edu.umd.cs.findbugs.LaunchAppropriateUI";

    //set classpath
    String javapath = System.getProperty("java.class.path");
    String jredir = System.getProperty("java.home") + "\\lib\\rt.jar";
    String libs = "C:\\Users\\liuyu\\lll\\src\\test\\java\\com\\demo\\libs\\spotbugs-4.0.2\\";
    String path = javapath + File.pathSeparator + jredir + File.pathSeparator + libs;

    Scene.v().setSootClassPath(path);

    //add an intra-procedural analysis phase to Soot
    TestCallGraphSootJar_3 analysis = new TestCallGraphSootJar_3();
    PackManager.v().getPack("wjtp").add(new Transform("wjtp.TestSootCallGraph", analysis));

    excludeJDKLibrary();

    Options.v().set_process_dir(Arrays.asList(analyzed_classes_dir));
    Options.v().set_whole_program(true);
    Options.v().set_no_bodies_for_excluded(true);
    Options.v().set_allow_phantom_refs(true);

    Scene.v().loadNecessaryClasses();
    SootClass appclass = Scene.v().getSootClass(mainclass);
    Scene.v().setMainClass(appclass); // exception here.

    enableSparkCallGraph();

    PackManager.v().runPacks();
}

Then the exception:

Exception in thread "main" java.lang.RuntimeException: Main-class has no main method!
at soot.Scene.setMainClass(Scene.java:187)
at com.ouc.TestCallGraphSootJar_3.main(TestCallGraphSootJar_3.java:65)

The statement "Scene.v().setMainClass(appclass);" throws the above exception.
I debugged it and found that the methodlst in the appclass is null. And appclass is phantom.
As shown in the picture.
fig. the debug information of appclass

The mainclass does exist in the specified path, and it does contain the main method.

I've submitted an issue in GitHub (https://github.com/Sable/soot/issues/1346#issuecomment-627551137) but didn't solve it. And the options manual also didn't help with this problem.

Btw, could I only analyze the call relationships in a given class? For example, I only want to get the call information inside the class C1.

Class C1{
  main(){
    m1(parm);
  }

  m1(args){
    m2(xxx);
  }

  m2(args){
    m3(xxx);
  }

  m3(args){
    ...
  }
}

Then I only want to get the follow call relationship:

main——>m1()——>m2()——m3()

If main or m1 or m2 or m3 calls a method in another class C2, I will ignore it, only focus on the methods in C1.


问:
Why do these constant functions performance differ?
In the following snippet, why is py_sqrt2 almost twice as fast as np_sqrt2?

from time import time
from numpy import sqrt as npsqrt
from math import sqrt as pysqrt

NP_SQRT2 = npsqrt(2.0)
PY_SQRT2 = pysqrt(2.0)

def np_sqrt2():
    return NP_SQRT2

def py_sqrt2():
    return PY_SQRT2

def main():
    samples = 10000000

    it = time()
    E = sum(np_sqrt2() for _ in range(samples)) / samples
    print("executed {} np_sqrt2's in {:.6f} seconds E={}".format(samples, time() - it, E))

    it = time()
    E = sum(py_sqrt2() for _ in range(samples)) / samples
    print("executed {} py_sqrt2's in {:.6f} seconds E={}".format(samples, time() - it, E))

if __name__ == "__main__":
    main()

```

<pre class="lang-none prettyprint-override"><code>$ python2.7 snippet.py
executed 10000000 np_sqrt2's in 1.380090 seconds E=1.41421356238
executed 10000000 py_sqrt2's in 0.855742 seconds E=1.41421356238
$ python3.6 snippet.py
executed 10000000 np_sqrt2's in 1.628093 seconds E=1.4142135623841212
executed 10000000 py_sqrt2's in 0.932918 seconds E=1.4142135623841212
</code>```

Notice that they are constant functions that just load from precomputed globals with the same value, and that the constants only differ in how they were computed at program start.

Moreover the disassembly of these functions show that they do as expected and only access the global constants.

```<code>In [73]: dis(py_sqrt2)
  2           0 LOAD_GLOBAL              0 (PY_SQRT2)
              2 RETURN_VALUE

In [74]: dis(np_sqrt2)
  2           0 LOAD_GLOBAL              0 (NP_SQRT2)
              2 RETURN_VALUE
</code>```

答:
because you are sending it to c every time for just one value

try the following instead

```<code>t0=time.time()
numpy.sqrt([2]*10000)
t1 = time.time()
print("Took %0.3fs to do 10k sqrt(2)"%(t1-t0))

t0 = time.time()
for i in range(10000):
    numpy.sqrt(2)
t1 = time.time()
print("Took %0.3fs to do 10k math.sqrt(2)"%(t1-t0))
</code>```

Body:
In the following snippet, why is py_sqrt2 almost twice as fast as np_sqrt2?

from time import time
from numpy import sqrt as npsqrt
from math import sqrt as pysqrt

NP_SQRT2 = npsqrt(2.0)
PY_SQRT2 = pysqrt(2.0)

def np_sqrt2():
    return NP_SQRT2

def py_sqrt2():
    return PY_SQRT2

def main():
    samples = 10000000

    it = time()
    E = sum(np_sqrt2() for _ in range(samples)) / samples
    print("executed {} np_sqrt2's in {:.6f} seconds E={}".format(samples, time() - it, E))

    it = time()
    E = sum(py_sqrt2() for _ in range(samples)) / samples
    print("executed {} py_sqrt2's in {:.6f} seconds E={}".format(samples, time() - it, E))

if __name__ == "__main__":
    main()

$ python2.7 snippet.py
executed 10000000 np_sqrt2's in 1.380090 seconds E=1.41421356238
executed 10000000 py_sqrt2's in 0.855742 seconds E=1.41421356238
$ python3.6 snippet.py
executed 10000000 np_sqrt2's in 1.628093 seconds E=1.4142135623841212
executed 10000000 py_sqrt2's in 0.932918 seconds E=1.4142135623841212

Notice that they are constant functions that just load from precomputed globals with the same value, and that the constants only differ in how they were computed at program start.

Moreover the disassembly of these functions show that they do as expected and only access the global constants.

In [73]: dis(py_sqrt2)
  2           0 LOAD_GLOBAL              0 (PY_SQRT2)
              2 RETURN_VALUE

In [74]: dis(np_sqrt2)
  2           0 LOAD_GLOBAL              0 (NP_SQRT2)
              2 RETURN_VALUE

Body:
because you are sending it to c every time for just one value

try the following instead

t0=time.time()
numpy.sqrt([2]*10000)
t1 = time.time()
print("Took %0.3fs to do 10k sqrt(2)"%(t1-t0))

t0 = time.time()
for i in range(10000):
    numpy.sqrt(2)
t1 = time.time()
print("Took %0.3fs to do 10k math.sqrt(2)"%(t1-t0))


问:
operator new inside namespace
```<code>namespace X
{
  void* operator new (size_t);
}
</code>```

gives error message as:

```<code>error: ‘void* X::operator new(size_t)’ may not be declared within a namespace
</code>```

Is it a gcc compiler bug ? In older gcc version it seems to be working.
Any idea, why it's not allowed ?

Use case:
I wanted to allow only custom operator new/delete for the classes and wanted to disallow global new/operator. Instead of linker error, it was easy to catch compiler error; so I coded:

```<code>namespace X {
  void* operator new (size_t);
}
using namespace X;
</code>```

This worked for older version of gcc but not for the new one.

答:
This is not allowed because it makes no sense. For example you have the following

```<code>int* ptr = 0;

namespace X {
    void* operator new (size_t);
    void operator delete(void*);
    void f()
    {
       ptr = new int();
    }
}

void f()
{
    delete ptr;
    ptr = 0;
}
</code>```

now how should the ptr be deleted - with global namespace operator delete() or with the one specific to namespace X? There's no possible way for C++ to deduce that.

ContentLicense: CC BY-SA 3.0

Title: operator new inside namespace

Body:
namespace X
{
  void* operator new (size_t);
}

gives error message as:

error: ‘void* X::operator new(size_t)’ may not be declared within a namespace

Is it a gcc compiler bug ? In older gcc version it seems to be working.
Any idea, why it's not allowed ?

Use case:
I wanted to allow only custom operator new/delete for the classes and wanted to disallow global new/operator. Instead of linker error, it was easy to catch compiler error; so I coded:

namespace X {
  void* operator new (size_t);
}
using namespace X;

This worked for older version of gcc but not for the new one.

Body:
This is not allowed because it makes no sense. For example you have the following

int* ptr = 0;

namespace X {
    void* operator new (size_t);
    void operator delete(void*);
    void f()
    {
       ptr = new int();
    }
}

void f()
{
    delete ptr;
    ptr = 0;
}

now how should the ptr be deleted - with global namespace operator delete() or with the one specific to namespace X? There's no possible way for C++ to deduce that.


问:
How to specify / select a particular property of an object
I am creating a react web app. My state in my parent component is an array of objects (one to many number of objects stored in this array...it could be any number of objects). I want to send object X of the array through to my child component through props. Here is my child component:

```<code>import React, { Component } from 'react'

export class Card extends Component {

    render() {
        console.log('in card');
        console.log(this.props.newCard);
        return (
            <div>
                <h2>Here is a card!</h2>

            </div>
        )
    }
}

export default Card
</code>```

For necessary context, here is my render method in the parent component that calls the child (named Card):

```<code>render() {
        return (
            <div>
                <Card newCard={this.state.cardList[this.state.eachCard]}></Card>
                <button>Next</button>
            </div>
        )
    }
</code>```

The this.state.eachCard is just referring to an accumulator I will later implement to go through each object of the array upon clicking the Next button. Right now it is just set to position 0 for testing purposes.

When I console.log the newCard prop in the child component, this is the structure of the object that is send from parent to child:

```<code>{CardID: 3, CardName: "test", CardDefinition: "testing", category_CategoryID: 2}
</code>```

However, I am wanting to specify a particular property of this object. For example, I want to retrieve the name of the card. However, when I tried to console.log this

```<code>console.log(this.props.newCard.CardName);
</code>```

I received the following error:

```<code>"Cannot read property 'CardName' of undefined"
</code>```

This does not make sense to me, as this.props.newCard was not undefined. Therefore it would make sense to me that specifying the newCard prop one more degree to newCard.CardName should logically work. I cannot figure out what I am missing. Is this some sort of syntax error? Or is my logic just totally off?
I seem to be very close, but am hung up on how to proceed...any ideas sure would be appreciated. Thanks!!

答: There is a typo in your console log, change porps by props.

Body:
I am creating a react web app. My state in my parent component is an array of objects (one to many number of objects stored in this array...it could be any number of objects). I want to send object X of the array through to my child component through props. Here is my child component:

import React, { Component } from 'react'

export class Card extends Component {

    render() {
        console.log('in card');
        console.log(this.props.newCard);
        return (

Here is a card!

        )
    }
}

export default Card

For necessary context, here is my render method in the parent component that calls the child (named Card):

render() {
        return (

                <Card newCard={this.state.cardList[this.state.eachCard]}></Card>
                <button>Next</button>

        )
    }

The this.state.eachCard is just referring to an accumulator I will later implement to go through each object of the array upon clicking the Next button. Right now it is just set to position 0 for testing purposes.

When I console.log the newCard prop in the child component, this is the structure of the object that is send from parent to child:

{CardID: 3, CardName: "test", CardDefinition: "testing", category_CategoryID: 2}

However, I am wanting to specify a particular property of this object. For example, I want to retrieve the name of the card. However, when I tried to console.log this

console.log(this.props.newCard.CardName);

I received the following error:

"Cannot read property 'CardName' of undefined"

This does not make sense to me, as this.props.newCard was not undefined. Therefore it would make sense to me that specifying the newCard prop one more degree to newCard.CardName should logically work. I cannot figure out what I am missing. Is this some sort of syntax error? Or is my logic just totally off?
I seem to be very close, but am hung up on how to proceed...any ideas sure would be appreciated. Thanks!!


问:
Provider Package and where to put my methods/logic?
I'm trying to convert my code into using providers (provider package) as I think it could be more efficient, especially due to the fact that I need to update widgets through a 'Settings Page' and 'Add More Names Page' which is further down the widget tree.

However, I'm unsure where to put the bulk of my 'logic' when using providers. For example, in my original format I have two lists names and games.

```<code>final List<String> names = [];
  List<String> games = ["Game 1", "Game 2", "Game 3", "Game 4", "Game 5"];
</code>```

Beforehand, I created a Text Field that would add to the list names.

```<code>TextEditingController nameController = TextEditingController();

TextField(
     controller: nameController,
     onSubmitted: addToList(),

addToList() {
    if (nameController.text.isNotEmpty) {
      setState(() {
        names.add(nameController.text);
      });
      nameController.clear();
    }
  }
</code>```

Should I put this TextField or addTooList method into my DataProvider class as shown below as I will need to add more names and games further down the widget tree. If so how/how would you use it?

```<code>import 'package:flutter/material.dart';

class DataProvider with ChangeNotifier{
  List<String> _names;
  List<String> _games;

  DataProvider(){
    _names = [];
    _games = ["Game 1", "Game 2", "Game 3", "Game 4", "Game 5"];
  }

  // Getters - How we get these values
  List<String> get names => _names;
  List<String> get games => _games;

  // Setters
  void setNames(List<String> names){
    _names = names;
    notifyListeners();
  }

  void setGames(List<String> games){
    _games = games;
    notifyListeners();
  }
}
</code>```

Thank you! Would appreciate any help.

答:
Generally, you would put anything that is not directly UI related in your Provider. And then do anything like modifying UI and consuming data from your Provider in the Widgets.

Another way to look at it is, "can I write less Code if it is in the Provider?" So if you are calling your function in many places, and those values get modified and used in other places, put it in the Provider.

Overall its just about making your development easier, so do whatever makes most sense, there are no strict rules.

EDIT:

Without seeing more of your code it's hard to say how I'd do it with your example. But I would guess the TextField stays in Widgets, since its a UI element. And your function looks like it should be in Provider.

Body:
I'm trying to convert my code into using providers (provider package) as I think it could be more efficient, especially due to the fact that I need to update widgets through a 'Settings Page' and 'Add More Names Page' which is further down the widget tree.

However, I'm unsure where to put the bulk of my 'logic' when using providers. For example, in my original format I have two lists names and games.

final List<String> names = [];
  List<String> games = ["Game 1", "Game 2", "Game 3", "Game 4", "Game 5"];

Beforehand, I created a Text Field that would add to the list names.

TextEditingController nameController = TextEditingController();

TextField(
     controller: nameController,
     onSubmitted: addToList(),

addToList() {
    if (nameController.text.isNotEmpty) {
      setState(() {
        names.add(nameController.text);
      });
      nameController.clear();
    }
  }

Should I put this TextField or addTooList method into my DataProvider class as shown below as I will need to add more names and games further down the widget tree. If so how/how would you use it?

import 'package:flutter/material.dart';

class DataProvider with ChangeNotifier{
  List<String> _names;
  List<String> _games;

  DataProvider(){
    _names = [];
    _games = ["Game 1", "Game 2", "Game 3", "Game 4", "Game 5"];
  }

  // Getters - How we get these values
  List<String> get names => _names;
  List<String> get games => _games;

  // Setters
  void setNames(List<String> names){
    _names = names;
    notifyListeners();
  }

  void setGames(List<String> games){
    _games = games;
    notifyListeners();
  }
}

Thank you! Would appreciate any help.


问:
Emacs: keep region selected after operation
In emacs, after an operation such as comment-region, the selected region is automatically deselected.

Is there any way of disabling this behaviour?

答:
Fortunately, Keyboard macros don't deselect the region if they alter it.  So you can write your function, then create a kbd macro that calls your function and then does C-x C-x once or, if you care about point and mark being as they were, do it twice.  Then name your kbd macro.  Then M-x write-kbd-macro  and, when prompted, give it the name of the file that you want the macro appended to and then give it the name of your new macro.  If you now bind your macro to a key you can repeatedly press the key without losing the region.
   It would sure be nice if  Emacs's 'interactive' took '_' as part of the string argument to retain the region and highlighting the way XEmacs's 'interactive' does.   </p>

ContentLicense: CC BY-SA 2.5


问:
How to add one to a cookie?
My goal is to add 1 to a cookie, once a button is clicked. My code looks like this:

```<code>    console.log("Checking for any existing cookies...");
    var ifcookie = $.cookie('searchcount');
    if (ifcookie >= 0) {
        var count = $.cookie('searchcount');
        const one = 1;
        var count = count + one;
        console.log("Total searches: " + count);
        $.cookie('searchcount', count, { expires: 99999 });
        var count = $.cookie('searchcount');
        console.log(count);}}
</code>```

So basically every time function "countSearches" is executed, I want to add 1 to the cookie "searchcount".
But my output is just "0111...". How can I add this and set this to a cookie?

I use jquery for the cookies.

答:
Change the line

```<code> var count = count + one;
</code>```

to

```<code>var count = parseInt(count) + one;
</code>```

The parseInt() function parses a string argument and returns an integer. The value of the cookie is a string, not a number.

Title: How to add one to a cookie?

Body:
My goal is to add 1 to a cookie, once a button is clicked. My code looks like this:

    console.log("Checking for any existing cookies...");
    var ifcookie = $.cookie('searchcount');
    if (ifcookie >= 0) {
        var count = $.cookie('searchcount');
        const one = 1;
        var count = count + one;
        console.log("Total searches: " + count);
        $.cookie('searchcount', count, { expires: 99999 });
        var count = $.cookie('searchcount');
        console.log(count);}}

So basically every time function "countSearches" is executed, I want to add 1 to the cookie "searchcount".
But my output is just "0111...". How can I add this and set this to a cookie?

I use jquery for the cookies.

Body:
Change the line

 var count = count + one;

to

var count = parseInt(count) + one;

The parseInt() function parses a string argument and returns an integer. The value of the cookie is a string, not a number.


问:
Flutter: How to sort ListView by ToggleButtons
I have a list view as follows:

Code of listview:

_listCountry(index) {
  Country country = _country[index];
  return Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: <Widget> [
      Text('${country.id}'),
      Text(country.name),
      Text('${country.population}'),
    ],
  );
}
```

<p>And I created methods to sort, it worked fine:</p>

<pre class="lang-js prettyprint-override"><code>_onSortID() {
  setState(() {
    _country.sort((a, b) => b.id.compareTo(a.id));
  });
}

_onSortName() {
  setState(() {
    _country.sort((a, b) => b.name.compareTo(a.name));
  });
}

_onSortPopulation() {
  setState(() {
    _country.sort((b, a) => b.population.compareTo(a.population));
  });
}
</code>```

So how do I get these methods into the Onpressed of ToggleButtons so that they can sort when pressed? This is the Toggle Button code:

ToggleButtons(
  children: <Widget> [
    Text('Country ID'),
    Text('Country Name'),
    Text('Country Population')
  ],
  onPressed: (int index) {
    setState(() {
      for (int buttonIndex = 0; buttonIndex < isSelected.length; buttonIndex++) {
        if (buttonIndex == index) {
          isSelected[buttonIndex] = !isSelected[buttonIndex];
        } else {
          isSelected[buttonIndex] = false;
        }
      }
    });
  },
  isSelected: isSelected,
)
```

答:
try this :

Define a list of methods

```<code>List sortMethods;
</code>```

Then create it in initState() like this :

```<code>@override
  initState() {
    sortMethods = List.of({
      () => setState(
            () {
              _country.sort((a, b) => b.id.compareTo(a.id));
            },
          ),
      () => setState(() {
            _country.sort((a, b) => b.name.compareTo(a.name));
          }),
      () => setState(() {
            _country.sort((a, b) => b.population.compareTo(a.population));
          })
    });
    super.initState();
  }
</code>```

When you select ToggleButton, call the method like this :

```<code> onPressed: (int index) {
   for (int buttonIndex = 0; buttonIndex < isSelected.length; buttonIndex++) {
        if (buttonIndex == index) {
          isSelected[buttonIndex] = !isSelected[buttonIndex];
        } else {
          isSelected[buttonIndex] = false;
        }
         sortMethods[index]();
      }
     }
</code>```

Body:
I have a list view as follows:

Code of listview:

_listCountry(index) {
  Country country = _country[index];
  return Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: <Widget> [
      Text('${country.id}'),
      Text(country.name),
      Text('${country.population}'),
    ],
  );
}

And I created methods to sort, it worked fine:

_onSortID() {
  setState(() {
    _country.sort((a, b) => b.id.compareTo(a.id));
  });
}

_onSortName() {
  setState(() {
    _country.sort((a, b) => b.name.compareTo(a.name));
  });
}

_onSortPopulation() {
  setState(() {
    _country.sort((b, a) => b.population.compareTo(a.population));
  });
}

So how do I get these methods into the Onpressed of ToggleButtons so that they can sort when pressed? This is the Toggle Button code:

ToggleButtons(
  children: <Widget> [
    Text('Country ID'),
    Text('Country Name'),
    Text('Country Population')
  ],
  onPressed: (int index) {
    setState(() {
      for (int buttonIndex = 0; buttonIndex < isSelected.length; buttonIndex++) {
        if (buttonIndex == index) {
          isSelected[buttonIndex] = !isSelected[buttonIndex];
        } else {
          isSelected[buttonIndex] = false;
        }
      }
    });
  },
  isSelected: isSelected,
)

Body:
try this :

Define a list of methods

List sortMethods;

Then create it in initState() like this :

@override
  initState() {
    sortMethods = List.of({
      () => setState(
            () {
              _country.sort((a, b) => b.id.compareTo(a.id));
            },
          ),
      () => setState(() {
            _country.sort((a, b) => b.name.compareTo(a.name));
          }),
      () => setState(() {
            _country.sort((a, b) => b.population.compareTo(a.population));
          })
    });
    super.initState();
  }

When you select ToggleButton, call the method like this :

 onPressed: (int index) {
   for (int buttonIndex = 0; buttonIndex < isSelected.length; buttonIndex++) {
        if (buttonIndex == index) {
          isSelected[buttonIndex] = !isSelected[buttonIndex];
        } else {
          isSelected[buttonIndex] = false;
        }
         sortMethods[index]();
      }
     }


问:
Round by next quarter minutes always
We have a requirement to Round by next quarter minutes in Java code, for example:

if current date time is  2020-05-28T10:01:00
then, round up to next quarter to make it  2020-05-28T10:15:00

if current date time is 2020-05-28T10:15:01
then, round up to next quarter to make it  2020-05-28T10:30:00

if current date time is 2020-05-28T10:46:15
then, round up to next quarter to make it  2020-05-28T11:00:00

if current date time is 2020-12-31T23:47:00
then, round up to next quarter to make it 2021-01-01T00:00:00

Can someone please provide Java code to achieve this. Any help is appreciated.

Tried below code but unable to get the output which I'm looking for:

```<code>import java.util.Calendar;
import java.util.Date;

    public class Main {
        public static void main(String[] args) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            int round = calendar.get(Calendar.MINUTE) % 15;
            calendar.add(Calendar.MINUTE, round < 8 ? -round : (15-round));
            calendar.set( Calendar.SECOND, 0 );
            System.out.println(calendar.getTime());
        }
    }
</code>```

答:
This can be easily done using the LocalDateTime class from the java.time package, which you should be using anyway1.

```<code>public static LocalDateTime roundUpToQuarter(LocalDateTime datetime) {
    int minutesToAdd = 15 - (datetime.getMinute() % 15);
    return datetime
        .plusMinutes(minutesToAdd)
        .truncatedTo(ChronoUnit.MINUTES);
}
</code>```

This calculation involving the modulus operator makes sure that we get the number of minutes to add to go to the next full quarter. The truncatedTo(ChronoUnit.MINUTES) call makes in turn sure that all fields smaller than 'minutes' are set to zero.

Update: I'm not certain of your exact use case, but, as Basil pointed out, if you want to represent a moment on the timeline, then you also need a timezone or offset. This can be done by replacing LocalDateTime instances with ZonedDateTime in the abovementioned method.

1 The Date, Calendar and SimpleDateFormat classes are obsolete. They may work in simple cases, but they will cause trouble in more complex cases. See What's wrong with Java Date & Time API?.

Title: Round by next quarter minutes always

Body:
We have a requirement to Round by next quarter minutes in Java code, for example:

if current date time is  2020-05-28T10:01:00
then, round up to next quarter to make it  2020-05-28T10:15:00

if current date time is 2020-05-28T10:15:01
then, round up to next quarter to make it  2020-05-28T10:30:00

if current date time is 2020-05-28T10:46:15
then, round up to next quarter to make it  2020-05-28T11:00:00

if current date time is 2020-12-31T23:47:00
then, round up to next quarter to make it 2021-01-01T00:00:00

Can someone please provide Java code to achieve this. Any help is appreciated.

Tried below code but unable to get the output which I'm looking for:

import java.util.Calendar;
import java.util.Date;

    public class Main {
        public static void main(String[] args) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            int round = calendar.get(Calendar.MINUTE) % 15;
            calendar.add(Calendar.MINUTE, round < 8 ? -round : (15-round));
            calendar.set( Calendar.SECOND, 0 );
            System.out.println(calendar.getTime());
        }
    }

Body:
This can be easily done using the LocalDateTime class from the java.time package, which you should be using anyway1.

public static LocalDateTime roundUpToQuarter(LocalDateTime datetime) {
    int minutesToAdd = 15 - (datetime.getMinute() % 15);
    return datetime
        .plusMinutes(minutesToAdd)
        .truncatedTo(ChronoUnit.MINUTES);
}

This calculation involving the modulus operator makes sure that we get the number of minutes to add to go to the next full quarter. The truncatedTo(ChronoUnit.MINUTES) call makes in turn sure that all fields smaller than 'minutes' are set to zero.

Update: I'm not certain of your exact use case, but, as Basil pointed out, if you want to represent a moment on the timeline, then you also need a timezone or offset. This can be done by replacing LocalDateTime instances with ZonedDateTime in the abovementioned method.

1 The Date, Calendar and SimpleDateFormat classes are obsolete. They may work in simple cases, but they will cause trouble in more complex cases. See What's wrong with Java Date & Time API?.


问:
Google domains registered hosts (glue records) are not resolving after 48 hours
I am using Google domains for my domain: violetnorthapp.com, I have a few custom nameservers that I am running and I want to create registered hosts (which is the term used by google for glue records). I created a registered host under test.ns.violetnorthapp.com which should resolve to 8.8.8.8.

It's been more than 48 hours but it's still not resolving with dig test.ns.violetnorthapp.com.

```<code>; <<>> DiG 9.10.6 <<>> test.ns.violetnorthapp.com.
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 63639
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;test.ns.violetnorthapp.com.    IN  A

;; AUTHORITY SECTION:
violetnorthapp.com. 300 IN  SOA ns-cloud-b1.googledomains.com. cloud-dns-hostmaster.google.com. 6 21600 3600 259200 300

;; Query time: 68 msec
;; SERVER: 192.168.0.1#53(192.168.0.1)
;; WHEN: Sat May 30 18:31:02 EDT 2020
;; MSG SIZE  rcvd: 145
</code>```

I tried running it with the TLD nameserver of com. One of them is a.gtld-servers.net., so the request is dig test.ns.violetnorthapp.com. @a.gtld-servers.net.:

```<code>; <<>> DiG 9.10.6 <<>> test.ns.violetnorthapp.com. @a.gtld-servers.net.
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 26571
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 4, ADDITIONAL: 9
;; WARNING: recursion requested but not available

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;test.ns.violetnorthapp.com.    IN  A

;; AUTHORITY SECTION:
violetnorthapp.com. 172800  IN  NS  ns-cloud-b1.googledomains.com.
violetnorthapp.com. 172800  IN  NS  ns-cloud-b2.googledomains.com.
violetnorthapp.com. 172800  IN  NS  ns-cloud-b3.googledomains.com.
violetnorthapp.com. 172800  IN  NS  ns-cloud-b4.googledomains.com.

;; ADDITIONAL SECTION:
ns-cloud-b1.googledomains.com. 172800 IN AAAA   2001:4860:4802:32::6b
ns-cloud-b1.googledomains.com. 172800 IN A  216.239.32.107
ns-cloud-b2.googledomains.com. 172800 IN AAAA   2001:4860:4802:34::6b
ns-cloud-b2.googledomains.com. 172800 IN A  216.239.34.107
ns-cloud-b3.googledomains.com. 172800 IN AAAA   2001:4860:4802:36::6b
ns-cloud-b3.googledomains.com. 172800 IN A  216.239.36.107
ns-cloud-b4.googledomains.com. 172800 IN AAAA   2001:4860:4802:38::6b
ns-cloud-b4.googledomains.com. 172800 IN A  216.239.38.107

;; Query time: 85 msec
;; SERVER: 192.5.6.30#53(192.5.6.30)
;; WHEN: Sat May 30 18:32:16 EDT 2020
;; MSG SIZE  rcvd: 349
</code>```

This is what the Google Domains looks like

Am I missing something here?

答:
Your host is fully registered at the registry, as whois attests:

```<code>$ whois -h whois.verisign-grs.com 'nameserver test.ns.violetnorthapp.com' | head -6
   Server Name: TEST.NS.VIOLETNORTHAPP.COM
   IP Address: 157.245.176.218
   Registrar: Google LLC
   Registrar WHOIS Server: whois.google.com
   Registrar URL: http://domains.google.com
>>> Last update of whois database: 2020-05-30T22:48:59Z <<<
</code>```

Or even better RDAP:

```<code>$ curl --silent https://rdap.verisign.com/com/v1/nameserver/test.ns.violetnorthapp.com | jq .
{
  "objectClassName": "nameserver",
  "ldhName": "TEST.NS.VIOLETNORTHAPP.COM",
  "ipAddresses": {
    "v4": [
      "157.245.176.218"
    ]
  },
  "links": [
    {
      "value": "https://rdap.verisign.com/com/v1/nameserver/TEST.NS.VIOLETNORTHAPP.COM",
      "rel": "self",
      "href": "https://rdap.verisign.com/com/v1/nameserver/TEST.NS.VIOLETNORTHAPP.COM",
      "type": "application/rdap+json"
    }
  ],
  "events": [
    {
      "eventAction": "last update of RDAP database",
      "eventDate": "2020-05-30T09:38:51Z"
    }
  ],
  "rdapConformance": [
    "rdap_level_0",
    "icann_rdap_technical_implementation_guide_0",
    "icann_rdap_response_profile_0"
  ],
  "notices": [
    {
      "title": "Terms of Use",
      "description": [
        "Service subject to Terms of Use."
      ],
      "links": [
        {
          "href": "https://www.verisign.com/domain-names/registration-data-access-protocol/terms-service/index.xhtml",
          "type": "text/html"
        }
      ]
    }
  ]
}
</code>```

However, glues serve a very specific record. It is not "free hosting" at the registry. You created an host object at the registry, but you did not associate it to any domain. As such there is no need to publish it in the DNS at the registry level.

As soon as you associate it to some domain under .com or .net, it should start to resolve shortly thereafter (and indeed you need to use dig with the @ flag to query the registry nameservers otherwise you are hitting your local recursive one, that can learn the IP address just by normal resolution and without any glue).

Body:
I am using Google domains for my domain: violetnorthapp.com, I have a few custom nameservers that I am running and I want to create registered hosts (which is the term used by google for glue records). I created a registered host under test.ns.violetnorthapp.com which should resolve to 8.8.8.8.

It's been more than 48 hours but it's still not resolving with dig test.ns.violetnorthapp.com.

; <<>> DiG 9.10.6 <<>> test.ns.violetnorthapp.com.
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 63639
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;test.ns.violetnorthapp.com.    IN  A

;; AUTHORITY SECTION:
violetnorthapp.com. 300 IN  SOA ns-cloud-b1.googledomains.com. cloud-dns-hostmaster.google.com. 6 21600 3600 259200 300

;; Query time: 68 msec
;; SERVER: 192.168.0.1#53(192.168.0.1)
;; WHEN: Sat May 30 18:31:02 EDT 2020
;; MSG SIZE  rcvd: 145

I tried running it with the TLD nameserver of com. One of them is a.gtld-servers.net., so the request is dig test.ns.violetnorthapp.com. @a.gtld-servers.net.:

; <<>> DiG 9.10.6 <<>> test.ns.violetnorthapp.com. @a.gtld-servers.net.
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 26571
;; flags: qr rd; QUERY: 1, ANSWER: 0, AUTHORITY: 4, ADDITIONAL: 9
;; WARNING: recursion requested but not available

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 4096
;; QUESTION SECTION:
;test.ns.violetnorthapp.com.    IN  A

;; AUTHORITY SECTION:
violetnorthapp.com. 172800  IN  NS  ns-cloud-b1.googledomains.com.
violetnorthapp.com. 172800  IN  NS  ns-cloud-b2.googledomains.com.
violetnorthapp.com. 172800  IN  NS  ns-cloud-b3.googledomains.com.
violetnorthapp.com. 172800  IN  NS  ns-cloud-b4.googledomains.com.

;; ADDITIONAL SECTION:
ns-cloud-b1.googledomains.com. 172800 IN AAAA   2001:4860:4802:32::6b
ns-cloud-b1.googledomains.com. 172800 IN A  216.239.32.107
ns-cloud-b2.googledomains.com. 172800 IN AAAA   2001:4860:4802:34::6b
ns-cloud-b2.googledomains.com. 172800 IN A  216.239.34.107
ns-cloud-b3.googledomains.com. 172800 IN AAAA   2001:4860:4802:36::6b
ns-cloud-b3.googledomains.com. 172800 IN A  216.239.36.107
ns-cloud-b4.googledomains.com. 172800 IN AAAA   2001:4860:4802:38::6b
ns-cloud-b4.googledomains.com. 172800 IN A  216.239.38.107

;; Query time: 85 msec
;; SERVER: 192.5.6.30#53(192.5.6.30)
;; WHEN: Sat May 30 18:32:16 EDT 2020
;; MSG SIZE  rcvd: 349

This is what the Google Domains looks like

Am I missing something here?

Body:
Your host is fully registered at the registry, as whois attests:

$ whois -h whois.verisign-grs.com 'nameserver test.ns.violetnorthapp.com' | head -6
   Server Name: TEST.NS.VIOLETNORTHAPP.COM
   IP Address: 157.245.176.218
   Registrar: Google LLC
   Registrar WHOIS Server: whois.google.com
   Registrar URL: http://domains.google.com
>>> Last update of whois database: 2020-05-30T22:48:59Z <<<

Or even better RDAP:

$ curl --silent https://rdap.verisign.com/com/v1/nameserver/test.ns.violetnorthapp.com | jq .
{
  "objectClassName": "nameserver",
  "ldhName": "TEST.NS.VIOLETNORTHAPP.COM",
  "ipAddresses": {
    "v4": [
      "157.245.176.218"
    ]
  },
  "links": [
    {
      "value": "https://rdap.verisign.com/com/v1/nameserver/TEST.NS.VIOLETNORTHAPP.COM",
      "rel": "self",
      "href": "https://rdap.verisign.com/com/v1/nameserver/TEST.NS.VIOLETNORTHAPP.COM",
      "type": "application/rdap+json"
    }
  ],
  "events": [
    {
      "eventAction": "last update of RDAP database",
      "eventDate": "2020-05-30T09:38:51Z"
    }
  ],
  "rdapConformance": [
    "rdap_level_0",
    "icann_rdap_technical_implementation_guide_0",
    "icann_rdap_response_profile_0"
  ],
  "notices": [
    {
      "title": "Terms of Use",
      "description": [
        "Service subject to Terms of Use."
      ],
      "links": [
        {
          "href": "https://www.verisign.com/domain-names/registration-data-access-protocol/terms-service/index.xhtml",
          "type": "text/html"
        }
      ]
    }
  ]
}

However, glues serve a very specific record. It is not "free hosting" at the registry. You created an host object at the registry, but you did not associate it to any domain. As such there is no need to publish it in the DNS at the registry level.

As soon as you associate it to some domain under .com or .net, it should start to resolve shortly thereafter (and indeed you need to use dig with the @ flag to query the registry nameservers otherwise you are hitting your local recursive one, that can learn the IP address just by normal resolution and without any glue).


问:
How to catch Exception like in a FrontController in Spring
Basically every repository method can possibly throw a DataAccessException . A lot of exceptions inherit from DataAccessException. So maybe I will catch DuplicateKeyException or maybe DataIntegrityViolationException . But all the other say 40 - 50 exceptions I will not catch explicitly. Instead I will just catch DataAccessException . So why always catch DataAccessException  ?? Instead I would prefer catching it just once. But how to do that in Spring. There is no Front Controller. There are just Controllers. So how should I catch it in a central place. The only place I know whould be start of Spring. But I don't think that works.</p>

```<code>@SpringBootApplication
@EnableJpaRepositories
public class Application {

    public static void main(String[] args) {
        try{
        SpringApplication.run(Application.class, args);
        }
        catch(DataAccessException e)
        {
              //Do your error handling here
        }
    }

}
</code>```

答:
Simplified process:

The run method call starts an embadded web server (and the whole spring infrastructure). So actually for example if you try to print out something after run call, it would not appear on the console.
The webserver runs and dispatch your requests in different threads. So the exception will happen on that threads. Spring use lot of exception handlers etc in the background.
So it more complicated in the reality. But you may see that this is not a simple, single threaded application.

The previous answer shows how to handle the exceptions in central place. For simple mvc application, I suggest to use  @ControllerAdvice

Body:
Basically every repository method can possibly throw a DataAccessException . A lot of exceptions inherit from DataAccessException. So maybe I will catch DuplicateKeyException or maybe DataIntegrityViolationException . But all the other say 40 - 50 exceptions I will not catch explicitly. Instead I will just catch DataAccessException . So why always catch DataAccessException  ?? Instead I would prefer catching it just once. But how to do that in Spring. There is no Front Controller. There are just Controllers. So how should I catch it in a central place. The only place I know whould be start of Spring. But I don't think that works.

@SpringBootApplication
@EnableJpaRepositories
public class Application {

    public static void main(String[] args) {
        try{
        SpringApplication.run(Application.class, args);
        }
        catch(DataAccessException e)
        {
              //Do your error handling here
        }
    }

}


问:
Is there a good way to add FutureLocal.java to custom Future.java extending CompletableFuture? (example code below)
I have the following code which was kind of close except when I call super.thenCompose and it returns a CompletableFuture instead of my Custom Future.java which is kind of critical.  I am trying to copy twitter's scala futures that

Be able to add cancellation chaining like twitter scala's futures

can have a request context flow through the thenApply and thenCompose chains to fix MDC in slf4j (much like a ThreadLocal but it is re-applied just before each lambda is run as seen in the code below)

public class Future extends CompletableFuture {

```<code>@Override
public <U> CompletableFuture<U> thenApply(Function<? super T, ? extends U> fn) {
    Map<String, Object> state = FutureLocal.fetchState();
    MyFunction f = new MyFunction(state, fn);

    return super.thenApply(f);
}

@Override
public <U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn) {
    Map<String, Object> state = FutureLocal.fetchState();
    MyFunction f = new MyFunction(state, fn);

    return super.thenCompose(f);
}

@SuppressWarnings("hiding")
private class MyFunction implements Function {

    private Map<String, Object> state;
    private Function fn;

    public MyFunction(Map<String, Object> state, @SuppressWarnings("rawtypes") Function fn) {
        this.state = state;
        this.fn = fn;

    }

    @Override
    public Object apply(Object t) {

        try {
            FutureLocal.restoreState(state);

            return fn.apply(t);

        } finally {
            FutureLocal.restoreState(null);
        }

    }

}

@Override
public boolean complete(T value) {
    return super.complete(value);
}

@Override
public boolean completeExceptionally(Throwable ex) {
    return super.completeExceptionally(ex);
}
</code>```

}

Here is some code I use to run that code but logging the "test" in the map starts failing on the 3rd remote call meaning slf4j MDC will break down.

```<code>public class TestCustomFutures {

    private Executor exec = Executors.newFixedThreadPool(3);

    @Test
    public void testFutureContext() throws InterruptedException, ExecutionException {

        Set<Integer> hashSet = new HashSet<Integer>();

        FutureLocal.put("test", 100);

        CompletableFuture<Integer> f = myRemoteCall(4)
            .thenCompose(s -> myRemoteCall(3))
            .thenCompose(s -> myRemoteCall(2));

        f.get();
    }

    private Future<Integer> myRemoteCall(int i) {
        System.out.println("result="+i+" map="+FutureLocal.get("test")+" thread="+Thread.currentThread().getName());

        Future<Integer> f = new Future<Integer>();

        exec.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    f.completeExceptionally(e);
                }

                f.complete(i);
            }
        });

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

The output then is this

```<code>result=4 map=100 thread=main
result=3 map=100 thread=pool-1-thread-1
result=2 map=null thread=pool-1-thread-2
</code>```

notice that last value we do not want to be null

答:
ahhh, I was missing one simple thing BECAUSE I was in jdk8.  In jdk11 however, you can override this...

```<code>@Override
public <U> CompletableFuture<U> newIncompleteFuture() {
    return new Future<U>();
}
</code>```

In jdk8, for some reason, this would not compile and it would not invoke this :(.  Crap, I didn't want to upgrade to 11 yet as some usages are stilll on jdk8 :(.

Body:
I have the following code which was kind of close except when I call super.thenCompose and it returns a CompletableFuture instead of my Custom Future.java which is kind of critical.  I am trying to copy twitter's scala futures that

Be able to add cancellation chaining like twitter scala's futures

can have a request context flow through the thenApply and thenCompose chains to fix MDC in slf4j (much like a ThreadLocal but it is re-applied just before each lambda is run as seen in the code below)

public class Future extends CompletableFuture {

@Override
public  CompletableFuture thenApply(Function<? super T, ? extends U> fn) {
    Map<String, Object> state = FutureLocal.fetchState();
    MyFunction f = new MyFunction(state, fn);

    return super.thenApply(f);
}

@Override
public  CompletableFuture thenCompose(Function<? super T, ? extends CompletionStage> fn) {
    Map<String, Object> state = FutureLocal.fetchState();
    MyFunction f = new MyFunction(state, fn);

    return super.thenCompose(f);
}

@SuppressWarnings("hiding")
private class MyFunction implements Function {

    private Map<String, Object> state;
    private Function fn;

    public MyFunction(Map<String, Object> state, @SuppressWarnings("rawtypes") Function fn) {
        this.state = state;
        this.fn = fn;

    }

    @Override
    public Object apply(Object t) {

        try {
            FutureLocal.restoreState(state);

            return fn.apply(t);

        } finally {
            FutureLocal.restoreState(null);
        }

    }

}

@Override
public boolean complete(T value) {
    return super.complete(value);
}

@Override
public boolean completeExceptionally(Throwable ex) {
    return super.completeExceptionally(ex);
}

}

Here is some code I use to run that code but logging the "test" in the map starts failing on the 3rd remote call meaning slf4j MDC will break down.

public class TestCustomFutures {

    private Executor exec = Executors.newFixedThreadPool(3);

    @Test
    public void testFutureContext() throws InterruptedException, ExecutionException {

        Set<Integer> hashSet = new HashSet<Integer>();

        FutureLocal.put("test", 100);

        CompletableFuture<Integer> f = myRemoteCall(4)
            .thenCompose(s -> myRemoteCall(3))
            .thenCompose(s -> myRemoteCall(2));

        f.get();
    }

    private Future<Integer> myRemoteCall(int i) {
        System.out.println("result="+i+" map="+FutureLocal.get("test")+" thread="+Thread.currentThread().getName());

        Future<Integer> f = new Future<Integer>();

        exec.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    f.completeExceptionally(e);
                }

                f.complete(i);
            }
        });

        return f;
    }
}

The output then is this

result=4 map=100 thread=main
result=3 map=100 thread=pool-1-thread-1
result=2 map=null thread=pool-1-thread-2

notice that last value we do not want to be null

Body:
ahhh, I was missing one simple thing BECAUSE I was in jdk8.  In jdk11 however, you can override this...

@Override
public <U> CompletableFuture<U> newIncompleteFuture() {
    return new Future<U>();
}

In jdk8, for some reason, this would not compile and it would not invoke this :(.  Crap, I didn't want to upgrade to 11 yet as some usages are stilll on jdk8 :(.


问:
Other host and my client side function properly but my server side fails at onClick Javascript youtube player
Using the pure html source code from the website below for a responsive youtube player on server side, it runs identical to the hyperlink's host. When I upload this into file into my google cloud server, the onclick function fails to change the ID attribute. The scrolling and other java works fine. Competently identical code.

```<code>http://woosterwebdesign.com/experiments/youtube-player.html
</code>```

1st fail:  link a script.js and structure the code differently

2rd fail:  Change the javascript formatting.

```<code>https://stackoverflow.com/questions/27140952/how-to-change-video-source-onclick

https://stackoverflow.com/questions/23693118/how-to-change-multiple-attributes-of-a-link-using-onclick-of-radio-button

https://stackoverflow.com/questions/41354535/how-to-update-youtube-video-id-when-clicking-different-play-buttons
</code>```

3th fail: After reading many variations on stack and such, I found this demo below and uploaded the identical code and now see the same problem persist.

```<code>https://jsfiddle.net/u3bntba6/
</code>```

At this point i'm certain it's somehow the google cloud. After apache2 trials and tribulation, I figured I didn't have something properly installed on Google Cloud Platform VM.

4th fail:  test and confirm that JQuery is installed and not the fault

Now I'm days deep in reading and I'm not sure what I'm looking for. I enjoy reading but can't find what I don't know. Any advice on how to get my server hosting a working youtube playlist would be highly appreciated.

答:
After cycling my code into the server,
copying the code from the browser and re-pasting into my notepad,
saving,
and uploading again into the server.

I have noticed certain code is displayed with additional text that once ran again would cause functioning error. This can be easily mimiced by copying the element of an embedded youtube player and noticing additional code after the ? (meaning the break)

Same thing happened with my paypal button code. It must be an intentional layer of security. Except this time the code was rewritten in a way that could not be fixed without source. This is more likely js side I believe.

It is very likely if you're experiencing this in the future, you have broken code hiding in your html and javascript.

Body:
Using the pure html source code from the website below for a responsive youtube player on server side, it runs identical to the hyperlink's host. When I upload this into file into my google cloud server, the onclick function fails to change the ID attribute. The scrolling and other java works fine. Competently identical code.

http://woosterwebdesign.com/experiments/youtube-player.html

1st fail:  link a script.js and structure the code differently

2rd fail:  Change the javascript formatting.

https://stackoverflow.com/questions/27140952/how-to-change-video-source-onclick

https://stackoverflow.com/questions/23693118/how-to-change-multiple-attributes-of-a-link-using-onclick-of-radio-button

https://stackoverflow.com/questions/41354535/how-to-update-youtube-video-id-when-clicking-different-play-buttons

3th fail: After reading many variations on stack and such, I found this demo below and uploaded the identical code and now see the same problem persist.

https://jsfiddle.net/u3bntba6/

At this point i'm certain it's somehow the google cloud. After apache2 trials and tribulation, I figured I didn't have something properly installed on Google Cloud Platform VM.

4th fail:  test and confirm that JQuery is installed and not the fault

Now I'm days deep in reading and I'm not sure what I'm looking for. I enjoy reading but can't find what I don't know. Any advice on how to get my server hosting a working youtube playlist would be highly appreciated.


问:
How to rollback all recent transactions in Rails
I'm writing my first Ruby on Rails application, and I'm having trouble managing record associations overall. In this question, specifically, I'd like to ask the community for suggestions on how to rollback recent saves to the database, based on the code below.

```<code>def create
    @aula = Aula.create!(:name => aula_params[:name], :block_duration => aula_params[:block_duration], :rest_time => aula_params[:rest_time], :user_id => @current_user.id)

    if @aula.valid?
      JSON.parse(aula_params[:blocks]).each do |id, b|
        @block = @aula.blocks.create!(:name => b["name"], :sequence_number => id)

        if @block.valid?
          b["workouts"].each do |id, w|
            @block.block_workouts.create!(:workout_id => w["id"], :duration => w["duration"], :sequence_number => id, :repetitions_number => w["repetitions_number"])
          end
        else
          render :json => { message: "Não foi possível criar essa aula", status: 500 }
        end
      end

      render :json => { message: "Aula criada com sucesso", status: 200 }
    else
      render :json => { message: "Não foi possível criar essa aula", status: 500 }
    end
  end
</code>```

This piece of code basically creates an "aula", that consists of multiple "blocks", that in turn are composed by multiple "workouts".

But, the problem is: suppose that the creation of a specific workout fails. In this case, the "aula" that was just created (and so the blocks and its related workouts) should be deleted. But I can't find a way of doing this in a concise, elegant manner.

答:
First thing, as you are creating objects of multiple classes in that block so I would suggest using ActiveRecord::Base.transaction over Aula.transaction to not be specific to that single class.

In the following code snippet, use only one aula = @current_user... line on the basis of your associations.

```<code>def create
  ActiveRecord::Base.transaction do
    # Use only any one of below lines
    aula = @current_user.aulas.create!(aula_params) # if user has_many aulas
    aula = @current_user.create_aula!(aula_params) # if user has_one Paula

    JSON.parse(params[:aula][:blocks]).each do |id, b|
      block = aula.blocks.create!(name: b['name'], sequence_number: id)

      block.save!
      b['workouts'].each do |s_id, w|
        block.block_workouts.create!(workout_id: w['id'],
                                     duration: w['duration'],
                                     sequence_number: s_id,
                                     repetitions_number: w['repetitions_number'])
      end
    end

    render json: { message: 'Aula criada com sucesso', status: 200 }
  end
rescue ActiveRecord::RecordInvalid
  render json: { message: 'Não foi possível criar essa aula', status: 500 }
end

def aula_params
  params.require(:aula).permit(:name, :block_duration, :rest_time)
end
</code>```

I think this should do the trick.

Body:
I'm writing my first Ruby on Rails application, and I'm having trouble managing record associations overall. In this question, specifically, I'd like to ask the community for suggestions on how to rollback recent saves to the database, based on the code below.

def create
    @aula = Aula.create!(:name => aula_params[:name], :block_duration => aula_params[:block_duration], :rest_time => aula_params[:rest_time], :user_id => @current_user.id)

    if @aula.valid?
      JSON.parse(aula_params[:blocks]).each do |id, b|
        @block = @aula.blocks.create!(:name => b["name"], :sequence_number => id)

        if @block.valid?
          b["workouts"].each do |id, w|
            @block.block_workouts.create!(:workout_id => w["id"], :duration => w["duration"], :sequence_number => id, :repetitions_number => w["repetitions_number"])
          end
        else
          render :json => { message: "Não foi possível criar essa aula", status: 500 }
        end
      end

      render :json => { message: "Aula criada com sucesso", status: 200 }
    else
      render :json => { message: "Não foi possível criar essa aula", status: 500 }
    end
  end

This piece of code basically creates an "aula", that consists of multiple "blocks", that in turn are composed by multiple "workouts".

But, the problem is: suppose that the creation of a specific workout fails. In this case, the "aula" that was just created (and so the blocks and its related workouts) should be deleted. But I can't find a way of doing this in a concise, elegant manner.

Body:
First thing, as you are creating objects of multiple classes in that block so I would suggest using ActiveRecord::Base.transaction over Aula.transaction to not be specific to that single class.

In the following code snippet, use only one aula = @current_user... line on the basis of your associations.

def create
  ActiveRecord::Base.transaction do
    # Use only any one of below lines
    aula = @current_user.aulas.create!(aula_params) # if user has_many aulas
    aula = @current_user.create_aula!(aula_params) # if user has_one Paula

    JSON.parse(params[:aula][:blocks]).each do |id, b|
      block = aula.blocks.create!(name: b['name'], sequence_number: id)

      block.save!
      b['workouts'].each do |s_id, w|
        block.block_workouts.create!(workout_id: w['id'],
                                     duration: w['duration'],
                                     sequence_number: s_id,
                                     repetitions_number: w['repetitions_number'])
      end
    end

    render json: { message: 'Aula criada com sucesso', status: 200 }
  end
rescue ActiveRecord::RecordInvalid
  render json: { message: 'Não foi possível criar essa aula', status: 500 }
end

def aula_params
  params.require(:aula).permit(:name, :block_duration, :rest_time)
end

I think this should do the trick.


问:
Python3 add multiple headers in a request
I want to send a request using these custom 2 Headers:

```<code>Host: website.com
Origin: anotherwebsite.com
</code>```

Here is my python3 code:

```<code>headers = [("Host" , "https://website.com",
           ("Origin" , "https://evil.com")]
request = requests.get(site, headers=headers)
</code>```

When executed it shows this error:
'list' object has no attribute 'items' and it refers to this line request = requests.get(site, headers=headers)

Any help is highly appreciated, thank you in advanced.

答:
I usually use a dictionary:

headers = {
    "Host": "https://website.com",
    "Origin": "https://evil.com",
}

request = requests.get(site, headers=headers)
```

Body:
I want to send a request using these custom 2 Headers:

Host: website.com
Origin: anotherwebsite.com

Here is my python3 code:

headers = [("Host" , "https://website.com",
           ("Origin" , "https://evil.com")]
request = requests.get(site, headers=headers)

When executed it shows this error:
'list' object has no attribute 'items' and it refers to this line request = requests.get(site, headers=headers)

Any help is highly appreciated, thank you in advanced.


问:
Function accessing cell range
I don't find how to use cell ranges with functions.

I vainly searched some examples.

I wrote the following test. I get "Object variable not set" error on both "for" lines (one is without "RangeAddress", and the second is with it, because I'm not sure of the correct syntax):

function CHECKBZRANGE(cellRange) as integer
    dim nCol as integer
    dim nLine as integer
    dim i as integer

    for nCol = cellRange.StartColumn to cellRange.EndColumn
        for nLine = cellRange.RangeAddress.StartRow to cellRange.RangeAddress.EndRow
            i = i + 1      ' placeholder for some computation
        next nLine
    next nCol
    checkBZ_range = i
end function
```

This function is called with a cell like =CHECKBZRANGE(A6:C9)

Can someone explain how to use a cell range passed by argument ?

答:
Yes. It is possible! Just activating compatibility to VBA.</p>

```<code>Option VBASupport 1

Option Compatible

Function Addressing(R As Range)

Addressing = R.Address

End Function
</code>```

Title: Function accessing cell range

Body:
I don't find how to use cell ranges with functions.

I vainly searched some examples.

I wrote the following test. I get "Object variable not set" error on both "for" lines (one is without "RangeAddress", and the second is with it, because I'm not sure of the correct syntax):

function CHECKBZRANGE(cellRange) as integer
    dim nCol as integer
    dim nLine as integer
    dim i as integer

    for nCol = cellRange.StartColumn to cellRange.EndColumn
        for nLine = cellRange.RangeAddress.StartRow to cellRange.RangeAddress.EndRow
            i = i + 1      ' placeholder for some computation
        next nLine
    next nCol
    checkBZ_range = i
end function

This function is called with a cell like =CHECKBZRANGE(A6:C9)

Can someone explain how to use a cell range passed by argument ?

Body:
Yes. It is possible! Just activating compatibility to VBA.

Option VBASupport 1

Option Compatible

Function Addressing(R As Range)

Addressing = R.Address

End Function