问:
Code won't run once adding transactions
Hello I have code that without transactions executes but with transactions doesn't run. My DB Class encapsulates prepared statements from which it is composed in my BaseApp Class and this is in turn is  extended by BaseTransactApp Class.

BasetransactApp Class  is extended by the EqRqst Class. EqRqst Class is extended by the EqLeaseRequest Class which is used to call the code in the trait with the problematic code.
At one point it showed the error 2SQLSTATE[HY000]: General error
when I did not set

```<code>$this->_pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES , false);
</code>```

My DB Class is

```<code> <?php
        class DB{
   `enter code here` private static $_instance = null;
    private $_pdo,
            $_query,
            $_error = false,
            $_results,
            $x,
            $_count = 0;

      private function __construct(){
        try{
               $this->_pdo = new PDO('mysql:host=' .Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'),       Config::get('mysql/password'));
            $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->_pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES , false);
        }catch(PDOException $e){
            die($e->getMessage());
        }

        }
        public static function getInstance(){
            if(!isset(self::$_instance)){
                self::$_instance = new DB();
            }
            return self::$_instance;
        }
        public function query($sql, $params = array()){
            $this->_error = false;
            if($this->_query = $this->_pdo->prepare($sql)){
                $x = 1;
               if(count($params)){
                foreach($params as $param){
                    $this->_query->bindValue($x,$param);
                    $x++;
                }
               }
               if($this->_query->execute()){
              $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
              $this->_count = $this->_query->rowCount();

               }else{
                $this->_error = true;
               }
            }
     return $this;

        }
        public function action($action,$table,$where = array()){
            if(count($where) === 3){
  $operators = array('=','>','<','>=','<=');

         $field = $where[0];
         $operator = $where[1];
         $value = $where[2];

         if(in_array($operator , $operators)){
            $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ? ";
            if(!$this->query($sql, array($value))->error()){
                return $this;
            }

         }

            }
            return false;
        }
        public function update($table,$id,$fields){
            $set = '';
            $x = 1;
            foreach($fields as $name => $value){
                $set .= "{$name} = ?";
                if($x < count($fields)){
                    $set .= ', ';
                }
                $x++;
            }

            $sql = "UPDATE {$table} SET {$set} WHERE {$name} = '{$id}'";
            echo $sql;
            if(!$this->query($sql,$fields)->error()){
                echo "true";

                return true;

            }
           return false;
        }

        public function get($table,$where){
        return $this->action('SELECT *',$table,$where);
        }
        public function delete($table,$where){
            return $this->action('DELETE',$table,$where);
        }
        public function insert($table,$fields = array()){
            if(count($fields)){
                echo 'this is the count  '.count($fields);
                $x=1;
               if(!is_multi_array($fields)){
                echo 'Not a multi array'.'<br>';
                $keys = array_keys($fields);
                print_r($keys);
                $values = '';

                }
                foreach($fields as $field => $fieldValue){
                    if(!is_array($fieldValue)){

                        echo $x;
                         $values .="?";
                   if($x< count($fields)){
                    $values .= ', ';
                   }
                   if($x == count($fields)){
                    echo 'insert query is Executed'.'<br>';
                    echo $x;
                     $sql ="INSERT INTO {$table} (`".implode('`,`',$keys). "`) VALUES ({$values})";
                       if(!$this->query($sql,$fields)->error()){
                echo "true";
                return true;
              }

                   }
                   $x++;
                    }else{
                        if($x <= count($fields)){
                         echo 'recursive insert called'.'<br>';
                         echo "number of recursive cycles is    ".$x;
                          $this->insert($table,$fieldValue);
                          if($x == count($fields)){
                            echo "Escaped";
                            exit();
                          }
                          $x++;
                        }

                     }
                   }

            }

           echo 'No no';
         return false;
        }

            public function getLastId(){
               return $this->_pdo->lastInsertId();
            }
            public function beginTransaction(){
                return $this->_pdo->beginTransaction();
            }
            public function commit(){
                 return $this->_pdo->commit();

            }
            public function rollBack(){
                 return $this->_pdo->rollBack();
            }
}

?>
</code>```

IT is composed in BaseApp Class

```<code>    protected $db,
              $data,
              $table;

    public function __construct(){
        $this->db = DB::getInstance();
    }
        public function getProp($prop){

                return $this->$_prop;

        }
         public function setProp($objVar,$val){
            $this->objVar = $val;

        }

        public function create($fields = array()){
if(!$this->db->insert($this->table, $fields) ){
    throw new Exception('There was a problem creating an account.');

}

        }

        public function get($where = array()){
            $dbResult = $this->db->get($this->table, $where);
            if($dbResult->count()){
                $this->data = $dbResult->first();

                return true;
            }
            return false;
        }

        public function update($fields = array(),$id = null){
        if(!$this->db->update($this->table,$id,$fields)){
            throw new Exception('There was a problem Updating');
        }
        }

    public function delete($where = array()){
        $this->db->delete($this->table,$where);
                }
                public function data(){
                    return $this->data;
                }
    public function getTable(){
        return $this->table;
    }
    public function getLastInsertId(){
        return $this->db->getLastId();
    }
}

?>
</code>```

which is extended by

```<code>   public function __construct(){

    parent::__construct();
     if($this->db){
        echo 'WWWWWWWWWWWWWWWW';
     }

   }

    public function beginTransaction(){
        return $this->db->beginTransaction();
    }
    public function commit(){
        return $this->db->commit();
    }
    public function rollBack(){
        return $this->db->rollBack();
    }
}

?>
</code>```

Then

```<code>    protected $EqRqst_ID,
              $DateOfRequest,
              $rqstState,
              $RequestedPackage = array(),
              $state_ID,
              $table = 'EqRqst';

    public function __construct(RqstState $state){
        parent::__construct();

        $this->rqstState = $state;

    }
   public function create($args = array()){
     BaseTransactApp::create($args);
   // $this->EqRqst_ID = $this->getLastInsertId();
   // echo $this->EqRqst_ID;
   }
    public function getRqstID(){
     return $this->EqRqst_ID;
    }
    public abstract function makeRequest($requestArg = array(),$elRqst = array(),$rqstPakg = array());

}

?>
</code>```

This trait contains the code that is Use by eqleaserequest .This code executes well without transactions but fails to do so with them

```<code>    public function makeRequest($requestArg = array(),$eqLsRqst = array(),$rqstPakg = array()){

        try{

        $this->beginTransaction();
        parent::create($requestArg);
        $this->EqRqst_ID = parent::getLastInsertId();
        $this->create($eqLsRqst);
        $this->_RequestPkg->create(multi_array_merge(array('EqRqst_ID'=> $this->EqRqst_ID),$rqstPakg));
     $this->commit();
            }catch(Exception $e){
                $this->rollBack();
                echo $e->getMessage().;
            }
        //$this->EqRqst_ID = $this->getRqstID();
    }
</code>```

This code is the problem it runs when I comment out the Transaction code but doesn't with it. IT Executed by

This class is the one that uses the TraitRequest

```<code>    use traitRequest;

   //protected  $table = 'EqLeaseRequest';

    private $_Emp,
            $_Emp_ID,
            $_RequestPkg,
            $_Intended_Use,
            $_EqRqst,
            $_EqRqst_ID,
            $_Expected_Returndate;

     public $rqstID;

    public function __construct(RqstState $state,Employee $Emp,RequestPackage $RqstPkg){

        parent::__construct($state);
        $this->_Emp = $Emp;
        $this->_RequestPkg = $RqstPkg;

    }
   public function create($eqLsRqstArg = array()){
       $this->table = 'EqLeaseRequest';
       print_r(array_merge(array('EqRqst_ID'=> $this->EqRqst_ID),$eqLsRqstArg));
       BaseTransactApp::create(array_merge(array('EqRqst_ID'=>$this->EqRqst_ID),$eqLsRqstArg));
       //BaseTransactApp::create($eqLsRqstArg);

   }

    }

}

?>
</code>```

答:
I was able to find the solution by changing the code in the Trait traitRequest.

The solution is as follows

trait traitRequest{
    public function makeRequest($requestArg = array(),$eqLsRqst = array(),$rqstPakg = array()){

```<code>    $this->beginTransaction();
    parent::create($requestArg);
     if(parent::count()){
         $this->EqRqst_ID = parent::getLastInsertId();
         $this->create($eqLsRqst);
         if($this->count()){
              foreach($rqstPakg as $pkg){
                  $this->_RequestPkg->create(array_merge(array('EqRqst_ID'=> $this->EqRqst_ID),$pkg));
                    if(!$this->_RequestPkg->count()){
                 $this->rollBack();
            }

              }
              $this->commit();

         }else{
             echo 'Second Rollback';
          $this->rollBack();
         }
     }else{

        echo 'First Rollback';
          $this->rollBack();
     }
}
</code>```

}

?>

Title: Code won't run once adding transactions

Body:
Hello I have code that without transactions executes but with transactions doesn't run. My DB Class encapsulates prepared statements from which it is composed in my BaseApp Class and this is in turn is  extended by BaseTransactApp Class.

BasetransactApp Class  is extended by the EqRqst Class. EqRqst Class is extended by the EqLeaseRequest Class which is used to call the code in the trait with the problematic code.
At one point it showed the error 2SQLSTATE[HY000]: General error
when I did not set

$this->_pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES , false);

My DB Class is

 <?php
        class DB{
   `enter code here` private static $_instance = null;
    private $_pdo,
            $_query,
            $_error = false,
            $_results,
            $x,
            $_count = 0;

      private function __construct(){
        try{
               $this->_pdo = new PDO('mysql:host=' .Config::get('mysql/host') . ';dbname=' . Config::get('mysql/db'), Config::get('mysql/username'),       Config::get('mysql/password'));
            $this->_pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->_pdo->setAttribute( PDO::ATTR_EMULATE_PREPARES , false);
        }catch(PDOException $e){
            die($e->getMessage());
        }

        }
        public static function getInstance(){
            if(!isset(self::$_instance)){
                self::$_instance = new DB();
            }
            return self::$_instance;
        }
        public function query($sql, $params = array()){
            $this->_error = false;
            if($this->_query = $this->_pdo->prepare($sql)){
                $x = 1;
               if(count($params)){
                foreach($params as $param){
                    $this->_query->bindValue($x,$param);
                    $x++;
                }
               }
               if($this->_query->execute()){
              $this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
              $this->_count = $this->_query->rowCount();

               }else{
                $this->_error = true;
               }
            }
     return $this;

        }
        public function action($action,$table,$where = array()){
            if(count($where) === 3){
  $operators = array('=','>','<','>=','<=');

         $field = $where[0];
         $operator = $where[1];
         $value = $where[2];

         if(in_array($operator , $operators)){
            $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ? ";
            if(!$this->query($sql, array($value))->error()){
                return $this;
            }

         }

            }
            return false;
        }
        public function update($table,$id,$fields){
            $set = '';
            $x = 1;
            foreach($fields as $name => $value){
                $set .= "{$name} = ?";
                if($x < count($fields)){
                    $set .= ', ';
                }
                $x++;
            }

            $sql = "UPDATE {$table} SET {$set} WHERE {$name} = '{$id}'";
            echo $sql;
            if(!$this->query($sql,$fields)->error()){
                echo "true";

                return true;

            }
           return false;
        }

        public function get($table,$where){
        return $this->action('SELECT *',$table,$where);
        }
        public function delete($table,$where){
            return $this->action('DELETE',$table,$where);
        }
        public function insert($table,$fields = array()){
            if(count($fields)){
                echo 'this is the count  '.count($fields);
                $x=1;
               if(!is_multi_array($fields)){
                echo 'Not a multi array'.'
';
                $keys = array_keys($fields);
                print_r($keys);
                $values = '';

                }
                foreach($fields as $field => $fieldValue){
                    if(!is_array($fieldValue)){

                        echo $x;
                         $values .="?";
                   if($x< count($fields)){
                    $values .= ', ';
                   }
                   if($x == count($fields)){
                    echo 'insert query is Executed'.'
';
                    echo $x;
                     $sql ="INSERT INTO {$table} (`".implode('`,`',$keys). "`) VALUES ({$values})";
                       if(!$this->query($sql,$fields)->error()){
                echo "true";
                return true;
              }

                   }
                   $x++;
                    }else{
                        if($x <= count($fields)){
                         echo 'recursive insert called'.'
';
                         echo "number of recursive cycles is    ".$x;
                          $this->insert($table,$fieldValue);
                          if($x == count($fields)){
                            echo "Escaped";
                            exit();
                          }
                          $x++;
                        }

                     }
                   }

            }

           echo 'No no';
         return false;
        }

            public function getLastId(){
               return $this->_pdo->lastInsertId();
            }
            public function beginTransaction(){
                return $this->_pdo->beginTransaction();
            }
            public function commit(){
                 return $this->_pdo->commit();

            }
            public function rollBack(){
                 return $this->_pdo->rollBack();
            }
}

?>

IT is composed in BaseApp Class

    protected $db,
              $data,
              $table;

    public function __construct(){
        $this->db = DB::getInstance();
    }
        public function getProp($prop){

                return $this->$_prop;

        }
         public function setProp($objVar,$val){
            $this->objVar = $val;

        }

        public function create($fields = array()){
if(!$this->db->insert($this->table, $fields) ){
    throw new Exception('There was a problem creating an account.');

}

        }

        public function get($where = array()){
            $dbResult = $this->db->get($this->table, $where);
            if($dbResult->count()){
                $this->data = $dbResult->first();

                return true;
            }
            return false;
        }

        public function update($fields = array(),$id = null){
        if(!$this->db->update($this->table,$id,$fields)){
            throw new Exception('There was a problem Updating');
        }
        }

    public function delete($where = array()){
        $this->db->delete($this->table,$where);
                }
                public function data(){
                    return $this->data;
                }
    public function getTable(){
        return $this->table;
    }
    public function getLastInsertId(){
        return $this->db->getLastId();
    }
}

?>

which is extended by

   public function __construct(){

    parent::__construct();
     if($this->db){
        echo 'WWWWWWWWWWWWWWWW';
     }

   }

    public function beginTransaction(){
        return $this->db->beginTransaction();
    }
    public function commit(){
        return $this->db->commit();
    }
    public function rollBack(){
        return $this->db->rollBack();
    }
}

?>

Then

    protected $EqRqst_ID,
              $DateOfRequest,
              $rqstState,
              $RequestedPackage = array(),
              $state_ID,
              $table = 'EqRqst';

    public function __construct(RqstState $state){
        parent::__construct();

        $this->rqstState = $state;

    }
   public function create($args = array()){
     BaseTransactApp::create($args);
   // $this->EqRqst_ID = $this->getLastInsertId();
   // echo $this->EqRqst_ID;
   }
    public function getRqstID(){
     return $this->EqRqst_ID;
    }
    public abstract function makeRequest($requestArg = array(),$elRqst = array(),$rqstPakg = array());

}

?>

This trait contains the code that is Use by eqleaserequest .This code executes well without transactions but fails to do so with them

    public function makeRequest($requestArg = array(),$eqLsRqst = array(),$rqstPakg = array()){

        try{

        $this->beginTransaction();
        parent::create($requestArg);
        $this->EqRqst_ID = parent::getLastInsertId();
        $this->create($eqLsRqst);
        $this->_RequestPkg->create(multi_array_merge(array('EqRqst_ID'=> $this->EqRqst_ID),$rqstPakg));
     $this->commit();
            }catch(Exception $e){
                $this->rollBack();
                echo $e->getMessage().;
            }
        //$this->EqRqst_ID = $this->getRqstID();
    }

This code is the problem it runs when I comment out the Transaction code but doesn't with it. IT Executed by

This class is the one that uses the TraitRequest

    use traitRequest;

   //protected  $table = 'EqLeaseRequest';

    private $_Emp,
            $_Emp_ID,
            $_RequestPkg,
            $_Intended_Use,
            $_EqRqst,
            $_EqRqst_ID,
            $_Expected_Returndate;

     public $rqstID;

    public function __construct(RqstState $state,Employee $Emp,RequestPackage $RqstPkg){

        parent::__construct($state);
        $this->_Emp = $Emp;
        $this->_RequestPkg = $RqstPkg;

    }
   public function create($eqLsRqstArg = array()){
       $this->table = 'EqLeaseRequest';
       print_r(array_merge(array('EqRqst_ID'=> $this->EqRqst_ID),$eqLsRqstArg));
       BaseTransactApp::create(array_merge(array('EqRqst_ID'=>$this->EqRqst_ID),$eqLsRqstArg));
       //BaseTransactApp::create($eqLsRqstArg);

   }

    }

}

?>

Body:
I was able to find the solution by changing the code in the Trait traitRequest.

The solution is as follows

trait traitRequest{
    public function makeRequest($requestArg = array(),$eqLsRqst = array(),$rqstPakg = array()){

    $this->beginTransaction();
    parent::create($requestArg);
     if(parent::count()){
         $this->EqRqst_ID = parent::getLastInsertId();
         $this->create($eqLsRqst);
         if($this->count()){
              foreach($rqstPakg as $pkg){
                  $this->_RequestPkg->create(array_merge(array('EqRqst_ID'=> $this->EqRqst_ID),$pkg));
                    if(!$this->_RequestPkg->count()){
                 $this->rollBack();
            }

              }
              $this->commit();

         }else{
             echo 'Second Rollback';
          $this->rollBack();
         }
     }else{

        echo 'First Rollback';
          $this->rollBack();
     }
}

}

?>


来源: stackexchange

问:
Cannot find the path of folder in the same directory location - Android studio
I drop a folder called profiles in the same directory where my java files stored.

I tried to find the folder but get a not-found error.

```<code>String dir = getApplicationInfo().dataDir;
Log.d("dir", dir);
File folder = new File("/profiles"); // also tried File folder = new File(dir+"/profiles");
if (!folder.exists()) {
    Log.d("Not Found Dir", "Not Found Dir  ");
} else {
    Log.d("Found Dir", "Found Dir  " );
}
</code>```

Print

```<code>D/dir: /data/user/0/com.pakhocheung.o
D/Not Found Dir: Not Found Dir
</code>```

Then I tried to list all the files in that directory

```<code>String path = dir;
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++) {
    Log.d("Files", "FileName:" + files[i].getName());
}
</code>```

Print

```<code>D/Files: Path: /data/user/0/com.pakhocheung.o
D/Files: Size: 6
D/Files: FileName:cache
D/Files: FileName:code_cache
D/Files: FileName:lib
D/Files: FileName:shared_prefs
D/Files: FileName:app_Paas
D/Files: FileName:files
</code>```

It seems I am in the wrong directory because I can't see those files. Any suggestions?

答:
Create assests folder inside main folder. Put your profiles folder in assets folder. To read file names inside profiles folder use this code.

```<code>String[] list = null;
    try {
        list = getAssets().list("profiles");
        for (String file: list){
            Log.d(TAG, "file name "+ file.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

To read file from this folder use this.

```<code>InputStream is = getAssets().open("profiles/example.txt");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I drop a folder called profiles in the same directory where my java files stored.

I tried to find the folder but get a not-found error.

String dir = getApplicationInfo().dataDir;
Log.d("dir", dir);
File folder = new File("/profiles"); // also tried File folder = new File(dir+"/profiles");
if (!folder.exists()) {
    Log.d("Not Found Dir", "Not Found Dir  ");
} else {
    Log.d("Found Dir", "Found Dir  " );
}

Print

D/dir: /data/user/0/com.pakhocheung.o
D/Not Found Dir: Not Found Dir

Then I tried to list all the files in that directory

String path = dir;
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++) {
    Log.d("Files", "FileName:" + files[i].getName());
}

Print

D/Files: Path: /data/user/0/com.pakhocheung.o
D/Files: Size: 6
D/Files: FileName:cache
D/Files: FileName:code_cache
D/Files: FileName:lib
D/Files: FileName:shared_prefs
D/Files: FileName:app_Paas
D/Files: FileName:files

It seems I am in the wrong directory because I can't see those files. Any suggestions?

Body:
Create assests folder inside main folder. Put your profiles folder in assets folder. To read file names inside profiles folder use this code.

String[] list = null;
    try {
        list = getAssets().list("profiles");
        for (String file: list){
            Log.d(TAG, "file name "+ file.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

To read file from this folder use this.

InputStream is = getAssets().open("profiles/example.txt");


问:
How to extract apache phoenix table/view data to a file
How can I extract data from an apache phoenix table/view to  CSV/PSV/text?

For ex query:

```<code>select * from test_view
</code>```

答:
You can use squirrel to extract the data to local file.
Refer
https://community.hortonworks.com/articles/44350/setting-up-squirrel-and-phoenix-integration.html</p>

Body:
How can I extract data from an apache phoenix table/view to  CSV/PSV/text?

For ex query:

select * from test_view


问:
Create a 12 Character Secret
I need to create some secret 12 character string in C#. It can only have regular latin characters plus digits.

Any ideas of best practices?

Thanks

答:
How about the simple solution of constructing a string of the characters you want then calling the random number generator 12 times. Use each random number to index the string and get the character you want, something like (from memory):</p>

```<code>String s = "abcdefghijklmnopqrstuvwxyz1234567890";
StringBuilder sekrit = new StringBuilder();
Random r = new Random();
for (int i = 0; i < 12; i++)
    sekrit = sekrit + s[r.Next(s.Length)];
return sekrit.ToString();
</code>```

ContentLicense: CC BY-SA 2.5

Title: Create a 12 Character Secret

Body:
How about the simple solution of constructing a string of the characters you want then calling the random number generator 12 times. Use each random number to index the string and get the character you want, something like (from memory):

String s = "abcdefghijklmnopqrstuvwxyz1234567890";
StringBuilder sekrit = new StringBuilder();
Random r = new Random();
for (int i = 0; i < 12; i++)
    sekrit = sekrit + s[r.Next(s.Length)];
return sekrit.ToString();


问:
How to parse HTTP raw bytes and get the HTTP content in python?
I use scapy to sniff some packets and I get some HTTP response packets that are bytes I cannot parse.For example:

```<code>  b'HTTP/1.1 200 OK\r\nDate: Thu, 07 Dec 2017 02:44:18 GMT\r\nServer:Apache/2.4.18 (Ubuntu)\r\nLast-Modified: Tue, 14 Nov 2017 05:51:36 GMT\r\nETag: "2c39-55deafadf0ac0-gzip"\r\nAccept-Ranges: bytes\r\nVary: Accept-Encoding\r\nContent-Encoding: gzip\r\nContent-Length: 3186\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n\x1f\x8b'
</code>```

Is there a way to get the content part of this byte array so I can use gzip library to decode? I don't want to use request to get the HTTP response because I merely want to process the raw packet I had.

答:
There's no built-in way to parse a raw HTTP response like this and handle compression properly. I would use urllib3:

```<code>import urllib3

from io import BytesIO
from http.client import HTTPResponse

class BytesIOSocket:
    def __init__(self, content):
        self.handle = BytesIO(content)

    def makefile(self, mode):
        return self.handle

def response_from_bytes(data):
    sock = BytesIOSocket(data)

    response = HTTPResponse(sock)
    response.begin()

    return urllib3.HTTPResponse.from_httplib(response)

if __name__ == '__main__':
    import socket

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(('httpbin.org', 80))
    sock.send(b'GET /gzip HTTP/1.1\r\nHost: httpbin.org\r\n\r\n')

    raw_response = sock.recv(8192)

    response = response_from_bytes(raw_response)
    print(response.headers)
    print(response.data)
</code>```

Body:
I use scapy to sniff some packets and I get some HTTP response packets that are bytes I cannot parse.For example:

  b'HTTP/1.1 200 OK\r\nDate: Thu, 07 Dec 2017 02:44:18 GMT\r\nServer:Apache/2.4.18 (Ubuntu)\r\nLast-Modified: Tue, 14 Nov 2017 05:51:36 GMT\r\nETag: "2c39-55deafadf0ac0-gzip"\r\nAccept-Ranges: bytes\r\nVary: Accept-Encoding\r\nContent-Encoding: gzip\r\nContent-Length: 3186\r\nConnection: close\r\nContent-Type: text/html\r\n\r\n\x1f\x8b'

Is there a way to get the content part of this byte array so I can use gzip library to decode? I don't want to use request to get the HTTP response because I merely want to process the raw packet I had.

Body:
There's no built-in way to parse a raw HTTP response like this and handle compression properly. I would use urllib3:

import urllib3

from io import BytesIO
from http.client import HTTPResponse

class BytesIOSocket:
    def __init__(self, content):
        self.handle = BytesIO(content)

    def makefile(self, mode):
        return self.handle

def response_from_bytes(data):
    sock = BytesIOSocket(data)

    response = HTTPResponse(sock)
    response.begin()

    return urllib3.HTTPResponse.from_httplib(response)

if __name__ == '__main__':
    import socket

    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(('httpbin.org', 80))
    sock.send(b'GET /gzip HTTP/1.1\r\nHost: httpbin.org\r\n\r\n')

    raw_response = sock.recv(8192)

    response = response_from_bytes(raw_response)
    print(response.headers)
    print(response.data)


问:
bootstrap-select when setting container then the options will not hiding after selected?
bootstrap-select when setting container then the options will not hide after selected?

```<code><form id="searchForm" action="" method="post" class="form-search">

   <label>section ：</label>

   <select name="section.id" class="" onchange="" id="section" tabindex="-98">

     <option value="35">S340NJ-LM2_ </option>

     <option value="16">S340NJ-</option>

   </select>
</code>```

```<code> $('select').selectpicker({
     container:'.form-search',
     liveSearch: true
 })
</code>```

delete js line 2, will find

jsfiddle:
https://jsfiddle.net/Seven4X/9ge8mcgp/

答:
You need to add the class to your select tag</p>

```<code>class="selectpicker"
</code>```

Body:
bootstrap-select when setting container then the options will not hide after selected?

<form id="searchForm" action="" method="post" class="form-search">

   section ：

   <select name="section.id" class="" onchange="" id="section" tabindex="-98">

     <option value="35">S340NJ-LM2_ </option>

     <option value="16">S340NJ-</option>

   </select>

 $('select').selectpicker({
     container:'.form-search',
     liveSearch: true
 })

delete js line 2, will find

jsfiddle:
https://jsfiddle.net/Seven4X/9ge8mcgp/

Body:
You need to add the class to your select tag

class="selectpicker"


问:
Python3 - Overwrite variable value in another python file using user input
I am currently trying to write to another python file to replace a variable using user input.

Suppose I have file_a.py and file_b.py

I want to execute file b to grab a variable from file a. Then save that userinput value to var1 in file_a.py.

Example:

file_a.py contents:

```<code>var1 = "/path/to/file"
</code>```

file_b.py contents:

```<code>print(var1 " is the current path")

userinput = input("Type new directory path here: ")
</code>```

答:
If both files are in the same folder you can:

file_b.py

```<code>from file_a import var1

print(var1 " is the current path")

userinput = input("Type new directory path here: ")

var1 = userinput
</code>```

Or

```<code>import file_a

print(file_a.var1 " is the current path")

userinput = input("Type new directory path here: ")

file_a.var1 = userinput
</code>```

But, Do you know that you can't modify the another file itself? var1 will be changed in the memory, but if you open file_a.py, var1 will be "/path/to/file".

P.S: A little suggestion print(var1 " is the current path") --> print(var1, "is the current path").

Edit: I think this will be good by your level (you are doing this like homework, if I make something more efficient or with some modules the teacher would notice it).

```<code>def re_write(new):
    with open("file_a.py", 'r') as file:
        new_file = []
        for line in file:
            if "var1" in line:
                new_file.append(line.split("var1")[0] + "var1 = '" + new + "'")
            else:
                new_file.append(line)
        with open("file_a.py", 'w') as file:
            for line in new_file:
                file.writelines(line)
</code>```

A better code (faster, with less memory usage and maybe better in general) could be find in this question.

Body:
I am currently trying to write to another python file to replace a variable using user input.

Suppose I have file_a.py and file_b.py

I want to execute file b to grab a variable from file a. Then save that userinput value to var1 in file_a.py.

Example:

file_a.py contents:

var1 = "/path/to/file"

file_b.py contents:

print(var1 " is the current path")

userinput = input("Type new directory path here: ")

Body:
If both files are in the same folder you can:

file_b.py

from file_a import var1

print(var1 " is the current path")

userinput = input("Type new directory path here: ")

var1 = userinput

Or

import file_a

print(file_a.var1 " is the current path")

userinput = input("Type new directory path here: ")

file_a.var1 = userinput

But, Do you know that you can't modify the another file itself? var1 will be changed in the memory, but if you open file_a.py, var1 will be "/path/to/file".

P.S: A little suggestion print(var1 " is the current path") --> print(var1, "is the current path").

Edit: I think this will be good by your level (you are doing this like homework, if I make something more efficient or with some modules the teacher would notice it).

def re_write(new):
    with open("file_a.py", 'r') as file:
        new_file = []
        for line in file:
            if "var1" in line:
                new_file.append(line.split("var1")[0] + "var1 = '" + new + "'")
            else:
                new_file.append(line)
        with open("file_a.py", 'w') as file:
            for line in new_file:
                file.writelines(line)

A better code (faster, with less memory usage and maybe better in general) could be find in this question.


问:
Are `select current_user` and `select current_database()` both SQL query statements?
In PostgreSQL, we can get the current user and database by

```<code>select current_user;

select current_database();
</code>```

Is select in both statements the same select in a SQL query?

Are current_user and current_database() both column names?

What are the tables they are selected from?

Thanks.

答:
select is the very same select as used in any select query

current_database() is a "System Information Function"

current_user is also a "System Information Function"  (see note below)

A function typically takes parameters and therefore are used with parentheses to hold those parameters, but some system functions, such as current_database() don't require any parameters, but the empty parentheses remain.

System Information Functions "extract session and system information" see: https://www.postgresql.org/docs/current/static/functions-info.html

Note

current_catalog, current_role, current_schema, current_user,
  session_user, and user have special syntactic status in SQL: they must
  be called without trailing parentheses.

Body:
In PostgreSQL, we can get the current user and database by

select current_user;

select current_database();

Is select in both statements the same select in a SQL query?

Are current_user and current_database() both column names?

What are the tables they are selected from?

Thanks.


问:
Python request.post gives 500 response
For one of my post requests, I get a 500 response every time I try to run it. When I copy and paste the details in postman, it works fine every time. The python post works fine for other requests that I run, but this one fails every time and I can't work out why.

Has anyone come across this problem before, or can anyone see something that I've done wrong?

```<code>json_body = '{"overrides": [], "id": 0, "name": "Rate Sheet 12", "resellerId": 2000001, "currency": "ZAR", "markup": {"id": 0, "method": "Percentage", "operand": 3}, "totalLinkedBands": 0, "totalLinkedAccounts": 0}'
token = 'JWT eyJ0eXA...s'
url = 'http://app01:8084//PriceScheme/CreatePriceScheme'
r = requests.post(url, json.loads(json_body), headers={'Authorization': token})
</code>```

In Postman it looks as follows:

```<code>(POST) http://app01:8084//PriceScheme/CreatePriceScheme
Content-Type - application/json
Authorization - JWT eyJ...

{"overrides": [], "name": "Rate Sheet 1", "currency": "ZAR", "totalLinkedAccounts": 0, "totalLinkedBands": 1, "id": 1, "markup": {"method": "Percentage", "operand": 3.0, "id": 0}, "resellerId": "2009340"}
</code>```

答:
try as blew

```<code>requests.post(url, json = json_body, headers={'Authorization': token})
</code>```

In Postman , auto using Content-Type - application/json

If using request post json data , should using json=data

Title: Python request.post gives 500 response

Body:
For one of my post requests, I get a 500 response every time I try to run it. When I copy and paste the details in postman, it works fine every time. The python post works fine for other requests that I run, but this one fails every time and I can't work out why.

Has anyone come across this problem before, or can anyone see something that I've done wrong?

json_body = '{"overrides": [], "id": 0, "name": "Rate Sheet 12", "resellerId": 2000001, "currency": "ZAR", "markup": {"id": 0, "method": "Percentage", "operand": 3}, "totalLinkedBands": 0, "totalLinkedAccounts": 0}'
token = 'JWT eyJ0eXA...s'
url = 'http://app01:8084//PriceScheme/CreatePriceScheme'
r = requests.post(url, json.loads(json_body), headers={'Authorization': token})

In Postman it looks as follows:

(POST) http://app01:8084//PriceScheme/CreatePriceScheme
Content-Type - application/json
Authorization - JWT eyJ...

{"overrides": [], "name": "Rate Sheet 1", "currency": "ZAR", "totalLinkedAccounts": 0, "totalLinkedBands": 1, "id": 1, "markup": {"method": "Percentage", "operand": 3.0, "id": 0}, "resellerId": "2009340"}

Body:
try as blew

requests.post(url, json = json_body, headers={'Authorization': token})

In Postman , auto using Content-Type - application/json

If using request post json data , should using json=data


答:
Are you trying to edit the text of file_a.py? If so then you could look into the package redbarron. If you are importing file_a as a module, you can edit its global variables as such:

import file_a
file_a.var1 = 'new value'

This is called "monkey patching" and the effect will be inplace until the program exits. Executing it next time will have no effect.

However, I feel like this question is likely misguided. Can I ask what you are trying to accomplish?

Title: Python3 - Overwrite variable value in another python file using user input


问:
CSS hovering doesn't work as expected
I want to display set of buttons which I wrapped with a span element on a hovering effect, initially one button will be shown and when user hovers over the span element initially showed button will be hidden and other buttons will be shown.

.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.buttons:hover .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.buttons:hover .settingsbtn {
    opacity: 0;
}

.btn {
    padding: 6px 12px;
    display: inline-block;
    margin-top: -10px;
    text-transform: capitalize;
    margin-left: 6px;
    float: right;
}

.spaceTest {
    margin-left: 32px;
}

.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span class="buttons">
     <button type="submit" class="btn btn-danger pull-right settingsbtn">
         <i class="material-icons">settings</i>
     </button>

        <button type="submit" class="btn btn-danger pull-right listbtn">
            <i class="material-icons">content_paste</i>
        </button>

     <button *ngIf="isScanning" type="submit" class="btn btn-danger pull-right spaceTest listbtn">
          <i class="material-icons">refresh</i>
      </button>
      <button type="submit" class="btn btn-danger pull-right listbtn">
          <i class="material-icons">delete</i>
      </button>
      <button type="submit" class="btn btn-danger pull-right listbtn">
          <i class="material-icons">mode_edit</i>
      </button>
</span></code>```

The problem I am facing is when user moves mouse between delete and rescan buttons icons are disappearing which shouldn't be as I am using css hovering for the span. Could you please describe to me what I am doing wrong?

答:
The issue you are encountering is caused by the pull-right classes that are added to your button elements. This causes the buttons to be floated to the right and therefore the wrapper span element cannot be hovered over when pointing your cursor between your floated buttons.

Here is a CodePen I made to demonstrate your issue: https://codepen.io/robertcooper_rc/pen/mqYGKN. I've got the functionality working as you desire at the moment, but if you uncomment the last three lines of CSS, you will see how the pull-right class affects the hovering of your buttons.

The styles for pull-right are added through Bootstrap. See the documentation for Bootstrap quick floats here: https://getbootstrap.com/docs/3.3/css/#helper-classes-floats

Solution - Clearfix

One way to solve this is by applying a "clearfix" to the span element to take care of all the floated elements inside of it. Here is what a clearfix looks like in CSS:

```<code>// Clearfix
.buttons:after {
  content: "";
  display: table;
  clear: both;
}
</code>```

The clearfix forces the span element to take up a width and height that is large enough to contain the floated elements. Without the clearfix, the span's height collapses to 0 if all child elements are floated and this is what is preventing you from hovering over the span.

Title: CSS hovering doesn't work as expected

Body:
I want to display set of buttons which I wrapped with a span element on a hovering effect, initially one button will be shown and when user hovers over the span element initially showed button will be hidden and other buttons will be shown.

.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

.buttons:hover .listbtn {
    opacity: 1;
}

.settingsbtn {
    opacity: 1;
    transition: opacity .35s ease;
}

.buttons:hover .settingsbtn {
    opacity: 0;
}

.btn {
    padding: 6px 12px;
    display: inline-block;
    margin-top: -10px;
    text-transform: capitalize;
    margin-left: 6px;
    float: right;
}

.spaceTest {
    margin-left: 32px;
}

.listbtn {
    opacity: 0;
    transition: opacity .35s ease;
}

     <button type="submit" class="btn btn-danger pull-right settingsbtn">
         settings
     </button>

        <button type="submit" class="btn btn-danger pull-right listbtn">
            content_paste
        </button>

     <button *ngIf="isScanning" type="submit" class="btn btn-danger pull-right spaceTest listbtn">
          refresh
      </button>
      <button type="submit" class="btn btn-danger pull-right listbtn">
          delete
      </button>
      <button type="submit" class="btn btn-danger pull-right listbtn">
          mode_edit
      </button>

The problem I am facing is when user moves mouse between delete and rescan buttons icons are disappearing which shouldn't be as I am using css hovering for the span. Could you please describe to me what I am doing wrong?

Body:
The issue you are encountering is caused by the pull-right classes that are added to your button elements. This causes the buttons to be floated to the right and therefore the wrapper span element cannot be hovered over when pointing your cursor between your floated buttons.

Here is a CodePen I made to demonstrate your issue: https://codepen.io/robertcooper_rc/pen/mqYGKN. I've got the functionality working as you desire at the moment, but if you uncomment the last three lines of CSS, you will see how the pull-right class affects the hovering of your buttons.

The styles for pull-right are added through Bootstrap. See the documentation for Bootstrap quick floats here: https://getbootstrap.com/docs/3.3/css/#helper-classes-floats

Solution - Clearfix

One way to solve this is by applying a "clearfix" to the span element to take care of all the floated elements inside of it. Here is what a clearfix looks like in CSS:

// Clearfix
.buttons:after {
  content: "";
  display: table;
  clear: both;
}

The clearfix forces the span element to take up a width and height that is large enough to contain the floated elements. Without the clearfix, the span's height collapses to 0 if all child elements are floated and this is what is preventing you from hovering over the span.


问:
Input Validation for GUI
My program works fine as is, I just need to add an input validation "invalid input, number has to be positive" dialog, after an input of 0 or a negative number for length: tLength and width: tWidth.

Here is my code which runs fine, just needs the validation added:

```<code>import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class FloorsRUs extends JFrame implements ActionListener, ItemListener
{

    public JTabbedPane jTP;
    public JRadioButton flrWood = null;
    public JRadioButton flrCarpet = null;
    public JTextField tCName;
    public JTextField tAddress;
    public JTextField tLength;
    public JTextField tWidth;
    public JButton calcArea;
    public JButton calcCost;
    public JButton subOrder;
    public JButton orderSum;
    public JButton ordList;
    public JPanel flrPan;
    public JPanel lwPan;
    public JPanel cPan;
    public JLabel lab1;
    public JLabel lab2;
    public JLabel lab3;
    public JLabel lab4;
    public String flrType;
    public double area = 0;
    public double cost = 0;

    FloorsRUs(String title)
    {
        super(title);
        jTP=new JTabbedPane();
        flrPan=new JPanel();
        lwPan=new JPanel();
        cPan=new JPanel();

        flrPan.add(flrWood=new JRadioButton("Choose Wood"));
        flrPan.add(flrCarpet=new JRadioButton("Choose Carpet"));

        ButtonGroup grp = new ButtonGroup();
        grp.add(flrWood);
        grp.add(flrCarpet);

        lwPan.add(lab1=new JLabel("Enter the Length : "));
        lwPan.add(tLength=new JTextField(10));

        lwPan.add(lab2=new JLabel("Enter the Width"));
        lwPan.add(tWidth=new JTextField(10));

        lwPan.add(calcArea=new JButton("Calculate the Area"));
        lwPan.add(calcCost=new JButton("Calculate the Cost"));
        lwPan.add(subOrder=new JButton("Submit the Order"));

        cPan.add(lab3=new JLabel("Enter the Customers Name : "));
        cPan.add(tCName=new JTextField(10));

        cPan.add(lab4=new JLabel("Enter the Customers Address : "));
        cPan.add(tAddress=new JTextField(10));

        cPan.add(orderSum=new JButton("The Order Summary"));
        cPan.add(ordList=new JButton("The Order List"));

        jTP.addTab("Select Floor Type ",flrPan);
        jTP.addTab("Enter Length and Width ",lwPan);
        jTP.addTab("Customer Info",cPan);
        add(jTP);

        calcArea.addActionListener(this);
        calcCost.addActionListener(this);
        subOrder.addActionListener(this);
        orderSum.addActionListener(this);
        ordList.addActionListener(this);
        flrWood.addItemListener(this);
        flrCarpet.addItemListener(this);

    }
    @Override
    public void itemStateChanged(ItemEvent ie)

    {
        if(flrWood.isSelected()){
            flrType="Wood";

        }

        else if(flrCarpet.isSelected()){
            flrType="Carpet";
        }

    }

    @Override
    public void actionPerformed(ActionEvent ae)
    {

        String source=ae.getActionCommand();

        switch (source) {

        case "Calculate the Area":
            System.out.println("Calc 1 Complete");
            area=Double.parseDouble(tLength.getText())
            *Double.parseDouble(tWidth.getText());
            break;

        case "Calculate the Cost":
            System.out.println("Calc 2 Complete");
            if(flrType.equals("Wood"))
            cost = area *20;
            else if(flrType.equals("Carpet"))
            cost = area *10;
            break;

        case "The Order Summary":
            JOptionPane.showMessageDialog(null,"The Order Summary - Area is :" +
            ""+area+""+ " The Cost is :  "+cost," Information",
            JOptionPane.INFORMATION_MESSAGE);
            break;

        case "The Order List":
            JOptionPane.showMessageDialog(null,"The Order List : \n Customer's name :
"+tCName.getText()
            +"\nAddress : "+tAddress.getText()
            +"\n The Area is :"+area
            +"\n The Cost is : "+cost,"Information",
            JOptionPane.INFORMATION_MESSAGE);
            break;

        default:

            break;
        }

    }

    public static void main(String args[])

    {
        FloorsRUs f1=new FloorsRUs("FloorsRUs Easy App");
        f1.setSize(new Dimension(650,450));
        f1.setVisible(true);
    }

}
</code>```

I've tried:

```<code>if(tLength.getText()<=0 && tWidth.getText()<=0)
{
    System.out.println("invalid input, number has to be positive");
}
</code>```

And it received errors for  "Bad operand for binary operator '<='". I believe because tLength and tWidth are both String.

So then I tried:

```<code>case "Calculate the Area":
System.out.println("Calc 1 Complete");
area=Double.parseDouble(tLength.getText())
*Double.parseDouble(tWidth.getText());
if((Double.parseDouble(tLength.getText())<=0) &&
((Double.parseDouble(tWidth.getText())<=0)))
{
   System.out.println("invalid input, number has to be positive");
}
break;
</code>```

It accepted it but didn't change the output when I put a 0 or negative number into the tLength or tWidth field.

So finally I tried:

```<code>case "Calculate the Area":
        System.out.println("Calc 1 Complete");
        try {
            if ((Double.parseDouble(tLength.getText()) < 0)
                    && ((Double.parseDouble(tWidth.getText()) < 0))) {
                System.out.println("invalid input, number has to be
positive");
            } else {
                area = Double.parseDouble(tLength.getText()) *
Double.parseDouble(tWidth.getText());
            }

        } catch (NumberFormatException e) {
            System.out.println("invalid input, number has to be positive");
        }
        break;
</code>```

Also, no errors but it didn't work when negative numbers or 0 were entered.

I have tried switching '&&' to '||' as well and no luck.

答:
TL;DR, the second code block is what you need.

You are almost there with this:

```<code>if(tLength.getText()<=0 && tWidth.getText()<=0)
{
    System.out.println("invalid input, number has to be positive");
}
</code>```

Aside from the fact that it should be || and not &&, the problem is you are trying to compare a String to an int. To make this work, you need to parse the String as an integer, so just wrap up your string in the Integer.parseInt() function. Your final if statement should look like this:

```<code>if (Integer.parseInt(tLength.getText()) <= 0 ||
    Integer.parseInt(tWidth.getText()) <=0 )
{
    System.out.println("invalid input, number has to be positive");
}
</code>```

This next part isn't necessary but helps keep code neat:

Because it is only 1 single statement inside the curly braces, you don't actually need them, so you can write the same thing as above, but like this:

```<code>if (Integer.parseInt(tLength.getText()) <= 0 ||
    Integer.parseInt(tWidth.getText()) <=0 )
        System.out.println("invalid input, number has to be positive");
</code>```

Any following lines of code will be outside the if statement code block.

A slightly more complex example:
If it were me, I would use the ternary operator and assign the result to the variable and print the variable like this:

```<code>String output = Integer.parseInt(tLength.getText()) <= 0 ||
                Integer.parseInt(tWidth.getText()) <= 0 ?
               "invalid input, number has to be positive" : "";
System.out.println(output);
</code>```

This is basically a few lines of code rolled into one. The first two words creates the 'output' variable. The thing on the RHS of the "=" is a ternary operation.
A ternary operation is just an if statement that says
If "x" = true then do A
else do B.

So if Integer.parseInt(tLength.getText()) <= 0 is true then the string "invalid input, number has to be positive" will be assigned to the variable 'output'.
But if Integer.parseInt(tLength.getText()) <= 0 is false then the string "" (an empty string) will be assigned to 'output'. This particular ternary operation also performs the same test on Integer.parseInt(tWidth.getText()), so if either of them are true, then the first option is used.
The last line prints the contents of 'output' and places the cursor on the next line. This means if the empty string is printed, then the cursor will still move to the next line, but it won't print anything. Moving the cursor to the next line may or may not be what you want to do (if you don't, you can always use System.out.print() instead of System.out.println()).

Hope that helps.

Title: Input Validation for GUI

Body:
My program works fine as is, I just need to add an input validation "invalid input, number has to be positive" dialog, after an input of 0 or a negative number for length: tLength and width: tWidth.

Here is my code which runs fine, just needs the validation added:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class FloorsRUs extends JFrame implements ActionListener, ItemListener
{

    public JTabbedPane jTP;
    public JRadioButton flrWood = null;
    public JRadioButton flrCarpet = null;
    public JTextField tCName;
    public JTextField tAddress;
    public JTextField tLength;
    public JTextField tWidth;
    public JButton calcArea;
    public JButton calcCost;
    public JButton subOrder;
    public JButton orderSum;
    public JButton ordList;
    public JPanel flrPan;
    public JPanel lwPan;
    public JPanel cPan;
    public JLabel lab1;
    public JLabel lab2;
    public JLabel lab3;
    public JLabel lab4;
    public String flrType;
    public double area = 0;
    public double cost = 0;

    FloorsRUs(String title)
    {
        super(title);
        jTP=new JTabbedPane();
        flrPan=new JPanel();
        lwPan=new JPanel();
        cPan=new JPanel();

        flrPan.add(flrWood=new JRadioButton("Choose Wood"));
        flrPan.add(flrCarpet=new JRadioButton("Choose Carpet"));

        ButtonGroup grp = new ButtonGroup();
        grp.add(flrWood);
        grp.add(flrCarpet);

        lwPan.add(lab1=new JLabel("Enter the Length : "));
        lwPan.add(tLength=new JTextField(10));

        lwPan.add(lab2=new JLabel("Enter the Width"));
        lwPan.add(tWidth=new JTextField(10));

        lwPan.add(calcArea=new JButton("Calculate the Area"));
        lwPan.add(calcCost=new JButton("Calculate the Cost"));
        lwPan.add(subOrder=new JButton("Submit the Order"));

        cPan.add(lab3=new JLabel("Enter the Customers Name : "));
        cPan.add(tCName=new JTextField(10));

        cPan.add(lab4=new JLabel("Enter the Customers Address : "));
        cPan.add(tAddress=new JTextField(10));

        cPan.add(orderSum=new JButton("The Order Summary"));
        cPan.add(ordList=new JButton("The Order List"));

        jTP.addTab("Select Floor Type ",flrPan);
        jTP.addTab("Enter Length and Width ",lwPan);
        jTP.addTab("Customer Info",cPan);
        add(jTP);

        calcArea.addActionListener(this);
        calcCost.addActionListener(this);
        subOrder.addActionListener(this);
        orderSum.addActionListener(this);
        ordList.addActionListener(this);
        flrWood.addItemListener(this);
        flrCarpet.addItemListener(this);

    }
    @Override
    public void itemStateChanged(ItemEvent ie)

    {
        if(flrWood.isSelected()){
            flrType="Wood";

        }

        else if(flrCarpet.isSelected()){
            flrType="Carpet";
        }

    }

    @Override
    public void actionPerformed(ActionEvent ae)
    {

        String source=ae.getActionCommand();

        switch (source) {

        case "Calculate the Area":
            System.out.println("Calc 1 Complete");
            area=Double.parseDouble(tLength.getText())
            *Double.parseDouble(tWidth.getText());
            break;

        case "Calculate the Cost":
            System.out.println("Calc 2 Complete");
            if(flrType.equals("Wood"))
            cost = area *20;
            else if(flrType.equals("Carpet"))
            cost = area *10;
            break;

        case "The Order Summary":
            JOptionPane.showMessageDialog(null,"The Order Summary - Area is :" +
            ""+area+""+ " The Cost is :  "+cost," Information",
            JOptionPane.INFORMATION_MESSAGE);
            break;

        case "The Order List":
            JOptionPane.showMessageDialog(null,"The Order List : \n Customer's name :
"+tCName.getText()
            +"\nAddress : "+tAddress.getText()
            +"\n The Area is :"+area
            +"\n The Cost is : "+cost,"Information",
            JOptionPane.INFORMATION_MESSAGE);
            break;

        default:

            break;
        }

    }

    public static void main(String args[])

    {
        FloorsRUs f1=new FloorsRUs("FloorsRUs Easy App");
        f1.setSize(new Dimension(650,450));
        f1.setVisible(true);
    }

}

I've tried:

if(tLength.getText()<=0 && tWidth.getText()<=0)
{
    System.out.println("invalid input, number has to be positive");
}

And it received errors for  "Bad operand for binary operator '<='". I believe because tLength and tWidth are both String.

So then I tried:

case "Calculate the Area":
System.out.println("Calc 1 Complete");
area=Double.parseDouble(tLength.getText())
*Double.parseDouble(tWidth.getText());
if((Double.parseDouble(tLength.getText())<=0) &&
((Double.parseDouble(tWidth.getText())<=0)))
{
   System.out.println("invalid input, number has to be positive");
}
break;

It accepted it but didn't change the output when I put a 0 or negative number into the tLength or tWidth field.

So finally I tried:

case "Calculate the Area":
        System.out.println("Calc 1 Complete");
        try {
            if ((Double.parseDouble(tLength.getText()) < 0)
                    && ((Double.parseDouble(tWidth.getText()) < 0))) {
                System.out.println("invalid input, number has to be
positive");
            } else {
                area = Double.parseDouble(tLength.getText()) *
Double.parseDouble(tWidth.getText());
            }

        } catch (NumberFormatException e) {
            System.out.println("invalid input, number has to be positive");
        }
        break;

Also, no errors but it didn't work when negative numbers or 0 were entered.

I have tried switching '&&' to '||' as well and no luck.

Body:
TL;DR, the second code block is what you need.

You are almost there with this:

if(tLength.getText()<=0 && tWidth.getText()<=0)
{
    System.out.println("invalid input, number has to be positive");
}

Aside from the fact that it should be || and not &&, the problem is you are trying to compare a String to an int. To make this work, you need to parse the String as an integer, so just wrap up your string in the Integer.parseInt() function. Your final if statement should look like this:

if (Integer.parseInt(tLength.getText()) <= 0 ||
    Integer.parseInt(tWidth.getText()) <=0 )
{
    System.out.println("invalid input, number has to be positive");
}

This next part isn't necessary but helps keep code neat:

Because it is only 1 single statement inside the curly braces, you don't actually need them, so you can write the same thing as above, but like this:

if (Integer.parseInt(tLength.getText()) <= 0 ||
    Integer.parseInt(tWidth.getText()) <=0 )
        System.out.println("invalid input, number has to be positive");

Any following lines of code will be outside the if statement code block.

A slightly more complex example:
If it were me, I would use the ternary operator and assign the result to the variable and print the variable like this:

String output = Integer.parseInt(tLength.getText()) <= 0 ||
                Integer.parseInt(tWidth.getText()) <= 0 ?
               "invalid input, number has to be positive" : "";
System.out.println(output);

This is basically a few lines of code rolled into one. The first two words creates the 'output' variable. The thing on the RHS of the "=" is a ternary operation.
A ternary operation is just an if statement that says
If "x" = true then do A
else do B.

So if Integer.parseInt(tLength.getText()) <= 0 is true then the string "invalid input, number has to be positive" will be assigned to the variable 'output'.
But if Integer.parseInt(tLength.getText()) <= 0 is false then the string "" (an empty string) will be assigned to 'output'. This particular ternary operation also performs the same test on Integer.parseInt(tWidth.getText()), so if either of them are true, then the first option is used.
The last line prints the contents of 'output' and places the cursor on the next line. This means if the empty string is printed, then the cursor will still move to the next line, but it won't print anything. Moving the cursor to the next line may or may not be what you want to do (if you don't, you can always use System.out.print() instead of System.out.println()).

Hope that helps.


问:
Plot a small region of a map with ocean in ggplot2
I am trying to plot some parts of Canada using the ggplot2 package. I know that it could be tricky to keep the entire polygons because ggplot is getting rid of the points outside the limits (if you use limits in scale_x/y_continuous()). To overcome this, it is useful to plot the entire map and then to apply a zoom (coord_map). My polygons are all okay except that ocean is in the same color than Canada/Alaska. However, if I look at the entire map it is white.

A working example :

```<code>require(rgdal)
require(ggplot2)
YK <- map_data("world")  ##World

## Regions Canada
library(autoimage)
data(canada)
library(broom)
canada_df <- tidy(canada)

p <- (ggplot()
      + theme_bw()
      + geom_polygon(data = YK, aes(x=long, y = lat, group = group), fill="gray70")
      + geom_path(data = canada_df, aes(x=long, y=lat, group=group), colour="black"))
p
</code>```

This gives a correct world map :

Then if I want to zoom at the west part of Canada :

```<code>p <- (ggplot()
      + theme_bw()
      + geom_polygon(data = YK, aes(x=long, y = lat, group = group), fill="gray70")
      + geom_path(data = canada_df, aes(x=long, y=lat, group=group), colour="black")
      + coord_map("mercator", xlim=c(-150, -120), ylim=c(50, 70)))
p
</code>```

This gives :

Regions are correct but the Pacific ocean should be in white in the left side...
So I tried with the other way :

```<code>p <- (ggplot()
      + theme_bw()
      + geom_polygon(data = YK, aes(x=long, y = lat, group = group), fill="gray70")
      + geom_path(data = canada_df, aes(x=long, y=lat, group=group), colour="black")
      + scale_x_continuous(limits = c(-150, -120))
      + scale_y_continuous(limits = c(50, 70)))
p
</code>```

Which gives :

The ocean is in white but as excepted, the polygons are cropped...

Is there a way to have this zoom with the entire polygons and the ocean in white ? Because like this, it is as if everything was the continent...

Thank you !

答:
Seems the problem is with coord_map. If using coord_cartesian or coord_fixed the zoom in is ok. And coord_quickmap works too.

```<code>p <- ggplot() +
      theme_bw() +
      geom_polygon(data = YK, aes(x=long, y = lat, group = group), fill="gray70") +
      geom_path(data = canada_df, aes(x=long, y=lat, group=group), colour="black")
p

p + coord_cartesian(xlim=c(-150, -120), ylim=c(50, 70))

p + coord_fixed(ratio = 2, xlim=c(-150, -120), ylim=c(50, 70))

p + coord_quickmap(xlim=c(-150, -120), ylim=c(50, 70))
</code>```

Body:
I am trying to plot some parts of Canada using the ggplot2 package. I know that it could be tricky to keep the entire polygons because ggplot is getting rid of the points outside the limits (if you use limits in scale_x/y_continuous()). To overcome this, it is useful to plot the entire map and then to apply a zoom (coord_map). My polygons are all okay except that ocean is in the same color than Canada/Alaska. However, if I look at the entire map it is white.

A working example :

require(rgdal)
require(ggplot2)
YK <- map_data("world")  ##World

## Regions Canada
library(autoimage)
data(canada)
library(broom)
canada_df <- tidy(canada)

p <- (ggplot()
      + theme_bw()
      + geom_polygon(data = YK, aes(x=long, y = lat, group = group), fill="gray70")
      + geom_path(data = canada_df, aes(x=long, y=lat, group=group), colour="black"))
p

This gives a correct world map :

Then if I want to zoom at the west part of Canada :

p <- (ggplot()
      + theme_bw()
      + geom_polygon(data = YK, aes(x=long, y = lat, group = group), fill="gray70")
      + geom_path(data = canada_df, aes(x=long, y=lat, group=group), colour="black")
      + coord_map("mercator", xlim=c(-150, -120), ylim=c(50, 70)))
p

This gives :

Regions are correct but the Pacific ocean should be in white in the left side...
So I tried with the other way :

p <- (ggplot()
      + theme_bw()
      + geom_polygon(data = YK, aes(x=long, y = lat, group = group), fill="gray70")
      + geom_path(data = canada_df, aes(x=long, y=lat, group=group), colour="black")
      + scale_x_continuous(limits = c(-150, -120))
      + scale_y_continuous(limits = c(50, 70)))
p

Which gives :

The ocean is in white but as excepted, the polygons are cropped...

Is there a way to have this zoom with the entire polygons and the ocean in white ? Because like this, it is as if everything was the continent...

Thank you !

Body:
Seems the problem is with coord_map. If using coord_cartesian or coord_fixed the zoom in is ok. And coord_quickmap works too.

p <- ggplot() +
      theme_bw() +
      geom_polygon(data = YK, aes(x=long, y = lat, group = group), fill="gray70") +
      geom_path(data = canada_df, aes(x=long, y=lat, group=group), colour="black")
p

p + coord_cartesian(xlim=c(-150, -120), ylim=c(50, 70))

p + coord_fixed(ratio = 2, xlim=c(-150, -120), ylim=c(50, 70))

p + coord_quickmap(xlim=c(-150, -120), ylim=c(50, 70))


问:
Set the first Record Value of LINQ
I have a DBSet which is db.Company and it contains 3 records like

id name is_active

```<code>1 company1 1
2 company2 1
3 company3 1
</code>```

My Created class to transfer the records:

```<code>public class CompanyFinal
    {
        public int id { get; set; }
        public string name { get; set; }
        public string selected { get; set; }
    }
</code>```

My LINQ looks like this:

```<code>(from h in db.Company where h.is_active == 1 select new CompanyFinal { id = h.id, name = h.name, selected = "false" }).ToList();
</code>```

No doubt this LINQ is working but i need to make the first record to be selected="true" which is the company 1 while doing it in LINQ.

How could i do that? Is it possible?

Thanks in advance

答:
From your result:

```<code>var companies = (from h in db.Company
                   where h.is_active == 1 select h).ToList();

var companyFinals = (from h in companies
                      select new CompanyFinal {
                         id = h.id,
                         name = h.name,
                         selected = "false"
                     }).ToList();

var firstCompany = companies.FirstOrDefault();

if (firstCompany != null) {
     firstCompany.selected = true;
}

// save result back to database
</code>```

There is no way to do it in 1 operation other than writing a stored procedure.

Title: Set the first Record Value of LINQ

Body:
I have a DBSet which is db.Company and it contains 3 records like

id name is_active

1 company1 1
2 company2 1
3 company3 1

My Created class to transfer the records:

public class CompanyFinal
    {
        public int id { get; set; }
        public string name { get; set; }
        public string selected { get; set; }
    }

My LINQ looks like this:

(from h in db.Company where h.is_active == 1 select new CompanyFinal { id = h.id, name = h.name, selected = "false" }).ToList();

No doubt this LINQ is working but i need to make the first record to be selected="true" which is the company 1 while doing it in LINQ.

How could i do that? Is it possible?

Thanks in advance

Body:
From your result:

var companies = (from h in db.Company
                   where h.is_active == 1 select h).ToList();

var companyFinals = (from h in companies
                      select new CompanyFinal {
                         id = h.id,
                         name = h.name,
                         selected = "false"
                     }).ToList();

var firstCompany = companies.FirstOrDefault();

if (firstCompany != null) {
     firstCompany.selected = true;
}

// save result back to database

There is no way to do it in 1 operation other than writing a stored procedure.


问:
Starred files in a spreadsheet
My starring workflow needs some work. I thought about creating a script to run in drive that looks for starred files (docs, slides, sheets) and adds them to spreadsheet.

I'm a complete noob, so I've checked the script reference to try and find snippets that might work.

```<code>iterate through drive
if starred file found
  add to new row in spreadsheet
</code>```

```<code>// Log the name of every starred file in the Designated Spreedsheet.
function addStarred() {
  var sheet = SpreadsheetApp.getActiveSheet(); //this will need to change to a designated sheet
  var files = DriveApp.getFiles();

  while (files.isStarred()) {
    var file = files.next();
    sheet.appendRow(file.getName());
  }
}
</code>```

The ideal would be a list in my spreadsheet that can then be filtered to find the correct starred file.

The first error I see is:

"Cannot find function isStarred in object FileIterator. (line 6, file "Code")"

Appreciate any help.

答:
isStarred() is a method of the Class File not of the Class Files. Change the while block to something like the following:</p>

```<code>while (files.hasNext()) {
  var file = files.next();
  if (file.isStarred()) sheet.appendRow([file.getName()])
}
</code>```

Title: Starred files in a spreadsheet

Body:
My starring workflow needs some work. I thought about creating a script to run in drive that looks for starred files (docs, slides, sheets) and adds them to spreadsheet.

I'm a complete noob, so I've checked the script reference to try and find snippets that might work.

iterate through drive
if starred file found
  add to new row in spreadsheet

// Log the name of every starred file in the Designated Spreedsheet.
function addStarred() {
  var sheet = SpreadsheetApp.getActiveSheet(); //this will need to change to a designated sheet
  var files = DriveApp.getFiles();

  while (files.isStarred()) {
    var file = files.next();
    sheet.appendRow(file.getName());
  }
}

The ideal would be a list in my spreadsheet that can then be filtered to find the correct starred file.

The first error I see is:

"Cannot find function isStarred in object FileIterator. (line 6, file "Code")"

Appreciate any help.

Body:
isStarred() is a method of the Class File not of the Class Files. Change the while block to something like the following:

while (files.hasNext()) {
  var file = files.next();
  if (file.isStarred()) sheet.appendRow([file.getName()])
}


问:
Providing callback in a _.forEach construct
(Working in the Postman environment) it was detected that the following code runs through all the url requests without printing the result.

```<code>    _.forEach(
            urls,
            function (myUrl) {
                pm.sendRequest({
                    url: myUrl,
                    method: 'GET',
                    header: {
                        'content-type': 'application/json'
                    }
                }, function (err, res) {
                    console.log(res)
                });
            }
        )
        pm.environment.set(`sections`,sections);
    }
</code>```

Is there any way to provide a callback within forEach, might appear something like given below code. Or is there any alternative to it.

```<code>    function callback() {
        console.log('callback');
    }

    _.forEach(
            urls,
            function (myUrl,callback) {
                pm.sendRequest({
                    url: myUrl,
                    method: 'GET',
                    header: {
                        'content-type': 'application/json'
                    }
                }, function (err, res) {
                    console.log(res)
                });
            }
        )
        pm.environment.set(`sections`,sections);
    }
</code>```

I had initially thought that the response handling function at the end would take care of that but it doesn't.

答:
Found it better to branch out the logic into another function getUrl and pass the callback into it.

Following code works:

```<code>_.forEach (
    urls,
    function (myUrl) {
        getUrl(myUrl,function (err,res) {
            if (err) {
                console.log(err);
            } else {
                console.log(JSON.stringify(res));
            }
        });
    }
);

function getUrl(myUrl, callback) {
    var call = {
        url: myUrl,
        method: 'GET',
        header: {
            "Authorization": `Bearer ${token}`,
            "Content-Type": "application/json"
        }
    };

    pm.sendRequest(
        call,
        function (err, res) {
            callback (err,res);
        }
    );
}
</code>```

Body:
(Working in the Postman environment) it was detected that the following code runs through all the url requests without printing the result.

    _.forEach(
            urls,
            function (myUrl) {
                pm.sendRequest({
                    url: myUrl,
                    method: 'GET',
                    header: {
                        'content-type': 'application/json'
                    }
                }, function (err, res) {
                    console.log(res)
                });
            }
        )
        pm.environment.set(`sections`,sections);
    }

Is there any way to provide a callback within forEach, might appear something like given below code. Or is there any alternative to it.

    function callback() {
        console.log('callback');
    }

    _.forEach(
            urls,
            function (myUrl,callback) {
                pm.sendRequest({
                    url: myUrl,
                    method: 'GET',
                    header: {
                        'content-type': 'application/json'
                    }
                }, function (err, res) {
                    console.log(res)
                });
            }
        )
        pm.environment.set(`sections`,sections);
    }

I had initially thought that the response handling function at the end would take care of that but it doesn't.

Body:
Found it better to branch out the logic into another function getUrl and pass the callback into it.

Following code works:

_.forEach (
    urls,
    function (myUrl) {
        getUrl(myUrl,function (err,res) {
            if (err) {
                console.log(err);
            } else {
                console.log(JSON.stringify(res));
            }
        });
    }
);

function getUrl(myUrl, callback) {
    var call = {
        url: myUrl,
        method: 'GET',
        header: {
            "Authorization": `Bearer ${token}`,
            "Content-Type": "application/json"
        }
    };

    pm.sendRequest(
        call,
        function (err, res) {
            callback (err,res);
        }
    );
}


答:
What if we define a local variable </p>

```<code>               var counter = 1;
               (from h in db.Company where h.is_active == 1 select new CompanyFinal { id = h.id, name = h.name, selected =  (counter++ == 1 ? "true" :"false") }).ToList();
</code>```

Title: Set the first Record Value of LINQ

Body:
What if we define a local variable

               var counter = 1;
               (from h in db.Company where h.is_active == 1 select new CompanyFinal { id = h.id, name = h.name, selected =  (counter++ == 1 ? "true" :"false") }).ToList();


问:
View doesn't change after clicking on routerLink to child route angular 2
Hey I'm having this problem and I cant seem to figure out what is wrong, basically I have a routerLink that goes to a child route, the url changes to the route I want but the view doesn't update to the component that is linked to the child route that is currently active

app.component.ts

```<code><app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
</code>```

html

```<code><div class="wide component">
    <div class="page-wrap">
        <img class="logo" src="../../assets/img/our-work-component-logo.png"><br>
        <h2>Component Elite</h2>
        <h3>Web portal and promotions</h3>

        <p class="short-description">Lorem Ipsum</p>
        <a routerLink="component" class="button orange-button">View More</a>
    </div>
</div>
</code>```

app.module.ts

```<code>import { OurWorkComponent } from './our-work/our-work.component';
import { ComponentComponent } from './our-work-content/component/component.component'

export const ROUTES: Routes = [
  { path: 'our-work', component: OurWorkComponent,
      children: [
         { path: 'component', component: ComponentComponent }
      ]
  }
];

@ngModule({
  declarations: [
     OurWorkComponent,
     ComponentComponent
  ],
  imports: [
     BrowserModule,
     RouterModule.forRoot(ROUTES)
  ],
  providers: [],
  bootstrap: [AppComponent]
})
</code>```

答:
Reason it's not changing is because of children of OurWorkComponent

```<code>children: [
    { path: 'component', component: ComponentComponent }
]
</code>```

This means there should be <router-outlet> in OurWorkComponent, but I can't see it, just add that in OurWorkComponent's html and you are good to go.

For more details please do read : https://angular.io/guide/router#nesting-routes

Body:
Hey I'm having this problem and I cant seem to figure out what is wrong, basically I have a routerLink that goes to a child route, the url changes to the route I want but the view doesn't update to the component that is linked to the child route that is currently active

app.component.ts

<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>

html

Component Elite

Web portal and promotions

Lorem Ipsum

        View More

app.module.ts

import { OurWorkComponent } from './our-work/our-work.component';
import { ComponentComponent } from './our-work-content/component/component.component'

export const ROUTES: Routes = [
  { path: 'our-work', component: OurWorkComponent,
      children: [
         { path: 'component', component: ComponentComponent }
      ]
  }
];

@ngModule({
  declarations: [
     OurWorkComponent,
     ComponentComponent
  ],
  imports: [
     BrowserModule,
     RouterModule.forRoot(ROUTES)
  ],
  providers: [],
  bootstrap: [AppComponent]
})

Body:
Reason it's not changing is because of children of OurWorkComponent

children: [
    { path: 'component', component: ComponentComponent }
]

This means there should be <router-outlet> in OurWorkComponent, but I can't see it, just add that in OurWorkComponent's html and you are good to go.

For more details please do read : https://angular.io/guide/router#nesting-routes

ContentLicense: CC BY-SA 4.0


问:
How do you find the cluster & service CIDR of a Kubernetes cluster?
How do you find the cluster/service CIDR for a Kubernetes cluster, once it is already running?

I know for Minikube, it is 10.0.0.1/24.

For GKE, you can find out via

```<code>gcloud container clusters describe XXXXXXX --zone=XXXXXX |
  grep -e clusterIpv4Cidr -e servicesIpv4Cidr
</code>```

But how do you find out on a generic Kubernetes cluster, particularly via kubectl?

答:
I can't leave a comment yet cause of rep so I'm just gonna answer with what I've found.

For minikube it looks like the CIDR can change, specifically for me it has. I found the CIDR under the .minikube directory at

.minikube\profiles\minikube

For windows you can find that at:

C:\Users\YourUserName\.minikube\profiles\minikube

For linux and mac I'd assume it would be under the ~/.minikube dir.

In the dir there should be a file called config.json which has a json object "KubernetesConfig": {} with the following field: ServiceCIDR. The value of that should be the CIDR for your services.

Unfortunately I have no other tips for kubectl to find the CIDR, maybe it's more of a provider thing and dependent on where/how you're running kubernetes.

Body:
How do you find the cluster/service CIDR for a Kubernetes cluster, once it is already running?

I know for Minikube, it is 10.0.0.1/24.

For GKE, you can find out via

gcloud container clusters describe XXXXXXX --zone=XXXXXX |
  grep -e clusterIpv4Cidr -e servicesIpv4Cidr

But how do you find out on a generic Kubernetes cluster, particularly via kubectl?


问:
Fibonacci Modified:How to fix this algorithm?
I have this problem in front of me and I can't figure out how to solve it.
It's about the series 0,1,1,2,5,29,866... (Every number besides the first two is the sum of the squares of the previous two numbers (2^2+5^2=29)).
In the first part I had to write an algorithm (Not a native speaker so I don't really know the terminology) that would receive a place in the series and return it's value (6 returned 29)
This is how I wrote it:

```<code>public static int mod(int n)
{
    if (n==1)
        return 0;
    if (n==2)
        return 1;
    else
        return (int)(Math.pow(mod(n-1), 2))+(int)(Math.pow(mod(n-2), 2));
}
</code>```

However, now I need that the algorithm will receive a number and return the total sum up to it in the series (6- 29+5+2+1+1+0=38)
I have no idea how to do this, I am trying but I am really unable to understand recursion so far, even if I wrote something right, how can I check it to be sure? And how generally to reach the right algorithm?

Using any extra parameters is forbidden.

Thanks in advance!

答:
Here is my proposal.

We know that:

f(n) = 0;   n < 2

f(n) = 1;   2 >= n <= 3

f(n) = f(n-1)^2 + f(n-2)^2;   n>3

So:

```<code>f(0)= 0
f(1)= 0
f(2)= f(1) + f(0) = 1
f(3)= f(2) + f(1) = 1
f(4)= f(3) + f(2) = 2
f(5)= f(4) + f(3) = 5
and so on
</code>```

According with this behaivor we must implement a recursive function to return:

Total = sum f(n); n= 0:k; where k>0

I read you can use a static method but not use more than one parameter into the function. So, i used a static variable with the static method, just for control the execution of loop:

```<code>class Dummy
{

    public static void main (String[] args) throws InterruptedException {

        int n=10;

        for(int i=1; i<=n; i++)
        {
            System.out.println("--------------------------");
            System.out.println("Total for n:" + i +" = " + Dummy.f(i));
        }
    }

    private static int counter = 0;
    public static long f(int n)
    {
        counter++;

        if(counter == 1)
        {
            long total = 0;
            while(n>=0)
            {
                total +=  f(n);
                n--;
            }
            counter--;
            return total;
        }

        long result = 0;
        long n1=0,n2=0;

        if(n >= 2 && n <=3)
            result++; //Increase 1
        else if(n>3)
        {
            n1 = f(n-1);
            n2 = f(n-2);

            result = n1*n1 + n2*n2;
        }

        counter--;
        return result;
    }
}
</code>```

the output:

```<code>--------------------------
Total for n:1 = 0
--------------------------
Total for n:2 = 1
--------------------------
Total for n:3 = 2
--------------------------
Total for n:4 = 4
--------------------------
Total for n:5 = 9
--------------------------
Total for n:6 = 38
--------------------------
Total for n:7 = 904
--------------------------
Total for n:8 = 751701
--------------------------
Total for n:9 = 563697636866
--------------------------
Total for n:10 = 9011676203564263700
</code>```

I hope it helps you.

UPDATE: Here is another version without a static method and has the same output:

```<code>class Dummy
{

    public static void main (String[] args) throws InterruptedException {

        Dummy app = new Dummy();
        int n=10;

        for(int i=1; i<=n; i++)
        {
            System.out.println("--------------------------");
            System.out.println("Total for n:" + i +" = " + app.mod(i));
        }
    }

    private static int counter = 0;
    public long mod(int n)
    {
        Dummy.counter++;

        if(counter == 1)
        {
            long total = 0;
            while(n>=0)
            {
                total +=  mod(n);
                n--;
            }
            Dummy.counter--;
            return total;
        }

        long result = 0;
        long n1=0,n2=0;

        if(n >= 2 && n <=3)
            result++; //Increase 1
        else if(n>3)
        {
            n1 = mod(n-1);
            n2 = mod(n-2);

            result = n1*n1 + n2*n2;
        }

        Dummy.counter--;
        return result;
    }
}
</code>```

Body:
I have this problem in front of me and I can't figure out how to solve it.
It's about the series 0,1,1,2,5,29,866... (Every number besides the first two is the sum of the squares of the previous two numbers (2^2+5^2=29)).
In the first part I had to write an algorithm (Not a native speaker so I don't really know the terminology) that would receive a place in the series and return it's value (6 returned 29)
This is how I wrote it:

public static int mod(int n)
{
    if (n==1)
        return 0;
    if (n==2)
        return 1;
    else
        return (int)(Math.pow(mod(n-1), 2))+(int)(Math.pow(mod(n-2), 2));
}

However, now I need that the algorithm will receive a number and return the total sum up to it in the series (6- 29+5+2+1+1+0=38)
I have no idea how to do this, I am trying but I am really unable to understand recursion so far, even if I wrote something right, how can I check it to be sure? And how generally to reach the right algorithm?

Using any extra parameters is forbidden.

Thanks in advance!

Body:
Here is my proposal.

We know that:

f(n) = 0;   n < 2

f(n) = 1;   2 >= n <= 3

f(n) = f(n-1)^2 + f(n-2)^2;   n>3

So:

f(0)= 0
f(1)= 0
f(2)= f(1) + f(0) = 1
f(3)= f(2) + f(1) = 1
f(4)= f(3) + f(2) = 2
f(5)= f(4) + f(3) = 5
and so on

According with this behaivor we must implement a recursive function to return:

Total = sum f(n); n= 0:k; where k>0

I read you can use a static method but not use more than one parameter into the function. So, i used a static variable with the static method, just for control the execution of loop:

class Dummy
{

    public static void main (String[] args) throws InterruptedException {

        int n=10;

        for(int i=1; i<=n; i++)
        {
            System.out.println("--------------------------");
            System.out.println("Total for n:" + i +" = " + Dummy.f(i));
        }
    }

    private static int counter = 0;
    public static long f(int n)
    {
        counter++;

        if(counter == 1)
        {
            long total = 0;
            while(n>=0)
            {
                total +=  f(n);
                n--;
            }
            counter--;
            return total;
        }

        long result = 0;
        long n1=0,n2=0;

        if(n >= 2 && n <=3)
            result++; //Increase 1
        else if(n>3)
        {
            n1 = f(n-1);
            n2 = f(n-2);

            result = n1*n1 + n2*n2;
        }

        counter--;
        return result;
    }
}

the output:

--------------------------
Total for n:1 = 0
--------------------------
Total for n:2 = 1
--------------------------
Total for n:3 = 2
--------------------------
Total for n:4 = 4
--------------------------
Total for n:5 = 9
--------------------------
Total for n:6 = 38
--------------------------
Total for n:7 = 904
--------------------------
Total for n:8 = 751701
--------------------------
Total for n:9 = 563697636866
--------------------------
Total for n:10 = 9011676203564263700

I hope it helps you.

UPDATE: Here is another version without a static method and has the same output:

class Dummy
{

    public static void main (String[] args) throws InterruptedException {

        Dummy app = new Dummy();
        int n=10;

        for(int i=1; i<=n; i++)
        {
            System.out.println("--------------------------");
            System.out.println("Total for n:" + i +" = " + app.mod(i));
        }
    }

    private static int counter = 0;
    public long mod(int n)
    {
        Dummy.counter++;

        if(counter == 1)
        {
            long total = 0;
            while(n>=0)
            {
                total +=  mod(n);
                n--;
            }
            Dummy.counter--;
            return total;
        }

        long result = 0;
        long n1=0,n2=0;

        if(n >= 2 && n <=3)
            result++; //Increase 1
        else if(n>3)
        {
            n1 = mod(n-1);
            n2 = mod(n-2);

            result = n1*n1 + n2*n2;
        }

        Dummy.counter--;
        return result;
    }
}


问:
How powerful is OpenGL?
I want to create an application which will capture one by camera and will manipulate the live images taken by it in milliseconds of the time.

The goal is that the application should change my clothes with some other clothes which I will supply.

I have few questions:

Does OpenGL have such power of modifying live images in a way it will change my clothes in the computer image? I will be moving my hands and the like, can it be that accurate so it'll just look like I am in changed clothes and not the original I am wearing?

答: Is not a matter of power. OpenGL is for rendering 3D graphics. What you want is in the area of Computer Vision and Augmented Reality. Use the right tool for the task. You might want to take a look at OpenCV.</p>

Title: How powerful is OpenGL?


问:
Adjust div position fluidly as window width changes
I have a div with multiple absolute-positioned divs within it. I would like the left position of these inner divs to move fluidly as the window is resized. An example of what I have so far can be seen here: https://jsfiddle.net/ewqmfa4d/.

How can I do this? I presume I'd use jQuery? Note that I'm not looking for media queries, but rather something that provides fluid movement as the width of the window changes.

答:
I'm still note sure quite what you're looking for, but in order to modify the text offset, what you're looking to do is make use of a combination of .resize(), .width() and .css().

First check the current offset of $('#text'). Note that you might think that you can do this with $('#text').css("left"), but you'll actually need to make use of .position().

On load, you'll need to check the current size of the window, so you can work out whether the window is getting larger or smaller (meaning you're shrinking or growing it when resizing). You can compare these values against those in .resize() to work out whether the window is now larger or smaller.

Finally, you can set the left offset of the #text element with $("#text").css("left", text_offset += 10). Note that you increase the offset when shrinking the window, and decrease the offset when enlarging the window.

Here's an example putting all this together:

var w = 0;
var text_offset = $('#text').position().left;

$(document).ready(function() {
  w = $(window).width();
});

$(window).resize(function() {
  if (w > $(window).width()) {
    $("#text").css("left", text_offset += 10);
  } else {
    $("#text").css("left", text_offset -= 10);
  }
  w = $(window).width();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.top {
  font: "Arial Bold";
  font-weight: bolder;
  height: 300px;
  background-color: #000000;
  position: relative;
  text-align: center;
}

.top div {
  position: absolute;
}

#text {
  color: #c9d35f;
  top: 100px;
  left: 150px;
}

#text2 {
  color: #fa48bc;
  top: 175px;
  left: 250px;
}</code>```

My text

Other text

```

I've also created a snippet showcasing this here.

Note that you'll need to play around with the offset values, probably using 1 in place of 10 (because you drag by a single pixel)!

Hope this helps! :)

Body:
I'm still note sure quite what you're looking for, but in order to modify the text offset, what you're looking to do is make use of a combination of .resize(), .width() and .css().

First check the current offset of $('#text'). Note that you might think that you can do this with $('#text').css("left"), but you'll actually need to make use of .position().

On load, you'll need to check the current size of the window, so you can work out whether the window is getting larger or smaller (meaning you're shrinking or growing it when resizing). You can compare these values against those in .resize() to work out whether the window is now larger or smaller.

Finally, you can set the left offset of the #text element with $("#text").css("left", text_offset += 10). Note that you increase the offset when shrinking the window, and decrease the offset when enlarging the window.

Here's an example putting all this together:

var w = 0;
var text_offset = $('#text').position().left;

$(document).ready(function() {
  w = $(window).width();
});

$(window).resize(function() {
  if (w > $(window).width()) {
    $("#text").css("left", text_offset += 10);
  } else {
    $("#text").css("left", text_offset -= 10);
  }
  w = $(window).width();
});

.top {
  font: "Arial Bold";
  font-weight: bolder;
  height: 300px;
  background-color: #000000;
  position: relative;
  text-align: center;
}

.top div {
  position: absolute;
}

#text {
  color: #c9d35f;
  top: 100px;
  left: 150px;
}

#text2 {
  color: #fa48bc;
  top: 175px;
  left: 250px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='top'>
  <div id="text">My text</div>
  <div id="text2">Other text</div>
</div>

I've also created a snippet showcasing this here.

Note that you'll need to play around with the offset values, probably using 1 in place of 10 (because you drag by a single pixel)!

Hope this helps! :)


问:
Opening an XML file and highlighting a specific line
In visual basic I have created a database utility that does the following: Takes in a string to 'find' then it searches an entire netwrok drive of xml files containing that specific line of text. If the given text is found, I list the file path in a listview and you can double click to open the file.

All of that works perfectly as is. What I want to the software to do is when the user double clicks the file path and opens the file, I would like the line of text that was found to be highlighted right there for the user.

Is there any built-in utility in VB that would allow me to do that?

Thank you.

***Edit

The software loads the xml externally. Whatever the user has set as the default program for xml files is what gets loaded. Ideally the solution would allow me to continue doing this, but hey, maybe a rtb is the right option.

答:
For the RichTextBox option here is an example:

Public Sub SelectLine(ByVal lineIndex As Integer)
   MyRichTextBox1.HideSelection = False

   If lineIndex < 0 Then Exit Sub
   If lineIndex > MyRichTextBox1.Lines.Count Then Exit Sub

   MyRichTextBox1.SelectionStart = MyRichTextBox1.GetFirstCharIndexFromLine(lineIndex)
   MyRichTextBox1.SelectionLength = MyRichTextBox1.Lines(lineIndex).Length
End Sub
```

Note: lineIndex is zero based. Also this assumes this sub is on a form with MyRichTextBox1.    See this link for another example and the code on which this is based.

Body:
For the RichTextBox option here is an example:

Public Sub SelectLine(ByVal lineIndex As Integer)
   MyRichTextBox1.HideSelection = False

   If lineIndex < 0 Then Exit Sub
   If lineIndex > MyRichTextBox1.Lines.Count Then Exit Sub

   MyRichTextBox1.SelectionStart = MyRichTextBox1.GetFirstCharIndexFromLine(lineIndex)
   MyRichTextBox1.SelectionLength = MyRichTextBox1.Lines(lineIndex).Length
End Sub

Note: lineIndex is zero based. Also this assumes this sub is on a form with MyRichTextBox1.    See this link for another example and the code on which this is based.


问:
Decode JSON value which can be either string or number
When I make an HTTP call to a REST API I may get the JSON value count back as a Number or String. I'ld like to marshal it to be an integer in either case. How can I deal with this in Go?.

答:
Use the "string" field tag option to specify that strings should be converted to numbers. The  documentation for the option is:

The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs:

Here's an example use:

```<code>type S struct {
    Count int `json:"count,string"`
}
</code>```

playground example

If the JSON value can be number or string, then unmarshal to interface{} and convert to int after unmarshaling:

```<code>Count interface{} `json:"count,string"`
</code>```

Use this function to convert the interface{} value to an int:

```<code>func getInt(v interface{}) (int, error) {
  switch v := v.(type) {
  case float64:
    return int(v), nil
  case string:
    c, err := strconv.Atoi(v)
    if err != nil {
       return 0, err
    }
    return c, nil
  default:
    return 0, fmt.Errorf("conversion to int from %T not supported", v)
  }
}
</code>```

Body:
Use the "string" field tag option to specify that strings should be converted to numbers. The  documentation for the option is:

The "string" option signals that a field is stored as JSON inside a JSON-encoded string. It applies only to fields of string, floating point, integer, or boolean types. This extra level of encoding is sometimes used when communicating with JavaScript programs:

Here's an example use:

type S struct {
    Count int `json:"count,string"`
}

playground example

If the JSON value can be number or string, then unmarshal to interface{} and convert to int after unmarshaling:

Count interface{} `json:"count,string"`

Use this function to convert the interface{} value to an int:

func getInt(v interface{}) (int, error) {
  switch v := v.(type) {
  case float64:
    return int(v), nil
  case string:
    c, err := strconv.Atoi(v)
    if err != nil {
       return 0, err
    }
    return c, nil
  default:
    return 0, fmt.Errorf("conversion to int from %T not supported", v)
  }
}