问:
jQuery datepicker not submitting
so this is my first try of fiddeling around with ruby and i am trying to do a blog type of entry, where i am given the current date by default and then i can enter text into another textfield.

I created a datepicker, and set the date to select the current date. It automatically shows the current date and when clicking on the field, i can select another, but when submitting the post, the date is not being processed.

If i create a text field and enter the date manually, it works.

This is my _form.html.erb

```<code>    <%= form_for(gym) do |f| %>
  <% if gym.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(gym.errors.count, "error") %> prohibited this gym from being saved:</h2>

      <ul>
      <% gym.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

 <!--  <div class="field", align="center">
    <%= f.label :Date %><br>
    <%= f.text_field :Date %>
  </div> -->

  <div class="input", align="center">
   <%= f.label :Date %>
 <input id="Date" type="text" size="10" >
 <script>
  $( function() {
    $( "#Date" ).datepicker({dateFormat: 'dd.mm.yy', defaultDate: new Date});
    $( "#Date" ).datepicker("setDate", new Date );
   } );
  </script>

</div>

  <div class="field", align="center">
    <%= f.label :Workout %><br>
    <%= f.text_field :Workout, size:"30x10" %>
  </div>

  <div class="actions", align="center">
    <%= f.submit "Submit a  Workout" %>
  </div>
<% end %>
</code>```

This is my new.html.erb

```<code>   <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
<body>
<h1>New Workout</h1>
<p id ="new_one" ><%= render 'form', gym: @gym %>
<p id ="new_two", align="center"><%= link_to 'Back', gyms_path, {:style => 'color:#FFF'} %>
</body>
</code>```

And this is the index.html.erb that displays the data.

```<code><p id="notice"><%= notice %></p>

<body bgcolor="#D6EAF8">

</body>
<h1 align="center">Workouts</h1>

<table  cellpadding="10", align="center" >
  <thead>
    <tr >
      <th>Date</th>
      <th>Workout</th>
      <th colspan="3"></th>
    </tr>
  </thead>

  <tbody bgcolor= "#EBDEF0", align="center">
    <% @gyms.each do |gym| %>
      <tr align="center">
        <td><%= gym.Date %></td>
        <td><%= gym.Workout %></td>
        <td><%= link_to 'Show', gym %></td>
        <td><%= link_to 'Edit', edit_gym_path(gym) %></td>
        <td><%= link_to 'Destroy', gym, method: :delete, data: { confirm: 'Are you sure?'} %></td>
      </tr>
    <% end %>
  </tbody>
</table>

<br>

<p id ="new_work", align="center"><%= link_to 'New Workout', new_gym_path, {:style => 'color:#FFF'}%>
</code>```

答:
When you use form helper to create text_field, rails will create a text field input with id is model_name_field_name

Example: When I create a form for user

```<code><%= form_for(user) do |f| %>
  <%= f.text_field :name %>
<% end %>
</code>```

Rails will create a text field:

```<code><input type="text" id="user_name" name="user[name]">
</code>```

When add datepicker:

```<code>$("#user_name").datepicker({dateFormat: 'dd.mm.yy', defaultDate: new Date})
</code>```

By another way, you also can create a text field input with custom id:

```<code> <%= f.text_field :name, id: "my_input_id" %>
</code>```

And

```<code>$("#my_input_id").datepicker({dateFormat: 'dd.mm.yy', defaultDate: new Date})
</code>```

Hope I can help.

Title: jQuery datepicker not submitting

Body:
so this is my first try of fiddeling around with ruby and i am trying to do a blog type of entry, where i am given the current date by default and then i can enter text into another textfield.

I created a datepicker, and set the date to select the current date. It automatically shows the current date and when clicking on the field, i can select another, but when submitting the post, the date is not being processed.

If i create a text field and enter the date manually, it works.

This is my _form.html.erb

    <%= form_for(gym) do |f| %>
  <% if gym.errors.any? %>

<%= pluralize(gym.errors.count, "error") %> prohibited this gym from being saved:

      <% gym.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

   <%= f.label :Date %>
 <input id="Date" type="text" size="10" >

    <%= f.label :Workout %>

    <%= f.text_field :Workout, size:"30x10" %>

    <%= f.submit "Submit a  Workout" %>

<% end %>

This is my new.html.erb

   <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>

New Workout

<%= render 'form', gym: @gym %>

<%= link_to 'Back', gyms_path, {:style => 'color:#FFF'} %>

And this is the index.html.erb that displays the data.

<%= notice %>

Workouts

      Date
      Workout

    <% @gyms.each do |gym| %>

        <%= gym.Date %>
        <%= gym.Workout %>
        <%= link_to 'Show', gym %>
        <%= link_to 'Edit', edit_gym_path(gym) %>
        <%= link_to 'Destroy', gym, method: :delete, data: { confirm: 'Are you sure?'} %>

    <% end %>

<%= link_to 'New Workout', new_gym_path, {:style => 'color:#FFF'}%>

Body:
When you use form helper to create text_field, rails will create a text field input with id is model_name_field_name

Example: When I create a form for user

<%= form_for(user) do |f| %>
  <%= f.text_field :name %>
<% end %>

Rails will create a text field:

<input type="text" id="user_name" name="user[name]">

When add datepicker:

$("#user_name").datepicker({dateFormat: 'dd.mm.yy', defaultDate: new Date})

By another way, you also can create a text field input with custom id:

 <%= f.text_field :name, id: "my_input_id" %>

And

$("#my_input_id").datepicker({dateFormat: 'dd.mm.yy', defaultDate: new Date})

Hope I can help.


来源: stackexchange

问:
Basic Communications with QSerialPort
I am trying to rig up some basic serial communications in QT
I am getting the port COM19 from QSerialPortInfo, and I speaking successfully to the port via Arduino. However, I cannot get anything back via QT.

```<code>#include "mainwindow.h"
#include <QApplication>
#include <QDebug>
#include <QTextStream>
#include <QFile>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()){
        qDebug() << "Name  :" << info.portName();
        qDebug() << "Description  :" << info.description();
        qDebug() << "Manufactuer :"  << info.manufacturer();

        QSerialPort serial;
        serial.setPort(info);

        if(serial.open(QIODevice::ReadWrite))
            qDebug() << serial.errorString();

            serial.write("M114 \n");

            qDebug() << serial.readAll();

            serial.close();
            // Now we need to send and receive commands

            serial.setPortName("COM19");
            serial.setBaudRate(QSerialPort::Baud57600);
            serial.setDataBits(QSerialPort::Data8);
            serial.setParity(QSerialPort::NoParity);
            serial.setStopBits(QSerialPort::OneStop);
            serial.setFlowControl(QSerialPort::NoFlowControl);

            if(serial.open(QIODevice::ReadWrite)){
                qDebug() << "opened";
              }else{
                qDebug() << "Not opened";
            }
           qDebug() << serial.errorString();

            serial.write("M114 \n");
            qDebug() << serial.readAll();

            serial.close();

    }

    MainWindow w;
    w.show();

    return a.exec();
}
</code>```

As you can see, I am trying a simple connection along the lines of the documentation, and one where I write out all the baud rate information. They throw two different errors.

Like I said, I am connecting via arduino to this same port and having success. Any ideas what's wrong?

```<code>Name  : "COM19"
Description  : "USB Serial (Communication Class, Abstract Control Model)"
Manufactuer : "PJRC.COM, LLC."
"Unknown error"
""
opened
"The handle is invalid."
""
</code>```

Any ideas for what I am doing wrong?

My idea is to send commands to the device, and read them back to the console.

答:
Starting with the tenth port, his name will be \\.\COM10

You can reassign the port to a different number in Device Manager

ContentLicense: CC BY-SA 3.0

Title: Basic Communications with QSerialPort

Body:
I am trying to rig up some basic serial communications in QT
I am getting the port COM19 from QSerialPortInfo, and I speaking successfully to the port via Arduino. However, I cannot get anything back via QT.

#include "mainwindow.h"
#include <QApplication>
#include <QDebug>
#include <QTextStream>
#include <QFile>
#include <QtSerialPort/QSerialPort>
#include <QtSerialPort/QSerialPortInfo>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()){
        qDebug() << "Name  :" << info.portName();
        qDebug() << "Description  :" << info.description();
        qDebug() << "Manufactuer :"  << info.manufacturer();

        QSerialPort serial;
        serial.setPort(info);

        if(serial.open(QIODevice::ReadWrite))
            qDebug() << serial.errorString();

            serial.write("M114 \n");

            qDebug() << serial.readAll();

            serial.close();
            // Now we need to send and receive commands

            serial.setPortName("COM19");
            serial.setBaudRate(QSerialPort::Baud57600);
            serial.setDataBits(QSerialPort::Data8);
            serial.setParity(QSerialPort::NoParity);
            serial.setStopBits(QSerialPort::OneStop);
            serial.setFlowControl(QSerialPort::NoFlowControl);

            if(serial.open(QIODevice::ReadWrite)){
                qDebug() << "opened";
              }else{
                qDebug() << "Not opened";
            }
           qDebug() << serial.errorString();

            serial.write("M114 \n");
            qDebug() << serial.readAll();

            serial.close();

    }

    MainWindow w;
    w.show();

    return a.exec();
}

As you can see, I am trying a simple connection along the lines of the documentation, and one where I write out all the baud rate information. They throw two different errors.

Like I said, I am connecting via arduino to this same port and having success. Any ideas what's wrong?

Name  : "COM19"
Description  : "USB Serial (Communication Class, Abstract Control Model)"
Manufactuer : "PJRC.COM, LLC."
"Unknown error"
""
opened
"The handle is invalid."
""

Any ideas for what I am doing wrong?

My idea is to send commands to the device, and read them back to the console.


问:
Docraptor PDF: How to avoid displaying header in 2nd Page
Im generating PDFs using docraptor API and my pdfs can have multiple pages. I have set the header image for the pdf but it appears on all pages. I need the header in the first page only.

TIA

答: Can you not just set it as normal content at the start of the document, not as a header which is repeated on each page?</p>


问:
Send a message directly from a thread to an object without using the main form
I'm using a 3rd party library that uses a lot of threads.

I've just started using messages to communicate back to the main thread from a thread. It's all working, but using SendMessage the way I describe below seems cumbersome because the main form has to dispatch all the messages. Is there a way to send a message directly to a frame or object, without depending on the main form?

At program startup:

```<code> MyMessageNumber1 :=  RegisterWindowMessage('MyUniqueID1');
 MyMessageNumber2 :=  RegisterWindowMessage('MyUniqueID2');
</code>```

When sending a message without any data, I do:

```<code> SendMessage(Application.MainForm.Handle,  MyMessageNumber1)
</code>```

My main form has this:

```<code>procedure WndProc(var Message: TMessage); override;
if (Message.Msg = MyMessageNumber1)
  ... call a frame or other object's method that handles this particular message
else if (Message.Msg = MyMessageNumber2) then
  ... call another ....
else
  inherited;
</code>```

In summary: the above WndProc has to know far more than I'd prefer about all the messages and who to dispatch them to.

How can I send a message directly from a thread in a way that any object can receive it?

All of these messages have no data associated with them. (We'll get to that some other day!) :-)

TIA

答:
Yes you can. You can use AllocateHWND to allocate a window handle in any object. This handle can be used to send messages to.

But you problem may lie in the SendMessage. If you use PostMessage instead of SendMessage, the call will return immediately. PostMessage does not wait for a message to be handled. So if you don't need the message result, and you don't need to send references to thread-data, you can just use PostMessage.

ContentLicense: CC BY-SA 2.5

Body:
I'm using a 3rd party library that uses a lot of threads.

I've just started using messages to communicate back to the main thread from a thread. It's all working, but using SendMessage the way I describe below seems cumbersome because the main form has to dispatch all the messages. Is there a way to send a message directly to a frame or object, without depending on the main form?

At program startup:

 MyMessageNumber1 :=  RegisterWindowMessage('MyUniqueID1');
 MyMessageNumber2 :=  RegisterWindowMessage('MyUniqueID2');

When sending a message without any data, I do:

 SendMessage(Application.MainForm.Handle,  MyMessageNumber1)

My main form has this:

procedure WndProc(var Message: TMessage); override;
if (Message.Msg = MyMessageNumber1)
  ... call a frame or other object's method that handles this particular message
else if (Message.Msg = MyMessageNumber2) then
  ... call another ....
else
  inherited;

In summary: the above WndProc has to know far more than I'd prefer about all the messages and who to dispatch them to.

How can I send a message directly from a thread in a way that any object can receive it?

All of these messages have no data associated with them. (We'll get to that some other day!) :-)

TIA


问:
C# Regex match and wrap multiple lines
I need to make such text, as example

```<code>Founded in 2008, Stack Overflow sees 40 million visitors each month

|| <b>ID</b> || <b>Column1</b> || <b>Column2</b> ||
| | | |

Stack Overflow Documentation, the largest content expansion since Q&A, launches in July

|| <b>Name</b> || <u>Surname</u> || <u>DoB</u> ||
| | | |

The Developer Story launches in October, giving developers a better way to present their skills
</code>```

look like that

```<code>    Founded in 2008, Stack Overflow sees 40 million visitors each month

<span>|| <b>ID</b> || <b>Column1</b> || <b>Column2</b> ||
| | | |</span>

Stack Overflow Documentation, the largest content expansion since Q&A, launches in July

<span>|| <b>Name</b> || <u>Surname</u> || <u>DoB</u> ||
| | | |
| | | |
</span>

The Developer Story launches in October, giving developers a better way to present their skills
</code>```

If I try such regex

```<code>(
 (
   (^|\r\n|)+(\|{1,2})
  )
  (
    [\s\S]*
  )
  (\|{1,2}
   ($|\r\n|)+
  )
)
</code>```

But its not what I need, it selecting wrong area, you can see it here https://regex101.com/r/0h7gVV/2

Other attempt was look like that

```<code>((^|\r\n{2,}|)+(\|{1,2}))(.*)(\|{1,2}(\r\n{2,}|$|)+)
</code>```

But it ended up selecting each line, you can see the example here https://regex101.com/r/qpwdwj/2

How I should change my regex to make it work in right way?

UPD

Wiktor Stribiżew (thanks to him) in comments told me to try his example, it works good for example above but not for all possilbe cases (example here https://regex101.com/r/PvPsxF/3)

So-called tables can look like that

```<code>|| A | B |
|| c | d |
</code>```

Or that

```<code>| a | b | c |
| d | e | f |
</code>```

UPD2

That's close one https://regex101.com/r/PvPsxF/7 but it has ugly empty space

UPD3

This one is close ( https://regex101.com/r/PvPsxF/8 ), but for this test text

```<code>Stack Overflow Documentation, the largest content expansion since Q&A, launches in July

|| <b>Name</b> || <u>Surname</u> || <u>DoB</u> ||
| | | |

||

| a | b | c | u |

The Developer Story launches in October, giving developers a better way to present their skills

| a | b | c |
| d | e | f |
</code>```

It goes like that

```<code>Stack Overflow Documentation, the largest content expansion since Q&A, launches in July
<span>
|| <b>Name</b> || <u>Surname</u> || <u>DoB</u> ||
| | | |

<!-- not suppose to be wraped up -->
</span><span>||

| a | b | c | u |

</span>The Developer Story launches in October, giving developers a better way to present their skills
<span>
| a | b | c |
| d | e | f |</span>
</code>```

When I am not want to wrap single || apperance within line (it suppose to be ignored in this case)

Screenshot for more example

P.S.

This, let's say, markup below

```<code>|| <b>ID</b> || <b>Column1</b> || <b>Column2</b> ||
| | | |
</code>```

Will be parsed to html to look like table, where || Cell || is stands for header and | cell | stands for regular cell

So, after parsing it gonna be look like

```<code><table>
  <tr>
    <th>ID</th>
    <th>Column1</th>
    <th>Column2</th>
  </tr>
  <tr>
    <td> </td>
    <td> </td>
    <td> </td>
  </tr>
</table>
</code>```

答:
The regex is

```<code>(\|\|?([^|\n\r]+\|\|?)+($|[\r\n]+))+
</code>```

The matching group is $0 (demo).

It works as follows:

```<code>(
  \|\|?         #the line starts with one or two pipes
  (
    [^|\n\r]+   #followed by at least one non-pipe characther
    \|\|?       #and the cell endt with one or two pipes
  )+            #at least one cell, otherwise even the line "||" would be matched
  (
    $           #the text ends (you are NOT in multiline mode)
  |
    [\r\n]+     #or [\r\n] characters are matched (at least one, otherwise would match even "||A|B"), in order to match also the possible following line
  )
)+              #at least one line
</code>```

If you don't want to match spaces/new lines after the "table", just use an a-few-harder regex (demo):

```<code>\|\|?([^|\n\r]+\|\|?)+$([\r\n]+\|\|?([^|\n\r]+\|\|?)+$)*
</code>```

In this last regex remember to use the m flag.

Title: C# Regex match and wrap multiple lines

Body:
I need to make such text, as example

Founded in 2008, Stack Overflow sees 40 million visitors each month

|| ID || Column1 || Column2 ||
| | | |

Stack Overflow Documentation, the largest content expansion since Q&A, launches in July

|| Name || Surname || DoB ||
| | | |

The Developer Story launches in October, giving developers a better way to present their skills

look like that

    Founded in 2008, Stack Overflow sees 40 million visitors each month

|| ID || Column1 || Column2 ||
| | | |

Stack Overflow Documentation, the largest content expansion since Q&A, launches in July

|| Name || Surname || DoB ||
| | | |
| | | |

The Developer Story launches in October, giving developers a better way to present their skills

If I try such regex

(
 (
   (^|\r\n|)+(\|{1,2})
  )
  (
    [\s\S]*
  )
  (\|{1,2}
   ($|\r\n|)+
  )
)

But its not what I need, it selecting wrong area, you can see it here https://regex101.com/r/0h7gVV/2

Other attempt was look like that

((^|\r\n{2,}|)+(\|{1,2}))(.*)(\|{1,2}(\r\n{2,}|$|)+)

But it ended up selecting each line, you can see the example here https://regex101.com/r/qpwdwj/2

How I should change my regex to make it work in right way?

UPD

Wiktor Stribiżew (thanks to him) in comments told me to try his example, it works good for example above but not for all possilbe cases (example here https://regex101.com/r/PvPsxF/3)

So-called tables can look like that

|| A | B |
|| c | d |

Or that

| a | b | c |
| d | e | f |

UPD2

That's close one https://regex101.com/r/PvPsxF/7 but it has ugly empty space

UPD3

This one is close ( https://regex101.com/r/PvPsxF/8 ), but for this test text

Stack Overflow Documentation, the largest content expansion since Q&A, launches in July

|| Name || Surname || DoB ||
| | | |

||

| a | b | c | u |

The Developer Story launches in October, giving developers a better way to present their skills

| a | b | c |
| d | e | f |

It goes like that

Stack Overflow Documentation, the largest content expansion since Q&A, launches in July

|| Name || Surname || DoB ||
| | | |

||

| a | b | c | u |

The Developer Story launches in October, giving developers a better way to present their skills

| a | b | c |
| d | e | f |

When I am not want to wrap single || apperance within line (it suppose to be ignored in this case)

Screenshot for more example

P.S.

This, let's say, markup below

|| ID || Column1 || Column2 ||
| | | |

Will be parsed to html to look like table, where || Cell || is stands for header and | cell | stands for regular cell

So, after parsing it gonna be look like

    ID
    Column1
    Column2

Body:
The regex is

(\|\|?([^|\n\r]+\|\|?)+($|[\r\n]+))+

The matching group is $0 (demo).

It works as follows:

(
  \|\|?         #the line starts with one or two pipes
  (
    [^|\n\r]+   #followed by at least one non-pipe characther
    \|\|?       #and the cell endt with one or two pipes
  )+            #at least one cell, otherwise even the line "||" would be matched
  (
    $           #the text ends (you are NOT in multiline mode)
  |
    [\r\n]+     #or [\r\n] characters are matched (at least one, otherwise would match even "||A|B"), in order to match also the possible following line
  )
)+              #at least one line

If you don't want to match spaces/new lines after the "table", just use an a-few-harder regex (demo):

\|\|?([^|\n\r]+\|\|?)+$([\r\n]+\|\|?([^|\n\r]+\|\|?)+$)*

In this last regex remember to use the m flag.


问:
Count how many numbers appears in a string
I was wondering if there's a combo of functions or a direct function that can count how many numbers appears in a string, without use a long-way as str_split and check every character in a loop.

From a string like:

```<code>fdsji2092mds1039m
</code>```

It returns that there's 8 numbers inside.

答:
Other solution:

```<code>function countNumbers(string $string) {
    return preg_match_all('/\d/', $string, $m);
}
</code>```

You can use regular expression

Body:
I was wondering if there's a combo of functions or a direct function that can count how many numbers appears in a string, without use a long-way as str_split and check every character in a loop.

From a string like:

fdsji2092mds1039m

It returns that there's 8 numbers inside.

Body:
Other solution:

function countNumbers(string $string) {
    return preg_match_all('/\d/', $string, $m);
}

You can use regular expression


问:
@ionic-native/network value capture from observable
I am using the @ionic-native/network with the cordova-plugin-network-information plugin for checking online-offline status. However i'm having difficulty updating the network status.

home.ts

```<code>import { Network } from '@ionic-native/network';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
public online:boolean=false;
  constructor(public navCtrl: NavController,private network: Network) {
      this.network.onDisconnect().subscribe(() => {
         this.online=false;
         console.log(this.online);      });
      this.network.onConnect().subscribe(() => {
          this.online=true;
        console.log(this.online);
      });
  }

}
</code>```

home.html

```<code><ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h1>{{online}}</h1>
</ion-content>
</code>```

However on running the application, it only shows false, yet the console.log(this.online) shows true-false changes whenever i toggle the wifi. Any suggestions on how to make the interface values to changes as well.

答:
```<code>@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
public online:boolean=false;
  constructor(public navCtrl: NavController,private network: Network) {}

  ngOnInit(){
      this.network.onConnect().subscribe(() => {
         this.online=true;
         console.log(this.online);

         this.network.onDisconnect().subscribe(() => {
          this.online=false;
          console.log(this.online);
         });

     });

  }

}
</code>```

Body:
I am using the @ionic-native/network with the cordova-plugin-network-information plugin for checking online-offline status. However i'm having difficulty updating the network status.

home.ts

import { Network } from '@ionic-native/network';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
public online:boolean=false;
  constructor(public navCtrl: NavController,private network: Network) {
      this.network.onDisconnect().subscribe(() => {
         this.online=false;
         console.log(this.online);      });
      this.network.onConnect().subscribe(() => {
          this.online=true;
        console.log(this.online);
      });
  }

}

home.html

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

{{online}}

</ion-content>

However on running the application, it only shows false, yet the console.log(this.online) shows true-false changes whenever i toggle the wifi. Any suggestions on how to make the interface values to changes as well.


问:
Xamarin Forms: how to hide back button title?
In my Xamarin Forms iOS application the previous page name is also appearing with the back button in all pages. Is there any way to hide the title of the previous page?

答:
There is also one workaround to hide back button title globally in whole application.
Add in your AppDelegate.cs in FinishedLaunching method:</p>

```<code>UIBarButtonItem.Appearance.SetBackButtonTitlePositionAdjustment (new UIOffset (-100, -60), UIBarMetrics.Default);
</code>```

Body:
There is also one workaround to hide back button title globally in whole application.
Add in your AppDelegate.cs in FinishedLaunching method:

UIBarButtonItem.Appearance.SetBackButtonTitlePositionAdjustment (new UIOffset (-100, -60), UIBarMetrics.Default);


问:
SQL Finding maximum average time for distinct cell
I have a table with large number of records for which i am trying to find only 10 numbers with the largest average time per number.

So the table may look like so:

```<code>number  |   time
012345  |  10s
012345  |  20s
055555  |  50s
055555  |  30s
068976  |  11s
etc...
</code>```

and the output should look like so:

```<code>number  |  time
012345  |  15s
055555  |  40s
068976  |  11s
</code>```

tried this but to no avail

```<code>select distinct(destination), avg(totalqueuetime)
from call
group by destination, totalqueuetime
order by totalqueue time desc limit 10;
</code>```

it does not seem to group the numbers.

答:
Please try the following code, which has been tested as confirmed as effective.   ...-

(If you wish to sort by average total queue time, as your code sample above suggests)

```<code>SELECT destination,
       AVG( totalqueuetime ) AS avgTQT
FROM call
GROUP BY destination
ORDER BY avgTQT DESC LIMIT 10;
</code>```

(If you wish to sort by destination, as your desired output sample above suggests)

```<code>SELECT destination,
       AVG( totalqueuetime ) AS avgTQT
FROM call
GROUP BY destination
ORDER BY destination DESC LIMIT 10;
</code>```

If you have any questions or comments, then please feel free to post a Comment accordingly.

Note : As for your supplied code, if you remove totalqueuetime from the GROUP BY clause you will not need to use DISTINCT.  Thanks to AVG your SELECT statement will place the average in every returned field, potentially leading to many instances of the same combination of description and average.  Grouping them by Destination will reduce the list to one instance of each combination only.

Body:
I have a table with large number of records for which i am trying to find only 10 numbers with the largest average time per number.

So the table may look like so:

number  |   time
012345  |  10s
012345  |  20s
055555  |  50s
055555  |  30s
068976  |  11s
etc...

and the output should look like so:

number  |  time
012345  |  15s
055555  |  40s
068976  |  11s

tried this but to no avail

select distinct(destination), avg(totalqueuetime)
from call
group by destination, totalqueuetime
order by totalqueue time desc limit 10;

it does not seem to group the numbers.

Body:
Please try the following code, which has been tested as confirmed as effective.   ...-

(If you wish to sort by average total queue time, as your code sample above suggests)

SELECT destination,
       AVG( totalqueuetime ) AS avgTQT
FROM call
GROUP BY destination
ORDER BY avgTQT DESC LIMIT 10;

(If you wish to sort by destination, as your desired output sample above suggests)

SELECT destination,
       AVG( totalqueuetime ) AS avgTQT
FROM call
GROUP BY destination
ORDER BY destination DESC LIMIT 10;

If you have any questions or comments, then please feel free to post a Comment accordingly.

Note : As for your supplied code, if you remove totalqueuetime from the GROUP BY clause you will not need to use DISTINCT.  Thanks to AVG your SELECT statement will place the average in every returned field, potentially leading to many instances of the same combination of description and average.  Grouping them by Destination will reduce the list to one instance of each combination only.


问:
PHP MongoDate toDateTime default timezone
When I create new DateTime object, it has timezone from "date.timezone" setting:

```<code>print_r(new DateTime());

DateTime Object
(
    [date] => 2015-03-02 03:19:50.000000
    [timezone_type] => 3
    [timezone] => Europe/Moscow
)
</code>```

But when I get DateTime object from MongoDate, it has UTC timezone:

```<code>print_r((new MongoDate()) -> toDateTime())

DateTime Object
(
    [date] => 2015-03-02 00:19:50.000000
    [timezone_type] => 1
    [timezone] => +00:00
)
</code>```

How can I setup MongoDate to create DateTime objects with my default timezone?

答:
A way from do this:

```
    $mongoDate = new \MongoDate();
    $dateTimeDefaultTimeZone = $mongoDate->toDateTime()->setTimezone(new \DateTimeZone(date_default_timezone_get()))
```

You will can get the DateTime with default TimeZone.

Body:
When I create new DateTime object, it has timezone from "date.timezone" setting:

print_r(new DateTime());

DateTime Object
(
    [date] => 2015-03-02 03:19:50.000000
    [timezone_type] => 3
    [timezone] => Europe/Moscow
)

But when I get DateTime object from MongoDate, it has UTC timezone:

print_r((new MongoDate()) -> toDateTime())

DateTime Object
(
    [date] => 2015-03-02 00:19:50.000000
    [timezone_type] => 1
    [timezone] => +00:00
)

How can I setup MongoDate to create DateTime objects with my default timezone?

Body:
A way from do this:

    $mongoDate = new \MongoDate();
    $dateTimeDefaultTimeZone = $mongoDate->toDateTime()->setTimezone(new \DateTimeZone(date_default_timezone_get()))

You will can get the DateTime with default TimeZone.


问:
How Do I Use a Date (in the MM-dd-yyyy format) in a URL in an MVC Application?
I have an MVC2 project that has a route in the RegisterRoutes method as follows:

```<code>routes.MapRoute(
    "PrettyUrl",
    "Airplanes/{query}/{page}",
    new { controller = "Airplanes", action = "Details", query ="", page = 0 }
);
</code>```

Currently, the URL for a GET looks like Airplanes/va123-va234/1 - I would like to add a date like: Airplanes/va123-va234/10-10-2010/1 but I can't figure out how to get the route to map the date to this format.

答:
You can add a parameter for date

```<code>routes.MapRoute(
    "PrettyUrl",
    "Airplanes/{query}/{date}/{page}",
    new { controller = "Airplanes", action = "Details", query ="", page = 0,
          date = UrlParameter.Optional }
);
</code>```

In your controller method, make sure you take in a date parameter.

```<code>    public ActionResult Details(string query, string date, int page) {
        var newDate = DateTime.Parse(date);
        return View();
    }
</code>```

Body:
I have an MVC2 project that has a route in the RegisterRoutes method as follows:

routes.MapRoute(
    "PrettyUrl",
    "Airplanes/{query}/{page}",
    new { controller = "Airplanes", action = "Details", query ="", page = 0 }
);

Currently, the URL for a GET looks like Airplanes/va123-va234/1 - I would like to add a date like: Airplanes/va123-va234/10-10-2010/1 but I can't figure out how to get the route to map the date to this format.

Body:
You can add a parameter for date

routes.MapRoute(
    "PrettyUrl",
    "Airplanes/{query}/{date}/{page}",
    new { controller = "Airplanes", action = "Details", query ="", page = 0,
          date = UrlParameter.Optional }
);

In your controller method, make sure you take in a date parameter.

    public ActionResult Details(string query, string date, int page) {
        var newDate = DateTime.Parse(date);
        return View();
    }


问:
XSLT for picking and grouping elements from XML schema
I have an XML schema where I need to filter specific elements from each node and group those filtered elements into desired XML format.

XML schema is as follows-

```<code><Roots>
 <Root>
  <Result>
   <Row index="1">
    <id>001</id>
    <value>Test Value</value>
   </Row>
   <Row index="2">
    <id>001</id>
    <value>Test Value1</value>
   </Row>
   <Row index="3">
    <id>001</id>
    <value>Test Value2</value>
   </Row>
   <Row index="4">
    <id>002</id>
    <value>Test Value3</value>
   </Row>
   <Row index="5">
    <id>002</id>
    <value>Test Value4</value>
   </Row>
   <Row index="6">
    <id>003</id>
    <value>Test Value5</value>
   </Row>
   <Row index="7">
    <id>003</id>
    <value>Test Value6</value>
   </Row>
   <Row index="8">
    <id>003</id>
    <value>Test Value7</value>
   </Row>
  </Result>
 </Root>
</Root>
</code>```

I want to select element <id> and <value> from each node <Row> grouping by <id>. The expected XML schema is as follows-

```<code><html>
<body>
<table border="1">
  <tr>
   <td>001</td>
   <td>Test Value</td>
   <td>Test Value1</td>
   <td>Test Value2</td>
  </tr>
  <tr>
   <td>002</td>
   <td>Test Value3</td>
   <td>Test Value4</td>
  </tr>
  <tr>
   <td>003</td>
   <td>Test Value5</td>
   <td>Test Value6</td>
   <td>Test Value7</td>
  </tr>
</table>
</body>
</html>
</code>```

Could you please help me for the above format.
Working XSLT is as follows-

```<code>'<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="Roots/Root/Result">
<html>
 <body>
  <table border="1">
   <xsl:for-each-group select="Row" group-by="id">
    <tr>
     <td><xsl:value-of select="id"/></td>
     <xsl:for-each select="current-group()">
        <td><xsl:value-of select="value"/></td>
    </xsl:for-each>
    </tr>
   </xsl:for-each-group>
  </table>
 </body>
</html>
</xsl:template>
</xsl:stylesheet>'
</code>```

答:
this is a standart grouping schema in XSLT 2.0 (i assume that you are using the 2.0 since you didnt specify).

https://www.xml.com/pub/a/2003/11/05/tr.html

Check this link and it will help you a lot to shape your algorithm to do what you want.

If you can share the  XSLT code then we could be able to help you more.

Good Luck

Body:
I have an XML schema where I need to filter specific elements from each node and group those filtered elements into desired XML format.

XML schema is as follows-

<Roots>
 <Root>
  <Result>
   <Row index="1">
    <id>001</id>
    <value>Test Value</value>
   </Row>
   <Row index="2">
    <id>001</id>
    <value>Test Value1</value>
   </Row>
   <Row index="3">
    <id>001</id>
    <value>Test Value2</value>
   </Row>
   <Row index="4">
    <id>002</id>
    <value>Test Value3</value>
   </Row>
   <Row index="5">
    <id>002</id>
    <value>Test Value4</value>
   </Row>
   <Row index="6">
    <id>003</id>
    <value>Test Value5</value>
   </Row>
   <Row index="7">
    <id>003</id>
    <value>Test Value6</value>
   </Row>
   <Row index="8">
    <id>003</id>
    <value>Test Value7</value>
   </Row>
  </Result>
 </Root>
</Root>

I want to select element <id> and <value> from each node <Row> grouping by <id>. The expected XML schema is as follows-

   001
   Test Value
   Test Value1
   Test Value2

   002
   Test Value3
   Test Value4

   003
   Test Value5
   Test Value6
   Test Value7

Could you please help me for the above format.
Working XSLT is as follows-

'<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="Roots/Root/Result">

   <xsl:for-each-group select="Row" group-by="id">

     <xsl:value-of select="id"/>
     <xsl:for-each select="current-group()">
        <xsl:value-of select="value"/>
    </xsl:for-each>

   </xsl:for-each-group>

</xsl:template>
</xsl:stylesheet>'


问:
convert large data in json format
i have a table named  mobile in which all the mobile data is contained which have more then 7000 records now i want to display in json format but some how records are not showing here is my code kindly check ..

```<code><?php
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";

$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
var_dump($result);

$myArray = array();

while($row = mysqli_fetch_assoc($result)){

    $myArray[] = $row;

}

mysqli_close($conn);

header('Content-Type: application/json');

//$json = file_get_contents('json.json');

/*

$myArray = array("user1" => array("firstName" => "Mike2", "lastName" => "Smith" , "age" => 34),"user2" => array("firstName" => "Mike2", "lastName" => "Smith" , "age" => 34));

*/

$json = json_encode($myArray);

echo $json;

?>
</code>```

table

答:
I assume you are probably using ajax to get your data in the browser you have used a var_dump() in your php code followed by the json headers followed by the json result which will not work.

In order to set headers , the header() function should be called first before printing out any other thing, also you do no need to put in the var dump. Try the following code:

```<code><?php
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";
$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
$myArray = array();

while($row = mysqli_fetch_assoc($result)){
    $myArray[] = $row;
}
mysqli_close($conn);
header('Content-Type: application/json');
$json = json_encode($myArray);
echo $json;
?>
</code>```

Title: convert large data in json format

Body:
i have a table named  mobile in which all the mobile data is contained which have more then 7000 records now i want to display in json format but some how records are not showing here is my code kindly check ..

<?php
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";

$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
var_dump($result);

$myArray = array();

while($row = mysqli_fetch_assoc($result)){

    $myArray[] = $row;

}

mysqli_close($conn);

header('Content-Type: application/json');

//$json = file_get_contents('json.json');

/*

$myArray = array("user1" => array("firstName" => "Mike2", "lastName" => "Smith" , "age" => 34),"user2" => array("firstName" => "Mike2", "lastName" => "Smith" , "age" => 34));

*/

$json = json_encode($myArray);

echo $json;

?>

table

Body:
I assume you are probably using ajax to get your data in the browser you have used a var_dump() in your php code followed by the json headers followed by the json result which will not work.

In order to set headers , the header() function should be called first before printing out any other thing, also you do no need to put in the var dump. Try the following code:

<?php
$conn = mysqli_connect("localhost","root","","test") or die ("Error ".mysqli_error($conn));
$sql = "select * from mobile";
$result = mysqli_query($conn, $sql) or die ("error" . mysqli_error($conn));
$myArray = array();

while($row = mysqli_fetch_assoc($result)){
    $myArray[] = $row;
}
mysqli_close($conn);
header('Content-Type: application/json');
$json = json_encode($myArray);
echo $json;
?>


问:
Deserialize a JSON that has a key variable jackson map ObjectMapper
JSON: </p>

```<code>  {
    "id": "1704",
    "title": "Choice of Drink",
    "multiselect": 0,
    "maximum_selection": 1,
    "ac_items": 1,
    "Choice of Drink": [{
        "id": "8151",
        "name": "Lemon Ice Tea",
        "price": 0,
        "orig_price": 0
    }, {
        "id": "8152",
        "name": "Fresh Lime",
        "price": 0,
        "orig_price": 0
    }]
}
</code>```

<p>The problem is that the key "Choice of Drink" is a variable.How can I put this in a @JsonProperty, when I don't have the name? </p>

答:
Try this</p>

```<code> Gson gson = new Gson();
Type mapType = new TypeToken<Map<String,Map<String, String>>>() {}.getType();
Map<String,Map<String, String>> map = gson.fromJson(jsonString, mapType);
</code>```

Body:
JSON:

  {
    "id": "1704",
    "title": "Choice of Drink",
    "multiselect": 0,
    "maximum_selection": 1,
    "ac_items": 1,
    "Choice of Drink": [{
        "id": "8151",
        "name": "Lemon Ice Tea",
        "price": 0,
        "orig_price": 0
    }, {
        "id": "8152",
        "name": "Fresh Lime",
        "price": 0,
        "orig_price": 0
    }]
}

The problem is that the key "Choice of Drink" is a variable.How can I put this in a @JsonProperty, when I don't have the name?

Body:
Try this

 Gson gson = new Gson();
Type mapType = new TypeToken<Map<String,Map<String, String>>>() {}.getType();
Map<String,Map<String, String>> map = gson.fromJson(jsonString, mapType);


问:
Installing a tar.gz on Linux
I have downloaded Node.js from this link, which points to this link when clicking the button:

https://nodejs.org/dist/v4.1.2/node-v4.1.2-linux-x64.tar.gz

As advice from the Ubuntu community on installing the tar.gz, the following steps are followed.

```<code>$ ./configure
$ make
$ [sudo] make install
</code>```

The problem is the current file I have downloaded does not contain ./configure.

So how do I install this? Should I extract this to the usr/ folder?

My OS is Debian 8 (Jessie).

Should I include the Java package from Oracle? Is it safe to extract these files to the /usr folder?

答:
I am mentioning version-specific installation of NVM and Node.js.

If you don't have brew installed, run this:

```<code>/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
</code>```

If you don't have wget installed, run this:

```<code>brew install wget
</code>```

To install Node.js of a specific version, run these commands: Here, I'm installing NVM - v0.33.1 and Node.js of v0.12.6.

```<code>wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.1/install.sh | bash

source ~/.bashrc

nvm install v0.12.6

command -v nvm  //verify install
</code>```

ContentLicense: CC BY-SA 4.0

Title: Installing a tar.gz on Linux

Body:
I have downloaded Node.js from this link, which points to this link when clicking the button:

https://nodejs.org/dist/v4.1.2/node-v4.1.2-linux-x64.tar.gz

As advice from the Ubuntu community on installing the tar.gz, the following steps are followed.

$ ./configure
$ make
$ [sudo] make install

The problem is the current file I have downloaded does not contain ./configure.

So how do I install this? Should I extract this to the usr/ folder?

My OS is Debian 8 (Jessie).

Should I include the Java package from Oracle? Is it safe to extract these files to the /usr folder?

Body:
I am mentioning version-specific installation of NVM and Node.js.

If you don't have brew installed, run this:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

If you don't have wget installed, run this:

brew install wget

To install Node.js of a specific version, run these commands: Here, I'm installing NVM - v0.33.1 and Node.js of v0.12.6.

wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.1/install.sh | bash

source ~/.bashrc

nvm install v0.12.6

command -v nvm  //verify install


问:
Console two line output
I have this code which output some value from array, plus - in new line under value a[i]

```<code>Console.Write(a[i] + "\n-");
</code>```

So it looks like this

```<code>a
-
</code>```

Now i have more of Console.Write(a[i+1] + "\n-"); codes and it outputs like this

```<code>a
-b
-c
-d
-
</code>```

I know why this is the case but how can I return one line up after every new line \n? So I can get this

```<code>abcd
----
</code>```

答:
You have to output the values first, then the dashes:

```<code>Console.WriteLine(string.Join("", a)); // make a string of all values and write a line end
Console.WriteLine(string.Join("", a.Select(v => "-"))); // write the dashes
</code>```

[Ideone]

Title: Console two line output

Body:
I have this code which output some value from array, plus - in new line under value a[i]

Console.Write(a[i] + "\n-");

So it looks like this

a
-

Now i have more of Console.Write(a[i+1] + "\n-"); codes and it outputs like this

a
-b
-c
-d
-

I know why this is the case but how can I return one line up after every new line \n? So I can get this

abcd
----

Body:
You have to output the values first, then the dashes:

Console.WriteLine(string.Join("", a)); // make a string of all values and write a line end
Console.WriteLine(string.Join("", a.Select(v => "-"))); // write the dashes

[Ideone]


问:
Replacing certain combination of characters
I'm trying to remove the first bad characters (CAP letter + dot + Space) of this.

A. Shipping Length of Unit

  C. OVERALL HEIGHT

  Overall Weigth

  X. Max Cutting Height

I tried something like that, but it doesn't work:

```<code>string.replaceAll("[A-Z]+". ", "");
</code>```

The result should look like this:

Shipping Length of Unit

  OVERALL HEIGHT

  Overall Weigth

  Max Cutting Height

答:
This should work:

```<code>string.replaceAll("^[A-Z]\\. ", "")
</code>```

Examples

```<code>"A. Shipping Length of Unit".replaceAll("^[A-Z]\\. ", "")
// => "Shipping Length of Unit"
"Overall Weigth".replaceAll("^[A-Z]\\. ", "")
// => "Overall Weigth"
</code>```

Body:
I'm trying to remove the first bad characters (CAP letter + dot + Space) of this.

A. Shipping Length of Unit

  C. OVERALL HEIGHT

  Overall Weigth

  X. Max Cutting Height

I tried something like that, but it doesn't work:

string.replaceAll("[A-Z]+". ", "");

The result should look like this:

Shipping Length of Unit

  OVERALL HEIGHT

  Overall Weigth

  Max Cutting Height

Body:
This should work:

string.replaceAll("^[A-Z]\\. ", "")

Examples

"A. Shipping Length of Unit".replaceAll("^[A-Z]\\. ", "")
// => "Shipping Length of Unit"
"Overall Weigth".replaceAll("^[A-Z]\\. ", "")
// => "Overall Weigth"


问:
Starting cmd.exe problem
In Windows, when a command prompt is opened (cmd.exe), the registry keys:

HKLM\Software\Microsoft\Command Processor

  HKCU\Software\Microsoft\Command Processor

are checked for a value called "AutoRun". If found, the batch file named in the value is executed, providing autoexec-like functionality. If both keys contain AutoRun values, both will be run. Awesome!

I'm using Process.Start to run cmd.exe and the AutoRun behavior is not occuring. My current code is:

```<code>private openShell( string folder )
{
    ProcessStartInfo startInfo = new ProcessStartInfo()
        {
            FileName = Environment.GetEnvironmentVariable( "COMSPEC" ) ?? "cmd.exe",
            Arguments = "/k cd \"" + folder + "\"",
            UseShellExecute = true
        };

    try
    {
        using ( var exeProcess = System.Diagnostics.Process.Start( startInfo ) )
        {
            exeProcess.WaitForExit();
        }
    }
    catch
    {
        // Log error.
    }
}
</code>```

I've also tried reducing it down to the simplest form:

```<code>System.Diagnostics.Process.Start( "cmd.exe" );
</code>```

Everything I try works perfectly (in that a command window is launched), but the AutoRun behavior never occurs.

答:
I found it. The problem was in how Windows stores (and retrieves) data from the registry in 64-bit versions of the operating system. My code was fine. The article on MSDN goes into some detail. From that article:

On 64-bit Windows, portions of the
  registry entries are stored separately
  for 32-bit application and 64-bit
  applications and mapped into separate
  logical registry views using the
  registry redirector and registry
  reflection, because the 64-bit version
  of an application may use different
  registry keys and values than the
  32-bit version. There are also shared
  registry keys that are not redirected
  or reflected.

The solution for me was to add my AutoRun key under:

```<code>HKLM\Software\Wow6432Node\Microsoft\Command Processor
</code>```

What really gets my goat is that I've run into this before. I so rarely fool with the registry, I'd just completely forgotten about it.

Title: Starting cmd.exe problem

Body:
In Windows, when a command prompt is opened (cmd.exe), the registry keys:

HKLM\Software\Microsoft\Command Processor

  HKCU\Software\Microsoft\Command Processor

are checked for a value called "AutoRun". If found, the batch file named in the value is executed, providing autoexec-like functionality. If both keys contain AutoRun values, both will be run. Awesome!

I'm using Process.Start to run cmd.exe and the AutoRun behavior is not occuring. My current code is:

private openShell( string folder )
{
    ProcessStartInfo startInfo = new ProcessStartInfo()
        {
            FileName = Environment.GetEnvironmentVariable( "COMSPEC" ) ?? "cmd.exe",
            Arguments = "/k cd \"" + folder + "\"",
            UseShellExecute = true
        };

    try
    {
        using ( var exeProcess = System.Diagnostics.Process.Start( startInfo ) )
        {
            exeProcess.WaitForExit();
        }
    }
    catch
    {
        // Log error.
    }
}

I've also tried reducing it down to the simplest form:

System.Diagnostics.Process.Start( "cmd.exe" );

Everything I try works perfectly (in that a command window is launched), but the AutoRun behavior never occurs.

Body:
I found it. The problem was in how Windows stores (and retrieves) data from the registry in 64-bit versions of the operating system. My code was fine. The article on MSDN goes into some detail. From that article:

On 64-bit Windows, portions of the
  registry entries are stored separately
  for 32-bit application and 64-bit
  applications and mapped into separate
  logical registry views using the
  registry redirector and registry
  reflection, because the 64-bit version
  of an application may use different
  registry keys and values than the
  32-bit version. There are also shared
  registry keys that are not redirected
  or reflected.

The solution for me was to add my AutoRun key under:

HKLM\Software\Wow6432Node\Microsoft\Command Processor

What really gets my goat is that I've run into this before. I so rarely fool with the registry, I'd just completely forgotten about it.


答:
Try like this:

```<code>$myString = 'Som3 Charak1ers ar3 N0mberZ h3re ;)';
$countNumbers = strlen((string)filter_var($myString, FILTER_SANITIZE_NUMBER_INT));
echo 'Your input haz ' . $countNumbers . ' digits in it, man';
</code>```

You can also make a function out of this to return only the number, if you need it.

Title: Count how many numbers appears in a string

Body:
I was wondering if there's a combo of functions or a direct function that can count how many numbers appears in a string, without use a long-way as str_split and check every character in a loop.

From a string like:

fdsji2092mds1039m

It returns that there's 8 numbers inside.

Body:
Try like this:

$myString = 'Som3 Charak1ers ar3 N0mberZ h3re ;)';
$countNumbers = strlen((string)filter_var($myString, FILTER_SANITIZE_NUMBER_INT));
echo 'Your input haz ' . $countNumbers . ' digits in it, man';

You can also make a function out of this to return only the number, if you need it.


答:
Following code does what you intend to do:

```<code><?php
$string = 'dsfds98fsdfsdf8sdf908f9dsf809fsd809f8s15d0d';
$splits=str_split($string);
$count=0;
foreach ($splits as $split){
    if(is_numeric($split)){
        $count++;
    }
}

print_r($count);
</code>```

Output: 17

Body:
Following code does what you intend to do:

<?php
$string = 'dsfds98fsdfsdf8sdf908f9dsf809fsd809f8s15d0d';
$splits=str_split($string);
$count=0;
foreach ($splits as $split){
    if(is_numeric($split)){
        $count++;
    }
}

print_r($count);

Output: 17


问:
Confusion about spark accumulator performed inside actions
From offical doc we can see that :

For accumulator updates performed inside actions only, Spark
  guarantees that each task’s update to the accumulator will only be
  applied once, i.e. restarted tasks will not update the value. In
  transformations, users should be aware of that each task’s update may
  be applied more than once if tasks or job stages are re-executed.

I think it is means that accumulator should be performed inside actions only, such as rdd.foreachPartition()

Through rdd.foreachPartition's API code in pyspark, I find that rdd.foreachPartition(accum_func) is equal to :

```<code>rdd.mapPartitions(accum_func).mapPartitions(lambda i: [sum(1 for _ in i)]).mapPartitions(lambda x: [sum(x)]).mapPartitions(some_add_func).collect()
</code>```

It seems that accum_func can run inside transformations(rdd.mapPartition) ?

Thanks a lot for any explanin

答:
if the node running a partition of a map() operation crashes,
Spark will rerun it on another node and even if the node does not crash but is simply
much slower than other nodes, Spark can preemptively launch a “speculative” copy
of the task on another node, and take its result if that finishes.

Even if no nodes fail,Spark may have to rerun a task to rebuild a cached value that falls out of memory.The net result is therefore that the same function may run multiple times on the same data depending on what happens on the cluster.

Accumulators used in actions, Spark applies each task’s update to each accumulator only once. Thus, if we want a reliable absolute value counter, regardless of failures or multiple evaluations, we must put it inside an action like foreach().

Body:
From offical doc we can see that :

For accumulator updates performed inside actions only, Spark
  guarantees that each task’s update to the accumulator will only be
  applied once, i.e. restarted tasks will not update the value. In
  transformations, users should be aware of that each task’s update may
  be applied more than once if tasks or job stages are re-executed.

I think it is means that accumulator should be performed inside actions only, such as rdd.foreachPartition()

Through rdd.foreachPartition's API code in pyspark, I find that rdd.foreachPartition(accum_func) is equal to :

rdd.mapPartitions(accum_func).mapPartitions(lambda i: [sum(1 for _ in i)]).mapPartitions(lambda x: [sum(x)]).mapPartitions(some_add_func).collect()

It seems that accum_func can run inside transformations(rdd.mapPartition) ?

Thanks a lot for any explanin


问:
How to find list intersection?
```<code>a = [1,2,3,4,5]
b = [1,3,5,6]
c = a and b
print c
</code>```

actual output: [1,3,5,6]
expected output: [1,3,5]

How can we achieve a boolean AND operation (list intersection) on two lists?

答:
A functional way can be achieved using filter and lambda operator.

```<code>list1 = [1,2,3,4,5,6]

list2 = [2,4,6,9,10]

>>> list(filter(lambda x:x in list1, list2))

[2, 4, 6]
</code>```

Edit: It filters out x that exists in both list1 and list, set difference can also be achieved using:

```<code>>>> list(filter(lambda x:x not in list1, list2))
[9,10]
</code>```

Edit2: python3 filter returns a filter object, encapsulating it with list returns the output list.

Title: How to find list intersection?

Body:
a = [1,2,3,4,5]
b = [1,3,5,6]
c = a and b
print c

actual output: [1,3,5,6]
expected output: [1,3,5]

How can we achieve a boolean AND operation (list intersection) on two lists?

Body:
A functional way can be achieved using filter and lambda operator.

list1 = [1,2,3,4,5,6]

list2 = [2,4,6,9,10]

>>> list(filter(lambda x:x in list1, list2))

[2, 4, 6]

Edit: It filters out x that exists in both list1 and list, set difference can also be achieved using:

>>> list(filter(lambda x:x not in list1, list2))
[9,10]

Edit2: python3 filter returns a filter object, encapsulating it with list returns the output list.


问:
Java: how to compare two strings in order to obtain the portions where they differ?
I would like to learn a way to obtain the portions where two strings differ.

Suppose I have these two strings:

```<code>String s1 = "x4.printString(\"Bianca.()\").y1();";
String s2 = "sb.printString(\"Bianca.()\").length();";
</code>```

I would like this output: ["x4", "y1", "sb", "length"] coming from a method receiving s1and s2as arguments.

I have looked for something like this in other posts, but I have only found links to StringUtils.difference(String first, String second).

But this method returns the second string from the index where it begins to differ from the first one.

I really don't know where to start and any advice would be very appreciated.

UPDATE
Following @aUserHimself advises, I managed to obtain all common subsequences among the two strings, but these subsequences come out like a unique String.

This is my code now:

```<code>private static int[][] lcs(String s, String t) {
    int m, n;
    m = s.length();
    n = t.length();
    int[][] table = new int[m+1][n+1];
    for (int i=0; i < m+1; i++)
        for (int j=0; j<n+1; j++)
            table[i][j] = 0;
    for (int i = 1; i < m+1; i++)
        for (int j = 1; j < n+1; j++)
            if (s.charAt(i-1) == t.charAt(j-1))
                table[i][j] = table[i-1][j-1] + 1;
            else
                table[i][j] = Math.max(table[i][j-1], table[i-1][j]);
    return table;
}

private static List<String> backTrackAll(int[][]table, String s, String t, int m, int n){
    List<String> result = new ArrayList<>();
    if (m == 0 || n == 0) {
        result.add("");
        return result;
    }
    else
        if (s.charAt(m-1) == t.charAt(n-1)) {
            for (String sub : backTrackAll(table, s, t, m - 1, n - 1))
                result.add(sub + s.charAt(m - 1));
            return result;
        }
        else {
            if (table[m][n - 1] >= table[m - 1][n])
                result.addAll(backTrackAll(table, s, t, m, n - 1));
            else
                result.addAll(backTrackAll(table, s, t, m - 1, n));
            return result;
        }
}

private List<String> getAllSubsequences(String s, String t){
    return backTrackAll(lcs(s, t), s, t, s.length(), t.length());
}
</code>```

Calling getAllSubsequences on these two strings:

```<code>String s1 = "while (x1 < 5)"
String s2 = "while (j < 5)"
</code>```

I receive this string: ["while ( < 5)"] not ["while (", " < 5)"] as I would like to obtain. I am not understanding where I am doing wrong.

答:
Find the longest common subsequence between two strings.
After that you can use indexOf to get index of this common string in between both strings and fetch uncommon values from both.

example :

```<code>CICROSOFK
WOCROSFGT
</code>```

Common letter is

```<code>CROS
</code>```

Find different string from 0 to index of SOFT and from index+'SOFT'.length to str.length

Body:
I would like to learn a way to obtain the portions where two strings differ.

Suppose I have these two strings:

String s1 = "x4.printString(\"Bianca.()\").y1();";
String s2 = "sb.printString(\"Bianca.()\").length();";

I would like this output: ["x4", "y1", "sb", "length"] coming from a method receiving s1and s2as arguments.

I have looked for something like this in other posts, but I have only found links to StringUtils.difference(String first, String second).

But this method returns the second string from the index where it begins to differ from the first one.

I really don't know where to start and any advice would be very appreciated.

UPDATE
Following @aUserHimself advises, I managed to obtain all common subsequences among the two strings, but these subsequences come out like a unique String.

This is my code now:

private static int[][] lcs(String s, String t) {
    int m, n;
    m = s.length();
    n = t.length();
    int[][] table = new int[m+1][n+1];
    for (int i=0; i < m+1; i++)
        for (int j=0; j<n+1; j++)
            table[i][j] = 0;
    for (int i = 1; i < m+1; i++)
        for (int j = 1; j < n+1; j++)
            if (s.charAt(i-1) == t.charAt(j-1))
                table[i][j] = table[i-1][j-1] + 1;
            else
                table[i][j] = Math.max(table[i][j-1], table[i-1][j]);
    return table;
}

private static List<String> backTrackAll(int[][]table, String s, String t, int m, int n){
    List<String> result = new ArrayList<>();
    if (m == 0 || n == 0) {
        result.add("");
        return result;
    }
    else
        if (s.charAt(m-1) == t.charAt(n-1)) {
            for (String sub : backTrackAll(table, s, t, m - 1, n - 1))
                result.add(sub + s.charAt(m - 1));
            return result;
        }
        else {
            if (table[m][n - 1] >= table[m - 1][n])
                result.addAll(backTrackAll(table, s, t, m, n - 1));
            else
                result.addAll(backTrackAll(table, s, t, m - 1, n));
            return result;
        }
}

private List<String> getAllSubsequences(String s, String t){
    return backTrackAll(lcs(s, t), s, t, s.length(), t.length());
}

Calling getAllSubsequences on these two strings:

String s1 = "while (x1 < 5)"
String s2 = "while (j < 5)"

I receive this string: ["while ( < 5)"] not ["while (", " < 5)"] as I would like to obtain. I am not understanding where I am doing wrong.

Body:
Find the longest common subsequence between two strings.
After that you can use indexOf to get index of this common string in between both strings and fetch uncommon values from both.

example :

CICROSOFK
WOCROSFGT

Common letter is

CROS

Find different string from 0 to index of SOFT and from index+'SOFT'.length to str.length


问:
AngularJS All slashes in URL changed to %2F
I'm having a massive problem with AngularJS routing.

Up until recently everything has been fine with the following route:

```<code>$routeProvider.when('/album/:albumId', {
    controller: 'albumPageController',
    templateUrl: 'views/album.html'
});
</code>```

and using the href:

```<code><a href="/#/album/{{album.id}}">Link</a>
</code>```

However, now all of the slashes are being encoded into %2F.

So when I click the link, or type localhost:8000/#/album/1 into the browser, the URL is changed to:

http://localhost:8000/#%2Falbum%2F1

I've tried several things to correct this:

Using ng-href instead of href,
Not using the first / (ie href="#/album/{{album.id}}")
Running the app in Homestead localhost (Laravel's linux vagrant machine) instead of localhost on Windows 10

Any help would be much appreciated!

答:
A bit late to the party but adding a '!' to your URLs will work just fine. This bothered me for a bit as well. This is a change in the latest AngularJS 1.6.x and I read somewhere that Google requires SPAs to have that '!' after the hash. As a result my routes look as they should but my navigation makes sure I add '!' in my references. For example:

```<code><ul>
    <li><a href="#!/">Home</a></li>
    <li><a href="#!/page2">Page 2</a></li>
    <li><a href="#!/page3">Page 3</a></li>
    <li><a href="#!/page4">Page 4</a></li>
</ul>
</code>```

I hope this helps you.

Regards!

Body:
I'm having a massive problem with AngularJS routing.

Up until recently everything has been fine with the following route:

$routeProvider.when('/album/:albumId', {
    controller: 'albumPageController',
    templateUrl: 'views/album.html'
});

and using the href:

Link

However, now all of the slashes are being encoded into %2F.

So when I click the link, or type localhost:8000/#/album/1 into the browser, the URL is changed to:

http://localhost:8000/#%2Falbum%2F1

I've tried several things to correct this:

Using ng-href instead of href,
Not using the first / (ie href="#/album/{{album.id}}")
Running the app in Homestead localhost (Laravel's linux vagrant machine) instead of localhost on Windows 10

Any help would be much appreciated!

Body:
A bit late to the party but adding a '!' to your URLs will work just fine. This bothered me for a bit as well. This is a change in the latest AngularJS 1.6.x and I read somewhere that Google requires SPAs to have that '!' after the hash. As a result my routes look as they should but my navigation makes sure I add '!' in my references. For example:

<ul>
    <li><a href="#!/">Home</a></li>
    <li><a href="#!/page2">Page 2</a></li>
    <li><a href="#!/page3">Page 3</a></li>
    <li><a href="#!/page4">Page 4</a></li>
</ul>

I hope this helps you.

Regards!


问:
Send a message directly from a thread to an object without using the main form
I'm using a 3rd party library that uses a lot of threads.

I've just started using messages to communicate back to the main thread from a thread. It's all working, but using SendMessage the way I describe below seems cumbersome because the main form has to dispatch all the messages. Is there a way to send a message directly to a frame or object, without depending on the main form?

At program startup:

```<code> MyMessageNumber1 :=  RegisterWindowMessage('MyUniqueID1');
 MyMessageNumber2 :=  RegisterWindowMessage('MyUniqueID2');
</code>```

When sending a message without any data, I do:

```<code> SendMessage(Application.MainForm.Handle,  MyMessageNumber1)
</code>```

My main form has this:

```<code>procedure WndProc(var Message: TMessage); override;
if (Message.Msg = MyMessageNumber1)
  ... call a frame or other object's method that handles this particular message
else if (Message.Msg = MyMessageNumber2) then
  ... call another ....
else
  inherited;
</code>```

In summary: the above WndProc has to know far more than I'd prefer about all the messages and who to dispatch them to.

How can I send a message directly from a thread in a way that any object can receive it?

All of these messages have no data associated with them. (We'll get to that some other day!) :-)

TIA

答:
Other forms and frames have handles as well, and you can define message-handling methods on them, then post the message directly to the form or frame.  (Or control, for that matter, if you're building your own custom controls.)

See http://docwiki.embarcadero.com/RADStudio/en/Declaring_a_New_Message-handling_Method for an overview on setting up message-handling methods.

Body:
I'm using a 3rd party library that uses a lot of threads.

I've just started using messages to communicate back to the main thread from a thread. It's all working, but using SendMessage the way I describe below seems cumbersome because the main form has to dispatch all the messages. Is there a way to send a message directly to a frame or object, without depending on the main form?

At program startup:

 MyMessageNumber1 :=  RegisterWindowMessage('MyUniqueID1');
 MyMessageNumber2 :=  RegisterWindowMessage('MyUniqueID2');

When sending a message without any data, I do:

 SendMessage(Application.MainForm.Handle,  MyMessageNumber1)

My main form has this:

procedure WndProc(var Message: TMessage); override;
if (Message.Msg = MyMessageNumber1)
  ... call a frame or other object's method that handles this particular message
else if (Message.Msg = MyMessageNumber2) then
  ... call another ....
else
  inherited;

In summary: the above WndProc has to know far more than I'd prefer about all the messages and who to dispatch them to.

How can I send a message directly from a thread in a way that any object can receive it?

All of these messages have no data associated with them. (We'll get to that some other day!) :-)

TIA


问:
Type Error on Code
Here is the instructions to my code and my code, I am receiving type error:

The greatest common divisor (GCD) of two integers is the largest integer that will evenly divide both integers. Write a program, with comments, that asks the user to input two positive integers and calculates the corresponding GCD. You may assume the user will input valid numbers. Display a suitable message showing the 2 integers and their GCD.

Steps for calculating the GCD is given below.

set a = to the larger integer and b = the smaller integer (if they are different)

while b≠0 perform the following steps:

rem = remainder obtained after dividing a by b

set a = to the current value of b

set b = rem (as calculated in step 2a)

gcd = value of a  (i.e. previous value of b) after exiting the while loop.

A sample session showing user inputs and corresponding outputs is given below.

```<code>def gcd(a, b):
    if b > a:
        return gcd(b, a)
    if a % b == 0:
        return b
    return gcd(b, a % b)
a=input('Enter first positive Integer :');
b=input('Enter second positive Integer :');
s = 'The gcd of ' + repr(a) + ' and ' + repr(b) + ' is ' +repr(gcd(a, b))
print(s)
</code>```

答:
You're getting a TypeError because the input function treats all inputs as strings.  You need to convert the input to an integer before trying to perform the gcd function on it.  e.g.:</p>

```<code>def gcd(a, b):
    a = int(a)
    b = int(b)
    if b > a:
        return gcd(b, a)
    if a % b == 0:
        return b
    return gcd(b, a % b)
</code>```

Title: Type Error on Code

Body:
Here is the instructions to my code and my code, I am receiving type error:

The greatest common divisor (GCD) of two integers is the largest integer that will evenly divide both integers. Write a program, with comments, that asks the user to input two positive integers and calculates the corresponding GCD. You may assume the user will input valid numbers. Display a suitable message showing the 2 integers and their GCD.

Steps for calculating the GCD is given below.

set a = to the larger integer and b = the smaller integer (if they are different)

while b≠0 perform the following steps:

rem = remainder obtained after dividing a by b

set a = to the current value of b

set b = rem (as calculated in step 2a)

gcd = value of a  (i.e. previous value of b) after exiting the while loop.

A sample session showing user inputs and corresponding outputs is given below.

def gcd(a, b):
    if b > a:
        return gcd(b, a)
    if a % b == 0:
        return b
    return gcd(b, a % b)
a=input('Enter first positive Integer :');
b=input('Enter second positive Integer :');
s = 'The gcd of ' + repr(a) + ' and ' + repr(b) + ' is ' +repr(gcd(a, b))
print(s)

Body:
You're getting a TypeError because the input function treats all inputs as strings.  You need to convert the input to an integer before trying to perform the gcd function on it.  e.g.:

def gcd(a, b):
    a = int(a)
    b = int(b)
    if b > a:
        return gcd(b, a)
    if a % b == 0:
        return b
    return gcd(b, a % b)


答:
Try this :

```<code>myString.replaceAll("([A-Z]\\.\\s)","")
</code>```

[A-Z] : match a single character in the range between A and Z.

\. : match the dot character.

\s : match the space character.

Title: Replacing certain combination of characters

Body:
I'm trying to remove the first bad characters (CAP letter + dot + Space) of this.

A. Shipping Length of Unit

  C. OVERALL HEIGHT

  Overall Weigth

  X. Max Cutting Height

I tried something like that, but it doesn't work:

string.replaceAll("[A-Z]+". ", "");

The result should look like this:

Shipping Length of Unit

  OVERALL HEIGHT

  Overall Weigth

  Max Cutting Height

Body:
Try this :

myString.replaceAll("([A-Z]\\.\\s)","")

[A-Z] : match a single character in the range between A and Z.

\. : match the dot character.

\s : match the space character.


问:
Could not load file or assembly 'Interop.MaConfigLib'.
I had tried to run one existing C# project to new system. Project is built successfully but i get an error while running the project which states:

Could not load file or assembly 'Interop.MaConfigLib, Version=12.3.2326.2749, Culture=neutral, PublicKeyToken=10639c8833d92508' or one of its dependencies. The system cannot find the file specified.

I am not able to find Interop.MaConfigLib.dll.
I had done some digging and find some suggestion of "GAC" but it didn't help much.

Can any one tell me how to resolve this error?

Any help would be appreciated.

答:
I think there is a reference in your project to third party library, and now you are just missing the file MaConfigLib.dll, on your old system you have installed application which library file you use in your solution, I think you should find out to whom belongs that file (i've done a little search and it shows   MAXIMIZER SERVICES INC).
Try to find out, if it's a standalone library, then download it and register with RegAsm.exe, if not you should install the proper application and when update the reference in your project.</p>


问:
how to remove the array values when table view cell is not selected in objective c?
This is my code

```<code> - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSArray *selectedRows=[_mytableview indexPathsForSelectedRows];
NSMutableArray *rownumberArray=[[NSMutableArray alloc]init];
NSMutableArray *valueofselectedcell = [[NSMutableArray alloc]init];
for (int i=0; i<selectedRows.count; i++) {

    customcell *cell = (customcell *)[_mytableview cellForRowAtIndexPath:indexPath];
    NSString *test = cell.balance.text;
    [valueofselectedcell addObject:test];
    NSArray *array = [valueofselectedcell copy];
    NSNumber* sum = [array valueForKeyPath: @"@sum.self"];
    NSLog(@"the sum valuie is .... %@",sum);
    NSString *totalamount = [sum stringValue];
    _amountlabel.text=totalamount;
    NSIndexPath *path = [tableView indexPathForSelectedRow];
    NSLog(@"%@ the selected path value is",path);
}}
</code>```

when the table cell values are selected the selected values are store in the valueselectedcell array it's working fine.Now how to remove the values in the array when i deselect the rows .

答:
Use Tableview's didDeselectRowAtIndexPath delegate method:

```<code>-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    customcell *cell = (customcell *)[_mytableview cellForRowAtIndexPath:indexPath];
    NSString *test = cell.balance.text;
    if ([valueofselectedcell containsObject: test])
    {
        [valueofselectedcell removeObject:test];
    }
}
</code>```

Body:
This is my code

 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSArray *selectedRows=[_mytableview indexPathsForSelectedRows];
NSMutableArray *rownumberArray=[[NSMutableArray alloc]init];
NSMutableArray *valueofselectedcell = [[NSMutableArray alloc]init];
for (int i=0; i<selectedRows.count; i++) {

    customcell *cell = (customcell *)[_mytableview cellForRowAtIndexPath:indexPath];
    NSString *test = cell.balance.text;
    [valueofselectedcell addObject:test];
    NSArray *array = [valueofselectedcell copy];
    NSNumber* sum = [array valueForKeyPath: @"@sum.self"];
    NSLog(@"the sum valuie is .... %@",sum);
    NSString *totalamount = [sum stringValue];
    _amountlabel.text=totalamount;
    NSIndexPath *path = [tableView indexPathForSelectedRow];
    NSLog(@"%@ the selected path value is",path);
}}

when the table cell values are selected the selected values are store in the valueselectedcell array it's working fine.Now how to remove the values in the array when i deselect the rows .

Body:
Use Tableview's didDeselectRowAtIndexPath delegate method:

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    customcell *cell = (customcell *)[_mytableview cellForRowAtIndexPath:indexPath];
    NSString *test = cell.balance.text;
    if ([valueofselectedcell containsObject: test])
    {
        [valueofselectedcell removeObject:test];
    }
}


问:
How to blur Selectize.js input after selection has been made in Bootstrap 3?
I am using the Selectize.js. From the docs it says I can set up a 'onDropdownClose' callback here: Selectize docs.  I can't seem to get it to work.

How do I blur (defocus) the input after a selection has been made using Selectize.js?  All the blurs in the below code do not work.

```<code>$(document).ready(function() {
    $("#myinput").selectize({
    onDropdownClose : function ($dropdown) {
                       $($dropdown).prev().find('input').blur();
                      }
    });
});
</code>```

EDIT:
I am using Bootstrap 3.1.1.  I just noticed that the default behavior for Bootstrap 2 is to blur the input after a selection has been made while Bootstrap 3+ leaves the input in focus after a selection has been made.  My question still stands for Bootstrap 3+

Edit:
I got it to work with the above code.

答:
Accepted (deadwards) answer was fine, but in situation like this:
you open the menu, and close it by clicking back on the input element. In this situation, the dropdownmenu gets opened again.
I used this variant. I know, it is an ugly solution, but it worked better in this situation. You could change timout delay to fit your situation bettter, this was fine for me.</p>

```<code>        onDropdownClose: function (dropdown) {
            var self = this;
            setTimeout(function() {
                self.$control_input.blur();
            }, 250);
        }
</code>```

Body:
I am using the Selectize.js. From the docs it says I can set up a 'onDropdownClose' callback here: Selectize docs.  I can't seem to get it to work.

How do I blur (defocus) the input after a selection has been made using Selectize.js?  All the blurs in the below code do not work.

$(document).ready(function() {
    $("#myinput").selectize({
    onDropdownClose : function ($dropdown) {
                       $($dropdown).prev().find('input').blur();
                      }
    });
});

EDIT:
I am using Bootstrap 3.1.1.  I just noticed that the default behavior for Bootstrap 2 is to blur the input after a selection has been made while Bootstrap 3+ leaves the input in focus after a selection has been made.  My question still stands for Bootstrap 3+

Edit:
I got it to work with the above code.

Body:
Accepted (deadwards) answer was fine, but in situation like this:
you open the menu, and close it by clicking back on the input element. In this situation, the dropdownmenu gets opened again.
I used this variant. I know, it is an ugly solution, but it worked better in this situation. You could change timout delay to fit your situation bettter, this was fine for me.

        onDropdownClose: function (dropdown) {
            var self = this;
            setTimeout(function() {
                self.$control_input.blur();
            }, 250);
        }


问:
How would I use the `...` C operator to get a function to print out all it's args?
Here's what I tried... but failed:</p>

```<code>void testfunc(...){
    printf(...);
}
</code>```

答:
This will create a function that is equivalent to printf.  Note that you cannot blindly print out arguments, since you somehow need to know what type each argument is in advance.  The format argument to printf informs it what arguments to expect and what types they will be.

```<code>#include <stdargs.h>

void testfunc(const char *format, ...)
{
    va_list ap;
    va_start(ap, format);

    vprintf(format, ap);

    va_end(ap);
}
</code>```

Body:
Here's what I tried... but failed:

void testfunc(...){
    printf(...);
}

Body:
This will create a function that is equivalent to printf.  Note that you cannot blindly print out arguments, since you somehow need to know what type each argument is in advance.  The format argument to printf informs it what arguments to expect and what types they will be.

#include <stdargs.h>

void testfunc(const char *format, ...)
{
    va_list ap;
    va_start(ap, format);

    vprintf(format, ap);

    va_end(ap);
}


问:
C# Capture label text from another application
I am using C#. I intend my program can get label text from another application by click. For an example:
 - When I click on the File Menu in Notepad program, my console application will show "File" text.
 - When I click on the title of Calculator in Windows, my console application will show "Calculator".
I don't know how to do that? Can some one help??</p>

答:
First,you have to know the Handle(IntPtr) of 'another application',to do this,you can use FindWindow and FindWindowEx,both of them can be found in user32.dll.
Second,you can get the text of the control that the Handel refered by sending a WM_GETTEXT message using SendMessage which can also be found in user32.dll.
The syntax,usage,examples etc of SendMessage,FindWindow,FindWindowEx can all be found on MSDN.</p>


问:
How to get the rows of a dataframe together (selcted row bottom up)
I explain my question with an example. For example, if I am in the row number 5 (following table), how can I get the rows before 5 that have the same P_P value. The point is the row index of the selected rows should be sequential.
For example in the case of following table, I need to get only rows 3 and 4 (since between the row 1 and the rest of the rows there is row number 2 with different P_P.)
FYI, I could use for loop to do it but I want to avoid it.

Thanks

```<code>ID   Contest   P_P   Time
1      UMA      A    2015
2      DOIS     B    2016
3      DOIS     A    2016
4      UMA      A    2017
5      DOIS     A    2017
</code>```

答:
You could do this in base R:

```<code>rw <- 5
df[(max(which(!(df[1:(rw-1),]$P_P==df[rw,]$P_P)))+1):(rw-1),]

# ID Contest P_P Time
#3  3    DOIS   A 2016
#4  4     UMA   A 2017
</code>```

The idea is to first find matches between 1 through rw-1 (i.e., df[1:(rw-1),]$P_P==df[rw,]$P_P) and then find the last non-match (i.e., FALSE) which is captured by max(which(!...)).

```<code>df <- structure(list(ID = 1:5, Contest = structure(c(2L, 1L, 1L, 2L,
1L), .Label = c("DOIS", "UMA"), class = "factor"), P_P = structure(c(1L,
2L, 1L, 1L, 1L), .Label = c("A", "B"), class = "factor"), Time = c(2015L,
2016L, 2016L, 2017L, 2017L)), .Names = c("ID", "Contest", "P_P",
"Time"), class = "data.frame", row.names = c(NA, -5L))
</code>```

Body:
I explain my question with an example. For example, if I am in the row number 5 (following table), how can I get the rows before 5 that have the same P_P value. The point is the row index of the selected rows should be sequential.
For example in the case of following table, I need to get only rows 3 and 4 (since between the row 1 and the rest of the rows there is row number 2 with different P_P.)
FYI, I could use for loop to do it but I want to avoid it.

Thanks

ID   Contest   P_P   Time
1      UMA      A    2015
2      DOIS     B    2016
3      DOIS     A    2016
4      UMA      A    2017
5      DOIS     A    2017

Body:
You could do this in base R:

rw <- 5
df[(max(which(!(df[1:(rw-1),]$P_P==df[rw,]$P_P)))+1):(rw-1),]

# ID Contest P_P Time
#3  3    DOIS   A 2016
#4  4     UMA   A 2017

The idea is to first find matches between 1 through rw-1 (i.e., df[1:(rw-1),]$P_P==df[rw,]$P_P) and then find the last non-match (i.e., FALSE) which is captured by max(which(!...)).

df <- structure(list(ID = 1:5, Contest = structure(c(2L, 1L, 1L, 2L,
1L), .Label = c("DOIS", "UMA"), class = "factor"), P_P = structure(c(1L,
2L, 1L, 1L, 1L), .Label = c("A", "B"), class = "factor"), Time = c(2015L,
2016L, 2016L, 2017L, 2017L)), .Names = c("ID", "Contest", "P_P",
"Time"), class = "data.frame", row.names = c(NA, -5L))


问:
Laravel, Route required parameter is not validating by Form Request Validation
I am using laravel 5.4

routes/web.php [Route]

```<code>Route::get('/email-confirmation/{token}', ['uses' => 'Components\ConfirmationController@sendEmailConfirmation', 'as' => 'web.email.confirmation']);
</code>```

Components/ConfirmationController.php [Controller]

```<code>public function sendEmailConfirmation(EmailConfirmationRequest $request)
{
dd($request->input('token'));
// ouput is empty
}
</code>```

// I know that, route required parameter is access by passing in it as second parameter

EmailConfirmationRequest.php [Request]

```<code>public function rules()
{
    return ['token' => 'required|max:3'];
}
</code>```

URL : /email-confirmation/hello - not validating

So, It cannot validated the token parameter in the request.

I am not sure, I am doing something wrong.

答:
As some of the comments already have said, you are passing the $token as a route parameter, not an input value.

To use this route parameter update your method (adding $token)

```<code>public function sendEmailConfirmation(EmailConfirmationRequest $request, $token)
{
    dd($token);
    // output should be $token value
}
</code>```

If you do want to pass it as an input you can add it as a hidden field in your form.

Body:
I am using laravel 5.4

routes/web.php [Route]

Route::get('/email-confirmation/{token}', ['uses' => 'Components\ConfirmationController@sendEmailConfirmation', 'as' => 'web.email.confirmation']);

Components/ConfirmationController.php [Controller]

public function sendEmailConfirmation(EmailConfirmationRequest $request)
{
dd($request->input('token'));
// ouput is empty
}

// I know that, route required parameter is access by passing in it as second parameter

EmailConfirmationRequest.php [Request]

public function rules()
{
    return ['token' => 'required|max:3'];
}

URL : /email-confirmation/hello - not validating

So, It cannot validated the token parameter in the request.

I am not sure, I am doing something wrong.

Body:
As some of the comments already have said, you are passing the $token as a route parameter, not an input value.

To use this route parameter update your method (adding $token)

public function sendEmailConfirmation(EmailConfirmationRequest $request, $token)
{
    dd($token);
    // output should be $token value
}

If you do want to pass it as an input you can add it as a hidden field in your form.


问:
How to enable and disable button accordingly if i select the dropdown options in Angular js
If I click on the dropdown which is marked inside the blue border, I want the buttons below to be enabled/disabled according to the condition.

If I select first dropdown value. I want the 3rd and 4th button to disabled and 1st and 2nd should be active.

I was looking some angular js code (ng-disabled or ng-class)

答:
The selector must be binded to some ng-model, which keep track of the current value. Supposing you have something like this:

```<code><select ng-model="FooBar">
    Some options... (with their respectives value)
</select>
</code>```

you can enable or desable multiple buttons using this var "FooBar":

```<code><input ng-disabled="FooBar !== desiredEnableValue">
</code>```

Body:
The selector must be binded to some ng-model, which keep track of the current value. Supposing you have something like this:

<select ng-model="FooBar">
    Some options... (with their respectives value)
</select>

you can enable or desable multiple buttons using this var "FooBar":

<input ng-disabled="FooBar !== desiredEnableValue">


问:
EJB annotation not working
I have a problem with my EJB annotations:

I have a DAO:

```<code>@Singleton
@Startup
public class CassandraDAO<T extends Serializable> extends AbstractDAO {

  @PersistenceContext(unitName = "JPAService", type = PersistenceContextType.EXTENDED)
  private EntityManager em;

  @PostConstruct
  public void init() {
    System.out.println("***************** init CassandraDAO ***************************");
  }

  @PreDestroy
  public void destroy() {
    System.out.println("***************** destroying CassandraDAO *************************");
    if (em.isOpen()) {
      em.close();
    }
  }

  @Override
  public EntityManager getManager() {
    return em;
  }

  @Override
  public void setManager(EntityManager em) {
    this.em = em;
  }
}
</code>```

And there are several DAOs that extends this DAO:

```<code>@Stateless
public class IOConfigurationDAO extends CassandraDAO<IOConfiguration> {
...
}
</code>```

And here is how I use the DAO:

```<code>public class AddAlertTest extends TestCase {
  @EJB
  private IOConfigurationDAO ioConfigurationDAO;
  public void test() {
      ioConfigurationDAO.getManager().getTransaction().begin();
      IOConfiguration ioConfig = new IOConfiguration("CH1");
      ioConfigurationDAO.getManager().persist(ioConfig);
      ioConfigurationDAO.getManager().getTransaction().commit();
      int oldSize = ioConfig.getAlerts() == null ? 0 : ioConfig.getAlerts().size();
      System.out.println("Created IO configuration with id " + ioConfig.getIoConfigurationId());

      ioConfigurationDAO.getManager().getTransaction().begin();
      Alert alert = ioConfigurationDAO.addAlert(ioConfig,
          Operators[(int) (Math.random() * Operators.length)], new Double(Math.random() * 100));
      ioConfigurationDAO.getManager().getTransaction().commit();
      int newSize = ioConfig.getAlerts().size();
      System.out.println("Created new Alert with id " + alert.getAlertId());
      System.out.println("Alert list: " + ioConfig.getAlerts());
      System.out.println("Alert is connected to " + alert.getIoConfiguration());

      assertEquals(oldSize + 1, newSize);
      assertNotNull(ioConfigurationDAO.getManager().find(Alert.class, alert.getAlertId()));

      ioConfigurationDAO.getManager().getTransaction().begin();
      ioConfigurationDAO.getManager().remove(ioConfig);
      ioConfigurationDAO.getManager().getTransaction().commit();
      System.out.println("Deleted IO configuration with id " + ioConfig.getIoConfigurationId());
  }
</code>```

But my IOConfigurationDAO is always null, so my persistenceContext annotation doesn't work at all. And there is nothing printed out in my console, so my postConstruct annotations doesn't work as well.

Here is my persistence.xml:

```<code><?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
    <persistence-unit name="JPAService">
        <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
        <class>com.sensorhound.aigateway.domain.Alert</class>
        <class>com.sensorhound.aigateway.domain.DataSeriesMeta</class>
        <class>com.sensorhound.aigateway.domain.IOConfiguration</class>
        <class>com.sensorhound.aigateway.domain.NodeData</class>
        <properties>
            <property name="hibernate.transaction.jta.platform" value="JBossAS" />
            <property name="jboss.as.jpa.providerModule" value="org.hibernate:5.0" />
            <property name="hibernate.ogm.datastore.provider" value="cassandra_experimental"/>
            <property name="hibernate.ogm.datastore.host" value="127.0.0.1:9042"/>
            <property name="hibernate.ogm.datastore.database" value="dev"/>
            <property name="hibernate.hbm2ddl.auto" value="none"></property>
            <property name = "hibernate.show_sql" value = "true" />
            <property name = "hibernate.format_sql" value = "true" />
        </properties>
    </persistence-unit>
</persistence>
</code>```

I don't know what is wrong in my configuration. Someone please help me. If you need more information, I am willing to share.

Thanks!

答: The work of the DI annotations (@Inject, @EJB, @PersistenceContext,...) made by the container. When you run a unit test, the test run out of the container. So the injectable attributes stay null. For unit tests always mock this kind of dependencies. Learn a little bit about managed beans (CDI,JSF), unit testing and Mocking.</p>

Title: EJB annotation not working

Body:
I have a problem with my EJB annotations:

I have a DAO:

@Singleton
@Startup
public class CassandraDAO<T extends Serializable> extends AbstractDAO {

  @PersistenceContext(unitName = "JPAService", type = PersistenceContextType.EXTENDED)
  private EntityManager em;

  @PostConstruct
  public void init() {
    System.out.println("***************** init CassandraDAO ***************************");
  }

  @PreDestroy
  public void destroy() {
    System.out.println("***************** destroying CassandraDAO *************************");
    if (em.isOpen()) {
      em.close();
    }
  }

  @Override
  public EntityManager getManager() {
    return em;
  }

  @Override
  public void setManager(EntityManager em) {
    this.em = em;
  }
}

And there are several DAOs that extends this DAO:

@Stateless
public class IOConfigurationDAO extends CassandraDAO<IOConfiguration> {
...
}

And here is how I use the DAO:

public class AddAlertTest extends TestCase {
  @EJB
  private IOConfigurationDAO ioConfigurationDAO;
  public void test() {
      ioConfigurationDAO.getManager().getTransaction().begin();
      IOConfiguration ioConfig = new IOConfiguration("CH1");
      ioConfigurationDAO.getManager().persist(ioConfig);
      ioConfigurationDAO.getManager().getTransaction().commit();
      int oldSize = ioConfig.getAlerts() == null ? 0 : ioConfig.getAlerts().size();
      System.out.println("Created IO configuration with id " + ioConfig.getIoConfigurationId());

      ioConfigurationDAO.getManager().getTransaction().begin();
      Alert alert = ioConfigurationDAO.addAlert(ioConfig,
          Operators[(int) (Math.random() * Operators.length)], new Double(Math.random() * 100));
      ioConfigurationDAO.getManager().getTransaction().commit();
      int newSize = ioConfig.getAlerts().size();
      System.out.println("Created new Alert with id " + alert.getAlertId());
      System.out.println("Alert list: " + ioConfig.getAlerts());
      System.out.println("Alert is connected to " + alert.getIoConfiguration());

      assertEquals(oldSize + 1, newSize);
      assertNotNull(ioConfigurationDAO.getManager().find(Alert.class, alert.getAlertId()));

      ioConfigurationDAO.getManager().getTransaction().begin();
      ioConfigurationDAO.getManager().remove(ioConfig);
      ioConfigurationDAO.getManager().getTransaction().commit();
      System.out.println("Deleted IO configuration with id " + ioConfig.getIoConfigurationId());
  }

But my IOConfigurationDAO is always null, so my persistenceContext annotation doesn't work at all. And there is nothing printed out in my console, so my postConstruct annotations doesn't work as well.

Here is my persistence.xml:

<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
    <persistence-unit name="JPAService">
        <provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
        <class>com.sensorhound.aigateway.domain.Alert</class>
        <class>com.sensorhound.aigateway.domain.DataSeriesMeta</class>
        <class>com.sensorhound.aigateway.domain.IOConfiguration</class>
        <class>com.sensorhound.aigateway.domain.NodeData</class>
        <properties>
            <property name="hibernate.transaction.jta.platform" value="JBossAS" />
            <property name="jboss.as.jpa.providerModule" value="org.hibernate:5.0" />
            <property name="hibernate.ogm.datastore.provider" value="cassandra_experimental"/>
            <property name="hibernate.ogm.datastore.host" value="127.0.0.1:9042"/>
            <property name="hibernate.ogm.datastore.database" value="dev"/>
            <property name="hibernate.hbm2ddl.auto" value="none"></property>
            <property name = "hibernate.show_sql" value = "true" />
            <property name = "hibernate.format_sql" value = "true" />
        </properties>
    </persistence-unit>
</persistence>

I don't know what is wrong in my configuration. Someone please help me. If you need more information, I am willing to share.

Thanks!


问:
Detect when font changes in EPUB
I am trying to use or create and event listener when the user changes the font size of the EPUB in an ereader with Javascript but I haven't find the way.

What I have tried without success:

A resize event listener.

A timing event that measures the font size.

A listener that measures the scale of the viewport.

In ebook-viewer (aka Calibre viewer) I can see in the inspector that every time I change the font size the console prints Viewport cfi: /2/4/2/2/1:1. I see that when 1:1 changes, it's some sort of scale in int numbers.

That is why I tried to detect the viewport scale with this or this.

So I suppose it is possible only because I can see trough the inspector of ebook-viewer...

All the tries didn't work on iOS either.

Update

I know about the epubReadingSystem and its limitations. Also that JS is optional for EPUB3. What I am trying to solve is that in spanish poetry when a verse is larger that the box's size, it has to be a break and the next line has to be right aligned with a bracket:

A short verse.
A very very long
         [verse.

I figured out how to make this change. The issue is that when the user changes the font, the calculation has to be done again. I tried to solve this by doing a fixed EPUB, but iBooks and ebook-viewer allow the font increase...

A working example: jsfiddle.net/dxr9azy7

答:
There is no reliable way of doing what you want, where "reliable" means "working on any possible EPUB reading system". The reason is that the EPUB specification does not provide an official way for the document to "know" the properties of the context --- e.g., the current reading settings, like font size --- of the application rendering it.

Please note that Javascript support is not present in EPUB 2, and only optional in EPUB 3, and many reading systems restrict the type of Javascript code you can have inside your EPUB.

The EPUB 3 specification introduced a epubReadingSystem object for those reading systems that support Javascript, but it does not require that it should provide e.g. event bindings that can be used by JS code inside the EPUB to react to changes e.g. in the reading settings. (See: http://www.idpf.org/epub/31/spec/epub-contentdocs.html#app-epubReadingSystem )

On the other hand, since most reading systems are indeed built on top of rendering engines like WebKit, if they allows you to run Javascript, you can indeed do some "reverse engineering" and try to fish the correct global objects they maintain and the document model they use for displaying. With a bit of luck, you might be able to register your own bindings. However, this solution would require a lot of time to figure it out, it will work only on the given reading system(s) you tested, and it might break with app updated. In short, I do not recommend trying this route.

EDIT: BTW, what you are asking is similar to what I implemented in my own EPUB 3 reading app: https://www.readbeyond.it/minstrel/developers.html#js but unfortunately it is the only app (that I know of) that implements a mechanism establishing a communication channel between the JS inside the EPUB file and the reading system.

Title: Detect when font changes in EPUB