问:
Kill children of Python subprocess after subprocess.TimeoutExpired is thrown
I am calling a shell script fom within Python, that spawns multiple child processes. I want to terminate that process and all of its children, if it did not finish after two minutes.

Is there any way I can do that with subprocess.run or do I have to go back to using Popen? Since run is blocking, I am not able to save the pid somewhere to kill the children in an extra command. A short code example:

```<code>try:
    subprocess.run(["my_shell_script"], stderr=subprocess.STDOUT, timeout=120)
except subprocess.TimeoutExpired:
    print("Timeout during execution")
</code>```

答:
Quoting from the docs:

subprocess.run - This does not capture stdout or stderr by default. To do so, pass PIPE for the stdout and/or stderr arguments.

Don't have to use Popen() if you don't want to. The other functions in the module, such as .call(), .Popen().

There are three 'file' streams: stdin for input, and stdout and stderr for output. The application decides what to write where; usually error and diagnostic information to stderr, the rest to stdout. To capture the output for either of these outputs, specify the subprocess.PIPE argument so that the 'stream' is redirected into your program.

To kill the child process after timeout:

```<code>import os
import signal
import subprocess

try:
    proc = subprocess.Popen(["ls", "-l"], stdout=PIPE, stderr=PIPE, timeout=120)
except subprocess.TimeoutExpired:
    os.kill(proc.pid, signal.SIGTERM)
</code>```

Body:
I am calling a shell script fom within Python, that spawns multiple child processes. I want to terminate that process and all of its children, if it did not finish after two minutes.

Is there any way I can do that with subprocess.run or do I have to go back to using Popen? Since run is blocking, I am not able to save the pid somewhere to kill the children in an extra command. A short code example:

try:
    subprocess.run(["my_shell_script"], stderr=subprocess.STDOUT, timeout=120)
except subprocess.TimeoutExpired:
    print("Timeout during execution")

Body:
Quoting from the docs:

subprocess.run - This does not capture stdout or stderr by default. To do so, pass PIPE for the stdout and/or stderr arguments.

Don't have to use Popen() if you don't want to. The other functions in the module, such as .call(), .Popen().

There are three 'file' streams: stdin for input, and stdout and stderr for output. The application decides what to write where; usually error and diagnostic information to stderr, the rest to stdout. To capture the output for either of these outputs, specify the subprocess.PIPE argument so that the 'stream' is redirected into your program.

To kill the child process after timeout:

import os
import signal
import subprocess

try:
    proc = subprocess.Popen(["ls", "-l"], stdout=PIPE, stderr=PIPE, timeout=120)
except subprocess.TimeoutExpired:
    os.kill(proc.pid, signal.SIGTERM)


来源: stackexchange

问:
How to specify which domain using ngrok
I use mamp and I have virtual hosts all on port 8888. For example:

site1.dev:8888

site2.dev:8888

would point to localhost/site1/, localhost/site2/ etc.

Before using virtual hosts, I would just change my docroot to whatever project I was currently working on and would start ngrok like so

./ngrok http 8888 and it would launch and give me a random generated *.ngrok.io url.

My question is how do I specify the domain now since I am using virtual hosts?

I've tried ./ngrok http site1.dev:8888 and it starts but just serves up mamps webroot.

I am using a free account.

答:
If you prefer a free option, it is possible via:</p>
```<code>ngrok http -host-header=site1.dev 80
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to specify which domain using ngrok

Body:
If you prefer a free option, it is possible via:

ngrok http -host-header=site1.dev 80

ContentLicense: CC BY-SA 4.0


问:
How can I monitor the memory used by my Azure Functions?
How can I monitor the memory used by my Azure Functions?

The pricing calculator memory goes from 128 MB, up to the 1.5 GB. And the time has a 1 second de minimus

So is the minimum cost for each call the 128 MB x 1 second charge?

And how can I check what the memory & time footprint really are?

答:
Details of how this calculation is made is provided here: Azure Functions Billing Calculations

Functions are billed based on observed resource consumption measured in Gigabyte Seconds (GB-s)

Also, there is a free grant of 4,00,000 GB-s per month.

In order to understand the billing calculations, you will also need to know how many times your function gets called in a month and what is the duration of each execution.

EDIT:

As Mikhail has suggested refer the following thread for monitoring Memory:
Azure Functions memory / consumption unit usage


问:
Dictionary in python with order I set at start
I'm making dictionary:

```<code>d = {"server":"mpilgrim", "database":"master"}
d['mynewkey'] = 'mynewvalue'
</code>```

But when I display it I saw that this dict is reversed.

```<code>print(d)

{'mynewkey': 'mynewvalue', 'database': 'master', 'server': 'mpilgrim'}
</code>```

How to reverse it back?

Or if it is true that dictionary is not sortable what I must to use to have collection where the order of that informations matters?

答:
```<code>from collections import OrderedDict

d = OrderedDict()
d["server"] = "mpilgrim"
d["database"] = "master"
d['mynewkey'] = 'mynewvalue'

print(d)

OrderedDict([('server', 'mpilgrim'), ('database', 'master'), ('mynewkey', 'mynewvalue')])
</code>```

Body:
I'm making dictionary:

d = {"server":"mpilgrim", "database":"master"}
d['mynewkey'] = 'mynewvalue'

But when I display it I saw that this dict is reversed.

print(d)

{'mynewkey': 'mynewvalue', 'database': 'master', 'server': 'mpilgrim'}

How to reverse it back?

Or if it is true that dictionary is not sortable what I must to use to have collection where the order of that informations matters?

ContentLicense: CC BY-SA 2.5


问:
-nginx, uwsgi, 502 Bad gateway on domain
I was looking all over the internet for solutions, but none helped.
I want to deploy a django project at my server pointed to vps.florisdeboer.com. I've read some tutorials and did exactly what they told me, but the 502 error keep showing up.

I've got all important files, if you miss something, please comment while I can post it as an edit.

OK, let's go:

The projectname is webshop. Nothing special, just a webshop build in django. I use db.sqlite3 as my database.

/etc/uwsgi/sites

```<code>[uwsgi]
project = webshop
uid = floris
base = /home/%(uid)

chdir = %(base)/%(project)
home = %(base)/BIT/
module = %(project).wsgi:application

master = true
processes = 5

socket = /run/uwsgi/%(project).sock
chown-socket = %(uid):www-data
chmod-socket = 660
vacuum = true

plugins=python27
</code>```

/etc/nginx/sites-enabled

```<code>server {
    listen 80;
    server_name florisdeboer.com vps.florisdeboer.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/floris/webshop;
    }

    location / {
        include         uwsgi_params;
        uwsgi_pass      unix:/run/uwsgi/website.sock;
    }
}
</code>```

And the sudo systemctl status uwsgi

```<code>● uwsgi.service - uWSGI Emperor service
   Loaded: loaded (/etc/systemd/system/uwsgi.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2017-06-17 22:13:00 CEST; 17h ago
 Main PID: 24782 (uwsgi)
   Status: "The Emperor is governing 1 vassals"
   CGroup: /system.slice/uwsgi.service
           ├─24782 /usr/local/bin/uwsgi --emperor /etc/uwsgi/sites
           ├─24785 /usr/local/bin/uwsgi --ini webshop.ini
           ├─24788 /usr/local/bin/uwsgi --ini webshop.ini
           ├─24789 /usr/local/bin/uwsgi --ini webshop.ini
           ├─24790 /usr/local/bin/uwsgi --ini webshop.ini
           ├─24791 /usr/local/bin/uwsgi --ini webshop.ini
           └─24792 /usr/local/bin/uwsgi --ini webshop.ini

Jun 18 15:54:21 srvrfloris systemd[1]: Started uWSGI Emperor service.
Jun 18 15:57:20 srvrfloris systemd[1]: Started uWSGI Emperor service.
Jun 18 15:58:18 srvrfloris systemd[1]: Started uWSGI Emperor service.
Warning: Journal has been rotated since unit was started. Log output is incomplete or una was started. Log output is incomplete or unavailable.
</code>```

Here is the same command as above but for nginx

```<code>● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2017-06-18 15:54:13 CEST; 14min ago
 Main PID: 882 (nginx)
   CGroup: /system.slice/nginx.service
           ├─882 nginx: master process /usr/sbin/nginx -g daemon on; master_process on
           └─883 nginx: worker process

Jun 18 15:54:13 srvrfloris systemd[1]: Starting A high performance web server and a revering A high performance web server and a reverse proxy server...

Jun 18 15:54:13 srvrfloris systemd[1]: nginx.service: Failed to read PID from file /run/n.service: Failed to read PID from file /run/nginx.pid: Invalid argument

Jun 18 15:54:13 srvrfloris systemd[1]: Started A high performance web server and a reversed A high performance web server and a reverse proxy server.

~
</code>```

The error-log from root $ uwsgi --ini /etc/uwsgi/sites/webshop.ini

```<code>[uWSGI] getting INI configuration from /etc/uwsgi/sites
*** WARNING: Can't find section "uwsgi" in INI configuration file /etc/uwsgi/sites ***
*** Starting uWSGI 2.0.15 (64bit) on [Sun Jun 18 23:08:20 2017] ***
compiled with version: 5.4.0 20160609 on 17 June 2017 21:30:14
os: Linux-4.4.0-66-generic #87-Ubuntu SMP Fri Mar 3 15:29:05 UTC 2017
nodename: srvrfloris
machine: x86_64
clock source: unix
detected number of CPU cores: 1
current working directory: /home/floris
detected binary path: /usr/local/bin/uwsgi
!!! no internal routing support, rebuild with pcre support !!!
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 3826
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
The -s/--socket option is missing and stdin is not a socket.
</code>```

I hope someone can help me with this!

Cheers,

Floris

答:
If the question is actual.
in that line change website to the webshop unix:/run/uwsgi/website.sock;
and reboot you droplet or server.</p>

Body:
I was looking all over the internet for solutions, but none helped.
I want to deploy a django project at my server pointed to vps.florisdeboer.com. I've read some tutorials and did exactly what they told me, but the 502 error keep showing up.

I've got all important files, if you miss something, please comment while I can post it as an edit.

OK, let's go:

The projectname is webshop. Nothing special, just a webshop build in django. I use db.sqlite3 as my database.

/etc/uwsgi/sites

[uwsgi]
project = webshop
uid = floris
base = /home/%(uid)

chdir = %(base)/%(project)
home = %(base)/BIT/
module = %(project).wsgi:application

master = true
processes = 5

socket = /run/uwsgi/%(project).sock
chown-socket = %(uid):www-data
chmod-socket = 660
vacuum = true

plugins=python27

/etc/nginx/sites-enabled

server {
    listen 80;
    server_name florisdeboer.com vps.florisdeboer.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/floris/webshop;
    }

    location / {
        include         uwsgi_params;
        uwsgi_pass      unix:/run/uwsgi/website.sock;
    }
}

And the sudo systemctl status uwsgi

● uwsgi.service - uWSGI Emperor service
   Loaded: loaded (/etc/systemd/system/uwsgi.service; enabled; vendor preset: enabled)
   Active: active (running) since Sat 2017-06-17 22:13:00 CEST; 17h ago
 Main PID: 24782 (uwsgi)
   Status: "The Emperor is governing 1 vassals"
   CGroup: /system.slice/uwsgi.service
           ├─24782 /usr/local/bin/uwsgi --emperor /etc/uwsgi/sites
           ├─24785 /usr/local/bin/uwsgi --ini webshop.ini
           ├─24788 /usr/local/bin/uwsgi --ini webshop.ini
           ├─24789 /usr/local/bin/uwsgi --ini webshop.ini
           ├─24790 /usr/local/bin/uwsgi --ini webshop.ini
           ├─24791 /usr/local/bin/uwsgi --ini webshop.ini
           └─24792 /usr/local/bin/uwsgi --ini webshop.ini

Jun 18 15:54:21 srvrfloris systemd[1]: Started uWSGI Emperor service.
Jun 18 15:57:20 srvrfloris systemd[1]: Started uWSGI Emperor service.
Jun 18 15:58:18 srvrfloris systemd[1]: Started uWSGI Emperor service.
Warning: Journal has been rotated since unit was started. Log output is incomplete or una was started. Log output is incomplete or unavailable.

Here is the same command as above but for nginx

● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2017-06-18 15:54:13 CEST; 14min ago
 Main PID: 882 (nginx)
   CGroup: /system.slice/nginx.service
           ├─882 nginx: master process /usr/sbin/nginx -g daemon on; master_process on
           └─883 nginx: worker process

Jun 18 15:54:13 srvrfloris systemd[1]: Starting A high performance web server and a revering A high performance web server and a reverse proxy server...

Jun 18 15:54:13 srvrfloris systemd[1]: nginx.service: Failed to read PID from file /run/n.service: Failed to read PID from file /run/nginx.pid: Invalid argument

Jun 18 15:54:13 srvrfloris systemd[1]: Started A high performance web server and a reversed A high performance web server and a reverse proxy server.

~

The error-log from root $ uwsgi --ini /etc/uwsgi/sites/webshop.ini

[uWSGI] getting INI configuration from /etc/uwsgi/sites
*** WARNING: Can't find section "uwsgi" in INI configuration file /etc/uwsgi/sites ***
*** Starting uWSGI 2.0.15 (64bit) on [Sun Jun 18 23:08:20 2017] ***
compiled with version: 5.4.0 20160609 on 17 June 2017 21:30:14
os: Linux-4.4.0-66-generic #87-Ubuntu SMP Fri Mar 3 15:29:05 UTC 2017
nodename: srvrfloris
machine: x86_64
clock source: unix
detected number of CPU cores: 1
current working directory: /home/floris
detected binary path: /usr/local/bin/uwsgi
!!! no internal routing support, rebuild with pcre support !!!
uWSGI running as root, you can use --uid/--gid/--chroot options
*** WARNING: you are running uWSGI as root !!! (use the --uid flag) ***
*** WARNING: you are running uWSGI without its master process manager ***
your processes number limit is 3826
your memory page size is 4096 bytes
detected max file descriptor number: 1024
lock engine: pthread robust mutexes
thunder lock: disabled (you can enable it with --thunder-lock)
The -s/--socket option is missing and stdin is not a socket.

I hope someone can help me with this!

Cheers,

Floris


问:
Triple nested model not building correctly
I have an Organisme that has many Servicepoints and each Servicepoint has many Addresses. The Servicepoint is set to accepts_nested_attributes_for :addresses so that I can create a service point and at the same time create an Address with it.

My problem is that that, I can't figure out how to create the address that will be linked to the Servicepoint and that Servicepoint be linked to the Organisme. I am creating the Servicepoint inside the show view of an Organisme.

View:

```<code><%= form_for([@organisme, @organisme.servicepoints.build]) do |f| %>
  <p>
    <%= f.label :nom %><br>
    <%= f.text_field :nom %>
  </p>
  <p>
    <%= f.label :fax %><br>
    <%= f.text_field :fax %>
  </p>
  <p>
    <%= f.label :courriel %><br>
    <%= f.email_field :courriel %>
  </p>
  <p>
    <%= f.label :telephone %><br>
    <%= f.text_field :telephone %>
  </p>
  <%= f.fields_for :addresses do |address_attributes| %>
    <p>
      <%= address_attributes.label :no_civique %><br>
      <%= address_attributes.text_field :no_civique %><br>

      <%= address_attributes.label :rue %><br>
      <%= address_attributes.text_field :rue %><br>

      <%= address_attributes.label :ville %><br>
      <%= address_attributes.text_field :ville %><br>

      <%= address_attributes.label :province %><br>
      <%= address_attributes.text_field :province %><br>

      <%= address_attributes.label :etat %><br>
      <%= address_attributes.text_field :etat %><br>

      <%= address_attributes.label :code_postal %><br>
      <%= address_attributes.text_field :code_postal %><br>
    </p>
<% end %>
  <p>
    <%= f.submit :Ajouter, class: 'btn btn-info' %>
  </p>
<% end %>
</code>```

Controller:

organisme/show

```<code>def show
 @organisme = Organisme.find(params[:id])
end
</code>```

servicepoint/create

```<code>def create

  @organisme = Organisme.find(params[:organisme_id])

  @servicepoint = @organisme.servicepoints.create(servicepoint_params)

  redirect_to organisme_path(@organisme)

end

private
  def servicepoint_params
    params.require(:servicepoint).permit(:nom, :fax, :courriel, :telephone, addresses_attributes: [:id, :no_civique, :rue, :ville, :province, :etat, :code_postal])
end
</code>```

Routes:

```<code>resources :organismes do
  member { patch :activate }
  member { patch :deactivate }
  resources :addresses
  resources :servicepoints do
    resources :addresses
  end
end
</code>```

My problem right now is that the Address input information isn't even showing. I tried having a @servicepoint variable and then creating everything with that but the problem with that was that I could not link it to the Organisme.

If you need any more information I'll be happy to add anything.

Models:

```<code>class Organisme < ApplicationRecord
   has_many :addresses
   accepts_nested_attributes_for :addresses
   has_many :servicepoints
end

class Servicepoint < ApplicationRecord
   has_many :addresses
   accepts_nested_attributes_for :addresses
   belongs_to :organisme
end

class Address < ApplicationRecord
  belongs_to :organismereferent, optional: true
  belongs_to :organisme, optional: true
  belongs_to :servicepoint, optional: true
end
</code>```

答:
In the form you build a servicepoint, so an empty serviceform is shown as an empty form. No adress are shown because there is no address to iterate on. You need to build addresses too.

Be aware that your form will never allow you to edit servicepoint(s), because of the build in the form itself. And to allow the form to show more than one servicepoint, you need to iterate servicepoints somewhere.

Body:
I have an Organisme that has many Servicepoints and each Servicepoint has many Addresses. The Servicepoint is set to accepts_nested_attributes_for :addresses so that I can create a service point and at the same time create an Address with it.

My problem is that that, I can't figure out how to create the address that will be linked to the Servicepoint and that Servicepoint be linked to the Organisme. I am creating the Servicepoint inside the show view of an Organisme.

View:

<%= form_for([@organisme, @organisme.servicepoints.build]) do |f| %>

    <%= f.label :nom %>

    <%= f.text_field :nom %>

    <%= f.label :fax %>

    <%= f.text_field :fax %>

    <%= f.label :courriel %>

    <%= f.email_field :courriel %>

    <%= f.label :telephone %>

    <%= f.text_field :telephone %>

  <%= f.fields_for :addresses do |address_attributes| %>

      <%= address_attributes.label :no_civique %>

      <%= address_attributes.text_field :no_civique %>

      <%= address_attributes.label :rue %>

      <%= address_attributes.text_field :rue %>

      <%= address_attributes.label :ville %>

      <%= address_attributes.text_field :ville %>

      <%= address_attributes.label :province %>

      <%= address_attributes.text_field :province %>

      <%= address_attributes.label :etat %>

      <%= address_attributes.text_field :etat %>

      <%= address_attributes.label :code_postal %>

      <%= address_attributes.text_field :code_postal %>

<% end %>

    <%= f.submit :Ajouter, class: 'btn btn-info' %>

<% end %>

Controller:

organisme/show

def show
 @organisme = Organisme.find(params[:id])
end

servicepoint/create

def create

  @organisme = Organisme.find(params[:organisme_id])

  @servicepoint = @organisme.servicepoints.create(servicepoint_params)

  redirect_to organisme_path(@organisme)

end

private
  def servicepoint_params
    params.require(:servicepoint).permit(:nom, :fax, :courriel, :telephone, addresses_attributes: [:id, :no_civique, :rue, :ville, :province, :etat, :code_postal])
end

Routes:

resources :organismes do
  member { patch :activate }
  member { patch :deactivate }
  resources :addresses
  resources :servicepoints do
    resources :addresses
  end
end

My problem right now is that the Address input information isn't even showing. I tried having a @servicepoint variable and then creating everything with that but the problem with that was that I could not link it to the Organisme.

If you need any more information I'll be happy to add anything.

Models:

class Organisme < ApplicationRecord
   has_many :addresses
   accepts_nested_attributes_for :addresses
   has_many :servicepoints
end

class Servicepoint < ApplicationRecord
   has_many :addresses
   accepts_nested_attributes_for :addresses
   belongs_to :organisme
end

class Address < ApplicationRecord
  belongs_to :organismereferent, optional: true
  belongs_to :organisme, optional: true
  belongs_to :servicepoint, optional: true
end


问:
Round corners of table
I try to make round corners of my table

Here is  my code

      Hours Monday

      Hours Tuesday

      Hours Wednesday

      Hours  Thursday

      Hours  Friday

      Hours Saturday

      Hours Sunday

08.00

09.00

10.00

11.00

12.00

13.00

14.00

15.00

16.00

17.00

18.00

19.00

```

But it not works.

Where is trouble?

How I can make it rounded?

EDIT

I added whole code oа View for full understanding of problem. I see border, but not with rounded corners

答:
Your code is perfect. Run code snippet if you want to.

      Hours Monday

      Hours Tuesday

      Hours Wednesday

      Hours  Thursday

      Hours  Friday

      Hours Saturday

      Hours Sunday

08.00

09.00

10.00

11.00

12.00

13.00

14.00

15.00

16.00

17.00

18.00

19.00

```

Title: Round corners of table

Body:
I try to make round corners of my table

Here is  my code

      Hours Monday

      Hours Tuesday

      Hours Wednesday

      Hours  Thursday

      Hours  Friday

      Hours Saturday

      Hours Sunday

08.00

09.00

10.00

11.00

12.00

13.00

14.00

15.00

16.00

17.00

18.00

19.00

But it not works.

Where is trouble?

How I can make it rounded?

EDIT

I added whole code oа View for full understanding of problem. I see border, but not with rounded corners

Body:
Your code is perfect. Run code snippet if you want to.

<table class="table" style="width: 100%;border-style: solid; border-color: #1d69b4;border-radius: 10px;">
  <tr style="background: white;">
    <th style="font-size: 18px; text-align: center;">
      <b>Hours</b><b style="margin-left: 30px;"> Monday</b>
    </th>
    <th style="font-size: 20px; text-align: center;">
      <b>Hours</b><b style="margin-left: 30px;"> Tuesday</b>
    </th>
    <th style="font-size: 20px; text-align: center;">
      <b>Hours</b><b style="margin-left: 30px;"> Wednesday</b>
    </th>
    <th style="font-size: 20px; text-align: center;">
      <b>Hours</b><b style="margin-left: 30px;">  Thursday</b>
    </th>
    <th style="font-size: 20px; text-align: center;">
      <b>Hours</b><b style="margin-left: 30px;">  Friday</b>
    </th>
    <th style="font-size: 20px; text-align: center;">
      <b>Hours</b><b style="margin-left: 30px;"> Saturday</b>
    </th>
    <th style="font-size: 20px; text-align: center;">
      <b>Hours</b><b style="margin-left: 30px;"> Sunday</b>
    </th>

  </tr>
  <tr>
    <td class="title" style="text-align: center; font-size: 20px;">
      <div style="margin-top: 10px;"><b class="blue-text">08.00</b></div>
      <div style="margin-top: 10px;"><b class="blue-text">09.00</b></div>
      <div style="margin-top: 10px;"><b class="blue-text">10.00</b></div>
      <div style="margin-top: 10px;"><b class="blue-text">11.00</b></div>
      <div style="margin-top: 10px;"><b class="blue-text">12.00</b></div>
      <div style="margin-top: 10px;"><b class="blue-text">13.00</b></div>
      <div style="margin-top: 10px;"><b class="blue-text">14.00</b></div>
      <div style="margin-top: 10px;"><b class="blue-text">15.00</b></div>
      <div style="margin-top: 10px;"><b class="blue-text">16.00</b></div>
      <div style="margin-top: 10px;"><b class="blue-text">17.00</b></div>
      <div style="margin-top: 10px;"><b class="blue-text">18.00</b></div>
      <div style="margin-top: 10px;"><b class="blue-text">19.00</b></div>
    </td>

  </tr>
</table>


问:
Tree of mutable slices
Some algorithms recursively partition an array into smaller pieces. You can build an explicit binary tree that results from such a process, where each leaf holds a disjoint slice of the array. If you need to alter or reorder elements in the leaf, its slice must be mutable.

```<code>enum Tree<'a> {
    Branch(Box<[Tree<'a>; 2]>),
    Leaf(&'a mut[f32]),
}
</code>```

Suppose I need to split all the leaves that are larger than some threshold. Easy: recursively walk down the tree from the root; when I find a leaf with a slice long enough, split it into 2 halves, wrap them into a 2-leaf subtree, and replace the leaf.

```<code>impl<'a> Tree<'a> {
    fn split(&mut self, max: usize) {
        match self {
            &mut Tree::Branch(ref mut trees) => {
                trees[0].split(max);
                trees[1].split(max);
            },
            &mut Tree::Leaf(ref mut leaf) if leaf.len() > max => {
                let mid = leaf.len() / 2;
                let (l, r) = leaf.split_at_mut(mid);
                let trees = [Tree::Leaf(l), Tree::Leaf(r)];
                *self = Tree::Branch(Box::new(trees));
            },
        }
    }
}
</code>```

Unfortunately, the borrow-checker is unable to find a suitable lifetime for the ref mut leaf pattern. It wants it dead before allowing the assignement to *self, but I don't see how to make the assignment out of the match arm.

How to make this work?

答:
I'm not sure how to fix the whole case, but I might be able to lead you in the right direction. First, you need to be explicit about the lifetime of self:

```<code>fn split(&'a mut self, max: usize)
</code>```

The next issue is a non-exhaustive match; this can be easily avoided (for now) with the following base case:

```<code>_ => unimplemented!()
</code>```

Now the issue is that you mutably borrow trees twice in the first match arm; this can be solved by using a loop:

```<code>&mut Tree::Branch(ref mut trees) => {
    for tree in trees.iter_mut() {
        tree.split(max);
    }
}
</code>```

Now you have:

```<code>error[E0506]: cannot assign to `*self` because it is borrowed
  --> <anon>:18:17
   |
14 |             &mut Tree::Leaf(ref mut leaf) if leaf.len() > max => {
   |                             ------------ borrow of `*self` occurs here
...
18 |                 *self = Tree::Branch(Box::new(trees));
   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `*self` occurs here
</code>```

This can be avoided by not destructuring the Leaf in the match arm and using a helper function:

```<code>impl<'a> Tree<'a> {
    fn get_trees(&'a mut self, max: usize) -> Option<[Tree<'a>; 2]> {
        if let &mut Tree::Leaf(ref mut leaf) = self {
            if leaf.len() > max {
                let mid = leaf.len() / 2;
                let (l, r) = leaf.split_at_mut(mid);
                Some([Tree::Leaf(l), Tree::Leaf(r)])
            } else {
                None
            }
        } else {
            None
        }
    }
}
</code>```

and

```<code>&mut Tree::Leaf(_) => {
    let trees = self.get_trees(max).unwrap(); // safe (under a valid match arm)
    *self = Tree::Branch(Box::new(trees));
}
</code>```

Now comes a bigger problem, because you can't assign to self while borrowing from it. I would consider making it Cloneable (and creating trees based on a copy of self), but in your case it can't be derived automatically; maybe someone else will have a better idea.

Full code in the Rust playground

Title: Tree of mutable slices

Body:
Some algorithms recursively partition an array into smaller pieces. You can build an explicit binary tree that results from such a process, where each leaf holds a disjoint slice of the array. If you need to alter or reorder elements in the leaf, its slice must be mutable.

enum Tree<'a> {
    Branch(Box<[Tree<'a>; 2]>),
    Leaf(&'a mut[f32]),
}

Suppose I need to split all the leaves that are larger than some threshold. Easy: recursively walk down the tree from the root; when I find a leaf with a slice long enough, split it into 2 halves, wrap them into a 2-leaf subtree, and replace the leaf.

impl<'a> Tree<'a> {
    fn split(&mut self, max: usize) {
        match self {
            &mut Tree::Branch(ref mut trees) => {
                trees[0].split(max);
                trees[1].split(max);
            },
            &mut Tree::Leaf(ref mut leaf) if leaf.len() > max => {
                let mid = leaf.len() / 2;
                let (l, r) = leaf.split_at_mut(mid);
                let trees = [Tree::Leaf(l), Tree::Leaf(r)];
                *self = Tree::Branch(Box::new(trees));
            },
        }
    }
}

Unfortunately, the borrow-checker is unable to find a suitable lifetime for the ref mut leaf pattern. It wants it dead before allowing the assignement to *self, but I don't see how to make the assignment out of the match arm.

How to make this work?

Body:
I'm not sure how to fix the whole case, but I might be able to lead you in the right direction. First, you need to be explicit about the lifetime of self:

fn split(&'a mut self, max: usize)

The next issue is a non-exhaustive match; this can be easily avoided (for now) with the following base case:

_ => unimplemented!()

Now the issue is that you mutably borrow trees twice in the first match arm; this can be solved by using a loop:

&mut Tree::Branch(ref mut trees) => {
    for tree in trees.iter_mut() {
        tree.split(max);
    }
}

Now you have:

error[E0506]: cannot assign to `*self` because it is borrowed
  --> <anon>:18:17
   |
14 |             &mut Tree::Leaf(ref mut leaf) if leaf.len() > max => {
   |                             ------------ borrow of `*self` occurs here
...
18 |                 *self = Tree::Branch(Box::new(trees));
   |                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ assignment to borrowed `*self` occurs here

This can be avoided by not destructuring the Leaf in the match arm and using a helper function:

impl<'a> Tree<'a> {
    fn get_trees(&'a mut self, max: usize) -> Option<[Tree<'a>; 2]> {
        if let &mut Tree::Leaf(ref mut leaf) = self {
            if leaf.len() > max {
                let mid = leaf.len() / 2;
                let (l, r) = leaf.split_at_mut(mid);
                Some([Tree::Leaf(l), Tree::Leaf(r)])
            } else {
                None
            }
        } else {
            None
        }
    }
}

and

&mut Tree::Leaf(_) => {
    let trees = self.get_trees(max).unwrap(); // safe (under a valid match arm)
    *self = Tree::Branch(Box::new(trees));
}

Now comes a bigger problem, because you can't assign to self while borrowing from it. I would consider making it Cloneable (and creating trees based on a copy of self), but in your case it can't be derived automatically; maybe someone else will have a better idea.

Full code in the Rust playground


问:
How to use a variable from an Angular Service
Inside of my Angular Service I have a method that I do the logic for getting the next item, in a pagination. This method returns the name of the page where I will navigate if I click next on pagination buttons.

Because I did the logic in this method, from here I need the active class, to implement it in the sidebar component. In the sidebar I have to set the active url to mach my link and to make it diff color with css.

The navigate method from my Service

```<code>private _pages = [
{name: '/page1', index: 0},
{name: '/page2', index: 1},
{name: '/page3', index: 2}
];

public activeClass;
private _current = null;

public getCurrent() {
    return this._current;
}

public navigate(action: string) {
    if (typeof this.ACTIONS[action] === 'undefined')
      return;

    let shift = this.ACTIONS[action];
    this.setCurrent(shift);

    const curr = this.getCurrent();
    this.activeClass = 'done-' + curr.index;
    return this.router.navigate([curr.name]);
}
</code>```

In my sidebar I injected the service and in the ts file I want to get the activeClass from my Service like this:

```<code>public activeClasss() {
    this.activeClass = this.PrevNextService.activeClass;
  }
</code>```

And to use it in the sidebar html like this:

```<code><div class="list-group-wrapper" [ngClass]="activeClasss()">
</code>```

Of course I did some SASS rules that with a for loop takes care of each class.

My problem is that I can't take that activeClass from my Service in the way that I put above, because I get an error. I can't declare this activeClass outside my navigate(), from Service, because in navigate() I create the logic that when I use it I can see the current url.

So is it any way to get this

```<code>this.activeClass = 'done-' + curr.index;
</code>```

from my Service method and use it the sidebar ts file?

答:
What is wrong with your code? In HTML you use a function:

```<code><div class="list-group-wrapper" [ngClass]="activeClasss()">
</code>```

But that function does not return anything

```<code>public activeClasss() {
    this.activeClass = this.PrevNextService.activeClass;
}
</code>```

Use in template Component variable or return something from function. Code you have should be working fine...

Body:
Inside of my Angular Service I have a method that I do the logic for getting the next item, in a pagination. This method returns the name of the page where I will navigate if I click next on pagination buttons.

Because I did the logic in this method, from here I need the active class, to implement it in the sidebar component. In the sidebar I have to set the active url to mach my link and to make it diff color with css.

The navigate method from my Service

private _pages = [
{name: '/page1', index: 0},
{name: '/page2', index: 1},
{name: '/page3', index: 2}
];

public activeClass;
private _current = null;

public getCurrent() {
    return this._current;
}

public navigate(action: string) {
    if (typeof this.ACTIONS[action] === 'undefined')
      return;

    let shift = this.ACTIONS[action];
    this.setCurrent(shift);

    const curr = this.getCurrent();
    this.activeClass = 'done-' + curr.index;
    return this.router.navigate([curr.name]);
}

In my sidebar I injected the service and in the ts file I want to get the activeClass from my Service like this:

public activeClasss() {
    this.activeClass = this.PrevNextService.activeClass;
  }

And to use it in the sidebar html like this:

Of course I did some SASS rules that with a for loop takes care of each class.

My problem is that I can't take that activeClass from my Service in the way that I put above, because I get an error. I can't declare this activeClass outside my navigate(), from Service, because in navigate() I create the logic that when I use it I can see the current url.

So is it any way to get this

this.activeClass = 'done-' + curr.index;

from my Service method and use it the sidebar ts file?

Body:
What is wrong with your code? In HTML you use a function:

<div class="list-group-wrapper" [ngClass]="activeClasss()">

But that function does not return anything

public activeClasss() {
    this.activeClass = this.PrevNextService.activeClass;
}

Use in template Component variable or return something from function. Code you have should be working fine...


问:
PHP download adding underscores
I am trying to download the file that is passed in by the POST value. However if the file name is "Functional requirements example" when downloaded its name will be "__Functional"

Am I doing something very wrong here?
The downloaded file is in a folder called folder1. Unsure how to download the file from there. Any ideas how I can fix this so it downloads proper?

```<code> <?php
    $ticType = $_POST['submit_param'];
    header('Content-type: text/plain');
    header('Content-Disposition: attachment; filename=\"/'.$ticType.'\"');
    readfile('folder1/'.$ticType);
    ?>
</code>```

答: If i'm not in error, you must not enclose your file name in ' or " because they are treated as characters of the name. You are using two invalid characters: / and " that in a filename cannot be used, so PHP replace them with an underscore for every invalid character. Remove this chars and you should resolve!

Title: PHP download adding underscores

Body:
I am trying to download the file that is passed in by the POST value. However if the file name is "Functional requirements example" when downloaded its name will be "__Functional"

Am I doing something very wrong here?
The downloaded file is in a folder called folder1. Unsure how to download the file from there. Any ideas how I can fix this so it downloads proper?

 <?php
    $ticType = $_POST['submit_param'];
    header('Content-type: text/plain');
    header('Content-Disposition: attachment; filename=\"/'.$ticType.'\"');
    readfile('folder1/'.$ticType);
    ?>


问:
C: read in more than one file
Hey guys using POSIX API system calls read, write, open, etc. I can open, read, write to a file  and copy its contents to an output file. How would I go about copying more than one file to an output file using related system calls only?

I currently have:

```<code>filein = open(argv[1],O_RDONLY,0);
</code>```

to open one file.(which is argv1 but I'd like to know how to do argv2 and argv3 etc.)

I tried :

```<code>j=0;
filein = open(argv[j],O_RDONLY,0);
</code>```

but that prints out contents of argv0 into my outputfile.

I am stuck on the next stage to do more than one file. (I also have an EOF loop so after 1 file it exits-How would I make this continue for the next file).

Please could you help me with how to approach the next stage? Thanks.

答:
to open one file.(which is argv1 but I'd like to know how to do argv2 and argv3 etc.)

fopen(argv[2], ...)

Title: C: read in more than one file

Body:
Hey guys using POSIX API system calls read, write, open, etc. I can open, read, write to a file  and copy its contents to an output file. How would I go about copying more than one file to an output file using related system calls only?

I currently have:

filein = open(argv[1],O_RDONLY,0);

to open one file.(which is argv1 but I'd like to know how to do argv2 and argv3 etc.)

I tried :

j=0;
filein = open(argv[j],O_RDONLY,0);

but that prints out contents of argv0 into my outputfile.

I am stuck on the next stage to do more than one file. (I also have an EOF loop so after 1 file it exits-How would I make this continue for the next file).

Please could you help me with how to approach the next stage? Thanks.


问:
C# Monogame Performance when Drawing Thousands of SpriteBatch.DrawString()
I'm currently creating a large map, that consists of a lot of rectangles (33,844), that all have a unique name (label), which I'm drawing on top of them using a SpriteFont.

Drawing all of the rectangles takes no performance hit at all. But, as soon as I try to write all of their labels with DrawString(), my performance goes into the dumps.

In my head, I would like to draw all my rectangles and text to one texture all at once, and only have to keep redrawing that entire finished texture. My issue is, this is an enormous map, and some of the coordinates for the rectangles are very high (example: one slot's x is 14869 and y is 23622), and they're far bigger than a Texture2D allows.

Since this is a map, I really only need to draw the entire thing once, and then allow the user to scroll/move around it. There's no need for me to continually redraw all of the individual rectangles and their labels.

Does anyone have experience with this type of situation?

答:
There are two ways to solve your problem.

You can either render your map to a RenderTarget(2D/3D) or you can cull the rectangles/text that are offscreen. However, I am not 100% sure that RenderTargets can go as large as you would need, but you could always segment your map into multiple smaller RenderTargets.

From more information on RenderTargets, you might want to check out RB Whitaker's article on them, http://rbwhitaker.wikidot.com/render-to-texture

Culling, in case you are familiar with the term when used in this context, means to only render what is visible to the end-user. There are various ways that culling can be implemented. This does however require you to have already implemented a camera (or some type of view region) and you perform a basic axis-aligned bounding box collision (AABB collision, which MonoGame's Rectangle supports out of the box) of the rectangles against the camera's viewport and only render it if there is a collision.

A basic implementation of culling would look something like this:

```<code>Rectangle myRect = new Rectangle(100, 100, 48, 32);
public void DrawMapItem(SpriteBatch batch, Rectangle viewRegion)
{
    if (viewRegion.Contains(myRect))
    {
        //Render your object here with the SpriteBatch
    }
}
</code>```

Where 'viewRegion' is the area of you world that the camera/end-user can actually see.

You can also combine the two methods, and render the map to multiple render targets, and then cull the render targets.

Hope this helps!

Body:
There are two ways to solve your problem.

You can either render your map to a RenderTarget(2D/3D) or you can cull the rectangles/text that are offscreen. However, I am not 100% sure that RenderTargets can go as large as you would need, but you could always segment your map into multiple smaller RenderTargets.

From more information on RenderTargets, you might want to check out RB Whitaker's article on them, http://rbwhitaker.wikidot.com/render-to-texture

Culling, in case you are familiar with the term when used in this context, means to only render what is visible to the end-user. There are various ways that culling can be implemented. This does however require you to have already implemented a camera (or some type of view region) and you perform a basic axis-aligned bounding box collision (AABB collision, which MonoGame's Rectangle supports out of the box) of the rectangles against the camera's viewport and only render it if there is a collision.

A basic implementation of culling would look something like this:

Rectangle myRect = new Rectangle(100, 100, 48, 32);
public void DrawMapItem(SpriteBatch batch, Rectangle viewRegion)
{
    if (viewRegion.Contains(myRect))
    {
        //Render your object here with the SpriteBatch
    }
}

Where 'viewRegion' is the area of you world that the camera/end-user can actually see.

You can also combine the two methods, and render the map to multiple render targets, and then cull the render targets.

Hope this helps!


问:
Bind table row's class to checkbox checked state
I created a table where the first column contains a checkbox that is used to select its parent row. I'm trying to style the table so that the whole row has a blue background when selected.

component typescript:

```<code>public items = [{ name: 'row 1' }, { name: 'row 2' }, { name: 'etc' }];
</code>```

component template:

```<code><table>
    <tr>
      <th><!-- selector column --></th>
      <th>Item</th>
    </tr>
    <tr *ngFor="let item of items" [ngClass]="{ selected: selector.checked }">
      <td><input #selector type="checkbox"></td>
      <td>{{item.name}}</td>
    </tr>
</table>
</code>```

component stylesheet:

```<code>tr.selected {
  background-color: blue;
}
</code>```

Binding ngClass to the checked state of the checkbox in each row appears to work at least partially. When a box is checked, the selected class is added to the row but only after a very noticeable delay.

I believe that the class is not added until after change detection runs and it appears that the act of checking the box does not trigger change detection.

Am I doing something wrong? My component uses the default change detection strategy.

Angular 4.1.3

Here is a Plunkr demo: https://plnkr.co/edit/Tj6IU5?p=preview

答:
```<code><ng-container *ngFor="let item of items">
  <tr [ngClass]="{ selected: selector.checked }">
    <td><input #selector type="checkbox"></td>
    <td>{{item.name}}</td>
  </tr>
</ng-container>
</code>```

or

```<code><tr *ngFor="let item of items; let i=index" [ngClass]="{ selected: inputs[i] }">
  <td><input type="checkbox" (change)="inputs[i] = $event.target.value"></td>
  <td>{{item.name}}</td>
</tr>
</code>```

```<code>...
this.items = ...;
this.inputs = new Array(this.items.length);
this.inputs.fill(false);
</code>```

Body:
I created a table where the first column contains a checkbox that is used to select its parent row. I'm trying to style the table so that the whole row has a blue background when selected.

component typescript:

public items = [{ name: 'row 1' }, { name: 'row 2' }, { name: 'etc' }];

component template:

      Item

      <input #selector type="checkbox">
      {{item.name}}

component stylesheet:

tr.selected {
  background-color: blue;
}

Binding ngClass to the checked state of the checkbox in each row appears to work at least partially. When a box is checked, the selected class is added to the row but only after a very noticeable delay.

I believe that the class is not added until after change detection runs and it appears that the act of checking the box does not trigger change detection.

Am I doing something wrong? My component uses the default change detection strategy.

Angular 4.1.3

Here is a Plunkr demo: https://plnkr.co/edit/Tj6IU5?p=preview

Body:
<ng-container *ngFor="let item of items">
  <tr [ngClass]="{ selected: selector.checked }">
    <td><input #selector type="checkbox"></td>
    <td>{{item.name}}</td>
  </tr>
</ng-container>

or

<tr *ngFor="let item of items; let i=index" [ngClass]="{ selected: inputs[i] }">
  <td><input type="checkbox" (change)="inputs[i] = $event.target.value"></td>
  <td>{{item.name}}</td>
</tr>

...
this.items = ...;
this.inputs = new Array(this.items.length);
this.inputs.fill(false);


问:
Win32 windowless application - wait for program exit
I have a windowless application whose only purpose is to install a 32 bit hook DLL file and wait until the parent program (a 64-bit program) exits. The 64-bit program is written in C#, and the windowless application is written in C++. I originally had this GetMessage loop which held the program open:

```<code>while(GetMessage(&msg, NULL, 0, 0) > 0)
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}
</code>```

I was closing the C++ application using the Process.Kill method in C#, but I found out that that isn't allowing the C++ application to close cleanly. Also, if the C# application crashed, the C++ application would stay open forever. I made the C++ application check to see if the C# application is still running, using this loop:

```<code>while(true)
{
    if(PeekMessage(&msg, NULL, 0, 0, true))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    if(!isMainProgramRunning())
        break;

    Sleep(1000);
}
</code>```

For some reason the Sleep causes problems. The hooks installed by the DLL file are WH_CBT and WH_KEYBOARD. Whenever I press a key while the C++ application is running with this loop, the keys just get eaten up. Removing the Sleep makes it work fine, but, as expected, it uses 100% CPU, which I don't want. I tried removing the message loop altogether and instead using WaitForSingleObject with an infinite timeout on a thread which would end when isMainProgramRunning returned false. This basically locks up the whole computer.

I don't really understand why GetMessage, which, as far as I saw, never returned, but suspended the main thread indefinitely, didn't cause these problems yet WaitForSingleObject causes every application to freeze when I click on it. How can I get the C++ application to stay open until the C# application closes?

Edit:

Since it's been pointed out to me that sleeping in a message pump is bad, let me ask this: Is there a way to specify a timeout on the message waiting, so the program isn't waiting indefinitely for a message, but rather, will wait about 250 ms, timeout, let me run the isMainProgramRunning method, then wait some more?

Edit2:

I tried using MsgWaitForMultipleObjects, although in a somewhat different way than Leo suggested.  This is the loop I used:

```<code>while(MsgWaitForMultipleObjects (0, NULL, true, 250, QS_ALLPOSTMESSAGE) != WAIT_FAILED)
{
    if(PeekMessage(&msg, NULL, 0, 0, true))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    if(!isMainProgramRunning())
        break;
}
</code>```

Again I had the same problem with the Sleep. I also tried suspending the main thread and having the other thread resume it. Same problem. What is it that GetMessage does that allows it to wait without causing these problems? Maybe this should be the subject of another post, but why is it that when the C++ application installing the hooks sleeps or is suspended, all processing in the hooks seems to suspend as well?

Edit3:

Here is the DLL method that the C++ application calls to install the hooks:

```<code>extern "C" __declspec(dllexport) void install()
{
    cbtHook = SetWindowsHookEx(WH_CBT, hookWindowEvents, hinst, NULL);

    if(cbtHook == NULL)
        MessageBox(NULL, "Unable to install CBT hook", "Error!", MB_OK);

    keyHook = SetWindowsHookEx(WH_KEYBOARD, LowLevelKeyboardProc, hinst, NULL);

    if(keyHook == NULL)
        MessageBox(NULL, "Unable to install key hook", "Error!", MB_OK);
}
</code>```

答:
GetMessage never returns is because you don't have a window created!

To use a message-queue you have to have some GUI. You Can for instance create a hidden window.

Body:
I have a windowless application whose only purpose is to install a 32 bit hook DLL file and wait until the parent program (a 64-bit program) exits. The 64-bit program is written in C#, and the windowless application is written in C++. I originally had this GetMessage loop which held the program open:

while(GetMessage(&msg, NULL, 0, 0) > 0)
{
    TranslateMessage(&msg);
    DispatchMessage(&msg);
}

I was closing the C++ application using the Process.Kill method in C#, but I found out that that isn't allowing the C++ application to close cleanly. Also, if the C# application crashed, the C++ application would stay open forever. I made the C++ application check to see if the C# application is still running, using this loop:

while(true)
{
    if(PeekMessage(&msg, NULL, 0, 0, true))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    if(!isMainProgramRunning())
        break;

    Sleep(1000);
}

For some reason the Sleep causes problems. The hooks installed by the DLL file are WH_CBT and WH_KEYBOARD. Whenever I press a key while the C++ application is running with this loop, the keys just get eaten up. Removing the Sleep makes it work fine, but, as expected, it uses 100% CPU, which I don't want. I tried removing the message loop altogether and instead using WaitForSingleObject with an infinite timeout on a thread which would end when isMainProgramRunning returned false. This basically locks up the whole computer.

I don't really understand why GetMessage, which, as far as I saw, never returned, but suspended the main thread indefinitely, didn't cause these problems yet WaitForSingleObject causes every application to freeze when I click on it. How can I get the C++ application to stay open until the C# application closes?

Edit:

Since it's been pointed out to me that sleeping in a message pump is bad, let me ask this: Is there a way to specify a timeout on the message waiting, so the program isn't waiting indefinitely for a message, but rather, will wait about 250 ms, timeout, let me run the isMainProgramRunning method, then wait some more?

Edit2:

I tried using MsgWaitForMultipleObjects, although in a somewhat different way than Leo suggested.  This is the loop I used:

while(MsgWaitForMultipleObjects (0, NULL, true, 250, QS_ALLPOSTMESSAGE) != WAIT_FAILED)
{
    if(PeekMessage(&msg, NULL, 0, 0, true))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    if(!isMainProgramRunning())
        break;
}

Again I had the same problem with the Sleep. I also tried suspending the main thread and having the other thread resume it. Same problem. What is it that GetMessage does that allows it to wait without causing these problems? Maybe this should be the subject of another post, but why is it that when the C++ application installing the hooks sleeps or is suspended, all processing in the hooks seems to suspend as well?

Edit3:

Here is the DLL method that the C++ application calls to install the hooks:

extern "C" __declspec(dllexport) void install()
{
    cbtHook = SetWindowsHookEx(WH_CBT, hookWindowEvents, hinst, NULL);

    if(cbtHook == NULL)
        MessageBox(NULL, "Unable to install CBT hook", "Error!", MB_OK);

    keyHook = SetWindowsHookEx(WH_KEYBOARD, LowLevelKeyboardProc, hinst, NULL);

    if(keyHook == NULL)
        MessageBox(NULL, "Unable to install key hook", "Error!", MB_OK);
}


问:
How to Display Wrapper Class Variable in Apex Controller
Find the link and provide me the solution for that.

I could paste the code here directly,so fine the link

click here to view the code

答:
```<code>for(Restaurantwrapper.cls_nearby_restaurants nearby_restaurant : Restaurantwrapper.nearby_restaurants){
    String name = nearby_restaurant.restaurant.name;
}
</code>```


问:
List the names of people that have never scored above 3
From a table like this:

```<code>Name   | Score
------ | ------
Bill   | 1
Bill   | 2
Bill   | 1
Steve  | 1
Steve  | 4
Steve  | 1
</code>```

Return the names of people that have never scored above 3

Answer would be:

```<code>Name   |
------ |
Bill   |
</code>```

答:
The key is to get the maximum score for each person, then filter to those whose maximum is less than 3. To get the maximum you need to do an aggregate (GROUP BY and MAX). Then to apply filters to aggregates you must use HAVING rather than WHERE. So you would end up with:

```<code>SELECT Name, MAX(Score) AS HighScore
FROM Table
GROUP BY Name
HAVING MAX(Score) <= 3;
</code>```

Body:
From a table like this:

Name   | Score
------ | ------
Bill   | 1
Bill   | 2
Bill   | 1
Steve  | 1
Steve  | 4
Steve  | 1

Return the names of people that have never scored above 3

Answer would be:

Name   |
------ |
Bill   |

Body:
The key is to get the maximum score for each person, then filter to those whose maximum is less than 3. To get the maximum you need to do an aggregate (GROUP BY and MAX). Then to apply filters to aggregates you must use HAVING rather than WHERE. So you would end up with:

SELECT Name, MAX(Score) AS HighScore
FROM Table
GROUP BY Name
HAVING MAX(Score) <= 3;


问:
Placeholder text not visible for mdInput (material design for Angular2)
Update: I have now made the two completely identical. My local version being served with npm run lite and the Plunker version are 100% the same and yet my local version does not get the placeholder text.

I have a large Angular2 (2.4.9) application going and I started using Google's @angular/material (2.0.0-beta.2) - specifically their mdInput.

I noticed that the placeholder text is not visible unless I add css like input::-webkit-input-placeholder{ color:black;}, but then it does not disappear when the user clicks in the field (when the animation starts that moves it to float above the input), it only disappears when the user starts typing.

I then pulled apart my very large application to get as minimal an example as possible so I could post a plunker of this.  The version running locally and the Plunker version are now 100% the same.

So why does the Plunker example work but not my local version?

Here are the ALL the differences (After updates, no differences remain between Plunker and local version.):

app.component.ts:
(moved file out of sub directory and served directly, not from build folder.  Plunker and local are now identcal)

index.html:
(Updated so these are now identical, problem remains)

systemjs.config.js:
(Updated so these are now identical.  Moved components into root directory to match Plunker.  Problem remains.)

Packages section in my file:
(Updated so they are now identical.)

Full plunker files:

app.component.html:

<md-input-container>
  <input mdInput placeholder="Favorite food">
</md-input-container>

```

<p><strong>app.component.ts</strong></p>

<pre class="lang-ts prettyprint-override"><code>import { Component } from '@angular/core';

@Component({
  selector: 'app',
  templateUrl:'./app.component.html'
})
export class AppComponent {

}
</code>```

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import {MaterialModule } from '@angular/material';
import { AppComponent } from './app.component';

@NgModule({
  imports:      [
    BrowserModule,
    HttpModule,
    MaterialModule,
    ],
  declarations: [

    AppComponent

    ],
  providers: [

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
```

<p><strong>index.html</strong></p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>

    <title>Test</title>
    <meta charset="UTF-8">

  <script src="https://cdnjs.cloudflare.com/ajax/libs/typescript/2.0.3/typescript.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/2.4.1/core.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/zone.js/0.6.25/zone.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.38/system.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/hammer.js/2.0.8/hammer.min.js"></script>

  <script src="systemjs.config.js"></script>

    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>

  <link href="https://unpkg.com/@angular/material/core/theming/prebuilt/indigo-pink.css" rel="stylesheet">

</head>

  <body>
    <app>Loading...</app>
  </body>
</html>
</code>```

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

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

const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule)
    .then(success => console.log("Bootstrap success"))
    .catch( err => console.log(err));
```

<p><strong>systemjs.config.js</strong></p>

<pre class="lang-js prettyprint-override"><code>(function (global) {
  System.config({
  transpiler: 'typescript',
  typescriptOptions: {
    emitDecoratorMetadata: true
  },
    // map tells the System loader where to look for things
    map: {
      'app':'.',
    // Angular specific mappings.
    '@angular/core': 'https://unpkg.com/@angular/core/bundles/core.umd.js',
    '@angular/common': 'https://unpkg.com/@angular/common/bundles/common.umd.js',
    '@angular/compiler': 'https://unpkg.com/@angular/compiler/bundles/compiler.umd.js',
    '@angular/http': 'https://unpkg.com/@angular/http/bundles/http.umd.js',
    '@angular/forms': 'https://unpkg.com/@angular/forms/bundles/forms.umd.js',
    '@angular/router': 'https://unpkg.com/@angular/router/bundles/router.umd.js',
    '@angular/platform-browser': 'https://unpkg.com/@angular/platform-browser/bundles/platform-browser.umd.js',
    '@angular/platform-browser-dynamic': 'https://unpkg.com/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
    '@angular/material': 'https://unpkg.com/@angular/material/bundles/material.umd.js',

    // Rxjs mapping
    'rxjs': 'https://unpkg.com/rxjs',

    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.ts',
        defaultExtension: 'ts'
      },
      '.': {
        defaultExtension: 'ts'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);
</code>```

答: This problem also happens if you don't include animations module, like in this thread (just in case someone else gets here and the above solution don't fix the problem).</p>

Body:
Update: I have now made the two completely identical. My local version being served with npm run lite and the Plunker version are 100% the same and yet my local version does not get the placeholder text.

I have a large Angular2 (2.4.9) application going and I started using Google's @angular/material (2.0.0-beta.2) - specifically their mdInput.

I noticed that the placeholder text is not visible unless I add css like input::-webkit-input-placeholder{ color:black;}, but then it does not disappear when the user clicks in the field (when the animation starts that moves it to float above the input), it only disappears when the user starts typing.

I then pulled apart my very large application to get as minimal an example as possible so I could post a plunker of this.  The version running locally and the Plunker version are now 100% the same.

So why does the Plunker example work but not my local version?

Here are the ALL the differences (After updates, no differences remain between Plunker and local version.):

app.component.ts:
(moved file out of sub directory and served directly, not from build folder.  Plunker and local are now identcal)

index.html:
(Updated so these are now identical, problem remains)

systemjs.config.js:
(Updated so these are now identical.  Moved components into root directory to match Plunker.  Problem remains.)

Packages section in my file:
(Updated so they are now identical.)

Full plunker files:

app.component.html:

<md-input-container>
  <input mdInput placeholder="Favorite food">
</md-input-container>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app',
  templateUrl:'./app.component.html'
})
export class AppComponent {

}

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from '@angular/http';
import {MaterialModule } from '@angular/material';
import { AppComponent } from './app.component';

@NgModule({
  imports:      [
    BrowserModule,
    HttpModule,
    MaterialModule,
    ],
  declarations: [

    AppComponent

    ],
  providers: [

  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

index.html

<!DOCTYPE html>

    <title>Test</title>
    <meta charset="UTF-8">

  <link href="https://unpkg.com/@angular/material/core/theming/prebuilt/indigo-pink.css" rel="stylesheet">

    <app>Loading...</app>

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

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

const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule)
    .then(success => console.log("Bootstrap success"))
    .catch( err => console.log(err));

systemjs.config.js

(function (global) {
  System.config({
  transpiler: 'typescript',
  typescriptOptions: {
    emitDecoratorMetadata: true
  },
    // map tells the System loader where to look for things
    map: {
      'app':'.',
    // Angular specific mappings.
    '@angular/core': 'https://unpkg.com/@angular/core/bundles/core.umd.js',
    '@angular/common': 'https://unpkg.com/@angular/common/bundles/common.umd.js',
    '@angular/compiler': 'https://unpkg.com/@angular/compiler/bundles/compiler.umd.js',
    '@angular/http': 'https://unpkg.com/@angular/http/bundles/http.umd.js',
    '@angular/forms': 'https://unpkg.com/@angular/forms/bundles/forms.umd.js',
    '@angular/router': 'https://unpkg.com/@angular/router/bundles/router.umd.js',
    '@angular/platform-browser': 'https://unpkg.com/@angular/platform-browser/bundles/platform-browser.umd.js',
    '@angular/platform-browser-dynamic': 'https://unpkg.com/@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
    '@angular/material': 'https://unpkg.com/@angular/material/bundles/material.umd.js',

    // Rxjs mapping
    'rxjs': 'https://unpkg.com/rxjs',

    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.ts',
        defaultExtension: 'ts'
      },
      '.': {
        defaultExtension: 'ts'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);


问:
Lottery game, add css class based on numerical range
I'm making a lottery random number generator and have it working, all I want to do is change the background colour of the ball varying on what number range its called between. The second block of code is what I have come up with so far.

For example

o 1-9: White
o 10-19: Blue
o 20-29: Ping,
o 30-39: Green,
o 40-49: Yellow

```<code>    <!DOCTYPE html>
    <head>
      <!-- meta tags -->
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1">

      <title>NRONLINE - Buckinghamshire Web Design, Digital Marketing Workshops and Kofax Consultancy</title>

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <style>
 body {
    background: #444;
    font-family: sans-serif;
    font-size: 18px;
    font-weight: 100;
}

ul {
    position: absolute;
    padding: 0;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    margin: auto;
    list-style-type: none;
    width: 690px;
    height: 100px;
}

ul li {
    float: left;
    width: 100px;
    height: 100px;
    border-radius: 50px;
    margin-right: 10px;
    color: white;
    text-align: center;
    line-height: 100px;
    font-size: 36px;
}

ul li:nth-child(5n) {
    margin-right: 40px;
}

.ball-placeholder {
    background: #222222;
    background: -moz-linear-gradient(-45deg, #222222 0%, black 100%);
    background: -webkit-gradient(linear, left top, right bottom, color-stop(0%, #222222), color-stop(100%, black));
    background: -webkit-linear-gradient(-45deg, #222222 0%, black 100%);
    background: -o-linear-gradient(-45deg, #222222 0%, black 100%);
    background: -ms-linear-gradient(-45deg, #222222 0%, black 100%);
    background: linear-gradient(135deg, #222222 0%, black 100%);
    filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#222222', endColorstr='#000000',GradientType=1 );
}

.next-ball, .play-again {
    position: absolute;
    right: 0;
    left: 0;
    margin: auto;
    border: 0;
    color: white;
}

.next-ball {
    bottom: 20px;
    width: 100px;
    height: 40px;
    font-size: 16px;
    background: #7ac9ed;
}

.play-again {
    display: none;
    bottom: 20px;
    width: 200px;
    height: 80px;
    font-size: 24px;
    background: #d74d2f;
}

.white-ball {
    background: #fff;
    color:#101010;
}

.blue-ball {
    background: #99ccff;
    color:#101010;
}

.pink-ball {
    background: #ffccff;
    color:#101010;
}

.green-ball {
    background: #00cc66;
    color:#101010;
}

.yellow-ball {
    background: #fac600;
    color:#101010;
}
    </style>
    </head>
    <body role="document">

        <ul class="ball-placeholders">
          <li class="ball-placeholder"></li>
          <li class="ball-placeholder"></li>
          <li class="ball-placeholder"></li>
          <li class="ball-placeholder"></li>
          <li class="ball-placeholder"></li>
          <li class="ball-placeholder"></li>
        </ul>
        <ul class="lottery"></ul>
        <button class="next-ball">Next Ball</button>
        <button class="play-again">Play Again!</button>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

    <script>
    var arr = new Array();
    $('.next-ball').on('click', function(){
      //generate random number between 1 and 50
      var random = Math.floor(Math.random()*50 ) + 1;
      // array to store css class references
      var classList = ["white-ball", "blue-ball", "pink-ball", "green-ball", "yellow-ball"];
      console.log(random);
      //if index of random number is less than 50
      if( arr.indexOf(random) == -1){
        //generate random number
        arr.push(random);
        //add css class to lottery-ball class relevant to array value range
        $('.lottery').append('<li class="lottery-ball ' + classList[Math.floor(random/10)] + '">' + random + '</li>');
      }
      // if the number already exists ignore and generate a new number
      else {
        console.log(random);
      }
      console.log(arr);
      //if lottery number calls is greater than 5 then switch button classes and send an alert to the user
      if ( $('.lottery').children().length > 5 ) {
        $('.next-ball').hide();
        $('.play-again').show();
        alert('Did You Win?');
      }

    });
    //If once the game is finished the user chooses to play again switch button classes
    $('.play-again').on('click', function(){
      $('.lottery').children().remove();
      arr = [];
      $('.next-ball').show();
      $('.play-again').hide();
    });
    </script>
    </body>
    </html>
</code>```

答:
Your idea should work, but since the only thing that changes is the class of the li it could be more compact.  Here I've stored the class names in an array, and used the first digit of the ball number - Math.floor(random/10) to find the right element.  Also your indexOf line had a bug - a return of zero from indexOf means the element was found at the start of the array, so check for -1.

```<code>  var classList = ["white-ball", "blue-ball", "pink-ball", "green-ball", "yellow-ball"];

  if( arr.indexOf(random) == -1){
    arr.push(random);
    $('.lottery').append('<li class="lottery-ball ' + classList[Math.floor(random/10)] + '">' + random + '</li>');
  }
</code>```

Body:
I'm making a lottery random number generator and have it working, all I want to do is change the background colour of the ball varying on what number range its called between. The second block of code is what I have come up with so far.

For example

o 1-9: White
o 10-19: Blue
o 20-29: Ping,
o 30-39: Green,
o 40-49: Yellow

    <!DOCTYPE html>

      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width,initial-scale=1">

      <title>NRONLINE - Buckinghamshire Web Design, Digital Marketing Workshops and Kofax Consultancy</title>

      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <button class="next-ball">Next Ball</button>
        <button class="play-again">Play Again!</button>

Body:
Your idea should work, but since the only thing that changes is the class of the li it could be more compact.  Here I've stored the class names in an array, and used the first digit of the ball number - Math.floor(random/10) to find the right element.  Also your indexOf line had a bug - a return of zero from indexOf means the element was found at the start of the array, so check for -1.

  var classList = ["white-ball", "blue-ball", "pink-ball", "green-ball", "yellow-ball"];

  if( arr.indexOf(random) == -1){
    arr.push(random);
    $('.lottery').append('<li class="lottery-ball ' + classList[Math.floor(random/10)] + '">' + random + '</li>');
  }


问:
Running Gradle plugin directly from command line
In Maven, if I wanted to analyze my project with sonar, I could do:

```<code>mvn sonar:sonar
</code>```

using the 'short' plugin name and goal.

In Gradle, is there a similar way to run plugins, without declaring them in the build.gradle script?

答:
This code works fine:

```<code>allprojects {
    buildscript {
        repositories {
            mavenCentral()
            maven {
                url "https://plugins.gradle.org/m2/"
            }
        }
        dependencies {
            classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.5"
        }
    }

    apply plugin: 'java'
    apply plugin: 'jacoco'

    afterEvaluate { project ->
        project.apply plugin: 'org.sonarqube'
    }
}
</code>```

gradle --init-script etc/quality.gradle sonarqube

Body:
In Maven, if I wanted to analyze my project with sonar, I could do:

mvn sonar:sonar

using the 'short' plugin name and goal.

In Gradle, is there a similar way to run plugins, without declaring them in the build.gradle script?

Body:
This code works fine:

allprojects {
    buildscript {
        repositories {
            mavenCentral()
            maven {
                url "https://plugins.gradle.org/m2/"
            }
        }
        dependencies {
            classpath "org.sonarsource.scanner.gradle:sonarqube-gradle-plugin:2.5"
        }
    }

    apply plugin: 'java'
    apply plugin: 'jacoco'

    afterEvaluate { project ->
        project.apply plugin: 'org.sonarqube'
    }
}

gradle --init-script etc/quality.gradle sonarqube


问:
How to get an HTML file using Python?
I am not very familiar with Python. I am trying to extract the artist names (for a start :)) from the following page: http://www.infolanka.com/miyuru_gee/art/art.html.

How do I retrieve the page? My two main concerns are; what functions to use and how to filter out useless links from the page?

答:
I think "eyquem" way would be my choice too, but I like to use httplib2 instead of urllib. urllib2 is too low level lib for this work.
```
import httplib2, re<br/>
pat = re.compile('<DT><a href="[^"]+">(.+?)</a>')
http = httplib2.Http()
headers, body = http.request("http://www.infolanka.com/miyuru_gee/art/art.html")<br/>
li = pat.findall(body)
print li
```

Title: How to get an HTML file using Python?

Body:
I think "eyquem" way would be my choice too, but I like to use httplib2 instead of urllib. urllib2 is too low level lib for this work.

import httplib2, re

pat = re.compile('<DT><a href="[^"]+">(.+?)</a>')
http = httplib2.Http()
headers, body = http.request("http://www.infolanka.com/miyuru_gee/art/art.html")

li = pat.findall(body)
print li


问:
Using LINQ Where result in foreach: hidden if statement, double foreach?
```<code>foreach (Person criminal in people.Where(person => person.isCriminal)
{
    // do something
}
</code>```

I have this piece of code and want to know how does it actually work. Is it equivalent to an if statement nested inside the foreach iteration or does it first loop through the list of people and repeats the loop with selected values? I care to know more about this from the perspective of efficiency.

```<code>foreach (Person criminal in people)
{
    if (criminal.isCriminal)
    {
        // do something
    }
}
</code>```

答:
Where uses deferred execution.

This means that the filtering does not occur immediately when you call Where. Instead, each time you call GetEnumerator().MoveNext() on the return value of Where, it checks if the next element in the sequence satisfies the condition. If it does not, it skips over this element and checks the next one. When there is an element that satisfies the condition, it stops advancing and you can get the value using Current.

Basically, it is like having an if statement inside a foreach loop.

Body:
foreach (Person criminal in people.Where(person => person.isCriminal)
{
    // do something
}

I have this piece of code and want to know how does it actually work. Is it equivalent to an if statement nested inside the foreach iteration or does it first loop through the list of people and repeats the loop with selected values? I care to know more about this from the perspective of efficiency.

foreach (Person criminal in people)
{
    if (criminal.isCriminal)
    {
        // do something
    }
}


问:
Assertion error while running test with LatchCountDownAndCallRealMethodAnswer from RabbitMQ
I have a listener test, where i post a message in a parallel thread and check with LatchCountDownAndCallRealMethodAnswer if the all were processed successfully. Running the test alone, it works perfectly, however if you run all other tests together, it fails because it failed to leave the counter at zero, but the listener received and processed the message normally. Does anyone have any ideas?

My Test Class

```<code>@RunWith(SpringRunner.class)
@SpringBootTest
@RabbitListenerTest
@ActiveProfiles("test")
public class EventListenerTest {

    EventListener eventListener;

    @Autowired
    protected RabbitListenerTestHarness harness;

    @Autowired
    private EventStoreRepository repository;

    @SpyBean
    private DomainEventPublisher publisher;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        DomainRegister.setDomainEventPublisher(publisher);
        eventListener = this.harness.getSpy("eventListenerId");
    }

    @Test
    public void storeEventsListenerTest() throws Exception {

        LatchCountDownAndCallRealMethodAnswer answer = new LatchCountDownAndCallRealMethodAnswer(1);
        doAnswer(answer).when(eventListener).storeEvents(any(BalanceReserved.class));

        publisher.publish(new BalanceReserved("12233", 150.0, BigDecimal.ZERO), "");

        assertTrue(answer.getLatch().await(10, TimeUnit.SECONDS));

        verify(eventListener, times(1)).storeEvents(any(BalanceReserved.class));
    }

    @After
    public void tearDown() {
        DomainRegister.setDomainEventPublisher(null);
        reset(eventListener);
        repository.deleteAll();
    }

}
</code>```

Error

```<code>java.lang.AssertionError
</code>```

答:
If you have other tests using the same queue, you need to shut down the application context for each test so the test's listeners are stopped. By default, the Spring Test framework caches the application context for reuse. This will cause other tests to "steal" messages.

Add @DirtiesContext to each test class that uses @RabbitListeners, to tell the test framework to shutdown the context.

Body:
I have a listener test, where i post a message in a parallel thread and check with LatchCountDownAndCallRealMethodAnswer if the all were processed successfully. Running the test alone, it works perfectly, however if you run all other tests together, it fails because it failed to leave the counter at zero, but the listener received and processed the message normally. Does anyone have any ideas?

My Test Class

@RunWith(SpringRunner.class)
@SpringBootTest
@RabbitListenerTest
@ActiveProfiles("test")
public class EventListenerTest {

    EventListener eventListener;

    @Autowired
    protected RabbitListenerTestHarness harness;

    @Autowired
    private EventStoreRepository repository;

    @SpyBean
    private DomainEventPublisher publisher;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        DomainRegister.setDomainEventPublisher(publisher);
        eventListener = this.harness.getSpy("eventListenerId");
    }

    @Test
    public void storeEventsListenerTest() throws Exception {

        LatchCountDownAndCallRealMethodAnswer answer = new LatchCountDownAndCallRealMethodAnswer(1);
        doAnswer(answer).when(eventListener).storeEvents(any(BalanceReserved.class));

        publisher.publish(new BalanceReserved("12233", 150.0, BigDecimal.ZERO), "");

        assertTrue(answer.getLatch().await(10, TimeUnit.SECONDS));

        verify(eventListener, times(1)).storeEvents(any(BalanceReserved.class));
    }

    @After
    public void tearDown() {
        DomainRegister.setDomainEventPublisher(null);
        reset(eventListener);
        repository.deleteAll();
    }

}

Error

java.lang.AssertionError


问:
clear input textbox value on load
I have the following form which is getting pre populated with values on load. I want to have empty input boxes on load using Javascript. However I do not have access to the  tag so <body onload="" will not work here. Is there any other way to clear the form fields on load?

```<code><form method="POST" action="">
  <input name="username" id="user" value="" /><br />
  <input name="pwd" id="pass" value="" />
  <input type="submit" value="Go" />
</form>
</code>```

答:
```<code>onload=()=>{
    document.getElementById('user').value='';
}
</code>```

or

```<code>onload=()=>{
    document.getElementById('user').setAttribute('value','');
}
</code>```

Title: clear input textbox value on load

Body:
I have the following form which is getting pre populated with values on load. I want to have empty input boxes on load using Javascript. However I do not have access to the  tag so <body onload="" will not work here. Is there any other way to clear the form fields on load?

<form method="POST" action="">
  <input name="username" id="user" value="" />

  <input name="pwd" id="pass" value="" />
  <input type="submit" value="Go" />
</form>

Body:
onload=()=>{
    document.getElementById('user').value='';
}

or

onload=()=>{
    document.getElementById('user').setAttribute('value','');
}


问:
How to "redefine" one char * to another char *?
Something like that: (it is task, how to do this, and not to change body of main function)

I thought that it is too simple... but... I don't know how to do it...

```<code>#include <iostream>

#define "a" "b"

int main( int argc,char ** argv) {
   std::cout << "a";
   return 0;
}
</code>```

// output: b

How to do it?

答:
Probably you want to do this:

```<code>#include <iostream>

#define a "b"

int main( int argc,char ** argv) {
   std::cout << a;
   return 0;
}
</code>```

Output :  b

Body:
Something like that: (it is task, how to do this, and not to change body of main function)

I thought that it is too simple... but... I don't know how to do it...

#include <iostream>

#define "a" "b"

int main( int argc,char ** argv) {
   std::cout << "a";
   return 0;
}

// output: b

How to do it?

Body:
Probably you want to do this:

#include <iostream>

#define a "b"

int main( int argc,char ** argv) {
   std::cout << a;
   return 0;
}

Output :  b


问:
HEROKU LOGIN ON UBUNTU 17.04
Trying to execute heroku login:</p>

```<code>heroku login
WARNING
WARNING Node version must be >=7.10.0 to use the Heroku CLI
WARNING
/opt/npm-global/lib/node_modules/heroku-cli/node_modules/cli-engine/lib/cli.js:73
  async run() {
        ^^^
SyntaxError: Unexpected identifier
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/opt/npm-global/lib/node_modules/heroku-cli/bin/run.js:10:34)
    at Module._compile (module.js:570:32)
</code>```

答:
Looks like your version of Node is out of date. I was having the same problem while trying to add heroku as a place I could push code to while in Cloud9. The commands below will help if you're using nvm.

```<code>$ node --version
v4.7.3
$ nvm install 8.1.3
Downloading https://nodejs.org/dist/v8.1.3/node-v8.1.3-linux-x64.tar.xz...
######################################################################## 100.0%
Now using node v8.1.3 (npm v5.0.3)
$ node --version
v8.1.3
</code>```

After this, I didn't get that error. If this doesn't help then you may want to google around for how to update Node. This may be worth a shot: https://stackoverflow.com/a/41196107. Good luck!

Title: HEROKU LOGIN ON UBUNTU 17.04

Body:
Trying to execute heroku login:

heroku login
WARNING
WARNING Node version must be >=7.10.0 to use the Heroku CLI
WARNING
/opt/npm-global/lib/node_modules/heroku-cli/node_modules/cli-engine/lib/cli.js:73
  async run() {
        ^^^
SyntaxError: Unexpected identifier
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:542:28)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (/opt/npm-global/lib/node_modules/heroku-cli/bin/run.js:10:34)
    at Module._compile (module.js:570:32)

Body:
Looks like your version of Node is out of date. I was having the same problem while trying to add heroku as a place I could push code to while in Cloud9. The commands below will help if you're using nvm.

$ node --version
v4.7.3
$ nvm install 8.1.3
Downloading https://nodejs.org/dist/v8.1.3/node-v8.1.3-linux-x64.tar.xz...
######################################################################## 100.0%
Now using node v8.1.3 (npm v5.0.3)
$ node --version
v8.1.3

After this, I didn't get that error. If this doesn't help then you may want to google around for how to update Node. This may be worth a shot: https://stackoverflow.com/a/41196107. Good luck!


问:
Hive Partitions - How to delete null or hive_default_partition
I am facing a problem with hive default partition (null partition) in hive.
I will explain the situation briefly here.. I have a hive main table and data ingestion is happening to that table everyday. but somehow when data is ingested into the hive table something went wrong and partition is showing _hive_default_partition_ or in my understanding it is null partition.

i need to delete the partition from hive tables. (it is external table)...

I am using hive version 1.1 and CDH version 5.4.8 ..

I tried the below syntax and its not working for me..

```<code>alter table "tablename" drop partition(partn='_hive_default_partition_);

alter table "tablename" drop partition(partn<'1');

alter table "tablename" drop partition(partn = 1);

alter table "tablename" drop partition(partn='0');
</code>```

i tried all the above steps and nothing worked..

Hope someone can help me with this.

Thanks in advance ,

答:
The way that worked for me was altering the datatype of the partition column, deleting the partition and changing it back.

Considering that you are comparing the partition to an int in the question, I assume that is the column datatype to start with, however this should work regardless of the datatype you start with.

-- Change the column type to string
ALTER TABLE tablename PARTITION COLUMN (partn STRING);

-- Drop the offending partitions
ALTER TABLE tablename DROP PARTITION (partn='__HIVE_DEFAULT_PARTITION__');

-- Change the column type back to int
ALTER TABLE tablename PARTITION COLUMN (partn INT);

Body:
I am facing a problem with hive default partition (null partition) in hive.
I will explain the situation briefly here.. I have a hive main table and data ingestion is happening to that table everyday. but somehow when data is ingested into the hive table something went wrong and partition is showing _hive_default_partition_ or in my understanding it is null partition.

i need to delete the partition from hive tables. (it is external table)...

I am using hive version 1.1 and CDH version 5.4.8 ..

I tried the below syntax and its not working for me..

alter table "tablename" drop partition(partn='_hive_default_partition_);

alter table "tablename" drop partition(partn<'1');

alter table "tablename" drop partition(partn = 1);

alter table "tablename" drop partition(partn='0');

i tried all the above steps and nothing worked..

Hope someone can help me with this.

Thanks in advance ,


问:
Life of distributed cache in Hadoop
When files are transferred to nodes using the distributed cache mechanism in a Hadoop streaming job, does the system delete these files after a job is completed? If they are deleted, which i presume they are, is there a way to make the cache remain for multiple jobs? Does this work the same way on Amazon's Elastic Mapreduce?</p>

答: I was digging around in the source code, and it looks like files are deleted by TrackerDistributedCacheManager about once a minute when their reference count drops to zero.  The TaskRunner explicitly releases all its files at the end of a task.  Maybe you should edit TaskRunner to not do this, and control the cache through more explicit means yourself?

Title: Life of distributed cache in Hadoop


问:
Triple nested model not building correctly
I have an Organisme that has many Servicepoints and each Servicepoint has many Addresses. The Servicepoint is set to accepts_nested_attributes_for :addresses so that I can create a service point and at the same time create an Address with it.

My problem is that that, I can't figure out how to create the address that will be linked to the Servicepoint and that Servicepoint be linked to the Organisme. I am creating the Servicepoint inside the show view of an Organisme.

View:

```<code><%= form_for([@organisme, @organisme.servicepoints.build]) do |f| %>
  <p>
    <%= f.label :nom %><br>
    <%= f.text_field :nom %>
  </p>
  <p>
    <%= f.label :fax %><br>
    <%= f.text_field :fax %>
  </p>
  <p>
    <%= f.label :courriel %><br>
    <%= f.email_field :courriel %>
  </p>
  <p>
    <%= f.label :telephone %><br>
    <%= f.text_field :telephone %>
  </p>
  <%= f.fields_for :addresses do |address_attributes| %>
    <p>
      <%= address_attributes.label :no_civique %><br>
      <%= address_attributes.text_field :no_civique %><br>

      <%= address_attributes.label :rue %><br>
      <%= address_attributes.text_field :rue %><br>

      <%= address_attributes.label :ville %><br>
      <%= address_attributes.text_field :ville %><br>

      <%= address_attributes.label :province %><br>
      <%= address_attributes.text_field :province %><br>

      <%= address_attributes.label :etat %><br>
      <%= address_attributes.text_field :etat %><br>

      <%= address_attributes.label :code_postal %><br>
      <%= address_attributes.text_field :code_postal %><br>
    </p>
<% end %>
  <p>
    <%= f.submit :Ajouter, class: 'btn btn-info' %>
  </p>
<% end %>
</code>```

Controller:

organisme/show

```<code>def show
 @organisme = Organisme.find(params[:id])
end
</code>```

servicepoint/create

```<code>def create

  @organisme = Organisme.find(params[:organisme_id])

  @servicepoint = @organisme.servicepoints.create(servicepoint_params)

  redirect_to organisme_path(@organisme)

end

private
  def servicepoint_params
    params.require(:servicepoint).permit(:nom, :fax, :courriel, :telephone, addresses_attributes: [:id, :no_civique, :rue, :ville, :province, :etat, :code_postal])
end
</code>```

Routes:

```<code>resources :organismes do
  member { patch :activate }
  member { patch :deactivate }
  resources :addresses
  resources :servicepoints do
    resources :addresses
  end
end
</code>```

My problem right now is that the Address input information isn't even showing. I tried having a @servicepoint variable and then creating everything with that but the problem with that was that I could not link it to the Organisme.

If you need any more information I'll be happy to add anything.

Models:

```<code>class Organisme < ApplicationRecord
   has_many :addresses
   accepts_nested_attributes_for :addresses
   has_many :servicepoints
end

class Servicepoint < ApplicationRecord
   has_many :addresses
   accepts_nested_attributes_for :addresses
   belongs_to :organisme
end

class Address < ApplicationRecord
  belongs_to :organismereferent, optional: true
  belongs_to :organisme, optional: true
  belongs_to :servicepoint, optional: true
end
</code>```

答:
I would build everything in the controller action:</p>

```<code><%= form_for([@organisme, @servicepoint]) do |f| %>
...

def show
  @organisme = Organisme.find(params[:organisme_id])
  @servicepoint = @organisme.servicepoints.build
  @servicepoint.addressess.build
end
</code>```

Body:
I have an Organisme that has many Servicepoints and each Servicepoint has many Addresses. The Servicepoint is set to accepts_nested_attributes_for :addresses so that I can create a service point and at the same time create an Address with it.

My problem is that that, I can't figure out how to create the address that will be linked to the Servicepoint and that Servicepoint be linked to the Organisme. I am creating the Servicepoint inside the show view of an Organisme.

View:

<%= form_for([@organisme, @organisme.servicepoints.build]) do |f| %>

    <%= f.label :nom %>

    <%= f.text_field :nom %>

    <%= f.label :fax %>

    <%= f.text_field :fax %>

    <%= f.label :courriel %>

    <%= f.email_field :courriel %>

    <%= f.label :telephone %>

    <%= f.text_field :telephone %>

  <%= f.fields_for :addresses do |address_attributes| %>

      <%= address_attributes.label :no_civique %>

      <%= address_attributes.text_field :no_civique %>

      <%= address_attributes.label :rue %>

      <%= address_attributes.text_field :rue %>

      <%= address_attributes.label :ville %>

      <%= address_attributes.text_field :ville %>

      <%= address_attributes.label :province %>

      <%= address_attributes.text_field :province %>

      <%= address_attributes.label :etat %>

      <%= address_attributes.text_field :etat %>

      <%= address_attributes.label :code_postal %>

      <%= address_attributes.text_field :code_postal %>

<% end %>

    <%= f.submit :Ajouter, class: 'btn btn-info' %>

<% end %>

Controller:

organisme/show

def show
 @organisme = Organisme.find(params[:id])
end

servicepoint/create

def create

  @organisme = Organisme.find(params[:organisme_id])

  @servicepoint = @organisme.servicepoints.create(servicepoint_params)

  redirect_to organisme_path(@organisme)

end

private
  def servicepoint_params
    params.require(:servicepoint).permit(:nom, :fax, :courriel, :telephone, addresses_attributes: [:id, :no_civique, :rue, :ville, :province, :etat, :code_postal])
end

Routes:

resources :organismes do
  member { patch :activate }
  member { patch :deactivate }
  resources :addresses
  resources :servicepoints do
    resources :addresses
  end
end

My problem right now is that the Address input information isn't even showing. I tried having a @servicepoint variable and then creating everything with that but the problem with that was that I could not link it to the Organisme.

If you need any more information I'll be happy to add anything.

Models:

class Organisme < ApplicationRecord
   has_many :addresses
   accepts_nested_attributes_for :addresses
   has_many :servicepoints
end

class Servicepoint < ApplicationRecord
   has_many :addresses
   accepts_nested_attributes_for :addresses
   belongs_to :organisme
end

class Address < ApplicationRecord
  belongs_to :organismereferent, optional: true
  belongs_to :organisme, optional: true
  belongs_to :servicepoint, optional: true
end

Body:
I would build everything in the controller action:

<%= form_for([@organisme, @servicepoint]) do |f| %>
...

def show
  @organisme = Organisme.find(params[:organisme_id])
  @servicepoint = @organisme.servicepoints.build
  @servicepoint.addressess.build
end


问:
Error while authorization to HealthKit - Code=100 "Rolling back the health database is unsupported."
Here is my code:

```<code>    var shareTypes = Set<HKSampleType>()
    shareTypes.insert(HKSampleType.categoryType(forIdentifier: .mindfulSession)!)

    var readTypes = Set<HKObjectType>()
    readTypes.insert(HKObjectType.categoryType(forIdentifier: .mindfulSession)!)

    healthStore.requestAuthorization(toShare: shareTypes, read: readTypes) { (success, error) -> Void in
        if success {
            print("success")
        } else {
            print("failure")
        }

        if let error = error { print(error) }
    }
</code>```

Here I get error:
Error Domain=com.apple.healthkit Code=100 "Rolling back the health database is unsupported."

Cant find any information about this error, can anybody help?

I use Xcode 8.3.3 Swift 3

答: This indicates that you had a newer version of iOS installed on this device previously and then you rolled back to an older version. In general, rolling back is not supported accross iOS (although some parts of the system can handle it better than others). You should always erase a device before installing an older OS on it.</p>

Body:
Here is my code:

    var shareTypes = Set<HKSampleType>()
    shareTypes.insert(HKSampleType.categoryType(forIdentifier: .mindfulSession)!)

    var readTypes = Set<HKObjectType>()
    readTypes.insert(HKObjectType.categoryType(forIdentifier: .mindfulSession)!)

    healthStore.requestAuthorization(toShare: shareTypes, read: readTypes) { (success, error) -> Void in
        if success {
            print("success")
        } else {
            print("failure")
        }

        if let error = error { print(error) }
    }

Here I get error:
Error Domain=com.apple.healthkit Code=100 "Rolling back the health database is unsupported."

Cant find any information about this error, can anybody help?

I use Xcode 8.3.3 Swift 3