问:
find a value in a block matrix
I wrote a sparse matrix class, based on Block compressed storage, I wrote almost all the method, but I have not idea to how to write the method findValue(i,j) that give 2 indexes of the original matrix ! the storage consists in four vectors :

`ba_': stored the non zero block (rectangular block in which almost one element is different from zero) of the matrix in top-down left-right order

an_ is the vector of index that points to the first element of the block in the vector ba

aj_ stored the index of the block columns in the blocked matrix.

ai_ stored the first block of each row in the blocked matrix.

the picture clarify anything :

here the following class in which I use two methods to achieve the result, findBlockIndex and findValue(i,j,Brows,Bcols) but I need to get the value of the original i,j index using findValue(i,j) in which i,j are the index in the sparse complete matrix

```<code> # include <iosfwd>
    # include <vector>
    # include <string>
    # include <initializer_list>
    # include "MatrixException.H"
    # include <sstream>
    # include <fstream>
    # include <algorithm>
    # include <iomanip>

    // forward declarations
    template <typename T, std::size_t R, std::size_t C>
    class BCRSmatrix ;

    template <typename T, std::size_t R, std::size_t C>
    std::ostream& operator<<(std::ostream& os , const BCRSmatrix<T,R,C>& m );

    template <typename T, std::size_t Br, std::size_t Bc >
    std::vector<T> operator*(const BCRSmatrix<T,Br,Bc>& m, const std::vector<T>& x );

    template <typename data_type, std::size_t BR , std::size_t BC>
    class BCRSmatrix {

          template <typename T, std::size_t R, std::size_t C>
          friend std::ostream& operator<<(std::ostream& os , const BCRSmatrix<T,R,C>& m );

          template <typename T, std::size_t Br,std::size_t Bc>
          friend std::vector<T> operator*(const BCRSmatrix<T,Br,Bc>& m, const std::vector<T>& x );

       public:

         constexpr BCRSmatrix(std::initializer_list<std::vector<data_type>> dense );

         constexpr BCRSmatrix(const std::string& );

         virtual ~BCRSmatrix() = default ;

         auto constexpr print_block(const std::vector<std::vector<data_type>>& dense,
                                      std::size_t i, std::size_t j) const noexcept ;

         auto constexpr validate_block(const std::vector<std::vector<data_type>>& dense,
                                      std::size_t i, std::size_t j) const noexcept ;

         auto constexpr insert_block(const std::vector<std::vector<data_type>>& dense,
                                                           std::size_t i, std::size_t j) noexcept ;

         auto constexpr printBCRS() const noexcept ;

         auto constexpr printBlockMatrix() const noexcept  ;

         auto constexpr size1() const noexcept { return denseRows ;}

         auto constexpr size2() const noexcept { return denseCols ;}

         auto constexpr printBlock(std::size_t i) const noexcept ;

         auto constexpr print() const noexcept ;

       private:

        std::size_t bn  ;
        std::size_t bBR ;
        std::size_t nnz ;
        std::size_t denseRows ;
        std::size_t denseCols ;

        std::vector<data_type>    ba_ ;
        std::vector<std::size_t>  an_ ;
        std::vector<std::size_t>  ai_ ;
        std::vector<std::size_t>  aj_ ;

        std::size_t index =0 ;

        auto constexpr findBlockIndex(const std::size_t r, const std::size_t c) const noexcept ;

        auto constexpr recomposeMatrix() const noexcept ;

        auto constexpr findValue(
                                  const std::size_t i, const std::size_t j,
                                  const std::size_t rBlock, const std::size_t cBlock
                                ) const noexcept ;

    };

    //---------------------------      IMPLEMENTATION
    template <typename T, std::size_t BR, std::size_t BC>
    constexpr BCRSmatrix<T,BR,BC>::BCRSmatrix(std::initializer_list<std::vector<T>> dense_ )
    {
          this->denseRows = dense_.size();
          auto it         = *(dense_.begin());
          this->denseCols = it.size();

          if( (denseRows*denseCols) % BR != 0 )
          {
                throw InvalidSizeException("Error block size is not multiple of dense matrix size");
          }

         std::vector<std::vector<T>> dense(dense_);
         bBR = BR*BC ;
         bn  = denseRows*denseCols/(BR*BC) ;

        ai_.resize(denseRows/BR +1);
        ai_[0] = 1;

        for(std::size_t i = 0; i < dense.size() / BR ; i++)
        {
            auto rowCount =0;
            for(std::size_t j = 0; j < dense[i].size() / BC ; j++)
            {
                if(validate_block(dense,i,j))
                {
                      aj_.push_back(j+1);
                      insert_block(dense, i, j);
                      rowCount ++ ;
                }

            }
            ai_[i+1] = ai_[i] + rowCount ;
         }
         printBCRS();
    }

    template <typename T, std::size_t BR, std::size_t BC>
    constexpr BCRSmatrix<T,BR,BC>::BCRSmatrix(const std::string& fname)
    {
        std::ifstream f(fname , std::ios::in);
        if(!f)
        {
           throw OpeningFileException("error opening file in constructor !");
        }
        else
        {
           std::vector<std::vector<T>> dense;
           std::string line, tmp;
           T elem = 0 ;
           std::vector<T> row;
           std::size_t i=0, j=0 ;

           while(getline(f, line))
           {
              row.clear();
              std::istringstream ss(line);
              if(i==0)
              {
                while(ss >> elem)
                {
                  row.push_back(elem);
                  j++;
                }
              }
              else
              {
                while(ss >> elem)
                  row.push_back(elem);
              }
              dense.push_back(row);
              i++;
           }

           this->denseRows = i;
           this->denseCols = j;

           bBR = BR*BR ;
           bn  = denseRows*denseCols/(BR*BC) ;

           ai_.resize(denseRows/BR +1);
           ai_[0] = 1;

           for(std::size_t i = 0; i < dense.size() / BR ; i++)
           {
              auto rowCount =0;
              for(std::size_t j = 0; j < dense[i].size() / BC ; j++)
              {
                  if(validate_block(dense,i,j))
                  {
                        aj_.push_back(j+1);
                        insert_block(dense, i, j);
                        rowCount ++ ;
                  }

              }
              ai_[i+1] = ai_[i] + rowCount ;
           }

        }
        printBCRS();

    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::printBlockMatrix() const noexcept
    {

          for(auto i=0 ; i < denseRows / BR ; i++)
          {
            for(auto j=1 ; j <= denseCols / BC  ; j++)
            {
                std::cout << findBlockIndex(i,j) << ' ' ;
            }
             std::cout << std::endl;
          }
    }

    template <typename T,std::size_t BR,std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::printBlock(std::size_t i) const noexcept
    {
       auto w = i-1 ;
       auto k = 0;
       for(std::size_t i = 0 ; i < BR ; ++i)
       {
          for(std::size_t j=0 ; j < BC ; ++j )
          {
              std::cout << std::setw(8) << ba_.at(an_.at(w)-1+k) << ' ';
              k++;
          }
       }
    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::print_block(const std::vector<std::vector<T>>& dense,
                                                           std::size_t i, std::size_t j) const noexcept
    {
       for(std::size_t m = i * BR ; m < BR * (i + 1); ++m)
       {
          for(std::size_t n = j * BC ; n < BC * (j + 1); ++n)
                      std::cout << dense[m][n] << ' ';
          std::cout << '\n';
       }
    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::validate_block(const std::vector<std::vector<T>>& dense,
                                                           std::size_t i, std::size_t j) const noexcept
    {
       bool nonzero = false ;
       for(std::size_t m = i * BR ; m < BR * (i + 1); ++m)
       {
          for(std::size_t n = j * BC ; n < BC * (j + 1); ++n)
          {
                if(dense[m][n] != 0) nonzero = true;
          }
       }
       return nonzero ;
    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::insert_block(const std::vector<std::vector<T>>& dense,
                                                           std::size_t i, std::size_t j) noexcept
    {

       bool firstElem = true ;
       for(std::size_t m = i * BR ; m < BR * (i + 1); ++m)
       {
          for(std::size_t n = j * BC ; n < BC * (j + 1); ++n)
          {
                if(firstElem)
                {
                      an_.push_back(index+1);
                      firstElem = false ;
                }
                ba_.push_back(dense[m][n]);
                index ++ ;
          }
       }
    }

    template <typename T, std::size_t BR,std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::findBlockIndex(const std::size_t r, const std::size_t c) const noexcept
    {
          for(auto j= ai_.at(r) ; j < ai_.at(r+1) ; j++ )
          {
             if( aj_.at(j-1) == c  )
             {
                return j ;
             }
          }
    }

    template <typename T, std::size_t BR, std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::printBCRS() const noexcept
    {

      std::cout << "ba_ :   " ;
      for(auto &x : ba_ )
          std::cout << x << ' ' ;
        std::cout << std::endl;

      std::cout << "an_ :   " ;
      for(auto &x : an_ )
          std::cout <<  x << ' ' ;
        std::cout << std::endl;

      std::cout << "aj_ :   " ;
      for(auto &x : aj_ )
          std::cout <<  x << ' ' ;
        std::cout << std::endl;

       std::cout << "ai_ :   " ;
       for(auto &x : ai_ )
          std::cout << x << ' ' ;
        std::cout << std::endl;

    }

    template <typename T, std::size_t BR, std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::print() const noexcept
    {
        //for each BCRS row
        for(auto i=0 ; i < denseRows / BR ; i++){
            //for each Block sub row.
            for(auto rBlock = 0; rBlock < BR; rBlock++){
                //for each BCSR col.
                for(auto j = 1; j <= denseCols / BC; j++){
                    //for each Block sub col.
                    for(auto cBlock = 0; cBlock < BC; cBlock++){
                        std::cout<< findValue(i, j, rBlock, cBlock) <<'\t';
                    }
                }
                std::cout << std::endl;
            }
        }
    }

    template <typename T, std::size_t BR,std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::recomposeMatrix() const noexcept
    {

        std::vector<std::vector<T>> sparseMat(denseRows, std::vector<T>(denseCols, 0));
        auto BA_i = 0, AJ_i = 0;
        //for each BCSR row
        for(auto r = 0; r < denseRows/BR; r++){
            //for each Block in row
            for(auto nBlock = 0; nBlock < ai_.at(r+1)-ai_.at(r); nBlock++){
                //for each subMatrix (Block)
                for(auto rBlock = 0; rBlock < BR; rBlock++){
                    for(auto cBlock = 0; cBlock < BC; cBlock++){
                        //insert value
                        sparseMat.at(rBlock + r*BR).at(cBlock + (aj_.at(AJ_i)-1)*BC) = ba_.at(BA_i);
                        ++BA_i;
                    }
                }
            ++AJ_i;
            }
        }
        return sparseMat;
    }

    template <typename T, std::size_t BR,std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::findValue(
                                               const std::size_t i, const std::size_t j,
                                               const std::size_t rBlock, const std::size_t cBlock
                                              ) const noexcept
    {
        auto index = findBlockIndex(i,j);
        if(index != 0)
            return ba_.at(an_.at(index-1)-1 + cBlock + rBlock*BC);
        else
          return T(0);
    }

    template <typename T, std::size_t BR,std::size_t BC>
    std::ostream& operator<<(std::ostream& os , const BCRSmatrix<T,BR,BC>& m )
    {
        for(auto i=0 ; i < m.denseRows / BR ; i++)
        {
            //for each Block sub row.
            for(auto rBlock = 0; rBlock < BR; rBlock++)
            {
                //for each BCSR col.
                for(auto j = 1; j <= m.denseCols / BC; j++)
                {
                    //for each Block sub col.
                    for(auto cBlock = 0; cBlock < BC; cBlock++)
                    {
                        os << m.findValue(i, j, rBlock, cBlock) <<'\t';
                    }
                }
                os << std::endl;
            }
        }
        return os;
    }

    template <typename T, std::size_t BR, std::size_t BC>
    std::vector<T> operator*(const BCRSmatrix<T,BR,BC>& m, const std::vector<T>& x )
    {
          std::vector<T> y(x.size());
          if(m.size1() != x.size())
          {
           std::string to = "x" ;
           std::string mess = "Error occured in operator* attempt to perfor productor between op1: "
                            + std::to_string(m.size1()) + to + std::to_string(m.size2()) +
                                     " and op2: " + std::to_string(x.size());
                throw InvalidSizeException(mess.c_str());
          }
          else
          {
                auto brows = m.denseRows/BR ;
                auto bnze  = m.an_.size()   ;

                auto z=0;

                for(auto b=0 ; b < brows ; b++)
                {
                   for(auto j= m.ai_.at(b) ; j <= m.ai_.at(b+1)-1; j++ )
                   {
                      for(auto k=0 ; k < BR ; k++ )
                      {
                         for(auto t=0 ; t < BC ; t++)
                         {
                             y.at(BC*b+k) += m.ba_.at(z) * x.at(BC*(m.aj_.at(j-1)-1)+t) ;
                             z++ ;
                         }
                      }
                   }
                }

          }
          return y;

    }
</code>```

and this is the main

```<code># include "BCSmatrix.H"

using namespace std;

int main(){

  BCRSmatrix<int,2,2> bbcsr1 =  {{11,12,13,14,0,0},{0,22,23,0,0,0},{0,0,33,34,35,36},{0,0,0,44,45,0},
                           {0,0,0,0,0,56},{0,0,0,0,0,66}};

  BCRSmatrix<int,2,2> bbcsr2 = {{11,12,0,0,0,0,0,0} ,{0,22,0,0,0,0,0,0} ,{31,32,33,0,0,0,0,0},
                              {41,42,43,44,0,0,0,0}, {0,0,0,0,55,56,0,0},{0,0,0,0,0,66,67,0},{0,0,0,0,0,0,77,78},{0,0,0,0,0,0,87,88}};

  BCRSmatrix<int,2,4> bbcsr3 = {{11,12,0,0,0,0,0,0} ,{0,22,0,0,0,0,0,0} ,{31,32,33,0,0,0,0,0},
                              {41,42,43,44,0,0,0,0}, {0,0,0,0,55,56,0,0},{0,0,0,0,0,66,67,0},{0,0,0,0,0,0,77,78},{0,0,0,0,0,0,87,88}};

  bbcsr3.printBlockMatrix();

  bbcsr3.print();

  BCRSmatrix<int,2,2> bbcsr4("input17.dat");

  bbcsr4.printBlockMatrix();

  BCRSmatrix<int,2,4> bbcsr5("input18.dat");

  bbcsr5.printBlockMatrix();
  cout << bbcsr5 ;

  BCRSmatrix<int,4,4> bbcsr6("input18.dat");

  bbcsr6.printBlockMatrix();

  bbcsr6.print();

  cout << bbcsr4 ; //.print();

  BCRSmatrix<int,2,4> bbcsr7("input20.dat");

  cout << bbcsr7;

  bbcsr7.printBlockMatrix();

  std::vector<int> v1 = {3,4,0,1,6,8,1,19};

  std::vector<int> v01 = {3,4,0,1,6,8,1,19,15,2};

  std::vector<int> v2 = bbcsr4 *v1 ;

  for(auto& x : v2)
        cout << x << ' ' ;
  cout << endl;

  BCRSmatrix<double,2,2> bbcsr8("input21.dat");

  bbcsr8.print() ;
  bbcsr8.printBlockMatrix();

  return 0;
}
</code>```

答:
how to write the method findValue(i,j) that give 2 indexes of the original matrix

It is similar to the previous findValue method:

```<code>template <typename T, std::size_t BR,std::size_t BC>
auto constexpr BCRSmatrix<T,BR,BC>::myNewfindValue(const std::size_t i, const std::size_t j) const noexcept{
    auto index = findBlockIndex(i/BR, j/BC);
    if(index != 0)
        return ba_.at(an_.at(index-1)-1 + j%BC + (i%BR)*BC);
    else
        return T(0);
}
</code>```

To recall this function: you have to do a little change to your findBlockIndex: just change if( aj_.at(j-1) == c  ) whit if( aj_.at(j-1) == c+1  ), than you have to modify your for statements in the others functions for(auto j = 1; j <= .. whit for(auto j = 0; j < ...

Let me know if there are problems or this is not the answer you were looking for.
I hope to be of help to you,

best regards Marco.

Title: find a value in a block matrix

Body:
I wrote a sparse matrix class, based on Block compressed storage, I wrote almost all the method, but I have not idea to how to write the method findValue(i,j) that give 2 indexes of the original matrix ! the storage consists in four vectors :

`ba_': stored the non zero block (rectangular block in which almost one element is different from zero) of the matrix in top-down left-right order

an_ is the vector of index that points to the first element of the block in the vector ba

aj_ stored the index of the block columns in the blocked matrix.

ai_ stored the first block of each row in the blocked matrix.

the picture clarify anything :

here the following class in which I use two methods to achieve the result, findBlockIndex and findValue(i,j,Brows,Bcols) but I need to get the value of the original i,j index using findValue(i,j) in which i,j are the index in the sparse complete matrix

 # include <iosfwd>
    # include <vector>
    # include <string>
    # include <initializer_list>
    # include "MatrixException.H"
    # include <sstream>
    # include <fstream>
    # include <algorithm>
    # include <iomanip>

    // forward declarations
    template <typename T, std::size_t R, std::size_t C>
    class BCRSmatrix ;

    template <typename T, std::size_t R, std::size_t C>
    std::ostream& operator<<(std::ostream& os , const BCRSmatrix<T,R,C>& m );

    template <typename T, std::size_t Br, std::size_t Bc >
    std::vector<T> operator*(const BCRSmatrix<T,Br,Bc>& m, const std::vector<T>& x );

    template <typename data_type, std::size_t BR , std::size_t BC>
    class BCRSmatrix {

          template <typename T, std::size_t R, std::size_t C>
          friend std::ostream& operator<<(std::ostream& os , const BCRSmatrix<T,R,C>& m );

          template <typename T, std::size_t Br,std::size_t Bc>
          friend std::vector<T> operator*(const BCRSmatrix<T,Br,Bc>& m, const std::vector<T>& x );

       public:

         constexpr BCRSmatrix(std::initializer_list<std::vector<data_type>> dense );

         constexpr BCRSmatrix(const std::string& );

         virtual ~BCRSmatrix() = default ;

         auto constexpr print_block(const std::vector<std::vector<data_type>>& dense,
                                      std::size_t i, std::size_t j) const noexcept ;

         auto constexpr validate_block(const std::vector<std::vector<data_type>>& dense,
                                      std::size_t i, std::size_t j) const noexcept ;

         auto constexpr insert_block(const std::vector<std::vector<data_type>>& dense,
                                                           std::size_t i, std::size_t j) noexcept ;

         auto constexpr printBCRS() const noexcept ;

         auto constexpr printBlockMatrix() const noexcept  ;

         auto constexpr size1() const noexcept { return denseRows ;}

         auto constexpr size2() const noexcept { return denseCols ;}

         auto constexpr printBlock(std::size_t i) const noexcept ;

         auto constexpr print() const noexcept ;

       private:

        std::size_t bn  ;
        std::size_t bBR ;
        std::size_t nnz ;
        std::size_t denseRows ;
        std::size_t denseCols ;

        std::vector<data_type>    ba_ ;
        std::vector<std::size_t>  an_ ;
        std::vector<std::size_t>  ai_ ;
        std::vector<std::size_t>  aj_ ;

        std::size_t index =0 ;

        auto constexpr findBlockIndex(const std::size_t r, const std::size_t c) const noexcept ;

        auto constexpr recomposeMatrix() const noexcept ;

        auto constexpr findValue(
                                  const std::size_t i, const std::size_t j,
                                  const std::size_t rBlock, const std::size_t cBlock
                                ) const noexcept ;

    };

    //---------------------------      IMPLEMENTATION
    template <typename T, std::size_t BR, std::size_t BC>
    constexpr BCRSmatrix<T,BR,BC>::BCRSmatrix(std::initializer_list<std::vector<T>> dense_ )
    {
          this->denseRows = dense_.size();
          auto it         = *(dense_.begin());
          this->denseCols = it.size();

          if( (denseRows*denseCols) % BR != 0 )
          {
                throw InvalidSizeException("Error block size is not multiple of dense matrix size");
          }

         std::vector<std::vector<T>> dense(dense_);
         bBR = BR*BC ;
         bn  = denseRows*denseCols/(BR*BC) ;

        ai_.resize(denseRows/BR +1);
        ai_[0] = 1;

        for(std::size_t i = 0; i < dense.size() / BR ; i++)
        {
            auto rowCount =0;
            for(std::size_t j = 0; j < dense[i].size() / BC ; j++)
            {
                if(validate_block(dense,i,j))
                {
                      aj_.push_back(j+1);
                      insert_block(dense, i, j);
                      rowCount ++ ;
                }

            }
            ai_[i+1] = ai_[i] + rowCount ;
         }
         printBCRS();
    }

    template <typename T, std::size_t BR, std::size_t BC>
    constexpr BCRSmatrix<T,BR,BC>::BCRSmatrix(const std::string& fname)
    {
        std::ifstream f(fname , std::ios::in);
        if(!f)
        {
           throw OpeningFileException("error opening file in constructor !");
        }
        else
        {
           std::vector<std::vector<T>> dense;
           std::string line, tmp;
           T elem = 0 ;
           std::vector<T> row;
           std::size_t i=0, j=0 ;

           while(getline(f, line))
           {
              row.clear();
              std::istringstream ss(line);
              if(i==0)
              {
                while(ss >> elem)
                {
                  row.push_back(elem);
                  j++;
                }
              }
              else
              {
                while(ss >> elem)
                  row.push_back(elem);
              }
              dense.push_back(row);
              i++;
           }

           this->denseRows = i;
           this->denseCols = j;

           bBR = BR*BR ;
           bn  = denseRows*denseCols/(BR*BC) ;

           ai_.resize(denseRows/BR +1);
           ai_[0] = 1;

           for(std::size_t i = 0; i < dense.size() / BR ; i++)
           {
              auto rowCount =0;
              for(std::size_t j = 0; j < dense[i].size() / BC ; j++)
              {
                  if(validate_block(dense,i,j))
                  {
                        aj_.push_back(j+1);
                        insert_block(dense, i, j);
                        rowCount ++ ;
                  }

              }
              ai_[i+1] = ai_[i] + rowCount ;
           }

        }
        printBCRS();

    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::printBlockMatrix() const noexcept
    {

          for(auto i=0 ; i < denseRows / BR ; i++)
          {
            for(auto j=1 ; j <= denseCols / BC  ; j++)
            {
                std::cout << findBlockIndex(i,j) << ' ' ;
            }
             std::cout << std::endl;
          }
    }

    template <typename T,std::size_t BR,std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::printBlock(std::size_t i) const noexcept
    {
       auto w = i-1 ;
       auto k = 0;
       for(std::size_t i = 0 ; i < BR ; ++i)
       {
          for(std::size_t j=0 ; j < BC ; ++j )
          {
              std::cout << std::setw(8) << ba_.at(an_.at(w)-1+k) << ' ';
              k++;
          }
       }
    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::print_block(const std::vector<std::vector<T>>& dense,
                                                           std::size_t i, std::size_t j) const noexcept
    {
       for(std::size_t m = i * BR ; m < BR * (i + 1); ++m)
       {
          for(std::size_t n = j * BC ; n < BC * (j + 1); ++n)
                      std::cout << dense[m][n] << ' ';
          std::cout << '\n';
       }
    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::validate_block(const std::vector<std::vector<T>>& dense,
                                                           std::size_t i, std::size_t j) const noexcept
    {
       bool nonzero = false ;
       for(std::size_t m = i * BR ; m < BR * (i + 1); ++m)
       {
          for(std::size_t n = j * BC ; n < BC * (j + 1); ++n)
          {
                if(dense[m][n] != 0) nonzero = true;
          }
       }
       return nonzero ;
    }

    template <typename T,std::size_t BR, std::size_t BC>
    inline auto constexpr BCRSmatrix<T,BR,BC>::insert_block(const std::vector<std::vector<T>>& dense,
                                                           std::size_t i, std::size_t j) noexcept
    {

       bool firstElem = true ;
       for(std::size_t m = i * BR ; m < BR * (i + 1); ++m)
       {
          for(std::size_t n = j * BC ; n < BC * (j + 1); ++n)
          {
                if(firstElem)
                {
                      an_.push_back(index+1);
                      firstElem = false ;
                }
                ba_.push_back(dense[m][n]);
                index ++ ;
          }
       }
    }

    template <typename T, std::size_t BR,std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::findBlockIndex(const std::size_t r, const std::size_t c) const noexcept
    {
          for(auto j= ai_.at(r) ; j < ai_.at(r+1) ; j++ )
          {
             if( aj_.at(j-1) == c  )
             {
                return j ;
             }
          }
    }

    template <typename T, std::size_t BR, std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::printBCRS() const noexcept
    {

      std::cout << "ba_ :   " ;
      for(auto &x : ba_ )
          std::cout << x << ' ' ;
        std::cout << std::endl;

      std::cout << "an_ :   " ;
      for(auto &x : an_ )
          std::cout <<  x << ' ' ;
        std::cout << std::endl;

      std::cout << "aj_ :   " ;
      for(auto &x : aj_ )
          std::cout <<  x << ' ' ;
        std::cout << std::endl;

       std::cout << "ai_ :   " ;
       for(auto &x : ai_ )
          std::cout << x << ' ' ;
        std::cout << std::endl;

    }

    template <typename T, std::size_t BR, std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::print() const noexcept
    {
        //for each BCRS row
        for(auto i=0 ; i < denseRows / BR ; i++){
            //for each Block sub row.
            for(auto rBlock = 0; rBlock < BR; rBlock++){
                //for each BCSR col.
                for(auto j = 1; j <= denseCols / BC; j++){
                    //for each Block sub col.
                    for(auto cBlock = 0; cBlock < BC; cBlock++){
                        std::cout<< findValue(i, j, rBlock, cBlock) <<'\t';
                    }
                }
                std::cout << std::endl;
            }
        }
    }

    template <typename T, std::size_t BR,std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::recomposeMatrix() const noexcept
    {

        std::vector<std::vector<T>> sparseMat(denseRows, std::vector<T>(denseCols, 0));
        auto BA_i = 0, AJ_i = 0;
        //for each BCSR row
        for(auto r = 0; r < denseRows/BR; r++){
            //for each Block in row
            for(auto nBlock = 0; nBlock < ai_.at(r+1)-ai_.at(r); nBlock++){
                //for each subMatrix (Block)
                for(auto rBlock = 0; rBlock < BR; rBlock++){
                    for(auto cBlock = 0; cBlock < BC; cBlock++){
                        //insert value
                        sparseMat.at(rBlock + r*BR).at(cBlock + (aj_.at(AJ_i)-1)*BC) = ba_.at(BA_i);
                        ++BA_i;
                    }
                }
            ++AJ_i;
            }
        }
        return sparseMat;
    }

    template <typename T, std::size_t BR,std::size_t BC>
    auto constexpr BCRSmatrix<T,BR,BC>::findValue(
                                               const std::size_t i, const std::size_t j,
                                               const std::size_t rBlock, const std::size_t cBlock
                                              ) const noexcept
    {
        auto index = findBlockIndex(i,j);
        if(index != 0)
            return ba_.at(an_.at(index-1)-1 + cBlock + rBlock*BC);
        else
          return T(0);
    }

    template <typename T, std::size_t BR,std::size_t BC>
    std::ostream& operator<<(std::ostream& os , const BCRSmatrix<T,BR,BC>& m )
    {
        for(auto i=0 ; i < m.denseRows / BR ; i++)
        {
            //for each Block sub row.
            for(auto rBlock = 0; rBlock < BR; rBlock++)
            {
                //for each BCSR col.
                for(auto j = 1; j <= m.denseCols / BC; j++)
                {
                    //for each Block sub col.
                    for(auto cBlock = 0; cBlock < BC; cBlock++)
                    {
                        os << m.findValue(i, j, rBlock, cBlock) <<'\t';
                    }
                }
                os << std::endl;
            }
        }
        return os;
    }

    template <typename T, std::size_t BR, std::size_t BC>
    std::vector<T> operator*(const BCRSmatrix<T,BR,BC>& m, const std::vector<T>& x )
    {
          std::vector<T> y(x.size());
          if(m.size1() != x.size())
          {
           std::string to = "x" ;
           std::string mess = "Error occured in operator* attempt to perfor productor between op1: "
                            + std::to_string(m.size1()) + to + std::to_string(m.size2()) +
                                     " and op2: " + std::to_string(x.size());
                throw InvalidSizeException(mess.c_str());
          }
          else
          {
                auto brows = m.denseRows/BR ;
                auto bnze  = m.an_.size()   ;

                auto z=0;

                for(auto b=0 ; b < brows ; b++)
                {
                   for(auto j= m.ai_.at(b) ; j <= m.ai_.at(b+1)-1; j++ )
                   {
                      for(auto k=0 ; k < BR ; k++ )
                      {
                         for(auto t=0 ; t < BC ; t++)
                         {
                             y.at(BC*b+k) += m.ba_.at(z) * x.at(BC*(m.aj_.at(j-1)-1)+t) ;
                             z++ ;
                         }
                      }
                   }
                }

          }
          return y;

    }

and this is the main

# include "BCSmatrix.H"

using namespace std;

int main(){

  BCRSmatrix<int,2,2> bbcsr1 =  {{11,12,13,14,0,0},{0,22,23,0,0,0},{0,0,33,34,35,36},{0,0,0,44,45,0},
                           {0,0,0,0,0,56},{0,0,0,0,0,66}};

  BCRSmatrix<int,2,2> bbcsr2 = {{11,12,0,0,0,0,0,0} ,{0,22,0,0,0,0,0,0} ,{31,32,33,0,0,0,0,0},
                              {41,42,43,44,0,0,0,0}, {0,0,0,0,55,56,0,0},{0,0,0,0,0,66,67,0},{0,0,0,0,0,0,77,78},{0,0,0,0,0,0,87,88}};

  BCRSmatrix<int,2,4> bbcsr3 = {{11,12,0,0,0,0,0,0} ,{0,22,0,0,0,0,0,0} ,{31,32,33,0,0,0,0,0},
                              {41,42,43,44,0,0,0,0}, {0,0,0,0,55,56,0,0},{0,0,0,0,0,66,67,0},{0,0,0,0,0,0,77,78},{0,0,0,0,0,0,87,88}};

  bbcsr3.printBlockMatrix();

  bbcsr3.print();

  BCRSmatrix<int,2,2> bbcsr4("input17.dat");

  bbcsr4.printBlockMatrix();

  BCRSmatrix<int,2,4> bbcsr5("input18.dat");

  bbcsr5.printBlockMatrix();
  cout << bbcsr5 ;

  BCRSmatrix<int,4,4> bbcsr6("input18.dat");

  bbcsr6.printBlockMatrix();

  bbcsr6.print();

  cout << bbcsr4 ; //.print();

  BCRSmatrix<int,2,4> bbcsr7("input20.dat");

  cout << bbcsr7;

  bbcsr7.printBlockMatrix();

  std::vector<int> v1 = {3,4,0,1,6,8,1,19};

  std::vector<int> v01 = {3,4,0,1,6,8,1,19,15,2};

  std::vector<int> v2 = bbcsr4 *v1 ;

  for(auto& x : v2)
        cout << x << ' ' ;
  cout << endl;

  BCRSmatrix<double,2,2> bbcsr8("input21.dat");

  bbcsr8.print() ;
  bbcsr8.printBlockMatrix();

  return 0;
}

Body:
how to write the method findValue(i,j) that give 2 indexes of the original matrix

It is similar to the previous findValue method:

template <typename T, std::size_t BR,std::size_t BC>
auto constexpr BCRSmatrix<T,BR,BC>::myNewfindValue(const std::size_t i, const std::size_t j) const noexcept{
    auto index = findBlockIndex(i/BR, j/BC);
    if(index != 0)
        return ba_.at(an_.at(index-1)-1 + j%BC + (i%BR)*BC);
    else
        return T(0);
}

To recall this function: you have to do a little change to your findBlockIndex: just change if( aj_.at(j-1) == c  ) whit if( aj_.at(j-1) == c+1  ), than you have to modify your for statements in the others functions for(auto j = 1; j <= .. whit for(auto j = 0; j < ...

Let me know if there are problems or this is not the answer you were looking for.
I hope to be of help to you,

best regards Marco.


来源: stackexchange

问:
Use exec to execute a file inside a function with globals()
I need to execute a file inside a python shell.

I can

```<code>exec(open('Test.py').read())
</code>```

But I need to call it from inside a function.

"Test.py" will set variable C=10

So,

```<code>#x.py
def load(file):
    exec(open(file).read(),globals())

>>> import x
>>> x.load('Test.py')
>>> C
>>> NameError: name 'C' is not defined
</code>```

I have passed in the globals, but I still cant access the varibales from exec.
References:

In Python, why doesn't an import in an exec in a function work?

How to execute a file within the python interpreter?

答:
use import instead

```<code>from Test import C
print C
</code>```

EDIT:

If Test.py is in a different directory, you have to modify the sys.path

```<code>import sys.path
sys.path.insert(0, "path_to_directory")

from Test import C
print C
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to execute a file inside a python shell.

I can

exec(open('Test.py').read())

But I need to call it from inside a function.

"Test.py" will set variable C=10

So,

#x.py
def load(file):
    exec(open(file).read(),globals())

>>> import x
>>> x.load('Test.py')
>>> C
>>> NameError: name 'C' is not defined

I have passed in the globals, but I still cant access the varibales from exec.
References:

In Python, why doesn't an import in an exec in a function work?

How to execute a file within the python interpreter?

Body:
use import instead

from Test import C
print C

EDIT:

If Test.py is in a different directory, you have to modify the sys.path

import sys.path
sys.path.insert(0, "path_to_directory")

from Test import C
print C


问:
SQL for applying conditions to multiple rows in a join
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

```<code>SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');
</code>```

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

答:
Ok, stating the problem again.

"Find users that have entries in the tags table for both tag1 and tag2". This means at least 2 rows in the child tags table for each user table entry

Solution 1: The intersection of "users with tag1" and "users with tag2"

```<code>SELECT u.*
FROM
    users u INNER JOIN
    (
    SELECT user_id FROM tags WHERE name = 'tag1'
    INTERSECT
    SELECT user_id FROM tags WHERE name = 'tag2'
    ) t ON u.id = t.user_id
</code>```

Solution 2: EXISTS

```<code>SELECT u.*
FROM
    users u
WHERE
    EXISTS (SELECT * FROM tags t1 WHERE t1.name = 'tag1'
                     AND u.id = t1.user_id)
    AND
    EXISTS (SELECT * FROM tags t2 WHERE t2.name = 'tag2'
                     AND u.id = t2.user_id)
</code>```

Solution 3: JOIN

```<code>SELECT u.* FROM
   users u
   INNER JOIN
   tags as t1 on t1.user_id = u.id
   INNER JOIN
   tags as t2 on t2.user_id = u.id
WHERE
   t1.name='tag1' AND t2.name='tag2'
</code>```

Solution 4: IN

```<code>SELECT u.*
FROM
    users u
WHERE
    u.id (SELECT t1.user_id FROM tags t1 WHERE t1.name = 'tag1')
    AND
    u.id (SELECT t2.user_id FROM tags t2 WHERE t2.name = 'tag2')
</code>```

All The EXISTS, INTERSECT and IN should give the same execution plan in SQL Server

Now, these are all for the case where you are looking for 2 tags. As you want more tags, they become cumbersome so use shahkalpesh's solution.

However, I'd modify it so the tags are in a table and no extra OR clauses are needed

```<code>SELECT u.*
FROM
    Users u
    Inner join
    tags t ON t.user_id = u.id
    JOIN
    @MyTags mt ON t.name = mt.name
GROUP BY u.*
HAVING count(tags.*) = COUNT(DISTINCT mt.name)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I think I found the answer to my question, I'm just unsure of the syntax, I keep getting SQL errors.

Basically, I want to do the opposite of IN. Take this example:

SELECT *
  FROM users INNER JOIN
       tags ON tags.user_id = users.id
 WHERE tags.name IN ('tag1', 'tag2');

The above will return ANY users that have 'tag1' OR 'tag2'. I want users that have BOTH. They must have both tags to be returned. I'm assuming the keyword ALL should be used, but can't get it to work.

Thanks for your help.

Body:
Ok, stating the problem again.

"Find users that have entries in the tags table for both tag1 and tag2". This means at least 2 rows in the child tags table for each user table entry

Solution 1: The intersection of "users with tag1" and "users with tag2"

SELECT u.*
FROM
    users u INNER JOIN
    (
    SELECT user_id FROM tags WHERE name = 'tag1'
    INTERSECT
    SELECT user_id FROM tags WHERE name = 'tag2'
    ) t ON u.id = t.user_id

Solution 2: EXISTS

SELECT u.*
FROM
    users u
WHERE
    EXISTS (SELECT * FROM tags t1 WHERE t1.name = 'tag1'
                     AND u.id = t1.user_id)
    AND
    EXISTS (SELECT * FROM tags t2 WHERE t2.name = 'tag2'
                     AND u.id = t2.user_id)

Solution 3: JOIN

SELECT u.* FROM
   users u
   INNER JOIN
   tags as t1 on t1.user_id = u.id
   INNER JOIN
   tags as t2 on t2.user_id = u.id
WHERE
   t1.name='tag1' AND t2.name='tag2'

Solution 4: IN

SELECT u.*
FROM
    users u
WHERE
    u.id (SELECT t1.user_id FROM tags t1 WHERE t1.name = 'tag1')
    AND
    u.id (SELECT t2.user_id FROM tags t2 WHERE t2.name = 'tag2')

All The EXISTS, INTERSECT and IN should give the same execution plan in SQL Server

Now, these are all for the case where you are looking for 2 tags. As you want more tags, they become cumbersome so use shahkalpesh's solution.

However, I'd modify it so the tags are in a table and no extra OR clauses are needed

SELECT u.*
FROM
    Users u
    Inner join
    tags t ON t.user_id = u.id
    JOIN
    @MyTags mt ON t.name = mt.name
GROUP BY u.*
HAVING count(tags.*) = COUNT(DISTINCT mt.name)


问:
How to extract values from list to add to another list in python
I have the following code:

```<code>items = list()
for i in response['Contents']:
    items[i].append('s3://' + response['Name'] + '/' + i['Key'])
    items[i].append(i['Key'].rsplit('/', 1)[-1])
    items[i].append(i['Size'])
</code>```

response['Contents'] has a schema like this:

```<code>{u'LastModified': datetime.datetime(, tzinfo=tzlocal()),
 u'ETag': '"tag"',
 u'StorageClass': 'STANDARD',
 u'Key': u'filepath/1/something.jpeg',
 u'Owner':
      {u'DisplayName': 'a', u'ID': 'b'},
 u'Size': 32}
</code>```

Basically, I want an output of a 3-value tuple, [[value1, value2, value3], [value1, value2, value3]...].

How can I extract the values correctly?
(I'll be using zip with another list that has column names to create a dict later).

答:
As this question is open I'm gonna give my take: I'd write it as this:</p>

```<code>import os

items = []
s1 = 's3://{Name}/{{Key}}'.format(**response)

for i in response['Contents']:

    v1 = s1.format(name,**i)
    v2 = os.path.basename(i['Key'])
    v3 = i['Size']

    items.append([v1,v2,v3])
</code>```

Body:
I have the following code:

items = list()
for i in response['Contents']:
    items[i].append('s3://' + response['Name'] + '/' + i['Key'])
    items[i].append(i['Key'].rsplit('/', 1)[-1])
    items[i].append(i['Size'])

response['Contents'] has a schema like this:

{u'LastModified': datetime.datetime(, tzinfo=tzlocal()),
 u'ETag': '"tag"',
 u'StorageClass': 'STANDARD',
 u'Key': u'filepath/1/something.jpeg',
 u'Owner':
      {u'DisplayName': 'a', u'ID': 'b'},
 u'Size': 32}

Basically, I want an output of a 3-value tuple, [[value1, value2, value3], [value1, value2, value3]...].

How can I extract the values correctly?
(I'll be using zip with another list that has column names to create a dict later).

Body:
As this question is open I'm gonna give my take: I'd write it as this:

import os

items = []
s1 = 's3://{Name}/{{Key}}'.format(**response)

for i in response['Contents']:

    v1 = s1.format(name,**i)
    v2 = os.path.basename(i['Key'])
    v3 = i['Size']

    items.append([v1,v2,v3])


问:
Excel VBA Userform If Focus Changes Trigger
I have a couple user forms in VBA, id like to add a feature that when a user first clicks on a textbox (changes the focus to it), any text inside gets selected. I've seen this feature in some accounting applications and in your web browser when you first click the URL bar. Its essentially meant so that users can immediately overwrite a text field. Was wondering how I might do the same in VBA, but I'm still a novice. I looked through a couple sub triggers(dont know the correct term) but haven't seen any. I found one for when you click the text box but I don't want the text constantly being selected every time I click the field.
Thanks.</p>

答:
put this in your textbox event

```<code>Dim checked As Boolean

Private Sub TextBox1_Change()
    If checked = True Then
        TextBox1.SelStart = 0
        TextBox1.SelLength = 0
    checked = True
    End If
End Sub

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    checked = False
End Sub

Private Sub TextBox1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    If checked = False Then
        TextBox1.SelStart = 0
        TextBox1.SelLength = Len(TextBox1)
        checked = True
    End If
End Sub
</code>```

once you click your textbox, it will hightlight the text, if you click the text, it will unhightlight and allow you to modified the text. if you click outside that textbox and click back inside that will rehighlight the whole text.

Body:
put this in your textbox event

Dim checked As Boolean

Private Sub TextBox1_Change()
    If checked = True Then
        TextBox1.SelStart = 0
        TextBox1.SelLength = 0
    checked = True
    End If
End Sub

Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
    checked = False
End Sub

Private Sub TextBox1_MouseDown(ByVal Button As Integer, ByVal Shift As Integer, ByVal X As Single, ByVal Y As Single)
    If checked = False Then
        TextBox1.SelStart = 0
        TextBox1.SelLength = Len(TextBox1)
        checked = True
    End If
End Sub

once you click your textbox, it will hightlight the text, if you click the text, it will unhightlight and allow you to modified the text. if you click outside that textbox and click back inside that will rehighlight the whole text.


问:
Bokeh plot is deactivated when user clicks in DataTable, and there's no proper way to activate the plot
When I use a DataTable in my bokeh application, the plots on my page become decativated whenever I click inside the datatable. This happens with editable=True and editable=False.

The only way that I found to activate the plot again is to click the "Reset" tool button.

Questions:

Am I doing something wrong in my Bokeh app?

Has anyone else encountered this, and found a workaround? (a Javascript workaround, perhaps?)

Screen shot (notice the deactivated color in the plot):

The complete bokeh app is below, run with bokeh serve --show filename.py:

```<code>from datetime import datetime, timedelta

import numpy as np
import pandas as pd
import bokeh
from bokeh.layouts import widgetbox, row, layout
from bokeh.models import ColumnDataSource, Button, DataTable, TableColumn, Paragraph
from bokeh.models.widgets.tables import DateFormatter, StringEditor
from bokeh.plotting import curdoc, figure

def create_dataframe(number_of_series, number_of_values):
    t0 = datetime(2017, 1, 1)
    data = {
        "timestamp": [t0 + (i * timedelta(seconds=3600*2)) for i in range(number_of_values)]
    }
    data.update({
        "col{}".format(i): np.random.rand(number_of_values)
        for i in range(number_of_series)
    })
    return pd.DataFrame(data).set_index("timestamp")

source = ColumnDataSource(create_dataframe(10, 1000))

btn = Button(label="Click Me")

my_figure = figure(x_axis_type="datetime")
my_figure.line(y="col0", x="timestamp", source=source)

data_table = DataTable(editable=True, source=source, columns=[
    TableColumn(title="Timestamp", field="timestamp", formatter=DateFormatter(format="%Y-%m-%d %H:%M:%S"), editor=StringEditor()),
    TableColumn(title="col0", field="col0")
])

page_layout = layout([
    [widgetbox(Paragraph(text="Bokeh version: {}".format(bokeh.__version__)))],
    [widgetbox(btn), my_figure],
    [data_table]
])

curdoc().add_root(page_layout)
</code>```

答:
This is actually the intended behaviour behind using a bokeh ColumnDataSource. When you select a row in the table, that is registered in the data source selected attribute. see

https://docs.bokeh.org/en/latest/docs/user_guide/data.html#columndatasource

You cant notice this at first because there are a large number of data points on the plot - any one isnt visible when selected.Try shift click and select multiple rows, and you will see segments of the plot turn dark blue - corresponding to those rows.

The simplest way to prevent the behaviour is to use seperate data sources.

If you wanted them to be the same, you would have to restore the source.selected dictionary each time it is updated, which seems pointless.

```<code>from datetime import datetime, timedelta

import numpy as np
import pandas as pd
import bokeh
from bokeh.layouts import widgetbox, row, layout
from bokeh.models import ColumnDataSource, Button, DataTable, TableColumn, Paragraph
from bokeh.models.widgets.tables import DateFormatter, StringEditor
from bokeh.plotting import curdoc, figure

def create_dataframe(number_of_series, number_of_values):
    t0 = datetime(2017, 1, 1)
    data = {
        "timestamp": [t0 + (i * timedelta(seconds=3600*2)) for i in range(number_of_values)]
    }
    data.update({
        "col{}".format(i): np.random.rand(number_of_values)
        for i in range(number_of_series)
    })
    return pd.DataFrame(data).set_index("timestamp")

source = ColumnDataSource(create_dataframe(10, 1000))

sourcetable = ColumnDataSource(create_dataframe(10, 1000))

btn = Button(label="Click Me")

my_figure = figure(x_axis_type="datetime")
my_figure.line(y="col0", x="timestamp", source=source)

data_table = DataTable(editable=True, reorderable=False, source=sourcetable, columns=[
    TableColumn(title="Timestamp", field="timestamp", formatter=DateFormatter(format="%Y-%m-%d %H:%M:%S"), editor=StringEditor()),
    TableColumn(title="col0", field="col0")
])

page_layout = layout([
    [widgetbox(Paragraph(text="Bokeh version: {}".format(bokeh.__version__)))],
    [widgetbox(btn), my_figure],
    [data_table]
])

curdoc().add_root(page_layout)
</code>```

Body:
When I use a DataTable in my bokeh application, the plots on my page become decativated whenever I click inside the datatable. This happens with editable=True and editable=False.

The only way that I found to activate the plot again is to click the "Reset" tool button.

Questions:

Am I doing something wrong in my Bokeh app?

Has anyone else encountered this, and found a workaround? (a Javascript workaround, perhaps?)

Screen shot (notice the deactivated color in the plot):

The complete bokeh app is below, run with bokeh serve --show filename.py:

from datetime import datetime, timedelta

import numpy as np
import pandas as pd
import bokeh
from bokeh.layouts import widgetbox, row, layout
from bokeh.models import ColumnDataSource, Button, DataTable, TableColumn, Paragraph
from bokeh.models.widgets.tables import DateFormatter, StringEditor
from bokeh.plotting import curdoc, figure

def create_dataframe(number_of_series, number_of_values):
    t0 = datetime(2017, 1, 1)
    data = {
        "timestamp": [t0 + (i * timedelta(seconds=3600*2)) for i in range(number_of_values)]
    }
    data.update({
        "col{}".format(i): np.random.rand(number_of_values)
        for i in range(number_of_series)
    })
    return pd.DataFrame(data).set_index("timestamp")

source = ColumnDataSource(create_dataframe(10, 1000))

btn = Button(label="Click Me")

my_figure = figure(x_axis_type="datetime")
my_figure.line(y="col0", x="timestamp", source=source)

data_table = DataTable(editable=True, source=source, columns=[
    TableColumn(title="Timestamp", field="timestamp", formatter=DateFormatter(format="%Y-%m-%d %H:%M:%S"), editor=StringEditor()),
    TableColumn(title="col0", field="col0")
])

page_layout = layout([
    [widgetbox(Paragraph(text="Bokeh version: {}".format(bokeh.__version__)))],
    [widgetbox(btn), my_figure],
    [data_table]
])

curdoc().add_root(page_layout)

Body:
This is actually the intended behaviour behind using a bokeh ColumnDataSource. When you select a row in the table, that is registered in the data source selected attribute. see

https://docs.bokeh.org/en/latest/docs/user_guide/data.html#columndatasource

You cant notice this at first because there are a large number of data points on the plot - any one isnt visible when selected.Try shift click and select multiple rows, and you will see segments of the plot turn dark blue - corresponding to those rows.

The simplest way to prevent the behaviour is to use seperate data sources.

If you wanted them to be the same, you would have to restore the source.selected dictionary each time it is updated, which seems pointless.

from datetime import datetime, timedelta

import numpy as np
import pandas as pd
import bokeh
from bokeh.layouts import widgetbox, row, layout
from bokeh.models import ColumnDataSource, Button, DataTable, TableColumn, Paragraph
from bokeh.models.widgets.tables import DateFormatter, StringEditor
from bokeh.plotting import curdoc, figure

def create_dataframe(number_of_series, number_of_values):
    t0 = datetime(2017, 1, 1)
    data = {
        "timestamp": [t0 + (i * timedelta(seconds=3600*2)) for i in range(number_of_values)]
    }
    data.update({
        "col{}".format(i): np.random.rand(number_of_values)
        for i in range(number_of_series)
    })
    return pd.DataFrame(data).set_index("timestamp")

source = ColumnDataSource(create_dataframe(10, 1000))

sourcetable = ColumnDataSource(create_dataframe(10, 1000))

btn = Button(label="Click Me")

my_figure = figure(x_axis_type="datetime")
my_figure.line(y="col0", x="timestamp", source=source)

data_table = DataTable(editable=True, reorderable=False, source=sourcetable, columns=[
    TableColumn(title="Timestamp", field="timestamp", formatter=DateFormatter(format="%Y-%m-%d %H:%M:%S"), editor=StringEditor()),
    TableColumn(title="col0", field="col0")
])

page_layout = layout([
    [widgetbox(Paragraph(text="Bokeh version: {}".format(bokeh.__version__)))],
    [widgetbox(btn), my_figure],
    [data_table]
])

curdoc().add_root(page_layout)

ContentLicense: CC BY-SA 4.0


问:
Modeling velocity and height of rocket c++
Hi We are supposed to model the height and velocity of a rocket in c++ for our final project. Having user input the total flight time and delta time for the points during flight that they wish to measure. The following is the code I have written for this project. The velocity is supposed to start positive and after 60 seconds at which point there is no fuel left and thus no thrust the velocity should start becoming negative. However both my height and velocity are coming out as negative from the start and reaching negative infinite by the end.

```<code>#include <iostream>
using namespace std;
int main()
{
    float *v;
    float *h;
    float a;

    double mass=0.0, thrust, time, dt;
    double g = 32.2;
    double K = 0.008;

    cout << "enter time";
    cin >> time;
    cout << "enter dt";
    cin >> dt;

    a = (time/dt);
    v = new float[a];
    h = new float[a];

    v[0] = 0;
    h[0] = 0;
    float tt = 0;

    // for loop to calculate velocity and time
    for(int i = 0; i <= (time/dt) ; i++)
    {
        tt = dt + tt;

        if( tt <= 60)
        {
            mass = (3000-(40*tt)/g);
            thrust = 7000;
        }
        if ( tt > 60)
        {
            mass = 3000/g;
            thrust = 0;
        }

        // these are the formulas for velocity and height position our prof gave us
        v[i+1] = v[i] - (K/mass)*v[i]*v[i-1] * dt + (thrust/mass - g)*dt;
        h[i+1] = v[i+1] * dt + h[i];
    }

    // for loop to output
    for(int i = 0; i <= (time/dt); i++)
    {
        cout << i << " - " << "Velocity:" << v[i+1] << " Position:" << h[i+1] <<endl;
    }
    return 0;
}
</code>```

sample output:

```<code>enter time120
enter dt.01
0 - Velocity:-0.298667 Position:-0.00298667
1 - Velocity:-0.597333 Position:-0.00896
2 - Velocity:-0.895999 Position:-0.01792
3 - Velocity:-1.19467 Position:-0.0298666
4 - Velocity:-1.49333 Position:-0.0448
5 - Velocity:-1.792 Position:-0.0627199
6 - Velocity:-2.09066 Position:-0.0836266
7 - Velocity:-2.38933 Position:-0.10752

<...i left out a lot of numbers in the middle to not make this post too long...>

11994 - Velocity:-inf Position:-inf
11995 - Velocity:-inf Position:-inf
11996 - Velocity:-inf Position:-inf
11997 - Velocity:-inf Position:-inf
11998 - Velocity:-inf Position:-inf
11999 - Velocity:-inf Position:-inf
12000 - Velocity:-inf Position:-inf
Program ended with exit code: 0
</code>```

I have compared with my friends who are getting good results and we can not determine a difference between their code and mine. I have the rest of my program complete and working fine I just cannot figure out why my calculations are wrong

答:
Ignoring the out-of-bounds access to v[-1] when i is zero, there is something wrong with your thrust, mass, or g.

thrust is 7000, mass is 3000 at time = 0.  That means thrust/mass is just over 2.  With g=32 (really? you are doing rocketry calculations in imperial units?), that means the rocket never has enough thrust to counter gravity, and just sits on the pad.

Edit:  That would be reality.  Because this is a fairly simple simulation, and doesn't include a "pad", in the model the rocket starts free-falling to the centre of the earth.

Body:
Hi We are supposed to model the height and velocity of a rocket in c++ for our final project. Having user input the total flight time and delta time for the points during flight that they wish to measure. The following is the code I have written for this project. The velocity is supposed to start positive and after 60 seconds at which point there is no fuel left and thus no thrust the velocity should start becoming negative. However both my height and velocity are coming out as negative from the start and reaching negative infinite by the end.

#include <iostream>
using namespace std;
int main()
{
    float *v;
    float *h;
    float a;

    double mass=0.0, thrust, time, dt;
    double g = 32.2;
    double K = 0.008;

    cout << "enter time";
    cin >> time;
    cout << "enter dt";
    cin >> dt;

    a = (time/dt);
    v = new float[a];
    h = new float[a];

    v[0] = 0;
    h[0] = 0;
    float tt = 0;

    // for loop to calculate velocity and time
    for(int i = 0; i <= (time/dt) ; i++)
    {
        tt = dt + tt;

        if( tt <= 60)
        {
            mass = (3000-(40*tt)/g);
            thrust = 7000;
        }
        if ( tt > 60)
        {
            mass = 3000/g;
            thrust = 0;
        }

        // these are the formulas for velocity and height position our prof gave us
        v[i+1] = v[i] - (K/mass)*v[i]*v[i-1] * dt + (thrust/mass - g)*dt;
        h[i+1] = v[i+1] * dt + h[i];
    }

    // for loop to output
    for(int i = 0; i <= (time/dt); i++)
    {
        cout << i << " - " << "Velocity:" << v[i+1] << " Position:" << h[i+1] <<endl;
    }
    return 0;
}

sample output:

enter time120
enter dt.01
0 - Velocity:-0.298667 Position:-0.00298667
1 - Velocity:-0.597333 Position:-0.00896
2 - Velocity:-0.895999 Position:-0.01792
3 - Velocity:-1.19467 Position:-0.0298666
4 - Velocity:-1.49333 Position:-0.0448
5 - Velocity:-1.792 Position:-0.0627199
6 - Velocity:-2.09066 Position:-0.0836266
7 - Velocity:-2.38933 Position:-0.10752

<...i left out a lot of numbers in the middle to not make this post too long...>

11994 - Velocity:-inf Position:-inf
11995 - Velocity:-inf Position:-inf
11996 - Velocity:-inf Position:-inf
11997 - Velocity:-inf Position:-inf
11998 - Velocity:-inf Position:-inf
11999 - Velocity:-inf Position:-inf
12000 - Velocity:-inf Position:-inf
Program ended with exit code: 0

I have compared with my friends who are getting good results and we can not determine a difference between their code and mine. I have the rest of my program complete and working fine I just cannot figure out why my calculations are wrong


问:
Force SSL for Django Postgres connection
I want to force Django to use SSL to connect to my postgres database.

This question indicates that I need to pass sslmode='require' to the psycopg2 connect call.  How do I add this to Django's database paremeters?

答:
Add 'OPTIONS': {'sslmode': 'require'}, to your database config.  For example:

```<code>DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': "db_name",
        'USER': "db_username",
        'PASSWORD': "db_password",
        'HOST': "db_host",
        'OPTIONS': {'sslmode': 'require'},
    },
}
</code>```

As jklingen92 points out, if you are using a database URL, such as through django-environ, add ?sslmode=require to the end of your database URL.  For example:

```<code>postgres://<DB_USERNAME>:<DB_PASSWORD>@<DB_HOST>:<PORT>/<DB_NAME>?sslmode=require
</code>```

Body:
Add 'OPTIONS': {'sslmode': 'require'}, to your database config.  For example:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': "db_name",
        'USER': "db_username",
        'PASSWORD': "db_password",
        'HOST': "db_host",
        'OPTIONS': {'sslmode': 'require'},
    },
}

As jklingen92 points out, if you are using a database URL, such as through django-environ, add ?sslmode=require to the end of your database URL.  For example:

postgres://<DB_USERNAME>:<DB_PASSWORD>@<DB_HOST>:<PORT>/<DB_NAME>?sslmode=require


答:
with df as your data frame</p>

```<code>df_iscase = df[df.is_case]

def transform(se):
    remaining = df.loc[se.name:]
    if len(remaining) < 2: # check if not last value
        return np.nan
    remaining = remaining.iloc[1:] # grab all next value (removing self)
    remaining = remaining[remaining.value_b >= se.value_a] # all where b >= a
    if len(remaining) < 1: # if not any
        return np.nan
    return remaining.iloc[0].name # return first value where b >= a

df_iscase.apply(transform, axis=1)
</code>```

Title: Returning a pandas DataFrame with the indexes of first next cases of >= value

Body:
Initial DataFrame

index        is_case        value_a         value_b
03/01/2005      True    0.598081665     0.189099313
04/01/2005     False    0.480809369     0.142255603
05/01/2005     False    0.963128886     0.422756089
06/01/2005     False    0.687675456     0.739599384
07/01/2005      True    0.513017431     0.397303797
08/01/2005      True    0.691884131     0.922642361
09/01/2005     False    0.659555415     0.222993436
10/01/2005     False    0.920539474     0.553573214
11/01/2005     False    0.360990121     0.535021421
12/01/2005     False    0.512528553     0.343931584
13/01/2005     False    0.083391071     0.277004714
14/01/2005     False    0.382696661     0.204780359
15/01/2005     False    0.838666246     0.337101306
16/01/2005      True    0.363920089     0.355211134
17/01/2005     False    0.354853214     0.691884131
18/01/2005     False    0.089324832     0.910276245
19/01/2005     False    0.611991454     0.513667459
20/01/2005      True    0.210785609     0.839849547

Desired Output:

The important thing about the output is to contain the column output and the index. Other columns may or may not be in the output.

index        is_case        value_a         value_b          output
03/01/2005      True    0.598081665     0.189099313      06/01/2005
07/01/2005      True    0.513017431     0.397303797      08/01/2005
08/01/2005      True    0.691884131     0.922642361      17/01/2005
16/01/2005      True    0.363920089     0.355211134      17/01/2005
20/01/2005      True    0.210785609     0.839849547             NaN

Transformation Logic

Get the value_a of all rows where is_case is True and search from the next row onwards for a value_b which is greater or equal than value_a, it returns the first index that meets this criteria in column output.

Body:
with df as your data frame

df_iscase = df[df.is_case]

def transform(se):
    remaining = df.loc[se.name:]
    if len(remaining) < 2: # check if not last value
        return np.nan
    remaining = remaining.iloc[1:] # grab all next value (removing self)
    remaining = remaining[remaining.value_b >= se.value_a] # all where b >= a
    if len(remaining) < 1: # if not any
        return np.nan
    return remaining.iloc[0].name # return first value where b >= a

df_iscase.apply(transform, axis=1)


问:
Passing one vector element as function parameter
i would like to pass a vector element at a certain position as a function argument, to generate a string. With that string I would like to open a file.
Right now my vector is filled with some strings, I print them with cout, the user should type a number and with the vector element at this position should the other function be called.

```<code>vector <string> kurzbez;                    //vector definition

void datei_oeffnen(string* var[]);          //function definition

cout << ("Bitte die Zahl eingeben") << endl;
cin >> kurs_auswahl;                        //Type in Number
cout << endl;

datei_oeffnen(kurzbez.at(kurs_auswahl))     //function call with problem
</code>```

I expect that the function is called with the vector element at the specific iterator.

The result i'm getting is this error at compiling: 69   41  D:\main.cpp [Error] cannot convert 'std::basic_string' to 'std::string** {aka std::basic_string}' for argument '1' to 'void datei_oeffnen(std::string)'

I've tried to wrap my head around that error and searched several days, but to no avail. Could somebody more knowledgeable help me?

I'm using Dev-C++  5.8.2 with GCC 4.8.1.

答: Change the argument from string *[] to just string (or even better string const &), for what you are doing there is no need to pass a pointer to the element in the vector.</p>

Body:
i would like to pass a vector element at a certain position as a function argument, to generate a string. With that string I would like to open a file.
Right now my vector is filled with some strings, I print them with cout, the user should type a number and with the vector element at this position should the other function be called.

vector <string> kurzbez;                    //vector definition

void datei_oeffnen(string* var[]);          //function definition

cout << ("Bitte die Zahl eingeben") << endl;
cin >> kurs_auswahl;                        //Type in Number
cout << endl;

datei_oeffnen(kurzbez.at(kurs_auswahl))     //function call with problem

I expect that the function is called with the vector element at the specific iterator.

The result i'm getting is this error at compiling: 69   41  D:\main.cpp [Error] cannot convert 'std::basic_string' to 'std::string** {aka std::basic_string}' for argument '1' to 'void datei_oeffnen(std::string)'

I've tried to wrap my head around that error and searched several days, but to no avail. Could somebody more knowledgeable help me?

I'm using Dev-C++  5.8.2 with GCC 4.8.1.


问:
Auto Refresh Crystal Report and Send to TV screen
I am running Crystal Reports 2008. I want to be able to automatically refresh a report every 10 minutes and send the updated output to a television screen in a hallway to keep employees updated. Does anyone know how to achieve this?</p>

答: Go to the File menu and make sure that "Save Data With Report" is turned off </p>


问:
How to write an algorithm to check if the sum of any two numbers in an array/list matches a given number?
How can I write an algorithm to check if the sum of any two numbers in an array/list matches a given number
with a complexity of nlogn?

答:
Solved the question in Swift 4.0

Solved in 3 different ways (with 2 different type of return -> Boolean and Indexes)

A) TimeComplexity => 0(n Log n) SpaceComplexity => 0(n).

B) TimeComplexity => 0(n^2) SpaceComplexity => 0(1).

C) TimeComplexity => 0(n) SpaceComplexity => 0(n)

Choose Solution A, B or C depending on TradeOff.

```<code>//***********************Solution A*********************//
//This solution returns TRUE if any such two pairs exist in the array
func binarySearch(list: [Int], key: Int, start: Int, end: Int) -> Int? { //Helper Function

            if end < start {
                return -1
            } else {
                let midIndex = (start + end) / 2

                if list[midIndex] > key {
                    return binarySearch(list: list, key: key, start: start, end:  midIndex - 1)
                } else if list[midIndex] < key {
                    return binarySearch(list: list, key: key, start: midIndex + 1, end: end)
                } else {
                    return midIndex
                }
            }
        }

        func twoPairSum(sum : Int, inputArray: [Int]) -> Bool {

            //Do this only if array isn't Sorted!
            let sortedArray = inputArray.sorted()

            for (currentIndex, value)  in sortedArray.enumerated() {
                if let indexReturned =  binarySearch(list: sortedArray, key: sum - value, start: 0, end: sortedArray.count-1) {
                    if indexReturned != -1 && (indexReturned != currentIndex) {
                        return true
                    }
                }
            }
            return false
        }

 //***********************Solution B*********************//
 //This solution returns the indexes of the two pair elements if any such two pairs exists in the array
 func twoPairSum(_ nums: [Int], _ target: Int) -> [Int] {

            for currentIndex in 0..<nums.count {
                for nextIndex in currentIndex+1..<nums.count {
                    if calculateSum(firstElement: nums[currentIndex], secondElement: nums[nextIndex], target: target) {
                        return [currentIndex, nextIndex]
                    }
                }
            }

            return []
        }

        func calculateSum (firstElement: Int, secondElement: Int, target: Int) -> Bool {//Helper Function
            return (firstElement + secondElement) == target
        }

    //*******************Solution C*********************//
   //This solution returns the indexes of the two pair elements if any such two pairs exists in the array
   func twoPairSum(_ nums: [Int], _ target: Int) -> [Int] {

            var dict = [Int: Int]()

            for (index, value) in nums.enumerated() {
                dict[value] = index
            }

            for (index, value) in nums.enumerated() {
                let otherIndex = dict[(target - value)]
                if otherIndex != nil && otherIndex != index {
                    return [index, otherIndex!]
                }
            }

            return []
        }
</code>```

Body:
Solved the question in Swift 4.0

Solved in 3 different ways (with 2 different type of return -> Boolean and Indexes)

A) TimeComplexity => 0(n Log n) SpaceComplexity => 0(n).

B) TimeComplexity => 0(n^2) SpaceComplexity => 0(1).

C) TimeComplexity => 0(n) SpaceComplexity => 0(n)

Choose Solution A, B or C depending on TradeOff.

//***********************Solution A*********************//
//This solution returns TRUE if any such two pairs exist in the array
func binarySearch(list: [Int], key: Int, start: Int, end: Int) -> Int? { //Helper Function

            if end < start {
                return -1
            } else {
                let midIndex = (start + end) / 2

                if list[midIndex] > key {
                    return binarySearch(list: list, key: key, start: start, end:  midIndex - 1)
                } else if list[midIndex] < key {
                    return binarySearch(list: list, key: key, start: midIndex + 1, end: end)
                } else {
                    return midIndex
                }
            }
        }

        func twoPairSum(sum : Int, inputArray: [Int]) -> Bool {

            //Do this only if array isn't Sorted!
            let sortedArray = inputArray.sorted()

            for (currentIndex, value)  in sortedArray.enumerated() {
                if let indexReturned =  binarySearch(list: sortedArray, key: sum - value, start: 0, end: sortedArray.count-1) {
                    if indexReturned != -1 && (indexReturned != currentIndex) {
                        return true
                    }
                }
            }
            return false
        }

 //***********************Solution B*********************//
 //This solution returns the indexes of the two pair elements if any such two pairs exists in the array
 func twoPairSum(_ nums: [Int], _ target: Int) -> [Int] {

            for currentIndex in 0..<nums.count {
                for nextIndex in currentIndex+1..<nums.count {
                    if calculateSum(firstElement: nums[currentIndex], secondElement: nums[nextIndex], target: target) {
                        return [currentIndex, nextIndex]
                    }
                }
            }

            return []
        }

        func calculateSum (firstElement: Int, secondElement: Int, target: Int) -> Bool {//Helper Function
            return (firstElement + secondElement) == target
        }

    //*******************Solution C*********************//
   //This solution returns the indexes of the two pair elements if any such two pairs exists in the array
   func twoPairSum(_ nums: [Int], _ target: Int) -> [Int] {

            var dict = [Int: Int]()

            for (index, value) in nums.enumerated() {
                dict[value] = index
            }

            for (index, value) in nums.enumerated() {
                let otherIndex = dict[(target - value)]
                if otherIndex != nil && otherIndex != index {
                    return [index, otherIndex!]
                }
            }

            return []
        }


问:
Only search DataTables on valid query
If I have a searchable $().dataTable object, how can I prevent the search from firing on invalid data?

For example, suppose I want the search to only be executed when all of the search's characters are numbers.

答:
You can override the default event handler(s) and use isNaN() to evaluate the input :

var table = $('#example').DataTable({
  initComplete: function() {
    var api = this.api();
    $('.dataTables_filter input').unbind().bind('keyup', function() {
      if (!isNaN(this.value)) {
        api.search(this.value).draw()
      }
    })
  }
})
```

Title: Only search DataTables on valid query


问:
Panel events won't work in c#
Hi all
I'm struggling with some problem in a project from college.
I'm building a "4 in a row" game in c# for a project in my c# course at my college.

I have created a Form named GameForm and inside it I added a Panel named panelBoardGame.
to that panelBoardGame I added an array of labels to be clickable (to execute a move) and i added a matrix of labels too , to represent the Board itself.

Now, my mission is whenever the mouse is inside the Panel area, the CoinImage of a certain player is moving along with the Cursor as long it is inside the panel area. when the mouse is outside the area, the CoinImage wont show.

To do so I tried triggering the onMouseEnter,OnMouseLeave events of the panelBoardGame, but somehow they wont even get executed.
Whenever my mouse is inside the panelBoardGame area the code inside panelBoardGame_MouseMove(......) function doesn't get executed.

Anyone could help me with that?

Since im new here i cant post images, but ive uploaded the image to here Image of the Form

Here is the image of the Form, inside it with a border in black around it is the panel and inside the panel i added labels

答: Let me guess, your labels completely cover the the area of the panel.  In Windows only the top control receives mouse events.  So when the mouse is over one of your labels the mouse events go to the label, not to the panel that contains the label.  So set a MouseMove event handler on your labels and you'll see that execute.</p>

Title: Panel events won't work in c#


问:
wpf datagrid rowheader expander togglebuttton style from resource dictionary
I have a WPF DataGrid with RowDetails which uses the RowHeader Expander to expand/collapse the RowDetails.
I am trying to set the style of the RowHeader Expander ToggleButton to a ToggleButton style defined in a resource dictionary. I tried this:

```<code><DataGrid.RowHeaderTemplate>
<DataTemplate>
    <Expander Expanded="Expander_Expanded" Collapsed="Expander_Collapsed" >
        <Style TargetType="ToggleButton" BasedOn="{StaticResource ExpandCollapseToggleStyle}" />
    </Expander>
</DataTemplate>
</code>```

This compiles but does not change the style of the ToggleButton.

答:
It's not quite that easy.  If you are forcing an Expander into your RowHeaderTemplate, you need to style the actual Expander object in order to have an impact on the ToggleButton buried within it.

Given below is the default styling for the Expander object in the Aero.Normal WPF theme.  Using that as a base, you can then modify the ToggleButton contained within.

```<code><Style x:Key="{x:Type Expander}"
       TargetType="{x:Type Expander}">
    <Setter Property="Foreground"
            Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
    <Setter Property="Background"
            Value="Transparent"/>
    <Setter Property="HorizontalContentAlignment"
            Value="Stretch"/>
    <Setter Property="VerticalContentAlignment"
            Value="Stretch"/>
    <Setter Property="BorderBrush"
            Value="Transparent"/>
    <Setter Property="BorderThickness"
            Value="1"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Expander}">
                <Border BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        Background="{TemplateBinding Background}"
                        CornerRadius="3"
                        SnapsToDevicePixels="true">
                    <DockPanel>
                        <ToggleButton x:Name="HeaderSite"
                                      DockPanel.Dock="Top"
                                      Margin="1"
                                      MinWidth="0"
                                      MinHeight="0"
                                      Style="{StaticResource ExpanderDownHeaderStyle}"
                                      FocusVisualStyle="{StaticResource ExpanderHeaderFocusVisual}"
                                      IsChecked="{Binding Path=IsExpanded,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}"
                                      Content="{TemplateBinding Header}"
                                      ContentTemplate="{TemplateBinding HeaderTemplate}"
                                      ContentTemplateSelector="{TemplateBinding HeaderTemplateSelector}"
                                      Foreground="{TemplateBinding Foreground}"
                                      Padding="{TemplateBinding Padding}"
                                      FontFamily="{TemplateBinding FontFamily}"
                                      FontSize="{TemplateBinding FontSize}"
                                      FontStyle="{TemplateBinding FontStyle}"
                                      FontStretch="{TemplateBinding FontStretch}"
                                      FontWeight="{TemplateBinding FontWeight}"
                                      HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                                      VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        <ContentPresenter x:Name="ExpandSite"
                                          DockPanel.Dock="Bottom"
                                          Visibility="Collapsed"
                                          Focusable="false"
                                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                          Margin="{TemplateBinding Padding}"/>
                    </DockPanel>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsExpanded"
                             Value="true">
                        <Setter Property="Visibility"
                                Value="Visible"
                                TargetName="ExpandSite"/>
                    </Trigger>
                    <Trigger Property="ExpandDirection"
                             Value="Right">
                        <Setter Property="DockPanel.Dock"
                                Value="Right"
                                TargetName="ExpandSite"/>
                        <Setter Property="DockPanel.Dock"
                                Value="Left"
                                TargetName="HeaderSite"/>
                        <Setter Property="Style"
                                Value="{StaticResource ExpanderRightHeaderStyle}"
                                TargetName="HeaderSite"/>
                    </Trigger>
                    <Trigger Property="ExpandDirection"
                             Value="Up">
                        <Setter Property="DockPanel.Dock"
                                Value="Top"
                                TargetName="ExpandSite"/>
                        <Setter Property="DockPanel.Dock"
                                Value="Bottom"
                                TargetName="HeaderSite"/>
                        <Setter Property="Style"
                                Value="{StaticResource ExpanderUpHeaderStyle}"
                                TargetName="HeaderSite"/>
                    </Trigger>
                    <Trigger Property="ExpandDirection"
                             Value="Left">
                        <Setter Property="DockPanel.Dock"
                                Value="Left"
                                TargetName="ExpandSite"/>
                        <Setter Property="DockPanel.Dock"
                                Value="Right"
                                TargetName="HeaderSite"/>
                        <Setter Property="Style"
                                Value="{StaticResource ExpanderLeftHeaderStyle}"
                                TargetName="HeaderSite"/>
                    </Trigger>
                    <Trigger Property="IsEnabled"
                             Value="false">
                        <Setter Property="Foreground"
                                Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

Body:
I have a WPF DataGrid with RowDetails which uses the RowHeader Expander to expand/collapse the RowDetails.
I am trying to set the style of the RowHeader Expander ToggleButton to a ToggleButton style defined in a resource dictionary. I tried this:

<DataGrid.RowHeaderTemplate>
<DataTemplate>
    <Expander Expanded="Expander_Expanded" Collapsed="Expander_Collapsed" >

Body:
It's not quite that easy.  If you are forcing an Expander into your RowHeaderTemplate, you need to style the actual Expander object in order to have an impact on the ToggleButton buried within it.

Given below is the default styling for the Expander object in the Aero.Normal WPF theme.  Using that as a base, you can then modify the ToggleButton contained within.

<Style x:Key="{x:Type Expander}"
       TargetType="{x:Type Expander}">
    <Setter Property="Foreground"
            Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
    <Setter Property="Background"
            Value="Transparent"/>
    <Setter Property="HorizontalContentAlignment"
            Value="Stretch"/>
    <Setter Property="VerticalContentAlignment"
            Value="Stretch"/>
    <Setter Property="BorderBrush"
            Value="Transparent"/>
    <Setter Property="BorderThickness"
            Value="1"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Expander}">
                <Border BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        Background="{TemplateBinding Background}"
                        CornerRadius="3"
                        SnapsToDevicePixels="true">
                    <DockPanel>
                        <ToggleButton x:Name="HeaderSite"
                                      DockPanel.Dock="Top"
                                      Margin="1"
                                      MinWidth="0"
                                      MinHeight="0"
                                      Style="{StaticResource ExpanderDownHeaderStyle}"
                                      FocusVisualStyle="{StaticResource ExpanderHeaderFocusVisual}"
                                      IsChecked="{Binding Path=IsExpanded,Mode=TwoWay,RelativeSource={RelativeSource TemplatedParent}}"
                                      Content="{TemplateBinding Header}"
                                      ContentTemplate="{TemplateBinding HeaderTemplate}"
                                      ContentTemplateSelector="{TemplateBinding HeaderTemplateSelector}"
                                      Foreground="{TemplateBinding Foreground}"
                                      Padding="{TemplateBinding Padding}"
                                      FontFamily="{TemplateBinding FontFamily}"
                                      FontSize="{TemplateBinding FontSize}"
                                      FontStyle="{TemplateBinding FontStyle}"
                                      FontStretch="{TemplateBinding FontStretch}"
                                      FontWeight="{TemplateBinding FontWeight}"
                                      HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                                      VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        <ContentPresenter x:Name="ExpandSite"
                                          DockPanel.Dock="Bottom"
                                          Visibility="Collapsed"
                                          Focusable="false"
                                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                          Margin="{TemplateBinding Padding}"/>
                    </DockPanel>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsExpanded"
                             Value="true">
                        <Setter Property="Visibility"
                                Value="Visible"
                                TargetName="ExpandSite"/>
                    </Trigger>
                    <Trigger Property="ExpandDirection"
                             Value="Right">
                        <Setter Property="DockPanel.Dock"
                                Value="Right"
                                TargetName="ExpandSite"/>
                        <Setter Property="DockPanel.Dock"
                                Value="Left"
                                TargetName="HeaderSite"/>
                        <Setter Property="Style"
                                Value="{StaticResource ExpanderRightHeaderStyle}"
                                TargetName="HeaderSite"/>
                    </Trigger>
                    <Trigger Property="ExpandDirection"
                             Value="Up">
                        <Setter Property="DockPanel.Dock"
                                Value="Top"
                                TargetName="ExpandSite"/>
                        <Setter Property="DockPanel.Dock"
                                Value="Bottom"
                                TargetName="HeaderSite"/>
                        <Setter Property="Style"
                                Value="{StaticResource ExpanderUpHeaderStyle}"
                                TargetName="HeaderSite"/>
                    </Trigger>
                    <Trigger Property="ExpandDirection"
                             Value="Left">
                        <Setter Property="DockPanel.Dock"
                                Value="Left"
                                TargetName="ExpandSite"/>
                        <Setter Property="DockPanel.Dock"
                                Value="Right"
                                TargetName="HeaderSite"/>
                        <Setter Property="Style"
                                Value="{StaticResource ExpanderLeftHeaderStyle}"
                                TargetName="HeaderSite"/>
                    </Trigger>
                    <Trigger Property="IsEnabled"
                             Value="false">
                        <Setter Property="Foreground"
                                Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>


问:
C# Namespace, Folders, Compiler Error
I'm using VS 2017 v15.5.0.

I have a minimal Console project named, Con_02. The namespace for the main class in this project is simply Con_02 (the class is shown below).

Within this project I add a new folder named, Business. Within the Business folder I create a class named, Employee. The default namespace generated by VS for the Employee class is Con_02.Business. I simplify this namespace to Business.

Back in my main class I instantiate Employee. Here is my full main class:

```<code>namespace Con_02 {
    class Program {
        Business.Employee e1 = new Business.Employee();

        private static void Main() { }
    }
}
</code>```

So far, so good. Everything compiles.

Now, I create another class, Company, in the Business folder. VS generates a namespace, Con_02.Business.

Now, the main Con_02.Program class no longer compiles. Specifically, the creation of the Business.Employee object which had previously compiled just fine, gives me a compiler error:

The type or namespace name 'Employee' does not exist in the namespace 'Con_02.Business' (are you missing an assembly reference?)

I'm not asking how to fix the problem so much as I'm trying to understand why compiler seems to assume a namespace relative to Con_02.

答:
Add

using Business;

at the top of you Program class.

and remove The Business-part from your Employee instantiation.

OR. Use the same namespace for all you classes.

Title: C# Namespace, Folders, Compiler Error

Body:
I'm using VS 2017 v15.5.0.

I have a minimal Console project named, Con_02. The namespace for the main class in this project is simply Con_02 (the class is shown below).

Within this project I add a new folder named, Business. Within the Business folder I create a class named, Employee. The default namespace generated by VS for the Employee class is Con_02.Business. I simplify this namespace to Business.

Back in my main class I instantiate Employee. Here is my full main class:

namespace Con_02 {
    class Program {
        Business.Employee e1 = new Business.Employee();

        private static void Main() { }
    }
}

So far, so good. Everything compiles.

Now, I create another class, Company, in the Business folder. VS generates a namespace, Con_02.Business.

Now, the main Con_02.Program class no longer compiles. Specifically, the creation of the Business.Employee object which had previously compiled just fine, gives me a compiler error:

The type or namespace name 'Employee' does not exist in the namespace 'Con_02.Business' (are you missing an assembly reference?)

I'm not asking how to fix the problem so much as I'm trying to understand why compiler seems to assume a namespace relative to Con_02.


问:
HTML - Footer places itself above container
I am creating a small webpage to practice my HTML on and I can't seem to figure out why the Footer just places itself at underneath the Header instead of underneath the container I have created.

It is most likely something small that I have overlooked but I can't seem to figure out or a find a solution anywhere so advice here would be greatly appreciated.

header {
  height: 50px;
  width: 900px;
  color: white;
  margin: auto;
  padding: auto;
  background-color: black;
  display: block;
}

nav {
  float: right;
  background-color: black;
}

p,
h1,
h2,
li {
  font-family: sans-serif;
}

footer {
  height: 50px;
  width: 900px;
  color: white;
  margin: auto;
  background-color: black;
  text-align: center;
  padding: auto;
  display: block;
}

main {
  padding: auto;
  display: block;
}

#container {
  display: block;
  padding-bottom: 50px;
  margin: auto;
  width: 900px;
}

#left-column {
  display: inline-block;
  width: 450px;
  float: left;
}

#right-column {
  display: inline-block;
  float: right;
}

#button {
  border-radius: 5px;
  background-color: red;
  text-align: center;
  color: white;
  height: 50px;
  width: 80px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <header>
    <p>Logo</p>
    <nav></nav>
  </header>
  <main>
    <div id="left-column">
      <h1>Website title</h1>
      <h2>Article title</h2>
      <p>Some text followed by a list:</p>
      <ul>
        <li>A list item</li>
        <li>A list item with a link (Click me)</li>
        <li>New deals daily</li>
      </ul>
      <p> Some more text</p>
    </div>
    <div id="right-column">
      <h2>Some content related to the article</h2>
      <div id="button">
        <p>A Button</p>
      </div>
    </div>
  </main>
  <footer>
    <p>©Website name 2017</p>
  </footer>
</div></code>```

答:
header {
  height: 50px;
  color: white;
  margin: auto;
  padding: auto;
  background-color: black;
  display: block;
}

nav {
  float: right;
  background-color: black;
}

p,
h1,
h2,
li {
  font-family: sans-serif;
}

footer {
  height: 50px;
  color: white;
  margin: auto;
  background-color: black;
  text-align: center;
  padding: auto;
  display: block;

}

main {
  padding: auto;
  display: block;
  overflow:hidden;
}

#container {
  display: block;
  padding-bottom: 50px;
  margin: auto;
  width: 900px;
}

#left-column {
  display: inline-block;
  width: 450px;
  float: left;
}

#right-column {
  display: inline-block;
  float: right;
}

#button {
  border-radius: 5px;
  background-color: red;
  text-align: center;
  color: white;
  height: 50px;
  width: 80px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container">
  <header>
    <p>Logo</p>
    <nav></nav>
  </header>
  <main>
    <div id="left-column">
      <h1>Website title</h1>
      <h2>Article title</h2>
      <p>Some text followed by a list:</p>
      <ul>
        <li>A list item</li>
        <li>A list item with a link (Click me)</li>
        <li>New deals daily</li>
      </ul>
      <p> Some more text</p>
    </div>
    <div id="right-column">
      <h2>Some content related to the article</h2>
      <div id="button">
        <p>A Button</p>
      </div>
    </div>
  </main>
  <footer>
    <p>©Website name 2017</p>
  </footer>
</div></code>```

Body:
I am creating a small webpage to practice my HTML on and I can't seem to figure out why the Footer just places itself at underneath the Header instead of underneath the container I have created.

It is most likely something small that I have overlooked but I can't seem to figure out or a find a solution anywhere so advice here would be greatly appreciated.

header {
  height: 50px;
  width: 900px;
  color: white;
  margin: auto;
  padding: auto;
  background-color: black;
  display: block;
}

nav {
  float: right;
  background-color: black;
}

p,
h1,
h2,
li {
  font-family: sans-serif;
}

footer {
  height: 50px;
  width: 900px;
  color: white;
  margin: auto;
  background-color: black;
  text-align: center;
  padding: auto;
  display: block;
}

main {
  padding: auto;
  display: block;
}

#container {
  display: block;
  padding-bottom: 50px;
  margin: auto;
  width: 900px;
}

#left-column {
  display: inline-block;
  width: 450px;
  float: left;
}

#right-column {
  display: inline-block;
  float: right;
}

#button {
  border-radius: 5px;
  background-color: red;
  text-align: center;
  color: white;
  height: 50px;
  width: 80px;
}

Logo

Website title

Article title

Some text followed by a list:

A list item

A list item with a link (Click me)

New deals daily

 Some more text

Some content related to the article

A Button

©Website name 2017

Body:
header {
  height: 50px;
  color: white;
  margin: auto;
  padding: auto;
  background-color: black;
  display: block;
}

nav {
  float: right;
  background-color: black;
}

p,
h1,
h2,
li {
  font-family: sans-serif;
}

footer {
  height: 50px;
  color: white;
  margin: auto;
  background-color: black;
  text-align: center;
  padding: auto;
  display: block;

}

main {
  padding: auto;
  display: block;
  overflow:hidden;
}

#container {
  display: block;
  padding-bottom: 50px;
  margin: auto;
  width: 900px;
}

#left-column {
  display: inline-block;
  width: 450px;
  float: left;
}

#right-column {
  display: inline-block;
  float: right;
}

#button {
  border-radius: 5px;
  background-color: red;
  text-align: center;
  color: white;
  height: 50px;
  width: 80px;
}

<div id="container">
  <header>
    <p>Logo</p>
    <nav></nav>
  </header>
  <main>
    <div id="left-column">
      <h1>Website title</h1>
      <h2>Article title</h2>
      <p>Some text followed by a list:</p>
      <ul>
        <li>A list item</li>
        <li>A list item with a link (<a href="#">Click me</a>)</li>
        <li>New deals daily</li>
      </ul>
      <p> Some more text</p>
    </div>
    <div id="right-column">
      <h2>Some content related to the article</h2>
      <div id="button">
        <p>A Button</p>
      </div>
    </div>
  </main>
  <footer>
    <p>&copy;Website name 2017</p>
  </footer>
</div>


问:
CSS not centering
I have the following html and css.

  .divOuter {
  width: 50%;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 150px;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="logo">
  <img src="http://i.cubeupload.com/jmdKlW.png"></img>
</div>
<div id="title">
  <h3>Who's watching</h3>
</div>
<div class="divOuter">
  <div class="divInner1">First DIV</div>
  <div class="divInner2">Second DIV</div>
  <div class="divInner3">Third DIV</div>
</div></code>```

I used the outer div to try and center everything inside. but i get the following image:

The squares in the middle are not centered. A working example is on xat.me/madses1996

I would like the squares next to eachtother.

答:
Just use flex on outer

```<code>.divOuter {
  width: 50%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

.divInner1,
.divInner2,
.divInner3 {
  flex: 1
}
</code>```

Title: CSS not centering

Body:
I have the following html and css.

  .divOuter {
  width: 50%;
  margin: 0 auto;
}

.divInner1,
.divInner2,
.divInner3 {
  border: 1px solid;
  float: left;
  width: 150px;
  height: 150px;
  margin-left: 3px;
  margin-right: 3px;
  margin-top: 50px;
  text-align: center;

Who's watching

First DIV

Second DIV

Third DIV

I used the outer div to try and center everything inside. but i get the following image:

The squares in the middle are not centered. A working example is on xat.me/madses1996

I would like the squares next to eachtother.

Body:
Just use flex on outer

.divOuter {
  width: 50%;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
}

.divInner1,
.divInner2,
.divInner3 {
  flex: 1
}


问:
Solve the memory management problems by proving program correctness like with coq?
I just wanted to ask if it would be possible to construct a language with a type system that can solve the memory management problems (memory leaks, dangling pointers, double free(), etc.) by automatically trying to prove the correctness of any program with its types as propositions like with an integrated coq-like theorem prover (in the mindset of programs as proofs)?

Is there a fundamental logical problem to this approach (halting problem maybe?) or is it just unfeasible? Thanks for any answers and I'm sorry that I'm not so well-versed in this field, just want to know out of curiosity ;)

答: Yes, there has been a lot of research into languages that do compile-time memory management. Rust and its ownership model is the most high profile industry language in this area. You might always want to look into "linear types".</p>