问:
Count and Stats api showing different doc's count in Elasticsearch?
1)I have an index "data" which has  479427 documents in it. To get the count i had used GET /data/_search  i got response like this

```<code>"hits": {
    "total": 479427,
    "max_score": 1,
</code>```

2)I checked using count api GET /data/_count and response i got is like this

```<code>{
  "count": 479427,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  }
}
</code>```

FROM 1 and 2 the count of articles is same .

But when i tried GET /data/_stats command i am getting different counts in get and total fields.

```<code>"data": {
  "primaries": {
    "docs": {
      "count": 2407154,
      "deleted": 357392
    },
    "indexing": {
      "index_total": 4926760,
      "index_time_in_millis": 31181542,
      "index_current": 2744,
      "index_failed": 260136,
      "delete_total": 0,
      "delete_time_in_millis": 0,
      "delete_current": 0,
      "noop_update_total": 175,
      "is_throttled": false,
      "throttle_time_in_millis": 0
    },
    "get": {
      "total": 4773829,
      "time_in_millis": 857412,
      "exists_total": 4773829,
      "exists_time_in_millis": 857412,
      "missing_total": 0,
      "missing_time_in_millis": 0,
      "current": 0
    },
    "merges": {
      "current": 0,
      "current_docs": 0,
      "current_size_in_bytes": 0,
      "total": 82217,
      "total_time_in_millis": 19552894,
      "total_docs": 87321796,
      "total_size_in_bytes": 281542406990,
      "total_stopped_time_in_millis": 0,
      "total_throttled_time_in_millis": 488983,
      "total_auto_throttle_in_bytes": 35543080
    },
    "refresh": {
      "total": 956338,
      "total_time_in_millis": 29144660
    },
    "flush": {
      "total": 697,
      "total_time_in_millis": 469603
    },
    "segments": {
      "count": 114,
      "memory_in_bytes": 7145544,
      "terms_memory_in_bytes": 4862940,
      "stored_fields_memory_in_bytes": 1037064,
      "term_vectors_memory_in_bytes": 0,
      "norms_memory_in_bytes": 116928,
      "doc_values_memory_in_bytes": 1128612,
      "index_writer_memory_in_bytes": 13753207,
      "index_writer_max_memory_in_bytes": 548831232,
      "version_map_memory_in_bytes": 2182,
      "fixed_bit_set_memory_in_bytes": 350648
    },
    "translog": {
      "operations": 19488,
      "size_in_bytes": 799972235
    },
    "suggest": {
      "total": 0,
      "time_in_millis": 0,
      "current": 0
    },
    "request_cache": {
      "memory_size_in_bytes": 0,
      "evictions": 0,
      "hit_count": 0,
      "miss_count": 0
    },
    "recovery": {
      "current_as_source": 0,
      "current_as_target": 0,
      "throttle_time_in_millis": 13306
    }
  },
  **"total": {
    "docs": {                >Here i am getting total docs count 4814308
      "count": 4814308,
      "deleted": 715540
    },**
    "store": {
      "size_in_bytes": 11910376476,
      "throttle_time_in_millis": 0
    },
    "indexing": {
      "index_total": 9590499,
      "index_time_in_millis": 61324893,
      "index_current": 2744,
      "index_failed": 310323,
      "delete_total": 0,
      "delete_time_in_millis": 0,
      "delete_current": 0,
      "noop_update_total": 175,
      "is_throttled": false,
      "throttle_time_in_millis": 0
    },
    "get": {
      "total": 4773829,
      "time_in_millis": 857412,
      "exists_total": 4773829,
      "exists_time_in_millis": 857412,
      "missing_total": 0,
      "missing_time_in_millis": 0,
      "current": 0
    },
    "search": {
      "open_contexts": 0,
      "query_total": 21901088,
      "query_time_in_millis": 11241895,
      "query_current": 0,
      "fetch_total": 4578094,
      "fetch_time_in_millis": 1774794,
      "fetch_current": 0,
      "scroll_total": 0,
      "scroll_time_in_millis": 0,
      "scroll_current": 0
    },
    "merges": {
      "current": 0,
      "current_docs": 0,
      "current_size_in_bytes": 0,
      "total": 153172,
      "total_time_in_millis": 37586865,
      "total_docs": 170014671,
      "total_size_in_bytes": 542992816504,
      "total_stopped_time_in_millis": 0,
      "total_throttled_time_in_millis": 920242,
      "total_auto_throttle_in_bytes": 71693630
    },
    "refresh": {
      "total": 1841635,
      "total_time_in_millis": 56292736
    },
    "flush": {
      "total": 1343,
      "total_time_in_millis": 946306
    },
    "warmer": {
      "current": 0,
      "total": 3822250,
      "total_time_in_millis": 1098530
    },
    "query_cache": {
      "memory_size_in_bytes": 2706088,
      "total_count": 20222398,
      "hit_count": 4846746,
      "miss_count": 15375652,
      "cache_size": 271,
      "cache_count": 2267,
      "evictions": 1996
    },
    "fielddata": {
      "memory_size_in_bytes": 0,
      "evictions": 0
    },
    "percolate": {
      "total": 0,
      "time_in_millis": 0,
      "current": 0,
      "memory_size_in_bytes": -1,
      "memory_size": "-1b",
      "queries": 0
    },
    "completion": {
      "size_in_bytes": 0
    },
    "segments": {
      "count": 229,
      "memory_in_bytes": 14245875,
      "terms_memory_in_bytes": 9804839,
      "stored_fields_memory_in_bytes": 2068360,
      "term_vectors_memory_in_bytes": 0,
      "norms_memory_in_bytes": 234752,
      "doc_values_memory_in_bytes": 2137924,
      "index_writer_memory_in_bytes": 25849179,
      "index_writer_max_memory_in_bytes": 1097662464,
      "version_map_memory_in_bytes": 4364,
      "fixed_bit_set_memory_in_bytes": 701360
    },
    "translog": {
      "operations": 39262,
      "size_in_bytes": 1616348491
    },
    "suggest": {
      "total": 0,
      "time_in_millis": 0,
      "current": 0
    },
    "request_cache": {
      "memory_size_in_bytes": 0,
      "evictions": 0,
      "hit_count": 0,
      "miss_count": 0
    },
    "recovery": {
      "current_as_source": 0,
      "current_as_target": 0,
      "throttle_time_in_millis": 32764
    }
  }
}
</code>```

I even checked the same in curator by giving curator_cli show_indices --verbose which given response like this:

data      open   11.1GB   4814308   5   1 2017-05-31T13:00:37Z

Why there is difference ?

Update ----------------------

1)You mean stats API considers each field in nested as a document right?
Note:BTW I am talking about the total.docs.count field in stats api.
2)Where as count API will give the count of documents that are present in the index based on unique id.

So My question is if i want to know how many documents are present inside the index which api gives the right count whether count,get,stats  or curator_cli show_indices --verbose(using curator) ?

Thanks

答: the stats API includes so called nested documents, as fields, which are marked as nested in the mapping are counted as own lucene documents, where as the count API is just counting the top level objects.

Body:
1)I have an index "data" which has  479427 documents in it. To get the count i had used GET /data/_search  i got response like this

"hits": {
    "total": 479427,
    "max_score": 1,

2)I checked using count api GET /data/_count and response i got is like this

{
  "count": 479427,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  }
}

FROM 1 and 2 the count of articles is same .

But when i tried GET /data/_stats command i am getting different counts in get and total fields.

"data": {
  "primaries": {
    "docs": {
      "count": 2407154,
      "deleted": 357392
    },
    "indexing": {
      "index_total": 4926760,
      "index_time_in_millis": 31181542,
      "index_current": 2744,
      "index_failed": 260136,
      "delete_total": 0,
      "delete_time_in_millis": 0,
      "delete_current": 0,
      "noop_update_total": 175,
      "is_throttled": false,
      "throttle_time_in_millis": 0
    },
    "get": {
      "total": 4773829,
      "time_in_millis": 857412,
      "exists_total": 4773829,
      "exists_time_in_millis": 857412,
      "missing_total": 0,
      "missing_time_in_millis": 0,
      "current": 0
    },
    "merges": {
      "current": 0,
      "current_docs": 0,
      "current_size_in_bytes": 0,
      "total": 82217,
      "total_time_in_millis": 19552894,
      "total_docs": 87321796,
      "total_size_in_bytes": 281542406990,
      "total_stopped_time_in_millis": 0,
      "total_throttled_time_in_millis": 488983,
      "total_auto_throttle_in_bytes": 35543080
    },
    "refresh": {
      "total": 956338,
      "total_time_in_millis": 29144660
    },
    "flush": {
      "total": 697,
      "total_time_in_millis": 469603
    },
    "segments": {
      "count": 114,
      "memory_in_bytes": 7145544,
      "terms_memory_in_bytes": 4862940,
      "stored_fields_memory_in_bytes": 1037064,
      "term_vectors_memory_in_bytes": 0,
      "norms_memory_in_bytes": 116928,
      "doc_values_memory_in_bytes": 1128612,
      "index_writer_memory_in_bytes": 13753207,
      "index_writer_max_memory_in_bytes": 548831232,
      "version_map_memory_in_bytes": 2182,
      "fixed_bit_set_memory_in_bytes": 350648
    },
    "translog": {
      "operations": 19488,
      "size_in_bytes": 799972235
    },
    "suggest": {
      "total": 0,
      "time_in_millis": 0,
      "current": 0
    },
    "request_cache": {
      "memory_size_in_bytes": 0,
      "evictions": 0,
      "hit_count": 0,
      "miss_count": 0
    },
    "recovery": {
      "current_as_source": 0,
      "current_as_target": 0,
      "throttle_time_in_millis": 13306
    }
  },
  **"total": {
    "docs": {                >Here i am getting total docs count 4814308
      "count": 4814308,
      "deleted": 715540
    },**
    "store": {
      "size_in_bytes": 11910376476,
      "throttle_time_in_millis": 0
    },
    "indexing": {
      "index_total": 9590499,
      "index_time_in_millis": 61324893,
      "index_current": 2744,
      "index_failed": 310323,
      "delete_total": 0,
      "delete_time_in_millis": 0,
      "delete_current": 0,
      "noop_update_total": 175,
      "is_throttled": false,
      "throttle_time_in_millis": 0
    },
    "get": {
      "total": 4773829,
      "time_in_millis": 857412,
      "exists_total": 4773829,
      "exists_time_in_millis": 857412,
      "missing_total": 0,
      "missing_time_in_millis": 0,
      "current": 0
    },
    "search": {
      "open_contexts": 0,
      "query_total": 21901088,
      "query_time_in_millis": 11241895,
      "query_current": 0,
      "fetch_total": 4578094,
      "fetch_time_in_millis": 1774794,
      "fetch_current": 0,
      "scroll_total": 0,
      "scroll_time_in_millis": 0,
      "scroll_current": 0
    },
    "merges": {
      "current": 0,
      "current_docs": 0,
      "current_size_in_bytes": 0,
      "total": 153172,
      "total_time_in_millis": 37586865,
      "total_docs": 170014671,
      "total_size_in_bytes": 542992816504,
      "total_stopped_time_in_millis": 0,
      "total_throttled_time_in_millis": 920242,
      "total_auto_throttle_in_bytes": 71693630
    },
    "refresh": {
      "total": 1841635,
      "total_time_in_millis": 56292736
    },
    "flush": {
      "total": 1343,
      "total_time_in_millis": 946306
    },
    "warmer": {
      "current": 0,
      "total": 3822250,
      "total_time_in_millis": 1098530
    },
    "query_cache": {
      "memory_size_in_bytes": 2706088,
      "total_count": 20222398,
      "hit_count": 4846746,
      "miss_count": 15375652,
      "cache_size": 271,
      "cache_count": 2267,
      "evictions": 1996
    },
    "fielddata": {
      "memory_size_in_bytes": 0,
      "evictions": 0
    },
    "percolate": {
      "total": 0,
      "time_in_millis": 0,
      "current": 0,
      "memory_size_in_bytes": -1,
      "memory_size": "-1b",
      "queries": 0
    },
    "completion": {
      "size_in_bytes": 0
    },
    "segments": {
      "count": 229,
      "memory_in_bytes": 14245875,
      "terms_memory_in_bytes": 9804839,
      "stored_fields_memory_in_bytes": 2068360,
      "term_vectors_memory_in_bytes": 0,
      "norms_memory_in_bytes": 234752,
      "doc_values_memory_in_bytes": 2137924,
      "index_writer_memory_in_bytes": 25849179,
      "index_writer_max_memory_in_bytes": 1097662464,
      "version_map_memory_in_bytes": 4364,
      "fixed_bit_set_memory_in_bytes": 701360
    },
    "translog": {
      "operations": 39262,
      "size_in_bytes": 1616348491
    },
    "suggest": {
      "total": 0,
      "time_in_millis": 0,
      "current": 0
    },
    "request_cache": {
      "memory_size_in_bytes": 0,
      "evictions": 0,
      "hit_count": 0,
      "miss_count": 0
    },
    "recovery": {
      "current_as_source": 0,
      "current_as_target": 0,
      "throttle_time_in_millis": 32764
    }
  }
}

I even checked the same in curator by giving curator_cli show_indices --verbose which given response like this:

data      open   11.1GB   4814308   5   1 2017-05-31T13:00:37Z

Why there is difference ?

Update ----------------------

1)You mean stats API considers each field in nested as a document right?
Note:BTW I am talking about the total.docs.count field in stats api.
2)Where as count API will give the count of documents that are present in the index based on unique id.

So My question is if i want to know how many documents are present inside the index which api gives the right count whether count,get,stats  or curator_cli show_indices --verbose(using curator) ?

Thanks


来源: stackexchange

问:
Replacing DIV content based on variable sent from another HTML file
I'm trying to get this JavaScript working:

I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.

```<code><!-- ORIGINAL DIV -->
<div id="Email">

</div>

<!-- DIV replacement function -->

<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>

<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';

ReplaceContentInContainer('Email1',content);
}
</script>

<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';

ReplaceContentInContainer('Email2',content);
}
</script>
</code>```

Any ideas what I've done wrong that is causing it not to work?

答:
I noticed you are putting a closing "}" after you call "ReplaceContentInContainer". I don't know if that is your complete problem but it would definitely cause the javascript not to parse correctly. Remove the closing "}". </p>

<p>With the closing "}", you are closing a block of code you never opened. </p>

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to get this JavaScript working:

I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.

Any ideas what I've done wrong that is causing it not to work?

Body:
I noticed you are putting a closing "}" after you call "ReplaceContentInContainer". I don't know if that is your complete problem but it would definitely cause the javascript not to parse correctly. Remove the closing "}".

With the closing "}", you are closing a block of code you never opened.


问:
slack API users.identity not working
I am trying to get my python slack bot to work. I want to get the info of the user who is trying to make API calls using users.identity API. However, I was unable to make it to work.

Any tips and idea why?

This is the error I get.

Thanks in advance.

答: It won't work on https://api.slack.com/methods/users.identity/test. But if you create an "app/script" where you can authenticate and then request with https://slack.com/api/users.identity?token=xxx you will get a valid response for the logged in person. With User Name,User id and Team id</p>

ContentLicense: CC BY-SA 3.0

Title: slack API users.identity not working


问:
Launch ClojureScript + ghost script from terminal
I installed phantomjs and casperjs, created a new project with lein new mies casper-ghost and added the [ghost "0.1.0-alpha1] dependency to project.clj.

I then copied over the example code from https://github.com/casperjs/ghost to the core.cljs file and successfully compiled it, with ./scripts/build.

When I try to run it with casperjs out/casper_ghost.js it gives me the error:

```<code>ClojureScript could not load :main, did you forget to specify :asset-path?
ReferenceError: Can't find variable: goog

  file:///usr/lib/node_modules/casperjs/bin/bootstrap.js:1 in global code
</code>```

I tried creating a custom build script as follows:

```<code>(require 'cljs.build.api)

(cljs.build.api/build "src"
                      {:main 'hello-world.core
                       :output-to "out/main.js"})
</code>```

And ran that successfully with lein -m clojure.main build.clj, but running out/main.js with casperjs would cause the same error.

Can someone point me in the right direction how to run the ghost scripts from the linux terminal?

答: Making the Google closure compiler write everything into a single file by using :optimizations "simple" to the build options did the trick.

Body:
I installed phantomjs and casperjs, created a new project with lein new mies casper-ghost and added the [ghost "0.1.0-alpha1] dependency to project.clj.

I then copied over the example code from https://github.com/casperjs/ghost to the core.cljs file and successfully compiled it, with ./scripts/build.

When I try to run it with casperjs out/casper_ghost.js it gives me the error:

ClojureScript could not load :main, did you forget to specify :asset-path?
ReferenceError: Can't find variable: goog

  file:///usr/lib/node_modules/casperjs/bin/bootstrap.js:1 in global code

I tried creating a custom build script as follows:

(require 'cljs.build.api)

(cljs.build.api/build "src"
                      {:main 'hello-world.core
                       :output-to "out/main.js"})

And ran that successfully with lein -m clojure.main build.clj, but running out/main.js with casperjs would cause the same error.

Can someone point me in the right direction how to run the ghost scripts from the linux terminal?


问:
How do you add a custom component in admin-on-rest that doesn't require login
How would I able to add a custom page(component) to admin-on-rest that is public? Note, I would like to use the admin component so the layout is there.</p>

答:
If your application was named myApp, the easiest way in my opinion is to have two folders in your react project's source directory:

```<code> 1. /myApp/src/public
 2. /myApp/src/private
</code>```

In (1) you would have your public components, with their own router and routes mapped to paths that render components stored in your src/public subfolder, as you would normally do with a standard react + react-router application.

In (2) you would have the admin-on-rest file structure.

There are other ways, such as injecting custom routes to the Admin component and customizing your own authClient to ignore certain routes, but I found the above method simple and clean, and it also helps keeping stuff organized.

You can find more help here:

Custom Routes

Authentication Documentation

I hope this helps.

Body:
If your application was named myApp, the easiest way in my opinion is to have two folders in your react project's source directory:

 1. /myApp/src/public
 2. /myApp/src/private

In (1) you would have your public components, with their own router and routes mapped to paths that render components stored in your src/public subfolder, as you would normally do with a standard react + react-router application.

In (2) you would have the admin-on-rest file structure.

There are other ways, such as injecting custom routes to the Admin component and customizing your own authClient to ignore certain routes, but I found the above method simple and clean, and it also helps keeping stuff organized.

You can find more help here:

Custom Routes

Authentication Documentation

I hope this helps.


问:
How to change focus different Jbuttons when a keyboard key is pressed?
So hey guys, I've been trying to design a piano through java, net-beans for my final project at uni. thing here is every thing works well so far but I've got issues with focus here. for example I'm trying to play the keys through the keyboard, i want the piano keys to get focused to the specified key its assigned any idea on how to do it? much appreciated. this is my 1st question here, so I'm not sure if I'm asking the right things here.

I'm gonna provide the sample I'm working with.

```<code>   package javaapplication5;

   import sun.audio.*;

   import java.io.*;

   import javax.swing.JOptionPane;

   public class NewJFrame1 extends javax.swing.JFrame {

public NewJFrame1() {

    initComponents();

}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton1.setText("A");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });
    jButton1.addFocusListener(new java.awt.event.FocusAdapter() {
        public void focusGained(java.awt.event.FocusEvent evt) {
            jButton1FocusGained(evt);
        }
    });
    jButton1.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            jButton1KeyPressed(evt);
        }
        public void keyReleased(java.awt.event.KeyEvent evt) {
            jButton1KeyReleased(evt);
        }
    });

    jButton2.setText("B");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });
    jButton2.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            jButton2KeyPressed(evt);
        }
    });

    jButton3.setText("C");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });
    jButton3.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            jButton3KeyPressed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(89, 89, 89)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(123, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
            .addContainerGap(91, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(110, 110, 110))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(45, 45, 45)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(190, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(51, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\A.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\B.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
   InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\C.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {

    if(evt.getKeyChar()=='z'){
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\A.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
   }

}

private void jButton2KeyPressed(java.awt.event.KeyEvent evt) {

    if(evt.getKeyChar()=='x'){
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\B.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
   }
}

private void jButton3KeyPressed(java.awt.event.KeyEvent evt) {

    if(evt.getKeyChar()=='c'){
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\C.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
   }
}

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new NewJFrame1().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JPanel jPanel1;
// End of variables declaration
</code>```

}

As this is a sample I'm working with just 3 buttons here. I'd like to get all the help i can thanks in advance

答: Register keylister with jframe using addKeyListener(...) for all three keys.  so when any keypressed within frame, key event works. Before key press,  check your frame is active.  if not click within frame then press key. Can also change focus on button using requestFocus() method</p>

Body:
So hey guys, I've been trying to design a piano through java, net-beans for my final project at uni. thing here is every thing works well so far but I've got issues with focus here. for example I'm trying to play the keys through the keyboard, i want the piano keys to get focused to the specified key its assigned any idea on how to do it? much appreciated. this is my 1st question here, so I'm not sure if I'm asking the right things here.

I'm gonna provide the sample I'm working with.

   package javaapplication5;

   import sun.audio.*;

   import java.io.*;

   import javax.swing.JOptionPane;

   public class NewJFrame1 extends javax.swing.JFrame {

public NewJFrame1() {

    initComponents();

}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jButton1 = new javax.swing.JButton();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jButton1.setText("A");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });
    jButton1.addFocusListener(new java.awt.event.FocusAdapter() {
        public void focusGained(java.awt.event.FocusEvent evt) {
            jButton1FocusGained(evt);
        }
    });
    jButton1.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            jButton1KeyPressed(evt);
        }
        public void keyReleased(java.awt.event.KeyEvent evt) {
            jButton1KeyReleased(evt);
        }
    });

    jButton2.setText("B");
    jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
        }
    });
    jButton2.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            jButton2KeyPressed(evt);
        }
    });

    jButton3.setText("C");
    jButton3.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton3ActionPerformed(evt);
        }
    });
    jButton3.addKeyListener(new java.awt.event.KeyAdapter() {
        public void keyPressed(java.awt.event.KeyEvent evt) {
            jButton3KeyPressed(evt);
        }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addGap(89, 89, 89)
            .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(123, Short.MAX_VALUE))
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
            .addContainerGap(91, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(110, 110, 110))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(45, 45, 45)
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(190, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addContainerGap(51, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\A.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\B.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
   InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\C.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
}

private void jButton1KeyPressed(java.awt.event.KeyEvent evt) {

    if(evt.getKeyChar()=='z'){
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\A.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
   }

}

private void jButton2KeyPressed(java.awt.event.KeyEvent evt) {

    if(evt.getKeyChar()=='x'){
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\B.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
   }
}

private void jButton3KeyPressed(java.awt.event.KeyEvent evt) {

    if(evt.getKeyChar()=='c'){
    InputStream iAudio;

    try{
        iAudio = new FileInputStream(new File("C:\\Users\\MohammedRishad\\Desktop\\Audios\\C.wav"));
        AudioStream iMusic = new AudioStream(iAudio);
        AudioPlayer.player.start(iMusic);
    }
    catch(Exception e){
        JOptionPane.showMessageDialog(null, e);
    }
   }
}

public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {

        public void run() {
            new NewJFrame1().setVisible(true);
        }
    });
}
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JPanel jPanel1;
// End of variables declaration

}

As this is a sample I'm working with just 3 buttons here. I'd like to get all the help i can thanks in advance


问:
1-million-row ListView
I have a SysListView32 that should potentially host millions of rows, and three columns of text A, B, C each < 256 characters.

Let's say column B has many many repetitions (example: column A is filename, column B is path, and each row is a file of the filesystem), and has only 100k different values (instead of several millions).

Is it possible to avoid duplication in RAM of content of column B of the ListView GUI element?

Can we fill a ListView with only pointers to arrays elements (taken from the 100k-element-array of different values of column B), instead of duplicated data?

How to modify this to make it work?

```<code>LV_ITEM item;
item.mask = LVIF_TEXT;
item.pszText = "Hello";
...
ListView_SetItem(hList, &item);
</code>```

答:
What you need is also referred as "Virtual List". A virtual list control is a list view control that has the LVS_OWNERDATA style. This style enables the control to support an item count up to a DWORD (the default item count only extends to an int). However, the biggest advantage provided by this style is the ability to only have a subset of data items in memory at any one time. This allows the virtual list view control to lend itself for use with large databases of information, where specific methods of accessing data are already in place. For a given set of data (list or dynamic array), you need to follow these steps:

Add LVS_OWNERDATA style to your ListView

Make a call to CListCtrl::SetItemCount passing the data source size, like std::vector::size().

Catch the LVN_GETDISPINFO notification. This is where the data is rendered into the ListCtrl.

Please have a look at the attached links I added, for more information and sample code. If you use CListView you can have access to the CListCtrl with GetListCtrl.

Links:

Virtual List Controls

Using virtual lists

Title: 1-million-row ListView

Body:
I have a SysListView32 that should potentially host millions of rows, and three columns of text A, B, C each < 256 characters.

Let's say column B has many many repetitions (example: column A is filename, column B is path, and each row is a file of the filesystem), and has only 100k different values (instead of several millions).

Is it possible to avoid duplication in RAM of content of column B of the ListView GUI element?

Can we fill a ListView with only pointers to arrays elements (taken from the 100k-element-array of different values of column B), instead of duplicated data?

How to modify this to make it work?

LV_ITEM item;
item.mask = LVIF_TEXT;
item.pszText = "Hello";
...
ListView_SetItem(hList, &item);


问:
How to stop Sublime Text 2 crashing on startup
I've got a problem with Sublime Text 2 in that when I start it it automatically tries to load a file that leads it to crash.

I can see that there are ways of changing the settings once it's loaded - how do I fix it when it won't finish start-up?

I'm running on Mac OSX (Mavericks).

答:
Delete Session.sublime_session from ~/Library/Application Support/Sublime Text 3/Local.

rm ~/Library/Application\ Support/Sublime\ Text\ 3/Local/Session.sublime_session

Also:
Please don't delete all content in the ~/Library/Application Support/Sublime Text 3/Local folder as this will also delete your Licence. @kushdilip (Tried to add this as a comment to your post but didn't have enough reputation to do so.)


问:
I cannot save data from angular to backend laravel database
I am passing form input from angular to laravel view api. But data cannot be saved in the database. I am getting the following error messages in the console:

```<code>error: [ngRepeat:dupes] http://errors.angularjs.org/1.5.0/ngRepeat/dupes?p0=app%20in%20apps&p1=string%3A%3C&p2=%3C
    at Error (native)
    at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:6:416
    at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:292:254
    at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:137:302
    at m.$digest (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:138:399)
    at m.$apply (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:141:341)
    at g (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:94:139)
    at t (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:98:260)
    at XMLHttpRequest.u.onload (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:99:297)(anonymous function) @ angular.js:13236
apps.js:28 0
http://localhost/myapp/public/api/apps Failed to load resource: the server responded with a status of 500 (Internal Server Error)
I also get laravel errors:
                            <span class="exception_title"><abbr title="Illuminate\Database\QueryException">QueryException</abbr> in <a title="C:\xampp\htdocs\dukamart\vendor\laravel\framework\src\Illuminate\Database\Connection.php line 651" ondblclick="var f=this.innerHTML;this.innerHTML=this.title;this.title=f;">Connection.php line 651</a>:</span>
span class="exception_message">SQLSTATE[23000]: Integrity constraint violation: 1048 Column associated with input values.
</code>```

I have checked my laravel controller seem to be fine. I am posting data from a popup form.

employeeController.php

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Employee;

class Employees extends Controller
{
    //
     public function index($id = null) {
        if ($id == null) {
            return Employee::orderBy('id', 'asc')->get();
        } else {
            return $this->show($id);
        }
    }

    public function store(Request $request) {
        $employee = new Employee;

        $employee->name = $request->input('name');
        $employee->email = $request->input('email');
        $employee->contact_number = $request->input('contact_number');
        $employee->position = $request->input('position');
        $employee->save();

        return 'Employee record successfully created with id ' . $employee->id;
    }
</code>```

//My angular controller

```<code>app.controller('employeesController', function($scope, $http, API_URL) {
    //retrieve employees listing from API
    $http.get(API_URL + "employees")
            .success(function(response) {
                $scope.employees = response;
            });

    //show modal form
    $scope.toggle = function(modalstate, id) {
        $scope.modalstate = modalstate;

        switch (modalstate) {
            case 'add':
                $scope.form_title = "Add New Employee";
                break;
            case 'edit':
                $scope.form_title = "Employee Detail";
                $scope.id = id;
                $http.get(API_URL + 'employees/' + id)
                        .success(function(response) {
                            console.log(response);
                            $scope.employee = response;
                        });
                break;
            default:
                break;
        }
        console.log(id);
        $('#myModal').modal('show');
    }

    //save new record / update existing record
    $scope.save = function(modalstate, id) {
        var url = API_URL + "employees";

        //append Employee id to the URL if the form is in edit mode
        if (modalstate === 'edit'){
            url += "/" + id;
        }

        $http({
            method: 'POST',
            url: url,
            data: $.param($scope.employee),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).success(function(response) {
            console.log(response);
            location.reload();
        }).error(function(response) {
            console.log(response);
            alert('This is embarassing. An error has occured. Please check the log for details');
        });
    }

    //delete record
    $scope.confirmDelete = function(id) {
        var isConfirmDelete = confirm('Are you sure you want this record?');
        if (isConfirmDelete) {
            $http({
                method: 'DELETE',
                url: API_URL + 'employees/' + id
            }).
                    success(function(data) {
                        console.log(data);
                        location.reload();
                    }).
                    error(function(data) {
                        console.log(data);
                        alert('Unable to delete');
                    });
        } else {
            return false;
        }
    }
});
</code>```

When I click to save the data, I am getting an error message I had setup in employeeController.js controller

```<code>$http({
            method: 'POST',
            url: url,
            data: $.param($scope.hotel),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).success(function(response) {
            console.log(response);
            location.reload();
        }).error(function(response) {
            console.log(response);
            alert('This is embarassing. An error has occured. Please check the log for details');
        });
    }
</code>```

This my app.js

```<code>var app = angular.module(employees, [])
        .constant('API_URL', 'http://localhost/myapp/public/api/');
</code>```

My routes.php

```<code>Route::get('/api/v1/employees/{id?}', 'Employees@index');
Route::post('/api/v1/employees', 'Employees@store');
Route::post('/api/v1/employees/{id}', 'Employees@update');
Route::post('/api/v1/employees/update/{id}',['as'=>'update','uses'=> 'Employees@update']);
Route::delete('/api/v1/employees/{id}', 'Employees@destroy');
</code>```

What could be the cause of this? Please help. I have tried to solve this for 3 days without success.

My View in resources/views/employees/employee.php

```<code><!DOCTYPE html>
<html lang="en-US" ng-app="employeeRecords">
    <head>
        <title>Laravel 5 AngularJS CRUD Example</title>

        <!-- Load Bootstrap CSS -->
        <link href="<?= asset('css/bootstrap.min.css') ?>" rel="stylesheet">
    </head>
    <body>
        <h2>Employees Database</h2>
        <div  ng-controller="employeesController">

            <!-- Table-to-load-the-data Part -->
            <table class="table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Contact No</th>
                        <th>Position</th>
                        <th><button id="btn-add" class="btn btn-primary btn-xs" ng-click="toggle('add', 0)">Add New Employee</button></th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="employee in employees">
                        <td>{{  employee.id }}</td>
                        <td>{{ employee.name }}</td>
                        <td>{{ employee.email }}</td>
                        <td>{{ employee.contact_number }}</td>
                        <td>{{ employee.position }}</td>
                        <td>
                            <button class="btn btn-default btn-xs btn-detail" ng-click="toggle('edit', employee.id)">Edit</button>
                            <button class="btn btn-danger btn-xs btn-delete" ng-click="confirmDelete(employee.id)">Delete</button>
                        </td>
                    </tr>
                </tbody>
            </table>
            <!-- End of Table-to-load-the-data Part -->
            <!-- Modal (Pop up when detail button clicked) -->
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                            <h4 class="modal-title" id="myModalLabel">{{form_title}}</h4>
                        </div>
                        <div class="modal-body">
                            <form name="frmEmployees" class="form-horizontal" novalidate="">

                                <div class="form-group error">
                                    <label for="inputEmail3" class="col-sm-3 control-label">Name</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control has-error" id="name" name="name" placeholder="Fullname" value="{{name}}"
                                        ng-model="employee.name" ng-required="true">
                                        <span class="help-inline"
                                        ng-show="frmEmployees.name.$invalid && frmEmployees.name.$touched">Name field is required</span>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="inputEmail3" class="col-sm-3 control-label">Email</label>
                                    <div class="col-sm-9">
                                        <input type="email" class="form-control" id="email" name="email" placeholder="Email Address" value="{{email}}"
                                        ng-model="employee.email" ng-required="true">
                                        <span class="help-inline"
                                        ng-show="frmEmployees.email.$invalid && frmEmployees.email.$touched">Valid Email field is required</span>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="inputEmail3" class="col-sm-3 control-label">Contact Number</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control" id="contact_number" name="contact_number" placeholder="Contact Number" value="{{contact_number}}"
                                        ng-model="employee.contact_number" ng-required="true">
                                    <span class="help-inline"
                                        ng-show="frmEmployees.contact_number.$invalid && frmEmployees.contact_number.$touched">Contact number field is required</span>
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="inputEmail3" class="col-sm-3 control-label">Position</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control" id="position" name="position" placeholder="Position" value="{{position}}"
                                        ng-model="employee.position" ng-required="true">
                                    <span class="help-inline"
                                        ng-show="frmEmployees.position.$invalid && frmEmployees.position.$touched">Position field is required</span>
                                    </div>
                                </div>

                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary" id="btn-save" ng-click="save(modalstate, id)" ng-disabled="frmEmployees.$invalid">Save changes</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Load Javascript Libraries (AngularJS, JQuery, Bootstrap) -->
        <script src="<?= asset('app/lib/angular/angular.min.js') ?>"></script>
        <script src="<?= asset('js/jquery.min.js') ?>"></script>
        <script src="<?= asset('js/bootstrap.min.js') ?>"></script>

        <!-- AngularJS Application Scripts -->
        <script src="<?= asset('app/app.js') ?>"></script>
        <script src="<?= asset('app/controllers/employees.js') ?>"></script>
    </body>
</html>
</code>```

答:
sound like your key is being duplicate in ng-repeat. Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: app in apps, Duplicate key: string:<, Duplicate value: <

this issue happens once

Invalid:
ng-repeat="value in [4, 4]"

valid
ng-repeat="value in [4, 4] track by $index"

Body:
I am passing form input from angular to laravel view api. But data cannot be saved in the database. I am getting the following error messages in the console:

error: [ngRepeat:dupes] http://errors.angularjs.org/1.5.0/ngRepeat/dupes?p0=app%20in%20apps&p1=string%3A%3C&p2=%3C
    at Error (native)
    at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:6:416
    at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:292:254
    at http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:137:302
    at m.$digest (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:138:399)
    at m.$apply (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:141:341)
    at g (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:94:139)
    at t (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:98:260)
    at XMLHttpRequest.u.onload (http://localhost/myapp/public/app/lib/angular-1.5.0/angular.min.js:99:297)(anonymous function) @ angular.js:13236
apps.js:28 0
http://localhost/myapp/public/api/apps Failed to load resource: the server responded with a status of 500 (Internal Server Error)
I also get laravel errors:
                            QueryException in Connection.php line 651:
span class="exception_message">SQLSTATE[23000]: Integrity constraint violation: 1048 Column associated with input values.

I have checked my laravel controller seem to be fine. I am posting data from a popup form.

employeeController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Employee;

class Employees extends Controller
{
    //
     public function index($id = null) {
        if ($id == null) {
            return Employee::orderBy('id', 'asc')->get();
        } else {
            return $this->show($id);
        }
    }

    public function store(Request $request) {
        $employee = new Employee;

        $employee->name = $request->input('name');
        $employee->email = $request->input('email');
        $employee->contact_number = $request->input('contact_number');
        $employee->position = $request->input('position');
        $employee->save();

        return 'Employee record successfully created with id ' . $employee->id;
    }

//My angular controller

app.controller('employeesController', function($scope, $http, API_URL) {
    //retrieve employees listing from API
    $http.get(API_URL + "employees")
            .success(function(response) {
                $scope.employees = response;
            });

    //show modal form
    $scope.toggle = function(modalstate, id) {
        $scope.modalstate = modalstate;

        switch (modalstate) {
            case 'add':
                $scope.form_title = "Add New Employee";
                break;
            case 'edit':
                $scope.form_title = "Employee Detail";
                $scope.id = id;
                $http.get(API_URL + 'employees/' + id)
                        .success(function(response) {
                            console.log(response);
                            $scope.employee = response;
                        });
                break;
            default:
                break;
        }
        console.log(id);
        $('#myModal').modal('show');
    }

    //save new record / update existing record
    $scope.save = function(modalstate, id) {
        var url = API_URL + "employees";

        //append Employee id to the URL if the form is in edit mode
        if (modalstate === 'edit'){
            url += "/" + id;
        }

        $http({
            method: 'POST',
            url: url,
            data: $.param($scope.employee),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).success(function(response) {
            console.log(response);
            location.reload();
        }).error(function(response) {
            console.log(response);
            alert('This is embarassing. An error has occured. Please check the log for details');
        });
    }

    //delete record
    $scope.confirmDelete = function(id) {
        var isConfirmDelete = confirm('Are you sure you want this record?');
        if (isConfirmDelete) {
            $http({
                method: 'DELETE',
                url: API_URL + 'employees/' + id
            }).
                    success(function(data) {
                        console.log(data);
                        location.reload();
                    }).
                    error(function(data) {
                        console.log(data);
                        alert('Unable to delete');
                    });
        } else {
            return false;
        }
    }
});

When I click to save the data, I am getting an error message I had setup in employeeController.js controller

$http({
            method: 'POST',
            url: url,
            data: $.param($scope.hotel),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).success(function(response) {
            console.log(response);
            location.reload();
        }).error(function(response) {
            console.log(response);
            alert('This is embarassing. An error has occured. Please check the log for details');
        });
    }

This my app.js

var app = angular.module(employees, [])
        .constant('API_URL', 'http://localhost/myapp/public/api/');

My routes.php

Route::get('/api/v1/employees/{id?}', 'Employees@index');
Route::post('/api/v1/employees', 'Employees@store');
Route::post('/api/v1/employees/{id}', 'Employees@update');
Route::post('/api/v1/employees/update/{id}',['as'=>'update','uses'=> 'Employees@update']);
Route::delete('/api/v1/employees/{id}', 'Employees@destroy');

What could be the cause of this? Please help. I have tried to solve this for 3 days without success.

My View in resources/views/employees/employee.php

<!DOCTYPE html>

        <title>Laravel 5 AngularJS CRUD Example</title>

        <link href="<?= asset('css/bootstrap.min.css') ?>" rel="stylesheet">

Employees Database

                        ID
                        Name
                        Email
                        Contact No
                        Position
                        <button id="btn-add" class="btn btn-primary btn-xs" ng-click="toggle('add', 0)">Add New Employee</button>

                        {{  employee.id }}
                        {{ employee.name }}
                        {{ employee.email }}
                        {{ employee.contact_number }}
                        {{ employee.position }}

                            <button class="btn btn-default btn-xs btn-detail" ng-click="toggle('edit', employee.id)">Edit</button>
                            <button class="btn btn-danger btn-xs btn-delete" ng-click="confirmDelete(employee.id)">Delete</button>

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

{{form_title}}

                            <form name="frmEmployees" class="form-horizontal" novalidate="">

                                    Name

                                        <input type="text" class="form-control has-error" id="name" name="name" placeholder="Fullname" value="{{name}}"
                                        ng-model="employee.name" ng-required="true">
                                        Name field is required

                                    Email

                                        <input type="email" class="form-control" id="email" name="email" placeholder="Email Address" value="{{email}}"
                                        ng-model="employee.email" ng-required="true">
                                        Valid Email field is required

                                    Contact Number

                                        <input type="text" class="form-control" id="contact_number" name="contact_number" placeholder="Contact Number" value="{{contact_number}}"
                                        ng-model="employee.contact_number" ng-required="true">
                                    Contact number field is required

                                    Position

                                        <input type="text" class="form-control" id="position" name="position" placeholder="Position" value="{{position}}"
                                        ng-model="employee.position" ng-required="true">
                                    Position field is required

                            </form>

                            <button type="button" class="btn btn-primary" id="btn-save" ng-click="save(modalstate, id)" ng-disabled="frmEmployees.$invalid">Save changes</button>


问:
how to display data from database into an option tag html?
any one can help me with this?
i want to displaying my database data into a option tag but it not showing anything. i have try to make a code for that but that code not work to display my data into html option tag. someone please help me to solve my problem.

this is my code that i make

// JavaScript Document
// for make the option tag
$(function() {

$('#chkveg').multiselect({

includeSelectAllOption: true

});
});

// for call the data from my database
$(document).on('click','#nama_check',function(e){
    $.ajax({
        type:"POST",
        url:"../php/absen/absen_karyawan_autocomplete.php",
        success: function(data){
            var list = JSON.parse(data);
            for(var i=0; i < list.length; i++){
                $('#chkveg').val((list[i]['bagian']));

            }
            return false;
        }
    });
});
```

<pre class="lang-html prettyprint-override"><code><script src="https://davidstutz.github.io/bootstrap-multiselect/docs/js/bootstrap-3.3.2.min.js"></script>
<link href="https://davidstutz.github.io/bootstrap-multiselect/docs/css/bootstrap-3.3.2.min.css" rel="stylesheet"/>
<link href="https://davidstutz.github.io/bootstrap-multiselect/dist/css/bootstrap-multiselect.css" rel="stylesheet"/>
<script src="https://davidstutz.github.io/bootstrap-multiselect/dist/js/bootstrap-multiselect.js"></script>

<form id="form1" method="post">

        <div style="padding:20px">

        <select id="chkveg" multiple="multiple">
        </select>

        </div>

        </form>
</code>```

答:
You have two issues here. Firstly to add values to the select you need to append new option elements to it, not repeatedly set the val(). Secondly, you should call multiselect() after the options have been added.

Also note that you can place all code within a single document.ready handler. Try this:

```<code>$(function() {
  $(document).on('click','#nama_check',function(e){
    $.ajax({
      type: "POST",
      url: "../php/absen/absen_karyawan_autocomplete.php",
      dataType: 'json',
      success: function(data) {
        var html = '';
        for(var i = 0; i < data.length; i++) {
          html += '<option>' + data[i]['bagian'] + '</option>';
        }
        $('#chkveg').html(html).multiselect({
          includeSelectAllOption: true
        });
      }
    });
  });
});
</code>```

Body:
any one can help me with this?
i want to displaying my database data into a option tag but it not showing anything. i have try to make a code for that but that code not work to display my data into html option tag. someone please help me to solve my problem.

this is my code that i make

// JavaScript Document
// for make the option tag
$(function() {

$('#chkveg').multiselect({

includeSelectAllOption: true

});
});

// for call the data from my database
$(document).on('click','#nama_check',function(e){
    $.ajax({
        type:"POST",
        url:"../php/absen/absen_karyawan_autocomplete.php",
        success: function(data){
            var list = JSON.parse(data);
            for(var i=0; i < list.length; i++){
                $('#chkveg').val((list[i]['bagian']));

            }
            return false;
        }
    });
});

<link href="https://davidstutz.github.io/bootstrap-multiselect/docs/css/bootstrap-3.3.2.min.css" rel="stylesheet"/>
<link href="https://davidstutz.github.io/bootstrap-multiselect/dist/css/bootstrap-multiselect.css" rel="stylesheet"/>

<form id="form1" method="post">

        <select id="chkveg" multiple="multiple">
        </select>

        </form>

Body:
You have two issues here. Firstly to add values to the select you need to append new option elements to it, not repeatedly set the val(). Secondly, you should call multiselect() after the options have been added.

Also note that you can place all code within a single document.ready handler. Try this:

$(function() {
  $(document).on('click','#nama_check',function(e){
    $.ajax({
      type: "POST",
      url: "../php/absen/absen_karyawan_autocomplete.php",
      dataType: 'json',
      success: function(data) {
        var html = '';
        for(var i = 0; i < data.length; i++) {
          html += '<option>' + data[i]['bagian'] + '</option>';
        }
        $('#chkveg').html(html).multiselect({
          includeSelectAllOption: true
        });
      }
    });
  });
});


问:
add click event for href located in the table row
I populate table with data from the ajax request like this

```<code>$.ajax({
    type: 'GET',
    url: '/notes-rest/search',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(data) {
        $('#notes-table tbody').append(
                $.map(data, function(note, index) {
                    return '<tr>' +
                            '<td style="display:none;">' + note.noteId + '</td>' +
                            '<td>' + $.format.date(new Date(note.date), "dd/MM/yyyy") + '</td>' +
                            '<td>' + note.owner + '</td>' +
                            '<td>' + note.name + '</td>' +
                            '<td>' + note.text + '</td>' +
                            '<td><ul id="tags-list" class="hr">' + processTags(note.tags) + '</ul></td>' +
                            '<td><a href="#" id="delete-record">delete</a> | <a href="#" id="update-record">update</a></td>'
                            + '</tr>';
                }).join()
        );
    }
});
</code>```

How to add click event for href (delete-record and update-record) in the last column? In that event I'd like to get the whole row with data, where the href is located. Table looks like this

```<code><table class="table table-striped table-hover" style="table-layout: fixed" id="notes-table">
    <thead>
    <tr>
        <th>Date</th>
        <th>Owner</th>
        <th>Name</th>
        <th>Text</th>
        <th>Tags</th>
        <th>Actions</th>
    </tr>
    </thead>
    <tbody></tbody>
</table>
</code>```

答:
In the end I decided to do like this

```<code>$.ajax({
    type: 'GET',
    url: '/notes-rest/search',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(data) {
        $('#notes-table tbody').append(
                $.map(data, function(note, index) {
                    var rowIndex = index + 1;
                    return '<tr id="row-' + rowIndex + '">' +
                            '<td style="display:none;">' + note.noteId + '</td>' +
                            '<td>' + $.format.date(new Date(note.date), "dd/MM/yyyy") + '</td>' +
                            '<td>' + note.owner + '</td>' +
                            '<td>' + note.name + '</td>' +
                            '<td>' + note.text + '</td>' +
                            '<td><ul id="tags-list" class="hr">' + processTags(note.tags) + '</ul></td>' +
                            '<td><a href="#" onclick="deleteRecord(' + rowIndex + ');">delete</a></td>'
                            + '</tr>';
                }).join()
        );
    }
})
</code>```

With function

```<code>function deleteRecord(id) {
    var recordId = $('#notes-table').find("tr")[id].cells[0].innerHTML;
    $.ajax({
        url: '/notes-rest/note/' + recordId,
        type: 'DELETE',
        success: function() {
            location.reload();
        }
    });
}
</code>```

Body:
I populate table with data from the ajax request like this

$.ajax({
    type: 'GET',
    url: '/notes-rest/search',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(data) {
        $('#notes-table tbody').append(
                $.map(data, function(note, index) {
                    return '
' +
                            '' + note.noteId + '	' +
                            '' + $.format.date(new Date(note.date), "dd/MM/yyyy") + '	' +
                            '' + note.owner + '	' +
                            '' + note.name + '	' +
                            '' + note.text + '	' +
                            '
' + processTags(note.tags) + '
	' +
                            'delete | update	'
                            + '
';
                }).join()
        );
    }
});

How to add click event for href (delete-record and update-record) in the last column? In that event I'd like to get the whole row with data, where the href is located. Table looks like this

        Date
        Owner
        Name
        Text
        Tags
        Actions

Body:
In the end I decided to do like this

$.ajax({
    type: 'GET',
    url: '/notes-rest/search',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function(data) {
        $('#notes-table tbody').append(
                $.map(data, function(note, index) {
                    var rowIndex = index + 1;
                    return '<tr id="row-' + rowIndex + '">' +
                            '<td style="display:none;">' + note.noteId + '</td>' +
                            '<td>' + $.format.date(new Date(note.date), "dd/MM/yyyy") + '</td>' +
                            '<td>' + note.owner + '</td>' +
                            '<td>' + note.name + '</td>' +
                            '<td>' + note.text + '</td>' +
                            '<td><ul id="tags-list" class="hr">' + processTags(note.tags) + '</ul></td>' +
                            '<td><a href="#" onclick="deleteRecord(' + rowIndex + ');">delete</a></td>'
                            + '</tr>';
                }).join()
        );
    }
})

With function

function deleteRecord(id) {
    var recordId = $('#notes-table').find("tr")[id].cells[0].innerHTML;
    $.ajax({
        url: '/notes-rest/note/' + recordId,
        type: 'DELETE',
        success: function() {
            location.reload();
        }
    });
}


问:
sendAsynchronousRequest was deprecated in iOS 9, How to alter code to fix
Below is my code I am getting the issue with:

```<code>func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void)
{
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in

        if ((error) != nil)
        {
            callback(feed: nil, error: error)
        }
        else
        {
            self.callbackClosure = callback

            let parser : NSXMLParser = NSXMLParser(data: data!)
            parser.delegate = self
            parser.shouldResolveExternalEntities = false
            parser.parse()
        }
    }
}
</code>```

This is now deprecated as of iOS 9, and is telling me to use dataTaskWithRequest instead. Can someone help me change sendAsync with dataTask, I don't know how to.

答:
with swift 3.1</p>

```<code>let request = NSMutableURLRequest(url: NSURL(string: image_url_string)! as URL)
    let session = URLSession.shared
    request.httpMethod = "POST"

    let params = ["username":"username", "password":"password"] as Dictionary<String, String>

    request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
        print("Response: \(String(describing: response))")})

    task.resume()
</code>```

Body:
Below is my code I am getting the issue with:

func parseFeedForRequest(request: NSURLRequest, callback: (feed: RSSFeed?, error: NSError?) -> Void)
{
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in

        if ((error) != nil)
        {
            callback(feed: nil, error: error)
        }
        else
        {
            self.callbackClosure = callback

            let parser : NSXMLParser = NSXMLParser(data: data!)
            parser.delegate = self
            parser.shouldResolveExternalEntities = false
            parser.parse()
        }
    }
}

This is now deprecated as of iOS 9, and is telling me to use dataTaskWithRequest instead. Can someone help me change sendAsync with dataTask, I don't know how to.

Body:
with swift 3.1

let request = NSMutableURLRequest(url: NSURL(string: image_url_string)! as URL)
    let session = URLSession.shared
    request.httpMethod = "POST"

    let params = ["username":"username", "password":"password"] as Dictionary<String, String>

    request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in
        print("Response: \(String(describing: response))")})

    task.resume()


问:
Changing the Trashcan icon in the dock
Is it possible to write a program for Mac OS X that monitors the trashcan and changes the icon dynamically when you fill the can?</p>

答: Yes, it's possible. Candybar does it. I expect that rather than dynamically changing the icon, they just register a new 'empty' and 'full' icon with the Dock process.</p>

Title: Changing the Trashcan icon in the dock


问:
How to setup git on ubutu server?
I want to configure git on ubutu server and commit our source code using shell command.

Thanks

答:
here explain how to direct commit code with Aptana but its hang system so use the shell command or other tool for commit code like SmartGit

http://nealbuerger.com/2013/11/aptana-eclipse-set-up-git-repository-github-bitbucket/

ContentLicense: CC BY-SA 4.0

Title: How to setup git on ubutu server?


问:
Query in php returns null or empty value
I wrote the following query:

```<code> $query1 = "SELECT * FROM session WHERE Id_session IN (SELECT * FROM students_in_session WHERE Username = '$email')";
   $res = mysqli_query($conn,$query1);
   $query2 ="SELECT * FROM students_in_session WHERE Username='$email'";
    $res2 = mysqli_query($conn,$query2);
    if (!$res) {
    die(mysqli_error($conn));
 }else{
     while ($row = mysqli_fetch_array($res)) {
       print_r($row);
     $course = $row['Degree'];
     $date = $row['Date'];
     $hour = $row['Hour'];
     $room = $row['Room'];
     }
}
if(!$res2){
    die(mysqli_error($conn));
}else{
    while ($row = mysqli_fetch_array($res2)) {
      print_r($row);
          $prof = $row['Professor'];
        $assis = $row['Assistent'];
    }
}
     return "\n\nDegree: ".$course."\n"."Date: ".$date."\n"."Hour: ".$hour."\n"."Room: ".$room."\n"."Prof: ".$prof."\n"."Assistent: ".$assis;
 }
</code>```

Currently using phpmyadmin and testing the query returns the expected result,but using the query in the code the variables are all empty.

These are DB's Table:

session

```<code>|Id_Session|Date|Hour|Room|Degree|
</code>```

students_in_session

```<code>|Id_Session|Code|Name|Surname|Username|Professor|Assistent|
</code>```

答:
when you use a IN over a nested query, the nested query can return only one column:

SELECT * FROM session WHERE Id_session IN
(SELECT Id_Session  FROM students_in_session WHERE Username = '$email')
```

<p>However a nested query is not the best approach in your case, because MySQL will have to execute 2 queries. You would better do an INNER JOIN :</p>

<pre class="lang-sql prettyprint-override"><code>SELECT S.*
FROM session S
INNER JOIN students_in_session SS ON SS.Id_Session=S.Id_Session
WHERE SS.Username = '$email'
</code>```

Body:
I wrote the following query:

 $query1 = "SELECT * FROM session WHERE Id_session IN (SELECT * FROM students_in_session WHERE Username = '$email')";
   $res = mysqli_query($conn,$query1);
   $query2 ="SELECT * FROM students_in_session WHERE Username='$email'";
    $res2 = mysqli_query($conn,$query2);
    if (!$res) {
    die(mysqli_error($conn));
 }else{
     while ($row = mysqli_fetch_array($res)) {
       print_r($row);
     $course = $row['Degree'];
     $date = $row['Date'];
     $hour = $row['Hour'];
     $room = $row['Room'];
     }
}
if(!$res2){
    die(mysqli_error($conn));
}else{
    while ($row = mysqli_fetch_array($res2)) {
      print_r($row);
          $prof = $row['Professor'];
        $assis = $row['Assistent'];
    }
}
     return "\n\nDegree: ".$course."\n"."Date: ".$date."\n"."Hour: ".$hour."\n"."Room: ".$room."\n"."Prof: ".$prof."\n"."Assistent: ".$assis;
 }

Currently using phpmyadmin and testing the query returns the expected result,but using the query in the code the variables are all empty.

These are DB's Table:

session

|Id_Session|Date|Hour|Room|Degree|

students_in_session

|Id_Session|Code|Name|Surname|Username|Professor|Assistent|

Body:
when you use a IN over a nested query, the nested query can return only one column:

SELECT * FROM session WHERE Id_session IN
(SELECT Id_Session  FROM students_in_session WHERE Username = '$email')

However a nested query is not the best approach in your case, because MySQL will have to execute 2 queries. You would better do an INNER JOIN :

SELECT S.*
FROM session S
INNER JOIN students_in_session SS ON SS.Id_Session=S.Id_Session
WHERE SS.Username = '$email'


问:
Code Coverage issue when spyon is used
I am writing a unit test for my component(Angular2 app) using Karma-Jasmine. And I am making use of Istanbul for Code Coverage report.

Here is my test case,

```<code>it('Should Invoke onNext function', async(() => {
    const fixture = TestBed.createComponent(LoginComponent);
    fixture.detectChanges();
    const login = fixture.componentInstance;

    spyOn(login, 'onNext');

    let email = fixture.debugElement.nativeElement.querySelector("input[name='username']");
    email.value = "email";

    let nextButton = fixture.debugElement.nativeElement.querySelectorAll("button")[1];
    nextButton.click();

    fixture.whenStable().then(() => {
      expect(login.onNext).toHaveBeenCalled();
    })
  }));
</code>```

As you can see I am spying on onNext function to verify whether it is getting called or not on nextbutton click. It is working fine and the test passes.

But the code coverage report for my Login page shows that the onNext function is  not covered.

What am I doing wrong??

And also if I don't spy on onNext function, the function is covered,

```<code>it('Should Invoke onNext function', async(() => {
    const fixture = TestBed.createComponent(LoginComponent);
    fixture.detectChanges();
    const login = fixture.componentInstance;

    let email = fixture.debugElement.nativeElement.querySelector("input[name='username']");
    email.value = "email";

    let nextButton = fixture.debugElement.nativeElement.querySelectorAll("button")[1];
    nextButton.click();
  }));
</code>```

答:
Use this:

spyOn(login, 'onNext').and.callThrough()

Title: Code Coverage issue when spyon is used

Body:
I am writing a unit test for my component(Angular2 app) using Karma-Jasmine. And I am making use of Istanbul for Code Coverage report.

Here is my test case,

it('Should Invoke onNext function', async(() => {
    const fixture = TestBed.createComponent(LoginComponent);
    fixture.detectChanges();
    const login = fixture.componentInstance;

    spyOn(login, 'onNext');

    let email = fixture.debugElement.nativeElement.querySelector("input[name='username']");
    email.value = "email";

    let nextButton = fixture.debugElement.nativeElement.querySelectorAll("button")[1];
    nextButton.click();

    fixture.whenStable().then(() => {
      expect(login.onNext).toHaveBeenCalled();
    })
  }));

As you can see I am spying on onNext function to verify whether it is getting called or not on nextbutton click. It is working fine and the test passes.

But the code coverage report for my Login page shows that the onNext function is  not covered.

What am I doing wrong??

And also if I don't spy on onNext function, the function is covered,

it('Should Invoke onNext function', async(() => {
    const fixture = TestBed.createComponent(LoginComponent);
    fixture.detectChanges();
    const login = fixture.componentInstance;

    let email = fixture.debugElement.nativeElement.querySelector("input[name='username']");
    email.value = "email";

    let nextButton = fixture.debugElement.nativeElement.querySelectorAll("button")[1];
    nextButton.click();
  }));


问:
how to retrieve the value of javascript var through python?
I need to get the data of productSkus[ using python but I don't know how to access it. the javascript comes from http://www.ulta.com/lid-lingerie-eye-tint?productId=xlsImpprod15361061 .
This is how it looks like.

```<code><script type="text/javascript">
  var currentSkuId = '2502111';
  var currentProductId = 'xlsImpprod15361061';

  var productSkus = new Object();

              productSkus[2502111] =
                {"displayName":"Fame & Fortune","id":"2502111","imgUrl":"http://images.ulta.com/is/image/Ulta/2502111?$detail$","largeImgUrl":"http://images.ulta.com/is/image/Ulta/2502111?$lg$","swatchImgUrl":"http://images.ulta.com/is/image/Ulta/2502111sw?$50px$","swatchHoverImgUrl":"http://images.ulta.com/is/image/Ulta/2502111sm?$md$","skuSize":"0.13","skuSizeUOM":"oz"};........
</code>```

Can anyone help me with this?

答:
If you want to use productSkus on the server side, then you need to use AJAX to send the JS variable to the server.

As Django template is compiled server side. It is then sent to the client where their browser executes the JavaScript. Nothing that is changed by the JavaScript executing on the client browser can have an affect on the template. It's too late at that point.

However the JavaScript could do something like make another request from the server for more information. Or you could just pre-compute the value on the server before you send it to the client.

You can of course use Django templates to set JavaScript variables.

```<code><script>
    var myVar = '{{ py_var }}';
</script>
</code>```

Body:
If you want to use productSkus on the server side, then you need to use AJAX to send the JS variable to the server.

As Django template is compiled server side. It is then sent to the client where their browser executes the JavaScript. Nothing that is changed by the JavaScript executing on the client browser can have an affect on the template. It's too late at that point.

However the JavaScript could do something like make another request from the server for more information. Or you could just pre-compute the value on the server before you send it to the client.

You can of course use Django templates to set JavaScript variables.

<script>
    var myVar = '{{ py_var }}';
</script>


问:
How to start a thread at creation time of a class and (re)use it to execute a method multiple times
I am trying to solve an exercise while studying for my next exam. This is the question

Use Java to implement a MsgBatcher class that holds a (finite) set of
  messages and sends them, on request, in batch. Suppose we have a
  Message class with a method void send(). MsgBatcher provides a method
  void enqueue(Message) to add a new message to the batch. It suspends
  the caller if the MsgBatcher is full (the maximum number of messages
  that can be enqueued is provided in the MsgBatcher constructor). A
  method void sendAll() is also provided to send all messages enqueued
  up to that moment (it empties the MsgBatcher). Organize
  synchronization that will take care of the fact that sending a message
  may take a long time. Optional: implement the sendAll method so that
  the sending is performed asynchronously w.r.t. the caller (i.e., in a
  separate thread, which should be started at MsgBatcher creation time
  and reused for each sending).

So far i have written this

import java.util.ArrayList;

public class MsgBatcher {

    public ArrayList<Message> batch = new ArrayList<Message>();
    int maxSpaces;

    public void MsgBatcher(int max){
        this.maxSpaces= max;
    }
    public synchronized void enqueue(Message m) throws InterruptedException{
        while(batch.size() == maxSpaces) wait();
        this.batch.add(m);
    }
    public void sendAll(){
        ArrayList<Message> toSend = new ArrayList<Message>();
        toSend.addAll(batch);
        batch.clear(); //in this way i can accept other messages while sending the others

        for (Message m : toSend){
            m.send();
        }
        batch.clear();
    }
}
```

<p>and since the Message class is not really important i have written just a few lines to emulate the asked behaviour</p>

<pre class="lang-java prettyprint-override"><code>public class Message {

 public void send(){
     System.out.println("Sending");
     try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     System.out.println("Sent");
 }
}
</code>```

what i do not understand is how to deal with

Organize synchronization that will take care of the fact that sending
  a message may take a long time.

and especially with

Optional: implement the sendAll method so that the sending is
  performed asynchronously w.r.t. the caller (i.e., in a separate
  thread, which should be started at MsgBatcher creation time and reused
  for each sending).

as per title of this question

I know i should ask the Professor, and i have already sent him an email, but he did not answer.
Thanks for your help!

答:
I think you were preparing the exam Middleware technologies for dist sys at PoliMi.

I'm doing as well and I found your question because I'm doing the same exercise. This is my solution and it seems to work well.

I posted it, even if you don't probably need it anymore, in case someone else will need while preparing this exam.

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

public class TestThread extends Thread{

private String name;
private MsgBatcher msgBatcher;

public TestThread(String name, MsgBatcher msgBatcher){
    this.name = name;
    this.msgBatcher = msgBatcher;
}

/**
 * Each thread tries to add 10 messages.
 */
public void run(){
    for(int i = 0; i < 10; i++){
        Message msg = new Message("Thread " + this.name + " | i: " + i);
        try{
            System.out.println("[T] Thread " + this.name + " Adding " + i);
            this.msgBatcher.enqueue(msg);
            System.out.println("[T] Thread " + this.name + " Added " + i);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

public static void main(String[] args){
    MsgBatcher msgBatcher = new MsgBatcher(10);
    TestThread t1 = new TestThread("1", msgBatcher);
    TestThread t2 = new TestThread("2", msgBatcher);

    t1.start();
    t2.start();

    try{
        //After 3 seconds we try to send the first batch
        Thread.sleep(3000);
        msgBatcher.sendAll();
    }catch (Exception e){
        e.printStackTrace();
    }

}
}

class MsgSender extends Thread{

private ArrayList<Message> toSend;

public MsgSender(){
    this.toSend = new ArrayList<Message>();
}

public void run(){
    while(true){
        synchronized (this){
            try{
                System.out.println("[MS] Starting run.");
                while (this.toSend.size() == 0){
                    System.out.println("[MS] Waiting for messages." + this.toSend.size());
                    wait();
                }

                System.out.println("[MS] Messages ready to be sent.");

                for(Message msg: this.toSend){
                    msg.send();
                }

                this.toSend.clear();

                System.out.println("[MS] Messages sent.");

                notifyAll();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

public synchronized void addMsgs(ArrayList<Message> toSend){
    synchronized (this){
        try{
            System.out.println("[MS] Adding messages.");
            while (this.toSend.size() != 0){
                System.out.println("[MS] Adding messages. Waiting toSend to become empty");
                wait();
            }

            this.toSend = toSend;

            System.out.println("[MS] Messages added. Notifying the run."  + this.toSend.size());

            notifyAll();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    this.toSend = toSend;

    notify();
}
}

class MsgBatcher{

private int size;
private ArrayList<Message> queue;
private MsgSender msgSender;

public MsgBatcher(int size){
    this.size = size;
    this.queue = new ArrayList<Message>(this.size);
    this.msgSender = new MsgSender();
    this.msgSender.start();
    try{
        //wait enough time to be sure the msgSender thread is ready
        Thread.sleep(3000);
    }catch (Exception e){
        e.printStackTrace();
    }
}

public synchronized void enqueue(Message msg) throws InterruptedException{
    System.out.println("[MB] size: " + this.queue.size());
    while(this.queue.size() == this.size){
        wait();
    }

    this.queue.add(msg);

    notifyAll();
}

public synchronized void sendAll(){
    System.out.println("Sending all messages");

    ArrayList<Message> toSend = new ArrayList<Message>();
    toSend.addAll(this.queue);

    this.msgSender.addMsgs(toSend);

    this.queue.clear();

    notifyAll();
}
}

class Message {

private String text;

public Message(String text){
    this.text = text;
}

public void send(){
    System.out.println("[M] Sending: " + this.text);
    try{
        Thread.sleep(1000);
    }catch (Exception e){
        e.printStackTrace();
    }
    System.out.println("[M] Sent: " + this.text);
}
}
</code>```

Body:
I am trying to solve an exercise while studying for my next exam. This is the question

Use Java to implement a MsgBatcher class that holds a (finite) set of
  messages and sends them, on request, in batch. Suppose we have a
  Message class with a method void send(). MsgBatcher provides a method
  void enqueue(Message) to add a new message to the batch. It suspends
  the caller if the MsgBatcher is full (the maximum number of messages
  that can be enqueued is provided in the MsgBatcher constructor). A
  method void sendAll() is also provided to send all messages enqueued
  up to that moment (it empties the MsgBatcher). Organize
  synchronization that will take care of the fact that sending a message
  may take a long time. Optional: implement the sendAll method so that
  the sending is performed asynchronously w.r.t. the caller (i.e., in a
  separate thread, which should be started at MsgBatcher creation time
  and reused for each sending).

So far i have written this

import java.util.ArrayList;

public class MsgBatcher {

    public ArrayList<Message> batch = new ArrayList<Message>();
    int maxSpaces;

    public void MsgBatcher(int max){
        this.maxSpaces= max;
    }
    public synchronized void enqueue(Message m) throws InterruptedException{
        while(batch.size() == maxSpaces) wait();
        this.batch.add(m);
    }
    public void sendAll(){
        ArrayList<Message> toSend = new ArrayList<Message>();
        toSend.addAll(batch);
        batch.clear(); //in this way i can accept other messages while sending the others

        for (Message m : toSend){
            m.send();
        }
        batch.clear();
    }
}

and since the Message class is not really important i have written just a few lines to emulate the asked behaviour

public class Message {

 public void send(){
     System.out.println("Sending");
     try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
     System.out.println("Sent");
 }
}

what i do not understand is how to deal with

Organize synchronization that will take care of the fact that sending
  a message may take a long time.

and especially with

Optional: implement the sendAll method so that the sending is
  performed asynchronously w.r.t. the caller (i.e., in a separate
  thread, which should be started at MsgBatcher creation time and reused
  for each sending).

as per title of this question

I know i should ask the Professor, and i have already sent him an email, but he did not answer.
Thanks for your help!

Body:
I think you were preparing the exam Middleware technologies for dist sys at PoliMi.

I'm doing as well and I found your question because I'm doing the same exercise. This is my solution and it seems to work well.

I posted it, even if you don't probably need it anymore, in case someone else will need while preparing this exam.

import java.util.ArrayList;

public class TestThread extends Thread{

private String name;
private MsgBatcher msgBatcher;

public TestThread(String name, MsgBatcher msgBatcher){
    this.name = name;
    this.msgBatcher = msgBatcher;
}

/**
 * Each thread tries to add 10 messages.
 */
public void run(){
    for(int i = 0; i < 10; i++){
        Message msg = new Message("Thread " + this.name + " | i: " + i);
        try{
            System.out.println("[T] Thread " + this.name + " Adding " + i);
            this.msgBatcher.enqueue(msg);
            System.out.println("[T] Thread " + this.name + " Added " + i);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

public static void main(String[] args){
    MsgBatcher msgBatcher = new MsgBatcher(10);
    TestThread t1 = new TestThread("1", msgBatcher);
    TestThread t2 = new TestThread("2", msgBatcher);

    t1.start();
    t2.start();

    try{
        //After 3 seconds we try to send the first batch
        Thread.sleep(3000);
        msgBatcher.sendAll();
    }catch (Exception e){
        e.printStackTrace();
    }

}
}

class MsgSender extends Thread{

private ArrayList<Message> toSend;

public MsgSender(){
    this.toSend = new ArrayList<Message>();
}

public void run(){
    while(true){
        synchronized (this){
            try{
                System.out.println("[MS] Starting run.");
                while (this.toSend.size() == 0){
                    System.out.println("[MS] Waiting for messages." + this.toSend.size());
                    wait();
                }

                System.out.println("[MS] Messages ready to be sent.");

                for(Message msg: this.toSend){
                    msg.send();
                }

                this.toSend.clear();

                System.out.println("[MS] Messages sent.");

                notifyAll();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

public synchronized void addMsgs(ArrayList<Message> toSend){
    synchronized (this){
        try{
            System.out.println("[MS] Adding messages.");
            while (this.toSend.size() != 0){
                System.out.println("[MS] Adding messages. Waiting toSend to become empty");
                wait();
            }

            this.toSend = toSend;

            System.out.println("[MS] Messages added. Notifying the run."  + this.toSend.size());

            notifyAll();
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    this.toSend = toSend;

    notify();
}
}

class MsgBatcher{

private int size;
private ArrayList<Message> queue;
private MsgSender msgSender;

public MsgBatcher(int size){
    this.size = size;
    this.queue = new ArrayList<Message>(this.size);
    this.msgSender = new MsgSender();
    this.msgSender.start();
    try{
        //wait enough time to be sure the msgSender thread is ready
        Thread.sleep(3000);
    }catch (Exception e){
        e.printStackTrace();
    }
}

public synchronized void enqueue(Message msg) throws InterruptedException{
    System.out.println("[MB] size: " + this.queue.size());
    while(this.queue.size() == this.size){
        wait();
    }

    this.queue.add(msg);

    notifyAll();
}

public synchronized void sendAll(){
    System.out.println("Sending all messages");

    ArrayList<Message> toSend = new ArrayList<Message>();
    toSend.addAll(this.queue);

    this.msgSender.addMsgs(toSend);

    this.queue.clear();

    notifyAll();
}
}

class Message {

private String text;

public Message(String text){
    this.text = text;
}

public void send(){
    System.out.println("[M] Sending: " + this.text);
    try{
        Thread.sleep(1000);
    }catch (Exception e){
        e.printStackTrace();
    }
    System.out.println("[M] Sent: " + this.text);
}
}