问:
How to switch Ansible playbook to another host when calling second playbook
I have two playbooks - my first playbook iterates on the list of ESXi servers getting list of all VMs, and then passes that list to the second playbook, that should iterates on the IPs of the VMs. Instead it is still trying to execute on the last ESXi server. I have to switch host to that VM IP that I'm currently passing to the second playbook. Don't know how to switch... Anybody?

First playbook:

```<code>- name: get VM list from ESXi
  hosts: all

  tasks:
  - name: get facts
    vmware_vm_facts:
      hostname: "{{ inventory_hostname }}"
      username: "{{ ansible_ssh_user }}"
      password: "{{ ansible_ssh_pass }}"
    delegate_to: localhost
    register: esx_facts

  - name: Debugging data
    debug:
      msg: "IP of {{ item.key }} is {{ item.value.ip_address }} and is {{ item.value.power_state }}"
    with_dict: "{{ esx_facts.virtual_machines }}"

  - name: Passing data to include file
    include: includeFile.yml ip_address="{{ item.value.ip_address }}"
    with_dict: "{{ esx_facts.virtual_machines }}"
</code>```

My second playbook:

```<code>- name: <<Check the IP received
  debug:
    msg: "Received IP: {{ ip_address }}"

- name: <<Get custom facts
  vmware_vm_facts:
    hostname: "{{ ip_address }}"
    username: root
    password: passw
    validate_certs: False
  delegate_to: localhost
  register: custom_facts
</code>```

I do receive the correct VM's ip_address but vmware_vm_facts is still trying to run on the ESXi server instead...

答:
If you can't afford to setup dynamic inventory for VMs, your playbook should have two plays: one for collecting VMs' IPs and another for tasks on that VMs, like this (pseudocode):

```<code>---
- hosts: hypervisors
  gather_facts: no
  connection: local
  tasks:
    - vmware_vm_facts:
        ... params_here ...
      register: vmfacts
    - add_host:
        name: "{{ item.key }}"
        ansible_host: "{{ item.value.ip_address }}"
        group: myvms
      with_dict: "{{ vmfacts.virtual_machines }}"

- hosts: myvms
  tasks:
    - apt:
        name: "*"
        state: latest
</code>```

Within the first play we collect facts from each hypervisor and populate myvms group of inmemory inventory. Within second play we run apt module for every host in myvms group.

Body:
I have two playbooks - my first playbook iterates on the list of ESXi servers getting list of all VMs, and then passes that list to the second playbook, that should iterates on the IPs of the VMs. Instead it is still trying to execute on the last ESXi server. I have to switch host to that VM IP that I'm currently passing to the second playbook. Don't know how to switch... Anybody?

First playbook:

- name: get VM list from ESXi
  hosts: all

  tasks:
  - name: get facts
    vmware_vm_facts:
      hostname: "{{ inventory_hostname }}"
      username: "{{ ansible_ssh_user }}"
      password: "{{ ansible_ssh_pass }}"
    delegate_to: localhost
    register: esx_facts

  - name: Debugging data
    debug:
      msg: "IP of {{ item.key }} is {{ item.value.ip_address }} and is {{ item.value.power_state }}"
    with_dict: "{{ esx_facts.virtual_machines }}"

  - name: Passing data to include file
    include: includeFile.yml ip_address="{{ item.value.ip_address }}"
    with_dict: "{{ esx_facts.virtual_machines }}"

My second playbook:

- name: <<Check the IP received
  debug:
    msg: "Received IP: {{ ip_address }}"

- name: <<Get custom facts
  vmware_vm_facts:
    hostname: "{{ ip_address }}"
    username: root
    password: passw
    validate_certs: False
  delegate_to: localhost
  register: custom_facts

I do receive the correct VM's ip_address but vmware_vm_facts is still trying to run on the ESXi server instead...

Body:
If you can't afford to setup dynamic inventory for VMs, your playbook should have two plays: one for collecting VMs' IPs and another for tasks on that VMs, like this (pseudocode):

---
- hosts: hypervisors
  gather_facts: no
  connection: local
  tasks:
    - vmware_vm_facts:
        ... params_here ...
      register: vmfacts
    - add_host:
        name: "{{ item.key }}"
        ansible_host: "{{ item.value.ip_address }}"
        group: myvms
      with_dict: "{{ vmfacts.virtual_machines }}"

- hosts: myvms
  tasks:
    - apt:
        name: "*"
        state: latest

Within the first play we collect facts from each hypervisor and populate myvms group of inmemory inventory. Within second play we run apt module for every host in myvms group.


来源: stackexchange

问:
How can HTML <select/> prevent click through parent's div
I'm creating shopping cart page that there's a div have a click listener for redirecting to the product page, but you also can select qty on the div. How can I prevent the redirection when selecting from <select/>

I've tried event.stopPropagation() / e.preventDefault() on select but not working

Here's the sample code.

https://jsfiddle.net/hk7861es/2/

答:
Change keypress to click and keydown to change.

$('#box').click(function() {
  $('#text').append('You clicked');
})

$("#select").click(function (event) {
console.log('1111',event)
       //$(this).val(valueToKeep);
         event.stopPropagation();
  event.preventDefault();
  event.stopPropagation();
});
$("#select").change(function (event) {
console.log('222',event)
  event.stopPropagation();
  event.preventDefault();
  event.stopPropagation();
  valueToKeep = $(this).val();

});  ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#box {
  height: 200px;
  width: 400px;
  background-color: lightgrey;
  display: flex;
  align-items: center;
  justify-content: center;
}</code>```

  Volvo: 200hp ; $3000

  QTY:
  <select id="select">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
  </select>

```

ContentLicense: CC BY-SA 3.0

Body:
Change keypress to click and keydown to change.

$('#box').click(function() {
  $('#text').append('You clicked');
})

$("#select").click(function (event) {
console.log('1111',event)
       //$(this).val(valueToKeep);
         event.stopPropagation();
  event.preventDefault();
  event.stopPropagation();
});
$("#select").change(function (event) {
console.log('222',event)
  event.stopPropagation();
  event.preventDefault();
  event.stopPropagation();
  valueToKeep = $(this).val();

});

#box {
  height: 200px;
  width: 400px;
  background-color: lightgrey;
  display: flex;
  align-items: center;
  justify-content: center;
}

<div id="box">
  Volvo: 200hp ; $3000

  QTY:
  <select id="select">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
  </select>

</div>
<p id="text"></p>


问:
Many-to-many mapping with extra columns in join table
Here is the domain that I wish to have:

```<code>public class Person
{
    public int Id { get; set; }
    public IList<AcquiredCertificate> AcquiredCertificates { get; set; }
}

public class AcquiredCertificate
{
    public Person Acquirer { get; set; }
    public Certificate Certificate { get; set; }
    public DateTime DateAcquired;
}

public class Certificate
{
    public int Id { get; set; }
}
</code>```

And this is the schema that I have:

```<code>CREATE TABLE People (
    PersonId INT PRIMARY KEY
);

CREATE TABLE Certificates (
    CertificateId INT PRIMARY KEY
);

CREATE TABLE CertificatesAcquiredByPeople (
    PersonId INT,
    CertificatedId INT,
    DateAcquired DATETIME
);
</code>```

It's a contrived schema and domain but it's pretty much the same as something that I am working with. I currently have it working by writing a 3rd domain entity to represent the CertificatesAcquiredByPeople table but that really seems strange to me.

How would I map this using NHibernate? I believe the component tag in the hbm file should do what I want, but I can't quite figure it out.

Is my domain out of whack because I have a DateAcquired property on my Certificate class? The date really is only a concern of a Person that has a certificate.

[Edit]

I've altered the domain model now to reflect that a new entity is needed. Now for the mapping do I need 3 (for each entity) mappings or can I do it with 2 (for Person and Certificate)?

答:
By design, NHibernate only supports the implicit many-to-many mapping if there is absolutely NOTHING other than the pair of FKs represented in the intermediate (middle) table that holds the many-to-many relationship.

Some time ago, Billy McCafferty blogged about this exact 'issue' (not really an issue since its BY DESIGN)...

http://devlicio.us/blogs/billy_mccafferty/archive/2008/07/11/when-to-use-many-to-one-s-vs-many-to-many-with-nhibernate.aspx

OwnerDisplayName: Scott Muc

ContentLicense: CC BY-SA 2.5

Body:
Here is the domain that I wish to have:

public class Person
{
    public int Id { get; set; }
    public IList<AcquiredCertificate> AcquiredCertificates { get; set; }
}

public class AcquiredCertificate
{
    public Person Acquirer { get; set; }
    public Certificate Certificate { get; set; }
    public DateTime DateAcquired;
}

public class Certificate
{
    public int Id { get; set; }
}

And this is the schema that I have:

CREATE TABLE People (
    PersonId INT PRIMARY KEY
);

CREATE TABLE Certificates (
    CertificateId INT PRIMARY KEY
);

CREATE TABLE CertificatesAcquiredByPeople (
    PersonId INT,
    CertificatedId INT,
    DateAcquired DATETIME
);

It's a contrived schema and domain but it's pretty much the same as something that I am working with. I currently have it working by writing a 3rd domain entity to represent the CertificatesAcquiredByPeople table but that really seems strange to me.

How would I map this using NHibernate? I believe the component tag in the hbm file should do what I want, but I can't quite figure it out.

Is my domain out of whack because I have a DateAcquired property on my Certificate class? The date really is only a concern of a Person that has a certificate.

[Edit]

I've altered the domain model now to reflect that a new entity is needed. Now for the mapping do I need 3 (for each entity) mappings or can I do it with 2 (for Person and Certificate)?

LastEditorDisplayName: Scott Muc

OwnerDisplayName: sbohlen


问:
Meta Query Posts by Sub Field Value ACF
I am attempting to query posts by those with sub field values of 'audi'. I have looked and looked but cannot find an answer. The $args I have are below, and posts exist in the database which match 'audi' as the value for sub field 'model' of repeater 'cars'.

```<code>$args = array(
    'post_type' => 'manufacturers',
    'meta_query' => array(
       array(
        'key' => 'cars_%_model',
        'value' => 'audi',
        'compare' => 'LIKE'
       )
    )
);
$query = new WP_Query($args);
</code>```

Any hints as to where this code falls down would be really appreciated.

答:
I spent a few hours on this and have a solution for you:

First thing you need to do is setup a filter which replaces '=' comparisons with 'LIKE' comparisons (include this above your previous code):

```<code>function my_posts_where( $where ) {
     $where = str_replace("meta_key = 'cars_", "meta_key LIKE 'cars_", $where);
     // note if using wordpress < v4.8.3 add a % to the meta key like this: meta_key = 'cars_%",...
     return $where;
}

add_filter('posts_where', 'my_posts_where');
</code>```

Now all you need to do is update your meta_query comparison to '=':

```<code>$args = array(
    'post_type' => 'manufacturers',
    'meta_query' => array(
       array(
        'key' => 'cars_%_model',
        'value' => 'audi',
        'compare' => '='
       )
    )
);
$query = new WP_Query($args);
</code>```

This is included in the ACF documentation however the documentation does not mention the updates following Wordpress 4.8.3 which is mentioned here.

Title: Meta Query Posts by Sub Field Value ACF

Body:
I am attempting to query posts by those with sub field values of 'audi'. I have looked and looked but cannot find an answer. The $args I have are below, and posts exist in the database which match 'audi' as the value for sub field 'model' of repeater 'cars'.

$args = array(
    'post_type' => 'manufacturers',
    'meta_query' => array(
       array(
        'key' => 'cars_%_model',
        'value' => 'audi',
        'compare' => 'LIKE'
       )
    )
);
$query = new WP_Query($args);

Any hints as to where this code falls down would be really appreciated.

Body:
I spent a few hours on this and have a solution for you:

First thing you need to do is setup a filter which replaces '=' comparisons with 'LIKE' comparisons (include this above your previous code):

function my_posts_where( $where ) {
     $where = str_replace("meta_key = 'cars_", "meta_key LIKE 'cars_", $where);
     // note if using wordpress < v4.8.3 add a % to the meta key like this: meta_key = 'cars_%",...
     return $where;
}

add_filter('posts_where', 'my_posts_where');

Now all you need to do is update your meta_query comparison to '=':

$args = array(
    'post_type' => 'manufacturers',
    'meta_query' => array(
       array(
        'key' => 'cars_%_model',
        'value' => 'audi',
        'compare' => '='
       )
    )
);
$query = new WP_Query($args);

This is included in the ACF documentation however the documentation does not mention the updates following Wordpress 4.8.3 which is mentioned here.


问:
Fetch in ReactJS with Basic Auth return 401 (Unauthorized). Preflight request doesn't pass access control check
I'm new at ReactJS but I'm trying to learn by myself now. I'm facing a problem when I try to add data do may Database, in my RestAPI with MongoDB, using fetch function on my web Application. When I click my button, it runs the following code:

```<code>SubmitClick(){
    //console.log('load Get User page'); //debug only

    fetch('http://localhost:4000/users/', {
      method: 'POST',
      headers: {
        'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: 'deadpool@gmail.com',
        first_name: 'Wade',
        last_name: 'Wilson',
        personal_phone: '(11) 91111-2222',
        password: 'wolv3Rine'
      })
    })

    //this.props.history.push('/get'); //change page layout and URL
}
</code>```

and I get the following message on my browser:

OPTIONS http://localhost:4000/users/ 401 (Unauthorized)

Failed to load http://localhost:4000/users/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Uncaught (in promise) TypeError: Failed to fetch

My RestAPI have Basic Auth, but i don't know what i'm supposed to insert in headers to have access. I got this 'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=', from Postman, when I configured the Authorization tab, and it was automatically added to the headers.

I'm using Google Chrome as my default browser.

My backend code is the following:

```<code>const express =     require('express');
const bodyParser =  require('body-parser');
const mongoose =    require('mongoose');
var basicAuth =     require('express-basic-auth')

const app = express();

mongoose.connect('mongodb://localhost/usersregs', { useMongoClient: true });
mongoose.Promise = global.Promise;

app.use(basicAuth({
    users: {
        'admin': 'supersecret',
        'adam': 'password1234',
        'eve': 'asdfghjkl'
    }
}))

app.use(bodyParser.json());

app.use(function(err, req, res, next){
    console.log(err);
    //res.status(450).send({err: err.message})
});

app.use(require('./routes/api'));

app.listen(4000, function(){
    console.log('Now listening for request at port 4000');
});
</code>```

答:
You're trying to access port 4000 (your API, or backend) from port 3000 (Your client). This violates the Same-origin policy, even though you're clearly running both the client and the API from the same machine.

To get around this the easiest way is to just fire up your client from the same port as your API (port 4000) this should allow your host to see that you're trying to access resources from the same domain/port which won't force a preflight request.

If that's not possible you'll have to configure CORS for your API, and this question doesn't give any details about the backend so I can't instruct you on how to do that at the moment.

And of course this approach obviously won't work if you're running two separate servers in production, but that's probably outside of the scope of this question.

Body:
I'm new at ReactJS but I'm trying to learn by myself now. I'm facing a problem when I try to add data do may Database, in my RestAPI with MongoDB, using fetch function on my web Application. When I click my button, it runs the following code:

SubmitClick(){
    //console.log('load Get User page'); //debug only

    fetch('http://localhost:4000/users/', {
      method: 'POST',
      headers: {
        'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        email: 'deadpool@gmail.com',
        first_name: 'Wade',
        last_name: 'Wilson',
        personal_phone: '(11) 91111-2222',
        password: 'wolv3Rine'
      })
    })

    //this.props.history.push('/get'); //change page layout and URL
}

and I get the following message on my browser:

OPTIONS http://localhost:4000/users/ 401 (Unauthorized)

Failed to load http://localhost:4000/users/: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Uncaught (in promise) TypeError: Failed to fetch

My RestAPI have Basic Auth, but i don't know what i'm supposed to insert in headers to have access. I got this 'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=', from Postman, when I configured the Authorization tab, and it was automatically added to the headers.

I'm using Google Chrome as my default browser.

My backend code is the following:

const express =     require('express');
const bodyParser =  require('body-parser');
const mongoose =    require('mongoose');
var basicAuth =     require('express-basic-auth')

const app = express();

mongoose.connect('mongodb://localhost/usersregs', { useMongoClient: true });
mongoose.Promise = global.Promise;

app.use(basicAuth({
    users: {
        'admin': 'supersecret',
        'adam': 'password1234',
        'eve': 'asdfghjkl'
    }
}))

app.use(bodyParser.json());

app.use(function(err, req, res, next){
    console.log(err);
    //res.status(450).send({err: err.message})
});

app.use(require('./routes/api'));

app.listen(4000, function(){
    console.log('Now listening for request at port 4000');
});


问:
Angular 2 routing to specific part of a webpage from one component link to another component
I have a link in footer that takes to the terms page but I want that link to take to a specific part of the terms webpage (3rd paragraph in terms).

Here is the code for footer.component.html

```<code><a routerLink="terms">Terms & conditions</a> |
<a routerLink="terms">Privacy policy</a> |
<a routerLink="terms">Cancellation policy</a>
</code>```

In terms.component.html is the place where i want the privacy policy link in the footer to be opened when clicked.

```<code><ol start="3">
    <li>INFORMATION SUBMITTED THROUGH OR TO OUR SERVICES</li>
</ol>
</code>```

What do we need to use for these to work? Any help is appreciated. Thanks.

答:
Here is the answer ,

and  Terms & conditions | Privacy policy | Cancellation policy

Instead of just using . Terms & conditions

use like this

```<code> <a [routerLink]="['/terms']" fragment="terms"> Terms & conditions </a>
 <a [routerLink]="['/terms']" fragment="cancel"> Cancellation policy </a>
 <a [routerLink]="['/terms']" fragment="privacy"> Privacy policy </a>
</code>```

page should be like

```<code><ol start="3" id="privacy" >
     <li>INFORMATION SUBMITTED THROUGH OR TO OUR SERVICES</li>
</ol>

 <ol start="3" id="terms" >
     <li>INFORMATION SUBMITTED THROUGH OR TO OUR SERVICES</li>
 </ol>

 <ol start="3" id="cancel" >
     <li>INFORMATION SUBMITTED THROUGH OR TO OUR SERVICES</li>
 </ol>
</code>```

Refer to the API for detailed descriptions and usage. - https://angular.io/api/router/RouterLink

Body:
I have a link in footer that takes to the terms page but I want that link to take to a specific part of the terms webpage (3rd paragraph in terms).

Here is the code for footer.component.html

Terms & conditions |
Privacy policy |
Cancellation policy

In terms.component.html is the place where i want the privacy policy link in the footer to be opened when clicked.

INFORMATION SUBMITTED THROUGH OR TO OUR SERVICES

What do we need to use for these to work? Any help is appreciated. Thanks.

Body:
Here is the answer ,

and  <a routerLink="terms">Terms & conditions</a> | <a routerLink="terms">Privacy policy</a> | <a routerLink="terms">Cancellation policy</a>

Instead of just using . <a routerLink="terms">Terms & conditions</a>

use like this

 <a [routerLink]="['/terms']" fragment="terms"> Terms & conditions </a>
 <a [routerLink]="['/terms']" fragment="cancel"> Cancellation policy </a>
 <a [routerLink]="['/terms']" fragment="privacy"> Privacy policy </a>

page should be like

<ol start="3" id="privacy" >
     <li>INFORMATION SUBMITTED THROUGH OR TO OUR SERVICES</li>
</ol>

 <ol start="3" id="terms" >
     <li>INFORMATION SUBMITTED THROUGH OR TO OUR SERVICES</li>
 </ol>

 <ol start="3" id="cancel" >
     <li>INFORMATION SUBMITTED THROUGH OR TO OUR SERVICES</li>
 </ol>

Refer to the API for detailed descriptions and usage. - https://angular.io/api/router/RouterLink


问:
Can I Avoid Passing Default Value of Optional Parameters?
Background:

This method accepts 3 optional parameters (with default values)

```<code>public void Test(string Name, int p1 = 1, int p2 = 2, int p3 = 3)
{
   // do something
}
</code>```

Can be called by:

```<code>Test("Something");
</code>```

If I need to override p1:

```<code>Test("Something", 5);
</code>```

Question:

Is there any way to override p3 without passing values to p1 and p2? so I can use default values of p1 and p2 without passing them.

I need something like:

```<code>Test("Something", default, default, 50);
</code>```

答:
you can do it by specify the param name</p>

```<code>Test("Something", p3:50)
</code>```

Body:
Background:

This method accepts 3 optional parameters (with default values)

public void Test(string Name, int p1 = 1, int p2 = 2, int p3 = 3)
{
   // do something
}

Can be called by:

Test("Something");

If I need to override p1:

Test("Something", 5);

Question:

Is there any way to override p3 without passing values to p1 and p2? so I can use default values of p1 and p2 without passing them.

I need something like:

Test("Something", default, default, 50);

Body:
you can do it by specify the param name

Test("Something", p3:50)


问:
Changing variables
I am sure this is just something simple but I am just getting into C# and this isn't clicking in my mind.

I basically need to assign to a button of mine the function of changing the variable offsets that my tool uses to write data to my 3DS.

I have both variables but I don't really know how to tell it to switch from using 1 set to the other when I press it and then waterfall back if I press it again.

This is my code here showing my variables that are called upon throughout my tool

```<code>public partial class MainForm : Form
{

    public delegate void LogDelegate(string l);
    public LogDelegate delLastLog;
    public string lastlog = "";
    public int pid = 0;
    public PKHeX dumpedPKHeX = new PKHeX();
    //Possibly Ultra box layout Offset? 0x33015AB0
    //Possibly Ultra Wondercard Offset? 0x33075BF4
    public uint boxOff = 0x330D9838;
    public uint wcOff = 0x331397E4;
    public uint partyOff = 0x34195E10;
</code>```

Then this is my button I have started.

```<code>private void btn_ConvertMode_Click(object sender, EventArgs e)
{
    MessageBox.Show("Ultra Support Mode Activated!", "WonderInjection", MessageBoxButtons.OK);
    return;
}
</code>```

Any idea guys? Basically the boxoff and wcoff offsets I need to be able to be switched to the ones I have commented out one the command of the button.

答:
I'd just create a variable of type bool to hold the toggle state. On each button click event, toggle the state of this variable:

```<code>toggleVar = !toggleVar;
</code>```

Then use the value of this toggleVar to decide which offset to use.

Title: Changing variables

Body:
I am sure this is just something simple but I am just getting into C# and this isn't clicking in my mind.

I basically need to assign to a button of mine the function of changing the variable offsets that my tool uses to write data to my 3DS.

I have both variables but I don't really know how to tell it to switch from using 1 set to the other when I press it and then waterfall back if I press it again.

This is my code here showing my variables that are called upon throughout my tool

public partial class MainForm : Form
{

    public delegate void LogDelegate(string l);
    public LogDelegate delLastLog;
    public string lastlog = "";
    public int pid = 0;
    public PKHeX dumpedPKHeX = new PKHeX();
    //Possibly Ultra box layout Offset? 0x33015AB0
    //Possibly Ultra Wondercard Offset? 0x33075BF4
    public uint boxOff = 0x330D9838;
    public uint wcOff = 0x331397E4;
    public uint partyOff = 0x34195E10;

Then this is my button I have started.

private void btn_ConvertMode_Click(object sender, EventArgs e)
{
    MessageBox.Show("Ultra Support Mode Activated!", "WonderInjection", MessageBoxButtons.OK);
    return;
}

Any idea guys? Basically the boxoff and wcoff offsets I need to be able to be switched to the ones I have commented out one the command of the button.

Body:
I'd just create a variable of type bool to hold the toggle state. On each button click event, toggle the state of this variable:

toggleVar = !toggleVar;

Then use the value of this toggleVar to decide which offset to use.


问:
what are the reasons for virtualising these instructions?
why is it the below instructions has to be virtualised. How is failing to virtualise this can cause problem.

sgdt,sldt,sidt,smsw

fcall,longjump,srt

lar,verr,verw,lsl

pushf, popf, iret

答:
When Intel VMX mode is used for virtualization, which is the case for current virtualization solutions on Intel platforms, none of these instructions need to be virtualized by the VMM, because they do not access or change the protected machine state.

The VMM is allowed (but not required) to request a VM exit for sgdt, sldt, sidt, and str. Other than these, none of the instructions listed ever cause a VM exit.

The processor itself performs minor virtualization of two of these instructions:

The behavior of SMSW is changed in the guest so that the guest sees
the value the VMM wants it to.

The behavior of the IRET instruction is changed in the guest to clear
NMI blocking.


问:
java split keep the separator as independent array element
I want to split the string

```<code>Actual #keys: {}, Estimated #keys:{}, Err%: {}"
</code>```

to

```<code>[{}, Actual #keys: , {}, Estimated #keys:, {}, Err%: , {}]
</code>```

I try use

```<code>str.split("(?=\\b\\{\\})")
</code>```

but its result is

```<code>[{}Actual #keys: {}, Estimated #keys:{}, Err%: {}]
</code>```

答: If {} is separator then (?<=.)(?=\\{}))|((?<=\\{})(?=.)) should work. This means - split between any char and separator or between separator and any char.

Body:
I want to split the string

Actual #keys: {}, Estimated #keys:{}, Err%: {}"

to

[{}, Actual #keys: , {}, Estimated #keys:, {}, Err%: , {}]

I try use

str.split("(?=\\b\\{\\})")

but its result is

[{}Actual #keys: {}, Estimated #keys:{}, Err%: {}]


问:
Storing Results of queries into one table
I have multiple different queries and I want to store their results into one table. Results of this queries may have different number of rows and columns.

e.g.
I have three queries:

Q1. select name,id from employee;  (Result has 2 columns and 2 rows)

Q2. select salary from emp_table     (Result has 1 column and 4 rows)

Q3. select country_name,Country_id,count(id) from players group by country_name,Country_id (result has 3 columns and 3 rows)

Now, I want to store these results into one table which has structure like :

```<code>Query_ID | col1  | col2 | col3
-------------------------------
</code>```

In this table query_id is unique id to queries like A1,A2,A3...

When queries have less than three columns as result, remaining column should be filled with null (for first query col3 should be null and for second query col2 and col 3 should be null).

desired output:

```<code>Query_ID | col1   | col2 | col3
----------
A1       | John   | 1356 | NULL
A1       | Mathew | 1667 | NULL
A2       | 1500   | NULL | NULL
A2       | 2000   | NULL | NULL
A2       | 3000   | NULL | NULL
A2       | 3500   | NULL | NULL
A3       | US     | 010  | 25
A3       | UK     | 012  | 26
A3       | GER    | 016  | 16
</code>```

答:
```<code>insert into new_table (query_id,col1,col2,col3)
select 'A1' as QUERY_ID,name as col1,id as col2,'' as col3 from employee
union all
select 'A2' AS QUERY_ID,salary as col1,'' as col2,'' as col3 from emp_table
union all
select 'A3' AS QUERY_ID,country_name,Country_id,count(id) from players group by country_name,Country_id;
</code>```

Make sure the data types of the column that you are fetching are compatible. Suppose name column is varchar and salary that you are fetching is number that this will fail.

ContentLicense: CC BY-SA 4.0

Body:
I have multiple different queries and I want to store their results into one table. Results of this queries may have different number of rows and columns.

e.g.
I have three queries:

Q1. select name,id from employee;  (Result has 2 columns and 2 rows)

Q2. select salary from emp_table     (Result has 1 column and 4 rows)

Q3. select country_name,Country_id,count(id) from players group by country_name,Country_id (result has 3 columns and 3 rows)

Now, I want to store these results into one table which has structure like :

Query_ID | col1  | col2 | col3
-------------------------------

In this table query_id is unique id to queries like A1,A2,A3...

When queries have less than three columns as result, remaining column should be filled with null (for first query col3 should be null and for second query col2 and col 3 should be null).

desired output:

Query_ID | col1   | col2 | col3
----------
A1       | John   | 1356 | NULL
A1       | Mathew | 1667 | NULL
A2       | 1500   | NULL | NULL
A2       | 2000   | NULL | NULL
A2       | 3000   | NULL | NULL
A2       | 3500   | NULL | NULL
A3       | US     | 010  | 25
A3       | UK     | 012  | 26
A3       | GER    | 016  | 16

Body:
insert into new_table (query_id,col1,col2,col3)
select 'A1' as QUERY_ID,name as col1,id as col2,'' as col3 from employee
union all
select 'A2' AS QUERY_ID,salary as col1,'' as col2,'' as col3 from emp_table
union all
select 'A3' AS QUERY_ID,country_name,Country_id,count(id) from players group by country_name,Country_id;

Make sure the data types of the column that you are fetching are compatible. Suppose name column is varchar and salary that you are fetching is number that this will fail.


问:
Extract vector images from Revit file
I was wondering if it's possible to extract Vector images from 2d views of revit files from forge api. I've used the following endpoint to achieve thumbnail of the views, but the thumbnails are very small (400 x 400)

https://developer.autodesk.com/en/docs/model-derivative/v2/reference/http/urn-thumbnail-GET/

Is there a way I can extract high resolution image, (preferably in vector formate that can be zoomed in or out) from a 2d View ?

Here's an example that I've tried:
https://jsfiddle.net/uLnvwyLa/

答:
For the 2d views in Revit, the short answer is that Forge does not support translating 2d views to vector images or high resolution images as you wanted.

But here is some additional information in case this is also workable for you. You can use Model Derivative API to translate the 2d views into f2d format, just make sure to set the output.formats.views to both "2d" and "3d". You can not open this f2d file directly, but only through the Viewer3D library to load it into browser just as same as svf file, check the doc and tutorials here, the result looks as follow, and you can use http://lmv.ninja.autodesk.com to play with a 2d sheet and see how it works in browser.

Title: Extract vector images from Revit file


问:
How does select work when multiple channels are involved?
I found when using select on multiple non buffered channels like

```<code>select {
case <- chana:
case <- chanb:
}
</code>```

Even when both channels have data, but when processing this select,
the call that falls in case chana and case chanb is not balanced.

```<code>package main

import (
    "fmt"
    _ "net/http/pprof"
    "sync"
    "time"
)

func main() {
    chana := make(chan int)
    chanb := make(chan int)

    go func() {
        for i := 0; i < 1000; i++ {
            chana <- 100 * i
        }
    }()

    go func() {
        for i := 0; i < 1000; i++ {
            chanb <- i
        }
    }()

    time.Sleep(time.Microsecond * 300)

    acount := 0
    bcount := 0
    wg := sync.WaitGroup{}
    wg.Add(1)
    go func() {
        for {
            select {
            case <-chana:
                acount++
            case <-chanb:
                bcount++
            }
            if acount == 1000 || bcount == 1000 {
                fmt.Println("finish one acount, bcount", acount, bcount)
                break
            }
        }
        wg.Done()
    }()

    wg.Wait()
}
</code>```

Run this demo, when one of the chana,chanb finished read/write, the other may remain 999-1 left.

Is there any method to ensure the balance?

found related topic

golang-channels-select-statement

答:
Edited : You can balance from the supply side too, but @icza's answer seems to be a better option to me than this & also explains scheduling which was causing this in the first place. Surprisingly it was one-sided even on my (virtual) machine.

Here's something which can balance two routines from the supply side (somehow doesn't seem to work on Playground).

```<code>package main

import (
    "fmt"
    _ "net/http/pprof"
    "sync"
    "sync/atomic"
    "time"
)

func main() {
    chana := make(chan int)
    chanb := make(chan int)
    var balanceSwitch int32

    go func() {
        for i := 0; i < 1000; i++ {
            for atomic.LoadInt32(&balanceSwitch) != 0 {
                fmt.Println("Holding R1")
                time.Sleep(time.Nanosecond * 1)
            }
            chana <- 100 * i
            fmt.Println("R1: Sent i", i)
            atomic.StoreInt32(&balanceSwitch, 1)

        }
    }()

    go func() {
        for i := 0; i < 1000; i++ {

            for atomic.LoadInt32(&balanceSwitch) != 1 {
                fmt.Println("Holding R2")
                time.Sleep(time.Nanosecond * 1)
            }
            chanb <- i
            fmt.Println("R2: Sent i", i)
            atomic.StoreInt32(&balanceSwitch, 0)

        }
    }()

    time.Sleep(time.Microsecond * 300)

    acount := 0
    bcount := 0
    wg := sync.WaitGroup{}
    wg.Add(1)
    go func() {
        for {
            select {
            case <-chana:
                acount++
            case <-chanb:
                bcount++
            }
            fmt.Println("Acount Bcount", acount, bcount)
            if acount == 1000 || bcount == 1000 {
                fmt.Println("finish one acount, bcount", acount, bcount)
                break
            }
        }
        wg.Done()
    }()

    wg.Wait()
}
</code>```

By changing atomic.LoadInt32(&balanceSwitch) != XX and atomic.StoreInt32(&balanceSwitch, X), or other mechanisms you can map it to any number of routines. It may not be the best thing to do, but if that's a requirement then you may have to consider such options. Hope this helps.

Body:
I found when using select on multiple non buffered channels like

select {
case <- chana:
case <- chanb:
}

Even when both channels have data, but when processing this select,
the call that falls in case chana and case chanb is not balanced.

package main

import (
    "fmt"
    _ "net/http/pprof"
    "sync"
    "time"
)

func main() {
    chana := make(chan int)
    chanb := make(chan int)

    go func() {
        for i := 0; i < 1000; i++ {
            chana <- 100 * i
        }
    }()

    go func() {
        for i := 0; i < 1000; i++ {
            chanb <- i
        }
    }()

    time.Sleep(time.Microsecond * 300)

    acount := 0
    bcount := 0
    wg := sync.WaitGroup{}
    wg.Add(1)
    go func() {
        for {
            select {
            case <-chana:
                acount++
            case <-chanb:
                bcount++
            }
            if acount == 1000 || bcount == 1000 {
                fmt.Println("finish one acount, bcount", acount, bcount)
                break
            }
        }
        wg.Done()
    }()

    wg.Wait()
}

Run this demo, when one of the chana,chanb finished read/write, the other may remain 999-1 left.

Is there any method to ensure the balance?

found related topic

golang-channels-select-statement

Body:
Edited : You can balance from the supply side too, but @icza's answer seems to be a better option to me than this & also explains scheduling which was causing this in the first place. Surprisingly it was one-sided even on my (virtual) machine.

Here's something which can balance two routines from the supply side (somehow doesn't seem to work on Playground).

package main

import (
    "fmt"
    _ "net/http/pprof"
    "sync"
    "sync/atomic"
    "time"
)

func main() {
    chana := make(chan int)
    chanb := make(chan int)
    var balanceSwitch int32

    go func() {
        for i := 0; i < 1000; i++ {
            for atomic.LoadInt32(&balanceSwitch) != 0 {
                fmt.Println("Holding R1")
                time.Sleep(time.Nanosecond * 1)
            }
            chana <- 100 * i
            fmt.Println("R1: Sent i", i)
            atomic.StoreInt32(&balanceSwitch, 1)

        }
    }()

    go func() {
        for i := 0; i < 1000; i++ {

            for atomic.LoadInt32(&balanceSwitch) != 1 {
                fmt.Println("Holding R2")
                time.Sleep(time.Nanosecond * 1)
            }
            chanb <- i
            fmt.Println("R2: Sent i", i)
            atomic.StoreInt32(&balanceSwitch, 0)

        }
    }()

    time.Sleep(time.Microsecond * 300)

    acount := 0
    bcount := 0
    wg := sync.WaitGroup{}
    wg.Add(1)
    go func() {
        for {
            select {
            case <-chana:
                acount++
            case <-chanb:
                bcount++
            }
            fmt.Println("Acount Bcount", acount, bcount)
            if acount == 1000 || bcount == 1000 {
                fmt.Println("finish one acount, bcount", acount, bcount)
                break
            }
        }
        wg.Done()
    }()

    wg.Wait()
}

By changing atomic.LoadInt32(&balanceSwitch) != XX and atomic.StoreInt32(&balanceSwitch, X), or other mechanisms you can map it to any number of routines. It may not be the best thing to do, but if that's a requirement then you may have to consider such options. Hope this helps.


问:
Loop synchronization deadlock
I've got the following classes in Java

```<code>public class Counter {
    private int value;

    public Counter(int value) {
        this.value = value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public void decrement() {
        this.value--;
    }
    public int getValue() {
        return this.value;
    }
}

public class Cell extends Thread {

    private Object sync;
    private Counter counter;

    public Cell(Object sync, Counter counter) {
        this.sync = sync;
        this.counter = counter;
    }

    public void run() {
        for (int r=0; r<Simulation.ROUND_NUM; r++) {

            // do something

            synchronized(counter) {
                counter.decrement();
                counter.notifyAll();
            }
            synchronized(sync) {
                try {
                    sync.wait();
                }
                catch (Exception ex) {}
            }

        }
    }
}

public class Simulation extends Thread {

    public static final int THREAD_NUM = 5;
    public static final int ROUND_NUM = 5;

    public Object sync = new Object();
    private Counter counter = new Counter(THREAD_NUM);

    public void run() {

        for (int i=0; i<THREAD_NUM; i++) {
            Cell c = new Cell(sync,counter);
            c.start();
        }

        for (int i=0; i<ROUND_NUM; i++) {
            synchronized(counter) {
                while(counter.getValue() != 0) {
                    try {
                        counter.wait();
                    }
                    catch (Exception ex) {}
                }
                counter.setValue(THREAD_NUM);
            }

            synchronized(sync) {
                sync.notifyAll();
            }
        }
    }
}
</code>```

The aim is to prevent from executing the next iteration of loop in each Cell Thread, until every Cell Thread will be done on each iteration. My solution sometimes leads to deadlock. I can't understand why. Please help

答:
Lovely example!  It isn't deadlock, since by definition that can only occur when a thread holds more than one lock simultaneously, and another tries to acquire the same locks in a different order.

I suspect that the problem here is caused by spurious wake-ups occurring in the Cell objects (if a spurious wake-up occured in the Simulation object it would have no effect as the wait() is called in a loop which will cause the wait to be re-entered).

A spurious wake-up in a Cell will cause an extra decrement.  This in turn will make the test while(counter.getValue() != 0) to be stepped over.

Change that condition to while(counter.getValue() >= 0) and the 'deadlocks should disappear.  Please let us know if it works.

Title: Loop synchronization deadlock

Body:
I've got the following classes in Java

public class Counter {
    private int value;

    public Counter(int value) {
        this.value = value;
    }
    public void setValue(int value) {
        this.value = value;
    }
    public void decrement() {
        this.value--;
    }
    public int getValue() {
        return this.value;
    }
}

public class Cell extends Thread {

    private Object sync;
    private Counter counter;

    public Cell(Object sync, Counter counter) {
        this.sync = sync;
        this.counter = counter;
    }

    public void run() {
        for (int r=0; r<Simulation.ROUND_NUM; r++) {

            // do something

            synchronized(counter) {
                counter.decrement();
                counter.notifyAll();
            }
            synchronized(sync) {
                try {
                    sync.wait();
                }
                catch (Exception ex) {}
            }

        }
    }
}

public class Simulation extends Thread {

    public static final int THREAD_NUM = 5;
    public static final int ROUND_NUM = 5;

    public Object sync = new Object();
    private Counter counter = new Counter(THREAD_NUM);

    public void run() {

        for (int i=0; i<THREAD_NUM; i++) {
            Cell c = new Cell(sync,counter);
            c.start();
        }

        for (int i=0; i<ROUND_NUM; i++) {
            synchronized(counter) {
                while(counter.getValue() != 0) {
                    try {
                        counter.wait();
                    }
                    catch (Exception ex) {}
                }
                counter.setValue(THREAD_NUM);
            }

            synchronized(sync) {
                sync.notifyAll();
            }
        }
    }
}

The aim is to prevent from executing the next iteration of loop in each Cell Thread, until every Cell Thread will be done on each iteration. My solution sometimes leads to deadlock. I can't understand why. Please help


问:
Issue with If Clause in php
I am very new to this site and this is my first question. I want to display different submission forms on the basis of input being sent via form. Please have a look at the following code:

```<code><?php
if(isset($_POST['submit'])){
    $camp = $_POST['camp'];

    if($camp == "Final Expense"){
        echo "FE Form Goes Here";
    }
    if($camp == "Home Improvements"){
        echo "HI Form Goes Here";
    }
?>
</code>```

Now since there is space between Home Improvements and also between Final Expense Word, therefore it is always false. If I remove the space from input and remove space from here e.g Home_Improvements and Final_Expense then it works.

How Can I maintain the input with spaces and the tests here with spaces too. Please answer anybody. Thanks..

答:
The blanks shouldn't be problem.

Be sure that you have post the whole words. You could check this by echoing the field you posted.

To avoid posting incomplete words, please add quotation marks.

Title: Issue with If Clause in php

Body:
I am very new to this site and this is my first question. I want to display different submission forms on the basis of input being sent via form. Please have a look at the following code:

<?php
if(isset($_POST['submit'])){
    $camp = $_POST['camp'];

    if($camp == "Final Expense"){
        echo "FE Form Goes Here";
    }
    if($camp == "Home Improvements"){
        echo "HI Form Goes Here";
    }
?>

Now since there is space between Home Improvements and also between Final Expense Word, therefore it is always false. If I remove the space from input and remove space from here e.g Home_Improvements and Final_Expense then it works.

How Can I maintain the input with spaces and the tests here with spaces too. Please answer anybody. Thanks..


问:
How I can improve execution time of recursive promise on Edge? On chrome it is almost instantenous for 100000 records
In code snippet below the promise is recursively called after completion of itself. I ran the following code snippet on Edge and on Chrome and am seeing a marked difference in execution time. Is there something wrong that I am doing? How I can improve the execution time on Edge?

Please ignore the promise 'anti-pattern'. It is just to simulate an asynchronous method.

Chrome result -
Count - 99999
Start 1512416096194
last update 1512416096509
End 1512416096577
recursiveFnReturnsPromise finished

execution time - 397ms

Edge result -
Count - 99999
Start 1512415183349
last update 1512415508413
End 1512415907219
recursiveFnReturnsPromise finished

execution time between the start and the end- 723870ms

execution time between last the DOM update and the end- 398806ms

//large array
let aValues = Array(100000);

//utility function
function writeln(text) {
  let p = document.createElement('div');
  p.innerText = text;
  document.getElementById('v1').appendChild(p);
}

writeln('Start ' +Date.now()); //note start recursion time

recursiveFnReturnsPromiseV1(aValues, 1).then(function() {
  writeln('End ' +Date.now());//note end recursion time
  writeln('recursiveFnReturnsPromise finished');
}, function() {
  writeln('End' +Date.now());
  writeln('recursiveFnReturnsPromise failed');
})

//the recursive functions which returns a promise
function recursiveFnReturnsPromiseV1(pValues, ix) {
  if (pValues.length <= ix)
    return Promise.resolve();

  return new Promise(function(c, e) {
    document.getElementById('output').innerText = ix;
    if(ix==99999) writeln('last update ' +Date.now());
    c();
  }).then(function() {
    return recursiveFnReturnsPromiseV1(pValues, ++ix);
  })
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>Count - <span id='output'></span>
<div id='v1'></div></code>```

Note - for anyone interested in trying to do promise recursion right please see related post - What is the difference in following pattern to call recursive JavaScript function which returns a promise?

答:
It may have something to do with Chrome optimizing paints so when I add an element to dom and then change style in 2 different resolve functions it is handled as one action (one paint) depending how quickly the 2 dom interaction requests were made.

The following won't animate in Chrome:

const el = document.querySelector("#content");
Promise.resolve(el)
.then(
  _=>
    el.innerHTML = `

hello world

    `
)
.then(
  _ =>
    // setTimeout(x=>el.querySelector("div").style.top = "2px",100)
    el.querySelector("div").style.top = "2px"
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content">
</div></code>```

If that one animates in Edge that means your appendChild and innerText causes thousands of paints in edge but doesn't in Chrome, the following will animate in Chrome and Firefox because getBoundingClientRect will flush scheduled changes to the dom, you could use this if add and/or animate elements in a promise chain:

const el = document.querySelector("#content");
Promise.resolve(el)
.then(
  _=>{
    el.innerHTML = `

hello world

    `;
    //this will trigger paint as well (in case you do want to animate)
    //  it will flush changes to the dom before getting bounding
    el.getBoundingClientRect();
  }
)
.then(
  _ =>
    // setTimeout(x=>el.querySelector("div").style.top = "2px",100)
    el.querySelector("div").style.top = "2px"
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content">
</div></code>```

Body:
In code snippet below the promise is recursively called after completion of itself. I ran the following code snippet on Edge and on Chrome and am seeing a marked difference in execution time. Is there something wrong that I am doing? How I can improve the execution time on Edge?

Please ignore the promise 'anti-pattern'. It is just to simulate an asynchronous method.

Chrome result -
Count - 99999
Start 1512416096194
last update 1512416096509
End 1512416096577
recursiveFnReturnsPromise finished

execution time - 397ms

Edge result -
Count - 99999
Start 1512415183349
last update 1512415508413
End 1512415907219
recursiveFnReturnsPromise finished

execution time between the start and the end- 723870ms

execution time between last the DOM update and the end- 398806ms

//large array
let aValues = Array(100000);

//utility function
function writeln(text) {
  let p = document.createElement('div');
  p.innerText = text;
  document.getElementById('v1').appendChild(p);
}

writeln('Start ' +Date.now()); //note start recursion time

recursiveFnReturnsPromiseV1(aValues, 1).then(function() {
  writeln('End ' +Date.now());//note end recursion time
  writeln('recursiveFnReturnsPromise finished');
}, function() {
  writeln('End' +Date.now());
  writeln('recursiveFnReturnsPromise failed');
})

//the recursive functions which returns a promise
function recursiveFnReturnsPromiseV1(pValues, ix) {
  if (pValues.length <= ix)
    return Promise.resolve();

  return new Promise(function(c, e) {
    document.getElementById('output').innerText = ix;
    if(ix==99999) writeln('last update ' +Date.now());
    c();
  }).then(function() {
    return recursiveFnReturnsPromiseV1(pValues, ++ix);
  })
}

Count -

Note - for anyone interested in trying to do promise recursion right please see related post - What is the difference in following pattern to call recursive JavaScript function which returns a promise?

Body:
It may have something to do with Chrome optimizing paints so when I add an element to dom and then change style in 2 different resolve functions it is handled as one action (one paint) depending how quickly the 2 dom interaction requests were made.

The following won't animate in Chrome:

const el = document.querySelector("#content");
Promise.resolve(el)
.then(
  _=>
    el.innerHTML = `
    <div style="position:absolute;top:100px;transition:top 2s;">hello world</div>
    `
)
.then(
  _ =>
    // setTimeout(x=>el.querySelector("div").style.top = "2px",100)
    el.querySelector("div").style.top = "2px"
);

<div id="content">
</div>

If that one animates in Edge that means your appendChild and innerText causes thousands of paints in edge but doesn't in Chrome, the following will animate in Chrome and Firefox because getBoundingClientRect will flush scheduled changes to the dom, you could use this if add and/or animate elements in a promise chain:

const el = document.querySelector("#content");
Promise.resolve(el)
.then(
  _=>{
    el.innerHTML = `
    <div style="position:absolute;top:100px;transition:top 2s;">hello world</div>
    `;
    //this will trigger paint as well (in case you do want to animate)
    //  it will flush changes to the dom before getting bounding
    el.getBoundingClientRect();
  }
)
.then(
  _ =>
    // setTimeout(x=>el.querySelector("div").style.top = "2px",100)
    el.querySelector("div").style.top = "2px"
);

<div id="content">
</div>


问:
How secondary index scan works in InnoDB?
InnoDB has two types of indexes: primary (clustered), and secondary (with pimary index key).

When I type query that scan fields indexed by secondary index my question starts.
Is InnoDB scan secondary index and retrive one by one records that hit condition?
If I have 50 hits in secondary index InnoDB seek 50 times primary index?

答:
Is InnoDB scan secondary index and retrive one by one records that hit condition?

If you select columns not covered by the secondary index, then yes, it should retrieve them from the table (the clustered index).

If you have this layout:

```<code>CREATE TABLE a (id INT NOT NULL PRIMARY KEY, ca INT NOT NULL, cb INT NOT NULL, KEY(ca))

SELECT  cb
FROM    a
WHERE   ca = $some_value
</code>```

the following happens:

Using a B-Tree seek, InnoDB finds the first record in the index on ca which holds $some_value

It then traverses the index, taking records one by one, until it finds the first record greater than $some_value.

Since only ca (key column) and id (row pointer) are contained in the index, InnoDB needs to find values of cb in the table itself.

For each record in the index, it takes the value of id and searches the table for it. Since the table is in fact a clustered index on id, B-Tree search is used for that.

However, if you have this query:

```<code>SELECT  ca, id
FROM    a
WHERE   ca = $some_value
</code>```

, then everything can be retrieved right from the index, and steps 3 and 4 are not performed. It is shown in the query plan as using index.

If I have 50 hits in secondary index InnoDB seek 50 times primary index?

Yes (with regard to the comment above)

Body:
Is InnoDB scan secondary index and retrive one by one records that hit condition?

If you select columns not covered by the secondary index, then yes, it should retrieve them from the table (the clustered index).

If you have this layout:

CREATE TABLE a (id INT NOT NULL PRIMARY KEY, ca INT NOT NULL, cb INT NOT NULL, KEY(ca))

SELECT  cb
FROM    a
WHERE   ca = $some_value

the following happens:

Using a B-Tree seek, InnoDB finds the first record in the index on ca which holds $some_value

It then traverses the index, taking records one by one, until it finds the first record greater than $some_value.

Since only ca (key column) and id (row pointer) are contained in the index, InnoDB needs to find values of cb in the table itself.

For each record in the index, it takes the value of id and searches the table for it. Since the table is in fact a clustered index on id, B-Tree search is used for that.

However, if you have this query:

SELECT  ca, id
FROM    a
WHERE   ca = $some_value

, then everything can be retrieved right from the index, and steps 3 and 4 are not performed. It is shown in the query plan as using index.

If I have 50 hits in secondary index InnoDB seek 50 times primary index?

Yes (with regard to the comment above)


问:
ngModel is not working in select options inside a for loop
I am trying to add options in a html select inside a for loop. To get the selected option i am using [(ngModel)] but by default no option is selected.

Sample Code:

```<code><table align="center">
    <tr *ngFor="let d of data; let i = index">
        <td>
          <select id="status" [(ngModel)]="d.status" name="d.status" (change)="onStatusChange(i, d.id)">
            <option *ngFor="let o of statusArray" [ngValue]="o">{{o.name}}</option>
          </select>
        </td>
    </tr>
</table>
</code>```

This is the component that I am using:

```<code>export class AboutComponent implements OnInit {
    statusArray;
    data;

  constructor() { }

  ngOnInit() {
    this.statusArray = [
        {
            "id": 1,
            "name": "Testing"
        },
        {
            "id": 2,
            "name": "Free Trial"
        },
        {
            "id": 3,
            "name": "Active/Paying"
        }
    ];

    this.data = [
        {
            "id": 2,
            "status": {
                "id": 1,
                "name": "Testing"
            },
            "new": false
        },
        {
            "id": 3,
            "status": {
                "id": 1,
                "name": "Testing"
            },
            "new": false
        },
        {
            "id": 4,
            "status": {
                "id": 2,
                "name": "Free Trial"
            },
            "new": false
        }
    ];
  }

}
</code>```

Output :

Here in the output i am getting the options in the list but default value is not selected:

答:
you compare options to select by compareWith property, If you are using angular 4.

HTML File :

```<code><select [compareWith]="byAnimal" [(ngModel)]="selectedAnimal">
  <option *ngFor="let animal of animals" [ngValue]="animal">
    {{animal.type}}
  </option>
</select>
</code>```

TS File

```<code>byAnimal(item1,item2){
  return item1.type == item2.type;
}
</code>```

One of the best soltion from this link

Body:
I am trying to add options in a html select inside a for loop. To get the selected option i am using [(ngModel)] but by default no option is selected.

Sample Code:

          <select id="status" [(ngModel)]="d.status" name="d.status" (change)="onStatusChange(i, d.id)">
            <option *ngFor="let o of statusArray" [ngValue]="o">{{o.name}}</option>
          </select>

This is the component that I am using:

export class AboutComponent implements OnInit {
    statusArray;
    data;

  constructor() { }

  ngOnInit() {
    this.statusArray = [
        {
            "id": 1,
            "name": "Testing"
        },
        {
            "id": 2,
            "name": "Free Trial"
        },
        {
            "id": 3,
            "name": "Active/Paying"
        }
    ];

    this.data = [
        {
            "id": 2,
            "status": {
                "id": 1,
                "name": "Testing"
            },
            "new": false
        },
        {
            "id": 3,
            "status": {
                "id": 1,
                "name": "Testing"
            },
            "new": false
        },
        {
            "id": 4,
            "status": {
                "id": 2,
                "name": "Free Trial"
            },
            "new": false
        }
    ];
  }

}

Output :

Here in the output i am getting the options in the list but default value is not selected:

Body:
you compare options to select by compareWith property, If you are using angular 4.

HTML File :

<select [compareWith]="byAnimal" [(ngModel)]="selectedAnimal">
  <option *ngFor="let animal of animals" [ngValue]="animal">
    {{animal.type}}
  </option>
</select>

TS File

byAnimal(item1,item2){
  return item1.type == item2.type;
}

One of the best soltion from this link


问:
finding out what portion of a QGraphicsItem is visible in a QGraphicsView
I am trying to figure out how to do the mapping between what pixels i can currently see in a QGraphicsView and the actual pixel in the image that is a QGraphicsItem.

For example, if my viewer is 50x50 and my image is 100x100, then when the image loads and is untouched, the 0,0 pixel of the image corresponds to the 0,0 pixel of the viewer.

Now, if I drag the image to the right 10 pixels, that top left 0,0 pixel of the image, is now at (10,0), and I can only see columns 10-40 of the original image.

Also, if I scale to zoom out, to make the image smaller that the QGraphicsView area, perhaps 0,0 of the image maps to 10,0 of the viewer, but 100,100 of the image might only map to 40,40 in the viewer, because i scaled it so small.

I know there are a lot of mapping functions for a QGraphicsItem, but I am just not sure how to detect whichs parts are visible, and how to do that mapping between the Item, Scene, and View.

Thanks for any help

For reference..so far, here is waht I have tried:
Get item shape
map the shape to the scene
mape that from scene using the view
get the bounding rect of the path and find the top left corner of that

Ended up using something like the following:

```<code>    QRect portRect = ui->graphicsView->viewport()->rect();
    QRectF sceneRect = ui->graphicsView->mapToScene(portRect).boundingRect();
    QRectF itemRect = item->mapRectFromScene(sceneRect);

    QRectF isec = itemRect.intersected(item->boundingRect());
</code>```

Thanks stephen chu

答:
```<code>QRect portRect = yourGraphicsView->viewPort()->rect();
QRectF sceneRect = yourGraphicsView->mapToScene(portRect);
QRectF itemRect = yourItem->mapRectFromScene(sceneRect);
</code>```

You may want to do an intersection of the resulting rect with your item's actual rect since the viewport may bt larger than the item.

Body:
I am trying to figure out how to do the mapping between what pixels i can currently see in a QGraphicsView and the actual pixel in the image that is a QGraphicsItem.

For example, if my viewer is 50x50 and my image is 100x100, then when the image loads and is untouched, the 0,0 pixel of the image corresponds to the 0,0 pixel of the viewer.

Now, if I drag the image to the right 10 pixels, that top left 0,0 pixel of the image, is now at (10,0), and I can only see columns 10-40 of the original image.

Also, if I scale to zoom out, to make the image smaller that the QGraphicsView area, perhaps 0,0 of the image maps to 10,0 of the viewer, but 100,100 of the image might only map to 40,40 in the viewer, because i scaled it so small.

I know there are a lot of mapping functions for a QGraphicsItem, but I am just not sure how to detect whichs parts are visible, and how to do that mapping between the Item, Scene, and View.

Thanks for any help

For reference..so far, here is waht I have tried:
Get item shape
map the shape to the scene
mape that from scene using the view
get the bounding rect of the path and find the top left corner of that

Ended up using something like the following:

    QRect portRect = ui->graphicsView->viewport()->rect();
    QRectF sceneRect = ui->graphicsView->mapToScene(portRect).boundingRect();
    QRectF itemRect = item->mapRectFromScene(sceneRect);

    QRectF isec = itemRect.intersected(item->boundingRect());

Thanks stephen chu

Body:
QRect portRect = yourGraphicsView->viewPort()->rect();
QRectF sceneRect = yourGraphicsView->mapToScene(portRect);
QRectF itemRect = yourItem->mapRectFromScene(sceneRect);

You may want to do an intersection of the resulting rect with your item's actual rect since the viewport may bt larger than the item.


问:
echo $(command) gets a different result with the output of the command
The Bash command I used:

$ ssh user@myserver.com ps -aux|grep -v \"grep\"|grep "/srv/adih/server/app.js"|awk '{print $2}'

```<code>6373
</code>```

$ ssh user@myserver.com echo $(ps -aux|grep -v \"grep\"|grep "/srv/adih/server/app.js"|awk '{print $2}')

```<code>8630
</code>```

The first result is the correct one and the second one will change echo time I execute it. But I don't know why they are different.

What am I doing?

My workstation has very limited resources, so I use a remote machine to run my Node.js application. I run it using ssh user@remotebox.com "cd /application && grunt serve" in debug mode. When I command Ctrl + C, the grunt task is stopped, but the application is is still running in debug mode. I just want to kill it, and I need to get the PID first.

答:
Short answer: the $(ps ... ) command substitution is being run on the local computer, and then its output is sent (along with the echo command) to the remote computer. Essentially, it's running ssh user@myserver.com echo 8630.

Your first command is also probably not doing what you expect; the pipes are interpreted on the local computer, so it's running ssh user@myserver.com ps -aux, piping the output to grep on the local computer, piping that to another grep on the local computer, etc. I'm guessing that you wanted that whole thing to run on the remote computer so that the result could be used on the remote computer to kill a process.

Long answer: the order things are parsed and executed in shell is a bit confusing; with an ssh command in the mix, things get even more complicated. Basically, what happens is that the local shell parses the command line, including splitting it into separate commands (separated by pipes, ;, etc), and expanding $(command) and $variable substitutions (unless they're in single-quotes). It then removes the quotes and escapes (they've done their jobs) and passes the results as arguments to the various commands (such as ssh). ssh takes its arguments, sticks all the ones that look like parts of the remote command together with spaces between them, and sends them to a shell on the remote computer which does this process over again.

This means that quoting and/or escaping things like $ and | is necessary if you want them to be parsed/acted on by the remote shell rather than the local shell. And quotes don't nest, so putting quotes around the whole thing may not work the way you expect (e.g. if you're not careful, the $2 in that awk command might get expanded on the local computer, even though it looks like it's in single-quotes).

When things get messy like this, the easiest way is sometimes to pass the remote command as a here-document rather than as arguments to the ssh command. But you want quotes around the here-document delimiter to keep the various $ expansions from being done by the local shell. Something like this:

```<code>ssh user@myserver.com <<'EOF'
echo $(ps -aux|grep -v "grep"|grep "/srv/adih/server/app.js"|awk '{print $2}')
EOF
</code>```

Note: be careful with indenting the remote command, since the text will be sent literally to the remote computer. If you indent it with tab characters, you can use <<- as the here-document delimiter (e.g. <<-'EOF') and it'll remove the leading tabs.

EDIT: As @tripleee pointed out, there's no need for the multiple greps, since awk can do the whole job itself. It's also unnecessary to exclude the search commands from the results (grep -v grep) because the "/" characters in the pattern need to be escaped, meaning that it won't match itself.. So you can simplify the pipeline to:

```<code>ps -aux | awk '/\/srv\/adih\/server\/app.js/ {print $2}'
</code>```

Now, I've been assuming that the actual goal is to kill the relevant pid, and echo is just there for testing. If that's the case, the actual command winds up being:

```<code>ssh user@myserver.com <<'EOF'
kill $(ps -aux | awk '/\/srv\/adih\/server\/app.js/ {print $2}')
EOF
</code>```

If that's not right, then the whole echo $( ) thing is best skipped entirely. There's no reason to capture the pipeline's output and then echo it, just run it and let it output directly.

And if pkill (or something similar) is available, it's much simpler to use that instead.

Body:
The Bash command I used:

$ ssh user@myserver.com ps -aux|grep -v \"grep\"|grep "/srv/adih/server/app.js"|awk '{print $2}'

6373

$ ssh user@myserver.com echo $(ps -aux|grep -v \"grep\"|grep "/srv/adih/server/app.js"|awk '{print $2}')

8630

The first result is the correct one and the second one will change echo time I execute it. But I don't know why they are different.

What am I doing?

My workstation has very limited resources, so I use a remote machine to run my Node.js application. I run it using ssh user@remotebox.com "cd /application && grunt serve" in debug mode. When I command Ctrl + C, the grunt task is stopped, but the application is is still running in debug mode. I just want to kill it, and I need to get the PID first.

Body:
Short answer: the $(ps ... ) command substitution is being run on the local computer, and then its output is sent (along with the echo command) to the remote computer. Essentially, it's running ssh user@myserver.com echo 8630.

Your first command is also probably not doing what you expect; the pipes are interpreted on the local computer, so it's running ssh user@myserver.com ps -aux, piping the output to grep on the local computer, piping that to another grep on the local computer, etc. I'm guessing that you wanted that whole thing to run on the remote computer so that the result could be used on the remote computer to kill a process.

Long answer: the order things are parsed and executed in shell is a bit confusing; with an ssh command in the mix, things get even more complicated. Basically, what happens is that the local shell parses the command line, including splitting it into separate commands (separated by pipes, ;, etc), and expanding $(command) and $variable substitutions (unless they're in single-quotes). It then removes the quotes and escapes (they've done their jobs) and passes the results as arguments to the various commands (such as ssh). ssh takes its arguments, sticks all the ones that look like parts of the remote command together with spaces between them, and sends them to a shell on the remote computer which does this process over again.

This means that quoting and/or escaping things like $ and | is necessary if you want them to be parsed/acted on by the remote shell rather than the local shell. And quotes don't nest, so putting quotes around the whole thing may not work the way you expect (e.g. if you're not careful, the $2 in that awk command might get expanded on the local computer, even though it looks like it's in single-quotes).

When things get messy like this, the easiest way is sometimes to pass the remote command as a here-document rather than as arguments to the ssh command. But you want quotes around the here-document delimiter to keep the various $ expansions from being done by the local shell. Something like this:

ssh user@myserver.com <<'EOF'
echo $(ps -aux|grep -v "grep"|grep "/srv/adih/server/app.js"|awk '{print $2}')
EOF

Note: be careful with indenting the remote command, since the text will be sent literally to the remote computer. If you indent it with tab characters, you can use <<- as the here-document delimiter (e.g. <<-'EOF') and it'll remove the leading tabs.

EDIT: As @tripleee pointed out, there's no need for the multiple greps, since awk can do the whole job itself. It's also unnecessary to exclude the search commands from the results (grep -v grep) because the "/" characters in the pattern need to be escaped, meaning that it won't match itself.. So you can simplify the pipeline to:

ps -aux | awk '/\/srv\/adih\/server\/app.js/ {print $2}'

Now, I've been assuming that the actual goal is to kill the relevant pid, and echo is just there for testing. If that's the case, the actual command winds up being:

ssh user@myserver.com <<'EOF'
kill $(ps -aux | awk '/\/srv\/adih\/server\/app.js/ {print $2}')
EOF

If that's not right, then the whole echo $( ) thing is best skipped entirely. There's no reason to capture the pipeline's output and then echo it, just run it and let it output directly.

And if pkill (or something similar) is available, it's much simpler to use that instead.


问:
Build errors in cpprest sdk (casablanca) on Ubuntu 16.04
While searching for an HTTP client C++ based library, I have decided to use the casablanca -- so I needed to build it.
I'm running on Ubuntu 16.04.

While following the "common" build steps described here: How-to-build-for-Linux I have encountered a build error (when running the make command as the last operation of step 4).

The entire error output can be found here (now it is the last comment in the thread cpprestsdk-build-error#266).

Just to be sure my system has the needed build tools and libraries I performed the command mentioned in step 2 and this is the output:

--> Which means my system is "good to go".

答:
So after I struggled it a little more, I have found "an alternative" way to build it:

I have downloaded the source code from here: Source Package: casablanca (2.8.0-2) [universe], and again, followed the same instructions STARTING FROM STEP 4 from the link mentioned in the question (How-to-build-for-Linux).

This time the make phase was successful !! (it is worth to mention that not all the unit tests that are recommended to be run on step 5 passed - I did not spend time trying to understand why...).

Went on and "copied-pasted" the complete sample provided at the bottom of the following link: cpprestsdk-Getting-Started-Tutorial.

Built the program with the following command (the program contained a single cpp file called main):

```<code>g++ -std=c++11 main.cpp -o myProg -lboost_system -lcrypto -lssl -lcpprest
</code>```

Ran the program

```<code>./myProg
</code>```

and it passed (there was output in the console saying:"Received response status code:200").

Would be glad to hear if you have encountered the same issue, or perhaps I did something wrong in my first attempt (or in any other step along the way).

Body:
So after I struggled it a little more, I have found "an alternative" way to build it:

I have downloaded the source code from here: Source Package: casablanca (2.8.0-2) [universe], and again, followed the same instructions STARTING FROM STEP 4 from the link mentioned in the question (How-to-build-for-Linux).

This time the make phase was successful !! (it is worth to mention that not all the unit tests that are recommended to be run on step 5 passed - I did not spend time trying to understand why...).

Went on and "copied-pasted" the complete sample provided at the bottom of the following link: cpprestsdk-Getting-Started-Tutorial.

Built the program with the following command (the program contained a single cpp file called main):

g++ -std=c++11 main.cpp -o myProg -lboost_system -lcrypto -lssl -lcpprest

Ran the program

./myProg

and it passed (there was output in the console saying:"Received response status code:200").

Would be glad to hear if you have encountered the same issue, or perhaps I did something wrong in my first attempt (or in any other step along the way).


问:
How can HTML <select/> prevent click through parent's div
I'm creating shopping cart page that there's a div have a click listener for redirecting to the product page, but you also can select qty on the div. How can I prevent the redirection when selecting from <select/>

I've tried event.stopPropagation() / e.preventDefault() on select but not working

Here's the sample code.

https://jsfiddle.net/hk7861es/2/

答:
You can just exclude the <select/> from the click event.

```<code>$('#box').click(function(e) {
            if($(e.target).is('#select')){
            e.preventDefault();
            return;
        }
  $('#text').append('You clicked');
});
</code>```

https://jsfiddle.net/hk7861es/10/

Body:
You can just exclude the <select/> from the click event.

$('#box').click(function(e) {
            if($(e.target).is('#select')){
            e.preventDefault();
            return;
        }
  $('#text').append('You clicked');
});

https://jsfiddle.net/hk7861es/10/


问:
How to get the select value into the controller
I'm trying to create a simple calculator using Angularjs,in my code I can't get the operator value.How can I fix that?

Home html contains get the two numbers and the operator.User have to select the operator..

my Code -

var name = "myApp";
requires = [];
app = angular.module(name, requires);

app.controller('calcCtrl', function($scope) {
    //$scope.cdata={};

    console.log("calcCtrl works!");
    var opp;
    ans = 0;
    opp = $scope.singleSelect;

    console.log("opp ==> "+opp);

    $scope.calculateNums = function(nu1, nu2) {
        console.log("function works!");
        console.log("nu1 ==> "+nu1);
        console.log("opp in calculateNums ==> "+opp);
        if (opp == "+") {
            ans = (parseInt(nu1) + parseInt(nu2));
            console.log("ans ==> "+ans);
        } else if (opp == "-") {
            ans = (parseInt(nu1) - parseInt(nu2));
        }
        console.log("ans ==> "+ans);
        return ans;
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
<script src="app.js"></script>
</head>
<body>
<h3>Hello</h3>
<div ng-controller='calcCtrl' >
Number 1::<input Type="text" name="number1" ng-model="n1"/ required> <br/>
Number 2::<input Type="text" name="number2" ng-model="n2"/ required> <br/>
operator::<select ng-model="singleSelect">
        <option value="+">+</option>
        <option >*</option>
        <option>-</option>
        <option>/</option>
     </select></p> <br/>

<button ng-click="calculateNums(n1,n2)">Calculate Now</button>
</div>
  </body>
</html></code>```

So, The output I get is -

```<code>calcCtrl works!
opp ==> undefined
function works!
nu1 ==> 1
opp in calculateNums ==> undefined
ans ==> 0
</code>```

the operator values are undefined here..

答:
You can directly use scope variable in your controller it's good habits to use angular js variable.

I have updated your answer.

```<code><div ng-controller='calcCtrl' >
    Number 1::<input Type="text" name="number1" ng-model="n1"/ required> <br/>
    Number 2::<input Type="text" name="number2" ng-model="n2"/ required> <br/>
    operator::<select ng-model="singleSelect">
                  <option value="+">+</option>
                  <option value="*">*</option> <-- pass value
                  <option value="-">-</option> <-- pass value
                  <option value="/">/</option> <-- pass value
               </select><br/>

    <button ng-click="calculateNums()">Calculate Now</button> <-- remove n1 and n2
    Final answer <b>{{ans}}</b>
</div>
</code>```

And controller

```<code>var name="myApp";
requires=[];
app=angular.module(name,requires);

app.controller('calcCtrl',function($scope){
    console.log("calcCtrl works!");
    $scope.ans=0;
    $scope.calculateNums=function(){
        console.log("function works!");
        console.log($scope.n1); <-- use scope variable direct here
        console.log($scope.n2);  <-- use scope variable direct here
        console.log($scope.singleSelect);  <-- use scope variable direct here
        if($scope.singleSelect=="+"){
            $scope.ans= (parseInt($scope.n1) + parseInt($scope.n2));
        }else if ($scope.singleSelect=="-"){
            $scope.ans= (parseInt($scope.n1) - parseInt($scope.n2));
        }else if ($scope.singleSelect=="*"){
            $scope.ans= (parseInt($scope.n1) * parseInt($scope.n2));
        }else if ($scope.singleSelect=="/"){
            $scope.ans= (parseInt($scope.n1) / parseInt($scope.n2));
        }
        console.log($scope.ans);
     }
});
</code>```

Body:
I'm trying to create a simple calculator using Angularjs,in my code I can't get the operator value.How can I fix that?

Home html contains get the two numbers and the operator.User have to select the operator..

my Code -

var name = "myApp";
requires = [];
app = angular.module(name, requires);

app.controller('calcCtrl', function($scope) {
    //$scope.cdata={};

    console.log("calcCtrl works!");
    var opp;
    ans = 0;
    opp = $scope.singleSelect;

    console.log("opp ==> "+opp);

    $scope.calculateNums = function(nu1, nu2) {
        console.log("function works!");
        console.log("nu1 ==> "+nu1);
        console.log("opp in calculateNums ==> "+opp);
        if (opp == "+") {
            ans = (parseInt(nu1) + parseInt(nu2));
            console.log("ans ==> "+ans);
        } else if (opp == "-") {
            ans = (parseInt(nu1) - parseInt(nu2));
        }
        console.log("ans ==> "+ans);
        return ans;
    }
});

Hello

Number 1::<input Type="text" name="number1" ng-model="n1"/ required>

Number 2::<input Type="text" name="number2" ng-model="n2"/ required>

operator::<select ng-model="singleSelect">
        <option value="+">+</option>
        <option >*</option>
        <option>-</option>
        <option>/</option>
     </select>

<button ng-click="calculateNums(n1,n2)">Calculate Now</button>

So, The output I get is -

calcCtrl works!
opp ==> undefined
function works!
nu1 ==> 1
opp in calculateNums ==> undefined
ans ==> 0

the operator values are undefined here..

Body:
You can directly use scope variable in your controller it's good habits to use angular js variable.

I have updated your answer.

<div ng-controller='calcCtrl' >
    Number 1::<input Type="text" name="number1" ng-model="n1"/ required> <br/>
    Number 2::<input Type="text" name="number2" ng-model="n2"/ required> <br/>
    operator::<select ng-model="singleSelect">
                  <option value="+">+</option>
                  <option value="*">*</option> <-- pass value
                  <option value="-">-</option> <-- pass value
                  <option value="/">/</option> <-- pass value
               </select><br/>

    <button ng-click="calculateNums()">Calculate Now</button> <-- remove n1 and n2
    Final answer <b>{{ans}}</b>
</div>

And controller

var name="myApp";
requires=[];
app=angular.module(name,requires);

app.controller('calcCtrl',function($scope){
    console.log("calcCtrl works!");
    $scope.ans=0;
    $scope.calculateNums=function(){
        console.log("function works!");
        console.log($scope.n1); <-- use scope variable direct here
        console.log($scope.n2);  <-- use scope variable direct here
        console.log($scope.singleSelect);  <-- use scope variable direct here
        if($scope.singleSelect=="+"){
            $scope.ans= (parseInt($scope.n1) + parseInt($scope.n2));
        }else if ($scope.singleSelect=="-"){
            $scope.ans= (parseInt($scope.n1) - parseInt($scope.n2));
        }else if ($scope.singleSelect=="*"){
            $scope.ans= (parseInt($scope.n1) * parseInt($scope.n2));
        }else if ($scope.singleSelect=="/"){
            $scope.ans= (parseInt($scope.n1) / parseInt($scope.n2));
        }
        console.log($scope.ans);
     }
});


问:
iOS - CAKeyFrameAnimation - Not Playing
I have looked at a few guides for CAKeyFrameAnimation and I am failing to see how to trigger them. The only thing I can think of is that I have to use it as a return, but that doesn't make much sense to me.

-H File-

```<code>#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@interface ImageSequenceViewController : UIViewController
          <UIGestureRecognizerDelegate>{

 UISwipeGestureRecognizer *swipeLeftRecognizer;

 NSMutableArray *myImages;
 IBOutlet UIImageView *imageView;
 IBOutlet UIImageView *bView;
 IBOutlet UISegmentedControl *segmentedControl;
}

@property (nonatomic, retain) UISwipeGestureRecognizer *swipeLeftRecognizer;
@property (nonatomic, retain) UIImageView *imageView;
@property (nonatomic, retain) IBOutlet UISegmentedControl *segmentedControl;

-(IBAction)takeLeftSwipeRecognitionEnabledFrom:(UISegmentedControl *)aSegmentedControl;

-(IBAction)ButtonPressed1: (id)sender;

@end
</code>```

-M File-

```<code>#import "ImageSequenceViewController.h"

@implementation ImageSequenceViewController

@synthesize swipeLeftRecognizer;
@synthesize imageView;
@synthesize segmentedControl;

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

//CUSTOM CODE
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

-(void)loadLeft {
 //aView = [[UIImageView alloc] initWithFrame:self.view.frame];
 CALayer *layer = [CALayer layer];

 [layer setFrame:CGRectMake(0.0,
          0.0,
          [[self view] frame].size.height,
          [[self view] frame].size.width)];

 myImages = [[NSMutableArray alloc] init];

 for(NSUInteger count=0; count<100; count++){
  NSString *fileName;

  if (count < 10)
  {
   fileName = [NSString stringWithFormat:@"trailerRotation_000%d", count];
  }
  else if (10 <= count < 100)
  {
   fileName = [NSString stringWithFormat:@"trailerRotation_00%d", count];
  }
  else
  {
   fileName = [NSString stringWithFormat:@"trailerRotation_0%d", count];
  }

  NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"jpg"];

  //UIImage *image = [[UIImage alloc] initWithContentsOfFile:fileName];
  //[myImages addObject:image];

  [myImages addObject:[UIImage imageWithContentsOfFile:path]];
 }

 CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"Contents"];
 [anim setDuration:0.10];
 [anim setCalculationMode:kCAAnimationDiscrete];
 [anim setRepeatCount:1];
 [anim setValues:myImages];

 [self.view.layer addSublayer:layer];
 [layer addAnimation:anim forKey:@"images"];

 //aView.animationImages = myImages;
 //aView.animationDuration = 10.00;
 //aView.animationRepeatCount = 1;

}

-(void)loadRight {
 bView = [[UIImageView alloc] initWithFrame:self.view.frame];
 myImages = [[NSMutableArray alloc] init];

 for(NSUInteger count=99; count>0; count--){
  NSString *countString;

  if (count < 10)
  {
   countString = @"000";
   countString = [countString stringByAppendingFormat:@"%d", count];
  }
  else if (10 <= count < 100)
  {
   countString = @"00";
   countString = [countString stringByAppendingFormat:@"%d", count];
  }
  else if (100 <= count < 1000)
  {
   countString = @"00";
   countString = [countString stringByAppendingFormat:@"%d", count];
  }

  NSLog(@"%d", count);

  NSString *fileName = @"trailerRotation_";
  fileName = [fileName stringByAppendingFormat:countString];
  fileName = [fileName stringByAppendingFormat:@".jpg"];

  [myImages addObject:[UIImage imageNamed:fileName]];
 }

 bView.animationImages = myImages;
 bView.animationDuration = 10.00;
 bView.animationRepeatCount = 1;
}

- (void)viewDidLoad {
 [super viewDidLoad];

 imageView = [[UIImageView alloc] initWithFrame:self.view.frame];
 [imageView setImage:[UIImage imageNamed:@"trailerRotation_0000.jpg"]];
 //[self.view addSubview:imageView];

 [self loadLeft];
 [self loadRight];

 UIGestureRecognizer *recognizer;

 recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
 [self.view addGestureRecognizer:recognizer];
 [recognizer release];

 recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
 self.swipeLeftRecognizer = (UISwipeGestureRecognizer *) recognizer;
 swipeLeftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;

 if ([segmentedControl selectedSegmentIndex] == 0) {
  [self.view addGestureRecognizer:swipeLeftRecognizer];
 }

 self.swipeLeftRecognizer = (UISwipeGestureRecognizer *) recognizer;
 [recognizer release];
}

- (void)viewDidUnload {
 // Release any retained subviews of the main view.
 // e.g. self.myOutlet = nil;

 self.segmentedControl = nil;
 self.swipeLeftRecognizer = nil;
 self.imageView = nil;
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (void)viewDidAppear:(BOOL)animated {
    [self becomeFirstResponder];
}

-(void)startItLeft {
 NSLog(@"Left");

 //[aView startAnimating];
 //[self.view addSubview:aView];
 //[aView release];
 [bView release];
}

-(void)startItRight {
 NSLog(@"Right");

 [bView startAnimating];
 [self.view addSubview:bView];
 //[aView release];
 [bView release];
}

//- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
//}

//- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
//}

//- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {
//}

-(IBAction)ButtonPressed1:(id)sender
{
 NSLog(@"Button");

 //[aView stopAnimating];
 [bView stopAnimating];
 //[self loadLeft];
 [self loadRight];
}

-(IBAction)takeLeftSwipeRecognitionEnabledFrom:(UISegmentedControl *) aSegmentControl {

 if ([aSegmentControl selectedSegmentIndex] == 0) {
  [self.view addGestureRecognizer:swipeLeftRecognizer];
 }
 else {
  [self.view removeGestureRecognizer:swipeLeftRecognizer];
 }
}

-(void)handleSwipeFrom:(UISwipeGestureRecognizer *) recognizer {

 //CGPoint location = [recognizer locationInView:self.view];
 //[self showImageWithText:@"swipe" atPoint:location];

 if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
  //[self startItLeft];
 }
 else {
  [self startItRight];
 }
}
//CUSTOM CODE

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
 // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

 // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc {
    [super dealloc];
}

@end
</code>```

I'm rather new to iOS development so any advice is helpful.

Thanks.

答: It looks like you're trying to load up 100 images and cycle them all within the space of 0.1 second. Not only is that pretty ridiculous (that's 1000fps right there, and CoreAnimation is capped at 60fps), but it's likely to take longer than 0.1 seconds for CoreAnimation to copy all the images before it even starts, which means that it will have finished before it started (and therefore no animation will occur).</p>

Title: iOS - CAKeyFrameAnimation - Not Playing

Body:
I have looked at a few guides for CAKeyFrameAnimation and I am failing to see how to trigger them. The only thing I can think of is that I have to use it as a return, but that doesn't make much sense to me.

-H File-

#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>

@interface ImageSequenceViewController : UIViewController
          <UIGestureRecognizerDelegate>{

 UISwipeGestureRecognizer *swipeLeftRecognizer;

 NSMutableArray *myImages;
 IBOutlet UIImageView *imageView;
 IBOutlet UIImageView *bView;
 IBOutlet UISegmentedControl *segmentedControl;
}

@property (nonatomic, retain) UISwipeGestureRecognizer *swipeLeftRecognizer;
@property (nonatomic, retain) UIImageView *imageView;
@property (nonatomic, retain) IBOutlet UISegmentedControl *segmentedControl;

-(IBAction)takeLeftSwipeRecognitionEnabledFrom:(UISegmentedControl *)aSegmentedControl;

-(IBAction)ButtonPressed1: (id)sender;

@end

-M File-

#import "ImageSequenceViewController.h"

@implementation ImageSequenceViewController

@synthesize swipeLeftRecognizer;
@synthesize imageView;
@synthesize segmentedControl;

/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/

//CUSTOM CODE
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

-(void)loadLeft {
 //aView = [[UIImageView alloc] initWithFrame:self.view.frame];
 CALayer *layer = [CALayer layer];

 [layer setFrame:CGRectMake(0.0,
          0.0,
          [[self view] frame].size.height,
          [[self view] frame].size.width)];

 myImages = [[NSMutableArray alloc] init];

 for(NSUInteger count=0; count<100; count++){
  NSString *fileName;

  if (count < 10)
  {
   fileName = [NSString stringWithFormat:@"trailerRotation_000%d", count];
  }
  else if (10 <= count < 100)
  {
   fileName = [NSString stringWithFormat:@"trailerRotation_00%d", count];
  }
  else
  {
   fileName = [NSString stringWithFormat:@"trailerRotation_0%d", count];
  }

  NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"jpg"];

  //UIImage *image = [[UIImage alloc] initWithContentsOfFile:fileName];
  //[myImages addObject:image];

  [myImages addObject:[UIImage imageWithContentsOfFile:path]];
 }

 CAKeyframeAnimation *anim = [CAKeyframeAnimation animationWithKeyPath:@"Contents"];
 [anim setDuration:0.10];
 [anim setCalculationMode:kCAAnimationDiscrete];
 [anim setRepeatCount:1];
 [anim setValues:myImages];

 [self.view.layer addSublayer:layer];
 [layer addAnimation:anim forKey:@"images"];

 //aView.animationImages = myImages;
 //aView.animationDuration = 10.00;
 //aView.animationRepeatCount = 1;

}

-(void)loadRight {
 bView = [[UIImageView alloc] initWithFrame:self.view.frame];
 myImages = [[NSMutableArray alloc] init];

 for(NSUInteger count=99; count>0; count--){
  NSString *countString;

  if (count < 10)
  {
   countString = @"000";
   countString = [countString stringByAppendingFormat:@"%d", count];
  }
  else if (10 <= count < 100)
  {
   countString = @"00";
   countString = [countString stringByAppendingFormat:@"%d", count];
  }
  else if (100 <= count < 1000)
  {
   countString = @"00";
   countString = [countString stringByAppendingFormat:@"%d", count];
  }

  NSLog(@"%d", count);

  NSString *fileName = @"trailerRotation_";
  fileName = [fileName stringByAppendingFormat:countString];
  fileName = [fileName stringByAppendingFormat:@".jpg"];

  [myImages addObject:[UIImage imageNamed:fileName]];
 }

 bView.animationImages = myImages;
 bView.animationDuration = 10.00;
 bView.animationRepeatCount = 1;
}

- (void)viewDidLoad {
 [super viewDidLoad];

 imageView = [[UIImageView alloc] initWithFrame:self.view.frame];
 [imageView setImage:[UIImage imageNamed:@"trailerRotation_0000.jpg"]];
 //[self.view addSubview:imageView];

 [self loadLeft];
 [self loadRight];

 UIGestureRecognizer *recognizer;

 recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
 [self.view addGestureRecognizer:recognizer];
 [recognizer release];

 recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeFrom:)];
 self.swipeLeftRecognizer = (UISwipeGestureRecognizer *) recognizer;
 swipeLeftRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;

 if ([segmentedControl selectedSegmentIndex] == 0) {
  [self.view addGestureRecognizer:swipeLeftRecognizer];
 }

 self.swipeLeftRecognizer = (UISwipeGestureRecognizer *) recognizer;
 [recognizer release];
}

- (void)viewDidUnload {
 // Release any retained subviews of the main view.
 // e.g. self.myOutlet = nil;

 self.segmentedControl = nil;
 self.swipeLeftRecognizer = nil;
 self.imageView = nil;
}

- (BOOL)canBecomeFirstResponder {
    return YES;
}

- (void)viewDidAppear:(BOOL)animated {
    [self becomeFirstResponder];
}

-(void)startItLeft {
 NSLog(@"Left");

 //[aView startAnimating];
 //[self.view addSubview:aView];
 //[aView release];
 [bView release];
}

-(void)startItRight {
 NSLog(@"Right");

 [bView startAnimating];
 [self.view addSubview:bView];
 //[aView release];
 [bView release];
}

//- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
//}

//- (void)motionEnded:(UIEventSubtype)motion withEvent:(UIEvent *)event {
//}

//- (void)motionCancelled:(UIEventSubtype)motion withEvent:(UIEvent *)event {
//}

-(IBAction)ButtonPressed1:(id)sender
{
 NSLog(@"Button");

 //[aView stopAnimating];
 [bView stopAnimating];
 //[self loadLeft];
 [self loadRight];
}

-(IBAction)takeLeftSwipeRecognitionEnabledFrom:(UISegmentedControl *) aSegmentControl {

 if ([aSegmentControl selectedSegmentIndex] == 0) {
  [self.view addGestureRecognizer:swipeLeftRecognizer];
 }
 else {
  [self.view removeGestureRecognizer:swipeLeftRecognizer];
 }
}

-(void)handleSwipeFrom:(UISwipeGestureRecognizer *) recognizer {

 //CGPoint location = [recognizer locationInView:self.view];
 //[self showImageWithText:@"swipe" atPoint:location];

 if (recognizer.direction == UISwipeGestureRecognizerDirectionLeft) {
  //[self startItLeft];
 }
 else {
  [self startItRight];
 }
}
//CUSTOM CODE

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
 // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];

 // Release any cached data, images, etc that aren't in use.
}

- (void)dealloc {
    [super dealloc];
}

@end

I'm rather new to iOS development so any advice is helpful.

Thanks.