问:
Query to show match information for last 2 rounds of tournament
I dont know how to achieve this.

I have 2 tables in my database:

Table 1: rounds

```<code>+------------+----------+---------+----------+---------------+
|  round_id  |  format  |  Size   |  poster  | tournament_id |
+------------+----------+---------+----------+---------------+
|     6      |  Single  |   12    |  Luis    |      1
|     7      |  Single  |   9     |  Daniel  |      1        |
|     8      |  Single  |   4     |  Oscar   |      1        |
+------------+----------+---------+----------+---------------+
</code>```

Table 2: matches

```<code>+------------+----------+-------------+----------+----------+
|  round_id  |  player  |  position   |  score   |  winner  |
+------------+----------+-------------+----------+----------+
|     6      |  Doris   |     0       |    1     |    1     |
|     7      |  Arturo  |     0       |    3     |    1     |
|     7      |  Pablo   |     1       |    2     |    0     |
|     8      |  Ale     |     0       |    1     |    0     |
|     8      |  Maria   |     1       |    5     |    1     |
|     8      |  Roberto |     2       |    4     |    0     |
+------------+----------+-------------+----------+----------+
</code>```

At the first table i have the rounds of the tournaments and at the second table the matches from each round, as you can see each match in a round can have different size of players. So i want to get all info of the rounds BUT just the last 2 rounds from the table "rounds", to get something like this in one query:

Result from query:

//The main key can be the round_id or numbers in order 0 to n
//

```<code>[7] => Array
    (
        ['poster'] => 'Daniel'
        ['format'] => 'single'

            (
                [0] => Array
                      (
                          ['player'] => 'Arturo'
                          ['score'] => 3
                       )
                [1] => Array
                       (
                          ['player'] => 'Pablo'
                          ['score'] => 2
                       )
            )

    )
[8] => Array
    (
        ['poster'] => 'Oscar'
        ['format'] => 'single'

            (
                [0] => Array
                      (
                          ['player'] => 'Ale'
                          ['score'] => 1
                       )
                [1] => Array
                       (
                          ['player'] => 'Maria'
                          ['score'] => 5
                       )
                [2] => Array
                       (
                          ['player'] => 'Roberto'
                          ['score'] => 4
                       )
            )

    )
</code>```

So in my page i can show the last rounds uploaded, something like this:

```<code>+---------------------------+
|  by Daniel                |
|  Arturo (3) vs Pablo (2)  |
+---------------------------+

+---------------------------------------+
|  by Oscar                             |
|  Ale (1) vs Maria (5) vs Roberto (4)  |
+---------------------------------------+
</code>```

Hope a MySQL expert can help me with this :)

答:
Join the matches table with a subquery that gets the last 2 rows in the rounds table.

```<code>SELECT *
FROM (SELECT *
      FROM rounds
      ORDER BY round_id DESC
      LIMIT 2) AS r
JOIN matches AS m ON r.round_id = m.round_id
</code>```

See Creating one array from another array in php for how you can combine the match information for the same round in the PHP array.

If you want the query to return one row for each round, you can use GROUP_CONCAT to combine the match information into a single column:

```<code>SELECT r.poster, r.format, GROUP_CONCAT(CONCAT(m.player, '(', m.score, ')') SEPARATOR ' vs ') AS players
FROM (SELECT round_id, poster, format
      FROM rounds
      ORDER BY round_id DESC
      LIMIT 2) AS r
JOIN matches AS m ON r.round_id = m.round_id
GROUP BY m.round_id
</code>```

Body:
I dont know how to achieve this.

I have 2 tables in my database:

Table 1: rounds

+------------+----------+---------+----------+---------------+
|  round_id  |  format  |  Size   |  poster  | tournament_id |
+------------+----------+---------+----------+---------------+
|     6      |  Single  |   12    |  Luis    |      1
|     7      |  Single  |   9     |  Daniel  |      1        |
|     8      |  Single  |   4     |  Oscar   |      1        |
+------------+----------+---------+----------+---------------+

Table 2: matches

+------------+----------+-------------+----------+----------+
|  round_id  |  player  |  position   |  score   |  winner  |
+------------+----------+-------------+----------+----------+
|     6      |  Doris   |     0       |    1     |    1     |
|     7      |  Arturo  |     0       |    3     |    1     |
|     7      |  Pablo   |     1       |    2     |    0     |
|     8      |  Ale     |     0       |    1     |    0     |
|     8      |  Maria   |     1       |    5     |    1     |
|     8      |  Roberto |     2       |    4     |    0     |
+------------+----------+-------------+----------+----------+

At the first table i have the rounds of the tournaments and at the second table the matches from each round, as you can see each match in a round can have different size of players. So i want to get all info of the rounds BUT just the last 2 rounds from the table "rounds", to get something like this in one query:

Result from query:

//The main key can be the round_id or numbers in order 0 to n
//

[7] => Array
    (
        ['poster'] => 'Daniel'
        ['format'] => 'single'

            (
                [0] => Array
                      (
                          ['player'] => 'Arturo'
                          ['score'] => 3
                       )
                [1] => Array
                       (
                          ['player'] => 'Pablo'
                          ['score'] => 2
                       )
            )

    )
[8] => Array
    (
        ['poster'] => 'Oscar'
        ['format'] => 'single'

            (
                [0] => Array
                      (
                          ['player'] => 'Ale'
                          ['score'] => 1
                       )
                [1] => Array
                       (
                          ['player'] => 'Maria'
                          ['score'] => 5
                       )
                [2] => Array
                       (
                          ['player'] => 'Roberto'
                          ['score'] => 4
                       )
            )

    )

So in my page i can show the last rounds uploaded, something like this:

+---------------------------+
|  by Daniel                |
|  Arturo (3) vs Pablo (2)  |
+---------------------------+

+---------------------------------------+
|  by Oscar                             |
|  Ale (1) vs Maria (5) vs Roberto (4)  |
+---------------------------------------+

Hope a MySQL expert can help me with this :)

Body:
Join the matches table with a subquery that gets the last 2 rows in the rounds table.

SELECT *
FROM (SELECT *
      FROM rounds
      ORDER BY round_id DESC
      LIMIT 2) AS r
JOIN matches AS m ON r.round_id = m.round_id

See Creating one array from another array in php for how you can combine the match information for the same round in the PHP array.

If you want the query to return one row for each round, you can use GROUP_CONCAT to combine the match information into a single column:

SELECT r.poster, r.format, GROUP_CONCAT(CONCAT(m.player, '(', m.score, ')') SEPARATOR ' vs ') AS players
FROM (SELECT round_id, poster, format
      FROM rounds
      ORDER BY round_id DESC
      LIMIT 2) AS r
JOIN matches AS m ON r.round_id = m.round_id
GROUP BY m.round_id


来源: stackexchange

问:
Java wait, notify - wait not working?
I'm learning work with Thread in Java.
I am trying to write a program that will have two threads.
Each thread will write your name in the cycle.
In Main run cycle will generate numbers ( 0 , 9 ).
When it generates an odd number, wait the thread 1 ( even - thread 2 ) .
If a thread will sleep and wake him up .
The problem is that when I call wait , the program freezes .
Code:

```<code>import java.util.Random;

public class TestClass {

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

        myThread one = new myThread("Thread one");
        myThread two = new myThread("Thread two");

        one.start();
        two.start();

        Random random = new Random();

        for (int i = 0; i < 10; i++) {
            int rnd = random.nextInt(10);
            if (rnd % 2 == 0) {
                synchronized (two) {
                    two.wait(); // first loop - freez
                }
            } else {
                synchronized (one) {
                    one.wait();
                }
            }
        }

    }

}

class myThread extends Thread {

    private boolean canIRun = true;
    private final String name;

    myThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        while (canIRun) {
            System.out.println("My name is: " + name);
        }
    }

}
</code>```

答:
I wanted to create an answer that re-broadcasts @jonskeet's comment above:

Do not call wait() or notify() on Thread objects - it's unfortunate, but Thread uses its own monitor for other things.

I have found this out several times the hard way in classes that extend Thread or implement Runnable that were hung because of synchronized(this).  Since finding this question, I have searched many times and in nowhere have I found any warning to not do this.  And if you have a fast, idle computer, you will probably never find this in testing.

Perhaps someone with better google-foo can find the documentation.  If so, please comment or amend this answer.

wait notify threads synchronized this hung thread

ContentLicense: CC BY-SA 3.0

Title: Java wait, notify - wait not working?

Body:
I'm learning work with Thread in Java.
I am trying to write a program that will have two threads.
Each thread will write your name in the cycle.
In Main run cycle will generate numbers ( 0 , 9 ).
When it generates an odd number, wait the thread 1 ( even - thread 2 ) .
If a thread will sleep and wake him up .
The problem is that when I call wait , the program freezes .
Code:

import java.util.Random;

public class TestClass {

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

        myThread one = new myThread("Thread one");
        myThread two = new myThread("Thread two");

        one.start();
        two.start();

        Random random = new Random();

        for (int i = 0; i < 10; i++) {
            int rnd = random.nextInt(10);
            if (rnd % 2 == 0) {
                synchronized (two) {
                    two.wait(); // first loop - freez
                }
            } else {
                synchronized (one) {
                    one.wait();
                }
            }
        }

    }

}

class myThread extends Thread {

    private boolean canIRun = true;
    private final String name;

    myThread(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        while (canIRun) {
            System.out.println("My name is: " + name);
        }
    }

}


问:
How to add an item from a list to another list
I have a list called "enctypechances" and I want to give the item "Land" to another list.

```<code>public static List<Encounter> enctypechances = new List<Encounter>();
Encounter Land = new Encounter(20, 20, 10, 10, 10, 10, 5, 5, 4, 4, 1, 1);
</code>```

Here is where I want to add the "Land" item

```<code>List<Encounter> enctypes = new List<Encounter>();

void Start () {
    enctypes.Add( ??? );
}
</code>```

答:
Land has to be visible within the start() scope. You have to declare it inside the method, pass it in as an argument to the method, or make sure it's otherwise visible inside the class.

As others have commented though, you should probably show us more code for a more specific answer.

Body:
I have a list called "enctypechances" and I want to give the item "Land" to another list.

public static List<Encounter> enctypechances = new List<Encounter>();
Encounter Land = new Encounter(20, 20, 10, 10, 10, 10, 5, 5, 4, 4, 1, 1);

Here is where I want to add the "Land" item

List<Encounter> enctypes = new List<Encounter>();

void Start () {
    enctypes.Add( ??? );
}


问:
python syntax error can figure out!! variable
I have this code in python, to ask people how many cigarettes do they smoke and return how many they smoke in a month and in a year. I have an error at line 4, I have searched this but I don't find any that work. I know it is a syntax problem but I can't figure it out.

Here is the code:

```<code>print ("Hola, Que Tal")
print ("Como te llamas?")
miNumbre=input()
print ("Mucho Gusto " + miNumbre )
print ("Cuantos Paquetes de Puchos Fumas Por Dia?")
puchos=input()
print ("Fumas " +str(int(puchos) * 30) + " Paquetes de Puchos Por Mes")
print ("En Un Año Fumas " +str(int(puchos) * 360) + " Paquetes de Puchos")
</code>```

答:
and it's better to format the string like this when you have to use nums and chars:</p>

```<code>print ("Mucho Gusto {}".format(miNumbre ))
</code>```

Body:
I have this code in python, to ask people how many cigarettes do they smoke and return how many they smoke in a month and in a year. I have an error at line 4, I have searched this but I don't find any that work. I know it is a syntax problem but I can't figure it out.

Here is the code:

print ("Hola, Que Tal")
print ("Como te llamas?")
miNumbre=input()
print ("Mucho Gusto " + miNumbre )
print ("Cuantos Paquetes de Puchos Fumas Por Dia?")
puchos=input()
print ("Fumas " +str(int(puchos) * 30) + " Paquetes de Puchos Por Mes")
print ("En Un Año Fumas " +str(int(puchos) * 360) + " Paquetes de Puchos")

Body:
and it's better to format the string like this when you have to use nums and chars:

print ("Mucho Gusto {}".format(miNumbre ))


问:
Controller not loading ocLazyLoad
I have newly included the lazyload library.

```<code>var app = angular.module(subdomain, ['ngRoute','ngResource','ngCookies','ngSanitize','angular-md5','mm.foundation','chieffancypants.loadingBar', 'ngAnimate','ui-notification','infinite-scroll','oc.lazyLoad']);
</code>```

I have loaded the controller in routes page:

```<code> $routeProvider
     .when('/',
     {
        templateUrl: 'app/components/home/home.html',
        access: { requiredLogin: true },
        resolve: {
            lazy: ['$ocLazyLoad', function($ocLazyLoad) {
                return $ocLazyLoad.load([{
                    name: 'app',
                    files: ['dist/home.min.js']
                }]);
            }]
        },
        controller: 'homeController'
    })
</code>```

and my controller file has:

```<code>app.controller("homeController",[....])
</code>```

I am getting home controller not defined error. If I change the app to angular.module in the controller its working but that's not what I want. Is there any solution for this so I can use app variable?

答:
Looks like you're having the same issue as this guy: https://stackoverflow.com/a/44414548/1040731

You should reference your controller through the module angular.module('myapp').controller('homeController',...)

Title: Controller not loading ocLazyLoad

Body:
I have newly included the lazyload library.

var app = angular.module(subdomain, ['ngRoute','ngResource','ngCookies','ngSanitize','angular-md5','mm.foundation','chieffancypants.loadingBar', 'ngAnimate','ui-notification','infinite-scroll','oc.lazyLoad']);

I have loaded the controller in routes page:

 $routeProvider
     .when('/',
     {
        templateUrl: 'app/components/home/home.html',
        access: { requiredLogin: true },
        resolve: {
            lazy: ['$ocLazyLoad', function($ocLazyLoad) {
                return $ocLazyLoad.load([{
                    name: 'app',
                    files: ['dist/home.min.js']
                }]);
            }]
        },
        controller: 'homeController'
    })

and my controller file has:

app.controller("homeController",[....])

I am getting home controller not defined error. If I change the app to angular.module in the controller its working but that's not what I want. Is there any solution for this so I can use app variable?


问:
How to change value of an array in knockout.js?
```<code><div class="row">
    <div class="col-md-6" data-bind="visible: application.candidateMostRecentAcademic" style="display:none;">
        <span>Education:</span>
             <!-- ko if: application.candidateMostRecentAcademic != null -->
               <!-- ko with: application.candidateMostRecentAcademic[0] -->
                 <span data-bind="text: $data.degreeTypeName"></span>
                 <span data-bind="text: $data.institutionName"></span>
                 <span data-bind="text: $data.dateToYear"></span>
               <!-- /ko -->
             <!-- /ko -->
    </div>
</div>
</code>```

I was going to make the the column visible only if application.candidateMostRecentAcademic (array) exists.

But I also wanted to add a condition for an array that has 0 length (which is not null).

So when I tried to do,

```<code><div class="col-md-6" data-bind="visible: application.candidateMostRecentAcademic.length != 0" style="display:none;">
</code>```

it gave me an error saying that it cannot access the "length" of a null object. So, what I am trying to do is, I want to set an array of length 0 to null so that it can just be invisible just like the null object.

How can I do this with knockout data-binding?

答:
If I understand you correctly, you want your if statement to pass if the Array is not null and if it's length is not equal to 0?

If this is the case, you could do this in your template:

```<code><div class="col-md-6" data-bind="visible: application.candidateMostRecentAcademic && application.candidateMostRecentAcademic.length !== 0">
</code>```

Body:
        Education:

I was going to make the the column visible only if application.candidateMostRecentAcademic (array) exists.

But I also wanted to add a condition for an array that has 0 length (which is not null).

So when I tried to do,

it gave me an error saying that it cannot access the "length" of a null object. So, what I am trying to do is, I want to set an array of length 0 to null so that it can just be invisible just like the null object.

How can I do this with knockout data-binding?

Body:
If I understand you correctly, you want your if statement to pass if the Array is not null and if it's length is not equal to 0?

If this is the case, you could do this in your template:

<div class="col-md-6" data-bind="visible: application.candidateMostRecentAcademic && application.candidateMostRecentAcademic.length !== 0">


问:
Apache Artemis V 2.1.0
I was using Artemis 1.5.3 and my addressing scheme was jms.topic.xxx for pub-sub and jms.queue.xxx for point to point and all worked great. However I switch to version 2.1.0 and the jms.topic.xxx work like a point to point routing, meaning not all subscribers receive the message. Previously, I was using ActiveMQ and their naming prefix was /topic.xxx and /queue.xxx. I also tried setting the multicast config in broker.xml per activemq.apache.org/artemis/docs/2.1.0/address-model.html but Artemis is complaining and will not start. Any help would be much appreciated.</p>

答:
Without seeing what the actual errors are in the logs, I am going to assume that your instance is not starting up because of the way that you are defining your queues and/or topics. In version 2.x and newer, Artemis changed the way you define a queue or topic (They switched to an Address Model http://activemq.apache.org/artemis/docs/2.1.0/address-model.html).  Below is an example.  I hope this helps.

….. rest of broker.xml configuration

```<code>  <addresses>
     <!-- default queues for artemis -->
     <address name="DLQ">
        <anycast>
           <queue name="DLQ" />
        </anycast>
     </address>
     <address name="ExpiryQueue">
        <anycast>
           <queue name="ExpiryQueue" />
        </anycast>
     </address>

     <!-- Define topics -->
     <address name="SomeTestTopic">
        <multicast/>
     </address>

     <!-- Define queues -->
     <address name="RequestReplyQueue">
        <anycast>
           <queue name="RequestReplyQueue" />
        </anycast>
     </address>

  </addresses>
</code>```

Title: Apache Artemis V 2.1.0

Body:
Without seeing what the actual errors are in the logs, I am going to assume that your instance is not starting up because of the way that you are defining your queues and/or topics. In version 2.x and newer, Artemis changed the way you define a queue or topic (They switched to an Address Model http://activemq.apache.org/artemis/docs/2.1.0/address-model.html).  Below is an example.  I hope this helps.

….. rest of broker.xml configuration

  <addresses>
     <!-- default queues for artemis -->
     <address name="DLQ">
        <anycast>
           <queue name="DLQ" />
        </anycast>
     </address>
     <address name="ExpiryQueue">
        <anycast>
           <queue name="ExpiryQueue" />
        </anycast>
     </address>

     <!-- Define topics -->
     <address name="SomeTestTopic">
        <multicast/>
     </address>

     <!-- Define queues -->
     <address name="RequestReplyQueue">
        <anycast>
           <queue name="RequestReplyQueue" />
        </anycast>
     </address>

  </addresses>


问:
How to change an element’s CSS class and remove all other classes on click
How do I handle a case in AngularJS 2 where on click of an element it needs to change its own style, and if other elements have that style they need to have it removed — preferably in one function.

Similar to Angular.js How to change an elements css class on click and to remove all others, only in AngularJS 2, using TypeScript.

Component

https://plnkr.co/edit/Q2BoU4sNnXdaJB5vrZ8h?p=preview

```<code>//our root app component
import { NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {Component} from '@angular/core';

@Component({
  selector: 'my-app',
  providers: [],
  template: `
    <div>
      <div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
        > I'm a div that gets styled on click
      </div>
      <div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
        > I also want to be styled but only when Im clicked
      </div>
      <div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
        > When one of us gets clicked the we want to be the only one with the style all others go back to normal
      </div>
       <div (click)="isClassVisible = !isClassVisible;" [ngClass]="{'my-class': isClassVisible }">
        > I'm just here cause my creator likes even numbers
      </div>
    </div>
  `,
  styles: [
  `
  .my-class {
    background-color: yellow;
  }
  `
  ]
})
class App {
  isClassVisible: false;

  constructor() {
  }

}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}
</code>```

答:
One solution which worked for me in showing the active menu is using typescript variable name in class as in

```<code>class="{{ text1Class }}"
</code>```

and assign the class name in typescript.

```<code>this.text1Class = "active";
</code>```

or

```<code>this.text1Class = "inactive";
</code>```

You need to have different style class like this

```<code>.inactive {
     background-color : gray;
     padding : 10px;
}
.active {
      background-color : green;
      padding : 10px;
}
</code>```

Assign the class name inside the function

```<code>textOneClicked() : void {
    this.text1Class = "active"; // set the active class
    this.text2Class = this.text3Class = this.text4Class = "inactive"; // reset other classes
}
</code>```

A working Plunker here

Body:
How do I handle a case in AngularJS 2 where on click of an element it needs to change its own style, and if other elements have that style they need to have it removed — preferably in one function.

Similar to Angular.js How to change an elements css class on click and to remove all others, only in AngularJS 2, using TypeScript.

Component

https://plnkr.co/edit/Q2BoU4sNnXdaJB5vrZ8h?p=preview

//our root app component
import { NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import {Component} from '@angular/core';

@Component({
  selector: 'my-app',
  providers: [],
  template: `

        > I'm a div that gets styled on click

        > I also want to be styled but only when Im clicked

        > When one of us gets clicked the we want to be the only one with the style all others go back to normal

        > I'm just here cause my creator likes even numbers

  `,
  styles: [
  `
  .my-class {
    background-color: yellow;
  }
  `
  ]
})
class App {
  isClassVisible: false;

  constructor() {
  }

}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Body:
One solution which worked for me in showing the active menu is using typescript variable name in class as in

class="{{ text1Class }}"

and assign the class name in typescript.

this.text1Class = "active";

or

this.text1Class = "inactive";

You need to have different style class like this

.inactive {
     background-color : gray;
     padding : 10px;
}
.active {
      background-color : green;
      padding : 10px;
}

Assign the class name inside the function

textOneClicked() : void {
    this.text1Class = "active"; // set the active class
    this.text2Class = this.text3Class = this.text4Class = "inactive"; // reset other classes
}

A working Plunker here

ContentLicense: CC BY-SA 4.0


问:
Only loading video into VideoView without instantly playing
I got a question is it possible in Android to load the video data into a VideoView without it instantly starting to play? If so, how could I do that?

答:
I have found that just doing VideoView.seekTo(n) isn't sufficient on all devices to show the video's first frame.

If all that you need to do is show the first frame, but not play the video, then you can just do this, which is helpful to render a video's thumbnail:

```<code>MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(context, uri);
Bitmap firstFrame = MediaMetadataRetriever.getFrameAtTime(0);
// Set firstFrame bitmap to ImageView...
</code>```

However, to reliably show the first frame in cases where you want to play the video at some point after rendering, such as from a user interaction, my solution is to register an OnPreparedListener, and then call start(). I also register an OnInfoListener so that I can be notified when rendering starts. I then check if the info is indeed a "rendering start" event, and I check if this is the first time that the VideoView has started rendering. If so, I pause() and then seekTo(0).

Here's how that would look:

```<code>private void showFirstFrame(final VideoView videoView, Uri uri) {
  videoView.setVideoURI(uri);

  final AtomicBoolean showedFirstFrame = new AtomicBoolean(false);

  videoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
      // If this is our first time starting video rendering, pause and show first frame
      if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START
          && showedFirstFrame.compareAndSet(false, true)) {
        videoView.pause();
        videoView.seekTo(0);
      }

      return false;
    }
  });

  videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
      videoView.start();
    }
  });
}
</code>```

Body:
I have found that just doing VideoView.seekTo(n) isn't sufficient on all devices to show the video's first frame.

If all that you need to do is show the first frame, but not play the video, then you can just do this, which is helpful to render a video's thumbnail:

MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever();
mediaMetadataRetriever.setDataSource(context, uri);
Bitmap firstFrame = MediaMetadataRetriever.getFrameAtTime(0);
// Set firstFrame bitmap to ImageView...

However, to reliably show the first frame in cases where you want to play the video at some point after rendering, such as from a user interaction, my solution is to register an OnPreparedListener, and then call start(). I also register an OnInfoListener so that I can be notified when rendering starts. I then check if the info is indeed a "rendering start" event, and I check if this is the first time that the VideoView has started rendering. If so, I pause() and then seekTo(0).

Here's how that would look:

private void showFirstFrame(final VideoView videoView, Uri uri) {
  videoView.setVideoURI(uri);

  final AtomicBoolean showedFirstFrame = new AtomicBoolean(false);

  videoView.setOnInfoListener(new MediaPlayer.OnInfoListener() {
    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
      // If this is our first time starting video rendering, pause and show first frame
      if (what == MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START
          && showedFirstFrame.compareAndSet(false, true)) {
        videoView.pause();
        videoView.seekTo(0);
      }

      return false;
    }
  });

  videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
    @Override
    public void onPrepared(MediaPlayer mp) {
      videoView.start();
    }
  });
}


问:
How to prevent Firefox Developer Tools to scroll page to top?
I've noticed that when I've the Firefox Developer Tools opened and I open any page (i.e. http://www.bbc.com/news) it scrolls the page to the top.

I've the 53.0.3 (64 bit). 32bit is the same.

How can I prevent this?

答:
This is obviously a regression in the Firefox DevTools. So I've created bug 1371050 for it.

Update:

My bug report got marked as duplicate of bug 1365209.


问:
how to call a method from a menu of methods?
I am learning about methods and am trying to make a menu of methods that do simple conversions. I don't know how to call a method from the menu and make it do the function. I would like to know how to call a method AND make it run with inputs not using the scanner class except in main.

```<code>public static void main(String[] args) {
    displayMenu();
    Scanner keyboard = new Scanner(System.in);
    int selection = keyboard.nextInt();
    switch(selection) {
    case 1:
        FahrToCel();
        break;
    case 2:
        CelToFahr();
        break;
    case 3:
        LbToKilo();
        break;
    case 4:
        KiloToLb();
        break;
   }

}

public static void displayMenu() {
    System.out.println("Enter 1 for Fahrenheit to Celsius" );
    System.out.println("Enter 2 for Celsius to Fahrenheit");
    System.out.println("Enter 3 for lb to kg");
    System.out.println("Enter 4 for kg to lb");
    return;

public static double FahrToCel() {

    double Fahrenheit = ???;
    double Celsius = 5 * (Fahrenheit - 32) / 9;

    return Celsius;

}

public static double CelToFahr() {
    double Celsius = ???;
    double Fahrenheit = (9 * Celsius / 5) + 32;
    return Fahrenheit;

}

public static double LbtoKilo() {
    double pounds = ???;
    double factor = 0.454;
    double Kilogram = pounds * factor;

    return Kilogram;

}
public static double KiloToLb() {
    double kilograms = ???;
    double factor = 0.454;
    double Pound = kilograms / factor;
    return Pound;

}
</code>```

the ??? are the variables that i want to get user input, but idk how to do that without making a new Scanner in each method.

idk how to get the inputs in the methods either.

When I run the code, I get the displayMenu options and i can input 1,2,3,4 but then nothing happens after that

答:
As @JoshKopen said, you were not providing the values you want to convert, my answer is pretty much the same, just being a little more specific and using a double value instead of an int for more precision.

Try this:

```<code>public static void main(String[] args) {
    displayMenu();
    Scanner keyboard = new Scanner(System.in);
    int selection = keyboard.nextInt();
    double value;
    switch(selection) {
    case 1:
        System.out.println("Enter the Fahrenheit value:");
        value = keyboard.nextDouble();
        FahrToCel(value);
        break;
    case 2:
        System.out.println("Enter the Celsius value:");
        value = keyboard.nextDouble();
        CelToFahr(value);
        break;
    case 3:
        System.out.println("Enter the Lb value:");
        value = keyboard.nextDouble();
        LbToKilo(value);
        break;
    case 4:
        System.out.println("Enter the Kilo value:");
        value = keyboard.nextDouble();
        KiloToLb(value);
        break;
   }

}

public static void displayMenu() {
    System.out.println("Enter 1 for Fahrenheit to Celsius" );
    System.out.println("Enter 2 for Celsius to Fahrenheit");
    System.out.println("Enter 3 for lb to kg");
    System.out.println("Enter 4 for kg to lb");
    return;
}
public static double FahrToCel(double fValue) {

    double Fahrenheit = fValue;
    double Celsius = 5 * (Fahrenheit - 32) / 9;

    return Celsius;

}

public static double CelToFahr(double cValue) {
    double Celsius = cValue;
    double Fahrenheit = (9 * Celsius / 5) + 32;
    return Fahrenheit;

}

public static double LbtoKilo(double lValue) {
    double pounds = lValue;
    double factor = 0.454;
    double Kilogram = pounds * factor;

    return Kilogram;

}
public static double KiloToLb(double kValue) {
    double kilograms = kValue;
    double factor = 0.454;
    double Pound = kilograms / factor;
    return Pound;

}
</code>```

Body:
I am learning about methods and am trying to make a menu of methods that do simple conversions. I don't know how to call a method from the menu and make it do the function. I would like to know how to call a method AND make it run with inputs not using the scanner class except in main.

public static void main(String[] args) {
    displayMenu();
    Scanner keyboard = new Scanner(System.in);
    int selection = keyboard.nextInt();
    switch(selection) {
    case 1:
        FahrToCel();
        break;
    case 2:
        CelToFahr();
        break;
    case 3:
        LbToKilo();
        break;
    case 4:
        KiloToLb();
        break;
   }

}

public static void displayMenu() {
    System.out.println("Enter 1 for Fahrenheit to Celsius" );
    System.out.println("Enter 2 for Celsius to Fahrenheit");
    System.out.println("Enter 3 for lb to kg");
    System.out.println("Enter 4 for kg to lb");
    return;

public static double FahrToCel() {

    double Fahrenheit = ???;
    double Celsius = 5 * (Fahrenheit - 32) / 9;

    return Celsius;

}

public static double CelToFahr() {
    double Celsius = ???;
    double Fahrenheit = (9 * Celsius / 5) + 32;
    return Fahrenheit;

}

public static double LbtoKilo() {
    double pounds = ???;
    double factor = 0.454;
    double Kilogram = pounds * factor;

    return Kilogram;

}
public static double KiloToLb() {
    double kilograms = ???;
    double factor = 0.454;
    double Pound = kilograms / factor;
    return Pound;

}

the ??? are the variables that i want to get user input, but idk how to do that without making a new Scanner in each method.

idk how to get the inputs in the methods either.

When I run the code, I get the displayMenu options and i can input 1,2,3,4 but then nothing happens after that

Body:
As @JoshKopen said, you were not providing the values you want to convert, my answer is pretty much the same, just being a little more specific and using a double value instead of an int for more precision.

Try this:

public static void main(String[] args) {
    displayMenu();
    Scanner keyboard = new Scanner(System.in);
    int selection = keyboard.nextInt();
    double value;
    switch(selection) {
    case 1:
        System.out.println("Enter the Fahrenheit value:");
        value = keyboard.nextDouble();
        FahrToCel(value);
        break;
    case 2:
        System.out.println("Enter the Celsius value:");
        value = keyboard.nextDouble();
        CelToFahr(value);
        break;
    case 3:
        System.out.println("Enter the Lb value:");
        value = keyboard.nextDouble();
        LbToKilo(value);
        break;
    case 4:
        System.out.println("Enter the Kilo value:");
        value = keyboard.nextDouble();
        KiloToLb(value);
        break;
   }

}

public static void displayMenu() {
    System.out.println("Enter 1 for Fahrenheit to Celsius" );
    System.out.println("Enter 2 for Celsius to Fahrenheit");
    System.out.println("Enter 3 for lb to kg");
    System.out.println("Enter 4 for kg to lb");
    return;
}
public static double FahrToCel(double fValue) {

    double Fahrenheit = fValue;
    double Celsius = 5 * (Fahrenheit - 32) / 9;

    return Celsius;

}

public static double CelToFahr(double cValue) {
    double Celsius = cValue;
    double Fahrenheit = (9 * Celsius / 5) + 32;
    return Fahrenheit;

}

public static double LbtoKilo(double lValue) {
    double pounds = lValue;
    double factor = 0.454;
    double Kilogram = pounds * factor;

    return Kilogram;

}
public static double KiloToLb(double kValue) {
    double kilograms = kValue;
    double factor = 0.454;
    double Pound = kilograms / factor;
    return Pound;

}


问:
How to test node.js module which returns anonymous function?
I'm writing small middleware for express.js route, but when I came to unit test this code I stuck, and I don't know how to properly test it using mocha, sinon and chai.

My middleware code has entrypoint something like this:

```<code> const searchByQuerystring = require('./search-by-querystring');
 const searchByMarker = require('./search-by-marker');

 module.exports = (req, res, next) => {

   if (req.marker) {
      searchByMarker(req, res, next);
   } else if (req.query) {
      searchByQuerystring(req, res, next);
   } else {
      next();
   }
};
</code>```

, and during unit test I would like to test if method searchByMarker or searchByQuerystring was called.

So I start with writing this test,

```<code>it('Should call search by querystring if querystring is present', () => {
    const req = httpMocks.createRequest({
            query: {
                value: 1000
            }
        }),
        res = httpMocks.createResponse(),
        next = sandbox.spy();
    searchIndex(req, res, next);

    sinon.assert.calledOnce(next);
});
</code>```

where my middleware should use searchByQuerystring for process request and I would like to test it if searchByQuerystring method was called, but I really don't know how to do that, maybe i just should write this code in some other way, I really don't want to use libraries like proxyquire .

Maybe my module is doing too much work (according to Single Responsibility Principle) - but whole middleware is for build search object where on start I just need to find out from which place parameters will came, so I thought that it is a good idea to put this logic on start of the middleware - and I just should have two middlewares?

Please for any help, suggestions about this.

答:
Alright,

So putting this post help me to to find a solution. I rewrite my middleware entry point, to looking like this

```<code>const searchRequestParser = require('./search-request-parser');
const search = require('../../../lib/search');

module.exports = (req, res, next) => {

  const searchRequest = searchRequestParser(req);
  if (searchRequest) {
    const searchCriteria = search(searchRequest.resourceToSearch);
    req.searchQuery =
  searchCriteria.buildQuery(searchRequest.queryParameters);
  }
  next();
};
</code>```

And test

```<code>    it('Should call search by querystring if querystring is present', () => {
    const req = httpMocks.createRequest({
            method: 'GET',
            params: {
                resourceToSearch: 'debts'
            },
            query: {
                value: 1000
            }
        }),
        res = httpMocks.createResponse(),
        next = sandbox.spy();
    searchIndex(req, res, next);

    expect(req).to.have.a.property('searchQuery');
});
</code>```

So methods searchByMarker or searchByQuerystring are gone and replaced by method searchRequestParser with output, then I process this output in code which as it turned out was duplicated previously in methods searchByMarker or searchByQuerystring.

Thanks to return outputs from functions I used, I didn't have to focus on mocking/stubing those functions.

Body:
I'm writing small middleware for express.js route, but when I came to unit test this code I stuck, and I don't know how to properly test it using mocha, sinon and chai.

My middleware code has entrypoint something like this:

 const searchByQuerystring = require('./search-by-querystring');
 const searchByMarker = require('./search-by-marker');

 module.exports = (req, res, next) => {

   if (req.marker) {
      searchByMarker(req, res, next);
   } else if (req.query) {
      searchByQuerystring(req, res, next);
   } else {
      next();
   }
};

, and during unit test I would like to test if method searchByMarker or searchByQuerystring was called.

So I start with writing this test,

it('Should call search by querystring if querystring is present', () => {
    const req = httpMocks.createRequest({
            query: {
                value: 1000
            }
        }),
        res = httpMocks.createResponse(),
        next = sandbox.spy();
    searchIndex(req, res, next);

    sinon.assert.calledOnce(next);
});

where my middleware should use searchByQuerystring for process request and I would like to test it if searchByQuerystring method was called, but I really don't know how to do that, maybe i just should write this code in some other way, I really don't want to use libraries like proxyquire .

Maybe my module is doing too much work (according to Single Responsibility Principle) - but whole middleware is for build search object where on start I just need to find out from which place parameters will came, so I thought that it is a good idea to put this logic on start of the middleware - and I just should have two middlewares?

Please for any help, suggestions about this.

Body:
Alright,

So putting this post help me to to find a solution. I rewrite my middleware entry point, to looking like this

const searchRequestParser = require('./search-request-parser');
const search = require('../../../lib/search');

module.exports = (req, res, next) => {

  const searchRequest = searchRequestParser(req);
  if (searchRequest) {
    const searchCriteria = search(searchRequest.resourceToSearch);
    req.searchQuery =
  searchCriteria.buildQuery(searchRequest.queryParameters);
  }
  next();
};

And test

    it('Should call search by querystring if querystring is present', () => {
    const req = httpMocks.createRequest({
            method: 'GET',
            params: {
                resourceToSearch: 'debts'
            },
            query: {
                value: 1000
            }
        }),
        res = httpMocks.createResponse(),
        next = sandbox.spy();
    searchIndex(req, res, next);

    expect(req).to.have.a.property('searchQuery');
});

So methods searchByMarker or searchByQuerystring are gone and replaced by method searchRequestParser with output, then I process this output in code which as it turned out was duplicated previously in methods searchByMarker or searchByQuerystring.

Thanks to return outputs from functions I used, I didn't have to focus on mocking/stubing those functions.


问:
Scala - XML PrettyPrinter.format() giving noSuchMethodError
I have this piece of code that should convert an XML.Elem object into a readable and properly indented text, but when I run it it keeps giving me an error, and I cannot understand why since as far as I know and searched I'm using the PrettyPrinter class as it is supposed to.

```<code>val xml = createXML(production_list: ProductionList)

// Using the PrettyPrinter class to make sure the XML is “human readable.”
val prettyPrinter = new scala.xml.PrettyPrinter(80, 2)
val prettyXml = prettyPrinter.format(xml)

XML.save(filename, scala.xml.XML.loadString(prettyXml), "UTF-8", true, null)
</code>```

Here is the header of the createXML method:

```<code>def createXML(production_list: ProductionList): xml.Elem = {(...)}
</code>```

And here is the error:

```<code>java.lang.NoSuchMethodError: scala.collection.immutable.$colon$colon.hd$1()Ljava/lang/Object;
  at scala.xml.NamespaceBinding.fromPrefixList$1(NamespaceBinding.scala:48)
  at scala.xml.NamespaceBinding.shadowRedefined(NamespaceBinding.scala:53)
  at scala.xml.NamespaceBinding.buildString(NamespaceBinding.scala:71)
  at scala.xml.Utility$.serialize(Utility.scala:218)
  at scala.xml.PrettyPrinter.traverse(PrettyPrinter.scala:151)
  at scala.xml.PrettyPrinter.format(PrettyPrinter.scala:209)
  at scala.xml.PrettyPrinter$$anonfun$format$2.apply(PrettyPrinter.scala:244)
  at scala.xml.PrettyPrinter$$anonfun$format$2.apply(PrettyPrinter.scala:244)
  at scala.xml.Utility$.sbToString(Utility.scala:33)
  at scala.xml.PrettyPrinter.format(PrettyPrinter.scala:244)
  ...
</code>```

Snippet of my created XML:

```<code><?xml version='1.0' encoding='UTF-8'?>
<Schedule xsi:schemaLocation="http://www.dei.isep.ipp.pt/ip_2017 ip_2017_out.xsd " xmlns="http://www.dei.isep.ipp.pt/ip_2017" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <TaskSchedule order="ORD_1" productNumber="1" task="TSK_1" start="0" end="100">
                <PhysicalResources>
              <Physical id="PRS_1"/><Physical id="PRS_3"/><Physical id="PRS_4"/>
                </PhysicalResources>
                <HumanResources>
              <Human name="Antonio"/><Human name="Susana"/><Human name="Maria"/>
                </HumanResources>
            </TaskSchedule><TaskSchedule order="ORD_1" productNumber="1" task="TSK_3" start="100" end="260">
                <PhysicalResources>
              <Physical id="PRS_1"/><Physical id="PRS_4"/><Physical id="PRS_7"/>
                </PhysicalResources>
                <HumanResources>
              <Human name="Antonio"/><Human name="Maria"/><Human name="Manuel"/>
                </HumanResources>
            </TaskSchedule>
    </Schedule>
</code>```

答:
This can be fixed by changing some of the parameters of the XML.save. Take it:

```<code>XML.save(xmlPath, XML.loadString(printer.format(prettyXml, scala.xml.TopScope)) , "UTF-8", true, null)
</code>```

Peace. RIP ISEP.

Body:
I have this piece of code that should convert an XML.Elem object into a readable and properly indented text, but when I run it it keeps giving me an error, and I cannot understand why since as far as I know and searched I'm using the PrettyPrinter class as it is supposed to.

val xml = createXML(production_list: ProductionList)

// Using the PrettyPrinter class to make sure the XML is “human readable.”
val prettyPrinter = new scala.xml.PrettyPrinter(80, 2)
val prettyXml = prettyPrinter.format(xml)

XML.save(filename, scala.xml.XML.loadString(prettyXml), "UTF-8", true, null)

Here is the header of the createXML method:

def createXML(production_list: ProductionList): xml.Elem = {(...)}

And here is the error:

java.lang.NoSuchMethodError: scala.collection.immutable.$colon$colon.hd$1()Ljava/lang/Object;
  at scala.xml.NamespaceBinding.fromPrefixList$1(NamespaceBinding.scala:48)
  at scala.xml.NamespaceBinding.shadowRedefined(NamespaceBinding.scala:53)
  at scala.xml.NamespaceBinding.buildString(NamespaceBinding.scala:71)
  at scala.xml.Utility$.serialize(Utility.scala:218)
  at scala.xml.PrettyPrinter.traverse(PrettyPrinter.scala:151)
  at scala.xml.PrettyPrinter.format(PrettyPrinter.scala:209)
  at scala.xml.PrettyPrinter$$anonfun$format$2.apply(PrettyPrinter.scala:244)
  at scala.xml.PrettyPrinter$$anonfun$format$2.apply(PrettyPrinter.scala:244)
  at scala.xml.Utility$.sbToString(Utility.scala:33)
  at scala.xml.PrettyPrinter.format(PrettyPrinter.scala:244)
  ...

Snippet of my created XML:

<?xml version='1.0' encoding='UTF-8'?>
<Schedule xsi:schemaLocation="http://www.dei.isep.ipp.pt/ip_2017 ip_2017_out.xsd " xmlns="http://www.dei.isep.ipp.pt/ip_2017" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <TaskSchedule order="ORD_1" productNumber="1" task="TSK_1" start="0" end="100">
                <PhysicalResources>
              <Physical id="PRS_1"/><Physical id="PRS_3"/><Physical id="PRS_4"/>
                </PhysicalResources>
                <HumanResources>
              <Human name="Antonio"/><Human name="Susana"/><Human name="Maria"/>
                </HumanResources>
            </TaskSchedule><TaskSchedule order="ORD_1" productNumber="1" task="TSK_3" start="100" end="260">
                <PhysicalResources>
              <Physical id="PRS_1"/><Physical id="PRS_4"/><Physical id="PRS_7"/>
                </PhysicalResources>
                <HumanResources>
              <Human name="Antonio"/><Human name="Maria"/><Human name="Manuel"/>
                </HumanResources>
            </TaskSchedule>
    </Schedule>

Body:
This can be fixed by changing some of the parameters of the XML.save. Take it:

XML.save(xmlPath, XML.loadString(printer.format(prettyXml, scala.xml.TopScope)) , "UTF-8", true, null)

Peace. RIP ISEP.


问:
We receive signed PDF documents with ulterior modifications
Maybe this one would fit better on so security? I'm not sure...

These are the facts:

We have a web app where users download a PDF document with a form, they fullfill this form, sign it with their electronic certificate and upload it back to our environment.

We've shown cases where the uploaded document is signed, but it show some  fields that have been altered after the signature. If we check the integrity of PDF signatures, it shows that have been data alteration after the signature, but the signature it's fine and valid.

If we right-click on the signature and select "See signed version" we see the real data loaded on the moment of the signature.

Now, this goes against my general perception of electronic signature functionality. If any change is made to the document (or the data loaded into it) after I make a signature, this signature should become invalid, as the document has been altered.

The behaviour of the PDF seems to be different, as not only the signature still is valid, also the "default version" that you see when you open the document is the last one, not the signed one.

Now I'm wondering

Is this some kind of bug or is a expected behaviour?

There is any place where info on the matter can be found? (google keeps redirecting me once and again to "how to sign a PDF" articles).

If this is a defined behaviour, how do you deal with it?

答:
Now, this goes against my general perception of electronic signature functionality. If any change is made to the document (or the data loaded into it) after I make a signature, this signature should become invalid, as the document has been altered.

The behaviour of the PDF seems to be different, as not only the signature still is valid, also the "default version" that you see when you open the document is the last one, not the signed one.

Is this some kind of bug or is a expected behaviour?

It is expected behavior.
You have to be aware of two special factors here:

A PDF signature field contains the information of the byte ranges signed. Obviously not the whole file can be signed as the signature itself is embedded and cannot be part of the signed bytes. Thus, the signed bytes ranges need to be recorded somewhere. Cf. this answer on Information Security Stack Exchange:

Additions to a PDF can be made by appending to the existing document, a process called an incremental update. These updates can again be signed etc., also cf. the answer referenced above:

Thus, making changes to a PDF by means of an incremental update, the existing integrated signatures in the document still correctly sign their respective signed by range. They still are mathematically valid in spite of the added changes.

Furthermore the current contents of a PDF are defined in particular by the newest incremental update, so when you open the document it shows the content including the last changes, not the signed one.

Now, while this sounds like PDF signatures have no meaning, this is not the case. The specification ISO 32000-1 clearly defines which changes are allowed to be made in an incremental update to a certified (= signed with some special flags) base version of a document, and Adobe in their Acrobat and Reader software have extrapolated restrictions from this for signed but not certified documents, cf. this answer on stack overflow.

In particular at most the following changes are allowed:

Adding signature fields

Adding or editing annotations

Supplying form field values

Digitally signing

If this is a defined behaviour, how do you deal with it?

As the documents originate from you, you can start by applying a certificate signature to the document which only allows as little changes as possible in your use case.

Then you can define signature lock information for the signature fields your users are to sign. In these lock information you can e.g. prescribe that after signing the given signature field, a number of form fields shall be read-only.

Finally you only accept back PDFs which still contain your certification signature and to which no disallowed changes were added.

There actually are numerous PDFs which are certified and contain a number of fields for additional approval signatures, and each of the approval signature fields is coupled with some form fields which will not be editable anymore after signing. After all the signature fields are signed, all fields are read-only.

There is any place where info on the matter can be found? (google keeps redirecting me once and again to "how to sign a PDF" articles).

You should in particular look at the PDF specification ISO 32000-1 and some Adobe documents on the behavior of their software. You'll find links at the bottom of the stack overflow documentation page the above mentioned links point to.


问:
Pandas: to_excel() float_format
I'm trying to get the float_format parameter working with pandas' to_excel() function, but it doesn't seem to do anything.

Code:

```<code>df = pd.DataFrame({
        'date':['1/15/2016','2/1/2016','2/15/2016','3/15/2016'],
        'numA':[1000,2000,3000,4000.3],
        'numB':[10000,20000.2,30000,40000]
    })

writer = pd.ExcelWriter('c:/.../pandas_excel_test.xlsx', engine = 'xlsxwriter')

print df.dtypes

df.to_excel(writer,
        index = False,
        float_format = '%.2f',
    )
</code>```

But the Excel file looks like this:

I confirmed dtypes as:

```<code>date     object
numA    float64
numB    float64
dtype: object
</code>```

Does anyone know how to properly format floats in to_excel()?

答:
I believe Excel formatting changes how floats are displayed. I tried to_csv method and float_format worked. For excel, telling excel how to display the column helps:

```<code>df = pd.DataFrame({
        'date':['1/15/2016','2/1/2016','2/15/2016','3/15/2016'],
        'numA':[1000,2000,3000,4000.3],
        'numB':[10000,20000.2,30000,40000]
    })

writer = pd.ExcelWriter('c:/.../pandas_excel_test.xlsx', engine = 'xlsxwriter')
df.to_excel(writer, index=False, sheet_name='Sheet1')
workbook  = writer.book
worksheet = writer.sheets['Sheet1']
format1 = workbook.add_format({'num_format': '0.00'})
worksheet.set_column('C:C', None, format1)  # Adds formatting to column C
writer.save()
</code>```

Result:

More info: http://xlsxwriter.readthedocs.io/example_pandas_column_formats.html

Title: Pandas: to_excel() float_format

Body:
I'm trying to get the float_format parameter working with pandas' to_excel() function, but it doesn't seem to do anything.

Code:

df = pd.DataFrame({
        'date':['1/15/2016','2/1/2016','2/15/2016','3/15/2016'],
        'numA':[1000,2000,3000,4000.3],
        'numB':[10000,20000.2,30000,40000]
    })

writer = pd.ExcelWriter('c:/.../pandas_excel_test.xlsx', engine = 'xlsxwriter')

print df.dtypes

df.to_excel(writer,
        index = False,
        float_format = '%.2f',
    )

But the Excel file looks like this:

I confirmed dtypes as:

date     object
numA    float64
numB    float64
dtype: object

Does anyone know how to properly format floats in to_excel()?

Body:
I believe Excel formatting changes how floats are displayed. I tried to_csv method and float_format worked. For excel, telling excel how to display the column helps:

df = pd.DataFrame({
        'date':['1/15/2016','2/1/2016','2/15/2016','3/15/2016'],
        'numA':[1000,2000,3000,4000.3],
        'numB':[10000,20000.2,30000,40000]
    })

writer = pd.ExcelWriter('c:/.../pandas_excel_test.xlsx', engine = 'xlsxwriter')
df.to_excel(writer, index=False, sheet_name='Sheet1')
workbook  = writer.book
worksheet = writer.sheets['Sheet1']
format1 = workbook.add_format({'num_format': '0.00'})
worksheet.set_column('C:C', None, format1)  # Adds formatting to column C
writer.save()

Result:

More info: http://xlsxwriter.readthedocs.io/example_pandas_column_formats.html


问:
Creating variable arity method
Trying to write a variable arity method serializeMethod() that takes any number of instances of Member as parameters and write them to a file in the order they are passed into the method. The file is hidden and is instead made available to you via an OutputStream object referenced by the ostream instance variable in the class in which your method will be placed. Having problems not sure why it doesn't accept member </p>

```<code>public void serializeMethod(Member... member) {
    ObjectOutputStream output = null;
    try {
        output = new ObjectOutputStream(ostream);
        output.writeObject(member);
        output.close();
    }catch(IOException e) {
        System.out.print("IOException :" + e);
    }

}

Test case:
Member m1 = new Member("SI2993", 'c', 2);
Member m2 = new Member("GE8103", 's', 1);
Member m3 = new Member("PD9320", 's', 1);
Member m4 = new Member("NE9025", 'c', 4);
Member m5 = new Member("QW3234", 's', 1);
serializeMethod(m1, m2, m3, m4, m5);
deSerializeMethod();

Expected result :

Member ID: SI2993
Member role: c
Length of membership: 2
Member ID: GE8103
Member role: s
Length of membership: 1
Member ID: PD9320
Member role: s
Length of membership: 1
Member ID: NE9025
Member role: c
Length of membership: 4
Member ID: QW3234
Member role: s
Length of membership: 1

My output:
Exception in thread "main" java.lang.ClassCastException: [LMember; cannot be cast to Member
\x09at SerializeMethodVariableArity.deSerializeMethod(SerializeMethodVariableArity.java:144)
\x09at SerializeMethodVariableArity.runTests(SerializeMethodVariableArity.java:188)
\x09at SerializeMethodVariableArity.main(SerializeMethodVariableArity.java:178)
</code>```

答:
Let's look at the error message:

[LMember; cannot be cast to Member

[LMember; is the encoded name of an array type (as described here), Member[]. So it's telling you that you're casting a Member[] to Member.

Presumably in your deSerializeMethod you have some code like this:

```<code>Member m = (Member) input.readObject();
</code>```

But in your serializeMethod, you're writing an array:

```<code>public void serializeMethod(Member... member) {
    ObjectOutputStream output = null;
    try {
        output = new ObjectOutputStream(ostream);
        output.writeObject(member);
        //                 ^^^^^^
        // member is an array, because varargs are
        // syntactic sugar for passing an array
        output.close();
    }catch(IOException e) {
        System.out.print("IOException :" + e);
    }
}
</code>```

Presumably you either need to loop over the varargs and write each one individually:

```<code>for (Member m : members) {
    output.writeObject(m);
}
</code>```

Or you need to read the object in as an array:

```<code>Member[] members = (Member[]) input.readObject();
</code>```

Title: Creating variable arity method

Body:
Trying to write a variable arity method serializeMethod() that takes any number of instances of Member as parameters and write them to a file in the order they are passed into the method. The file is hidden and is instead made available to you via an OutputStream object referenced by the ostream instance variable in the class in which your method will be placed. Having problems not sure why it doesn't accept member

public void serializeMethod(Member... member) {
    ObjectOutputStream output = null;
    try {
        output = new ObjectOutputStream(ostream);
        output.writeObject(member);
        output.close();
    }catch(IOException e) {
        System.out.print("IOException :" + e);
    }

}

Test case:
Member m1 = new Member("SI2993", 'c', 2);
Member m2 = new Member("GE8103", 's', 1);
Member m3 = new Member("PD9320", 's', 1);
Member m4 = new Member("NE9025", 'c', 4);
Member m5 = new Member("QW3234", 's', 1);
serializeMethod(m1, m2, m3, m4, m5);
deSerializeMethod();

Expected result :

Member ID: SI2993
Member role: c
Length of membership: 2
Member ID: GE8103
Member role: s
Length of membership: 1
Member ID: PD9320
Member role: s
Length of membership: 1
Member ID: NE9025
Member role: c
Length of membership: 4
Member ID: QW3234
Member role: s
Length of membership: 1

My output:
Exception in thread "main" java.lang.ClassCastException: [LMember; cannot be cast to Member
\x09at SerializeMethodVariableArity.deSerializeMethod(SerializeMethodVariableArity.java:144)
\x09at SerializeMethodVariableArity.runTests(SerializeMethodVariableArity.java:188)
\x09at SerializeMethodVariableArity.main(SerializeMethodVariableArity.java:178)

Body:
Let's look at the error message:

[LMember; cannot be cast to Member

[LMember; is the encoded name of an array type (as described here), Member[]. So it's telling you that you're casting a Member[] to Member.

Presumably in your deSerializeMethod you have some code like this:

Member m = (Member) input.readObject();

But in your serializeMethod, you're writing an array:

public void serializeMethod(Member... member) {
    ObjectOutputStream output = null;
    try {
        output = new ObjectOutputStream(ostream);
        output.writeObject(member);
        //                 ^^^^^^
        // member is an array, because varargs are
        // syntactic sugar for passing an array
        output.close();
    }catch(IOException e) {
        System.out.print("IOException :" + e);
    }
}

Presumably you either need to loop over the varargs and write each one individually:

for (Member m : members) {
    output.writeObject(m);
}

Or you need to read the object in as an array:

Member[] members = (Member[]) input.readObject();


问:
Multiple forms for entity instances - symfony3
I'm trying to create a form that would allow a manager to approve a list of time off requests (also planning to have a todo list and want to be able to mark them as done).

I have read [Generate same form type on same page multiple times Symfony2 (as well as several others) and I am close to understanding but I'm fairly to new to Symfony and not clear on what parts of the code should go in what files. I am using a form type and a controller in Symfony3 with Doctrine.

I have list of the entity instances that were returned from a query ($em->createQuery) in the controller and I am looking to produce a form for each entity instance or even two forms per entity (one for approve and one for reject).

The referenced question says you need a loop to display and save them. My intention is to only work on (submit) one at a time. I assume this part of the code would go in the controller?

I am using an indexAction for the controller but using it more like an Edit action since I will be processing forms, so I pass in a Request object and the objects as parameters.

>

```<code>class HRMgrController extends Controller
{
    /**
     * Lists all manager role requests and provide a means to approve/deny.
     *
     * @Route("/", name="hrmgr_index")
     * @Method({"GET", "POST"})
     * @Security("has_role('ROLE_APP_MANAGER')")
     */
public function indexAction(Request $request, TimeOffRequest $timeOffRequest)
{
    if (!empty($timeOffRequest)) {
            $form = $this->createForm('CockpitBundle\Form\TORApprovalType', $timeOffRequest);
        print "TOR Id = " . $timeOffRequest->getId() . "<BR>";
        $em = $this->getDoctrine()->getManager();
        $form->handleRequest($request);
        print "Form name = " . $form->getName() . "<BR>";
        if ($form->isSubmitted() && $form->isValid()) {
            if ($form->get('approve')->isClicked()) {
                print "This puppy was approved";
                $timeOffRequest['status'] = 4;
            }
            if ($form->get('reject')->isClicked()) {
                print "This puppy was rejected";
                $timeOffRequest['status'] = 1;
            }
            $this->getDoctrine()->getManager()->flush();
            print "At least its there<BR>";
            // return $this->redirectToRoute('hrmgr_index');
        } else {
            print "did not detect form submission<BR>";
        }
    }

    $emp = new \CockpitBundle\Entity\Employee();

    $date = new \DateTime();
    $year = $date->format('Y');
    $username = $this->getUser()->getUserName();
    $user = $em->getRepository('CockpitBundle:Employee')->findByUsername($username);
    $employees = $em->getRepository('CockpitBundle:Employee')->htmlContact($user);
    $tors = $em->getRepository('CockpitBundle:TimeOffRequest')->findMgrUnapprovedTORs($user->getId());
    $timeoff = "<h3>Unapproved Time Off Requests</h3>";
    $actions = true;

    $torforms = [];
    foreach ($tors as $tor) {
        $target = $this->generateUrl('hrmgr_index',array("tor_id" => $tor->getId()));
        $torforms[] = $this->actionForm($tor,$target)->createView();
    }
    return $this->render('hrmgr/index.html.twig', array(
        'torforms' => $torforms,
    ));
</code>```

I have the forms working nowbut when I submit them the isSubmitted() doesn't seem to be working. It outputs the "did not detect form submission" currently.

So when I have multiple forms and I submit one, does the handleRequest get the right one? I think I might be confusing two concepts here as well. I recently changed the code to submit the ID of the timeOffRequest as a parameter to the route. It is properly picking that up which allows me to potentially update the form but that part of the code doesn't seem to be working.

I noticed that if I look at the debugger, I get something like:

```<code>>   approval_form_2
   [▼
     "reject" => ""
     "_token" => "IE1rGa5c0vaJYk74_ncxgFsoDU7wWlkAAWWjLe3Jr1w"
   ]
</code>```

if I click the reject button. I get a similar form with "approve" if I click the approve button so it seems like I am close. Also, the proper ID shows up from the route given in the action.

Here is the form generator:

```<code><?php

namespace CockpitBundle\Form;

use CockpitBundle\Entity\Employee;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class TORApprovalType extends AbstractType
{

    private $nameSuffix = null;
    private $name = 'time_req_approval';
    public function __constructor(string $suffix = null)   {
        //parent::__construct();

        $this->nameSuffix = $this->generateNameSuffix();
    }

    private function generateNameSuffix() {
        if ($this->nameSuffix == null ||  $this->nameSuffix == '') {
            $generator = new SecureRandom();
            //change data to alphanumeric string
            return bin2hex($generator->nextBytes(10));
        }

        return $this->nameSuffix;
    }
    public function setNameSuffix($suffix){
        $this->nameSuffix = $suffix;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Build your form...
        $builder->add('approve', SubmitType::class, array(
            'label' => "Approve",
            'attr' => array("class"=>"action-approve"),
        ));
        $builder->add('reject', SubmitType::class, array(
            'label' => "Reject",
            'attr' => array("class"=>"action-reject"),
        ));
        //$builder->add('employee');

    }
    public function getName()    {
        if ($this->nameSuffix == null || $this->nameSuffix == "" ) {
            $this->nameSuffix = $this->generateNameSuffix();
        }
        return $this->name .'_'. $this->nameSuffix;
    }
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'CockpitBundle\Entity\TimeOffRequest'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'cockpitbundle_timeoffrequest';
    }

}
</code>```

Any clues? (sorry I am on vacation so not particular quick with updates.

答:
I was able to get it working with the following builder.

```<code>   $builder->add('approve', SubmitType::class, array(
        'label' => "Approve",
        'attr' => array("class"=>"action-approve"),
    ));
    $builder->add('reject', SubmitType::class, array(
        'label' => "Reject",
        'attr' => array("class"=>"action-reject"),
    ));
</code>```

Then in the controller form I generate and process the forms as such. Not sure if it is the optimal way but it works find. Of course, this approach redraws the whole list each time, but that is fine for what I'm doing.

```<code>class HRMgrController extends Controller
{
    /**
     * Lists all manager role requests and provide a means to approve/deny.
     *
     * @Route("/", name="manager_home")
     * @Method({"GET"})
     * @Security("has_role('ROLE_APP_MANAGER')")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
        $emp = new \CockpitBundle\Entity\Employee();
        $employeeSummary = [];
        $date = new \DateTime();
        $year = $date->format('Y');
        $username = $this->getUser()->getUserName();
        $user = $em->getRepository('CockpitBundle:Employee')->findByUsername($username);
        $myemployees = $em->getRepository('CockpitBundle:Employee')->findManagersEmployees($user);
        $torRep = $em->getRepository('CockpitBundle:TimeOffRequest');
        $toas = [];
        $torforms = [];
        foreach ($myemployees as $employee) {
            $tors = $torRep->findAllMine($employee,$year);
            $toas[$employee->getDisplayName()] = $em->getRepository('CockpitBundle:TimeOffAllocation')->getEmpAllocation($employee->getId(),$year);
            $employeeSummary[$employee->getDisplayName()] = $torRep->mySummary($tors,$toas[$employee->getDisplayName()]);
            if (array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Vacation']['Requested'])) {
                foreach ($employeeSummary[$employee->getDisplayName()]['Vacation']['Requested']['items'] as $tor) {
                    $target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
                    $torforms[] = $this->actionForm($tor,$target)->createView();
                }
            }
            if (array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Sick Time']['Requested'])) {
                foreach ($employeeSummary[$employee->getDisplayName()]['Sick Time']['Requested']['items'] as $tor) {
                    $target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
                    $torforms[] = $this->actionForm($tor,$target)->createView();
                }
            }
            if (array_key_exists('Time Off',$employeeSummary[$employee->getDisplayName()]) &&
                    array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Time Off']['Requested'])) {
                foreach ($employeeSummary[$employee->getDisplayName()]['Time Off']['Requested']['items'] as $tor) {
                    $target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
                    $torforms[] = $this->actionForm($tor,$target)->createView();
                }
            }
        }

        return $this->render('hrmgr/index.html.twig', array(
            'employeeSummary' => $employeeSummary,
            'torforms' => $torforms,
            'year' => $year,
        ));
    }
    /**
     * Lists all manager role requests and provide a means to approve/deny.
     *
     * @Route("/{tor_id}", name="hrmgr_tor_approval")
     * @Method({ "POST" })
     * @ParamConverter("timeOffRequest", class="CockpitBundle:TimeOffRequest", options={"id"="tor_id"})
     * @Security("has_role('ROLE_APP_MANAGER')")
     */
    public function approvalAction(Request $request, TimeOffRequest $timeOffRequest)
    {
        if (!empty($timeOffRequest)) {
            $form = $this->createForm('CockpitBundle\Form\TORApprovalType', $timeOffRequest);
            $id = $timeOffRequest->getId();
            $em = $this->getDoctrine()->getManager();
            $form->handleRequest($request);
            $postparams = $request->request->all();

            if (array_key_exists("approval_form_$id",$postparams)) {
                // Form was submitted
                if (array_key_exists("approve",$postparams["approval_form_$id"])) {
                    $status = $em->getReference('CockpitBundle\Entity\TimeOffStatus', 4);
                    $timeOffRequest->setStatus($status);
                    $timeOffRequest->setApprovedDate(new \DateTime);
                    $em->persist($timeOffRequest);
                    $em->flush($timeOffRequest);
                }
                if (array_key_exists("reject",$postparams["approval_form_$id"])) {
                    $status = $em->getReference('CockpitBundle\Entity\TimeOffStatus', 1);
                    $timeOffRequest->setStatus($status);
                    $timeOffRequest->setApprovedDate(new \DateTime);
                    $em->persist($timeOffRequest);
                    $em->flush($timeOffRequest);
                }
            } else {
                print "Form did not exist<BR>";
            }
            return $this->redirectToRoute('manager_home');
        }
    }
    public function actionForm($tor,$target) {
        return $this->get('form.factory')->createNamedBuilder('approval_form_'.$tor->getId(), \CockpitBundle\Form\TORApprovalType::class, $tor,
             array("action"=> $target))->getForm();
    }
}
</code>```

Body:
I'm trying to create a form that would allow a manager to approve a list of time off requests (also planning to have a todo list and want to be able to mark them as done).

I have read [Generate same form type on same page multiple times Symfony2 (as well as several others) and I am close to understanding but I'm fairly to new to Symfony and not clear on what parts of the code should go in what files. I am using a form type and a controller in Symfony3 with Doctrine.

I have list of the entity instances that were returned from a query ($em->createQuery) in the controller and I am looking to produce a form for each entity instance or even two forms per entity (one for approve and one for reject).

The referenced question says you need a loop to display and save them. My intention is to only work on (submit) one at a time. I assume this part of the code would go in the controller?

I am using an indexAction for the controller but using it more like an Edit action since I will be processing forms, so I pass in a Request object and the objects as parameters.

>

class HRMgrController extends Controller
{
    /**
     * Lists all manager role requests and provide a means to approve/deny.
     *
     * @Route("/", name="hrmgr_index")
     * @Method({"GET", "POST"})
     * @Security("has_role('ROLE_APP_MANAGER')")
     */
public function indexAction(Request $request, TimeOffRequest $timeOffRequest)
{
    if (!empty($timeOffRequest)) {
            $form = $this->createForm('CockpitBundle\Form\TORApprovalType', $timeOffRequest);
        print "TOR Id = " . $timeOffRequest->getId() . "
";
        $em = $this->getDoctrine()->getManager();
        $form->handleRequest($request);
        print "Form name = " . $form->getName() . "
";
        if ($form->isSubmitted() && $form->isValid()) {
            if ($form->get('approve')->isClicked()) {
                print "This puppy was approved";
                $timeOffRequest['status'] = 4;
            }
            if ($form->get('reject')->isClicked()) {
                print "This puppy was rejected";
                $timeOffRequest['status'] = 1;
            }
            $this->getDoctrine()->getManager()->flush();
            print "At least its there
";
            // return $this->redirectToRoute('hrmgr_index');
        } else {
            print "did not detect form submission
";
        }
    }

    $emp = new \CockpitBundle\Entity\Employee();

    $date = new \DateTime();
    $year = $date->format('Y');
    $username = $this->getUser()->getUserName();
    $user = $em->getRepository('CockpitBundle:Employee')->findByUsername($username);
    $employees = $em->getRepository('CockpitBundle:Employee')->htmlContact($user);
    $tors = $em->getRepository('CockpitBundle:TimeOffRequest')->findMgrUnapprovedTORs($user->getId());
    $timeoff = "
Unapproved Time Off Requests
";
    $actions = true;

    $torforms = [];
    foreach ($tors as $tor) {
        $target = $this->generateUrl('hrmgr_index',array("tor_id" => $tor->getId()));
        $torforms[] = $this->actionForm($tor,$target)->createView();
    }
    return $this->render('hrmgr/index.html.twig', array(
        'torforms' => $torforms,
    ));

I have the forms working nowbut when I submit them the isSubmitted() doesn't seem to be working. It outputs the "did not detect form submission" currently.

So when I have multiple forms and I submit one, does the handleRequest get the right one? I think I might be confusing two concepts here as well. I recently changed the code to submit the ID of the timeOffRequest as a parameter to the route. It is properly picking that up which allows me to potentially update the form but that part of the code doesn't seem to be working.

I noticed that if I look at the debugger, I get something like:

>   approval_form_2
   [▼
     "reject" => ""
     "_token" => "IE1rGa5c0vaJYk74_ncxgFsoDU7wWlkAAWWjLe3Jr1w"
   ]

if I click the reject button. I get a similar form with "approve" if I click the approve button so it seems like I am close. Also, the proper ID shows up from the route given in the action.

Here is the form generator:

<?php

namespace CockpitBundle\Form;

use CockpitBundle\Entity\Employee;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Form\Extension\Core\Type\ButtonType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;

class TORApprovalType extends AbstractType
{

    private $nameSuffix = null;
    private $name = 'time_req_approval';
    public function __constructor(string $suffix = null)   {
        //parent::__construct();

        $this->nameSuffix = $this->generateNameSuffix();
    }

    private function generateNameSuffix() {
        if ($this->nameSuffix == null ||  $this->nameSuffix == '') {
            $generator = new SecureRandom();
            //change data to alphanumeric string
            return bin2hex($generator->nextBytes(10));
        }

        return $this->nameSuffix;
    }
    public function setNameSuffix($suffix){
        $this->nameSuffix = $suffix;
    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // Build your form...
        $builder->add('approve', SubmitType::class, array(
            'label' => "Approve",
            'attr' => array("class"=>"action-approve"),
        ));
        $builder->add('reject', SubmitType::class, array(
            'label' => "Reject",
            'attr' => array("class"=>"action-reject"),
        ));
        //$builder->add('employee');

    }
    public function getName()    {
        if ($this->nameSuffix == null || $this->nameSuffix == "" ) {
            $this->nameSuffix = $this->generateNameSuffix();
        }
        return $this->name .'_'. $this->nameSuffix;
    }
    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'CockpitBundle\Entity\TimeOffRequest'
        ));
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'cockpitbundle_timeoffrequest';
    }

}

Any clues? (sorry I am on vacation so not particular quick with updates.

Body:
I was able to get it working with the following builder.

   $builder->add('approve', SubmitType::class, array(
        'label' => "Approve",
        'attr' => array("class"=>"action-approve"),
    ));
    $builder->add('reject', SubmitType::class, array(
        'label' => "Reject",
        'attr' => array("class"=>"action-reject"),
    ));

Then in the controller form I generate and process the forms as such. Not sure if it is the optimal way but it works find. Of course, this approach redraws the whole list each time, but that is fine for what I'm doing.

class HRMgrController extends Controller
{
    /**
     * Lists all manager role requests and provide a means to approve/deny.
     *
     * @Route("/", name="manager_home")
     * @Method({"GET"})
     * @Security("has_role('ROLE_APP_MANAGER')")
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
        $emp = new \CockpitBundle\Entity\Employee();
        $employeeSummary = [];
        $date = new \DateTime();
        $year = $date->format('Y');
        $username = $this->getUser()->getUserName();
        $user = $em->getRepository('CockpitBundle:Employee')->findByUsername($username);
        $myemployees = $em->getRepository('CockpitBundle:Employee')->findManagersEmployees($user);
        $torRep = $em->getRepository('CockpitBundle:TimeOffRequest');
        $toas = [];
        $torforms = [];
        foreach ($myemployees as $employee) {
            $tors = $torRep->findAllMine($employee,$year);
            $toas[$employee->getDisplayName()] = $em->getRepository('CockpitBundle:TimeOffAllocation')->getEmpAllocation($employee->getId(),$year);
            $employeeSummary[$employee->getDisplayName()] = $torRep->mySummary($tors,$toas[$employee->getDisplayName()]);
            if (array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Vacation']['Requested'])) {
                foreach ($employeeSummary[$employee->getDisplayName()]['Vacation']['Requested']['items'] as $tor) {
                    $target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
                    $torforms[] = $this->actionForm($tor,$target)->createView();
                }
            }
            if (array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Sick Time']['Requested'])) {
                foreach ($employeeSummary[$employee->getDisplayName()]['Sick Time']['Requested']['items'] as $tor) {
                    $target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
                    $torforms[] = $this->actionForm($tor,$target)->createView();
                }
            }
            if (array_key_exists('Time Off',$employeeSummary[$employee->getDisplayName()]) &&
                    array_key_exists('items',$employeeSummary[$employee->getDisplayName()]['Time Off']['Requested'])) {
                foreach ($employeeSummary[$employee->getDisplayName()]['Time Off']['Requested']['items'] as $tor) {
                    $target = $this->generateUrl('hrmgr_tor_approval',array("tor_id" => $tor->getId()));
                    $torforms[] = $this->actionForm($tor,$target)->createView();
                }
            }
        }

        return $this->render('hrmgr/index.html.twig', array(
            'employeeSummary' => $employeeSummary,
            'torforms' => $torforms,
            'year' => $year,
        ));
    }
    /**
     * Lists all manager role requests and provide a means to approve/deny.
     *
     * @Route("/{tor_id}", name="hrmgr_tor_approval")
     * @Method({ "POST" })
     * @ParamConverter("timeOffRequest", class="CockpitBundle:TimeOffRequest", options={"id"="tor_id"})
     * @Security("has_role('ROLE_APP_MANAGER')")
     */
    public function approvalAction(Request $request, TimeOffRequest $timeOffRequest)
    {
        if (!empty($timeOffRequest)) {
            $form = $this->createForm('CockpitBundle\Form\TORApprovalType', $timeOffRequest);
            $id = $timeOffRequest->getId();
            $em = $this->getDoctrine()->getManager();
            $form->handleRequest($request);
            $postparams = $request->request->all();

            if (array_key_exists("approval_form_$id",$postparams)) {
                // Form was submitted
                if (array_key_exists("approve",$postparams["approval_form_$id"])) {
                    $status = $em->getReference('CockpitBundle\Entity\TimeOffStatus', 4);
                    $timeOffRequest->setStatus($status);
                    $timeOffRequest->setApprovedDate(new \DateTime);
                    $em->persist($timeOffRequest);
                    $em->flush($timeOffRequest);
                }
                if (array_key_exists("reject",$postparams["approval_form_$id"])) {
                    $status = $em->getReference('CockpitBundle\Entity\TimeOffStatus', 1);
                    $timeOffRequest->setStatus($status);
                    $timeOffRequest->setApprovedDate(new \DateTime);
                    $em->persist($timeOffRequest);
                    $em->flush($timeOffRequest);
                }
            } else {
                print "Form did not exist<BR>";
            }
            return $this->redirectToRoute('manager_home');
        }
    }
    public function actionForm($tor,$target) {
        return $this->get('form.factory')->createNamedBuilder('approval_form_'.$tor->getId(), \CockpitBundle\Form\TORApprovalType::class, $tor,
             array("action"=> $target))->getForm();
    }
}


问:
Nest mapping the same type twice
I'm in trouble with Nest. I have a brand new index on Elasticsearch 5.1.1 and I'm trying to define a type mapping by dotnet core.

My classes look like that:

```<code>public class Review
{
    public Guid Id { get; set; }
    public User User { get; set; }
    public Movie Movie { get; set; }
    public int Grade { get; set; }
    public string Title { get; set; }
    public string Comment { get; set; }
    public bool HasSpoiler { get; set; }
    public bool BoughtInIngresso { get; set; }
    public ReviewStatus Status { get; set; }
    public DateTime Date { get; set; }
}

public class User
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

public class Movie
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
</code>```

In my application, I'm trying to define a short form of the type mapping (just for test) like that:

var pool = new StaticConnectionPool(nodes);

```<code>    var settings = new ConnectionSettings(pool);
    settings.DefaultIndex(elasticSettings.IndexName);

    var client = new ElasticClient(settings);

    client.Map<Review>(m =>
        m.Index("my_index")
        .Type("reviews")
        .Properties(ps=>
            ps.Keyword(k=>
                    k.Name("title"))
            .Text(t=>
                    t.Name("comment"))
        )
    );
</code>```

And the final result is this. Observe the reviews AND review mapping being created. I only want "reviews", not "review".

```<code>{
  "my_index": {
    "mappings": {
      "reviews": {
        "properties": {
          "comment": {
            "type": "text"
          },
          "title": {
            "type": "keyword"
          }
        }
      },
      "review": {
        "properties": {
          "boughtInSite": {
            "type": "boolean"
          },
          "comment": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "date": {
            "type": "date"
          },
          "grade": {
            "type": "long"
          },
          "hasSpoiler": {
            "type": "boolean"
          },
          "id": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "movie": {
            "properties": {
              "id": {
                "type": "text",
                "fields": {
                  "keyword": {
                    "type": "keyword",
                    "ignore_above": 256
                  }
                }
              },
              "name": {
                "type": "text",
                "fields": {
                  "keyword": {
                    "type": "keyword",
                    "ignore_above": 256
                  }
                }
              }
            }
          },
          "status": {
            "type": "long"
          },
          "title": {
            "type": "keyword"
          },
          "user": {
            "properties": {
              "id": {
                "type": "text",
                "fields": {
                  "keyword": {
                    "type": "keyword",
                    "ignore_above": 256
                  }
                }
              },
              "name": {
                "type": "text",
                "fields": {
                  "keyword": {
                    "type": "keyword",
                    "ignore_above": 256
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</code>```

What I'm doing wrong? This happen if I use AutoMap() too. I don't want to map with attributes because I want to preserve my POCO classes, but if was the only way, I can do.

Some help?

答:
You haven't shown how you are indexing Review types, but I suspect that you're not specifying the type as "reviews" when indexing; in this case, NEST will infer the type from the C# POCO type name.

NEST provides a way for the Elasticsearch type "reviews" to be associated with the C# POCO type Review using InferMappingFor<T>() on ConnectionSettings

```<code>public class Review
{
    public Guid Id { get; set; }
    public User User { get; set; }
    public Movie Movie { get; set; }
    public int Grade { get; set; }
    public string Title { get; set; }
    public string Comment { get; set; }
    public bool HasSpoiler { get; set; }
    public bool BoughtInIngresso { get; set; }
    public ReviewStatus Status { get; set; }
    public DateTime Date { get; set; }
}

public enum ReviewStatus
{
    Good,
    Bad,
    NotTooShabby
}

public class User
{
    public string Id { get; set; }
    public string Name { get; set; }
}

public class Movie
{
    public string Id { get; set; }
    public string Name { get; set; }
}

void Main()
{
    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
    var defaultIndex = "default-index";
    var connectionSettings = new ConnectionSettings(pool)
        .InferMappingFor<Review>(m => m
            .TypeName("reviews")
        )
        .DefaultIndex(defaultIndex);

    var client = new ElasticClient(connectionSettings);

    client.CreateIndex("my_index", c => c
        .Mappings(m => m
            .Map<Review>(mm => mm
                .Properties(ps => ps
                    .Keyword(k => k
                        .Name(n => n.Title)
                    )
                    .Text(t => t
                        .Name(n => n.Comment)
                    )
                )
            )
        )
    );
}
</code>```

With this approach, you don't need to specify the type on every request now, although you can override it per request if you need to.

With AutoMap(), you can let NEST infer the Elasticsearch field types from the C# POCO property types, then use .Properties() to override any mappings you'd like.

Title: Nest mapping the same type twice

Body:
I'm in trouble with Nest. I have a brand new index on Elasticsearch 5.1.1 and I'm trying to define a type mapping by dotnet core.

My classes look like that:

public class Review
{
    public Guid Id { get; set; }
    public User User { get; set; }
    public Movie Movie { get; set; }
    public int Grade { get; set; }
    public string Title { get; set; }
    public string Comment { get; set; }
    public bool HasSpoiler { get; set; }
    public bool BoughtInIngresso { get; set; }
    public ReviewStatus Status { get; set; }
    public DateTime Date { get; set; }
}

public class User
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

public class Movie
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

In my application, I'm trying to define a short form of the type mapping (just for test) like that:

var pool = new StaticConnectionPool(nodes);

    var settings = new ConnectionSettings(pool);
    settings.DefaultIndex(elasticSettings.IndexName);

    var client = new ElasticClient(settings);

    client.Map<Review>(m =>
        m.Index("my_index")
        .Type("reviews")
        .Properties(ps=>
            ps.Keyword(k=>
                    k.Name("title"))
            .Text(t=>
                    t.Name("comment"))
        )
    );

And the final result is this. Observe the reviews AND review mapping being created. I only want "reviews", not "review".

{
  "my_index": {
    "mappings": {
      "reviews": {
        "properties": {
          "comment": {
            "type": "text"
          },
          "title": {
            "type": "keyword"
          }
        }
      },
      "review": {
        "properties": {
          "boughtInSite": {
            "type": "boolean"
          },
          "comment": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "date": {
            "type": "date"
          },
          "grade": {
            "type": "long"
          },
          "hasSpoiler": {
            "type": "boolean"
          },
          "id": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          },
          "movie": {
            "properties": {
              "id": {
                "type": "text",
                "fields": {
                  "keyword": {
                    "type": "keyword",
                    "ignore_above": 256
                  }
                }
              },
              "name": {
                "type": "text",
                "fields": {
                  "keyword": {
                    "type": "keyword",
                    "ignore_above": 256
                  }
                }
              }
            }
          },
          "status": {
            "type": "long"
          },
          "title": {
            "type": "keyword"
          },
          "user": {
            "properties": {
              "id": {
                "type": "text",
                "fields": {
                  "keyword": {
                    "type": "keyword",
                    "ignore_above": 256
                  }
                }
              },
              "name": {
                "type": "text",
                "fields": {
                  "keyword": {
                    "type": "keyword",
                    "ignore_above": 256
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

What I'm doing wrong? This happen if I use AutoMap() too. I don't want to map with attributes because I want to preserve my POCO classes, but if was the only way, I can do.

Some help?

Body:
You haven't shown how you are indexing Review types, but I suspect that you're not specifying the type as "reviews" when indexing; in this case, NEST will infer the type from the C# POCO type name.

NEST provides a way for the Elasticsearch type "reviews" to be associated with the C# POCO type Review using InferMappingFor<T>() on ConnectionSettings

public class Review
{
    public Guid Id { get; set; }
    public User User { get; set; }
    public Movie Movie { get; set; }
    public int Grade { get; set; }
    public string Title { get; set; }
    public string Comment { get; set; }
    public bool HasSpoiler { get; set; }
    public bool BoughtInIngresso { get; set; }
    public ReviewStatus Status { get; set; }
    public DateTime Date { get; set; }
}

public enum ReviewStatus
{
    Good,
    Bad,
    NotTooShabby
}

public class User
{
    public string Id { get; set; }
    public string Name { get; set; }
}

public class Movie
{
    public string Id { get; set; }
    public string Name { get; set; }
}

void Main()
{
    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
    var defaultIndex = "default-index";
    var connectionSettings = new ConnectionSettings(pool)
        .InferMappingFor<Review>(m => m
            .TypeName("reviews")
        )
        .DefaultIndex(defaultIndex);

    var client = new ElasticClient(connectionSettings);

    client.CreateIndex("my_index", c => c
        .Mappings(m => m
            .Map<Review>(mm => mm
                .Properties(ps => ps
                    .Keyword(k => k
                        .Name(n => n.Title)
                    )
                    .Text(t => t
                        .Name(n => n.Comment)
                    )
                )
            )
        )
    );
}

With this approach, you don't need to specify the type on every request now, although you can override it per request if you need to.

With AutoMap(), you can let NEST infer the Elasticsearch field types from the C# POCO property types, then use .Properties() to override any mappings you'd like.