问:
Editing Fields in Event Mode with FullCalendar + Javascript
Good afternoon, I'm creating a simple calendar using the FullCalendar plugin, I'm almost done, but now I need to click on the desired event to show the information of the event and that there is an updated option in the image below you can see how are currently

Example

Now, continue with my codes up to this point, however, please note that I have already defined one updated button and the method that is used, but still  is not reaching at method. What I need is find out how to display the original data of the event and give the user a possibility to change and save this on database.

View:

```<code><head>
<div class="row" >
    <div class="col-sm-2">
        <a data-toggle="modal" data-target="#new_event" class="btn btn-primary">Nova Tarefa</a>
    </div>
</div>

<script>

$(document).ready(function() {

  $.post('<?php echo base_url();?>calendar2/getEvents',
  function(data){
  alert(data);

    $('#calendar').fullCalendar({
      locale: 'pt-br',
      header: {
        left: 'prev,next today',
        center: 'title',
        right: 'month,basicWeek,basicDay'
      },
      defaultDate: new Date(),
      navLinks: true, // can click day/week names to navigate views
      editable: true,
      eventLimit: true, // allow "more" link when too many events
      editable: true,
      events: $.parseJSON(data),

      eventDrop: function(event, delta, revertFunc){
        var id = event.id;
        var fi = event.start.format();
        var ff = event.end.format();

        $.post("<?php echo base_url();?>calendar2/updateEvents",
        {
          id:id,
          inicio:fi,
          fim:ff,
        },
        function(data){
          if(data == 1){
            alert('Evento atualizado');
          }else{
            alert('Evento Nao atualizado')
          }
        });
      },

      eventResize: function(event, delta, revertFunc) {
        var id = event.id;
        var fi = event.start.format();
        var ff = event.end.format();

        $.post("<?php echo base_url();?>calendar2/updateEvents",
        {
          id:id,
          inicio:fi,
          fim:ff,
        },
        function(data){
          if(data == 1){
          //alert('Evento atualizado');
        }else{
         // alert('Evento não atualizado')
        }

        });
      },

      // eventClick: function(event,jsEvent, view){
      //   $('#calendar').fullCalendar('removeEvents',event.id);
      //  }

      eventRender: function(event, element,data){
        var el = element.html();
        element.html("<div style='width:90%;float:left;'>" + el + "</div><div class='closeee' style='color:red; text-align:right;'>X</div>");

        element.find('.closeee').click(function(){
          if(!confirm("Excluir registro ??")){
            revertFunc();
          }else{
                var id = event.id
                $.post("<?php echo base_url();?>calendar2/deleteEvents",
                {
                  id:id,
                },
                function(data){
                  if(data == 1){
                    $('#calendar').fullCalendar('deleteEvents', event.id);
                  //alert('Tarefa Excluida');
                }else{
                 //alert('Tarefa não Excluida')
                }

                });
              }
          });
      },

      eventClick: function(event, jsEvent, view){
        $('#mtitulo').html(event.title);
        $('#autor').html(event.autor);
        $('#inicioEdit').val(event.start);
        $('#importanciaEdit').val(event.impor);
        $('#descricaoEventoEdit').val(event.text);
        $('#modalEvento').modal();
      },

    });
  });
});

</script>

</head>

<body>

    <div id='calendar'></div>

</body>

<!-- Modal visualizar-->

<div class="modal fade" id="modalEvento" tabindex="-1" role="dialog" aria-labelledby="mymodelLabel">
  <div class="modal-dialog" role="document">
  <div class="modal-content">
    <div class="modal-header bg-red">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
      <h4 class="modal-title" id="mymodelLabel"> Editar Evento</h4>
    </div>

    <div class="modal-body">

      <div class="row">
        <div class="form-group col-md-6">
            <label for="nomeEvento">Nome Cliente</label>
          <div class="form-control" id="mtitulo"></div>
        </div>

        <div class="form-group col-md-6">
          <label for="user">Responsavel</label>
          <div class="form-control" id="autor"></div>
        </div>
      </div>

      <div class="row">
        <div class="form-group col-md-6">
          <div class="input-group date">
            <input type="text" class="form-control date" id="inicioEdit" />
            <div class="input-group-addon">
              <span class="glyphicon glyphicon-th"></span>
            </div>
          </div>
        </div>

        <div class="form-group col-md-6">
            <label for="importancia">Prioridade</label>
            <input type="text" class="form-control" id="importanciaEdit" />
        </div>
      </div>

       <div class="row">
        <div class="form-group col-md-12">
          <label for="descricaoEvento">Descrição</label>
          <input type="text" class="form-control" id="descricaoEventoEdit" />
        </div>
       </div>

    </div>

    <div class="modal-footer">
      <button type="button" class="btn btn-default" id="closeM" data-dismiss="modal">Cancelar</button>
      <input href="http://localhost/sistema/calendar2/updateEvents2"  type="submit" class="btn btn-primary" name="btsalvar" value="Atualizar" />
    </div>
    </div>
  </div>
</div>
<!-- /.modal -->
</code>```

Controler:

```<code><?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Calendar2 extends CI_controller{

    function __construct(){
        parent:: __construct();
        $this->load->model('calendar2Model', 'model', TRUE);
    }

    public function index(){
        $this->template->set('title', 'Agenda');
        $this->template->load('layout', 'calendar_v.php');
        //$this->load->view('calendar_v.php');
    }

    public function getEvents(){
        $data = $this->model->get_events();
        echo json_encode($data);
    }

    public function updateEvents(){
        $param['id'] = $this->input->post('id');
        $param['inicio'] = $this->input->post('inicio');
        $param['fim'] = $this->input->post('fim');
        $r =  $this->model->updateEvents($param);
        echo json_encode($r);
    }

    public function updateEvents2(){
        die('');
    }

    public function deleteEvents(){
        $id = $this->input->post('id');
        $r = $this->model->deleteEvents($id);
        echo json_encode($r);
    }
</code>```

Modal:

```<code><?php

class calendar2Model extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    public function get_events(){
        $this->db->select('idevento id, inicio start, fim end,descricaoEvento text, user autor,importancia impor ,cnome title');
        $this->db->from('eventos');
        $this->db->join('clientes','clientes.ccod = eventos.nomeEvento');
        return $this->db->get()->result();

    }

    function inserir($data) {
        return $this->db->insert('eventos', $data);
    }

    function updateEvents($param) {
        $campos = array(
                'inicio' => $param['inicio'],
                'fim' => $param['fim']
            );

        $this->db->where('idevento', $param['id']);
        $this->db->update('eventos', $campos);

        if($this->db->affected_rows() == 1){
            return 1;
        } else{
            return 0;
            }
        }

    function deleteEvents($id){
        $this->db->where('idevento', $id);
        $this->db->delete('eventos');
        if($this->db->affected_rows() == 1){
            return 1;
        } else{
            return 0;
            }
        }
}
</code>```

答:
```<code><input href="http://localhost/sistema/calendar2/updateEvents2"  type="submit" class="btn btn-primary" name="btsalvar" value="Atualizar" />
</code>```

<p>'href' not an attributes for input tag
try to submitting the form to the server by giving it in action and method</p>

```<code><input type="submit" >
</code>```

Body:
Good afternoon, I'm creating a simple calendar using the FullCalendar plugin, I'm almost done, but now I need to click on the desired event to show the information of the event and that there is an updated option in the image below you can see how are currently

Example

Now, continue with my codes up to this point, however, please note that I have already defined one updated button and the method that is used, but still  is not reaching at method. What I need is find out how to display the original data of the event and give the user a possibility to change and save this on database.

View:

        Nova Tarefa

      <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

 Editar Evento

            Nome Cliente

          Responsavel

            <input type="text" class="form-control date" id="inicioEdit" />

            Prioridade
            <input type="text" class="form-control" id="importanciaEdit" />

          Descrição
          <input type="text" class="form-control" id="descricaoEventoEdit" />

      <button type="button" class="btn btn-default" id="closeM" data-dismiss="modal">Cancelar</button>
      <input href="http://localhost/sistema/calendar2/updateEvents2"  type="submit" class="btn btn-primary" name="btsalvar" value="Atualizar" />

Controler:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Calendar2 extends CI_controller{

    function __construct(){
        parent:: __construct();
        $this->load->model('calendar2Model', 'model', TRUE);
    }

    public function index(){
        $this->template->set('title', 'Agenda');
        $this->template->load('layout', 'calendar_v.php');
        //$this->load->view('calendar_v.php');
    }

    public function getEvents(){
        $data = $this->model->get_events();
        echo json_encode($data);
    }

    public function updateEvents(){
        $param['id'] = $this->input->post('id');
        $param['inicio'] = $this->input->post('inicio');
        $param['fim'] = $this->input->post('fim');
        $r =  $this->model->updateEvents($param);
        echo json_encode($r);
    }

    public function updateEvents2(){
        die('');
    }

    public function deleteEvents(){
        $id = $this->input->post('id');
        $r = $this->model->deleteEvents($id);
        echo json_encode($r);
    }

Modal:

<?php

class calendar2Model extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    public function get_events(){
        $this->db->select('idevento id, inicio start, fim end,descricaoEvento text, user autor,importancia impor ,cnome title');
        $this->db->from('eventos');
        $this->db->join('clientes','clientes.ccod = eventos.nomeEvento');
        return $this->db->get()->result();

    }

    function inserir($data) {
        return $this->db->insert('eventos', $data);
    }

    function updateEvents($param) {
        $campos = array(
                'inicio' => $param['inicio'],
                'fim' => $param['fim']
            );

        $this->db->where('idevento', $param['id']);
        $this->db->update('eventos', $campos);

        if($this->db->affected_rows() == 1){
            return 1;
        } else{
            return 0;
            }
        }

    function deleteEvents($id){
        $this->db->where('idevento', $id);
        $this->db->delete('eventos');
        if($this->db->affected_rows() == 1){
            return 1;
        } else{
            return 0;
            }
        }
}

Body:
<input href="http://localhost/sistema/calendar2/updateEvents2"  type="submit" class="btn btn-primary" name="btsalvar" value="Atualizar" />

'href' not an attributes for input tag
try to submitting the form to the server by giving it in action and method

<input type="submit" >


来源: stackexchange

问:
Center three div containers next to each other
I want three divs to be centered in the mid. In the end it should look like this

now my problem. In my css I used the float keyword but it seems this does not work for sure. The divs still split up.

As you can see in the following code example the containers are getting weird.

Would be awesome if someone could help me out there!

#selectionElementContainer {
  height: 70%;
  width: 100%;
  margin-top: 50px;
}

#selectionElementLeft {
  float: left;
}

#selectionElementCenter {
  margin: 0 auto;
}

#selectionElementRight {
  float: right;
}

.selectionElementImage {
  cursor: default;
  text-align: center;
  margin-top: 10px;
}

.selectionElementHeader {
  cursor: default;
  text-align: center;
  font-size: 30px;
  margin-top: 30px;
  color: #333f4b;
}

.selectionElementText {
  cursor: default;
  text-align: center;
  margin-top: 20px;
  font-size: 18px;
  color: #4c545c;
}

.selectionElementLinkContainer {
  cursor: default;
  margin-top: 10px;
}

.selectionElementBtn {
  text-decoration: none;
  text-align: center;
  cursor: pointer;
  border: none;
  font-size: 18px;
  background-color: white;
  color: #1bbee7;
  transition: 0.5s;
}

.selectionElementBtn:hover {
  color: #a4d662;
  transition: 0.5s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <div id="selectionElementContainer">
      <div id="selectionElementLeft">
        <div class="selectionElementImage">
          <img src="bild">
        </div>
        <div class="selectionElementHeader">
          Title
        </div>
        <div class="selectionElementText">
          Text
        </div>
        <div class="selectionElementLink">
          <button class="selectionElementBtn">Link</button>
        </div>
      </div>
      <div id="selectionElementCenter">
        <div class="selectionElementImage">
          <img src="bild">
        </div>
        <div class="selectionElementHeader">
          Title
        </div>
        <div class="selectionElementText">
          Text
        </div>
        <div class="selectionElementLink">
          <button class="selectionElementBtn">Link</button>
        </div>
      </div>
      <div id="selectionElementRight">
        <div class="selectionElementImage">
          <img src="bild">
        </div>
        <div class="selectionElementHeader">
          Title
        </div>
        <div class="selectionElementText">
          Text
        </div>
        <div class="selectionElementLinkContainer">
          <button class="selectionElementBtn">Link</button>
        </div>
      </div>
    </div></code>```

答:
If you're going to use floats, float all items to the left. Your center element was taking up the whole width of the container element and pushing the third element down.

Beyond that it looks like you're over-engineering things a little bit. See my example below on how you can simplify your markup and CSS and make it a bit more semantic.

.selection {
  box-sizing: border-box;
  float: left;
  width: 33.33333%;
  padding: 1rem;
  text-align: center;
}

.selection img {
  display: block;
  max-width: 100%;
  height: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="selections">

  <div class="selection">
    <img src="http://placehold.it/400x400/fc0">
    <h2>Title 1</h2>
    <p>
      Text
    </p>
    Link
  </div>

  <div class="selection">
    <img src="http://placehold.it/400x400/">
    <h2>Title 2</h2>
    <p>
      Text
    </p>
    Link
  </div>

  <div class="selection">
    <img src="http://placehold.it/400x400/fc0">
    <h2>Title 3</h2>
    <p>
      Text
    </p>
    Link
  </div>

</div></code>```

If you want to get a bit more modern with your approach, use flexbox.

#selections {
  display: flex;
}

.selection {
  padding: 1rem;
  text-align: center;
}

.selection img {
  display: block;
  max-width: 100%;
  height: auto;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="selections">

  <div class="selection">
    <img src="http://placehold.it/400x400/fc0">
    <h2>Title 1</h2>
    <p>
      Text
    </p>
    Link
  </div>

  <div class="selection">
    <img src="http://placehold.it/400x400/">
    <h2>Title 2</h2>
    <p>
      Text
    </p>
    Link
  </div>

  <div class="selection">
    <img src="http://placehold.it/400x400/fc0">
    <h2>Title 3</h2>
    <p>
      Text
    </p>
    Link
  </div>

</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
I want three divs to be centered in the mid. In the end it should look like this

now my problem. In my css I used the float keyword but it seems this does not work for sure. The divs still split up.

As you can see in the following code example the containers are getting weird.

Would be awesome if someone could help me out there!

#selectionElementContainer {
  height: 70%;
  width: 100%;
  margin-top: 50px;
}

#selectionElementLeft {
  float: left;
}

#selectionElementCenter {
  margin: 0 auto;
}

#selectionElementRight {
  float: right;
}

.selectionElementImage {
  cursor: default;
  text-align: center;
  margin-top: 10px;
}

.selectionElementHeader {
  cursor: default;
  text-align: center;
  font-size: 30px;
  margin-top: 30px;
  color: #333f4b;
}

.selectionElementText {
  cursor: default;
  text-align: center;
  margin-top: 20px;
  font-size: 18px;
  color: #4c545c;
}

.selectionElementLinkContainer {
  cursor: default;
  margin-top: 10px;
}

.selectionElementBtn {
  text-decoration: none;
  text-align: center;
  cursor: pointer;
  border: none;
  font-size: 18px;
  background-color: white;
  color: #1bbee7;
  transition: 0.5s;
}

.selectionElementBtn:hover {
  color: #a4d662;
  transition: 0.5s;
}

          Title

          Text

          <button class="selectionElementBtn">Link</button>

          Title

          Text

          <button class="selectionElementBtn">Link</button>

          Title

          Text

          <button class="selectionElementBtn">Link</button>

Body:
If you're going to use floats, float all items to the left. Your center element was taking up the whole width of the container element and pushing the third element down.

Beyond that it looks like you're over-engineering things a little bit. See my example below on how you can simplify your markup and CSS and make it a bit more semantic.

.selection {
  box-sizing: border-box;
  float: left;
  width: 33.33333%;
  padding: 1rem;
  text-align: center;
}

.selection img {
  display: block;
  max-width: 100%;
  height: auto;
}

<div id="selections">

  <div class="selection">
    <img src="http://placehold.it/400x400/fc0">
    <h2>Title 1</h2>
    <p>
      Text
    </p>
    <a href="#">Link</a>
  </div>

  <div class="selection">
    <img src="http://placehold.it/400x400/">
    <h2>Title 2</h2>
    <p>
      Text
    </p>
    <a href="#">Link</a>
  </div>

  <div class="selection">
    <img src="http://placehold.it/400x400/fc0">
    <h2>Title 3</h2>
    <p>
      Text
    </p>
    <a href="#">Link</a>
  </div>

</div>

If you want to get a bit more modern with your approach, use flexbox.

#selections {
  display: flex;
}

.selection {
  padding: 1rem;
  text-align: center;
}

.selection img {
  display: block;
  max-width: 100%;
  height: auto;
}

<div id="selections">

  <div class="selection">
    <img src="http://placehold.it/400x400/fc0">
    <h2>Title 1</h2>
    <p>
      Text
    </p>
    <a href="#">Link</a>
  </div>

  <div class="selection">
    <img src="http://placehold.it/400x400/">
    <h2>Title 2</h2>
    <p>
      Text
    </p>
    <a href="#">Link</a>
  </div>

  <div class="selection">
    <img src="http://placehold.it/400x400/fc0">
    <h2>Title 3</h2>
    <p>
      Text
    </p>
    <a href="#">Link</a>
  </div>

</div>


问:
Encrypted connection string can not be decrypted
I'm about to publish my application, but I want my connection strings to be encrypted.

aspnet_regiis -pef "sectionName of web.config" "path"

The command above does the job, I publish my application to the server and
run the following command on the server machine:

aspnet_regiis -pa "NetFrameworkConfigurationKey" "identityOfMyAppPool"

But when I try to browse my application I get the following error:

Configuration Error

Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error

Message: Failed to decrypt using provider 'RsaProtectedConfigurationProvider'. Error message from the provider: The data to be decrypted exceeds the maximum for this modulus of 128 bytes.

How can I fix it?

Thanks in advance,

答:
One instance where this error message is returned is when an RSA key with 2048 bits is used to encrypt the web.config, and an attempt is made to decrypt with a 1024 bit RSA key. Double-check to make sure you have the same key on both machines (all you need is the public portion of the key on the encrypting machine).

By default, the NetFrameworkConfigurationKey is different on each machine (and non-exportable?). To deploy an encrypted web.config from another machine, you need to export the public key from the destination machine and use it to encrypt (or follow all the tutorials and create your own key and put it on both machines...).


问:
Processor has been reset by watch dog timer (PIC16F72, XC8 compiler)
I have started PIC programming for PIC16F72 micro-controller through MPLAB X IDE and XC8 compiler.Below is my code, it is compiled successfully.

```<code>#define _XTAL_FREQ 4000000
#include<xc.h>
#pragma config FOSC = RC // Oscillator Selection bits (HS oscillator)
#pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT enabled)
#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOREN = ON // Brown-out Reset Enable bit (BOR enabled)
#pragma config CP = OFF // Flash Program Memory Code Protection bit (Code protection off)

char pattern[] = {0b10000001,0b11000011,0b11100111,0b11111111,0b11100111,0b11000011,0b10000001};

void write(char tab)
{
    char check;
    for(int a=0;a<8;a++)
    {
        check = ((tab >> a) & 1);
        if(check)
        {
            PORTBbits.RB7=1;
            PORTBbits.RB6=0;PORTBbits.RB6=1;
        }
        else
        {
            PORTBbits.RB7=0;
            PORTBbits.RB6=0;PORTBbits.RB6=1;
        }
    }
}
void main(void) {

    TRISB=0x00; //Initialize as output
    PORTBbits.RB6=0;
    PORTBbits.RB5=0;
    PORTBbits.RB5=1;
    while(1)
    {
        for(int i=0;i<7;i++)
        {
            write(pattern[i]);
           __delay_ms(1000);
        }
    }

    return;
}
</code>```

When I simulated my code in Proteus it shows below error
Processor has been reset by watch dog timer expiring at xxxxx after every 2.3 seconds.

I have searched for this problem with no success. I am unable to resolve the issue

答:
You can try to use MPLAB X to generate configuration bits for you.

In MPLAB X, click Window -> PIC Memory Views -> Configuration Bits. New window will show up where you can configure your PIC and disable watchdog. If you click button "Generate Source Code to Output" MPLAB will generate source code with proper Configuration Bits for PIC you're using in project. Here's official Microchip tutorial which describes it in detail -http://microchipdeveloper.com/mplabx:view-and-set-configuration-bits

Body:
I have started PIC programming for PIC16F72 micro-controller through MPLAB X IDE and XC8 compiler.Below is my code, it is compiled successfully.

#define _XTAL_FREQ 4000000
#include<xc.h>
#pragma config FOSC = RC // Oscillator Selection bits (HS oscillator)
#pragma config WDTE = OFF // Watchdog Timer Enable bit (WDT enabled)
#pragma config PWRTE = OFF // Power-up Timer Enable bit (PWRT disabled)
#pragma config BOREN = ON // Brown-out Reset Enable bit (BOR enabled)
#pragma config CP = OFF // Flash Program Memory Code Protection bit (Code protection off)

char pattern[] = {0b10000001,0b11000011,0b11100111,0b11111111,0b11100111,0b11000011,0b10000001};

void write(char tab)
{
    char check;
    for(int a=0;a<8;a++)
    {
        check = ((tab >> a) & 1);
        if(check)
        {
            PORTBbits.RB7=1;
            PORTBbits.RB6=0;PORTBbits.RB6=1;
        }
        else
        {
            PORTBbits.RB7=0;
            PORTBbits.RB6=0;PORTBbits.RB6=1;
        }
    }
}
void main(void) {

    TRISB=0x00; //Initialize as output
    PORTBbits.RB6=0;
    PORTBbits.RB5=0;
    PORTBbits.RB5=1;
    while(1)
    {
        for(int i=0;i<7;i++)
        {
            write(pattern[i]);
           __delay_ms(1000);
        }
    }

    return;
}

When I simulated my code in Proteus it shows below error
Processor has been reset by watch dog timer expiring at xxxxx after every 2.3 seconds.

I have searched for this problem with no success. I am unable to resolve the issue


答:
Float them all left and make the width 33% (roughly a third). I also made the text center aligned as I thought it looked better but feel free to omit if you prefer.

#selectionElementContainer {
  height: 70%;
  width: 100%;
  margin-top: 50px;
}

#selectionElementLeft, #selectionElementCenter,#selectionElementRight {
  float: left;
  width: 33%;
  text-align: center;
}

.selectionElementImage {
  cursor: default;
  text-align: center;
  margin-top: 10px;
}

.selectionElementHeader {
  cursor: default;
  text-align: center;
  font-size: 30px;
  margin-top: 30px;
  color: #333f4b;
}

.selectionElementText {
  cursor: default;
  text-align: center;
  margin-top: 20px;
  font-size: 18px;
  color: #4c545c;
}

.selectionElementLinkContainer {
  cursor: default;
  margin-top: 10px;
}

.selectionElementBtn {
  text-decoration: none;
  text-align: center;
  cursor: pointer;
  border: none;
  font-size: 18px;
  background-color: white;
  color: #1bbee7;
  transition: 0.5s;
}

.selectionElementBtn:hover {
  color: #a4d662;
  transition: 0.5s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="selectionElementContainer">
  <div id="selectionElementLeft">
    <div class="selectionElementImage">
      <img src="bild">
    </div>
    <div class="selectionElementHeader">
      Title
    </div>
    <div class="selectionElementText">
      Text
    </div>
    <div class="selectionElementLink">
      <button class="selectionElementBtn">Link</button>
    </div>
  </div>
  <div id="selectionElementCenter">
    <div class="selectionElementImage">
      <img src="bild">
    </div>
    <div class="selectionElementHeader">
      Title
    </div>
    <div class="selectionElementText">
      Text
    </div>
    <div class="selectionElementLink">
      <button class="selectionElementBtn">Link</button>
    </div>
  </div>
  <div id="selectionElementRight">
    <div class="selectionElementImage">
      <img src="bild">
    </div>
    <div class="selectionElementHeader">
      Title
    </div>
    <div class="selectionElementText">
      Text
    </div>
    <div class="selectionElementLinkContainer">
      <button class="selectionElementBtn">Link</button>
    </div>
  </div>
</div></code>```

Title: Center three div containers next to each other

Body:
Float them all left and make the width 33% (roughly a third). I also made the text center aligned as I thought it looked better but feel free to omit if you prefer.

#selectionElementContainer {
  height: 70%;
  width: 100%;
  margin-top: 50px;
}

#selectionElementLeft, #selectionElementCenter,#selectionElementRight {
  float: left;
  width: 33%;
  text-align: center;
}

.selectionElementImage {
  cursor: default;
  text-align: center;
  margin-top: 10px;
}

.selectionElementHeader {
  cursor: default;
  text-align: center;
  font-size: 30px;
  margin-top: 30px;
  color: #333f4b;
}

.selectionElementText {
  cursor: default;
  text-align: center;
  margin-top: 20px;
  font-size: 18px;
  color: #4c545c;
}

.selectionElementLinkContainer {
  cursor: default;
  margin-top: 10px;
}

.selectionElementBtn {
  text-decoration: none;
  text-align: center;
  cursor: pointer;
  border: none;
  font-size: 18px;
  background-color: white;
  color: #1bbee7;
  transition: 0.5s;
}

.selectionElementBtn:hover {
  color: #a4d662;
  transition: 0.5s;
}

<div id="selectionElementContainer">
  <div id="selectionElementLeft">
    <div class="selectionElementImage">
      <img src="bild">
    </div>
    <div class="selectionElementHeader">
      Title
    </div>
    <div class="selectionElementText">
      Text
    </div>
    <div class="selectionElementLink">
      <button class="selectionElementBtn">Link</button>
    </div>
  </div>
  <div id="selectionElementCenter">
    <div class="selectionElementImage">
      <img src="bild">
    </div>
    <div class="selectionElementHeader">
      Title
    </div>
    <div class="selectionElementText">
      Text
    </div>
    <div class="selectionElementLink">
      <button class="selectionElementBtn">Link</button>
    </div>
  </div>
  <div id="selectionElementRight">
    <div class="selectionElementImage">
      <img src="bild">
    </div>
    <div class="selectionElementHeader">
      Title
    </div>
    <div class="selectionElementText">
      Text
    </div>
    <div class="selectionElementLinkContainer">
      <button class="selectionElementBtn">Link</button>
    </div>
  </div>
</div>


问:
Finding first and last occurence of substring and replace them with re.sub()
```<code> import re

    def x(s):
        if re.match(r'^o|non', s):
            return re.sub(r'o|non', '', s, count=1)
        elif re.search(r'e|er|est$', s):
            return re.sub(r'(.*)e|er|est', r'\1''', s)
</code>```

So if the string starts with 'o' or 'non' the first occurence of one of those two will be replaced by ''. Or if the string ends with e, er or est that ending will be replaced by ''.

How can I write all this into one, so that if the string starts with 'non' and end with 'est' it will replace both of those and return the middle of the string. Also, I can't get this (r'(.*)e|er|est', r'\1''', s) to work, it only replaces the last e even if the string ends with 'est'. Am I missing something or is the '|' not the way to go?

答:
You do not have to check for a mach first and you can chain both substitutions. Finally the end of a string is indicated by a $ in regular expressions

```<code> re.sub(r'e$|est$|er$' , '', re.sub(r'^o|^non','',s))
</code>```

Body:
 import re

    def x(s):
        if re.match(r'^o|non', s):
            return re.sub(r'o|non', '', s, count=1)
        elif re.search(r'e|er|est$', s):
            return re.sub(r'(.*)e|er|est', r'\1''', s)

So if the string starts with 'o' or 'non' the first occurence of one of those two will be replaced by ''. Or if the string ends with e, er or est that ending will be replaced by ''.

How can I write all this into one, so that if the string starts with 'non' and end with 'est' it will replace both of those and return the middle of the string. Also, I can't get this (r'(.*)e|er|est', r'\1''', s) to work, it only replaces the last e even if the string ends with 'est'. Am I missing something or is the '|' not the way to go?

Body:
You do not have to check for a mach first and you can chain both substitutions. Finally the end of a string is indicated by a $ in regular expressions

 re.sub(r'e$|est$|er$' , '', re.sub(r'^o|^non','',s))


问:
"Value cannot be null.\r\nParameter name: source" with https://graph.microsoft.com/v1.0/users/?$select=id,mySite
I tried MS Graph API with following GET request: https://graph.microsoft.com/v1.0/users/?$select=id,mySite

However, it reports error Value cannot be null.\r\nParameter name: source.

It works if I remove mySite or change it with another user property such as userPrincipalName.

答:
This is a known limitation of the users endpoint (i.e. the collection of users). From the documentation:

Note: Listing users returns a default set of properties only
  (businessPhones, displayName, givenName, id, jobTitle, mail,
  mobilePhone, officeLocation, preferredLanguage, surname,
  userPrincipalName). Use $select to get the other properties and
  relationships for the user object. However, only the following
  properties can be selected for individual users, and not for collections of users: aboutMe, birthday, hireDate, interests, mySite, pastProjects, preferredName, responsibilities, schools, skills, mailboxSettings

For easier reading, the list of unsupported properties are:

aboutMe

birthday

hireDate

interests

mySite

pastProjects

preferredName

responsibilities

schools

skills

mailboxSettings


问:
JSON Response IBM BPM
In our environment we have to prepare the response call with a JSON format (tw.local.jsonResponse). I'm new to JSON, not sure how to parse the date with the following JSON format in IBM BPM. It could be a great help if anyone guide/suggest (by using the following data).

```<code>Success Response

Code: 200

Content:

{
        “status” : “success”
        “data” : {
                “change_number” : [string],
                “instance” : [string],
                “customer” : [string],
                “tasks” : [
                      { “task_number” : [string],
                        “description” : [string],
                        “schedule_start” : [datetime],
                        “schedule_end” : [datetime]
                      },
                      { /* another task */ }
                ]
        }
}
</code>```

答:
I have experienced similar problem with json and dates in IBM BPM.

In your solution, you can get the external JavaScript file json.js.

You can use the following function to return your JSON string:

```<code>BPMJSON.convertTWToJSON(tw.local.MyObject, false)
</code>```

Title: JSON Response IBM BPM

Body:
In our environment we have to prepare the response call with a JSON format (tw.local.jsonResponse). I'm new to JSON, not sure how to parse the date with the following JSON format in IBM BPM. It could be a great help if anyone guide/suggest (by using the following data).

Success Response

Code: 200

Content:

{
        “status” : “success”
        “data” : {
                “change_number” : [string],
                “instance” : [string],
                “customer” : [string],
                “tasks” : [
                      { “task_number” : [string],
                        “description” : [string],
                        “schedule_start” : [datetime],
                        “schedule_end” : [datetime]
                      },
                      { /* another task */ }
                ]
        }
}

Body:
I have experienced similar problem with json and dates in IBM BPM.

In your solution, you can get the external JavaScript file json.js.

You can use the following function to return your JSON string:

BPMJSON.convertTWToJSON(tw.local.MyObject, false)


问:
Best way to check if an PowerShell Object exist?
I am looking for the best way to check if a Com Object exists.

Here is the code that I have; I'd like to improve the last line:

```<code>$ie = New-Object -ComObject InternetExplorer.Application
$ie.Navigate("http://www.stackoverflow.com")
$ie.Visible = $true

$ie -ne $null #Are there better options?
</code>```

答:
In your particular example perhaps you do not have to perform any checks at all. Is that possible that New-Object return null? I have never seen that. The command should fail in case of a problem and the rest of the code in the example will not be executed. So why should we do that checks at all?

Only in the code like below we need some checks (explicit comparison with $null is the best):

```<code># we just try to get a new object
$ie = $null
try {
    $ie = New-Object -ComObject InternetExplorer.Application
}
catch {
    Write-Warning $_
}

# check and continuation
if ($ie -ne $null) {
    ...
}
</code>```

Body:
I am looking for the best way to check if a Com Object exists.

Here is the code that I have; I'd like to improve the last line:

$ie = New-Object -ComObject InternetExplorer.Application
$ie.Navigate("http://www.stackoverflow.com")
$ie.Visible = $true

$ie -ne $null #Are there better options?

Body:
In your particular example perhaps you do not have to perform any checks at all. Is that possible that New-Object return null? I have never seen that. The command should fail in case of a problem and the rest of the code in the example will not be executed. So why should we do that checks at all?

Only in the code like below we need some checks (explicit comparison with $null is the best):

# we just try to get a new object
$ie = $null
try {
    $ie = New-Object -ComObject InternetExplorer.Application
}
catch {
    Write-Warning $_
}

# check and continuation
if ($ie -ne $null) {
    ...
}

ContentLicense: CC BY-SA 2.5


问:
Is it possible to run SikuliX on a host computer and have the script interact with virtual machine?
Currently running Windows 10 (native) and VMware Workstation 12 Player. I am running various LTS releases of Ubuntu in VMware.

I am wondering if there is way for me to run SikuliX on my main OS, Windows 10, and have the script interact with a virtual machine, running an Ubuntu OS, that I have open.

The quickstart documentation on the download site isn't very specific about the limitations of SikuliX on this topic. It simply says that you can't run it on a headless system (which VMware is not), and you need to have a monitor - the only problem is that I have no idea if SikuliX considers VMware to be a legitimate monitor or not.

I am aware of the fact that you can install Sikulix on the virtual machine itself, but this is not preferable as I would have to possibly reconfigure my VM settings to allocate more memory OR just deal with running the script at a slower pace.

Any help would be greatly appreciated.

答:
The answer is yes, if you run SikuliX on a native host, it is possible to interact with the the interface of the virtual machine the same as running SikuliX on the virtual machine itself.  </p>

<p>Now that I think about it, I should have probably tested this out before posting the question, but hey, if anyone has the same question as I do, now you know. </p>

Body:
The answer is yes, if you run SikuliX on a native host, it is possible to interact with the the interface of the virtual machine the same as running SikuliX on the virtual machine itself.

Now that I think about it, I should have probably tested this out before posting the question, but hey, if anyone has the same question as I do, now you know.


问:
Can we send View object as parameter within OnCreate() method?
I'm a beginner Android developer. I'm still learning new things every day, and while learning I have heard this question quite frequently: What will happen if we send View object as parameter within OnCreate Method? I have searched about it but didn't find anything helpful. I just want to know is it really possible and if so then please explain the scenario.

答: oncreate() called when the activity is first created. This is where you should do all of your normal static set up: create views, bind data to lists, etc. This method also provides you with a Bundle containing the activity's previously frozen state.</p>


问:
Neo4j/Cypher: Match on dynamic property
According to the developer manual section 3.2.4 on Parameters:

Parameters cannot be used for the following constructs, as these form part of the >query structure that is compiled into a query plan:

property keys; so, MATCH (n) WHERE n.$param = 'something' is invalid (source)

Is there no way around this (c#, using the official driver)? I have a case where a node of a particular type can contain from a few up to hundreds of properties, and I want the users to be able to search for any of these without having to write all possible queries in advance. Ideally I'd like to be able to do something similar to

```<code>MATCH (a) WHERE ({prop} CONTAINS {val}) RETURN a
</code>```

supplying a dictionary where prop: "a.Description" and val: "Freeform item description"

Is this at all possible, or is string concatenation (with related drawbacks) the only possibility here?

答:
The syntax, n['foo'], can be used to reference n.foo.

So, this should work (I use the now-preferred $foo syntax instead of {foo} for parameters):

```<code>MATCH (a) WHERE a[$propName] CONTAINS $val
RETURN a;
</code>```

Where propName: "Description" and val: "Freeform item description"

Title: Neo4j/Cypher: Match on dynamic property

Body:
According to the developer manual section 3.2.4 on Parameters:

Parameters cannot be used for the following constructs, as these form part of the >query structure that is compiled into a query plan:

property keys; so, MATCH (n) WHERE n.$param = 'something' is invalid (source)

Is there no way around this (c#, using the official driver)? I have a case where a node of a particular type can contain from a few up to hundreds of properties, and I want the users to be able to search for any of these without having to write all possible queries in advance. Ideally I'd like to be able to do something similar to

MATCH (a) WHERE ({prop} CONTAINS {val}) RETURN a

supplying a dictionary where prop: "a.Description" and val: "Freeform item description"

Is this at all possible, or is string concatenation (with related drawbacks) the only possibility here?

Body:
The syntax, n['foo'], can be used to reference n.foo.

So, this should work (I use the now-preferred $foo syntax instead of {foo} for parameters):

MATCH (a) WHERE a[$propName] CONTAINS $val
RETURN a;

Where propName: "Description" and val: "Freeform item description"


答:
Easy explanation, instead using float which you may need to be controlling the parent size and applying an empty div, you can use display: inline-block as you may see at selectionElement class

You can use something like this:

```<code>#selectionElementContainer {
  height: 70%;
  width: 100%;
  margin-top: 50px;
}

.selectionElement {
  display: inline-block;
  width: 300px;
  border: #f0f thin solid;
}

.selectionElementImage {
  cursor: default;
  text-align: center;
  margin-top: 10px;
}

.selectionElementHeader {
  cursor: default;
  text-align: center;
  font-size: 30px;
  margin-top: 30px;
  color: #333f4b;
}

.selectionElementText {
  cursor: default;
  text-align: center;
  margin-top: 20px;
  font-size: 18px;
  color: #4c545c;
}

.selectionElementLinkContainer {
  cursor: default;
  margin-top: 10px;
}

.selectionElementBtn {
  text-decoration: none;
  text-align: center;
  cursor: pointer;
  border: none;
  font-size: 18px;
  background-color: white;
  color: #1bbee7;
  transition: 0.5s;
}

.selectionElementBtn:hover {
  color: #a4d662;
  transition: 0.5s;
}
</code>```

Body:
Easy explanation, instead using float which you may need to be controlling the parent size and applying an empty div, you can use display: inline-block as you may see at selectionElement class

You can use something like this:

#selectionElementContainer {
  height: 70%;
  width: 100%;
  margin-top: 50px;
}

.selectionElement {
  display: inline-block;
  width: 300px;
  border: #f0f thin solid;
}

.selectionElementImage {
  cursor: default;
  text-align: center;
  margin-top: 10px;
}

.selectionElementHeader {
  cursor: default;
  text-align: center;
  font-size: 30px;
  margin-top: 30px;
  color: #333f4b;
}

.selectionElementText {
  cursor: default;
  text-align: center;
  margin-top: 20px;
  font-size: 18px;
  color: #4c545c;
}

.selectionElementLinkContainer {
  cursor: default;
  margin-top: 10px;
}

.selectionElementBtn {
  text-decoration: none;
  text-align: center;
  cursor: pointer;
  border: none;
  font-size: 18px;
  background-color: white;
  color: #1bbee7;
  transition: 0.5s;
}

.selectionElementBtn:hover {
  color: #a4d662;
  transition: 0.5s;
}


问:
update pandas dataframe column with a sequence for matching rows
I have a pandas dataframe with 3 columns.

```<code>Event_occur Boolean
Event_predict Boolean
Incorrect_pred Number default 0
</code>```

Please refer to the screenshot. I am trying to update Incorrect_pred based on certain conditions.

Whenever Event_occur is True and Event_predict is False,
Incorrect_pred should be updated with an increasing number sequence.
Example, the first occurrence of Event_occur =True and Event_predict
=False, should update Incorrect_pred with 1, the second occurence with 2 and so on.

Whenever the 2 events are both True, then
Incorrect_pred should be updated with the previous non zero
number.(refer index row 5 and 9 in the example).

Whenever
Event_occur is False, the update is always 0 which is the default
value.

If this was sql, I could have used a windows function. Something like:

```<code>(case
   when Event_occur = 'FALSE' then 0
   else sum(case when Event_occur = Event_predict) then 0 else 1 end)
 over (order by <some column>) end)
</code>```

Is there a way I can do this in pandas?

expected dataframe

答:
Let's try:

```<code>df['pred'] = np.where(df.Event_occur == False,0,np.where(df.Event_occur != df.Event_predict,1,0)).cumsum()
df['Incorrect_pred']= df.pred.where(df.Event_occur == True).fillna(0)
print(df)
</code>```

Output:

```<code>   Event_occur  Event_predict  Incorrect_pred  pred
0        False           True             0.0     0
1         True          False             1.0     1
2         True          False             2.0     2
3        False          False             0.0     2
4         True          False             3.0     3
5         True           True             3.0     3
6         True           True             3.0     3
7         True          False             4.0     4
8        False           True             0.0     4
9         True           True             4.0     4
</code>```

Body:
I have a pandas dataframe with 3 columns.

Event_occur Boolean
Event_predict Boolean
Incorrect_pred Number default 0

Please refer to the screenshot. I am trying to update Incorrect_pred based on certain conditions.

Whenever Event_occur is True and Event_predict is False,
Incorrect_pred should be updated with an increasing number sequence.
Example, the first occurrence of Event_occur =True and Event_predict
=False, should update Incorrect_pred with 1, the second occurence with 2 and so on.

Whenever the 2 events are both True, then
Incorrect_pred should be updated with the previous non zero
number.(refer index row 5 and 9 in the example).

Whenever
Event_occur is False, the update is always 0 which is the default
value.

If this was sql, I could have used a windows function. Something like:

(case
   when Event_occur = 'FALSE' then 0
   else sum(case when Event_occur = Event_predict) then 0 else 1 end)
 over (order by <some column>) end)

Is there a way I can do this in pandas?

expected dataframe

Body:
Let's try:

df['pred'] = np.where(df.Event_occur == False,0,np.where(df.Event_occur != df.Event_predict,1,0)).cumsum()
df['Incorrect_pred']= df.pred.where(df.Event_occur == True).fillna(0)
print(df)

Output:

   Event_occur  Event_predict  Incorrect_pred  pred
0        False           True             0.0     0
1         True          False             1.0     1
2         True          False             2.0     2
3        False          False             0.0     2
4         True          False             3.0     3
5         True           True             3.0     3
6         True           True             3.0     3
7         True          False             4.0     4
8        False           True             0.0     4
9         True           True             4.0     4


问:
Is there a way to build the mobile nav bar in ng2-bootstrap?
I've been implementing ng2-bootstrap and Angular2.

I cannot figure out how to make the mobile navbar open / close.

Is this something that just isn't supported yet?  Or am I missing something?

Update, html:

```<code><nav class="navbar navbar-default">
    <div class="container-fluid">

    <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">
            <img src="/logo.png" />
        </a>
    </div>

    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
        <ul class="nav navbar-nav">
            <li router-active>
                <a [routerLink]=" ['Index'] ">Summary<span class="sr-only">(current)</span></a>
            </li>
            <li router-active>
                <a [routerLink]=" ['Portfolio'] ">Portfolio<span class="sr-only">(current)</span></a>
            </li>
            <li router-active>
                <a [routerLink]=" ['About'] ">About<span class="sr-only">(current)</span></a>
            </li>
        </ul>
        <form class="navbar-form navbar-left" role="search">
            <div class="form-group">
                <input type="text" class="form-control" placeholder="Search">
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
        </form>
        <ul class="nav navbar-nav navbar-right">
            <li dropdown keyboardNav="true">
                <a href class="dropdown-toggle" role="button" aria-expanded="false" dropdownToggle>
                    <span class="glyphicon glyphicon-user" aria-hidden="true"></span>
                    Andrew Duncan
                    <span class="caret"></span>
                </a>
                <ul class="dropdown-menu" role="menu">
                    <li role="menuitem"><a class="dropdown-item" href="#">Account Settings</a></li>
                    <li role="menuitem"><a class="dropdown-item" href="#">Another action</a></li>
                    <li role="menuitem"><a class="dropdown-item" href="#">Something else here</a></li>
                    <li class="divider dropdown-divider"></li>
                    <li role="menuitem"><a class="dropdown-item" href="#">Logout</a></li>
                </ul>
            </li>

        </ul>
    </div>
</div>
</code>```

Typescript:

```<code>/*
 * Angular 2 decorators and services
 */
import { Component, ViewEncapsulation } from '@angular/core';
import { RouteConfig, Router } from '@angular/router-deprecated';

import { AppState } from './app.service';
import { Home } from './home';
import { RouterActive } from './router-active';
import { BUTTON_DIRECTIVES, DROPDOWN_DIRECTIVES } from '../../node_modules/ng2-bootstrap';
/*
 * App Component
 * Top Level Component
 */
@Component({
  selector: 'app',
  pipes: [ ],
  providers: [ ],
  directives: [
    RouterActive,
    BUTTON_DIRECTIVES,
    DROPDOWN_DIRECTIVES ],
  encapsulation: ViewEncapsulation.None,
  styles: [
    require('./app.css')
  ],
  template: require('./app.html')
})
@RouteConfig([
  { path: '/',      name: 'Index', component: Home, useAsDefault: true },
  { path: '/home',  name: 'Home',  component: Home },
  // Async load a component using Webpack's require with es6-promise-loader and webpack `require`
  { path: '/about', name: 'About', loader: () => require('es6-promise!./about')('About') },
  { path: '/portfolio', name: 'Portfolio', loader: () => require('es6-promise!./portfolio')('Portfolio') }
])
export class App {
  angularclassLogo = 'assets/img/angularclass-avatar.png';
  loading = false;
  url = 'https://twitter.com/AngularClass';

  constructor(
    public appState: AppState) {

  }

  ngOnInit() {
    console.log('Initial App State', this.appState.state);
  }

}

/*
 * Please review the https://github.com/AngularClass/angular2-examples/ repo for
 * more angular app examples that you may copy/paste
 * (The examples may not be updated as quickly. Please open an issue on github for us to update it)
 * For help or questions please contact us at @AngularClass on twitter
 * or our chat on Slack at https://AngularClass.com/slack-join
 */
</code>```

答:
While Seth's solution works absolutely fine as it is, I modified the collapsing logic. Instead of using the click event, I subscribe to the router events to collapse the menu only after successful navigation.</p>

```<code>export class NavMenuComponent implements OnDestroy {
    public isCollapsed: boolean = true;
    private subscription: Subscription;

    constructor(private router: Router) {
        this.subscription = this.router.events.subscribe(s => {
            if (s instanceof NavigationEnd) {
                this.isCollapsed = true;
            }
        });
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}
</code>```

Body:
I've been implementing ng2-bootstrap and Angular2.

I cannot figure out how to make the mobile navbar open / close.

Is this something that just isn't supported yet?  Or am I missing something?

Update, html:

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            Toggle navigation

        </button>

                Summary(current)

                Portfolio(current)

                About(current)

        <form class="navbar-form navbar-left" role="search">

                <input type="text" class="form-control" placeholder="Search">

            <button type="submit" class="btn btn-default">Submit</button>
        </form>

                    Andrew Duncan

Account Settings

Another action

Something else here

Logout

Typescript:

/*
 * Angular 2 decorators and services
 */
import { Component, ViewEncapsulation } from '@angular/core';
import { RouteConfig, Router } from '@angular/router-deprecated';

import { AppState } from './app.service';
import { Home } from './home';
import { RouterActive } from './router-active';
import { BUTTON_DIRECTIVES, DROPDOWN_DIRECTIVES } from '../../node_modules/ng2-bootstrap';
/*
 * App Component
 * Top Level Component
 */
@Component({
  selector: 'app',
  pipes: [ ],
  providers: [ ],
  directives: [
    RouterActive,
    BUTTON_DIRECTIVES,
    DROPDOWN_DIRECTIVES ],
  encapsulation: ViewEncapsulation.None,
  styles: [
    require('./app.css')
  ],
  template: require('./app.html')
})
@RouteConfig([
  { path: '/',      name: 'Index', component: Home, useAsDefault: true },
  { path: '/home',  name: 'Home',  component: Home },
  // Async load a component using Webpack's require with es6-promise-loader and webpack `require`
  { path: '/about', name: 'About', loader: () => require('es6-promise!./about')('About') },
  { path: '/portfolio', name: 'Portfolio', loader: () => require('es6-promise!./portfolio')('Portfolio') }
])
export class App {
  angularclassLogo = 'assets/img/angularclass-avatar.png';
  loading = false;
  url = 'https://twitter.com/AngularClass';

  constructor(
    public appState: AppState) {

  }

  ngOnInit() {
    console.log('Initial App State', this.appState.state);
  }

}

/*
 * Please review the https://github.com/AngularClass/angular2-examples/ repo for
 * more angular app examples that you may copy/paste
 * (The examples may not be updated as quickly. Please open an issue on github for us to update it)
 * For help or questions please contact us at @AngularClass on twitter
 * or our chat on Slack at https://AngularClass.com/slack-join
 */

Body:
While Seth's solution works absolutely fine as it is, I modified the collapsing logic. Instead of using the click event, I subscribe to the router events to collapse the menu only after successful navigation.

export class NavMenuComponent implements OnDestroy {
    public isCollapsed: boolean = true;
    private subscription: Subscription;

    constructor(private router: Router) {
        this.subscription = this.router.events.subscribe(s => {
            if (s instanceof NavigationEnd) {
                this.isCollapsed = true;
            }
        });
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}


问:
What is the verifier in DotNetOpenAuth's DesktopConsumer ProcessUserAuthorization?
I am new to DotNetOpenAuth and I can't find what value to use as the verifier in ProcessUserAuthorization.

What I want to achieve is to log in with my user credentials into an application (called UserVoice) that uses OAuth. Here's what my code looks like:

```<code>string requestToken;
var authorizeUri = consumer.RequestUserAuthorization(new Dictionary<string, string>(), null, out requestToken).AbsoluteUri;
var verifier = "???";
var accessToken = consumer.ProcessUserAuthorization(requestToken, verifier).AccessToken;
consumer.PrepareAuthorizedRequest(endpoint, accessToken, data).GetResponse();
</code>```

I tried to use my username, my password, my consumer key, my consumer secret, but nothing seems to work. Does someone know which value I should use as the verifier?

Thanks

答:
The verifier is also used when the Authorization is done via WebAPI and you do not have a redirect displayed in a browser. In this you just send your AuthentificationRequest via code and get the verifier as a json-string without any user interaction.

In this case the process (for OAuth 1.0) looks as follows:

```<code>    public void AccessAPI ()
    {
        InMemoryOAuthTokenManager tokenManager = InMemoryOAuthTokenManager(YOUR_CLIENT_KEY, YOUR_CLIENT_SECRET);
        var consumer = new DesktopConsumer(GetAuthServerDescription(), tokenManager);

            // Get Request token
            string requestToken;
            var parameters = new Dictionary<string, string>();
            parameters["email"] = "foo";
            parameters["password"] = "bar";
            Uri authorizationUrl = consumer.RequestUserAuthorization(null, parameters, out requestToken);

            // Authorize and get a verifier (No OAuth Header necessary for the API I wanted to access)
            var request = WebRequest.Create(authorizationUrl) as HttpWebRequest;
            request.Method = "Get";
            request.Accept = "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2";
            var response = request.GetResponse() as HttpWebResponse;
            string verifier = new StreamReader(response.GetResponseStream()).ReadToEnd().Split('=')[1]; //Irgendwie will Json nicht parsen

            // Use verifier to get the final AccessToken
            AuthorizedTokenResponse authorizationResponse = consumer.ProcessUserAuthorization(requestToken, verifier);
            string accessToken = authorizationResponse.AccessToken;

            // Access Ressources
            HttpDeliveryMethods resourceHttpMethod = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest;
            var resourceEndpoint = new MessageReceivingEndpoint("https://api.discovergy.com/public/v1/meters", resourceHttpMethod);
            using (IncomingWebResponse resourceResponse = consumer.PrepareAuthorizedRequestAndSend(resourceEndpoint, accessToken))
            {
                string result = resourceResponse.GetResponseReader().ReadToEnd();
                dynamic content = JObject.Parse(result);
            }
    }

    private ServiceProviderDescription GetAuthServerDescription()
    {
        var authServerDescription = new ServiceProviderDescription();
        authServerDescription.RequestTokenEndpoint = new MessageReceivingEndpoint(YOUR_REQUEST_ENDPOINT, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
        authServerDescription.UserAuthorizationEndpoint = new MessageReceivingEndpoint(YOUR_AUTHORIZATION_ENDPOINT, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
        authServerDescription.AccessTokenEndpoint = new MessageReceivingEndpoint(YOUR_TOKEN_ENDPOINT, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
        authServerDescription.ProtocolVersion = ProtocolVersion.V10;
        authServerDescription.TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() };
        return authServerDescription;
    }
</code>```

Body:
I am new to DotNetOpenAuth and I can't find what value to use as the verifier in ProcessUserAuthorization.

What I want to achieve is to log in with my user credentials into an application (called UserVoice) that uses OAuth. Here's what my code looks like:

string requestToken;
var authorizeUri = consumer.RequestUserAuthorization(new Dictionary<string, string>(), null, out requestToken).AbsoluteUri;
var verifier = "???";
var accessToken = consumer.ProcessUserAuthorization(requestToken, verifier).AccessToken;
consumer.PrepareAuthorizedRequest(endpoint, accessToken, data).GetResponse();

I tried to use my username, my password, my consumer key, my consumer secret, but nothing seems to work. Does someone know which value I should use as the verifier?

Thanks

Body:
The verifier is also used when the Authorization is done via WebAPI and you do not have a redirect displayed in a browser. In this you just send your AuthentificationRequest via code and get the verifier as a json-string without any user interaction.

In this case the process (for OAuth 1.0) looks as follows:

    public void AccessAPI ()
    {
        InMemoryOAuthTokenManager tokenManager = InMemoryOAuthTokenManager(YOUR_CLIENT_KEY, YOUR_CLIENT_SECRET);
        var consumer = new DesktopConsumer(GetAuthServerDescription(), tokenManager);

            // Get Request token
            string requestToken;
            var parameters = new Dictionary<string, string>();
            parameters["email"] = "foo";
            parameters["password"] = "bar";
            Uri authorizationUrl = consumer.RequestUserAuthorization(null, parameters, out requestToken);

            // Authorize and get a verifier (No OAuth Header necessary for the API I wanted to access)
            var request = WebRequest.Create(authorizationUrl) as HttpWebRequest;
            request.Method = "Get";
            request.Accept = "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2";
            var response = request.GetResponse() as HttpWebResponse;
            string verifier = new StreamReader(response.GetResponseStream()).ReadToEnd().Split('=')[1]; //Irgendwie will Json nicht parsen

            // Use verifier to get the final AccessToken
            AuthorizedTokenResponse authorizationResponse = consumer.ProcessUserAuthorization(requestToken, verifier);
            string accessToken = authorizationResponse.AccessToken;

            // Access Ressources
            HttpDeliveryMethods resourceHttpMethod = HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest;
            var resourceEndpoint = new MessageReceivingEndpoint("https://api.discovergy.com/public/v1/meters", resourceHttpMethod);
            using (IncomingWebResponse resourceResponse = consumer.PrepareAuthorizedRequestAndSend(resourceEndpoint, accessToken))
            {
                string result = resourceResponse.GetResponseReader().ReadToEnd();
                dynamic content = JObject.Parse(result);
            }
    }

    private ServiceProviderDescription GetAuthServerDescription()
    {
        var authServerDescription = new ServiceProviderDescription();
        authServerDescription.RequestTokenEndpoint = new MessageReceivingEndpoint(YOUR_REQUEST_ENDPOINT, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
        authServerDescription.UserAuthorizationEndpoint = new MessageReceivingEndpoint(YOUR_AUTHORIZATION_ENDPOINT, HttpDeliveryMethods.GetRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
        authServerDescription.AccessTokenEndpoint = new MessageReceivingEndpoint(YOUR_TOKEN_ENDPOINT, HttpDeliveryMethods.PostRequest | HttpDeliveryMethods.AuthorizationHeaderRequest);
        authServerDescription.ProtocolVersion = ProtocolVersion.V10;
        authServerDescription.TamperProtectionElements = new ITamperProtectionChannelBindingElement[] { new HmacSha1SigningBindingElement() };
        return authServerDescription;
    }


问:
How to apply Excel settings only to a range using Epplus
For the values i=4 and i=6, following will apply background color as LightGrey to the entire 4th and 6th rows. Question: Are there any ways so we change the Background color (or any style for that matter) of a row within certain range, say, all the rows from 1st column to the 10th column?

```<code>int i;
ExcelRow rowRange = ws.Row(i);
ExcelFill RowFill = rowRange.Style.Fill;
RowFill.PatternType = ExcelFillStyle.Solid;
RowFill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);
</code>```

答:
Instead of using ws.Row(rowNumber) use

```<code>var firstColumn =  1;
var lastColumn  = 10;
var rowRange    = ws.Cells[rowNumber, firstColumn, rowNumber, lastColumn];
//now do styling on rowRange
</code>```

rowRange will contain references to all the cells in the rectangle defined by the values you passed to it.

Body:
For the values i=4 and i=6, following will apply background color as LightGrey to the entire 4th and 6th rows. Question: Are there any ways so we change the Background color (or any style for that matter) of a row within certain range, say, all the rows from 1st column to the 10th column?

int i;
ExcelRow rowRange = ws.Row(i);
ExcelFill RowFill = rowRange.Style.Fill;
RowFill.PatternType = ExcelFillStyle.Solid;
RowFill.BackgroundColor.SetColor(System.Drawing.Color.LightGray);

Body:
Instead of using ws.Row(rowNumber) use

var firstColumn =  1;
var lastColumn  = 10;
var rowRange    = ws.Cells[rowNumber, firstColumn, rowNumber, lastColumn];
//now do styling on rowRange

rowRange will contain references to all the cells in the rectangle defined by the values you passed to it.


答:
Check out this JSFiddle and see if it answered the question. Just need to float all left.</p>

```<code>float: left;
width:30%;
</code>```

Body:
I want three divs to be centered in the mid. In the end it should look like this

now my problem. In my css I used the float keyword but it seems this does not work for sure. The divs still split up.

As you can see in the following code example the containers are getting weird.

Would be awesome if someone could help me out there!

#selectionElementContainer {
  height: 70%;
  width: 100%;
  margin-top: 50px;
}

#selectionElementLeft {
  float: left;
}

#selectionElementCenter {
  margin: 0 auto;
}

#selectionElementRight {
  float: right;
}

.selectionElementImage {
  cursor: default;
  text-align: center;
  margin-top: 10px;
}

.selectionElementHeader {
  cursor: default;
  text-align: center;
  font-size: 30px;
  margin-top: 30px;
  color: #333f4b;
}

.selectionElementText {
  cursor: default;
  text-align: center;
  margin-top: 20px;
  font-size: 18px;
  color: #4c545c;
}

.selectionElementLinkContainer {
  cursor: default;
  margin-top: 10px;
}

.selectionElementBtn {
  text-decoration: none;
  text-align: center;
  cursor: pointer;
  border: none;
  font-size: 18px;
  background-color: white;
  color: #1bbee7;
  transition: 0.5s;
}

.selectionElementBtn:hover {
  color: #a4d662;
  transition: 0.5s;
}

          Title

          Text

          <button class="selectionElementBtn">Link</button>

          Title

          Text

          <button class="selectionElementBtn">Link</button>

          Title

          Text

          <button class="selectionElementBtn">Link</button>

Body:
Check out this JSFiddle and see if it answered the question. Just need to float all left.

float: left;
width:30%;


问:
ARM Cache behaviour: is "Clean" or "Invalidate" the correct command to flush cache memory?
This is probably a dumb question, but I'm a bit stuck on the wording of the ARM CMSIS Cache manipulation functions.

The ARM CMSIS exposes functions that can "clean" cache, functions that can "invalidate" cache, and a set of functions that do both.

What these actually do is not clear, and the arm documentation is frankly confusing me:

You can invalidate the whole data cache (flush data cache) in one operation without writing back dirty data.

You can invalidate individual lines without writing back any dirty data (flush data cache single entry).

You can perform cleaning on a line-by-line basis. The data is only written back through the write buffer when a dirty line is
  encountered, and the cleaned line remains in the cache (clean data
  cache single entry). You can clean cache lines using either their
  index within the data cache, or their address within memory.

You can clean and flush individual lines in one operation, using either their index within the data cache, or their address within
  memory.

My understanding is that "flushing" data in cache will result in it being written back to main memory, and "invalidating" data in cache will cause the processor to re-read the main memory on the next attempt to access the data in question.

However, the ARM docs seem to be be implying that a flush operation is actually an invalidation operation, and what I've been thinking is a flush operation is actually a "clean" operation.

I assume I'm just grossly misinterpreting the documentation. Can someone point me in the right direction?

I'm specifically developing for a cortex M7, if it's relevant.

答:
from the armv7-m ARM ARM they have this text.

The definitions of these operations are:

Clean

A cache clean operation ensures that updates made by an observer that
  controls the cache are made visible to other observers that can access
  memory at the point to which the operation is performed. Once the
  Clean has completed, the new memory values are guaranteed to be
  visible to the point to which the operation is performed, for example
  to the point of unification. The cleaning of a cache entry from a
  cache can overwrite memory that has been written by another observer
  only if the entry contains a location that has been written to by an
  observer in the shareability domain of that memory location.

Invalidate

A cache invalidate operation ensures that updates made visible by
  observers that access memory at the point to which the invalidate is
  defined are made visible to an observer that controls the cache. This
  might result in the loss of updates to the locations affected by the
  invalidate operation that have been written by observers that access
  the cache. If the address of an entry on which the invalidate operates
  does not have a Normal Cacheable attribute, or if the cache is
  disabled, then an invalidate operation also ensures that this address
  is not present in the cache.

I read that as saying a clean will take the items in that cache that have not been saved to the next level memory and will write those out (some folks like myself call a flush).  Invalidate doest care if there are unwritten values or not, it prepares the cache as if there are no values to be saved, ready to accept new addresses and data.

Thats how I read it...


问:
Prevent a user from closing a browser window using "X"?
Can I tell, using javascript, whether a user has clicked on the "X" icon on a browser dialog, or the "OK"/"Cancel" buttons? I have code I need to run when the window closes, but it will only run when OK or Cancel are clicked.

I currently capture the onunload event of the window. How can i accomplish this?

```<code>window.onunload = function() { alert("unloading"); }
</code>```

答: What about if he does ALT + F4?</p>

OwnerDisplayName: Pwninstein

Body:
Can I tell, using javascript, whether a user has clicked on the "X" icon on a browser dialog, or the "OK"/"Cancel" buttons? I have code I need to run when the window closes, but it will only run when OK or Cancel are clicked.

I currently capture the onunload event of the window. How can i accomplish this?

window.onunload = function() { alert("unloading"); }

Body: What about if he does ALT + F4?

OwnerDisplayName: SQLMenace


问:
XSLT Formatting to remove empty columns (And the headers)
I have a database field I am pulling xml out of. This field contains the content from multiple XML feeds of which I need two. I am displaying the XML on a page and using XSLT to format it.

My issue is that there could be up to 40 elements per message in the DB, of that I am looking for about 30. However, not all messages will have all 30. I need help figuring out how to remove a column if there is no data to display.

If I can use XSLT then great, if it is JavaScript(Jquery) then that is fine too. There will never be more then one row and one header at a time.

Here is a sample of the XML

```<code><MessageToUser>
  <Name>Bob</Name>
  <MessageType>Text Message</MessageType>
  <MessageID>121223</MessageID>
  <ResponseTo />
  <Message>Call Me Please </Message>
  <OfficePhone>555-555-1212</OfficePhone>
  <CellPhone>555-555-5555</CellPhone>
</MessageToUser>
</code>```

And here is the XSL I am using

```<code><xsl:template match="/">
<html>
<head>
  <style type="text/css">
    .Header{min-width: 100px;background-color:#9acddd;}
  </style>
</head>
<body>
  <table border="1">
    <tr>
        <th class="Header">Name</th>
        <th class="Header">Message</th>
        <th class="Header">Cell Phone</th>
        <th class="Header">Office Phone</th>
        <th class="Header">Message Type</th>
        <th class="Header">Message Time</th>
        <th class="Header">Message ID</th>
      </tr>
      <xsl:for-each select="MessageFromUser">
        <tr>
          <td><xsl:value-of select="Name" /></td>
          <td><xsl:value-of select="Message" /></td>
          <td><xsl:value-of select="CellPhone" /></td>
          <td><xsl:value-of select="OfficePhone" /></td>
          <td><xsl:value-of select="MessageType" /></td>
          <td><xsl:value-of select="MessageTime" /></td>
          <td><xsl:value-of select="MessageID" /></td>
        </tr>
      </xsl:for-each>
      <xsl:for-each select="MessageToUser">
        <tr>
          <td><xsl:value-of select="Name" /></td>
          <td><xsl:value-of select="Message" /></td>
          <td><xsl:value-of select="CellPhone" /></td>
          <td><xsl:value-of select="OfficePhone" /></td>
          <td><xsl:value-of select="MessageType" /></td>
          <td><xsl:value-of select="MessageTime" /></td>
          <td><xsl:value-of select="MessageID" /></td>
        </tr>
      </xsl:for-each>
    </table>
 </body>
</code>```

Using this XML MessageTime is blank and that column should be removed.

Thanks in advance for any help.

答:
This transformation:

```<code><xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my" exclude-result-prefixes="my" >
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <my:Layout>
  <html>
   <head>
      <style type="text/css">
        .Header{min-width: 100px;background-color:#9acddd;}
      </style>
   </head>
     <body>
      <table border="1">
        <tr>
            <header name="Name">Name</header>
            <header name="Message">Message</header>
            <header name="CellPhone">Cell Phone</header>
            <header name="OfficePhone">Office Phone</header>
            <header name="MessageType">Message Type</header>
            <header name="MessageTime">Message Time</header>
            <header name="MessageID">Message ID</header>
        </tr>
        <every select="MessageFromUser">
         <tr>
            <Name/>
            <Message/>
            <CellPhone/>
            <OfficePhone/>
            <MessageType/>
            <MessageTime/>
            <MessageID/>
         </tr>
        </every>
        <every select="MessageToUser">
         <tr>
            <Name/>
            <Message/>
            <CellPhone/>
            <OfficePhone/>
            <MessageType/>
            <MessageTime/>
            <MessageID/>
         </tr>
        </every>
       </table>
      </body>
   </html>
 </my:Layout>

 <xsl:variable name="vLayout" select="document('')/*/my:Layout/*"/>
 <xsl:variable name="vDoc" select="/"/>

 <xsl:template match="node()|@*">
   <xsl:param name="pContextNode"/>
     <xsl:copy>
       <xsl:apply-templates select="node()|@*">
       <xsl:with-param name="pContextNode" select="$pContextNode"/>
       </xsl:apply-templates>
     </xsl:copy>
 </xsl:template>

 <xsl:template match=
  "Name|Message|CellPhone|OfficePhone|MessageType|MessageTime|MessageID">
  <xsl:param name="pContextNode"/>

  <xsl:if test="not($vDoc/*/*[not(*[name()=name(current())])])">
    <td><xsl:value-of select="$pContextNode/*[name()=name(current())]"/></td>
  </xsl:if>

 </xsl:template>

 <xsl:template match="/*">
  <xsl:apply-templates select="$vLayout"/>
 </xsl:template>

 <xsl:template match="header">
  <xsl:if test="not($vDoc/*/*[not(*[name()=current()/@name])])">
    <th class="Header"><xsl:value-of select="."/></th>
  </xsl:if>
 </xsl:template>

 <xsl:template match="every">
   <xsl:variable name="vLayoutTop" select="."/>
   <xsl:for-each select="$vDoc/*/*[name()=current()/@select]">
    <xsl:apply-templates select="$vLayoutTop/*">
     <xsl:with-param name="pContextNode" select="."/>
    </xsl:apply-templates>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>
</code>```

when applied on this XML document (the provided one and added MessageFromUser):

```<code><Messages>
    <MessageFromUser>
        <Name>Bob</Name>
        <MessageType>Text Message</MessageType>
        <MessageID>121223</MessageID>
        <ResponseTo />
        <Message>Call Me Please </Message>
        <OfficePhone>555-555-1212</OfficePhone>
        <CellPhone>555-555-5555</CellPhone>
    </MessageFromUser>
    <MessageToUser>
        <Name>Bob</Name>
        <MessageType>Text Message</MessageType>
        <MessageID>121223</MessageID>
        <ResponseTo />
        <Message>Call Me Please </Message>
        <OfficePhone>555-555-1212</OfficePhone>
        <CellPhone>555-555-5555</CellPhone>
    </MessageToUser>
</Messages>
</code>```

produces the wanted output, in which the empty column 1MessageTime` is not displayed:

```<code><html xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my">
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <style type="text/css">
        .Header{min-width: 100px;background-color:#9acddd;}
      </style></head>
   <body>
      <table border="1">
         <tr>
            <th class="Header">Name</th>
            <th class="Header">Message</th>
            <th class="Header">Cell Phone</th>
            <th class="Header">Office Phone</th>
            <th class="Header">Message Type</th>
            <th class="Header">Message ID</th>
         </tr>
         <tr>
            <td>Bob</td>
            <td>Call Me Please </td>
            <td>555-555-5555</td>
            <td>555-555-1212</td>
            <td>Text Message</td>
            <td>121223</td>
         </tr>
         <tr>
            <td>Bob</td>
            <td>Call Me Please </td>
            <td>555-555-5555</td>
            <td>555-555-1212</td>
            <td>Text Message</td>
            <td>121223</td>
         </tr>
      </table>
   </body>
</html>
</code>```

Do note:

A better design (fill-in-the-blanks) is used, that separates the code and presentation. This is one of the most fundamental and powerful XSLT design (fill-in-the blanks) pattern.

This design allows the same code to be used with different layouts (passed as parameter) to produce completely different-looking results.

The identity rule copies "as-is" all non-variable nodes of the Layout.

We override the identity rule only for the "variable" parts of the Layout.

The auxhiliary element every specifies that iterative processing should be performed.

In a practical application the <my:Layout> element will reside as a separate XML document in a separate file and in this case one must replace document('')/* with document('theFileURI'). The greatest generality is achieved when this file URI is passed as a parameter to the XSLT transformation.

The condition tested in order to process only fields/columns that appear at least once at least in one record is (for headers):

not($vDoc/*/*[not(*[name()=current()/@name])])

A similar condition for cells is:

not($vDoc/*/*[not(*[name()=name(current())])])

Body:
I have a database field I am pulling xml out of. This field contains the content from multiple XML feeds of which I need two. I am displaying the XML on a page and using XSLT to format it.

My issue is that there could be up to 40 elements per message in the DB, of that I am looking for about 30. However, not all messages will have all 30. I need help figuring out how to remove a column if there is no data to display.

If I can use XSLT then great, if it is JavaScript(Jquery) then that is fine too. There will never be more then one row and one header at a time.

Here is a sample of the XML

<MessageToUser>
  <Name>Bob</Name>
  <MessageType>Text Message</MessageType>
  <MessageID>121223</MessageID>
  <ResponseTo />
  <Message>Call Me Please </Message>
  <OfficePhone>555-555-1212</OfficePhone>
  <CellPhone>555-555-5555</CellPhone>
</MessageToUser>

And here is the XSL I am using

<xsl:template match="/">

        Name
        Message
        Cell Phone
        Office Phone
        Message Type
        Message Time
        Message ID

      <xsl:for-each select="MessageFromUser">

          <xsl:value-of select="Name" />
          <xsl:value-of select="Message" />
          <xsl:value-of select="CellPhone" />
          <xsl:value-of select="OfficePhone" />
          <xsl:value-of select="MessageType" />
          <xsl:value-of select="MessageTime" />
          <xsl:value-of select="MessageID" />

      </xsl:for-each>
      <xsl:for-each select="MessageToUser">

          <xsl:value-of select="Name" />
          <xsl:value-of select="Message" />
          <xsl:value-of select="CellPhone" />
          <xsl:value-of select="OfficePhone" />
          <xsl:value-of select="MessageType" />
          <xsl:value-of select="MessageTime" />
          <xsl:value-of select="MessageID" />

      </xsl:for-each>

Using this XML MessageTime is blank and that column should be removed.

Thanks in advance for any help.

Body:
This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:my="my:my" exclude-result-prefixes="my" >
 <xsl:output omit-xml-declaration="yes" indent="yes"/>
 <xsl:strip-space elements="*"/>

 <my:Layout>
  <html>
   <head>
      <style type="text/css">
        .Header{min-width: 100px;background-color:#9acddd;}
      </style>
   </head>
     <body>
      <table border="1">
        <tr>
            <header name="Name">Name</header>
            <header name="Message">Message</header>
            <header name="CellPhone">Cell Phone</header>
            <header name="OfficePhone">Office Phone</header>
            <header name="MessageType">Message Type</header>
            <header name="MessageTime">Message Time</header>
            <header name="MessageID">Message ID</header>
        </tr>
        <every select="MessageFromUser">
         <tr>
            <Name/>
            <Message/>
            <CellPhone/>
            <OfficePhone/>
            <MessageType/>
            <MessageTime/>
            <MessageID/>
         </tr>
        </every>
        <every select="MessageToUser">
         <tr>
            <Name/>
            <Message/>
            <CellPhone/>
            <OfficePhone/>
            <MessageType/>
            <MessageTime/>
            <MessageID/>
         </tr>
        </every>
       </table>
      </body>
   </html>
 </my:Layout>

 <xsl:variable name="vLayout" select="document('')/*/my:Layout/*"/>
 <xsl:variable name="vDoc" select="/"/>

 <xsl:template match="node()|@*">
   <xsl:param name="pContextNode"/>
     <xsl:copy>
       <xsl:apply-templates select="node()|@*">
       <xsl:with-param name="pContextNode" select="$pContextNode"/>
       </xsl:apply-templates>
     </xsl:copy>
 </xsl:template>

 <xsl:template match=
  "Name|Message|CellPhone|OfficePhone|MessageType|MessageTime|MessageID">
  <xsl:param name="pContextNode"/>

  <xsl:if test="not($vDoc/*/*[not(*[name()=name(current())])])">
    <td><xsl:value-of select="$pContextNode/*[name()=name(current())]"/></td>
  </xsl:if>

 </xsl:template>

 <xsl:template match="/*">
  <xsl:apply-templates select="$vLayout"/>
 </xsl:template>

 <xsl:template match="header">
  <xsl:if test="not($vDoc/*/*[not(*[name()=current()/@name])])">
    <th class="Header"><xsl:value-of select="."/></th>
  </xsl:if>
 </xsl:template>

 <xsl:template match="every">
   <xsl:variable name="vLayoutTop" select="."/>
   <xsl:for-each select="$vDoc/*/*[name()=current()/@select]">
    <xsl:apply-templates select="$vLayoutTop/*">
     <xsl:with-param name="pContextNode" select="."/>
    </xsl:apply-templates>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

when applied on this XML document (the provided one and added MessageFromUser):

<Messages>
    <MessageFromUser>
        <Name>Bob</Name>
        <MessageType>Text Message</MessageType>
        <MessageID>121223</MessageID>
        <ResponseTo />
        <Message>Call Me Please </Message>
        <OfficePhone>555-555-1212</OfficePhone>
        <CellPhone>555-555-5555</CellPhone>
    </MessageFromUser>
    <MessageToUser>
        <Name>Bob</Name>
        <MessageType>Text Message</MessageType>
        <MessageID>121223</MessageID>
        <ResponseTo />
        <Message>Call Me Please </Message>
        <OfficePhone>555-555-1212</OfficePhone>
        <CellPhone>555-555-5555</CellPhone>
    </MessageToUser>
</Messages>

produces the wanted output, in which the empty column 1MessageTime` is not displayed:

<html xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:my="my:my">
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
   <style type="text/css">
        .Header{min-width: 100px;background-color:#9acddd;}
      </style></head>
   <body>
      <table border="1">
         <tr>
            <th class="Header">Name</th>
            <th class="Header">Message</th>
            <th class="Header">Cell Phone</th>
            <th class="Header">Office Phone</th>
            <th class="Header">Message Type</th>
            <th class="Header">Message ID</th>
         </tr>
         <tr>
            <td>Bob</td>
            <td>Call Me Please </td>
            <td>555-555-5555</td>
            <td>555-555-1212</td>
            <td>Text Message</td>
            <td>121223</td>
         </tr>
         <tr>
            <td>Bob</td>
            <td>Call Me Please </td>
            <td>555-555-5555</td>
            <td>555-555-1212</td>
            <td>Text Message</td>
            <td>121223</td>
         </tr>
      </table>
   </body>
</html>

Do note:

A better design (fill-in-the-blanks) is used, that separates the code and presentation. This is one of the most fundamental and powerful XSLT design (fill-in-the blanks) pattern.

This design allows the same code to be used with different layouts (passed as parameter) to produce completely different-looking results.

The identity rule copies "as-is" all non-variable nodes of the Layout.

We override the identity rule only for the "variable" parts of the Layout.

The auxhiliary element every specifies that iterative processing should be performed.

In a practical application the <my:Layout> element will reside as a separate XML document in a separate file and in this case one must replace document('')/* with document('theFileURI'). The greatest generality is achieved when this file URI is passed as a parameter to the XSLT transformation.

The condition tested in order to process only fields/columns that appear at least once at least in one record is (for headers):

not($vDoc/*/*[not(*[name()=current()/@name])])

A similar condition for cells is:

not($vDoc/*/*[not(*[name()=name(current())])])


问:
R Shiny in Memory Application or noSQL
I am running a tiny web app using R's shiny framework. The tool doesn't do that much. It's just filtering data frames with given parameters from the UI.
The problem I have now is the following. If a user is accessing the app via http it takes a long time to start the App. Since the data, which I load in the global.R, is pretty big (~5GB). After an initial start, the App is running smooth, also when re-accessing within a given time (the app seems to be completely in memory, for some minutes).
Since I got enough memory available, and my data doesn't change by user interaction, I am asking myself if I could keep the complete App in memory. Is it possible to force this? My server is running centOS 6. Also the problem isn't the file system, hard disk, etc. - I created a ram disk to load the data from, but the performance increase is marginal. So the bottle neck seems to be R, when processing the data.

Now I got two ideas, which may overcome the problem.

Just as I mentioned, is it possible to keep the complete app in memory?

Don't save the Data as R objects, instead use a fast noSQL DB e.g. Redis wich is in memory

May one of you has some experience when loading bigger data. I would be thankful if could get a discussion going. If it is possible, I would like to avoid external software, like Redis, to keep everything as simple as possible.

With all the best,

Mario

答:
You can set the timeout to be a longer value. I'm not sure if infinite value(or long enough value) is possible.

Other ways not involving a database may be:

use data.table fread if you read from csv. This can be several times faster than read.csv. Specify the column classes can further improve speed.

Or use binary format .RDS which should be fast and smaller in size thus quicker to read.

If you are using .RDS .Rdata already there is not much to do in this aspect.

Title: R Shiny in Memory Application or noSQL


问:
C++ linked list weird outputs
So i've been trying to code a linked list. When i debug or if i put one more print statement like this;

```<code>intlist.add_node(7);
intlist.print_list();
intlist.add_node(8);
</code>```

It works fine prints;

```<code>5
7
5
7
8
</code>```

But if i remove that statement, it only prints three eights. Same goes for debugging, it seems working but if i just run it doesn't. I didn't understand what is wrong.
Here's my main;

```<code>int main(){
  Linked_list intlist;
  intlist.add_node(5);
  intlist.add_node(7);
  intlist.print_list();
  intlist.add_node(8);
  intlist.print_list();
  return 0;
}
</code>```

header;

```<code>class Linked_list{
public:
  Linked_list();

  void add_node(int data);
  void remove_node(int data);
  int get_data(int index);
  void print_list();

  struct Node {
      int data;
      Node* next;
  };

  Node* head;
  int lenght;
};
</code>```

And header's source file;

```<code>Linked_list::Linked_list(){
  head = 0;
  lenght = 0;
}

void Linked_list::add_node(int data){
  Node* newnode = new Node;
  newnode->data = data;
  newnode->next = NULL;
  if (head == 0) {head = newnode; lenght = 1; return;}
  else{
      Node* temp = new Node;
      temp = head;
      while (temp->next != NULL){
          temp = temp->next;

      }
      lenght++;
      temp->next = newnode;
      delete temp;
  }
}

void Linked_list::remove_node(int data){
    return;
}

int Linked_list::get_data(int index){
    return 0;
}

void Linked_list::print_list(){
    if (head == 0) {std::cout << "List is empty!!" << std::endl;
    return;}
    else{
        Node* ptr = new Node;
        ptr = head;
        for (int i = lenght; i > 0; i--){
            std::cout << ptr->data << std::endl;
            ptr = ptr->next;
        }
    }
}
</code>```

答:
Your add_node function should be:

```<code>void Linked_list::add_node(int data) {

  Node* newnode = new Node;
  newnode->data = data;
  newnode->next = NULL;

  if (head == 0) {
      head = newnode;
      lenght = 1;
      return;
  } else {
      //Node* temp = new Node;
      Node *temp = head;
      while (temp->next != NULL) {
          temp = temp->next;
      }

      lenght++;
      temp->next = newnode;
      //delete temp;
  }
}
</code>```

You don't need to create a new Node object since you are only looking to reference head. delete temp actually deletes the content of the address previously pointed to by temp, which is the last element of your list.

Title: C++ linked list weird outputs

Body:
So i've been trying to code a linked list. When i debug or if i put one more print statement like this;

intlist.add_node(7);
intlist.print_list();
intlist.add_node(8);

It works fine prints;

5
7
5
7
8

But if i remove that statement, it only prints three eights. Same goes for debugging, it seems working but if i just run it doesn't. I didn't understand what is wrong.
Here's my main;

int main(){
  Linked_list intlist;
  intlist.add_node(5);
  intlist.add_node(7);
  intlist.print_list();
  intlist.add_node(8);
  intlist.print_list();
  return 0;
}

header;

class Linked_list{
public:
  Linked_list();

  void add_node(int data);
  void remove_node(int data);
  int get_data(int index);
  void print_list();

  struct Node {
      int data;
      Node* next;
  };

  Node* head;
  int lenght;
};

And header's source file;

Linked_list::Linked_list(){
  head = 0;
  lenght = 0;
}

void Linked_list::add_node(int data){
  Node* newnode = new Node;
  newnode->data = data;
  newnode->next = NULL;
  if (head == 0) {head = newnode; lenght = 1; return;}
  else{
      Node* temp = new Node;
      temp = head;
      while (temp->next != NULL){
          temp = temp->next;

      }
      lenght++;
      temp->next = newnode;
      delete temp;
  }
}

void Linked_list::remove_node(int data){
    return;
}

int Linked_list::get_data(int index){
    return 0;
}

void Linked_list::print_list(){
    if (head == 0) {std::cout << "List is empty!!" << std::endl;
    return;}
    else{
        Node* ptr = new Node;
        ptr = head;
        for (int i = lenght; i > 0; i--){
            std::cout << ptr->data << std::endl;
            ptr = ptr->next;
        }
    }
}

Body:
Your add_node function should be:

void Linked_list::add_node(int data) {

  Node* newnode = new Node;
  newnode->data = data;
  newnode->next = NULL;

  if (head == 0) {
      head = newnode;
      lenght = 1;
      return;
  } else {
      //Node* temp = new Node;
      Node *temp = head;
      while (temp->next != NULL) {
          temp = temp->next;
      }

      lenght++;
      temp->next = newnode;
      //delete temp;
  }
}

You don't need to create a new Node object since you are only looking to reference head. delete temp actually deletes the content of the address previously pointed to by temp, which is the last element of your list.


问:
Spring Rest template trying to parse JSON Response and model it in form of getters and setters
I have following json to parse in spring rest template.I could not see how I could do it.I have never seen such a json, but this is a valid json response.
THis is what I have tried :

```<code> @jsonignoreuknown(true)
class smsresponse {

    private String status;
    private String message;
    private Data data;
    getters/setters

    }

    class Data {

    private String group_id;
    private Map<String,SummaryPOJO> map;
    getters/setters

    }

    class SummaryPOJO {

    private String id;
    private String mobile;
    private String status;
    rest of fields
    getteers/setters

    }

restTemplate.exchange(url,method,null,some paramterhere)
</code>```

Is it right approach and what rest template API should I call to achieve this.

```<code> {
        "status": "OK",
        "data":
        {
            "group_id":zzz,
            "0":
            {
                "id": "wewew-1wewewew",
                "customid": "1",
                "customid1": "",
                "customid2": "",
                "mobile": "9190********",
                "status": "AWAITED-DLR",
                }
               "1":
                {
                "id": "2758-2",
                "customid": "2",
                "customid1": "",
                "customid2": "",
                "mobile": "9190********",
                "status": "AWAITED-DLR",
                }
              }
                ...
        }
        "message": "Campaign Submitted successfully"
    }
</code>```

答:
If you use spring boot RestTemplate with for example maven you automatically have jackson as dependency which maps your response object without any further code. Calling it correctly and specifying your expected class smsresponse and jackson will map it for you. It's much easier to use the methods restTemplate.getForObject(...) or restTemplate.postForObject(...) instead of restTemplate.exchange(...) for GET and POST but that highly depends on your needs. This methods have some limitations regarding setting headers and so on.

The spring documentation provides plenty of good examples:
https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/remoting.html

Body:
I have following json to parse in spring rest template.I could not see how I could do it.I have never seen such a json, but this is a valid json response.
THis is what I have tried :

 @jsonignoreuknown(true)
class smsresponse {

    private String status;
    private String message;
    private Data data;
    getters/setters

    }

    class Data {

    private String group_id;
    private Map<String,SummaryPOJO> map;
    getters/setters

    }

    class SummaryPOJO {

    private String id;
    private String mobile;
    private String status;
    rest of fields
    getteers/setters

    }

restTemplate.exchange(url,method,null,some paramterhere)

Is it right approach and what rest template API should I call to achieve this.

 {
        "status": "OK",
        "data":
        {
            "group_id":zzz,
            "0":
            {
                "id": "wewew-1wewewew",
                "customid": "1",
                "customid1": "",
                "customid2": "",
                "mobile": "9190********",
                "status": "AWAITED-DLR",
                }
               "1":
                {
                "id": "2758-2",
                "customid": "2",
                "customid1": "",
                "customid2": "",
                "mobile": "9190********",
                "status": "AWAITED-DLR",
                }
              }
                ...
        }
        "message": "Campaign Submitted successfully"
    }