问:
Snap Recyclerview item to Center when loaded
I am using an infinite scroll for recyclerview with X items which repeats.
Also i want am using PagerSnapHelper() to snap the scroll like viewpager.

So initially when the list is loaded the display is like -

As soon as i start scrolling on either side left or right the PageSnapHelper() come in work an snap it like viewpager with center alignment like this -

I want to show recyclerview as like 2nd image when initially loaded. Please tell what to do next to acheive that.

here is the code snipet -

```<code>linearLayoutManager = new LinearLayoutManager(mContext,   LinearLayoutManager.HORIZONTAL, false);
this.recyclerView.setLayoutManager(linearLayoutManager);
SnapHelper snapHelper = new PagerSnapHelper();
adapterCarousel = new AdapterCarousel(mContext, glideRequestManager);
adapterCarousel.setViewType(RECYCLER_VIEW_TYPE_NORMAL);
adapterCarousel.setCarousel(carousel);
this.recyclerView.setAdapter(adapterCarousel);
snapHelper.attachToRecyclerView(recyclerView);
linearLayoutManager.scrollToPosition(Integer.MAX_VALUE / 2);
</code>```

答:
```<code>   linearLayoutManager.scrollToPosition((Integer.MAX_VALUE / 2)-1);
   linearLayoutManager.smoothScrollToPosition(Integer.MAX_VALUE / 2);
</code>```

If there is a better way, please tell me

Body:
I am using an infinite scroll for recyclerview with X items which repeats.
Also i want am using PagerSnapHelper() to snap the scroll like viewpager.

So initially when the list is loaded the display is like -

As soon as i start scrolling on either side left or right the PageSnapHelper() come in work an snap it like viewpager with center alignment like this -

I want to show recyclerview as like 2nd image when initially loaded. Please tell what to do next to acheive that.

here is the code snipet -

linearLayoutManager = new LinearLayoutManager(mContext,   LinearLayoutManager.HORIZONTAL, false);
this.recyclerView.setLayoutManager(linearLayoutManager);
SnapHelper snapHelper = new PagerSnapHelper();
adapterCarousel = new AdapterCarousel(mContext, glideRequestManager);
adapterCarousel.setViewType(RECYCLER_VIEW_TYPE_NORMAL);
adapterCarousel.setCarousel(carousel);
this.recyclerView.setAdapter(adapterCarousel);
snapHelper.attachToRecyclerView(recyclerView);
linearLayoutManager.scrollToPosition(Integer.MAX_VALUE / 2);

Body:
   linearLayoutManager.scrollToPosition((Integer.MAX_VALUE / 2)-1);
   linearLayoutManager.smoothScrollToPosition(Integer.MAX_VALUE / 2);

If there is a better way, please tell me


来源: stackexchange

问:
Recursively delete particular directories and files
I want to delete particular directory in following mainDir.

```<code>public readonly DirectoryInfo mainDir = new DirectoryInfo("C:\Export\DataFiles\");
</code>```

The mainDir may contain subdirectories and subdirectories may contain more directories...

I only get file name with fullpath.. I want to delete all parents directories of the file (including files), but not the main directory. What is the better way to do it?

Example files:

```<code>C:\Export\DataFiles\20392\483928\292833\file1.txt
C:\Export\DataFiles\20392\483928\292833\file2.txt
</code>```

Here, I want to delete C:\Export\DataFiles\20392

```<code>C:\Export\DataFiles\3222\file1.txt
</code>```

Here, I want to delete C:\Export\DataFiles\3222

```<code>C:\Export\DataFiles\4342\425622\file1.txt
C:\Export\DataFiles\4342\425622\file2.txt
C:\Export\DataFiles\4342\425622\file3.txt
</code>```

Here, I want to delete C:\Export\DataFiles\4342

EDIT:

I cannot use following:

```<code>mainDir.delete(true);
</code>```

It will delete all the directories and files in the mainDir.

答:
This is called "itterating through a directory tree". A fairly simple problem, usually solved via recursion:
https://msdn.microsoft.com/en-us/library/bb513869.aspx

"Find every entry in the directory. If if it is a directory itself, recurse into it. Then delete the directory. Delete all non-directories (files) you find."

Once you have the full path a file, you can delete it. And that code finds you the full paths of all files and folders in a directory tree.

ContentLicense: CC BY-SA 3.0

Body:
I want to delete particular directory in following mainDir.

public readonly DirectoryInfo mainDir = new DirectoryInfo("C:\Export\DataFiles\");

The mainDir may contain subdirectories and subdirectories may contain more directories...

I only get file name with fullpath.. I want to delete all parents directories of the file (including files), but not the main directory. What is the better way to do it?

Example files:

C:\Export\DataFiles\20392\483928\292833\file1.txt
C:\Export\DataFiles\20392\483928\292833\file2.txt

Here, I want to delete C:\Export\DataFiles\20392

C:\Export\DataFiles\3222\file1.txt

Here, I want to delete C:\Export\DataFiles\3222

C:\Export\DataFiles\4342\425622\file1.txt
C:\Export\DataFiles\4342\425622\file2.txt
C:\Export\DataFiles\4342\425622\file3.txt

Here, I want to delete C:\Export\DataFiles\4342

EDIT:

I cannot use following:

mainDir.delete(true);

It will delete all the directories and files in the mainDir.


问:
OpenGL VAO not working as intended
From what I understand VAOs should store the states needed for rendering like the buffers and the attribute pointers.
But the problem I am having is, I need to set-up the VAO and load the data to the buffers every time before rendering or else the things being drawn is wrong.

I am using a class called mesh that hold the VAO and VBO handles as protected GLuint variables to initialize and load the vertex data into the GPU.

I searched for hours but it seams no one else is having the same problem.

So if I initialize like this and render  like this :

```<code>mesh coneMesh, sphereMesh, boxMesh;

coneMesh.setup(coneVertex, GL_STATIC_DRAW, 1, ShaderA);
sphereMesh.setup(*sphereVertex, GL_STATIC_DRAW,1, ShaderA);
boxMesh.setup(boxVertex, GL_STATIC_DRAW, 1, ShaderA);
</code>```

and in the rendering loop:

```<code>//sphereMesh.setup(*sphereVertex, GL_STATIC_DRAW,1, ShaderA);
sphereMesh.render(GL_TRIANGLE_STRIP,0,sphereVertex->size(),0);
sphereMesh.render(GL_TRIANGLE_STRIP,0,sphereVertex->size(),1);

//coneMesh.setup(coneVertex, GL_STATIC_DRAW, 1, ShaderA);
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE);
coneMesh.render(GL_TRIANGLE_STRIP,0,coneVertex.size(),2);
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL);

//boxMesh.setup(boxVertex, GL_STATIC_DRAW, 1, ShaderA);
boxMesh.render(GL_LINE_LOOP, 0, boxVertex.size());

glfwSwapBuffers(window);
</code>```

If I take out he comments and reinitialize the VAO and reload the data every thing works perfectly, can someone please tell me what I am doing wrong and how to fix it? Thank You

```<code>int mesh::setup(std::vector<vertex> &vert, GLenum BufferDataUsage, GLuint        nuberOfAttribute, shader &shad)
{

this->nuberOfAttribute = nuberOfAttribute;
this->shad = &shad;

std::vector<glm::vec3> position;
std::vector<glm::vec2> textureCoord;

position.reserve(vert.size());
textureCoord.reserve(vert.size());

for(unsigned int i; i<vert.size(); i++)
{
    position.push_back(vert[i].pos());
    textureCoord.push_back((vert[i].textureCoordinate));
}

glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

glGenBuffers(1,&vbo[0]);
glBindBuffer(GL_ARRAY_BUFFER,vbo[0]);
glBufferData(GL_ARRAY_BUFFER,(GLsizeiptr)vert.size() * sizeof (position[0]), &position[0], BufferDataUsage);
glEnableVertexAttribArray(0);
glVertexAttribPointer ( ( GLuint ) 0, 3, GL_FLOAT, GL_FALSE,0,0);

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

std::cout <<vbo[0]<<std::endl;
return 0;
}
</code>```

And the rendering function:

```<code>void mesh::render(GLenum DrawHint,  GLint first,GLsizei count)
{
shad->bind();//glUseProgram(id)
//set up transform matrix and set up uniform

glBindVertexArray(vao);
glDrawArrays(DrawHint, first, count);
glBindVertexArray(0);
</code>```

Edit

1.)I have ran the code in another machine and the problem didn't go away. So it's probably not a driver bug.

2.)I can confirm that the different VAO and VBO are not overwriting each other since the handles on each of them is unique.

3.) Now I have no idea what could possibly course this problem.

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

Unbinding the VBO has to go after unbinding the VAO, as otherwise VAO will remember your VBO not being bound.

EDIT

As pointed out in comments, it's OK to unbind GL_ARRAY_BUFFER before unbinding the VAO. It wouldn't be OK for GL_ELEMENT_ARRAY_BUFFER, which is not used in this example though.

Therefore, the problem must lie elsewhere.

Title: OpenGL VAO not working as intended

Body:
From what I understand VAOs should store the states needed for rendering like the buffers and the attribute pointers.
But the problem I am having is, I need to set-up the VAO and load the data to the buffers every time before rendering or else the things being drawn is wrong.

I am using a class called mesh that hold the VAO and VBO handles as protected GLuint variables to initialize and load the vertex data into the GPU.

I searched for hours but it seams no one else is having the same problem.

So if I initialize like this and render  like this :

mesh coneMesh, sphereMesh, boxMesh;

coneMesh.setup(coneVertex, GL_STATIC_DRAW, 1, ShaderA);
sphereMesh.setup(*sphereVertex, GL_STATIC_DRAW,1, ShaderA);
boxMesh.setup(boxVertex, GL_STATIC_DRAW, 1, ShaderA);

and in the rendering loop:

//sphereMesh.setup(*sphereVertex, GL_STATIC_DRAW,1, ShaderA);
sphereMesh.render(GL_TRIANGLE_STRIP,0,sphereVertex->size(),0);
sphereMesh.render(GL_TRIANGLE_STRIP,0,sphereVertex->size(),1);

//coneMesh.setup(coneVertex, GL_STATIC_DRAW, 1, ShaderA);
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE);
coneMesh.render(GL_TRIANGLE_STRIP,0,coneVertex.size(),2);
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL);

//boxMesh.setup(boxVertex, GL_STATIC_DRAW, 1, ShaderA);
boxMesh.render(GL_LINE_LOOP, 0, boxVertex.size());

glfwSwapBuffers(window);

If I take out he comments and reinitialize the VAO and reload the data every thing works perfectly, can someone please tell me what I am doing wrong and how to fix it? Thank You

int mesh::setup(std::vector<vertex> &vert, GLenum BufferDataUsage, GLuint        nuberOfAttribute, shader &shad)
{

this->nuberOfAttribute = nuberOfAttribute;
this->shad = &shad;

std::vector<glm::vec3> position;
std::vector<glm::vec2> textureCoord;

position.reserve(vert.size());
textureCoord.reserve(vert.size());

for(unsigned int i; i<vert.size(); i++)
{
    position.push_back(vert[i].pos());
    textureCoord.push_back((vert[i].textureCoordinate));
}

glGenVertexArrays(1, &vao);
glBindVertexArray(vao);

glGenBuffers(1,&vbo[0]);
glBindBuffer(GL_ARRAY_BUFFER,vbo[0]);
glBufferData(GL_ARRAY_BUFFER,(GLsizeiptr)vert.size() * sizeof (position[0]), &position[0], BufferDataUsage);
glEnableVertexAttribArray(0);
glVertexAttribPointer ( ( GLuint ) 0, 3, GL_FLOAT, GL_FALSE,0,0);

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

std::cout <<vbo[0]<<std::endl;
return 0;
}

And the rendering function:

void mesh::render(GLenum DrawHint,  GLint first,GLsizei count)
{
shad->bind();//glUseProgram(id)
//set up transform matrix and set up uniform

glBindVertexArray(vao);
glDrawArrays(DrawHint, first, count);
glBindVertexArray(0);

Edit

1.)I have ran the code in another machine and the problem didn't go away. So it's probably not a driver bug.

2.)I can confirm that the different VAO and VBO are not overwriting each other since the handles on each of them is unique.

3.) Now I have no idea what could possibly course this problem.

Body:
glBindBuffer(GL_ARRAY_BUFFER,0);
glBindVertexArray(0);

Unbinding the VBO has to go after unbinding the VAO, as otherwise VAO will remember your VBO not being bound.

EDIT

As pointed out in comments, it's OK to unbind GL_ARRAY_BUFFER before unbinding the VAO. It wouldn't be OK for GL_ELEMENT_ARRAY_BUFFER, which is not used in this example though.

Therefore, the problem must lie elsewhere.


问:
communication lost detection CAN
I have been implementing motor control
software. This control software runs in
one microcontroller which communicates
with different microcontroller over CAN
bus. I need information about CAN "failure"
(communication lost) in the control software.
I am not sure what could be the appropriate
symptom of the CAN "failure". I have an idea that
I would check whether the CAN periphery is in the
Bus off state. If so, I would trigger some timer
and after expiration of for example 1 s I would
take the communication for lost. As soon as the
CAN periphery transits into the Error active state
I would take the communication for secure again.
Is it possible or anybody solve this in different
manner? Thanks for any ideas.</p>

答:
There are two completely different things to consider:

On the application level, does whoever you are communicating with respond in time and do they send valid data?

Are there hardware errors on the CAN bus?

Regarding 2), bus-off and CAN error frames are hardware errors, usually caused by rather severe things such as incorrect installation, short between CAN high/low, bad wires/connectors, EMI noise, bad/no termination, crappy signal ground and/or shield etc. These are mostly non-recoverable errors that the software can't do much about. The only thing you can do is to display some diagnostics.

Rather than messing around and examining various CAN bus errors, this kind of rugged firmware (assuming industry/automotive) should be designed so that it just checks if you have received correct data in time, as required by 1). Because that's the only thing that is relevant to you. If the bus is feeling ill, if there are error frames, but you are still receiving data - fine, just keep running for as long as you are able.

So the only thing of interest is to use a timer with a sensible timeout - depending on how fast the controlled machine is moving (500ms is a general industry standard, though faster machines might need a shorter timeout). Each time you receive a valid (series of) CAN package(s) you refresh this timer. When the timer elapses, revert to a safe state.

When/how to recover from the safe state is highly application-specific. Many safety-critical applications forbid a recovery from a critical error without an explicit command from an operator.

Title: communication lost detection CAN


问:
how to make the following scala immutable
Suppose I have the following code:

BroadcastMessage gets a list of groups of students in the form of iterators that can only be traversed once

On call to sendMessage it will send message to all students in the groups.

```<code>class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    EmailClient.sendMessage(student.email,message)
  }

}

case class Student(id: String,email:String)
</code>```

Say that student can exist in several groups and we don't want to send him more than one email.

The mutable solution would be to add mutable set and to add the id of the student to the set and only send the message if the id exists in the set.

```<code>class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {
  // evil mutable set
  private var set:scala.collection.mutable.Set[String] = Set()

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    if (set.add(student.id)) {
      EmailClient.sendMessage(student.email, message)
    }
  }

}
</code>```

How do I implement it in immutable way?

答:
I managed to do do this. I think I lost some readability but it is mutable:</p>

```<code>class BroadcastMessage(message: String, groups: List[Iterator[Student]]) {

  def sendMessage(): Unit = {
    groups.foldLeft[Set[String]](Set.empty)(sendMessage)
  }

  private def sendMessage(sent: Set[String], group: Iterator[Student]):Set[String] = {
    group.foldLeft[Set[String]](sent)(sendMessage)
  }

  private def sendMessage(sent: Set[String], student: Student): Set[String] = {
    if (!sent.contains(student.id)) {
      EmailClient.sendMessage(student.email, message)
      return sent + student.id
    }
    sent
  }

}
</code>```

Body:
Suppose I have the following code:

BroadcastMessage gets a list of groups of students in the form of iterators that can only be traversed once

On call to sendMessage it will send message to all students in the groups.

class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    EmailClient.sendMessage(student.email,message)
  }

}

case class Student(id: String,email:String)

Say that student can exist in several groups and we don't want to send him more than one email.

The mutable solution would be to add mutable set and to add the id of the student to the set and only send the message if the id exists in the set.

class BroadcastMessage(message:String,groups:List[Iterator[Student]]) {
  // evil mutable set
  private var set:scala.collection.mutable.Set[String] = Set()

  def sendMessage:Unit = {
      groups.foreach(group=>group.foreach(sendeMessage))
  }

  private def sendMessage(student:Student): Unit ={
    if (set.add(student.id)) {
      EmailClient.sendMessage(student.email, message)
    }
  }

}

How do I implement it in immutable way?

Body:
I managed to do do this. I think I lost some readability but it is mutable:

class BroadcastMessage(message: String, groups: List[Iterator[Student]]) {

  def sendMessage(): Unit = {
    groups.foldLeft[Set[String]](Set.empty)(sendMessage)
  }

  private def sendMessage(sent: Set[String], group: Iterator[Student]):Set[String] = {
    group.foldLeft[Set[String]](sent)(sendMessage)
  }

  private def sendMessage(sent: Set[String], student: Student): Set[String] = {
    if (!sent.contains(student.id)) {
      EmailClient.sendMessage(student.email, message)
      return sent + student.id
    }
    sent
  }

}


问:
How to display column name in jquery table?
I want to display my data from SQLite in jquery table. When I run the app in my mobile, it only shows my data from SQLite. The column name is not showing.  How can I display the column name?

table in html

```<code>     <div data-role="main" class="ui-content">
         <table data-role="table" id="mytable" data-mode="reflow">
            <thead>
             <tr>
              <th>ID</th>
              <th>event</th>
              <th>location</th>
             </tr>
            </thead>
            <tbody id="abc"></tbody>
         </table>
    </div>
</code>```

javascript

```<code>function view() {
if (db==null) {
    alert('Error: Database is null.');
    return;
}

db.executeSql(
    'SELECT `id`, `data`, `data2` FROM `info` ORDER BY `data` ASC',
    [],
    function(resultset) {
        var length = resultset.rows.length;
        for(var i=0; i<length; i++) {
            $('#abc').append('<tr><th>'+resultset.rows.item(i).id+'</th>','<td>'+resultset.rows.item(i).data+'</td>','<td>'+resultset.rows.item(i).data2+'</td></tr>');
        }
        //$("#listData").listview( "refresh" );
    },
    function(error) {
        alert('Error: '+error.message);
    }
);
</code>```

答:
You have TH tag in your rows, try to use only TD in your TBODY.

EDIT:

Have you look at the CSS?

Body:
I want to display my data from SQLite in jquery table. When I run the app in my mobile, it only shows my data from SQLite. The column name is not showing.  How can I display the column name?

table in html

              ID
              event
              location

javascript

function view() {
if (db==null) {
    alert('Error: Database is null.');
    return;
}

db.executeSql(
    'SELECT `id`, `data`, `data2` FROM `info` ORDER BY `data` ASC',
    [],
    function(resultset) {
        var length = resultset.rows.length;
        for(var i=0; i<length; i++) {
            $('#abc').append('
'+resultset.rows.item(i).id+'	',''+resultset.rows.item(i).data+'	',''+resultset.rows.item(i).data2+'
');
        }
        //$("#listData").listview( "refresh" );
    },
    function(error) {
        alert('Error: '+error.message);
    }
);


问:
pthread_join - multiple threads waiting
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time.

If I have multiple threads waiting to insert using pthread_join then spawning a new thread
when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assume that the thread that receives the "thread complete" signal first will spawn a new thread blocking the others from creating new threads.

```<code>/* --- GLOBAL --- */
pthread_t insertThread;

/* --- DIFFERENT THREADS --- */
// Wait for Current insert to finish
pthread_join(insertThread, NULL);

// Done start a new one
pthread_create(&insertThread, NULL, Insert, Data);
</code>```

Thank you for the replies

The program is basically a huge hash table which takes requests from clients through Sockets.

Each new client connection spawns a new thread from which it can then perform multiple operations, specifically lookups or inserts. lookups can be conducted in parallel. But inserts need to be "re-combined" into a single thread. You could say that lookup operations could be done without spawning a new thread for the client, however they can take a while causing the server to lock, dropping new requests. The design tries to minimize system calls and thread creation as much as possible.

But now that i know it's not safe the way i first thought I should be able to cobble something together

Thanks

答:
It seems to me that you want to serialise inserts to the hashtable.

For this you want a lock - not spawning new threads.

Title: pthread_join - multiple threads waiting

Body:
Using POSIX threads & C++, I have an "Insert operation" which can only be done safely one at a time.

If I have multiple threads waiting to insert using pthread_join then spawning a new thread
when it finishes. Will they all receive the "thread complete" signal at once and spawn multiple inserts or is it safe to assume that the thread that receives the "thread complete" signal first will spawn a new thread blocking the others from creating new threads.

/* --- GLOBAL --- */
pthread_t insertThread;

/* --- DIFFERENT THREADS --- */
// Wait for Current insert to finish
pthread_join(insertThread, NULL);

// Done start a new one
pthread_create(&insertThread, NULL, Insert, Data);

Thank you for the replies

The program is basically a huge hash table which takes requests from clients through Sockets.

Each new client connection spawns a new thread from which it can then perform multiple operations, specifically lookups or inserts. lookups can be conducted in parallel. But inserts need to be "re-combined" into a single thread. You could say that lookup operations could be done without spawning a new thread for the client, however they can take a while causing the server to lock, dropping new requests. The design tries to minimize system calls and thread creation as much as possible.

But now that i know it's not safe the way i first thought I should be able to cobble something together

Thanks

LastEditorDisplayName: Hosam Aly

OwnerDisplayName: Douglas Leeder

ContentLicense: CC BY-SA 2.5


问:
Calling external contract in solidity dynamically
I am trying to make a contract have a function that is capable of calling functions of another contract. The key part of my goal is that the contract should not be able to be deployed without any import statements and will not know the name of the contract by default. In other words the user of this contract would input the called contracts data (i.e. address, name) as parameters. What is the best way to accomplish this?</p>

答:
You can do this by using an interface, as suggested by Rob Hitchens, or you could define the interface dynamically and execute a method by using .call, .callcode, .delegatecall.

Here's an example:

```<code>contract ContractsCaller {

    function execute(address contractAt, uint _i, bytes32 _b) returns (bool) {
        return contractAt.call(bytes4(sha3("testMethod(uint256,bytes32)")), _i, _b);
    }
}

contract Test {

    uint256 public i;
    bytes32 public b;

    function testMethod(uint256 _i, bytes32 _b) {
        i = _i;
        b = _b;
    }
}
</code>```

Test can be defined in a separate file. ContractsCaller doesn't need to know anything about Test besides its address and the signature of the method it's calling.

The signature of the method is the first 4 bytes of the method name and the types of its parameters:

```<code>bytes4(sha3("testMethod(uint256,bytes32)"))
</code>```

More information about .call, .callcode, .delegatecall.

Body:
You can do this by using an interface, as suggested by Rob Hitchens, or you could define the interface dynamically and execute a method by using .call, .callcode, .delegatecall.

Here's an example:

contract ContractsCaller {

    function execute(address contractAt, uint _i, bytes32 _b) returns (bool) {
        return contractAt.call(bytes4(sha3("testMethod(uint256,bytes32)")), _i, _b);
    }
}

contract Test {

    uint256 public i;
    bytes32 public b;

    function testMethod(uint256 _i, bytes32 _b) {
        i = _i;
        b = _b;
    }
}

Test can be defined in a separate file. ContractsCaller doesn't need to know anything about Test besides its address and the signature of the method it's calling.

The signature of the method is the first 4 bytes of the method name and the types of its parameters:

bytes4(sha3("testMethod(uint256,bytes32)"))

More information about .call, .callcode, .delegatecall.


问:
Fix for wordpress loop
I am new too wordpress and have one problem. I finaly understand post loop and it work well but have one problem. For example: I have two pages of my posts (all are 6). In one page i have five posts (excerpt only) and on secound page i have one post only and in this case (when on one of my pages i have only one post it change to content post but it need to stay excerpt). So my question is what can i change in my code to make it work well in this case when on some page left only one post?

It's my loop:

```<code>    <?php if (have_posts()) : ?>

  <?php if (($wp_query->post_count) > 1) : ?>
     <?php while (have_posts()) : the_post(); ?>
       <!-- Do your post header stuff here for excerpts-->
          <?php the_excerpt() ?>
       <!-- Do your post footer stuff here for excerpts-->
     <?php endwhile; ?>

  <?php else : ?>

     <?php while (have_posts()) : the_post(); ?>
       <!-- Do your post header stuff here for single post-->
          <?php the_content() ?>
       <!-- Do your post footer stuff here for single post-->
     <?php endwhile; ?>

  <?php endif; ?>

<?php else : ?>
     <!-- Stuff to do if there are no posts-->

<?php endif; ?>
</code>```

答:
Use the posts_per_page parameter to an array and start the loop.

```<code>$args = array( 'post_type' => 'post', 'posts_per_page' => 4,'category' => 2, 'paged' => $paged );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
  $content = get_the_content();
  echo $content;
endwhile;
</code>```

Here I have printed the 4 contents from the archive. So the page will only have 4 posts in it. You can change the value based on your need.

I have used and got the output. Hope this helps you too.

Title: Fix for wordpress loop

Body:
I am new too wordpress and have one problem. I finaly understand post loop and it work well but have one problem. For example: I have two pages of my posts (all are 6). In one page i have five posts (excerpt only) and on secound page i have one post only and in this case (when on one of my pages i have only one post it change to content post but it need to stay excerpt). So my question is what can i change in my code to make it work well in this case when on some page left only one post?

It's my loop:

    <?php if (have_posts()) : ?>

  <?php if (($wp_query->post_count) > 1) : ?>
     <?php while (have_posts()) : the_post(); ?>

          <?php the_excerpt() ?>

     <?php endwhile; ?>

  <?php else : ?>

     <?php while (have_posts()) : the_post(); ?>

          <?php the_content() ?>

     <?php endwhile; ?>

  <?php endif; ?>

<?php else : ?>

<?php endif; ?>

Body:
Use the posts_per_page parameter to an array and start the loop.

$args = array( 'post_type' => 'post', 'posts_per_page' => 4,'category' => 2, 'paged' => $paged );
$wp_query = new WP_Query($args);
while ( have_posts() ) : the_post();
  $content = get_the_content();
  echo $content;
endwhile;

Here I have printed the 4 contents from the archive. So the page will only have 4 posts in it. You can change the value based on your need.

I have used and got the output. Hope this helps you too.


问:
Ignore certain packages and their dependencies with pip freeze
Title basically says it all. How can I tell pip freeze to ignore certain packages, like pylint and pep8, and their dependencies?

答:
My approach is the following:

I my .bashrc I create the following alias: alias pipfreezeignore='pip freeze | grep -vFxf ignore_requirements.txt'

Create the virtual environment, and install first all the packages that I do not want to keep track of (i.e. pip install jedi flake8 importmagic autopep8 yapf).

Immediately save them in a ignore_requirements.txt file, as in pip freeze > ignore_requirements.txt.

Install the rest of packages (e.g. pip install django)

Use pipfreezeignore > requirements.txt (in the same folder where ignore_requirements.txt is) so I just get in requirements.txt the installed packages that are not in ignore_requirements.txt

If you always want to ignore the same packages (through all your virtual environments), you might redefine the alias as in alias pipfreezeignore='pip freeze | grep -vFxf /abs/path/to/ignore_requirements.txt'
Just make sure that no packages from ignore_requirements.txt are not actually necessary for your project.


问:
How to update id set from 1?
I have an id i.e primary key and auto increment. Is there any query to update my existing id and make my id start from 1 and next id 2 and so on..

For example

```<code>id  name
3   ABC
5   XYZ
9   PQR
</code>```

NOTE: id is already primary and auto increment and I don't want truncate my id.

if possible i want to get

```<code>id  name
1   ABC
2   XYZ
3   PQR
</code>```

ALTER TABLE table AUTO_INCREMENT = 1; is not my solution.

Thanks

答:
Is there any query to update my existing id and make my id start from 1 and next id 2 and so on

What you can do is transfer the content of your table to another table. Reset the auto increment counter, insert your data back into the original table but let MySQL assign the primary key.

Assuming your table name is mytable You do it like this:

```<code>CREATE TABLE mytable_tmp select * from mytable;
TRUNCATE TABLE mytable;
ALTER TABLE mytable AUTO_INCREMENT = 1;
INSERT INTO mytable(name) SELECT name FROM mytable_tmp ORDER BY id;
DROP TABLE mytable_tmp;
</code>```

Title: How to update id set from 1?

Body:
I have an id i.e primary key and auto increment. Is there any query to update my existing id and make my id start from 1 and next id 2 and so on..

For example

id  name
3   ABC
5   XYZ
9   PQR

NOTE: id is already primary and auto increment and I don't want truncate my id.

if possible i want to get

id  name
1   ABC
2   XYZ
3   PQR

ALTER TABLE table AUTO_INCREMENT = 1; is not my solution.

Thanks

Body:
Is there any query to update my existing id and make my id start from 1 and next id 2 and so on

What you can do is transfer the content of your table to another table. Reset the auto increment counter, insert your data back into the original table but let MySQL assign the primary key.

Assuming your table name is mytable You do it like this:

CREATE TABLE mytable_tmp select * from mytable;
TRUNCATE TABLE mytable;
ALTER TABLE mytable AUTO_INCREMENT = 1;
INSERT INTO mytable(name) SELECT name FROM mytable_tmp ORDER BY id;
DROP TABLE mytable_tmp;


问:
Setting the value for 'android: layout_below' property to a resource id from a different layout xml file
I have a blueprint which looks as thus:

I have the tablayout widget specified in xml like this:

```<code><android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    style="@style/AppTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="@color/tabBg"
    android:minHeight="?attr/actionBarSize"
    app:tabTextColor="@color/grey"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>
</code>```

I set it up with a ViewPager scrolling to swipe views for each tab. Now in one of the views - Tab 3, I need to arrange my components below the @id/tabLayout

This is the content of tab3.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/secondtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tabLayout"
        android:background="@android:color/white"
        android:text="second"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/thirdtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/secondtext"
        android:background="@android:color/white"
        android:text="third"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>
</code>```

Both the second and third textviews are displayed behind the tabLayout, they are covered/hidden by the tabLayout. How do i specify the textviews to display right under the tabLayout so the text is visible?

答: Define an id to RelativeLayout in tab3.xml and use it.</p>

Body:
I have a blueprint which looks as thus:

I have the tablayout widget specified in xml like this:

<android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    style="@style/AppTabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:background="@color/tabBg"
    android:minHeight="?attr/actionBarSize"
    app:tabTextColor="@color/grey"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>

I set it up with a ViewPager scrolling to swipe views for each tab. Now in one of the views - Tab 3, I need to arrange my components below the @id/tabLayout

This is the content of tab3.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/secondtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tabLayout"
        android:background="@android:color/white"
        android:text="second"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <TextView
        android:id="@+id/thirdtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/secondtext"
        android:background="@android:color/white"
        android:text="third"
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Both the second and third textviews are displayed behind the tabLayout, they are covered/hidden by the tabLayout. How do i specify the textviews to display right under the tabLayout so the text is visible?


问:
Is it possible to map values in a matrix to colours in MATLAB
I have been trying to get an image from a matrix. Initially I had converted the matrix to a grey-scale image with 5 levels. I want to know if the same thing can be done to make the grey-scale image a colors one, i.e. say I have a value 2.2 and I need it to be in dark blue color, is there any inbuilt function to map values this way and also is it possible to map all the 5 levels to different colours?

Consider the following to be my matrix

```<code>   x = [ 2.2 2.2 2.2 2.6
         2.2 2.3 2.4 2.5
         2.3 2.7 2.5 2.2
         2.6 2.2 2.2 2.2]
</code>```

And I need to map the levels as follows,such that when I convert this into an image , I should be getting the colors in my output image.

```<code>                 2.2--> Dark blue
                 2.3--> Blue
                 2.4--> Green
                 2.5--> Yellow
                 2.6--> Orange
                 2.7--> Red
</code>```

How do I do it? Please help..Thanks!!

答:
You can do it this way:

Reduce your matrix to a set of unique integers, so that each integer represents one of the original values

Show the integer-valued matrix with imagesc.

Use a custom colormap with the desired colors.

This ensures that way each original value, irrespective of their separation, will correspond to a different color.

```<code>x = [ 2.2 2.2 2.2 2.6
      2.2 2.3 2.4 2.5
      2.3 2.7 2.5 2.2
      2.6 2.2 2.2 2.2];                                        % example matrix
colors = [0 0 .6; 0 .6 1; 0 .8 0; 1 .9 0; 1 .5 0; .8 0 0];     % desired colors
[~, ~, xu] = unique(x);                                        % step 1
xu = reshape(xu, size(x));
imagesc(xu)                                                    % step 2
colormap(colors)                                               % step 3
</code>```

Body:
I have been trying to get an image from a matrix. Initially I had converted the matrix to a grey-scale image with 5 levels. I want to know if the same thing can be done to make the grey-scale image a colors one, i.e. say I have a value 2.2 and I need it to be in dark blue color, is there any inbuilt function to map values this way and also is it possible to map all the 5 levels to different colours?

Consider the following to be my matrix

   x = [ 2.2 2.2 2.2 2.6
         2.2 2.3 2.4 2.5
         2.3 2.7 2.5 2.2
         2.6 2.2 2.2 2.2]

And I need to map the levels as follows,such that when I convert this into an image , I should be getting the colors in my output image.

                 2.2--> Dark blue
                 2.3--> Blue
                 2.4--> Green
                 2.5--> Yellow
                 2.6--> Orange
                 2.7--> Red

How do I do it? Please help..Thanks!!

Body:
You can do it this way:

Reduce your matrix to a set of unique integers, so that each integer represents one of the original values

Show the integer-valued matrix with imagesc.

Use a custom colormap with the desired colors.

This ensures that way each original value, irrespective of their separation, will correspond to a different color.

x = [ 2.2 2.2 2.2 2.6
      2.2 2.3 2.4 2.5
      2.3 2.7 2.5 2.2
      2.6 2.2 2.2 2.2];                                        % example matrix
colors = [0 0 .6; 0 .6 1; 0 .8 0; 1 .9 0; 1 .5 0; .8 0 0];     % desired colors
[~, ~, xu] = unique(x);                                        % step 1
xu = reshape(xu, size(x));
imagesc(xu)                                                    % step 2
colormap(colors)                                               % step 3


问:
GoogleApp Directory API's to set the Proxy credentials
I am using GoogleApps Directory api to access the Googleapps. I have one query regarding Proxy , how to set the proxy credentials using directory API's.

As per googleApps API's documentation i can use class "GoogleNetHttpTransport" to set the Proxy (port and host).

static HttpTransport newProxyTransport() throws GeneralSecurityException, IOException {
    NetHttpTransport.Builder builder = new NetHttpTransport.Builder();
    builder.trustCertificates(GoogleUtils.getCertificateTrustStore());
    builder.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 3128)));
    return builder.build();
  }

But if i have credentials for proxy server then how can i set, there is no mention about setting up proxy credentials.

Is there any GoogleApps api which allow to set proxy credentials along with hostname and port?

If no , then should i go for setDefault(Authenticator) which will set the proxy credentials to system property ?

Can anyone have idea about this. Any input on this is highly appreciable!

答:
You may refer with this documentation. For HTTP proxy with the Java client library, if your corporate proxy server were running on my.proxy.domain.com, on port 3128, you could add the following to your code before creating a service object for Google Calendar, Google Spreadsheets, etc.

```<code>System.setProperty("http.proxyHost", "my.proxy.domain.com");
System.setProperty("http.proxyPort", "3128");
</code>```

Alternatively, this can be done on the command line when starting your servlet environment:

```<code>java -Dhttp.proxyHost=my.proxy.domain.com -Dhttp.proxyPort=3128
</code>```

You may also refer with this related thread: Google Directory API using Service Account via Proxy

Body:
You may refer with this documentation. For HTTP proxy with the Java client library, if your corporate proxy server were running on my.proxy.domain.com, on port 3128, you could add the following to your code before creating a service object for Google Calendar, Google Spreadsheets, etc.

System.setProperty("http.proxyHost", "my.proxy.domain.com");
System.setProperty("http.proxyPort", "3128");

Alternatively, this can be done on the command line when starting your servlet environment:

java -Dhttp.proxyHost=my.proxy.domain.com -Dhttp.proxyPort=3128

You may also refer with this related thread: Google Directory API using Service Account via Proxy


问:
Hide columns if cell has a given value
I would like to hide some columns if A1 changes but I am afraid that the function Worksheet_Change does not work.

I have the following code but if I change A1 nothing happens.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "A1" Then

        Call hideColumns()
        '
        '
    End If
End Sub
</code>```

答:
To hide Columns Columns("B").EntireColumn.Hidden = False / True Or
To hide Rows Rows("2:2").EntireRow.Hidden = False / True

Example

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = 0

    If Not Intersect(Target, ([A1])) Is Nothing Then
        If Target.Value = "" Then
            Columns("D").EntireColumn.Hidden = False
        Else
            Columns("D").EntireColumn.Hidden = True
        End If
    End If

    Application.EnableEvents = 1
End Sub
</code>```

Range.Hidden Property (Excel) Returns or sets a Variant value that indicates if the rows or columns are hidden, Set property to True to hide a row or column. The specified range must span an entire column or row.

Application.EnableEvents Property (Excel) EnableEvents Application Property in Excel VBA is used to enable events for the specified object. It has Boolean value that is either True or False.

Title: Hide columns if cell has a given value

Body:
I would like to hide some columns if A1 changes but I am afraid that the function Worksheet_Change does not work.

I have the following code but if I change A1 nothing happens.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = "A1" Then

        Call hideColumns()
        '
        '
    End If
End Sub

Body:
To hide Columns Columns("B").EntireColumn.Hidden = False / True Or
To hide Rows Rows("2:2").EntireRow.Hidden = False / True

Example

Private Sub Worksheet_Change(ByVal Target As Range)
    Application.EnableEvents = 0

    If Not Intersect(Target, ([A1])) Is Nothing Then
        If Target.Value = "" Then
            Columns("D").EntireColumn.Hidden = False
        Else
            Columns("D").EntireColumn.Hidden = True
        End If
    End If

    Application.EnableEvents = 1
End Sub

Range.Hidden Property (Excel) Returns or sets a Variant value that indicates if the rows or columns are hidden, Set property to True to hide a row or column. The specified range must span an entire column or row.

Application.EnableEvents Property (Excel) EnableEvents Application Property in Excel VBA is used to enable events for the specified object. It has Boolean value that is either True or False.


问:
How to call a AWS Lambda outside of AWS
This is a quite basic question, but I was unable to find it out: How can I call a lambda via https without using an EC2 instance or something similar which has to run 24/7. So that I can call my method from an App, via CURL or what every tool which supports http.

I found some references to some Gateway APIs, but I don't know how to call them. Also do I need to setup some access permissions? Can I setup also access control or do I need to implement that within the lambda?

答:
You can do it either with API or by CLI
The API way will be time-consuming, but usually more robust and maintainable.</p>

Title: How to call a AWS Lambda outside of AWS


问:
Smack 4.2 and CCS (XMPP to FCM/GCM) - response incorrectly parsed by Smack - drops JSON payload
Version 4.2 of the Smack library seems to drop the message body, as sent by FCM.
When I set the debugger on, I can see the following incoming message:

```<code><message><data:gcm xmlns:data="google:mobile:data">{"message_type":"nack","from":"xxx","message_id":"aaaa1","error":"BAD_REGISTRATION","error_description":""}</data:gcm></message>
</code>```

However, when Smack 4.2 parses this message, it drops the JSON body inside the message and gives me the following in my packet listener:

```<code><message><gcm xmlns="google:mobile:data"></gcm></message>
</code>```

Here's my test class:

```<code>import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.DefaultPacketExtension;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

import javax.net.ssl.SSLSocketFactory;

public class CcsClient {

    private static final String HOST = "fcm-xmpp.googleapis.com";
    private static final int PORT = 5235;
    private final XMPPConnection conn;

    public CcsClient(String senderId, String serverKey) {
        SASLAuthentication.supportSASLMechanism("PLAIN", 0);

        ConnectionConfiguration conf = new ConnectionConfiguration(HOST, PORT);
        conf.setSASLAuthenticationEnabled(true);
        conf.setSocketFactory(SSLSocketFactory.getDefault());
        conf.setServiceName(HOST);
        conf.setSendPresence(false);
        conf.setCompressionEnabled(false);
        conf.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
        conf.setDebuggerEnabled(true);

        this.conn = new XMPPConnection(conf);

        conn.addConnectionListener(new AbstractConnectionListener() {
            @Override
            public void connectionClosed() {
                super.connectionClosed();
            }

            @Override
            public void connectionClosedOnError(Exception e) {
                super.connectionClosedOnError(e);
            }

            @Override
            public void reconnectingIn(int seconds) {
                super.reconnectingIn(seconds);
            }

            @Override
            public void reconnectionFailed(Exception e) {
                super.reconnectionFailed(e);
            }

            @Override
            public void reconnectionSuccessful() {
                super.reconnectionSuccessful();
            }
        });

        try {
            conn.connect();
            conn.login(senderId + "@gcm.googleapis.com", serverKey);
            System.out.println("connected!");
        } catch (XMPPException e) {
            e.printStackTrace();
        }
    }

    private static final class GcmPacketExtension extends DefaultPacketExtension {

        private final String json;

        public GcmPacketExtension(String json) {
            super("gcm", "google:mobile:data");
            this.json = json;
        }

        public String getJson() {
            return json;
        }

        @Override
        public String toXML() {
            return "<gcm xmlns=\"google:mobile:data\">" + StringUtils.escapeForXML(json) + "</gcm>";
        }

        public Message toPacket() {
            Message message = new Message();
            message.addExtension(this);
            return message;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final CcsClient c = new CcsClient("xxx", "xxx");
        c.conn.addPacketListener(new PacketListener() {

            @Override
            public void processPacket(Packet packet) {
                System.out.println("incoming!" + packet.toString());
            }
        }, new PacketFilter() {
            @Override
            public boolean accept(Packet packet) {
                return true;
            }
        });

        for (int i = 0; i < 1; i++) {
            c.conn.sendPacket(new GcmPacketExtension("{\"to\":\"xxx\", \"message_id\":\"aaaa"+i+"\", \"delivery_receipt_requested\":true}").toPacket());
        }
        Thread.sleep(1000000);
    }
}
</code>```

What am I doing wrong?

答: So I finally got it working. An example client is here: https://gist.github.com/judepereira/fd8dc0a5321179b699f5c5e54812770c</p>

Body:
Version 4.2 of the Smack library seems to drop the message body, as sent by FCM.
When I set the debugger on, I can see the following incoming message:

<message><data:gcm xmlns:data="google:mobile:data">{"message_type":"nack","from":"xxx","message_id":"aaaa1","error":"BAD_REGISTRATION","error_description":""}</data:gcm></message>

However, when Smack 4.2 parses this message, it drops the JSON body inside the message and gives me the following in my packet listener:

<message><gcm xmlns="google:mobile:data"></gcm></message>

Here's my test class:

import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.DefaultPacketExtension;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;

import javax.net.ssl.SSLSocketFactory;

public class CcsClient {

    private static final String HOST = "fcm-xmpp.googleapis.com";
    private static final int PORT = 5235;
    private final XMPPConnection conn;

    public CcsClient(String senderId, String serverKey) {
        SASLAuthentication.supportSASLMechanism("PLAIN", 0);

        ConnectionConfiguration conf = new ConnectionConfiguration(HOST, PORT);
        conf.setSASLAuthenticationEnabled(true);
        conf.setSocketFactory(SSLSocketFactory.getDefault());
        conf.setServiceName(HOST);
        conf.setSendPresence(false);
        conf.setCompressionEnabled(false);
        conf.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);
        conf.setDebuggerEnabled(true);

        this.conn = new XMPPConnection(conf);

        conn.addConnectionListener(new AbstractConnectionListener() {
            @Override
            public void connectionClosed() {
                super.connectionClosed();
            }

            @Override
            public void connectionClosedOnError(Exception e) {
                super.connectionClosedOnError(e);
            }

            @Override
            public void reconnectingIn(int seconds) {
                super.reconnectingIn(seconds);
            }

            @Override
            public void reconnectionFailed(Exception e) {
                super.reconnectionFailed(e);
            }

            @Override
            public void reconnectionSuccessful() {
                super.reconnectionSuccessful();
            }
        });

        try {
            conn.connect();
            conn.login(senderId + "@gcm.googleapis.com", serverKey);
            System.out.println("connected!");
        } catch (XMPPException e) {
            e.printStackTrace();
        }
    }

    private static final class GcmPacketExtension extends DefaultPacketExtension {

        private final String json;

        public GcmPacketExtension(String json) {
            super("gcm", "google:mobile:data");
            this.json = json;
        }

        public String getJson() {
            return json;
        }

        @Override
        public String toXML() {
            return "<gcm xmlns=\"google:mobile:data\">" + StringUtils.escapeForXML(json) + "</gcm>";
        }

        public Message toPacket() {
            Message message = new Message();
            message.addExtension(this);
            return message;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final CcsClient c = new CcsClient("xxx", "xxx");
        c.conn.addPacketListener(new PacketListener() {

            @Override
            public void processPacket(Packet packet) {
                System.out.println("incoming!" + packet.toString());
            }
        }, new PacketFilter() {
            @Override
            public boolean accept(Packet packet) {
                return true;
            }
        });

        for (int i = 0; i < 1; i++) {
            c.conn.sendPacket(new GcmPacketExtension("{\"to\":\"xxx\", \"message_id\":\"aaaa"+i+"\", \"delivery_receipt_requested\":true}").toPacket());
        }
        Thread.sleep(1000000);
    }
}

What am I doing wrong?


问:
Log all method calls in Fitnesse
For debugging purpose, I want to log all method calls made to the fixture code.

I've an example where I can log method calls by instrumenting the code using Javassist. But that requires me to pass "-javaagent=<> " as command line parameters, which I can not do while running the Fitnesse test from browser.
I can add new package and classes but can not modify the existing fixtures.
Any pointers will be appreciated.
Fixture code is in Java, Fitnesse server is started from command prompt and tests are started from browser.

答:
When using slim you can use the 'LoggingInteraction' to have all methods invoked logged.

To enable this you can add the following line to the root/suite wiki page:
!define slim.flags {-i fitnesse.slim.fixtureInteraction.LoggingInteraction}, see the minimal documentation http://fitnesse.org/FitNesse.FullReferenceGuide.UserGuide.WritingAcceptanceTests.SliM.InteractionAwareFixture

Title: Log all method calls in Fitnesse


问:
Butterknife: temporarily disable listener
I set @OnClick listener to a view in a list item. In some cases I need to disable the listener for this view so that the list view can handle the click (OnItemClickListener should be called), and then enable it again. Is there a way to do this with Butterknife?

答: You can add a boolean flag like shouldListenClick in the app and set to true and false where ever you wish. Then, you can check the shouldListenClick in the @OnClick or any other ButterKnife listener call before executing its code.


问:
How statically linked binaries could be smaller than dynamically linked binaries?
If you read the description about stali, it mentions about statically linked binaries size:

It also targets binary size reduction through the avoidance of glibc
  and other bloated GNU libraries where possible (early experiments show
  that statically linked binaries are usually smaller than their
  dynamically linked glibc counterparts!!!).

I don't understand how including libraries in the binary itself will make the binary smaller than a binary with libraries included(Maybe there's something I'm missing regarding statically vs dynamically linked).

How's this possible? Does this only happen on some specific situations?

答:
If you use static linking, the linker can throw out symbols that are not used.

For instance, your library has both foo and bar, but the executable only uses bar, then foo will not be part of the executable.

In case of dynamic linking that is not possible, because the linker/compiler cannot know what will be used when building the library.

Aside from that, dynamic linking is a lovely source for errors (like segfaulting because the newer library is incompatible) that can be avoided by linking statically.

Further reading: http://harmful.cat-v.org/software/dynamic-linking/


问:
Can not construct instance of java.util.Date from String value - not a valid representation
Sorry for what it seems to be a redundant question but i do have many options,
and despite my effort reading dozen of threads, i'm not able to understand what to do.

I do have a java application which job is to :

get datas from a SOAP WS (XML),

do some logic ( incoming deliverydate will become datebl )

Finally send it to a REST WS (JSON Format), which will update an Oracle Table

Plan is thus as follows :

    SOAP WS ---- deliverydate ----> JAVA APP (logic)  ---- datebl ----> REST WS

Jar used in JAVA APP are jackson-core-asl-1.9.13.jar and jackson-mapper-asl-1.9.13.jar among others.

Issues i have is when dealing with dates.

Readings :
( Tried to be inspired but jackson version seems not to be the same ) :

JSON Serializing date in a custom format (Can not construct instance of java.util.Date from String value)

Jackson 2.3.2: Issue with deserializing a Date despite of setting the date format to ObjectMapper

Edit 01/04/15

http://jackson-users.ning.com/forum/topics/cannot-deserialize-a-date

The facts now

Point 1 :
When recovering data from SOAP WS, deliverydate is a String which exact value is  :

2014-07-31 07:00:00.0

Point 2:
Just before using the setter, i thought it could be a good idea to format this String to a date.

```<code>SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    Date dateebl = dateFormat.parse(deliverydate);
                                    msi.setDatebl(dateebl);
</code>```

datebl declaration in POJO

```<code>private java.util.Date    datebl;
</code>```

At this stage, datebl value has transformed to

Thu Jul 31 07:00:00 CEST 2014

(despite choosing the specific format yyyy-MM-dd HH:mm:ss)

Point 3 and ERROR i have :
The error i have is thrown by the rest server:

Can not construct instance of java.util.Date from String value 'Thu
  Jul 31 07:00:00 CEST 2014': not a valid representation (error: Can not
  parse date "Thu Jul 31 07:00:00 CEST 2014": not compatible with any of
  standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ",
  "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz",
  "yyyy-MM-dd"))  at [Source:
  org.glassfish.jersey.message.internal.EntityInputStream@5709779; line:
  1, column: 74] (through reference chain:
  com.rest.entities.MvtSwapsIn["datebl"])

What i tried to do :
 To resolve this, as i'm using a version prior to 2.x,  i thought that my best option was to use a custom serializer, so :

In pojo, annotation was added just before the getter

```<code>@JsonSerialize(using = CustomJsonDateSerializer.class)
    public java.util.Date getDatebl() {
        return datebl;
    }
</code>```

Serializer was created as follows

```<code>public class CustomJsonDateSerializer extends JsonSerializer<Date> {

@Override
public void serialize(Date value, JsonGenerator jgen,
        SerializerProvider provider) throws IOException,
        JsonProcessingException {
    SimpleDateFormat dateFormat = new SimpleDateFormat(Properties.General.FORMAT_HEURE_JSON_SERIALIZE_2);
    String dateString = dateFormat.format(value);
    jgen.writeString(dateString);
}
</code>```

}

In example,tried with FORMAT_HEURE_JSON_SERIALIZE_2, but tried many others without success.

```<code>public static final String  FORMAT_HEURE_JSON               = new String("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
public static final String  FORMAT_HEURE_JSON_SERIALIZE     = new String("EEE yyyy-MM-dd'T'HH:mm:ss.SSSZ");
public static final String  FORMAT_HEURE_JSON_SERIALIZE_2   = new String("EEE, dd MMM yyyy HH:mm:ss zzz");
public static final String  FORMAT_HEURE_JSON_SERIALIZE_3   = new String("yyyy-MM-dd HH:mm:ss");
</code>```

At this point, i'm lost.

I don't know where and how to update my code.

Should i still use SimpleDateFormat after getting date from SOAP ws ?

Given the fact i'm using jackson 1.9, is my @JsonSerialize annotation good ? ( as well as the serializer ?)

Do i have to modify something on the rest server ?

Please can someone help me organize my thoughts ?

Kind regards,

Pierre

答:
Open your POJO, annotate the date field declaration like so

```<code>@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "<your_date_pattern>")
</code>```

Where your_date_pattern can be something like

```<code>yyyy-MM-dd HH:mm:ss
</code>```

Done

Body:
Sorry for what it seems to be a redundant question but i do have many options,
and despite my effort reading dozen of threads, i'm not able to understand what to do.

I do have a java application which job is to :

get datas from a SOAP WS (XML),

do some logic ( incoming deliverydate will become datebl )

Finally send it to a REST WS (JSON Format), which will update an Oracle Table

Plan is thus as follows :

    SOAP WS ---- deliverydate ----> JAVA APP (logic)  ---- datebl ----> REST WS

Jar used in JAVA APP are jackson-core-asl-1.9.13.jar and jackson-mapper-asl-1.9.13.jar among others.

Issues i have is when dealing with dates.

Readings :
( Tried to be inspired but jackson version seems not to be the same ) :

JSON Serializing date in a custom format (Can not construct instance of java.util.Date from String value)

Jackson 2.3.2: Issue with deserializing a Date despite of setting the date format to ObjectMapper

Edit 01/04/15

http://jackson-users.ning.com/forum/topics/cannot-deserialize-a-date

The facts now

Point 1 :
When recovering data from SOAP WS, deliverydate is a String which exact value is  :

2014-07-31 07:00:00.0

Point 2:
Just before using the setter, i thought it could be a good idea to format this String to a date.

SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    Date dateebl = dateFormat.parse(deliverydate);
                                    msi.setDatebl(dateebl);

datebl declaration in POJO

private java.util.Date    datebl;

At this stage, datebl value has transformed to

Thu Jul 31 07:00:00 CEST 2014

(despite choosing the specific format yyyy-MM-dd HH:mm:ss)

Point 3 and ERROR i have :
The error i have is thrown by the rest server:

Can not construct instance of java.util.Date from String value 'Thu
  Jul 31 07:00:00 CEST 2014': not a valid representation (error: Can not
  parse date "Thu Jul 31 07:00:00 CEST 2014": not compatible with any of
  standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ",
  "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "EEE, dd MMM yyyy HH:mm:ss zzz",
  "yyyy-MM-dd"))  at [Source:
  org.glassfish.jersey.message.internal.EntityInputStream@5709779; line:
  1, column: 74] (through reference chain:
  com.rest.entities.MvtSwapsIn["datebl"])

What i tried to do :
 To resolve this, as i'm using a version prior to 2.x,  i thought that my best option was to use a custom serializer, so :

In pojo, annotation was added just before the getter

@JsonSerialize(using = CustomJsonDateSerializer.class)
    public java.util.Date getDatebl() {
        return datebl;
    }

Serializer was created as follows

public class CustomJsonDateSerializer extends JsonSerializer<Date> {

@Override
public void serialize(Date value, JsonGenerator jgen,
        SerializerProvider provider) throws IOException,
        JsonProcessingException {
    SimpleDateFormat dateFormat = new SimpleDateFormat(Properties.General.FORMAT_HEURE_JSON_SERIALIZE_2);
    String dateString = dateFormat.format(value);
    jgen.writeString(dateString);
}

}

In example,tried with FORMAT_HEURE_JSON_SERIALIZE_2, but tried many others without success.

public static final String  FORMAT_HEURE_JSON               = new String("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
public static final String  FORMAT_HEURE_JSON_SERIALIZE     = new String("EEE yyyy-MM-dd'T'HH:mm:ss.SSSZ");
public static final String  FORMAT_HEURE_JSON_SERIALIZE_2   = new String("EEE, dd MMM yyyy HH:mm:ss zzz");
public static final String  FORMAT_HEURE_JSON_SERIALIZE_3   = new String("yyyy-MM-dd HH:mm:ss");

At this point, i'm lost.

I don't know where and how to update my code.

Should i still use SimpleDateFormat after getting date from SOAP ws ?

Given the fact i'm using jackson 1.9, is my @JsonSerialize annotation good ? ( as well as the serializer ?)

Do i have to modify something on the rest server ?

Please can someone help me organize my thoughts ?

Kind regards,

Pierre

Body:
Open your POJO, annotate the date field declaration like so

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "<your_date_pattern>")

Where your_date_pattern can be something like

yyyy-MM-dd HH:mm:ss

Done

ContentLicense: CC BY-SA 4.0


问:
How to start video recording in Android TV (development)
I would like to implement video recording in Android TV, or at least a button that fires the recording event, I added the gradle dependency, but I could not find any RecordAction or RecordButton, only MultiAction, FastForwardAction etc.

What I would need is a button where the user clicks/presses and the current time of the current streamed media would be saved.

答:
You may follow this documentation. To tell the system that your TV input service supports recording, set the android:canRecord attribute in your service metadata XML file to true:

```<code><tv-input xmlns:android="http://schemas.android.com/apk/res/android"
  android:canRecord="true"
  android:setupActivity="com.example.sampletvinput.SampleTvInputSetupActivity" />
</code>```

Alternatively, you can indicate recording support in your code using these steps:

In your TV input service onCreate() method, create a new TvInputInfo object using the TvInputInfo.Builder class.

When creating the new TvInputInfo object, call setCanRecord(true) before calling build() to indicate your service supports recording.

Register your TvInputInfo object with the system by calling TvInputManager.updateTvInputInfo().

Regarding button where the user clicks/presses, unfortunately I can't find any samples about it. According to the same reference above, the system will invoke the RecordingSession.onStartRecording() callback when the system calls RecordingSession.onTune(). Then your app must start recording immediately.

Body:
You may follow this documentation. To tell the system that your TV input service supports recording, set the android:canRecord attribute in your service metadata XML file to true:

<tv-input xmlns:android="http://schemas.android.com/apk/res/android"
  android:canRecord="true"
  android:setupActivity="com.example.sampletvinput.SampleTvInputSetupActivity" />

Alternatively, you can indicate recording support in your code using these steps:

In your TV input service onCreate() method, create a new TvInputInfo object using the TvInputInfo.Builder class.

When creating the new TvInputInfo object, call setCanRecord(true) before calling build() to indicate your service supports recording.

Register your TvInputInfo object with the system by calling TvInputManager.updateTvInputInfo().

Regarding button where the user clicks/presses, unfortunately I can't find any samples about it. According to the same reference above, the system will invoke the RecordingSession.onStartRecording() callback when the system calls RecordingSession.onTune(). Then your app must start recording immediately.


问:
Image as hyperlink in a GridView
The ASP.NET GridView control's default column types just don't seem to be up to using an image as a hyperlink.  The HyperLinkField has no image attributes, and the ImageField has no navigation attributes.  Is this possible without using a TemplateField?</p>

答: You can try to use HyperLinkField.DataTextFormatString property with inserting the  tag into this format string</p>

Title: Image as hyperlink in a GridView


问:
Angular2 check if object has peoperty inside *ngIf
```<code>export interface Element {
    name: string;
}

export class Room implements Element {
name: string;
type:string
}

export class Hall implements Element {
name: string;
}
</code>```

and my varibale type is like below

```<code>selectedElement: Element;
</code>```

now in html how can I check if the object is having property 'type' or not?

```<code><div *ngIf="selectedElement?.type">
my div
</div>
</code>```

答:
in addition to what Günter Zöchbauer said:  </p>

```<code>*ngIf="selectedElement && selectedElement['type']"
</code>```

Body:
export interface Element {
    name: string;
}

export class Room implements Element {
name: string;
type:string
}

export class Hall implements Element {
name: string;
}

and my varibale type is like below

selectedElement: Element;

now in html how can I check if the object is having property 'type' or not?

my div

Body:
in addition to what Günter Zöchbauer said:

*ngIf="selectedElement && selectedElement['type']"


问:
How to use global variable in Objective c without struct or enum
var token : String { get and set}
Can any tell how to use the same thing in Objective C. In swift I can use any where in the project to access the token. I want the same thing to be done.. </p>

答:
First, you should avoid to use global var with OOP.

If you really need to use global var, make it become an instance var in appdelegate.

If you don't want to put it in appdelegate, create a source file and declare as static var could solve it, remember access it by accessor, Never access global var directly.

GlobalVar.h

```<code>void setGlobalVar(int var);
int getGlobalVar(void);
</code>```

GlobalVar.m

```<code>static int s_globalVar = 0;
void setGlobalVar(int var) {
    s_globalVar = var;
}

int getGlobalVar(void) {
    return s_globalVar;
}
</code>```

Body:
First, you should avoid to use global var with OOP.

If you really need to use global var, make it become an instance var in appdelegate.

If you don't want to put it in appdelegate, create a source file and declare as static var could solve it, remember access it by accessor, Never access global var directly.

GlobalVar.h

void setGlobalVar(int var);
int getGlobalVar(void);

GlobalVar.m

static int s_globalVar = 0;
void setGlobalVar(int var) {
    s_globalVar = var;
}

int getGlobalVar(void) {
    return s_globalVar;
}


问:
Disable Mapview scrolling while Zooming android
is there any option Google Map android Similar to iOS GoogleMap.settings.allowScrollGesturesDuringRotateOrZoom?

basically what i want to achieve is to keep my Relative Layout of Marker in Center of Map.

答:
You may refer with this thread. Although because of ScaleGestureDetector bug it will work only API > 16. Use regular Mapview with scale gestures enabled on API <= 16 and API > 16. Reference.

```<code>    public class CustomEventMapView extends MapView {

    private int fingers = 0;
    private GoogleMap googleMap;
    private long lastZoomTime = 0;
    private float lastSpan = -1;
    private Handler handler = new Handler();

    private ScaleGestureDetector gestureDetector;

    public CustomEventMapView(Context context, GoogleMapOptions options) {
        super(context, options);
    }

    public CustomEventMapView(Context context) {
        super(context);
    }

    @Override
    public void getMapAsync(final OnMapReadyCallback callback) {
        super.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(final GoogleMap googleMap) {
                gestureDetector = new ScaleGestureDetector(getContext(), new ScaleGestureDetector.OnScaleGestureListener() {
                    @Override
                    public boolean onScale(ScaleGestureDetector detector) {
                        if (lastSpan == -1) {
                            lastSpan = detector.getCurrentSpan();
                        } else if (detector.getEventTime() - lastZoomTime >= 50) {
                            lastZoomTime = detector.getEventTime();
                            googleMap.animateCamera(CameraUpdateFactory.zoomBy(getZoomValue(detector.getCurrentSpan(), lastSpan)), 50, null);
                            lastSpan = detector.getCurrentSpan();
                        }
                        return false;
                    }

                    @Override
                    public boolean onScaleBegin(ScaleGestureDetector detector) {
                        lastSpan = -1;
                        return true;
                    }

                    @Override
                    public void onScaleEnd(ScaleGestureDetector detector) {
                        lastSpan = -1;

                    }
                });
                CustomEventMapView.this.googleMap = googleMap;
                callback.onMapReady(googleMap);
            }
        });
    }

    private float getZoomValue(float currentSpan, float lastSpan) {
        double value = (Math.log(currentSpan / lastSpan) / Math.log(1.55d));
        return (float) value;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        switch (ev.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_POINTER_DOWN:
                fingers = fingers + 1;
                break;
            case MotionEvent.ACTION_POINTER_UP:
                fingers = fingers - 1;
                break;
            case MotionEvent.ACTION_UP:
                fingers = 0;
                break;
            case MotionEvent.ACTION_DOWN:
                fingers = 1;
                break;
        }
        if (fingers > 1) {
            disableScrolling();
        } else if (fingers < 1) {
            enableScrolling();
        }
        if (fingers > 1) {
            return gestureDetector.onTouchEvent(ev);
        } else {
            return super.dispatchTouchEvent(ev);
        }
    }

    private void enableScrolling() {
        if (googleMap != null && !googleMap.getUiSettings().isScrollGesturesEnabled()) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    googleMap.getUiSettings().setAllGesturesEnabled(true);
                }
            }, 50);
        }
    }

    private void disableScrolling() {
        handler.removeCallbacksAndMessages(null);
        if (googleMap != null && googleMap.getUiSettings().isScrollGesturesEnabled()) {
            googleMap.getUiSettings().setAllGesturesEnabled(false);
        }
    }
}
</code>```

Also, here's a related thread which might help: MapView - Disable dragging around, but allow zooming

Body:
You may refer with this thread. Although because of ScaleGestureDetector bug it will work only API > 16. Use regular Mapview with scale gestures enabled on API <= 16 and API > 16. Reference.

    public class CustomEventMapView extends MapView {

    private int fingers = 0;
    private GoogleMap googleMap;
    private long lastZoomTime = 0;
    private float lastSpan = -1;
    private Handler handler = new Handler();

    private ScaleGestureDetector gestureDetector;

    public CustomEventMapView(Context context, GoogleMapOptions options) {
        super(context, options);
    }

    public CustomEventMapView(Context context) {
        super(context);
    }

    @Override
    public void getMapAsync(final OnMapReadyCallback callback) {
        super.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(final GoogleMap googleMap) {
                gestureDetector = new ScaleGestureDetector(getContext(), new ScaleGestureDetector.OnScaleGestureListener() {
                    @Override
                    public boolean onScale(ScaleGestureDetector detector) {
                        if (lastSpan == -1) {
                            lastSpan = detector.getCurrentSpan();
                        } else if (detector.getEventTime() - lastZoomTime >= 50) {
                            lastZoomTime = detector.getEventTime();
                            googleMap.animateCamera(CameraUpdateFactory.zoomBy(getZoomValue(detector.getCurrentSpan(), lastSpan)), 50, null);
                            lastSpan = detector.getCurrentSpan();
                        }
                        return false;
                    }

                    @Override
                    public boolean onScaleBegin(ScaleGestureDetector detector) {
                        lastSpan = -1;
                        return true;
                    }

                    @Override
                    public void onScaleEnd(ScaleGestureDetector detector) {
                        lastSpan = -1;

                    }
                });
                CustomEventMapView.this.googleMap = googleMap;
                callback.onMapReady(googleMap);
            }
        });
    }

    private float getZoomValue(float currentSpan, float lastSpan) {
        double value = (Math.log(currentSpan / lastSpan) / Math.log(1.55d));
        return (float) value;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {

        switch (ev.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_POINTER_DOWN:
                fingers = fingers + 1;
                break;
            case MotionEvent.ACTION_POINTER_UP:
                fingers = fingers - 1;
                break;
            case MotionEvent.ACTION_UP:
                fingers = 0;
                break;
            case MotionEvent.ACTION_DOWN:
                fingers = 1;
                break;
        }
        if (fingers > 1) {
            disableScrolling();
        } else if (fingers < 1) {
            enableScrolling();
        }
        if (fingers > 1) {
            return gestureDetector.onTouchEvent(ev);
        } else {
            return super.dispatchTouchEvent(ev);
        }
    }

    private void enableScrolling() {
        if (googleMap != null && !googleMap.getUiSettings().isScrollGesturesEnabled()) {
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    googleMap.getUiSettings().setAllGesturesEnabled(true);
                }
            }, 50);
        }
    }

    private void disableScrolling() {
        handler.removeCallbacksAndMessages(null);
        if (googleMap != null && googleMap.getUiSettings().isScrollGesturesEnabled()) {
            googleMap.getUiSettings().setAllGesturesEnabled(false);
        }
    }
}

Also, here's a related thread which might help: MapView - Disable dragging around, but allow zooming


问:
symfony, can't I access to entity on another controller?
DefaultController.php

public function indexAction(Request $request) {
    if ($request->get ( 'email' )) {
        $email = $request->get ( 'email' );
        $em = $this->getDoctrine ();
        $mst_USERS = $em->getRepository ( 'AppBundle:mst_USERS' );
        $mst_USERS->findAll ();

        return $this->render ( 'default/main.html.twig', array (
                'email' => $email,
                'mst_USERS' => $mst_USERS
        ) );
    }
```

<p><code>main.html.twig</code>
</p>

```{% block styleSheet %}

{% endblock %}
{% block body %}

    THIS IS

    {{email}}

        {% for mst_USERS in mst_USERS %}

{{mst_USERS.email}}

        {% endfor %}

{% endblock %}

{% block styleSheet %}

{% endblock %}
```

I tried to use AppBundle:mst_USERS entity for DefaultController but It doesn't work at all.

It was working on another controller, named mst_USERSController.php
Can't I using it on another controller or is there something wrong?

答:
Try this at home

```<code>{% for user in mst_USERS %}
<li>{{user.email}}</li>
{% endfor %}
</code>```

And in the controller add

```<code>return $this->render ( 'default/main.html.twig', array (
    'email' => $email,
    'mst_USERS' => $mst_USERS->findAll()
));
</code>```

Body:
DefaultController.php

public function indexAction(Request $request) {
    if ($request->get ( 'email' )) {
        $email = $request->get ( 'email' );
        $em = $this->getDoctrine ();
        $mst_USERS = $em->getRepository ( 'AppBundle:mst_USERS' );
        $mst_USERS->findAll ();

        return $this->render ( 'default/main.html.twig', array (
                'email' => $email,
                'mst_USERS' => $mst_USERS
        ) );
    }

main.html.twig

{% block styleSheet %}

{% endblock %}
{% block body %}

    THIS IS

    {{email}}

        {% for mst_USERS in mst_USERS %}

{{mst_USERS.email}}

        {% endfor %}

{% endblock %}

{% block styleSheet %}

{% endblock %}

I tried to use AppBundle:mst_USERS entity for DefaultController but It doesn't work at all.

It was working on another controller, named mst_USERSController.php
Can't I using it on another controller or is there something wrong?

Body:
Try this at home

{% for user in mst_USERS %}
<li>{{user.email}}</li>
{% endfor %}

And in the controller add

return $this->render ( 'default/main.html.twig', array (
    'email' => $email,
    'mst_USERS' => $mst_USERS->findAll()
));


问:
how to show Delta Longitude and Latitude (vector change) in google map
how can i show Delta Longitude and Latitude (vector change) in google map,is there anyone worked with this before??
P.S:Delta Longitude and Latitude are different than longitude and latitude.</p>

答:
You may refer with this thread. Given an array of coordinates coords, this function returns the region (lat, lng and deltas) to contain those coordinates.

```<code>export function getRegionForCoordinates(points) {
  // points should be an array of { latitude: X, longitude: Y }
  let minX, maxX, minY, maxY;

  // init first point
  ((point) => {
    minX = point.latitude;
    maxX = point.latitude;
    minY = point.longitude;
    maxY = point.longitude;
  })(points[0]);

  // calculate rect
  points.map((point) => {
    minX = Math.min(minX, point.latitude);
    maxX = Math.max(maxX, point.latitude);
    minY = Math.min(minY, point.longitude);
    maxY = Math.max(maxY, point.longitude);
  });

  const midX = (minX + maxX) / 2;
  const midY = (minY + maxY) / 2;
  const deltaX = (maxX - minX);
  const deltaY = (maxY - minY);

  return {
    latitude: midX,
    longitude: midY,
    latitudeDelta: deltaX,
    longitudeDelta: deltaY
  };
}
</code>```

Here are some related threads:

Calculate latitudeDelta and longitudeDelta in titanium maps [Android]

How to calculate delta latitude and longitude for MapView component in React-Native?

Body:
You may refer with this thread. Given an array of coordinates coords, this function returns the region (lat, lng and deltas) to contain those coordinates.

export function getRegionForCoordinates(points) {
  // points should be an array of { latitude: X, longitude: Y }
  let minX, maxX, minY, maxY;

  // init first point
  ((point) => {
    minX = point.latitude;
    maxX = point.latitude;
    minY = point.longitude;
    maxY = point.longitude;
  })(points[0]);

  // calculate rect
  points.map((point) => {
    minX = Math.min(minX, point.latitude);
    maxX = Math.max(maxX, point.latitude);
    minY = Math.min(minY, point.longitude);
    maxY = Math.max(maxY, point.longitude);
  });

  const midX = (minX + maxX) / 2;
  const midY = (minY + maxY) / 2;
  const deltaX = (maxX - minX);
  const deltaY = (maxY - minY);

  return {
    latitude: midX,
    longitude: midY,
    latitudeDelta: deltaX,
    longitudeDelta: deltaY
  };
}

Here are some related threads:

Calculate latitudeDelta and longitudeDelta in titanium maps [Android]

How to calculate delta latitude and longitude for MapView component in React-Native?


问:
Python argparse requiring option, depending on the defined flags
I have a small python script, which uses argparse to let the user define options. It uses two flags for different modes and an argument to let the user define a file. See the simplified example below:

```<code>#!/usr/bin/python3

import argparse
from shutil import copyfile

def check_file(f):
    # Mock function: checks if file exists, else "argparse.ArgumentTypeError("file not found")"
    return f

def main():
    aFile = "/tmp/afile.txt"

    parser = argparse.ArgumentParser(description="An example",formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument("-f", "--file", help="A file, used with method A.", default=aFile, type=check_file)
    parser.add_argument("-a", "--ay", help="Method A, requires file.", action='store_true')
    parser.add_argument("-b", "--be", help="Method B, no file required.", action='store_true')

    args = parser.parse_args()
    f = args.file
    a = args.ay
    b = args.be

    if a:
        copyfile(f, f+".a")
    elif b:
        print("Method B")

if __name__ == "__main__":
    main()
</code>```

Method A requires the file.

Method B does not.

If I run the script with method A, I either use the default file or one that is defined with -f/--file. The script checks if the file exists and everything is fine.

Now, if I run the script with method B, it shouldn't require the file, but the default option is checked and if it doesn't exist the argparse function raises the exception and the script exits.

How can I configure argparse to make -f optional, if -b is defined and require it, if -a is defined?

edit: I just realized that it would be enough for me to make -f and -b mutually exclusive. But then, if I run -b only, the check_file is executed anyways. Is there a way to prevent that?

```<code>#!/usr/bin/python3

import argparse
from shutil import copyfile

def check_file(f):
    # Mock function: checks if file exists, else "argparse.ArgumentTypeError("file not found")"
    print("chk file")
    return f

def main():
    aFile = "/tmp/afile.txt"

    parser = argparse.ArgumentParser(description="An example",formatter_class=argparse.RawTextHelpFormatter)
    group = parser.add_mutually_exclusive_group(required=True)

    group.add_argument("-f", "--file", help="A file, used with method A.", default=aFile, type=check_file)
    parser.add_argument("-a", "--ay", help="Method A, requires file.", action='store_true')
    group.add_argument("-b", "--be", help="Method B, no file required.", action='store_true')

    args = parser.parse_args()
    f = args.file
    a = args.ay
    b = args.be

    if a:
        print("File: "+str(f))
    elif b:
        print("Method B")
        print("file: "+str(f))

if __name__ == "__main__":
    main()
</code>```

Output:

```<code>chk file
Method B
file: /tmp/afile.txt
</code>```

答:
You can defined subparser with ay/be as subcommand or alternatively declare a second parser instance for a. Something like:</p>

```<code>parser = argparse.ArgumentParser(
    description="An example",
    formatter_class=argparse.RawTextHelpFormatter
)
# ensure either option -a or -b only
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-a", "--ay", help="Method A, requires file.",
                   action='store_true')
group.add_argument("-b", "--be", help="Method B, no file required.",
                   action='store_true')
# define a parser for option -a
parser_a = argparse.ArgumentParser()
parser_a.add_argument("-f", "--file", help="A file, used with method A.",
                      type=check_file, required=True)
parser_a.add_argument("-a", "--ay", help="Method A, requires file.",
                      action='store_true')

# first parse - get either -a/-b
args = parser.parse_known_args(sys.argv[1:])
# if -a, use the second parser to ensure -f is in argument
# note parse_known_args return tuple, the first one is the populated namespace
if args[0].ay:
    args = parser_a.parse_args(sys.argv[1:])
</code>```

Body:
I have a small python script, which uses argparse to let the user define options. It uses two flags for different modes and an argument to let the user define a file. See the simplified example below:

#!/usr/bin/python3

import argparse
from shutil import copyfile

def check_file(f):
    # Mock function: checks if file exists, else "argparse.ArgumentTypeError("file not found")"
    return f

def main():
    aFile = "/tmp/afile.txt"

    parser = argparse.ArgumentParser(description="An example",formatter_class=argparse.RawTextHelpFormatter)
    parser.add_argument("-f", "--file", help="A file, used with method A.", default=aFile, type=check_file)
    parser.add_argument("-a", "--ay", help="Method A, requires file.", action='store_true')
    parser.add_argument("-b", "--be", help="Method B, no file required.", action='store_true')

    args = parser.parse_args()
    f = args.file
    a = args.ay
    b = args.be

    if a:
        copyfile(f, f+".a")
    elif b:
        print("Method B")

if __name__ == "__main__":
    main()

Method A requires the file.

Method B does not.

If I run the script with method A, I either use the default file or one that is defined with -f/--file. The script checks if the file exists and everything is fine.

Now, if I run the script with method B, it shouldn't require the file, but the default option is checked and if it doesn't exist the argparse function raises the exception and the script exits.

How can I configure argparse to make -f optional, if -b is defined and require it, if -a is defined?

edit: I just realized that it would be enough for me to make -f and -b mutually exclusive. But then, if I run -b only, the check_file is executed anyways. Is there a way to prevent that?

#!/usr/bin/python3

import argparse
from shutil import copyfile

def check_file(f):
    # Mock function: checks if file exists, else "argparse.ArgumentTypeError("file not found")"
    print("chk file")
    return f

def main():
    aFile = "/tmp/afile.txt"

    parser = argparse.ArgumentParser(description="An example",formatter_class=argparse.RawTextHelpFormatter)
    group = parser.add_mutually_exclusive_group(required=True)

    group.add_argument("-f", "--file", help="A file, used with method A.", default=aFile, type=check_file)
    parser.add_argument("-a", "--ay", help="Method A, requires file.", action='store_true')
    group.add_argument("-b", "--be", help="Method B, no file required.", action='store_true')

    args = parser.parse_args()
    f = args.file
    a = args.ay
    b = args.be

    if a:
        print("File: "+str(f))
    elif b:
        print("Method B")
        print("file: "+str(f))

if __name__ == "__main__":
    main()

Output:

chk file
Method B
file: /tmp/afile.txt

Body:
You can defined subparser with ay/be as subcommand or alternatively declare a second parser instance for a. Something like:

parser = argparse.ArgumentParser(
    description="An example",
    formatter_class=argparse.RawTextHelpFormatter
)
# ensure either option -a or -b only
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("-a", "--ay", help="Method A, requires file.",
                   action='store_true')
group.add_argument("-b", "--be", help="Method B, no file required.",
                   action='store_true')
# define a parser for option -a
parser_a = argparse.ArgumentParser()
parser_a.add_argument("-f", "--file", help="A file, used with method A.",
                      type=check_file, required=True)
parser_a.add_argument("-a", "--ay", help="Method A, requires file.",
                      action='store_true')

# first parse - get either -a/-b
args = parser.parse_known_args(sys.argv[1:])
# if -a, use the second parser to ensure -f is in argument
# note parse_known_args return tuple, the first one is the populated namespace
if args[0].ay:
    args = parser_a.parse_args(sys.argv[1:])