问:
Cannot convert String Type 'String' to 'MVCTutorial.Model.tblDept'
I'm trying to show list of employees to view by following code. I have tblemployee class and tblDept class.

```<code>EmployeeViewModel EmployeeVM = new EmployeeViewModel();
MvcEmployeeEntities db = new MvcEmployeeEntities();
List<TblEmployee> emplist = db.TblEmployees.ToList();

        List<EmployeeViewModel> EmpVMlist = emplist.Select(
            x => new EmployeeViewModel {
                Emp_ID = x.Emp_ID,
                Emp_Name = x.Emp_Name,
                Emp_Number = x.Emp_Number,
                DeptID = x.DeptID,
              **DeptName = x.tblDept.DeptName** }).ToList();

Return(EmpVMlist);
</code>```

at this point deptName shows error saying String can't be implicitly converted to NamespaceModel Class.

Is they any way to implicitly convert it ?

Note I have a Public virtual tblDept  deptName {get;set;} as it is driven from tbldept.class

```<code>public class EmployeeViewModel
{
    public int Emp_ID { get; set; }
    public string Emp_Name { get; set; }
    public Nullable<int> Emp_Number { get; set; }
    public Nullable<int> DeptID { get; set; }
    //virtual to use an other tble with in this tble, to get set there tblValues
    public virtual tblDept DeptName { get; set; }
}
</code>```

答:
The error is self explanatory.x.tblDept.DeptName in your LINQ Select expression will read the DeptName property value of the associated Department of the Employee record you are reading, but you are trying to set the property value to DeptName property which is of type tblDept! So basically you are trying to assign apple type to orange!

Ideally, your view model should not be using your entity classes. View models are models specific to a view. Keep it simple and lean. Most of the time simple-lean-flat view models are what you need.

So change your DeptName property in your view model to string.

```<code>public class EmployeeViewModel
{
    public int Emp_ID { get; set; }
    public string Emp_Name { get; set; }
    public int? Emp_Number { get; set; }
    public int? DeptID { get; set; }
    public string DeptName { get; set; }
}
</code>```

Keep only those properties you absolutely need in the view, in your view model. No need to copy the entire entity class structure.

Body:
I'm trying to show list of employees to view by following code. I have tblemployee class and tblDept class.

EmployeeViewModel EmployeeVM = new EmployeeViewModel();
MvcEmployeeEntities db = new MvcEmployeeEntities();
List<TblEmployee> emplist = db.TblEmployees.ToList();

        List<EmployeeViewModel> EmpVMlist = emplist.Select(
            x => new EmployeeViewModel {
                Emp_ID = x.Emp_ID,
                Emp_Name = x.Emp_Name,
                Emp_Number = x.Emp_Number,
                DeptID = x.DeptID,
              **DeptName = x.tblDept.DeptName** }).ToList();

Return(EmpVMlist);

at this point deptName shows error saying String can't be implicitly converted to NamespaceModel Class.

Is they any way to implicitly convert it ?

Note I have a Public virtual tblDept  deptName {get;set;} as it is driven from tbldept.class

public class EmployeeViewModel
{
    public int Emp_ID { get; set; }
    public string Emp_Name { get; set; }
    public Nullable<int> Emp_Number { get; set; }
    public Nullable<int> DeptID { get; set; }
    //virtual to use an other tble with in this tble, to get set there tblValues
    public virtual tblDept DeptName { get; set; }
}

Body:
The error is self explanatory.x.tblDept.DeptName in your LINQ Select expression will read the DeptName property value of the associated Department of the Employee record you are reading, but you are trying to set the property value to DeptName property which is of type tblDept! So basically you are trying to assign apple type to orange!

Ideally, your view model should not be using your entity classes. View models are models specific to a view. Keep it simple and lean. Most of the time simple-lean-flat view models are what you need.

So change your DeptName property in your view model to string.

public class EmployeeViewModel
{
    public int Emp_ID { get; set; }
    public string Emp_Name { get; set; }
    public int? Emp_Number { get; set; }
    public int? DeptID { get; set; }
    public string DeptName { get; set; }
}

Keep only those properties you absolutely need in the view, in your view model. No need to copy the entire entity class structure.


来源: stackexchange

问:
explanation of INameOfInterface nameOfVariable = new ExampleClass();
I will appreciate if someone could explain the following C# code

```<code>INameOfInterface nameOfVariable = new ExampleClass();
</code>```

ExampleClass is implementing interface INameOfInterface.
What is this line doing? Thank you all in advance.

答:
It initializes instance of ExampleClass type and assigns it to nameOfVariable variable.

ExampleClass implements INameOfInterface interface.

ContentLicense: CC BY-SA 3.0

Body:
I will appreciate if someone could explain the following C# code

INameOfInterface nameOfVariable = new ExampleClass();

ExampleClass is implementing interface INameOfInterface.
What is this line doing? Thank you all in advance.


问:
How to create responsive table with footer
I want to create a responsive table with footer. Right now i am using  tag But i am facing issue with the footer. It doesnot show properly on different screen sizes. Footer should be fixed to bottom of page. If user tries to resize the page it should show scroll in that case, with footer at bottom.

Sample Image

```<code><div class="container">
        <table class="tablelog">
            <thead  id="thead">
                <tr >
                    <th ><div  style="width:15px;"></div></th>
                    <th ><div  id="div-style">Column 1</div></th>
                    <th ><div  id="div-style">Column 2</div></th>
                    <th ><div  id="div-style">Column 3</div></th>
                    <th  id="last-column"><div >Column 4</div></th>
                </tr>
            </thead>
            <tbody  id="tbody">
                <tr  class="active">
                    <td  style="padding-right:15px;"><div  class="triangleright"></div></td>
                    <td ><div  id="div-style">value</div></td>
                    <td ><div  id="div-style">value</div></td>
                    <td >
                        <div  id="div-style">value</div>
                    </td>
                    <td  id="last-column">value</td>
                </tr><tr>
                    <td  style="padding-right:15px;"><div></div></td>
                    <td ><div  id="div-style">value</div></td>
                    <td ><div  id="div-style">value</div></td>
                    <td >
                        <div  id="div-style">value</div>
                    </td>
                    <td  id="last-column">value</td>
                </tr><tr>
                    <td  style="padding-right:15px;"><div></div></td>
                    <td ><div  id="div-style">value</div></td>
                    <td ><div  id="div-style">value</div></td>
                    <td >
                        <div  id="div-style">value</div>
                    </td>
                    <td  id="last-column">value</td>
                </tr>
            </tbody>
            <tfoot >
                <div  id="page-selector-control">
                    <div  id="pageselectorButtonContainr">
                        <button  id="page-selector-button-control" type="button" disabled=""><img  id="page-selector-button-control-image" src="images/extreme-left.png"></button>
                        <button  id="page-selector-button-control" type="button" disabled=""><img  id="page-selector-button-control-image" src="images/arrow-left.png"></button>
                        <button  id="page-selector-button-control" type="button" disabled=""><img  id="page-selector-button-control-image" src="images/arrow-right.png"></button>
                        <button  id="page-selector-button-control" type="button" disabled=""><img  id="page-selector-button-control-image" src="images/extreme-right.png"></button>
                    </div>
                    <div  class="pager-control">
                        <div  id="pagerdevidercontainer">
                            <div  id="pagerdeviderdivfirst"></div>
                            <div  id="pagerdeviderdivsecond"></div>
                        </div>
                        <label >Page</label>
                        <input  accept="number" id="pagetextfield" type="text" ng-reflect-model="1" class="ng-untouched ng-pristine ng-valid">
                        <label >of</label>
                        <label > </label>
                        <label >1</label>
                    </div>
                </div>`enter code here`
            </tfoot>
        </table>
    </div>
</code>```

答:
See updated
 here -

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Column 1

Column 2

Column 3

Column 4

value

value

value

                        value

value

value

value

                        value

value

value

value

                        value

        <button id="page-selector-button-control" type="button" disabled=""></button>
        <button id="page-selector-button-control" type="button" disabled=""></button>
        <button id="page-selector-button-control" type="button" disabled=""></button>
        <button id="page-selector-button-control" type="button" disabled=""></button>

        Page
        <input accept="number" id="pagetextfield" type="text" ng-reflect-model="1" class="ng-untouched ng-pristine ng-valid">
        of

        1

```

I've also used bootstrap here, which is useful for responsive design.

Body:
I want to create a responsive table with footer. Right now i am using  tag But i am facing issue with the footer. It doesnot show properly on different screen sizes. Footer should be fixed to bottom of page. If user tries to resize the page it should show scroll in that case, with footer at bottom.

Sample Image

Column 1

Column 2

Column 3

Column 4

value

value

value

                    value

value

value

value

                    value

value

value

value

                    value

                        <button  id="page-selector-button-control" type="button" disabled=""></button>
                        <button  id="page-selector-button-control" type="button" disabled=""></button>
                        <button  id="page-selector-button-control" type="button" disabled=""></button>
                        <button  id="page-selector-button-control" type="button" disabled=""></button>

                        Page
                        <input  accept="number" id="pagetextfield" type="text" ng-reflect-model="1" class="ng-untouched ng-pristine ng-valid">
                        of

                        1

`enter code here`

Body:
See updated <tfoot> here -

<!DOCTYPE html>
<html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>

<body>
    <div class="container">
        <div class="table-responsive">
            <table class="table tablelog">
                <thead id="thead">
                    <tr>
                        <th>
                            <div style="width:15px;"></div>
                        </th>
                        <th>
                            <div id="div-style">Column 1</div>
                        </th>
                        <th>
                            <div id="div-style">Column 2</div>
                        </th>
                        <th>
                            <div id="div-style">Column 3</div>
                        </th>
                        <th id="last-column">
                            <div>Column 4</div>
                        </th>
                    </tr>
                </thead>
                <tbody id="tbody">
                    <tr class="active">
                        <td style="padding-right:15px;">
                            <div class="triangleright"></div>
                        </td>
                        <td>
                            <div id="div-style">value</div>
                        </td>
                        <td>
                            <div id="div-style">value</div>
                        </td>
                        <td>
                            <div id="div-style">value</div>
                        </td>
                        <td id="last-column">value</td>
                    </tr>
                    <tr>
                        <td style="padding-right:15px;">
                            <div></div>
                        </td>
                        <td>
                            <div id="div-style">value</div>
                        </td>
                        <td>
                            <div id="div-style">value</div>
                        </td>
                        <td>
                            <div id="div-style">value</div>
                        </td>
                        <td id="last-column">value</td>
                    </tr>
                    <tr>
                        <td style="padding-right:15px;">
                            <div></div>
                        </td>
                        <td>
                            <div id="div-style">value</div>
                        </td>
                        <td>
                            <div id="div-style">value</div>
                        </td>
                        <td>
                            <div id="div-style">value</div>
                        </td>
                        <td id="last-column">value</td>
                    </tr>
                </tbody>
                <!-- <tfoot>
                    <tr>
                        <th></th>
                        <th colspan=3>
                            <button id="page-selector-button-control" type="button" disabled=""><img id="page-selector-button-control-image" src="images/extreme-left.png">1</button>
                            <button id="page-selector-button-control" type="button" disabled=""><img id="page-selector-button-control-image" src="images/arrow-left.png">2</button>
                            <button id="page-selector-button-control" type="button" disabled=""><img id="page-selector-button-control-image" src="images/arrow-right.png">3</button>
                            <button id="page-selector-button-control" type="button" disabled=""><img id="page-selector-button-control-image" src="images/extreme-right.png">4</button>
                        </th>
                        <th colspan=1>
                            <label>Page</label>
                            <input accept="number" id="pagetextfield" type="text" ng-reflect-model="1" class="ng-untouched ng-pristine ng-valid">
                            <label>of</label>
                            <label> </label>
                            <label>1</label>
                        </th>
                    </tr>
                </tfoot> -->
            </table>
        </div>
    </div>
</body>
<footer style="position: fixed;bottom: 0px;" class="col-xs-12">
    <div id="pageselectorButtonContainr" class="col-xs-6">
        <button id="page-selector-button-control" type="button" disabled=""><img id="page-selector-button-control-image" src="images/extreme-left.png"></button>
        <button id="page-selector-button-control" type="button" disabled=""><img id="page-selector-button-control-image" src="images/arrow-left.png"></button>
        <button id="page-selector-button-control" type="button" disabled=""><img id="page-selector-button-control-image" src="images/arrow-right.png"></button>
        <button id="page-selector-button-control" type="button" disabled=""><img id="page-selector-button-control-image" src="images/extreme-right.png"></button>
    </div>
    <div class="pager-control col-xs-6 pull-right">
        <label>Page</label>
        <input accept="number" id="pagetextfield" type="text" ng-reflect-model="1" class="ng-untouched ng-pristine ng-valid">
        <label>of</label>
        <label> </label>
        <label>1</label>
    </div>
</footer>

</html>

I've also used bootstrap here, which is useful for responsive design.


问:
Return a member variable if it exist
Somehow I feel there are several answer to the similar question, however I couldn't find a final solution to my problem.So, my apologies in advance:
I have many message structures that are either incoming:

```<code>struct X_1 //Y_2, Z_x, _...
{
 IncomingHeader incoming_header;
 //.......
};
</code>```

or Outgoing:

```<code>struct A_1 //B_2, C_x, _...
{
 OutgoingHeader outgoing_header;
 //.......
};
</code>```

The message headers are of only two types:

```<code>struct IncomingHeader
{
  A a;
  B b;
};

struct OutgoingHeader
{
  A a;
  B b;
  char c[SIZE};
};

//If it helps, eventually I am only interested in a and b in header structs.
</code>```

At some point during decoding, I need a get_header() function which would return the header member(incoming_header or outgoing_header).
Is there a way to solve this problem?
(I am using boost 1.46 and not C++11)

答:
Well, Walter addressed the idea, by introducing a common base type. But generally there are 2 approaches how one can handle the encoded/marshalled data.

Direct mapping of network bytes to data structures, e.g. C/C++ POD types

Using system independent data representation format, e.g. Google Protobuf, XDR, ASN.1 and many more (even non binary ones like XML, JSON, YAML...)

Case 1: POD like handling

C/C++ POD

Actually, the only part I don not agree with Walter's idea is to introduce the virtual base class. Especially, because the type no longer is a POD and one can't map it 1:1 to the network bytes and needs to copy data.

Usually types like A, B from your example are designed as PODs. And that allows very efficient marshalling/unmarshalling of them without copying.

Let's say you have smth. like:

```<code>struct incoming_header
{
  std::int32_t a;
  std::int64_t b;
};

struct outgoing_header
{
  std::int32_t a;
  std::int64_t b;
  char c[SIZE};
};
</code>```

Here we use C++ standard's guaranteed length integers to be sure that we deal with exact length of fields. Unfortunately, standard defines that they are optional and thus might not be available on your target platform (which actually seldom for fully fledged HW and likely to be the case on some embedded HW).

Sending PODs

Now because these types are POD we can simply send them by simply pushing their bytes through the network.

So the following pseudo code is fully OK:

```<code>outgoing_header oh{...};
send(&oh, sizeof(oh));
</code>```

Receiving PODs

Usually you know how (from your protocol how many bytes you need), given they are all copied into contiguous buffer you can obtain a proper view to that buffer. Let's say we do not deal with big/little endian issues at that point. Then what the networking code usually receives bytes for you and states how many these are.

So at that point let's rely that we can only receive outgoing_header right now and our buffer is big enough to contain the entire message length.

Then the code usually looks similar to:

```<code>constexpr static size_t max_size = ...;
char buf[max_size]{};

size_t got_bytes = receive(&buf, max_size);

// now we need to interpret these bytes as outgoing_header
outgoing_header* pheader = reinterpret_cast<outgoing_header*>(&buf[0]);

// now access the header items
pheader->a;
pheader->b;
</code>```

There are no copies involved, just a pointer cast.

Solving your problem

Usually any binary protocol has one common header sender and receiver can rely on. There is encoded, which message is being carried, how long it is, may be the protocol version etc.

What you need to do is to introduce a common header, in your case it should be carrying field a and b.

```<code>struct base_header
{
  std::int32_t a;
  std::int64_t b;
};

// Note! Using derivation will render the type as non-POD, thus aggregation
struct incoming_header
{
  base_header base;
};

struct outgoing_header
{
  base_header base;
  char c[SIZE};
};
</code>```

Now incoming_header and outgoing_header are both PODs. What you need to do here is to cast your buffer to the pointer to the base_header and grab a and b of interest:

```<code>base_header* pbase_header = reinterpret_cast<base_header*>(&buf[0]);
do_smth(pbase_header->a, pbase_header->b);
</code>```

Case 2: System independent data representation format

An alternative to that approach would be to use boost::variant class or if you switch to C++17 std::variant. In case that you can't have PODs and have some sort of custom serialization format with custom marshalling/unmarshalling lib e.g. Google Protobuf or alike...

Using variant you can just define your protocol, i.e. messages/headers which might arrive:

```<code>typedef boost::variant<boost::none, IncomingHeader, OutgoingHeader> message_header;

message_header get_header(char* bytes, size_t size)
{
  // dispatch bytes and put the message to variant:
  // let's say we get OutgoingHeader
  OutgoingHeader h{/* init from bytes here */};
  return h; // variant has implicit ctor to accept OutgoingHeader object
}
</code>```

Now you can use a hand crafted visitor type to get the desired value:

```<code>struct my_header_visitor
{
  typedef void result_type;

  explicit my_header_visitor(some_context& ctx)
    : ctx_{ctx}
  {}

  template<class T>
  result_type operator()(T const&)
  {
    // throw whatever error, due to unexpected dispatched type
  }

  result_type operator()(OutgoingHeader const& h)
  {
     // handle OutgoingHeader
     ctx_.do_smth_with_outgoing_header(h);
  }

  result_type operator()(IncomingHeader const& h)
  {
    // handle IncomingHeader
    ctx_.do_smth_with_incoming_header(h);
  }

private:
  some_context& ctx_;
};

my_header_visitor v{/* pass context here */};
message_header h {/* some init code here */};
boost::apply_visitor(v, h);
</code>```

P.S. if you are interested to understand why variant is needed or how the dispatching works, you can read Andrei Alexandrescu's article series on discriminated unions in Dr. Dobbs:

Discriminated Unions (I)

Discriminated Unions (II)

Generic: Discriminated Unions (III)

Title: Return a member variable if it exist

Body:
Somehow I feel there are several answer to the similar question, however I couldn't find a final solution to my problem.So, my apologies in advance:
I have many message structures that are either incoming:

struct X_1 //Y_2, Z_x, _...
{
 IncomingHeader incoming_header;
 //.......
};

or Outgoing:

struct A_1 //B_2, C_x, _...
{
 OutgoingHeader outgoing_header;
 //.......
};

The message headers are of only two types:

struct IncomingHeader
{
  A a;
  B b;
};

struct OutgoingHeader
{
  A a;
  B b;
  char c[SIZE};
};

//If it helps, eventually I am only interested in a and b in header structs.

At some point during decoding, I need a get_header() function which would return the header member(incoming_header or outgoing_header).
Is there a way to solve this problem?
(I am using boost 1.46 and not C++11)

Body:
Well, Walter addressed the idea, by introducing a common base type. But generally there are 2 approaches how one can handle the encoded/marshalled data.

Direct mapping of network bytes to data structures, e.g. C/C++ POD types

Using system independent data representation format, e.g. Google Protobuf, XDR, ASN.1 and many more (even non binary ones like XML, JSON, YAML...)

Case 1: POD like handling

C/C++ POD

Actually, the only part I don not agree with Walter's idea is to introduce the virtual base class. Especially, because the type no longer is a POD and one can't map it 1:1 to the network bytes and needs to copy data.

Usually types like A, B from your example are designed as PODs. And that allows very efficient marshalling/unmarshalling of them without copying.

Let's say you have smth. like:

struct incoming_header
{
  std::int32_t a;
  std::int64_t b;
};

struct outgoing_header
{
  std::int32_t a;
  std::int64_t b;
  char c[SIZE};
};

Here we use C++ standard's guaranteed length integers to be sure that we deal with exact length of fields. Unfortunately, standard defines that they are optional and thus might not be available on your target platform (which actually seldom for fully fledged HW and likely to be the case on some embedded HW).

Sending PODs

Now because these types are POD we can simply send them by simply pushing their bytes through the network.

So the following pseudo code is fully OK:

outgoing_header oh{...};
send(&oh, sizeof(oh));

Receiving PODs

Usually you know how (from your protocol how many bytes you need), given they are all copied into contiguous buffer you can obtain a proper view to that buffer. Let's say we do not deal with big/little endian issues at that point. Then what the networking code usually receives bytes for you and states how many these are.

So at that point let's rely that we can only receive outgoing_header right now and our buffer is big enough to contain the entire message length.

Then the code usually looks similar to:

constexpr static size_t max_size = ...;
char buf[max_size]{};

size_t got_bytes = receive(&buf, max_size);

// now we need to interpret these bytes as outgoing_header
outgoing_header* pheader = reinterpret_cast<outgoing_header*>(&buf[0]);

// now access the header items
pheader->a;
pheader->b;

There are no copies involved, just a pointer cast.

Solving your problem

Usually any binary protocol has one common header sender and receiver can rely on. There is encoded, which message is being carried, how long it is, may be the protocol version etc.

What you need to do is to introduce a common header, in your case it should be carrying field a and b.

struct base_header
{
  std::int32_t a;
  std::int64_t b;
};

// Note! Using derivation will render the type as non-POD, thus aggregation
struct incoming_header
{
  base_header base;
};

struct outgoing_header
{
  base_header base;
  char c[SIZE};
};

Now incoming_header and outgoing_header are both PODs. What you need to do here is to cast your buffer to the pointer to the base_header and grab a and b of interest:

base_header* pbase_header = reinterpret_cast<base_header*>(&buf[0]);
do_smth(pbase_header->a, pbase_header->b);

Case 2: System independent data representation format

An alternative to that approach would be to use boost::variant class or if you switch to C++17 std::variant. In case that you can't have PODs and have some sort of custom serialization format with custom marshalling/unmarshalling lib e.g. Google Protobuf or alike...

Using variant you can just define your protocol, i.e. messages/headers which might arrive:

typedef boost::variant<boost::none, IncomingHeader, OutgoingHeader> message_header;

message_header get_header(char* bytes, size_t size)
{
  // dispatch bytes and put the message to variant:
  // let's say we get OutgoingHeader
  OutgoingHeader h{/* init from bytes here */};
  return h; // variant has implicit ctor to accept OutgoingHeader object
}

Now you can use a hand crafted visitor type to get the desired value:

struct my_header_visitor
{
  typedef void result_type;

  explicit my_header_visitor(some_context& ctx)
    : ctx_{ctx}
  {}

  template<class T>
  result_type operator()(T const&)
  {
    // throw whatever error, due to unexpected dispatched type
  }

  result_type operator()(OutgoingHeader const& h)
  {
     // handle OutgoingHeader
     ctx_.do_smth_with_outgoing_header(h);
  }

  result_type operator()(IncomingHeader const& h)
  {
    // handle IncomingHeader
    ctx_.do_smth_with_incoming_header(h);
  }

private:
  some_context& ctx_;
};

my_header_visitor v{/* pass context here */};
message_header h {/* some init code here */};
boost::apply_visitor(v, h);

P.S. if you are interested to understand why variant is needed or how the dispatching works, you can read Andrei Alexandrescu's article series on discriminated unions in Dr. Dobbs:

Discriminated Unions (I)

Discriminated Unions (II)

Generic: Discriminated Unions (III)


问:
Can't get FreeType to render
Working with OpenGL, GLM, GLAD, GLFW and FreeType attempting to get fonts to render. I've stepped through to make sure no OpenGL errors had occured while rendering, nothing posts an error code, but nothing renders to the screen. I'm also not sure if I'm using glm's ortho function correctly, because i'm not sure where to actually use the variable:

```<code>glm::mat4 projection = glm::ortho(0.0f, 800.0f, 0.0f, 600.0f);
</code>```

This is my Draw Loop, it gets called after the scene Initializes:

```<code>void GameLoop::Run()
{
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);

    while (!glfwWindowShouldClose(m_game_window))
    {
        // Do That thing where you draw everything
    }
}
</code>```

The Font constructor which loads the font into textures:

```<code>Salem::Graphics::Font::Font(std::string p_font_path)
{
    FT_Library ft;
    if (FT_Init_FreeType(&ft))
    {
        std::cout << "Error loading FreeType library" << std::endl;
    }

    FT_Face face;
    if (FT_New_Face(ft, p_font_path.c_str(), 0, &face))
    {
        std::cout << "Error loading font;\n" << p_font_path << std::endl;
    }

    FT_Set_Pixel_Sizes(face, 0, 28);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // Disable byte-alignment restriction

    for (GLubyte c = 0; c < 128; c++)
    {
        if (FT_Load_Char(face, c, FT_LOAD_RENDER))
        {
            std::cout << "Failed to load a character glyph." << std::endl;
            continue;
        }

        GLuint texture;
        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        glTexImage2D(
                GL_TEXTURE_2D,
                0,
                GL_RED,
                face->glyph->bitmap.width,
                face->glyph->bitmap.rows,
                0,
                GL_RED,
                GL_UNSIGNED_BYTE,
                face->glyph->bitmap.buffer);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        Character character = {
                texture,
                glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
                glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top),
                face->glyph->advance.x
        };

        m_characters.insert(std::make_pair(c, character));
    }

    FT_Done_Face(face);
    FT_Done_FreeType(ft);
    std::cout << "Font loaded. " << std::endl;
}
</code>```

My text's Initialize function:

```<code>void Text::Initialize()
{
    glm::mat4 projection = glm::ortho(0.0f, 800.0f, 0.0f, 600.0f);
    glGenVertexArrays(1, &m_vao);
    glGenBuffers(1, &m_vbo);

    glBindVertexArray(m_vao);
    glBindBuffer(GL_ARRAY_BUFFER, m_vbo);

    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, nullptr, m_draw_method);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), nullptr);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);
}
</code>```

And my text's draw function:

```<code>void Text::Draw()
{
    glm::mat4 projection = glm::ortho(0.0f, 800.0f, 0.0f, 600.0f);

    shader()->Use();
    glUniform3f(glGetUniformLocation(shader()->id(), "textColor"), m_color.x, m_color.y, m_color.z);
    glActiveTexture(GL_TEXTURE0);
    glBindVertexArray(m_vao);

    for (std::string::const_iterator c = m_text.begin(); c != m_text.end(); ++c)
    {
        Character ch = m_font.characters()[*c];

        GLfloat xPosition = m_position.x + ch.Bearing.x * m_scale;
        GLfloat yPosition = m_position.y - (ch.Size.y - ch.Bearing.y) * m_scale;

        GLfloat width = ch.Size.x * m_scale;
        GLfloat height = ch.Size.y * m_scale;

        GLfloat vertices[6][4] = {
                {xPosition,         yPosition + height, 0.0, 0.0},
                {xPosition,         yPosition,          0.0, 1.0},
                {xPosition + width, yPosition,          1.0, 1.0},

                {xPosition,         yPosition + height, 0.0, 0.0},
                {xPosition + width, yPosition,          1.0, 1.0},
                {xPosition + width, yPosition + height, 1.0, 0.0}
        };

        glBindTexture(GL_TEXTURE_2D, ch.TextureID);
        glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
        glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
        //glBindBuffer(GL_ARRAY_BUFFER, 0);

        glDrawArrays(GL_TRIANGLES, 0, 6);

        m_position.x += (ch.Advance >> 6) * m_scale;
    }

    glBindVertexArray(0);
    glBindTexture(GL_TEXTURE_2D, 0);
}
</code>```

Didn't want the post to be too long, if my shaders are needed, let me know.

答:
Upon breaking up the code, i found a helpful resource which lead me to my problem. From https://learnopengl.com/#!In-Practice/Text-Rendering Project source, I found that my orthographic projection variable had to be passed to my shader program when I was Constructing the font. I did this by add the following code to my Font Constructor:</p>

```<code>glm::mat4 projection = glm::ortho(0.0f, 800.0f, 0.0f, 600.0f);
p_shader->Use();
glUniformMatrix4fv(glGetUniformLocation(p_shader->id(), "projection"), 1, GL_FALSE, glm::value_ptr(projection));
</code>```

Title: Can't get FreeType to render

Body:
Working with OpenGL, GLM, GLAD, GLFW and FreeType attempting to get fonts to render. I've stepped through to make sure no OpenGL errors had occured while rendering, nothing posts an error code, but nothing renders to the screen. I'm also not sure if I'm using glm's ortho function correctly, because i'm not sure where to actually use the variable:

glm::mat4 projection = glm::ortho(0.0f, 800.0f, 0.0f, 600.0f);

This is my Draw Loop, it gets called after the scene Initializes:

void GameLoop::Run()
{
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glClearColor(0.2f, 0.3f, 0.3f, 1.0f);

    while (!glfwWindowShouldClose(m_game_window))
    {
        // Do That thing where you draw everything
    }
}

The Font constructor which loads the font into textures:

Salem::Graphics::Font::Font(std::string p_font_path)
{
    FT_Library ft;
    if (FT_Init_FreeType(&ft))
    {
        std::cout << "Error loading FreeType library" << std::endl;
    }

    FT_Face face;
    if (FT_New_Face(ft, p_font_path.c_str(), 0, &face))
    {
        std::cout << "Error loading font;\n" << p_font_path << std::endl;
    }

    FT_Set_Pixel_Sizes(face, 0, 28);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // Disable byte-alignment restriction

    for (GLubyte c = 0; c < 128; c++)
    {
        if (FT_Load_Char(face, c, FT_LOAD_RENDER))
        {
            std::cout << "Failed to load a character glyph." << std::endl;
            continue;
        }

        GLuint texture;
        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);
        glTexImage2D(
                GL_TEXTURE_2D,
                0,
                GL_RED,
                face->glyph->bitmap.width,
                face->glyph->bitmap.rows,
                0,
                GL_RED,
                GL_UNSIGNED_BYTE,
                face->glyph->bitmap.buffer);

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

        Character character = {
                texture,
                glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
                glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top),
                face->glyph->advance.x
        };

        m_characters.insert(std::make_pair(c, character));
    }

    FT_Done_Face(face);
    FT_Done_FreeType(ft);
    std::cout << "Font loaded. " << std::endl;
}

My text's Initialize function:

void Text::Initialize()
{
    glm::mat4 projection = glm::ortho(0.0f, 800.0f, 0.0f, 600.0f);
    glGenVertexArrays(1, &m_vao);
    glGenBuffers(1, &m_vbo);

    glBindVertexArray(m_vao);
    glBindBuffer(GL_ARRAY_BUFFER, m_vbo);

    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 6 * 4, nullptr, m_draw_method);

    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), nullptr);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);
}

And my text's draw function:

void Text::Draw()
{
    glm::mat4 projection = glm::ortho(0.0f, 800.0f, 0.0f, 600.0f);

    shader()->Use();
    glUniform3f(glGetUniformLocation(shader()->id(), "textColor"), m_color.x, m_color.y, m_color.z);
    glActiveTexture(GL_TEXTURE0);
    glBindVertexArray(m_vao);

    for (std::string::const_iterator c = m_text.begin(); c != m_text.end(); ++c)
    {
        Character ch = m_font.characters()[*c];

        GLfloat xPosition = m_position.x + ch.Bearing.x * m_scale;
        GLfloat yPosition = m_position.y - (ch.Size.y - ch.Bearing.y) * m_scale;

        GLfloat width = ch.Size.x * m_scale;
        GLfloat height = ch.Size.y * m_scale;

        GLfloat vertices[6][4] = {
                {xPosition,         yPosition + height, 0.0, 0.0},
                {xPosition,         yPosition,          0.0, 1.0},
                {xPosition + width, yPosition,          1.0, 1.0},

                {xPosition,         yPosition + height, 0.0, 0.0},
                {xPosition + width, yPosition,          1.0, 1.0},
                {xPosition + width, yPosition + height, 1.0, 0.0}
        };

        glBindTexture(GL_TEXTURE_2D, ch.TextureID);
        glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
        glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
        //glBindBuffer(GL_ARRAY_BUFFER, 0);

        glDrawArrays(GL_TRIANGLES, 0, 6);

        m_position.x += (ch.Advance >> 6) * m_scale;
    }

    glBindVertexArray(0);
    glBindTexture(GL_TEXTURE_2D, 0);
}

Didn't want the post to be too long, if my shaders are needed, let me know.

Body:
Upon breaking up the code, i found a helpful resource which lead me to my problem. From https://learnopengl.com/#!In-Practice/Text-Rendering Project source, I found that my orthographic projection variable had to be passed to my shader program when I was Constructing the font. I did this by add the following code to my Font Constructor:

glm::mat4 projection = glm::ortho(0.0f, 800.0f, 0.0f, 600.0f);
p_shader->Use();
glUniformMatrix4fv(glGetUniformLocation(p_shader->id(), "projection"), 1, GL_FALSE, glm::value_ptr(projection));


问:
C++ vector debug implementation
While learning c++ I went through the pains of learning what iterators were, and exactly how to use them.  Then, I went through the pain of learning what function calls invalidate iterators, and spotting them quickly.  I've been following questions lately and have noticed that a very common theme is people not realizing that calling vector::erase() invalidates iterators.  This made me wonder if there were a debug implementation of vector that does runtime checking against vector valid-ness?

My initial thoughts were that it would have to be a wrapper around vector that basically tracked all existing iterators, and set an isValid boolean when an action was performed that invalidated them.  Then, when dereferencing or incrementing, isValid could be checked.

This would help diagnose more obscure errors where the erase() call is nested (accidentally, or unknowingly) deep within a function call, while that same vector is being iterator over.

Does anyone know of such an implementation, or any reasons why one should not be used?

EDIT: I am using linux and g++.

答:
That is found in Microsoft STD library implementation..

When an iterator is invalidated, it means using it to access an element will cause runtime error, exactly like you want....

ContentLicense: CC BY-SA 2.5

Title: C++ vector debug implementation


问:
Input Layout toggle hintText color change
I am using TextInputLayout in which i want to change the color of hinttext  when i enter text then the color of hint text should be blue other wise color should be gray and when edittext contains some value then the color of hintText should blue for more information please check my image.

Ultimate i want this after edit text containing some value.

This is my current result after using this code

```<code>  <style name="labelcolor" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Hint color and label color in FALSE state -->
    <item name="android:textColorHint">#868686</item>
    <item name="android:textSize">16sp</item>
    <item name="android:paddingTop">5sp</item>
    <!-- Label color in TRUE state and bar color FALSE and TRUE State -->
    <item name="colorAccent">#0ea3ff</item>
    <item name="colorControlNormal">#0ea3ffr</item>
    <item name="colorControlActivated">#0ea3ff</item>
</style>
</code>```

please help me how can i solve this issues.

答:
TextInputLayout takes colorAccent to hintTextColor when you start entering values in edittext.
So if you want it to be blue then set your colorAccent to blue colour in your theme. And when edittext has no value then set hintTextColor to grey. Do like this

```<code><android.support.design.widget.TextInputLayout
                    android:id="@+id/userNameTIL"
                    android:layout_width="match_parent"
                    android:layout_height="55dp"
                    android:background="@color/spinnerBg"
                    android:clipToPadding="false"
                    android:gravity="bottom"
                    android:paddingTop="4dp"
                    android:textColorHint="@color/grey"> /*Here it sets color to hintText when edittext has no value */

                    <EditText
                        android:layout_width="match_parent"
                        android:layout_height="50dp"
                        android:layout_gravity="bottom"
                        android:background="@null"
                        android:hint="Username"
                        android:inputType="text"
                        android:maxLength="30"
                        android:paddingEnd="3dp"
                        android:paddingStart="25dp"
                        android:paddingTop="3dp"
                        android:singleLine="true"
                        android:textColor="@color/black"
                        android:textColorHint="@color/black"
                        android:textSize="20sp"/>
                </android.support.design.widget.TextInputLayout>
</code>```

Body:
I am using TextInputLayout in which i want to change the color of hinttext  when i enter text then the color of hint text should be blue other wise color should be gray and when edittext contains some value then the color of hintText should blue for more information please check my image.

Ultimate i want this after edit text containing some value.

This is my current result after using this code

please help me how can i solve this issues.

Body:
TextInputLayout takes colorAccent to hintTextColor when you start entering values in edittext.
So if you want it to be blue then set your colorAccent to blue colour in your theme. And when edittext has no value then set hintTextColor to grey. Do like this

<android.support.design.widget.TextInputLayout
                    android:id="@+id/userNameTIL"
                    android:layout_width="match_parent"
                    android:layout_height="55dp"
                    android:background="@color/spinnerBg"
                    android:clipToPadding="false"
                    android:gravity="bottom"
                    android:paddingTop="4dp"
                    android:textColorHint="@color/grey"> /*Here it sets color to hintText when edittext has no value */

                    <EditText
                        android:layout_width="match_parent"
                        android:layout_height="50dp"
                        android:layout_gravity="bottom"
                        android:background="@null"
                        android:hint="Username"
                        android:inputType="text"
                        android:maxLength="30"
                        android:paddingEnd="3dp"
                        android:paddingStart="25dp"
                        android:paddingTop="3dp"
                        android:singleLine="true"
                        android:textColor="@color/black"
                        android:textColorHint="@color/black"
                        android:textSize="20sp"/>
                </android.support.design.widget.TextInputLayout>


问:
Angular4: Patternfly Secondary nav not working after bootstrapping the app inside keycloak.init()
This the first time I am configuring my Angular4 application with keycloak authentication. Here I am using patternfly for nav menu. Initially my menu was

For this I had bootstrapped my app like :
main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import {KeycloakService} from './keycloak.service';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

platformBrowserDynamic().bootstrapModule(AppModule);```
</div>
</div>
</p>

<p>But when I had implemented the Keycloak, changed my main.ts:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import {KeycloakService} from './keycloak.service';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

KeycloakService.init()
  .then(() => {
    platformBrowserDynamic().bootstrapModule(AppModule);
  })
  .catch(() => window.location.reload());</code>```

My HTML for the menu is :

        {{'administration_myOrders_label' | translate}}

        {{'administration_myQueues_label' | translate}}

          {{'administration_myQueues_label' | translate}}

              Boston MA - Safety(workorder)

              Boston MA - Safety(workorder)

              Boston MA - Safety(workorder)

```

Here I am using angular-cli in this app. And the Angular 4.3.5 Can somebody please give a solution.
Note : I have tried linking the patternfly css to index.html and remove it from angular-cli.json from webpacking; still could not make it work

答:
Solved the issue by setting a timeout to: $().setupVerticalNavigation(true)

```<code>setTimeout(function() { $().setupVerticalNavigation(true) }, 2000);
</code>```

inside script.js $(document).ready(function(){})

Body:
This the first time I am configuring my Angular4 application with keycloak authentication. Here I am using patternfly for nav menu. Initially my menu was

For this I had bootstrapped my app like :
main.ts

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import {KeycloakService} from './keycloak.service';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

platformBrowserDynamic().bootstrapModule(AppModule);

But when I had implemented the Keycloak, changed my main.ts:

import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import {KeycloakService} from './keycloak.service';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

KeycloakService.init()
  .then(() => {
    platformBrowserDynamic().bootstrapModule(AppModule);
  })
  .catch(() => window.location.reload());

My HTML for the menu is :

        {{'administration_myOrders_label' | translate}}

        {{'administration_myQueues_label' | translate}}

          {{'administration_myQueues_label' | translate}}

              Boston MA - Safety(workorder)

              Boston MA - Safety(workorder)

              Boston MA - Safety(workorder)

Here I am using angular-cli in this app. And the Angular 4.3.5 Can somebody please give a solution.
Note : I have tried linking the patternfly css to index.html and remove it from angular-cli.json from webpacking; still could not make it work

Body:
Solved the issue by setting a timeout to: $().setupVerticalNavigation(true)

setTimeout(function() { $().setupVerticalNavigation(true) }, 2000);

inside script.js $(document).ready(function(){})


问:
How to extract only specific parts from an image?

Hello, I have a task to build an android app that extracts only specific parts of an image.Like, for example, extract only the part of the image that contains the phone number above and then use an OCR to extract the text in that part.

I have already implemented Google's Text Recognition API to extract text from an image and it works good, but I don't want to extract everything, just a specific part.

Is that possible? and if it is, what techniques should I use to solve this problem?

Thank you

答:
The only general technique would be to ask a real person to designate (i.e. using a mouse) the area to be extracted.  But this will fail when the person gets tired, bored, asks for a pay raise, etc.

If you know where the phone number will (always) be in the image (e.g. 50 pixels from the top) then you can find based on that.  But this will fail if the documents are not aligned when scanning, if they are laid out inconsistently and so on.

But, frankly, the most reliable and cheapest solution will be to OCR the entire image and identify the phone number based on the OCR'd characters.


问:
Issue with Apache Kafka server start
I have an issue with start the kafka server in windows

Command
.\bin\windows\kafka-server-start.bat .\config\server.properties

Error Message:

The syntax of the command is incorrect.
Error: Could not find or load main class Files\IBM\WebSphere

Any idea?

答:
I recently faced the same issue. This happens when the host machine has already IBM MQ server installed, which adds few entries to the classpath and it takes precedence while starting kafka server.

You can confirm this by opening a command prompt and run echo %CLASSPATH%. If it returns something similar to the following, the issue is due to the presence of existing MQ installation; however editing environment variables to make kafka run will impact MQ instance.

```<code>D:\Runtimes\IBM\WebSphere MQ\java\lib\com.ibm.mqjms.jar;D:\Runtimes\IBM\WebSphere MQ\java\lib\com.ibm.mq.jar
</code>```

To overcome the problem:

Locate bin/windows/kafka-run-class.bat.

Edit the file and add the following line in the beginning of the script

```<code>set CLASSPATH=""
</code>```

Basically we are resetting the CLASSPATH before the Kakfa startup script attempts to generate the classpath from the Kakfa libraries.

I hope this will solve the issue.

Title: Issue with Apache Kafka server start

Body:
I recently faced the same issue. This happens when the host machine has already IBM MQ server installed, which adds few entries to the classpath and it takes precedence while starting kafka server.

You can confirm this by opening a command prompt and run echo %CLASSPATH%. If it returns something similar to the following, the issue is due to the presence of existing MQ installation; however editing environment variables to make kafka run will impact MQ instance.

D:\Runtimes\IBM\WebSphere MQ\java\lib\com.ibm.mqjms.jar;D:\Runtimes\IBM\WebSphere MQ\java\lib\com.ibm.mq.jar

To overcome the problem:

Locate bin/windows/kafka-run-class.bat.

Edit the file and add the following line in the beginning of the script

set CLASSPATH=""

Basically we are resetting the CLASSPATH before the Kakfa startup script attempts to generate the classpath from the Kakfa libraries.

I hope this will solve the issue.

ContentLicense: CC BY-SA 4.0


问:
Optimizing a troublesome query
I'm generating a PDF, via php from 2 mysql tables, that contains a table.  On larger tables the script is eating up a lot of memory and is starting to become a problem.

My first table contains "inspections."  There are many rows per day.  This has a many to one relationship with the user table.

Table "inspections"

      id
      area
      inpsection_date
      inpsection_agent_1
      inpsection_agent_2
      inpsection_agent_3

id (int)

area (varchar) - is one of 8 "areas" ie: Concrete, Soils, Earthwork

inspection_date (int) - unix timestamp

inspection_agent_1 (int) - a user id

inspection_agent_2 (int) - a user id

inspection_agent_3 (int) - a user id

Second table is the user's info.  All I need is to join the name to the "inspection_agents_x"

      id
      name

The final table, that is going to be in the PDF, needs to organize the data by:

by day

by user, find every "area" that the user "inspected" on that day

                 Concrete
Soils
Earthwork

1/18/2011

Jon Doe
          X

Jane Doe
        X
         X

And so on for each day.  Right now I'm just doing a simple join on the names and then organizing everything on the code end.  I know I'm leaving a lot on the table as far as the queries go, I just can't think of way to do it.

Thanks for any and all help.

答:
```<code>Select U.name
    , user_inspections.inspection_date
    , Min( Case When user_inspections.area = 'Concrete' Then 'X' End ) As Concrete
    , Min( Case When user_inspections.area = 'Soils' Then 'X' End ) As Soils
    , Min( Case When user_inspections.area = 'Earthwork' Then 'X' End ) As Earthwork
From users As U
    Join    (
            Select area, inspection_date, inspection_agent1 As user_id
            From inspections
            Union All
            Select area, inspection_date, inspection_agent2 As user_id
            From inspections
            Union All
            Select area, inspection_date, inspection_agent3 As user_id
            From inspections
            ) As user_inspections
        On user_inspections.user_id = U.id
Group By U.name, user_inspections.inspection_date
</code>```

This is effectively a static crosstab. It means that you will need to know all areas that should be outputted in the query at design time.

One of the reasons this query is problematic is that your schema is not normalized. Your inspection table should look like:

```<code>Create Table inspections
    (
    id int...
    , area varchar...
    , inspection_date date ...
    , inspection_agent int References Users ( Id )
    )
</code>```

That would avoid the inner Union All query to get the output you want.

Title: Optimizing a troublesome query

Body:
Select U.name
    , user_inspections.inspection_date
    , Min( Case When user_inspections.area = 'Concrete' Then 'X' End ) As Concrete
    , Min( Case When user_inspections.area = 'Soils' Then 'X' End ) As Soils
    , Min( Case When user_inspections.area = 'Earthwork' Then 'X' End ) As Earthwork
From users As U
    Join    (
            Select area, inspection_date, inspection_agent1 As user_id
            From inspections
            Union All
            Select area, inspection_date, inspection_agent2 As user_id
            From inspections
            Union All
            Select area, inspection_date, inspection_agent3 As user_id
            From inspections
            ) As user_inspections
        On user_inspections.user_id = U.id
Group By U.name, user_inspections.inspection_date

This is effectively a static crosstab. It means that you will need to know all areas that should be outputted in the query at design time.

One of the reasons this query is problematic is that your schema is not normalized. Your inspection table should look like:

Create Table inspections
    (
    id int...
    , area varchar...
    , inspection_date date ...
    , inspection_agent int References Users ( Id )
    )

That would avoid the inner Union All query to get the output you want.


问:
How to retrieve some specific rows and columns from an excel sheet?

I am reading an xlsx file using java (Apache POI).

I have created a Document class (having all excel column heading as variables)

i have to read each row in the excel and map to the Document class by creating a collection of Document class.

The problem I am facing is that I have to start reading from row 2 and from column 7 to column 35 and map the corresponding values to the document class.

Unable to to figure out exactly how the code should be ?

I have written the following lines of code.

```<code> List sheetData = new ArrayList();
        InputStream excelFile = new BufferedInputStream(new FileInputStream("D:\\Excel file\\data.xlsx"));
        Workbook workBook = new XSSFWorkbook(excelFile); // Creates Workbook
        XSSFSheet sheet = (XSSFSheet) workBook.getSheet("Daily");
        DataFormatter formatter = new DataFormatter();
        for (int i = 7; i <= 35; i++) {
            XSSFRow row = sheet.getRow(i);
            Cell cell = row.getCell(i);
            String val = formatter.formatCellValue(cell);
            sheetData.add(val);
        }
</code>```

答:
You could iterate with an Iterator in the document, but there is also an function "getRow() and getCell()"</p>

```<code>  Workbook workbook = new XSSFWorkbook(excelFile);

  // defines the standard pointer in document in the first Sheet
  XSSFSheet data = this.workbook.getSheetAt(0);
  // you could iterate the document with an iterator
  Iterator<Cell> iterator = this.data.iterator();

  // x/y pointer at the document
  Row row = data.getRow(y);
  Cell pointingCell = row.getCell(x);

  String pointingString = pointingCell.getStringCellValue();
</code>```

Body:
I am reading an xlsx file using java (Apache POI).

I have created a Document class (having all excel column heading as variables)

i have to read each row in the excel and map to the Document class by creating a collection of Document class.

The problem I am facing is that I have to start reading from row 2 and from column 7 to column 35 and map the corresponding values to the document class.

Unable to to figure out exactly how the code should be ?

I have written the following lines of code.

 List sheetData = new ArrayList();
        InputStream excelFile = new BufferedInputStream(new FileInputStream("D:\\Excel file\\data.xlsx"));
        Workbook workBook = new XSSFWorkbook(excelFile); // Creates Workbook
        XSSFSheet sheet = (XSSFSheet) workBook.getSheet("Daily");
        DataFormatter formatter = new DataFormatter();
        for (int i = 7; i <= 35; i++) {
            XSSFRow row = sheet.getRow(i);
            Cell cell = row.getCell(i);
            String val = formatter.formatCellValue(cell);
            sheetData.add(val);
        }

Body:
You could iterate with an Iterator in the document, but there is also an function "getRow() and getCell()"

  Workbook workbook = new XSSFWorkbook(excelFile);

  // defines the standard pointer in document in the first Sheet
  XSSFSheet data = this.workbook.getSheetAt(0);
  // you could iterate the document with an iterator
  Iterator<Cell> iterator = this.data.iterator();

  // x/y pointer at the document
  Row row = data.getRow(y);
  Cell pointingCell = row.getCell(x);

  String pointingString = pointingCell.getStringCellValue();


问:
How to scroll horizontal linearly from right to left on mouse wheel?
I have more than 6 articles and First I have to display 3 articles and when the user scrolls the mouse wheel than it linearly scrolls from right to left side.
Even I also want to hide the scrollbar.

Would you help me out in this?

I tried code but the same issue. Please check it.

jQuery(function ($) {
    $.fn.hScroll = function (amount) {
        amount = amount || 120;
        $(this).bind("DOMMouseScroll mousewheel", function (event) {
            var oEvent = event.originalEvent,
                direction = oEvent.detail ? oEvent.detail * -amount : oEvent.wheelDelta,
                position = $(this).scrollLeft();
            position += direction > 0 ? -amount : amount;
            $(this).scrollLeft(position);
            event.preventDefault();
        })
    };
});

$(document).ready(function() {
    $('.full_screen_100').hScroll(60); // You can pass (optionally) scrolling amount
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.horizontal_scroll .full_screen_100
{
 width: 100%;
 background-color: #fff;
   overflow-y: visible;
    overflow-x: auto;
    white-space: nowrap;
    vertical-align: text-top;
    margin: 0;
    padding: 0;
    clear: both;
    border-spacing: 5px;
}
.horizontal_scroll .full_screen_100 article{
 width: 33%;
 height: 100%;
  display: inline-block;
  border-left: solid 1px #E2E2E2;
   display: table-cell;

}
#left_scroll{
 overflow-y: visible;
    overflow-x: auto;
    white-space: nowrap;
    vertical-align: text-top;
    margin: 0;
    padding: 0;
    clear: both;
    border-spacing: 5px
}</code>```

01
Lorem ipsum dolor sit amet,

02
Lorem ipsum dolor sit amet,

03
Lorem ipsum dolor sit amet,

04
Lorem ipsum dolor sit amet,

05
Lorem ipsum dolor sit amet,

06
Lorem ipsum dolor sit amet,

答:
Using this code you will be able to scroll horizontally </p>

```<code>  $(document).ready(function() {
    $('#left_scroll').bind('mousewheel', function(e) {
      this.scrollLeft -= (e.originalEvent.wheelDelta );
     });
    $('#left_scroll').bind('DOMMouseScroll', function(e) {//Speacially for Mozilla
      this.scrollLeft += (e.originalEvent.detail*40);//Multiply by 40 because Mozilla DOMMouseScroll speed is 3px at time to match scrolling speed of chrome(speed of scrolling 120px at time)
     });
  });
</code>```

Body:
I have more than 6 articles and First I have to display 3 articles and when the user scrolls the mouse wheel than it linearly scrolls from right to left side.
Even I also want to hide the scrollbar.

Would you help me out in this?

I tried code but the same issue. Please check it.

jQuery(function ($) {
    $.fn.hScroll = function (amount) {
        amount = amount || 120;
        $(this).bind("DOMMouseScroll mousewheel", function (event) {
            var oEvent = event.originalEvent,
                direction = oEvent.detail ? oEvent.detail * -amount : oEvent.wheelDelta,
                position = $(this).scrollLeft();
            position += direction > 0 ? -amount : amount;
            $(this).scrollLeft(position);
            event.preventDefault();
        })
    };
});

$(document).ready(function() {
    $('.full_screen_100').hScroll(60); // You can pass (optionally) scrolling amount
});

.horizontal_scroll .full_screen_100
{
 width: 100%;
 background-color: #fff;
   overflow-y: visible;
    overflow-x: auto;
    white-space: nowrap;
    vertical-align: text-top;
    margin: 0;
    padding: 0;
    clear: both;
    border-spacing: 5px;
}
.horizontal_scroll .full_screen_100 article{
 width: 33%;
 height: 100%;
  display: inline-block;
  border-left: solid 1px #E2E2E2;
   display: table-cell;

}
#left_scroll{
 overflow-y: visible;
    overflow-x: auto;
    white-space: nowrap;
    vertical-align: text-top;
    margin: 0;
    padding: 0;
    clear: both;
    border-spacing: 5px
}

01
Lorem ipsum dolor sit amet,

02
Lorem ipsum dolor sit amet,

03
Lorem ipsum dolor sit amet,

04
Lorem ipsum dolor sit amet,

05
Lorem ipsum dolor sit amet,

06
Lorem ipsum dolor sit amet,

Body:
Using this code you will be able to scroll horizontally

  $(document).ready(function() {
    $('#left_scroll').bind('mousewheel', function(e) {
      this.scrollLeft -= (e.originalEvent.wheelDelta );
     });
    $('#left_scroll').bind('DOMMouseScroll', function(e) {//Speacially for Mozilla
      this.scrollLeft += (e.originalEvent.detail*40);//Multiply by 40 because Mozilla DOMMouseScroll speed is 3px at time to match scrolling speed of chrome(speed of scrolling 120px at time)
     });
  });


答:
It's doing three things at the same time.

It's defining a variable called nameOfVariable. Its type is INameOfInterface, which means that anything that implements INameOfInterface can be put there. Any code using it can assume that what it contains is either something that implements INameOfInterface or else is null. This means that any of the properties or methods defined in INameOfInterface can be called on it.

Creating a new object of type ExampleClass.

Putting that new object in that variable.

Title: explanation of INameOfInterface nameOfVariable = new ExampleClass();

Body:
I will appreciate if someone could explain the following C# code

INameOfInterface nameOfVariable = new ExampleClass();

ExampleClass is implementing interface INameOfInterface.
What is this line doing? Thank you all in advance.


问:
deep link not opening application activity
I am using below code to open my activity

```<code><activity
        android:name=".home.AddConferenceActivity"
        android:label="@string/add_conference"
        android:parentActivityName=".home.ConferenceActivity"
        android:screenOrientation="portrait">

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="cokeconference.com"
                android:pathPrefix="/info"
                android:scheme="cokeconference" />
        </intent-filter>
    </activity>
</code>```

and the URL is : cokeconference://cokeconference.com/info/Akshat/1234567891

I tried with both type of HTML files (with Java script as well) as below :

```<code><!DOCTYPE html>
<html>
<body>
    <script language="javascript">
        window.location =      'cokeconference://cokeconference.com/info/Akshat/1234567891';
    </script>
</body>
</html>
</code>```

and

```<code> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"      "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
 <HEAD>
  <TITLE>Base element example</TITLE>
   <a href="cokeconference://cokeconference.com/info/Akshat/1234567891"> Test     Conference Info </a>

</HEAD>
</code>```

Where I am going wrong ?
Thanks in Advance

答:
This is what i do. and its working</p>

```<code>       <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>
            <data android:scheme="http" /> // accept http and https
            <data android:scheme="https"/>
            <data android:host="www.website.com" /> //your host
            <data android:path="/*" /> // detect any path with your host
        </intent-filter>
</code>```

Body:
I am using below code to open my activity

<activity
        android:name=".home.AddConferenceActivity"
        android:label="@string/add_conference"
        android:parentActivityName=".home.ConferenceActivity"
        android:screenOrientation="portrait">

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data
                android:host="cokeconference.com"
                android:pathPrefix="/info"
                android:scheme="cokeconference" />
        </intent-filter>
    </activity>

and the URL is : cokeconference://cokeconference.com/info/Akshat/1234567891

I tried with both type of HTML files (with Java script as well) as below :

<!DOCTYPE html>

and

 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"      "http://www.w3.org/TR/html4/strict.dtd">

  <TITLE>Base element example</TITLE>
    Test     Conference Info

Where I am going wrong ?
Thanks in Advance

Body:
This is what i do. and its working

       <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>
            <data android:scheme="http" /> // accept http and https
            <data android:scheme="https"/>
            <data android:host="www.website.com" /> //your host
            <data android:path="/*" /> // detect any path with your host
        </intent-filter>


问:
Rspec check if a method has been called without calling the method
I am pretty new with RSpec an althought I have been reading a lot about how to check if a method has been called I cannot find a proper solution for the case I need. Sorry if this is a duplicate but couldn't find anything :S

I have an object which implements this function

```<code>def link
  paths.each do |old,new|
    FileUtils.ln_s old, new
  end
end
</code>```

Several links are done based on paths (which is a hash pairing old and new files). My test for this looks like this:

```<code>context "linking files to new ones" do
  it "links a sample to the propper file" do
    @comb.link
    expect(FileUtils).to have_received(:ln_s).with("/example/path/files/old.root",
                                             "example/path/nornmfiles/new.root")
  end
end
</code>```

Since I want to test that at least on of them has been called  have to use the have_received method since the receive ones will fail as soon as the ln_s method gets called with different arguments. The issue is that the test fails because this is a test and I an mot going to actually create the links because the files don't exists so it fails raising an exception because the files don't exists.

How can I test this without actually having to call the method?

This call also fail as soon as a different call is made

```<code>  it "links a sample with a region subpath to the propper file" do
    expect(FileUtils).to receive(:ln_s).with("/example/path/files/pathsuff/old.root",
                                             "/example/path/normfiles/pathsuff/new.root").at_least(:once)
    @comb.link
  end
</code>```

It gives this error:

```<code>RSpec::Mocks::MockExpectationError: FileUtils received :ln_s with unexpected
arguments
   expected: ("/example/path/files/pathsuff/old.root",
 "/example/path/normfiles/pathsuff/new.root")
   got: ("/example/path/files/old.root",
 "/example/path/normfiles/new.root")
</code>```

which is on of the other calls with different methods that can happen that can be called

答:
If you don't care about actual arguments (but rather simple number of calls)

```<code>expect(FileUtils).to receive(:ln_s).with(anything, anything).exactly(paths.length).times
@comb.link
</code>```

If you do care about arguments

```<code>expect(FileUtils).to receive(:ln_s).with('foo', 'bar').ordered
expect(FileUtils).to receive(:ln_s).with('foo2', 'bar2').ordered
expect(FileUtils).to receive(:ln_s).with('foo3', 'bar3').ordered
@comb.link
</code>```

Body:
I am pretty new with RSpec an althought I have been reading a lot about how to check if a method has been called I cannot find a proper solution for the case I need. Sorry if this is a duplicate but couldn't find anything :S

I have an object which implements this function

def link
  paths.each do |old,new|
    FileUtils.ln_s old, new
  end
end

Several links are done based on paths (which is a hash pairing old and new files). My test for this looks like this:

context "linking files to new ones" do
  it "links a sample to the propper file" do
    @comb.link
    expect(FileUtils).to have_received(:ln_s).with("/example/path/files/old.root",
                                             "example/path/nornmfiles/new.root")
  end
end

Since I want to test that at least on of them has been called  have to use the have_received method since the receive ones will fail as soon as the ln_s method gets called with different arguments. The issue is that the test fails because this is a test and I an mot going to actually create the links because the files don't exists so it fails raising an exception because the files don't exists.

How can I test this without actually having to call the method?

This call also fail as soon as a different call is made

  it "links a sample with a region subpath to the propper file" do
    expect(FileUtils).to receive(:ln_s).with("/example/path/files/pathsuff/old.root",
                                             "/example/path/normfiles/pathsuff/new.root").at_least(:once)
    @comb.link
  end

It gives this error:

RSpec::Mocks::MockExpectationError: FileUtils received :ln_s with unexpected
arguments
   expected: ("/example/path/files/pathsuff/old.root",
 "/example/path/normfiles/pathsuff/new.root")
   got: ("/example/path/files/old.root",
 "/example/path/normfiles/new.root")

which is on of the other calls with different methods that can happen that can be called

Body:
If you don't care about actual arguments (but rather simple number of calls)

expect(FileUtils).to receive(:ln_s).with(anything, anything).exactly(paths.length).times
@comb.link

If you do care about arguments

expect(FileUtils).to receive(:ln_s).with('foo', 'bar').ordered
expect(FileUtils).to receive(:ln_s).with('foo2', 'bar2').ordered
expect(FileUtils).to receive(:ln_s).with('foo3', 'bar3').ordered
@comb.link


问:
UML Diagram: Reflexive Association with class instance clarification
I used a plug-in in Eclipse Neon which is called ObjectAid, it's a plug-in that generates a UML Diagram automatically.

Now I understand everything in the generated UML except for one thing, which is the label next to the arrow "~class instance". What does that part mean?

This is just an identical image, not the real one, of the UML generated so please understand that that's just an example.

EDIT:

```<code>//more codes here
static APAGenerator generateAPA = new APAGenerator();

public static void main(String[] args) {
    try {
        generateAPA.run();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
//more codes here
</code>```

答:
@Helquin, you should code in java ?

If you do not specify the visibility the default is private-package. It explains the visibility.

Note: protected in java is also package (see java visibility).

But instead having ~class instance, you should get an underlined ~generateAPA with a cardinality of 1.

Body:
I used a plug-in in Eclipse Neon which is called ObjectAid, it's a plug-in that generates a UML Diagram automatically.

Now I understand everything in the generated UML except for one thing, which is the label next to the arrow "~class instance". What does that part mean?

This is just an identical image, not the real one, of the UML generated so please understand that that's just an example.

EDIT:

//more codes here
static APAGenerator generateAPA = new APAGenerator();

public static void main(String[] args) {
    try {
        generateAPA.run();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
//more codes here


问:
Multiple requests with dredd yml
Using node dredd against my API.
I opted for using yml file as this is a std that is familiar with my team.

Here is an example snippet we have functioning correctly:

```<code>  /api/station/{id}:
    get:
      produces:
        - application/json; charset=utf-8
      parameters:
      - name: id
        in: path
        required: true
        type: string
        description: DynamoDB ID of the station to edit
        x-example: 'daf04a00-c3bf-11e7-a913-b76623d265c4'
      responses:
        200:
          description: Returns a single station
          schema:
            $ref: '#/definitions/station'
</code>```

I think I can guess how to define alternate response object, i assume just add to the object eg:

```<code>  responses:
    200:
      description: Returns a single station
      schema:
        $ref: '#/definitions/station'
    422:
      description: Failed validation
</code>```

In the dredd docs: https://dredd.readthedocs.io/en/latest/how-to-guides.html#multiple-requests-and-responses-within-one-api-blueprint-action

There is an example how to send multiple requests to the same end point.. but this is for the API Blueprint format and not yaml.

Does anyone know how to pass multiple requests to the same endpoint using the yaml format? I cannot see any docs on how to do this

答:
Right below the section in docs you linked there's Testing non-2xx Responses with Swagger:

The Swagger format allows to specify multiple responses for a single operation.
  By default Dredd tests only responses with 2xx status codes. Responses with other
  codes are marked as skipped and can be activated in hooks - see Testing non-2xx Responses with Swagger.

Default responses are ignored by Dredd. Also, as of now,
  only application/json media type is supported in produces and consumes.
  Other media types are skipped.

Title: Multiple requests with dredd yml

Body:
Using node dredd against my API.
I opted for using yml file as this is a std that is familiar with my team.

Here is an example snippet we have functioning correctly:

  /api/station/{id}:
    get:
      produces:
        - application/json; charset=utf-8
      parameters:
      - name: id
        in: path
        required: true
        type: string
        description: DynamoDB ID of the station to edit
        x-example: 'daf04a00-c3bf-11e7-a913-b76623d265c4'
      responses:
        200:
          description: Returns a single station
          schema:
            $ref: '#/definitions/station'

I think I can guess how to define alternate response object, i assume just add to the object eg:

  responses:
    200:
      description: Returns a single station
      schema:
        $ref: '#/definitions/station'
    422:
      description: Failed validation

In the dredd docs: https://dredd.readthedocs.io/en/latest/how-to-guides.html#multiple-requests-and-responses-within-one-api-blueprint-action

There is an example how to send multiple requests to the same end point.. but this is for the API Blueprint format and not yaml.

Does anyone know how to pass multiple requests to the same endpoint using the yaml format? I cannot see any docs on how to do this


问:
Exposing property to databinding in WPF
This is my scenario. I have internal class with a standard int property.

```<code>public class Session : INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;

    private ushort _Level;
    public ushort Level
    {
        get { return _Level; }
    }

    private void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }

    // a timer code here updates the _Level property every 60 seconds
    // and calls OnPropertyChange("Level");
}
</code>```

In my UI window, I have a label that binds to the Session instance and displays the Level value.

```<code> <TextBlock Name="LevelTextBlock" Text="{Binding SessionInstance.Level, StringFormat='0%'}" />
</code>```

And the window constructor has this code:

```<code> public MyWindow()
    {
        SessionInstance = new Session();

        this.InitializeComponent();
    }

    public Session SessionInstance { get; set; }
</code>```

However, as you can guess, when I update the value of _Level, the UI doesn't update the textblock. Adding DependancyProperty inside the Session class is unacceptable. I could do this on the window, but then I still need notifier that would check the value back to the Session instance.
I was wondering if there's elegant way of doing this. I can't think of anything, other than running another timer in the window that would check and refresh the textblock value.
Any thoughts?

答: Are you calling OnPropertyChanged from the property setter?  This is really where it belongs.</p>

Title: Exposing property to databinding in WPF

Body:
This is my scenario. I have internal class with a standard int property.

public class Session : INotifyPropertyChanged {
    public event PropertyChangedEventHandler PropertyChanged;

    private ushort _Level;
    public ushort Level
    {
        get { return _Level; }
    }

    private void OnPropertyChanged(string name)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(name));
    }

    // a timer code here updates the _Level property every 60 seconds
    // and calls OnPropertyChange("Level");
}

In my UI window, I have a label that binds to the Session instance and displays the Level value.

 <TextBlock Name="LevelTextBlock" Text="{Binding SessionInstance.Level, StringFormat='0%'}" />

And the window constructor has this code:

 public MyWindow()
    {
        SessionInstance = new Session();

        this.InitializeComponent();
    }

    public Session SessionInstance { get; set; }

However, as you can guess, when I update the value of _Level, the UI doesn't update the textblock. Adding DependancyProperty inside the Session class is unacceptable. I could do this on the window, but then I still need notifier that would check the value back to the Session instance.
I was wondering if there's elegant way of doing this. I can't think of anything, other than running another timer in the window that would check and refresh the textblock value.
Any thoughts?


问:
VBA : Insert new column to the left of all columns up until the last column
I'm trying to insert a column next to each column starting from D, my issue is that the number of columns will change so I need to identify the last column within the code.

Whenever I run the below it doesn't seem to be identifying the last column correctly.

```<code>Sub InsertColumnsv2()
  Dim iLastCol As Long
  Dim StartCell As Range

  Set StartCell = Range("A1")

  iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column

  For colx = 4 To iLastCol Step 2
    ActiveSheet.UsedRange
    iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column
    Columns(colx).Insert Shift:=xlToRight
  Next colx
End Sub
</code>```

答:
Sine you are adding columns in between, the iLastCol changes, so you need to loop backwards, use Step -1 since you are adding a column each step.

Note: don't rely on ActiveSheet, instead fully qualify your Columns and Cells object using With Worksheets("YourSheetName").

```<code>Option Explicit

Sub InsertColumnsv2()

Dim iLastCol As Long, colx As Long

With Worksheets("Sheet1") ' <-- change to your sheet's name
    iLastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column ' get the last column for the first row

    For colx = iLastCol To 4 Step -1
        .Columns(colx).Insert Shift:=xlToRight
    Next colx
End With

End Sub
</code>```

Body:
I'm trying to insert a column next to each column starting from D, my issue is that the number of columns will change so I need to identify the last column within the code.

Whenever I run the below it doesn't seem to be identifying the last column correctly.

Sub InsertColumnsv2()
  Dim iLastCol As Long
  Dim StartCell As Range

  Set StartCell = Range("A1")

  iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column

  For colx = 4 To iLastCol Step 2
    ActiveSheet.UsedRange
    iLastCol = StartCell.SpecialCells(xlCellTypeLastCell).Column
    Columns(colx).Insert Shift:=xlToRight
  Next colx
End Sub

Body:
Sine you are adding columns in between, the iLastCol changes, so you need to loop backwards, use Step -1 since you are adding a column each step.

Note: don't rely on ActiveSheet, instead fully qualify your Columns and Cells object using With Worksheets("YourSheetName").

Option Explicit

Sub InsertColumnsv2()

Dim iLastCol As Long, colx As Long

With Worksheets("Sheet1") ' <-- change to your sheet's name
    iLastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column ' get the last column for the first row

    For colx = iLastCol To 4 Step -1
        .Columns(colx).Insert Shift:=xlToRight
    Next colx
End With

End Sub


问:
Detect GPS in case if Disabled
I want to detect user trip and when trip is started, I have to get LatLng in every 5 seconds. I am using Google FusedLocationAPI and My problem is until My GPS is enabled then its calculating all distance but Once I disabled GPS the its stucked. How can I Show pending trip if user Disabled GPS in mid of trip ?

My Service class is :

```<code>public class TripStartedService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    public static long UPDATE_INTERVAL_IN_MILLISECONDS = 1000 * 5;
    public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    public GoogleApiClient mGoogleApiClient;
    public LocationRequest mLocationRequest;

    private PendingIntent mPendingIntent;
    IBinder mBinder = new TripStartedService.LocalBinder();
    public static boolean isGPSOn = false;

    @Override
    public void onCreate() {
        super.onCreate();
        Intent mIntentService = new Intent(this, TripStartedIntent.class);
        mPendingIntent = PendingIntent.getService(this, 1, mIntentService, PendingIntent.FLAG_UPDATE_CURRENT);
        buildGoogleApiClient();
    }

    protected synchronized void buildGoogleApiClient() {
        Log.i("", "Building GoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
    }

    private void createLocationRequest() {
        Log.i("TRIP_START_Request", "createLocationRequest()");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onConnected(Bundle bundle) {
        startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i("", "Connection suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i("", "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
    }

    @Override
    public void onLocationChanged(Location location) {
        String message = "Latitude : " + location.getLatitude() + "\n Longitude : " + location.getLongitude() + "\n Accuracy: " + location.getAccuracy();
        Log.i("", "onLocationChanged: " + message);
    }

    private void startLocationUpdates() {
        Log.i("", "Started Location Updates");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mPendingIntent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        isGPSOn = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (mGoogleApiClient.isConnected()) {
            Log.i("GPS init" + " onStartCmd", "Connected");
            return START_STICKY;
        }

        if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) {
            Log.i("Connceti" + " onStartCmd", "GoogleApiClient not Connected");
            mGoogleApiClient.connect();
        }

        return START_STICKY;
    }

    private class LocalBinder extends Binder {
        public TripStartedService getServerInstance() {
            return TripStartedService.this;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopLocationUpdates();
    }

    public void stopLocationUpdates() {
        Log.i("", "Stopped Location Updates");
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mPendingIntent);
    }
}
</code>```

And My Calculation Class is

```<code> if (isGPSOn) {

            try {
                LocDatabaseHelper database = new LocDatabaseHelper(activity);
                Timestamp timestamp_start = new Timestamp(System.currentTimeMillis());
                Timestamp timestamp_end = new Timestamp(System.currentTimeMillis());

                final int TRIP_START_ID = 0;
                ContentValues contentValues = new ContentValues();

                final ArrayList<TripDistanceModels> trip_list_values = database.getTripDistance();

                try {
                    Location loc1 = new Location("");
                    loc1.setLatitude(Double.parseDouble(trip_list_values.get(0).getLatitude()));
                    loc1.setLongitude(Double.parseDouble(trip_list_values.get(0).getLongitude()));

                    Location loc2 = new Location("");
                    loc2.setLatitude(Double.parseDouble(trip_list_values.get(1).getLatitude()));
                    loc2.setLongitude(Double.parseDouble(trip_list_values.get(1).getLongitude()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                contentValues.put(TRIP_STARTED_ID, TRIP_START_ID);
                contentValues.put(TRIP_STARTED_LATTITUDE, start_trip_location.getLatitude());
                contentValues.put(TRIP_STARTED_LONGITUDE, start_trip_location.getLongitude());
                contentValues.put(TRIP_STARTED_TIMESTAMP, String.valueOf(timestamp_start));
                contentValues.put(TRIP_END_TIMESTAMP, String.valueOf(timestamp_end));
                database.tripInsertionOnDetect(TRIP_START_ID, start_trip_location.getLatitude(), start_trip_location.getLongitude(), timestamp_start, timestamp_end, "pending status");
                Log.d("TRIP STARTRED", contentValues.toString());

                final int trip_counts = database.getRowCountForTripStarted();
                final int back_counts = database.getRowCountForBackground();
                Log.e("TRip Database Rows Size", "" + trip_counts + "\t \tBackGroundTable Rows : " + back_counts + "\tGPS>>>: " + Boolean.toString(isGPSOn));
                activity.stopService(new Intent(activity, BackgroundLocationService.class));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
</code>```

答:
If your gps is not enable then you can use cell tower location. it's not accurate. you can get near by location.</p>

```<code>if (isNetworkEnabled) {
           locationManager.requestLocationUpdates(
              LocationManager.NETWORK_PROVIDER,
              MIN_TIME_BW_UPDATES,
              MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

           Log.d("Network", "Network");
           if (locationManager != null) {
              location = locationManager
                 .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

              if (location != null) {
                 latitude = location.getLatitude();
                 longitude = location.getLongitude();
              }
           }
        }
</code>```

Title: Detect GPS in case if Disabled

Body:
I want to detect user trip and when trip is started, I have to get LatLng in every 5 seconds. I am using Google FusedLocationAPI and My problem is until My GPS is enabled then its calculating all distance but Once I disabled GPS the its stucked. How can I Show pending trip if user Disabled GPS in mid of trip ?

My Service class is :

public class TripStartedService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    public static long UPDATE_INTERVAL_IN_MILLISECONDS = 1000 * 5;
    public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;
    public GoogleApiClient mGoogleApiClient;
    public LocationRequest mLocationRequest;

    private PendingIntent mPendingIntent;
    IBinder mBinder = new TripStartedService.LocalBinder();
    public static boolean isGPSOn = false;

    @Override
    public void onCreate() {
        super.onCreate();
        Intent mIntentService = new Intent(this, TripStartedIntent.class);
        mPendingIntent = PendingIntent.getService(this, 1, mIntentService, PendingIntent.FLAG_UPDATE_CURRENT);
        buildGoogleApiClient();
    }

    protected synchronized void buildGoogleApiClient() {
        Log.i("", "Building GoogleApiClient");
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
    }

    private void createLocationRequest() {
        Log.i("TRIP_START_Request", "createLocationRequest()");
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public void onConnected(Bundle bundle) {
        startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i("", "Connection suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i("", "Connection failed: ConnectionResult.getErrorCode() = " + connectionResult.getErrorCode());
    }

    @Override
    public void onLocationChanged(Location location) {
        String message = "Latitude : " + location.getLatitude() + "\n Longitude : " + location.getLongitude() + "\n Accuracy: " + location.getAccuracy();
        Log.i("", "onLocationChanged: " + message);
    }

    private void startLocationUpdates() {
        Log.i("", "Started Location Updates");
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mPendingIntent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        isGPSOn = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);

        if (mGoogleApiClient.isConnected()) {
            Log.i("GPS init" + " onStartCmd", "Connected");
            return START_STICKY;
        }

        if (!mGoogleApiClient.isConnected() || !mGoogleApiClient.isConnecting()) {
            Log.i("Connceti" + " onStartCmd", "GoogleApiClient not Connected");
            mGoogleApiClient.connect();
        }

        return START_STICKY;
    }

    private class LocalBinder extends Binder {
        public TripStartedService getServerInstance() {
            return TripStartedService.this;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopLocationUpdates();
    }

    public void stopLocationUpdates() {
        Log.i("", "Stopped Location Updates");
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mPendingIntent);
    }
}

And My Calculation Class is

 if (isGPSOn) {

            try {
                LocDatabaseHelper database = new LocDatabaseHelper(activity);
                Timestamp timestamp_start = new Timestamp(System.currentTimeMillis());
                Timestamp timestamp_end = new Timestamp(System.currentTimeMillis());

                final int TRIP_START_ID = 0;
                ContentValues contentValues = new ContentValues();

                final ArrayList<TripDistanceModels> trip_list_values = database.getTripDistance();

                try {
                    Location loc1 = new Location("");
                    loc1.setLatitude(Double.parseDouble(trip_list_values.get(0).getLatitude()));
                    loc1.setLongitude(Double.parseDouble(trip_list_values.get(0).getLongitude()));

                    Location loc2 = new Location("");
                    loc2.setLatitude(Double.parseDouble(trip_list_values.get(1).getLatitude()));
                    loc2.setLongitude(Double.parseDouble(trip_list_values.get(1).getLongitude()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                contentValues.put(TRIP_STARTED_ID, TRIP_START_ID);
                contentValues.put(TRIP_STARTED_LATTITUDE, start_trip_location.getLatitude());
                contentValues.put(TRIP_STARTED_LONGITUDE, start_trip_location.getLongitude());
                contentValues.put(TRIP_STARTED_TIMESTAMP, String.valueOf(timestamp_start));
                contentValues.put(TRIP_END_TIMESTAMP, String.valueOf(timestamp_end));
                database.tripInsertionOnDetect(TRIP_START_ID, start_trip_location.getLatitude(), start_trip_location.getLongitude(), timestamp_start, timestamp_end, "pending status");
                Log.d("TRIP STARTRED", contentValues.toString());

                final int trip_counts = database.getRowCountForTripStarted();
                final int back_counts = database.getRowCountForBackground();
                Log.e("TRip Database Rows Size", "" + trip_counts + "\t \tBackGroundTable Rows : " + back_counts + "\tGPS>>>: " + Boolean.toString(isGPSOn));
                activity.stopService(new Intent(activity, BackgroundLocationService.class));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

Body:
If your gps is not enable then you can use cell tower location. it's not accurate. you can get near by location.

if (isNetworkEnabled) {
           locationManager.requestLocationUpdates(
              LocationManager.NETWORK_PROVIDER,
              MIN_TIME_BW_UPDATES,
              MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

           Log.d("Network", "Network");
           if (locationManager != null) {
              location = locationManager
                 .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

              if (location != null) {
                 latitude = location.getLatitude();
                 longitude = location.getLongitude();
              }
           }
        }