问:
Replacing link text with jQuery doesn't work, no errors in console
There's a website that really wants to be bi-lingual even though the CMS doesn't support it. The system buttons can all be in English or Dutch but the content itself not. So they just write articles that have both the English and Dutch text.

Now I know, this is a trainwreck. But this is what the client wants so it's what he gets. I just don't have access to the CMS so I can't do this properly.

Now, to translate the menu buttons I perform a check if the title of a certain element is "Terms of Service" or "Regelement" which tells me if the website is in Dutch or English. I then have an each function that runs through all the li elements in the menu, checking if the text matches with one of the texts I need to translate, so basically:

```<code>if ($(this).text() == 'Nieuws') {
    $(this).text('News');
}
</code>```

This used to work, but after recently adding in a language switch button at the top of the website the menu's aren't translated anymore, just the sub menu's. The code runs fine, no errors, and I even put a few alerts in to check if it was detecting the language properly, etc. That all works fine.

For some reason only the submenu's get translated now. The jQuery is of course executed at the end of the page, after the content loads. The website in question is https://www.onsplatform.tv/genderhof/ but you can only see the "Vraag & aanbod" button there.

// for snippet purposes
var setlanguage = 'en';

// If language of user is English
if (setlanguage == 'en') {

 // Loop through each main level menu
 $("#menu li a").each(function(){
  // Set text of menu item to variable
  var tempmenutxt = $(this).text();

  // Translate text of menu item if match is found
  if (tempmenutxt == 'Nieuws ▼') { $(this).text('News ▼'); }
   else if (tempmenutxt == 'SamenVeilig') { $(this).text("Camera's"); }
   else if (tempmenutxt == 'Vraag & aanbod ▼') { $(this).text('Marketplace ▼'); }
   else if (tempmenutxt == 'Informatie ▼') { $(this).text('Information ▼'); }
   else if (tempmenutxt == 'Fotoalbum') { $(this).text("Photo's"); }
   else if (tempmenutxt == 'Spelletjes') { $(this).text("Games"); }
   else if (tempmenutxt == 'Enquêtes') { $(this).text("Polls"); }
   else if (tempmenutxt == 'Koffiehuukske') { $(this).text("Coffeecorner"); }
   else if (tempmenutxt == 'Activiteiten') { $(this).text("Activities"); }
   else if (tempmenutxt == 'Klachtenhoek') { $(this).text("Complaints"); }
 });
 // Because "display: none;" items can't be read, make all submenu's visible
 $("#menu li ul").each(function(){
  $(this).css("display","block");
 });
 // Translate text of menu item if match is found
 $("#menu li ul li a").each(function(){
  var tempmenutxt = $(this).text();
  if (tempmenutxt == '- Onderhoud aanvragen') { $(this).text('- Request maintenance'); }
   else if (tempmenutxt == '- Goederen/diensten') { $(this).text("- Goods/services"); }
   else if (tempmenutxt == '- Mantelzorg / I.B.') { $(this).text("- Caregiving/intensive support"); }
   else if (tempmenutxt == '- Belangrijke telefoonnummers') { $(this).text("- Important phone numbers"); }
 });
 // Make all submenu invisible again
 $("#menu li ul").each(function(){
  $(this).css("display","none");
 });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* This CSS is just to illustrate, don't mind it, quick and dirty */

#menu {
  width: 100%;
  list-style: none;
  margin: 0;
  padding: 0;
  background: #FF0000;
}

#menu li {
  display: inline-block;
  position: relative;
  padding: 0;
}

#menu li a {
  display: inline-block;
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  color: #FFF;
}

#menu li ul {
  display: none;
  width: auto;
  position: absolute;
  top: 30px;
  background: #000;
  z-index: 1000;
  list-style: none;
  margin: 0;
  padding: 0;
}

#menu li:hover ul {
  display: block !important;
}

#menu li ul li {
  display: block;
}
  </code>```

            Home

            Nieuws  ▼

                    - Wooninc.

                    - Request maintenance

            SamenVeilig

            Agenda

            Vraag & aanbod  ▼

                    - Goods/services

                    - Caregiving/intensive support

            Informatie  ▼

                    - Important phone numbers

            Fotoalbum

            Chat

            Spelletjes

            Enquêtes

            Koffiehuukske

            Activiteiten

            Klachtenhoek

            Digisoos

```

答:
Its a space problem. In your html they have two spaces 'Nieuws  ▼'.But compare with javascript single space

// for snippet purposes
var setlanguage = 'en';
$(document).ready(function(){
// If language of user is English
if (setlanguage == 'en') {

 // Loop through each main level menu
 $("#menu li a").each(function(){
  // Set text of menu item to variable
  var tempmenutxt = $(this).text().trim()
  // Translate text of menu item if match is found
  if (tempmenutxt == 'Nieuws  ▼') { $(this).text('News  ▼'); }
   else if (tempmenutxt == 'SamenVeilig') { $(this).text("Camera's"); }
   else if (tempmenutxt == 'Vraag & aanbod  ▼') { $(this).text('Marketplace  ▼'); }
   else if (tempmenutxt == 'Informatie  ▼') { $(this).text('Information  ▼'); }
   else if (tempmenutxt == 'Fotoalbum') { $(this).text("Photo's"); }
   else if (tempmenutxt == 'Spelletjes') { $(this).text("Games"); }
   else if (tempmenutxt == 'Enquêtes') { $(this).text("Polls"); }
   else if (tempmenutxt == 'Koffiehuukske') { $(this).text("Coffeecorner"); }
   else if (tempmenutxt == 'Activiteiten') { $(this).text("Activities"); }
   else if (tempmenutxt == 'Klachtenhoek') { $(this).text("Complaints"); }
 });
 // Because "display: none;" items can't be read, make all submenu's visible
 $("#menu li ul").each(function(){
  $(this).css("display","block");
 });
 // Translate text of menu item if match is found
 $("#menu li ul li a").each(function(){
  var tempmenutxt = $(this).text().trim();
  if (tempmenutxt == '- Onderhoud aanvragen') { $(this).text('- Request maintenance'); }
   else if (tempmenutxt == '- Goederen/diensten') { $(this).text("- Goods/services"); }
   else if (tempmenutxt == '- Mantelzorg / I.B.') { $(this).text("- Caregiving/intensive support"); }
   else if (tempmenutxt == '- Belangrijke telefoonnummers') { $(this).text("- Important phone numbers"); }
 });
 // Make all submenu invisible again
 $("#menu li ul").each(function(){
  $(this).css("display","none");
 });
}
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* This CSS is just to illustrate, don't mind it, quick and dirty */

#menu {
  width: 100%;
  list-style: none;
  margin: 0;
  padding: 0;
  background: #FF0000;
}

#menu li {
  display: inline-block;
  position: relative;
  padding: 0;
}

#menu li a {
  display: inline-block;
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  color: #FFF;
}

#menu li ul {
  display: none;
  width: auto;
  position: absolute;
  top: 30px;
  background: #000;
  z-index: 1000;
  list-style: none;
  margin: 0;
  padding: 0;
}

#menu li:hover ul {
  display: block !important;
}

#menu li ul li {
  display: block;
}</code>```

            Home

            Nieuws  ▼

                    - Wooninc.

                    - Request maintenance

            SamenVeilig

            Agenda

            Vraag & aanbod  ▼

                    - Goods/services

                    - Caregiving/intensive support

            Informatie  ▼

                    - Important phone numbers

            Fotoalbum

            Chat

            Spelletjes

            Enquêtes

            Koffiehuukske

            Activiteiten

            Klachtenhoek

            Digisoos

```

Body:
There's a website that really wants to be bi-lingual even though the CMS doesn't support it. The system buttons can all be in English or Dutch but the content itself not. So they just write articles that have both the English and Dutch text.

Now I know, this is a trainwreck. But this is what the client wants so it's what he gets. I just don't have access to the CMS so I can't do this properly.

Now, to translate the menu buttons I perform a check if the title of a certain element is "Terms of Service" or "Regelement" which tells me if the website is in Dutch or English. I then have an each function that runs through all the li elements in the menu, checking if the text matches with one of the texts I need to translate, so basically:

if ($(this).text() == 'Nieuws') {
    $(this).text('News');
}

This used to work, but after recently adding in a language switch button at the top of the website the menu's aren't translated anymore, just the sub menu's. The code runs fine, no errors, and I even put a few alerts in to check if it was detecting the language properly, etc. That all works fine.

For some reason only the submenu's get translated now. The jQuery is of course executed at the end of the page, after the content loads. The website in question is https://www.onsplatform.tv/genderhof/ but you can only see the "Vraag & aanbod" button there.

// for snippet purposes
var setlanguage = 'en';

// If language of user is English
if (setlanguage == 'en') {

 // Loop through each main level menu
 $("#menu li a").each(function(){
  // Set text of menu item to variable
  var tempmenutxt = $(this).text();

  // Translate text of menu item if match is found
  if (tempmenutxt == 'Nieuws ▼') { $(this).text('News ▼'); }
   else if (tempmenutxt == 'SamenVeilig') { $(this).text("Camera's"); }
   else if (tempmenutxt == 'Vraag & aanbod ▼') { $(this).text('Marketplace ▼'); }
   else if (tempmenutxt == 'Informatie ▼') { $(this).text('Information ▼'); }
   else if (tempmenutxt == 'Fotoalbum') { $(this).text("Photo's"); }
   else if (tempmenutxt == 'Spelletjes') { $(this).text("Games"); }
   else if (tempmenutxt == 'Enquêtes') { $(this).text("Polls"); }
   else if (tempmenutxt == 'Koffiehuukske') { $(this).text("Coffeecorner"); }
   else if (tempmenutxt == 'Activiteiten') { $(this).text("Activities"); }
   else if (tempmenutxt == 'Klachtenhoek') { $(this).text("Complaints"); }
 });
 // Because "display: none;" items can't be read, make all submenu's visible
 $("#menu li ul").each(function(){
  $(this).css("display","block");
 });
 // Translate text of menu item if match is found
 $("#menu li ul li a").each(function(){
  var tempmenutxt = $(this).text();
  if (tempmenutxt == '- Onderhoud aanvragen') { $(this).text('- Request maintenance'); }
   else if (tempmenutxt == '- Goederen/diensten') { $(this).text("- Goods/services"); }
   else if (tempmenutxt == '- Mantelzorg / I.B.') { $(this).text("- Caregiving/intensive support"); }
   else if (tempmenutxt == '- Belangrijke telefoonnummers') { $(this).text("- Important phone numbers"); }
 });
 // Make all submenu invisible again
 $("#menu li ul").each(function(){
  $(this).css("display","none");
 });
}

/* This CSS is just to illustrate, don't mind it, quick and dirty */

#menu {
  width: 100%;
  list-style: none;
  margin: 0;
  padding: 0;
  background: #FF0000;
}

#menu li {
  display: inline-block;
  position: relative;
  padding: 0;
}

#menu li a {
  display: inline-block;
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  color: #FFF;
}

#menu li ul {
  display: none;
  width: auto;
  position: absolute;
  top: 30px;
  background: #000;
  z-index: 1000;
  list-style: none;
  margin: 0;
  padding: 0;
}

#menu li:hover ul {
  display: block !important;
}

#menu li ul li {
  display: block;
}

            Home

            Nieuws  ▼

                    - Wooninc.

                    - Request maintenance

            SamenVeilig

            Agenda

            Vraag & aanbod  ▼

                    - Goods/services

                    - Caregiving/intensive support

            Informatie  ▼

                    - Important phone numbers

            Fotoalbum

            Chat

            Spelletjes

            Enquêtes

            Koffiehuukske

            Activiteiten

            Klachtenhoek

            Digisoos

Body:
Its a space problem. In your html they have two spaces 'Nieuws  ▼'.But compare with javascript single space

// for snippet purposes
var setlanguage = 'en';
$(document).ready(function(){
// If language of user is English
if (setlanguage == 'en') {

 // Loop through each main level menu
 $("#menu li a").each(function(){
  // Set text of menu item to variable
  var tempmenutxt = $(this).text().trim()
  // Translate text of menu item if match is found
  if (tempmenutxt == 'Nieuws  ▼') { $(this).text('News  ▼'); }
   else if (tempmenutxt == 'SamenVeilig') { $(this).text("Camera's"); }
   else if (tempmenutxt == 'Vraag & aanbod  ▼') { $(this).text('Marketplace  ▼'); }
   else if (tempmenutxt == 'Informatie  ▼') { $(this).text('Information  ▼'); }
   else if (tempmenutxt == 'Fotoalbum') { $(this).text("Photo's"); }
   else if (tempmenutxt == 'Spelletjes') { $(this).text("Games"); }
   else if (tempmenutxt == 'Enquêtes') { $(this).text("Polls"); }
   else if (tempmenutxt == 'Koffiehuukske') { $(this).text("Coffeecorner"); }
   else if (tempmenutxt == 'Activiteiten') { $(this).text("Activities"); }
   else if (tempmenutxt == 'Klachtenhoek') { $(this).text("Complaints"); }
 });
 // Because "display: none;" items can't be read, make all submenu's visible
 $("#menu li ul").each(function(){
  $(this).css("display","block");
 });
 // Translate text of menu item if match is found
 $("#menu li ul li a").each(function(){
  var tempmenutxt = $(this).text().trim();
  if (tempmenutxt == '- Onderhoud aanvragen') { $(this).text('- Request maintenance'); }
   else if (tempmenutxt == '- Goederen/diensten') { $(this).text("- Goods/services"); }
   else if (tempmenutxt == '- Mantelzorg / I.B.') { $(this).text("- Caregiving/intensive support"); }
   else if (tempmenutxt == '- Belangrijke telefoonnummers') { $(this).text("- Important phone numbers"); }
 });
 // Make all submenu invisible again
 $("#menu li ul").each(function(){
  $(this).css("display","none");
 });
}
})

/* This CSS is just to illustrate, don't mind it, quick and dirty */

#menu {
  width: 100%;
  list-style: none;
  margin: 0;
  padding: 0;
  background: #FF0000;
}

#menu li {
  display: inline-block;
  position: relative;
  padding: 0;
}

#menu li a {
  display: inline-block;
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  color: #FFF;
}

#menu li ul {
  display: none;
  width: auto;
  position: absolute;
  top: 30px;
  background: #000;
  z-index: 1000;
  list-style: none;
  margin: 0;
  padding: 0;
}

#menu li:hover ul {
  display: block !important;
}

#menu li ul li {
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu">
        <li class="selected">
            <a href="/genderhof/">Home</a>
        </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/nieuws" title="Nieuws">Nieuws  ▼</a>

            <ul style="display: none;" id="subMenu3393">
                <li>
                    <a href="https://www.onsplatform.tv/genderhof/wooninc" title="- Wooninc.">- Wooninc.</a>
                </li>
                <li>
                    <a href="https://www.onsplatform.tv/genderhof/CommunityUser/SendGroupMail/740" title="- Onderhoud aanvragen">- Request maintenance</a>
                </li>
            </ul>
         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/samenveilig" title="SamenVeilig">SamenVeilig </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/agenda" title="Agenda">Agenda </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/marktplaats" title="Vraag &amp; aanbod">Vraag &amp; aanbod  ▼</a>

            <ul style="display: none;" id="subMenu3396">
                <li>
                    <a href="https://www.onsplatform.tv/genderhof/goederen-diensten" title="- Goederen/diensten">- Goods/services</a>
                </li>
                <li>
                    <a href="https://www.onsplatform.tv/genderhof/mantelzorg---i-b" title="- Mantelzorg / I.B.">- Caregiving/intensive support</a>
                </li>
            </ul>
         </li>
        <li>
            <a href="#" title="Informatie">Informatie  ▼</a>

             <ul style="display: none;" id="subMenu3397">
                <li>
                    <a href="https://www.onsplatform.tv/genderhof/belangrijke-telefoonnummers_1" title="- Belangrijke telefoonnummers">- Important phone numbers</a>
                </li>
            </ul>
         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/fotoalbum" title="Fotoalbum" tmp_title="Fotoalbum">Fotoalbum </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/chat" title="Chat" tmp_title="Chat">Chat </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/spelletjes" title="Spelletjes">Spelletjes </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/enqu-tes" title="Enquêtes">Enquêtes </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/koffiehuukske" title="Koffiehuukske">Koffiehuukske </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/digisoos" title="Activiteiten">Activiteiten </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/klachtenhoek_1" title="Klachtenhoek">Klachtenhoek </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/digisoos_1" title="Digisoos">Digisoos </a>

        </li>
    </ul>


来源: stackexchange

问:
Querying nested JSON arrays in PostgreSQL
I am currently experimenting with the JSON functionality PostgreSQL. While queries of nested key-value pair objects are very easy to query, I am having trouble querying JSON arrays. To be more specific, I have a table mytable with two columns: An integer primary key id and a JSONB column info. The JSONB data have the following structure:

```<code>{
  "modes": [
    {
      "params": [
        {"name": "x", "value": 10},
        {"name": "y", "value": 15}
      ]
    },
    {
      "params": [
        {"name": "x", "value": 20},
        {"name": "y", "value": 25}
      ]
    }
  ]
}
</code>```

I want to select all table rows that have at least one params element whose name is x and has a value between 15 and 25. A pseudo-SQL query would be:

```<code>SELECT
  *
FROM
  mytable
WHERE
  (info->'modes[*]'->'params[*]'->>'name')::TEXT = 'x'
  AND
  (info->'modes[*]'->'params[*]'->>'value')::FLOAT BETWEEN 15 AND 25;
</code>```

I am using PostgreSQL 9.6.2

答:
I assumed you want to get id of row where exists array element with mentionned values. sample:

```<code>t=# create table so40 (i int, j json);
CREATE TABLE
t=# insert into so40 select 1,'{
t'#   "modes": [
t'#     {
t'#       "params": [
t'#         {"name": "x", "value": 10},
t'#         {"name": "y", "value": 15}
t'#       ]
t'#     },
t'#     {
t'#       "params": [
t'#         {"name": "x", "value": 20},
t'#         {"name": "y", "value": 25}
t'#       ]
t'#     }
t'#   ]
t'# }';
INSERT 0 1
</code>```

select:

```<code>with f as (
        with t as (
                with j as (select * from so40)
                select *,json_array_elements(j->'modes')->'params' p from j
        )
        select *,json_array_elements(p)->>'name' n,json_array_elements(p)->>'value' v from t
)
select i,j,n,v
from f
where  n  ='x' and v::int between 15 and 25
;
 i |                  j                  | n | v
---+-------------------------------------+---+----
 1 | {                                  +| x | 20
   |   "modes": [                       +|   |
   |     {                              +|   |
   |       "params": [                  +|   |
   |         {"name": "x", "value": 10},+|   |
   |         {"name": "y", "value": 15} +|   |
   |       ]                            +|   |
   |     },                             +|   |
   |     {                              +|   |
   |       "params": [                  +|   |
   |         {"name": "x", "value": 20},+|   |
   |         {"name": "y", "value": 25} +|   |
   |       ]                            +|   |
   |     }                              +|   |
   |   ]                                +|   |
   | }                                   |   |
(1 row)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am currently experimenting with the JSON functionality PostgreSQL. While queries of nested key-value pair objects are very easy to query, I am having trouble querying JSON arrays. To be more specific, I have a table mytable with two columns: An integer primary key id and a JSONB column info. The JSONB data have the following structure:

{
  "modes": [
    {
      "params": [
        {"name": "x", "value": 10},
        {"name": "y", "value": 15}
      ]
    },
    {
      "params": [
        {"name": "x", "value": 20},
        {"name": "y", "value": 25}
      ]
    }
  ]
}

I want to select all table rows that have at least one params element whose name is x and has a value between 15 and 25. A pseudo-SQL query would be:

SELECT
  *
FROM
  mytable
WHERE
  (info->'modes[*]'->'params[*]'->>'name')::TEXT = 'x'
  AND
  (info->'modes[*]'->'params[*]'->>'value')::FLOAT BETWEEN 15 AND 25;

I am using PostgreSQL 9.6.2

Body:
I assumed you want to get id of row where exists array element with mentionned values. sample:

t=# create table so40 (i int, j json);
CREATE TABLE
t=# insert into so40 select 1,'{
t'#   "modes": [
t'#     {
t'#       "params": [
t'#         {"name": "x", "value": 10},
t'#         {"name": "y", "value": 15}
t'#       ]
t'#     },
t'#     {
t'#       "params": [
t'#         {"name": "x", "value": 20},
t'#         {"name": "y", "value": 25}
t'#       ]
t'#     }
t'#   ]
t'# }';
INSERT 0 1

select:

with f as (
        with t as (
                with j as (select * from so40)
                select *,json_array_elements(j->'modes')->'params' p from j
        )
        select *,json_array_elements(p)->>'name' n,json_array_elements(p)->>'value' v from t
)
select i,j,n,v
from f
where  n  ='x' and v::int between 15 and 25
;
 i |                  j                  | n | v
---+-------------------------------------+---+----
 1 | {                                  +| x | 20
   |   "modes": [                       +|   |
   |     {                              +|   |
   |       "params": [                  +|   |
   |         {"name": "x", "value": 10},+|   |
   |         {"name": "y", "value": 15} +|   |
   |       ]                            +|   |
   |     },                             +|   |
   |     {                              +|   |
   |       "params": [                  +|   |
   |         {"name": "x", "value": 20},+|   |
   |         {"name": "y", "value": 25} +|   |
   |       ]                            +|   |
   |     }                              +|   |
   |   ]                                +|   |
   | }                                   |   |
(1 row)


问:
Knockoutjs select with option group
Is there any way in Knockoutjs binding where I can specify optionsGroup ? something like follwoing

```<code><select data-bind="options: collection, optionsText: 'Text', optionsGroup: 'Group'/>
</code>```

Please do reply.

答:
This will also allow a placeholder:

```<code><select class="form-control needsclick" data-bind="value: Value">
  <option value="" disabled selected>Select Value...</option>
  <!-- ko foreach: Group -->
    <optgroup data-bind="attr: { label: Label }, foreach: Collection">
      <option data-bind="text: Label, value: $data"></option>
    </optgroup>
  <!-- /ko -->
</select>
</code>```

JS would be in this format:

```<code>self.Group = ko.pauseableComputed(function () {
   var groups = [
     {
       Label: 'Group 1',
       Collection: [
          { Label: 'Data 1', Value: 'Data 1' },
          { Label: 'Data 2', Value: 'Data 2' },
       ]
     },
     {
       Label: 'Group 2',
       Collection: [
          { Label: 'Data 3', Value: 'Data 3' },
          { Label: 'Data 4', Value: 'Data 4' },
       ]
     },
   ]
   return groups;
})
</code>```

This option value, could be value in this simple instance.

```<code><option data-bind="text: Label, value: Value"></option>
</code>```

But for more complex object $data would be the better option.

Title: Knockoutjs select with option group

Body:
Is there any way in Knockoutjs binding where I can specify optionsGroup ? something like follwoing

<select data-bind="options: collection, optionsText: 'Text', optionsGroup: 'Group'/>

Please do reply.

Body:
This will also allow a placeholder:

<select class="form-control needsclick" data-bind="value: Value">
  <option value="" disabled selected>Select Value...</option>
  <!-- ko foreach: Group -->
    <optgroup data-bind="attr: { label: Label }, foreach: Collection">
      <option data-bind="text: Label, value: $data"></option>
    </optgroup>
  <!-- /ko -->
</select>

JS would be in this format:

self.Group = ko.pauseableComputed(function () {
   var groups = [
     {
       Label: 'Group 1',
       Collection: [
          { Label: 'Data 1', Value: 'Data 1' },
          { Label: 'Data 2', Value: 'Data 2' },
       ]
     },
     {
       Label: 'Group 2',
       Collection: [
          { Label: 'Data 3', Value: 'Data 3' },
          { Label: 'Data 4', Value: 'Data 4' },
       ]
     },
   ]
   return groups;
})

This option value, could be value in this simple instance.

<option data-bind="text: Label, value: Value"></option>

But for more complex object $data would be the better option.


问:
SendInput while using a system command not working
I'm making a program that detects a blue color, and according to its coordinates in the screen, the mouse will move / click.

The detection works fine, but when I add a virtual keyboard with the line "system("osk")", I have encountered a problem.

When the active window was the virtual keyboard, The program stopped working in the background. I mean that the program is running, but the mouse isn't moving or clicking. And when the active window is not the virtual keyboard, everything works fine.

Can you help me to know what's wrong in my code?

This is the code that moves the mouse:

```<code>void MouseMove(int x, int y)
{
    double fScreenWidth = ::GetSystemMetrics(SM_CXSCREEN) - 1;
    double fScreenHeight = ::GetSystemMetrics(SM_CYSCREEN) - 1;
    double fx = 2 * x*(65535.0f / (fScreenWidth - 200));
    double fy = 2 * y*(65535.0f / fScreenHeight);
    INPUT Input = { 0 };
    Input.type = INPUT_MOUSE;
    Input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
    Input.mi.dx = (LONG)fx;
    Input.mi.dy = (LONG)fy;
    ::SendInput(1, &Input, sizeof(INPUT));
}
</code>```

And this is the main function where the command System("osk") is located:

```<code>int main()
{
VideoCapture cap(0);
if (!cap.isOpened())
    return -1;

system("osk"); // <-----------------------------------------
while (true)
{
    int xMouse = 0, yMouse = 0;
    float totalX = 0.0, totalY = 0.0;

    Mat frame, frame2;
    cap >> frame;
    cvtColor(frame, frame2, COLOR_BGR2HSV);
    Mat hsvImg = frame2;

    inRange(hsvImg, Scalar(78, 241, 59), Scalar(255, 255, 255), hsvImg); // Blue

    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    erode(hsvImg, hsvImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
    dilate(hsvImg, hsvImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
    dilate(hsvImg, hsvImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
    erode(hsvImg, hsvImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));

    Mat drawing = Mat::zeros(frame.size(), CV_8UC3);

    flip(drawing, drawing, 1);
    flip(frame, frame, 1);
    flip(hsvImg, hsvImg, 1);

    RNG rng(12345);
    findContours(hsvImg, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

    if (contours.size() > 0)
    {
        float sumX = 0.0, sumY = 0.0;

        for (unsigned int i = 0; i < contours.size(); i++)
        {
            for (unsigned int j = 0; j < contours[i].size(); j++)
            {
                totalX += contours[i][j].x;
                sumX++;
                totalY += contours[i][j].y;
                sumY++;
            }
        }

        if (contours.size() == 2)
        {
            LeftClick();
            cout << contours.size() << endl << endl;
        }
        else if (contours.size() == 1)
        {
            xMouse = (int)(totalX / sumX);
            yMouse = (int)(totalY / sumY);
            MouseMove(xMouse, yMouse);
        }
        else{
            cout << "Too many Contours" << endl << endl;
        }

        for (unsigned int i = 0; i < contours.size(); i++)
        {
            Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
            drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point2f(xMouse, yMouse));
        }

    }

    imshow("Drawing", drawing);
    imshow("Original", frame);

    if (waitKey(30) == 'q') //Wait 30 milisec. If user pressed ‘q’ break the loop.
        break;
}
waitKey(0);
}
</code>```

Thanks :)

答:
I found a way to fix this for those who have the same problem :)

We can instead of using the Virtual keyboard of Windows, install a VK from the internet and it will not be considered as a "System program" (if we say it like that). Then, we'll just need to open the new VK we installed with the code:

```<code>ShellExecute(NULL, "open", "VK.exe", NULL, NULL, SW_SHOWDEFAULT);
</code>```

Then the VK will open in the program and the problem is fixed ! :)

Body:
I'm making a program that detects a blue color, and according to its coordinates in the screen, the mouse will move / click.

The detection works fine, but when I add a virtual keyboard with the line "system("osk")", I have encountered a problem.

When the active window was the virtual keyboard, The program stopped working in the background. I mean that the program is running, but the mouse isn't moving or clicking. And when the active window is not the virtual keyboard, everything works fine.

Can you help me to know what's wrong in my code?

This is the code that moves the mouse:

void MouseMove(int x, int y)
{
    double fScreenWidth = ::GetSystemMetrics(SM_CXSCREEN) - 1;
    double fScreenHeight = ::GetSystemMetrics(SM_CYSCREEN) - 1;
    double fx = 2 * x*(65535.0f / (fScreenWidth - 200));
    double fy = 2 * y*(65535.0f / fScreenHeight);
    INPUT Input = { 0 };
    Input.type = INPUT_MOUSE;
    Input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE;
    Input.mi.dx = (LONG)fx;
    Input.mi.dy = (LONG)fy;
    ::SendInput(1, &Input, sizeof(INPUT));
}

And this is the main function where the command System("osk") is located:

int main()
{
VideoCapture cap(0);
if (!cap.isOpened())
    return -1;

system("osk"); // <-----------------------------------------
while (true)
{
    int xMouse = 0, yMouse = 0;
    float totalX = 0.0, totalY = 0.0;

    Mat frame, frame2;
    cap >> frame;
    cvtColor(frame, frame2, COLOR_BGR2HSV);
    Mat hsvImg = frame2;

    inRange(hsvImg, Scalar(78, 241, 59), Scalar(255, 255, 255), hsvImg); // Blue

    vector<vector<Point>> contours;
    vector<Vec4i> hierarchy;
    erode(hsvImg, hsvImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
    dilate(hsvImg, hsvImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
    dilate(hsvImg, hsvImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));
    erode(hsvImg, hsvImg, getStructuringElement(MORPH_ELLIPSE, Size(5, 5)));

    Mat drawing = Mat::zeros(frame.size(), CV_8UC3);

    flip(drawing, drawing, 1);
    flip(frame, frame, 1);
    flip(hsvImg, hsvImg, 1);

    RNG rng(12345);
    findContours(hsvImg, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0));

    if (contours.size() > 0)
    {
        float sumX = 0.0, sumY = 0.0;

        for (unsigned int i = 0; i < contours.size(); i++)
        {
            for (unsigned int j = 0; j < contours[i].size(); j++)
            {
                totalX += contours[i][j].x;
                sumX++;
                totalY += contours[i][j].y;
                sumY++;
            }
        }

        if (contours.size() == 2)
        {
            LeftClick();
            cout << contours.size() << endl << endl;
        }
        else if (contours.size() == 1)
        {
            xMouse = (int)(totalX / sumX);
            yMouse = (int)(totalY / sumY);
            MouseMove(xMouse, yMouse);
        }
        else{
            cout << "Too many Contours" << endl << endl;
        }

        for (unsigned int i = 0; i < contours.size(); i++)
        {
            Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255), rng.uniform(0, 255));
            drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point2f(xMouse, yMouse));
        }

    }

    imshow("Drawing", drawing);
    imshow("Original", frame);

    if (waitKey(30) == 'q') //Wait 30 milisec. If user pressed ‘q’ break the loop.
        break;
}
waitKey(0);
}

Thanks :)

Body:
I found a way to fix this for those who have the same problem :)

We can instead of using the Virtual keyboard of Windows, install a VK from the internet and it will not be considered as a "System program" (if we say it like that). Then, we'll just need to open the new VK we installed with the code:

ShellExecute(NULL, "open", "VK.exe", NULL, NULL, SW_SHOWDEFAULT);

Then the VK will open in the program and the problem is fixed ! :)


答: There are actually two spaces between the symbol and the name, so I guess the if statements are simply not true</p>

Title: Replacing link text with jQuery doesn't work, no errors in console


问:
High performance wcf
How do I maximize performance for my wcf service? Is it possible to take
advantage of multicore? or multi-threading?

Thanks!!

答:
Here is a related article, gives some metrics around performance so you can benchmark.

WCF Service Performance

ContentLicense: CC BY-SA 2.5

Title: High performance wcf


问:
Set router link for select list in vue js2.0
I want to set for select drop down list

<select name="educationOption" class="form-control">
          <option>
            Search for SSC Course
          </option>
          <option v-link="'/higherEducationDetails/'+ user_id">
              Search for Higher Education
          </option>
</select>```
</div>
</div>
</p>

<p>I tried this also, but not working</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code> <select name="educationOption" class="form-control">
          <option>
            Search for SSC Course
          </option>
          <option>
            <router-link :to="'/higherEducationDetails/'+ $route.params.id">
              Search for Higher Education
            </router-link>
          </option>
        </select></code>```

Any suggestion

答:
What you are trying to achieve could be done like this.

const Foo = { template: '
foo
' }
const Bar = { template: '
bar
' }

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes
})

const app = new Vue({
  router,
 data: {
    selected: ''
  },
  methods:{
   changeRoute(event){
     const path = event.target.value;
      this.$router.push({ path: `/${path}` });
    }
  }
}).$mount('#app')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div id="app">
 <select v-model="selected" @change=changeRoute($event)>
  <option disabled value="">Please select one</option>
  <option value='foo'>Foo</option>
  <option value='bar'>Bar</option>
</select>
<span>Selected: {{ selected }}</span>
  <h1>Hello App!</h1>
  <p>
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
  <router-view></router-view>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</body>
</html></code>```

Doing something like this should also work for your application.

Body:
I want to set for select drop down list

<select name="educationOption" class="form-control">
          <option>
            Search for SSC Course
          </option>
          <option v-link="'/higherEducationDetails/'+ user_id">
              Search for Higher Education
          </option>
</select>

I tried this also, but not working

 <select name="educationOption" class="form-control">
          <option>
            Search for SSC Course
          </option>
          <option>
            <router-link :to="'/higherEducationDetails/'+ $route.params.id">
              Search for Higher Education
            </router-link>
          </option>
        </select>

Any suggestion

Body:
What you are trying to achieve could be done like this.

const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes
})

const app = new Vue({
  router,
 data: {
    selected: ''
  },
  methods:{
   changeRoute(event){
     const path = event.target.value;
      this.$router.push({ path: `/${path}` });
    }
  }
}).$mount('#app')

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div id="app">
 <select v-model="selected" @change=changeRoute($event)>
  <option disabled value="">Please select one</option>
  <option value='foo'>Foo</option>
  <option value='bar'>Bar</option>
</select>
<span>Selected: {{ selected }}</span>
  <h1>Hello App!</h1>
  <p>
    <router-link to="/foo">Go to Foo</router-link>
    <router-link to="/bar">Go to Bar</router-link>
  </p>
  <router-view></router-view>
</div>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</body>
</html>

Doing something like this should also work for your application.


问:
How to detect when a image is loaded, that is provided via props, and change state in React?
I want to load a different image(fake avatar) while the final avatar image is loading. The idea is to detect when the prop image is loaded and change a state. Is it possible? Some ideas? Thank you!</p>

```<code>class ImageUser extends React.Component {

constructor(props) {
    super(props);
    this.state = {userImageLoaded: false};
    let imageSrc = "";

    if (!this.props.userImage) {
        imageSrc = this.props.noUserImage;
    } else {
        imageSrc = this.props.userImage;
    }

    this.loadingImage = <img className={styles.imageUser}
                     src={this.props.loadingImage} alt="2"/>;

    this.userImage =
        <img onLoad={this.setState({userImageLoaded: true})}
             className={styles.imageUser} src={imageSrc}
             alt="1"/>;

}

render() {
    let image = "";
    if (this.state.userImageLoaded) {
        image = this.userImage;
    } else {
        image = this.loadingImage;
    }
    return (
        <div>
            {image}
        </div>
    );
}
}

export default ImageUser;
</code>```

答:
There are several ways to do this, but the simplest is to display the final image hidden, and then flip it to visible once it loads.

JSBin Demo

```<code>class Foo extends React.Component {
  constructor(){
    super();
    this.state = {loaded: false};
  }

  render(){
    return (
      <div>
        {this.state.loaded ? null :
          <div
            style={{
              background: 'red',
              height: '400px',
              width: '400px',
            }}
          />
        }
        <img
          style={this.state.loaded ? {} : {display: 'none'}}
          src={this.props.src}
          onLoad={() => this.setState({loaded: true})}
        />
      </div>
    );
  }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to load a different image(fake avatar) while the final avatar image is loading. The idea is to detect when the prop image is loaded and change a state. Is it possible? Some ideas? Thank you!

class ImageUser extends React.Component {

constructor(props) {
    super(props);
    this.state = {userImageLoaded: false};
    let imageSrc = "";

    if (!this.props.userImage) {
        imageSrc = this.props.noUserImage;
    } else {
        imageSrc = this.props.userImage;
    }

    this.loadingImage = ;

    this.userImage =
        ;

}

render() {
    let image = "";
    if (this.state.userImageLoaded) {
        image = this.userImage;
    } else {
        image = this.loadingImage;
    }
    return (

            {image}

    );
}
}

export default ImageUser;

Body:
There are several ways to do this, but the simplest is to display the final image hidden, and then flip it to visible once it loads.

JSBin Demo

class Foo extends React.Component {
  constructor(){
    super();
    this.state = {loaded: false};
  }

  render(){
    return (
      <div>
        {this.state.loaded ? null :
          <div
            style={{
              background: 'red',
              height: '400px',
              width: '400px',
            }}
          />
        }
        <img
          style={this.state.loaded ? {} : {display: 'none'}}
          src={this.props.src}
          onLoad={() => this.setState({loaded: true})}
        />
      </div>
    );
  }
}


问:
Trying to change the content of a page without reloading after passing a value to a variable on submit
Retrieving data from an API using Php. This my code:

```<code><?php
if(isset($_POST['search']))
{
    $login = 'something';
    $password = 'something';
    $query = urlencode( $_POST[ "search"]);
    $url = 'something' . $query;;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, $login . ":" . $password);
    $result = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($result, true);

    foreach ($output['response']['customers']['customer'] as $r)
        {
            $inner = $r['lifetime_points'];
        };
 }
  else
 {
      echo ("No search query has received");
 }
?>
</code>```

Html code:

```<code> <div id="get_text" >
<div><em>CHECK YOUR POINTS</em></div>
<div ><em>Enter mobile number</em></div>
<form action='' method='POST' id='search-form'>
<div>
<input type='search' name='search' id="sub1" />
</div>
<div>
<button type="submit"  id="sub" >Submit</button>
</div>
</form>
</div>

<div id="show_text" >
<div><em>YOUR CURRENT POINTS ARE </em></div>
<form action='' method='GET' id='result'>
<div>
<input type='text' name='points' value="<?php echo $inner; ?>"/>
</div>
</form>
</div>
</code>```

So through AJAX I'm initially displaying my div tag with ID=get_text in which I'm retrieving data from an API and storing it in a variable after pressing submit. After pressing submit I'm hiding the div tag with id=get_text and displaying the div tag with id=show_text.

```<code> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script type="text/javascript">
     $(document).ready(function () {
    $("#show_text").hide();
    $("#sub").on("click", function (e) {
        e.preventDefault();
        $.ajax({
            url: 'aristocracy-test.php',
            method: 'POST',
            data : $("#get_text").serialize(), //pass your form elements as key-value pairs
            success: function (response) {
                $("#show_text").show();
                $("#get_text").hide();
            }
        });
    });
});
 </script>
</code>```

The problem I'm facing is that the value is not getting passed to div tag with ID=show_text after pressing the submit button on hiding the div tag with id=get_text. There isn't anything wrong with my API code, as I have tested it before implementing AJAX.

答: Please Check your Data posted to server ,Data Returned from server in Browser console .

Body:
Retrieving data from an API using Php. This my code:

<?php
if(isset($_POST['search']))
{
    $login = 'something';
    $password = 'something';
    $query = urlencode( $_POST[ "search"]);
    $url = 'something' . $query;;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    curl_setopt($ch, CURLOPT_USERPWD, $login . ":" . $password);
    $result = curl_exec($ch);
    curl_close($ch);
    $output = json_decode($result, true);

    foreach ($output['response']['customers']['customer'] as $r)
        {
            $inner = $r['lifetime_points'];
        };
 }
  else
 {
      echo ("No search query has received");
 }
?>

Html code:

CHECK YOUR POINTS

Enter mobile number

<form action='' method='POST' id='search-form'>

<input type='search' name='search' id="sub1" />

<button type="submit"  id="sub" >Submit</button>

</form>

YOUR CURRENT POINTS ARE

<form action='' method='GET' id='result'>

<input type='text' name='points' value="<?php echo $inner; ?>"/>

</form>

So through AJAX I'm initially displaying my div tag with ID=get_text in which I'm retrieving data from an API and storing it in a variable after pressing submit. After pressing submit I'm hiding the div tag with id=get_text and displaying the div tag with id=show_text.

The problem I'm facing is that the value is not getting passed to div tag with ID=show_text after pressing the submit button on hiding the div tag with id=get_text. There isn't anything wrong with my API code, as I have tested it before implementing AJAX.


问:
Proper placement of q.all inside array.map with _.forEach
I have the following code which searches my mongodb using find() using values extracted using array.map. Said search returns an object, which I then used a _.forEach to extract the values.

I used this article as basis, however the difference between his examples and mine was he used only one loop. I'm using two. In this case, where should I put my q.all()?

Here's my code. Please note that is server-side:

```<code>'use strict';
var q = require('q');

exports.downloadEmployee = function (req, res) {
    var tempCtr = [];

    if (req.params.hasdr === "yes") {
        return queries.generateDirectReportsCSV(req.params.id).then(function (directReports) {
            return directReports;
        }).then(function (directReports) {
            var empIDcoll = _.pluck(directReports.Data, "employeenumber");
            return empIDcoll;
        }).then(function (empIDcoll) {
            var promises = [];

            empIDcoll.map(function (id) {

                return EmployeeInfo.find({ employeeID: id }, function (err, results) {
                    if (err) { return err; }

                    _.forEach(results, function (item) {
                        if (item) {
                            tempCtr.push({
                                employeeID: item.employeeID,
                                employeeName: item.employeeName
                            });
                            promises.push(tempCtr);
                        }
                    });
                });

                q.all(promises).then(function (results) {
                    return res.json(results);
                });
            });
        });
    }
</code>```

When I run this, I don't get any result back.

Any answers will be greatly appreciated.

Thank you.

UPDATE: I've decided to revise my code and replaced array.map with the usual for loop:

```<code>.then(function (empIDcoll) {

    for (var i = 0; i <= empIDcoll.length - 1; i++) {
        var promise = EmployeeInfo.find({ employeeID: empIDcoll[i] }, function (err, results) {
            if (err) { return err; }

            _.forEach(results, function (item) {
                if (item) {
                    tempCtr.push({
                        employeeID: item.employeeID,
                        employeeName: item.employeeName,
                        currentShift: item.currentShift,
                        isOpenToIntlAssignment: item.isOpenToIntlAssignment,
                        desiredRole1: item.desiredRole1,
                        desiredRole2: item.desiredRole2,
                        desiredRole3: item.desiredRole3,
                        desiredRoleOther: item.desiredRoleOther,
                        passportInfo: item.passportInfo,
                        visaInfo: item.visaInfo,
                        yrsInIT: item.yrsInIT,
                        yrsAsCustomerPM: item.yrsAsCustomerPM,
                        yrsAsCustomerProgM: item.yrsAsCustomerProgM,
                        primaryDomain: item.primaryDomain,
                        primaryDomainOther: item.primaryDomainOther,
                        primaryIndustry: item.primaryIndustry,
                        primaryIndustryOther: item.primaryIndustryOther,
                        isPMPCertified: item.isPMPCertified,
                        pmpCertExpiryDate: item.pmpCertExpiryDate,
                        isPGMPCertified: item.isPGMPCertified,
                        pgmpCertExpiryDate: item.pgmpCertExpiryDate,
                        isScrumCertified: item.isScrumCertified,
                        scrumCertExpiryDate: item.scrumCertExpiryDate,
                        biggestProjectTCV: item.biggestProjectTCV,
                        biggestTeamSizeManaged: item.biggestTeamSizeManaged,
                        avgTeamSizeManaged: item.avgTeamSizeManaged,
                        biggestBilledFTE: item.biggestBilledFTE,
                        avgBilledFTE: item.avgBilledFTE
                    });
                }
            });
        });
        promises.push(promise);
    }

    return q.all(promises).then(function(data){
        return res.json(data);
    });

});
</code>```

...but it's still not returning anything. What am I doing wrong?

答:
Just look, </p>

```<code>var promises = questions.map(function(question) {

        return $http({
            url   : 'upload/question',
            method: 'POST',
            data  : question
        });

    });

    return $q.all(promises);
</code>```

Body:
I have the following code which searches my mongodb using find() using values extracted using array.map. Said search returns an object, which I then used a _.forEach to extract the values.

I used this article as basis, however the difference between his examples and mine was he used only one loop. I'm using two. In this case, where should I put my q.all()?

Here's my code. Please note that is server-side:

'use strict';
var q = require('q');

exports.downloadEmployee = function (req, res) {
    var tempCtr = [];

    if (req.params.hasdr === "yes") {
        return queries.generateDirectReportsCSV(req.params.id).then(function (directReports) {
            return directReports;
        }).then(function (directReports) {
            var empIDcoll = _.pluck(directReports.Data, "employeenumber");
            return empIDcoll;
        }).then(function (empIDcoll) {
            var promises = [];

            empIDcoll.map(function (id) {

                return EmployeeInfo.find({ employeeID: id }, function (err, results) {
                    if (err) { return err; }

                    _.forEach(results, function (item) {
                        if (item) {
                            tempCtr.push({
                                employeeID: item.employeeID,
                                employeeName: item.employeeName
                            });
                            promises.push(tempCtr);
                        }
                    });
                });

                q.all(promises).then(function (results) {
                    return res.json(results);
                });
            });
        });
    }

When I run this, I don't get any result back.

Any answers will be greatly appreciated.

Thank you.

UPDATE: I've decided to revise my code and replaced array.map with the usual for loop:

.then(function (empIDcoll) {

    for (var i = 0; i <= empIDcoll.length - 1; i++) {
        var promise = EmployeeInfo.find({ employeeID: empIDcoll[i] }, function (err, results) {
            if (err) { return err; }

            _.forEach(results, function (item) {
                if (item) {
                    tempCtr.push({
                        employeeID: item.employeeID,
                        employeeName: item.employeeName,
                        currentShift: item.currentShift,
                        isOpenToIntlAssignment: item.isOpenToIntlAssignment,
                        desiredRole1: item.desiredRole1,
                        desiredRole2: item.desiredRole2,
                        desiredRole3: item.desiredRole3,
                        desiredRoleOther: item.desiredRoleOther,
                        passportInfo: item.passportInfo,
                        visaInfo: item.visaInfo,
                        yrsInIT: item.yrsInIT,
                        yrsAsCustomerPM: item.yrsAsCustomerPM,
                        yrsAsCustomerProgM: item.yrsAsCustomerProgM,
                        primaryDomain: item.primaryDomain,
                        primaryDomainOther: item.primaryDomainOther,
                        primaryIndustry: item.primaryIndustry,
                        primaryIndustryOther: item.primaryIndustryOther,
                        isPMPCertified: item.isPMPCertified,
                        pmpCertExpiryDate: item.pmpCertExpiryDate,
                        isPGMPCertified: item.isPGMPCertified,
                        pgmpCertExpiryDate: item.pgmpCertExpiryDate,
                        isScrumCertified: item.isScrumCertified,
                        scrumCertExpiryDate: item.scrumCertExpiryDate,
                        biggestProjectTCV: item.biggestProjectTCV,
                        biggestTeamSizeManaged: item.biggestTeamSizeManaged,
                        avgTeamSizeManaged: item.avgTeamSizeManaged,
                        biggestBilledFTE: item.biggestBilledFTE,
                        avgBilledFTE: item.avgBilledFTE
                    });
                }
            });
        });
        promises.push(promise);
    }

    return q.all(promises).then(function(data){
        return res.json(data);
    });

});

...but it's still not returning anything. What am I doing wrong?

Body:
Just look,

var promises = questions.map(function(question) {

        return $http({
            url   : 'upload/question',
            method: 'POST',
            data  : question
        });

    });

    return $q.all(promises);


问:
Dataframe not showing in Pycharm
I am using PyCharm 2016.2.1 . When I try to view a Pandas dataframe through the newly added feature 'View as DataFrame' in the debugger, this works as expected for a small (e.g. 4x4) DataFrame.

However when I try to view a DataFrame (generated by custom script) of ~10,000 rows x ~50 columns, I get the message: "Nothing to show".

When I run the same script (that generates the DataFrame) in Spyder, I am able to view it, so I am pretty sure it's not an error in my script.

Does anyone know if there is a maximum size to the DataFrames that can be viewed in PyCharm, and if there is a way to change this?

EDIT:

It seems that the maximum size allowed is 1000 x 15 , as in some cases it gets truncated to this size (when the number of rows is too large, but when there are too many columns pycharm just says 'nothing to show').

Still, I would like to know if there is a way to increase the maximum allowed rows and columns viewable through the DataFrame viewer.

答:
In the case that you don't strictly need to use the functionalities given by the DataFrame viewer, you can print the whole DataFrame in the output window, using:</p>

```<code>def print_full(x):
    pd.set_option('display.max_rows', len(x))
    print(x)
    pd.reset_option('display.max_rows')
</code>```

Title: Dataframe not showing in Pycharm

Body:
In the case that you don't strictly need to use the functionalities given by the DataFrame viewer, you can print the whole DataFrame in the output window, using:

def print_full(x):
    pd.set_option('display.max_rows', len(x))
    print(x)
    pd.reset_option('display.max_rows')


问:
How to execute Vim substitute command without effect the current searching pattern?
I want to jump to the lines containing certain pattern and determine whether or not to apply :s command.

But after applying :s command, the '/' register was replaced by the pattern in the :s command,
and it wasn't very convenient to jump with original pattern.

So, does it have a comfortable way to achieve this task?

Thanks!

答:
You can achieve that via vim-script. Something on these lines should help :</p>

```<code>function! s:CustomSearch()
    let oldsearch = @/
    :%s/pattern/replace/flags
    let @/=oldsearch
endfunction
</code>```

Body:
You can achieve that via vim-script. Something on these lines should help :

function! s:CustomSearch()
    let oldsearch = @/
    :%s/pattern/replace/flags
    let @/=oldsearch
endfunction


问:
Validation not working on Ranges?
Can someone explain to me why my validation won't get triggered when I submit a string such as "foo" to number?

```<code>class Course < ActiveRecord::Base

  validates :number, :inclusion => 0..100

end
</code>```

Only when I change my code to this...

```<code>class Course < ActiveRecord::Base

  validates :number, :inclusion  => 0..100, :numericality => true

end
</code>```

... the validation gets triggered.

Is this a Rails bug or am I missing something really fundamental here?

I am using Rails 4.2.0 by the way.

答:
Please try this:

```<code>validates_numericality_of :number, :only_integer => true,
 :greater_than_or_equal_to => 1,
 :less_than_or_equal_to => 99,
 :message => "can only be number between 1 and 100."
</code>```

ref: http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_numericality_of

Title: Validation not working on Ranges?

Body:
Can someone explain to me why my validation won't get triggered when I submit a string such as "foo" to number?

class Course < ActiveRecord::Base

  validates :number, :inclusion => 0..100

end

Only when I change my code to this...

class Course < ActiveRecord::Base

  validates :number, :inclusion  => 0..100, :numericality => true

end

... the validation gets triggered.

Is this a Rails bug or am I missing something really fundamental here?

I am using Rails 4.2.0 by the way.

Body:
Please try this:

validates_numericality_of :number, :only_integer => true,
 :greater_than_or_equal_to => 1,
 :less_than_or_equal_to => 99,
 :message => "can only be number between 1 and 100."

ref: http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_numericality_of


问:
Webpage won't parse PHP code
I'm trying to add some of my own PHP to a nearly-unreadable template file on a forum system. I know it all works perfectly as far as the server config, etc. goes, but PHP simply doesn't parse on this page. JS works fine. Any ideas? It's a simple .html page.</p>

答:
A lot of template systems use their own coding syntax. If this is the case it will not be possible to include PHP code in your template without opening up a lot of security holes.

Try to learn the specific templating language used, or find out where you should put the code without changing the template file (there may be a controller or plugin system built for such stuff).

Title: Webpage won't parse PHP code


答:
Use his. This snippet is working

$(".btn").on("click", function() {
 $("a").filter(function(index) {
     if($(this).text().includes("Nieuws")) {
          var text = $(this).text()
          $(this).text(text.replace("Nieuws", "News"))
          }

   });
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu">
        <li class="selected">
            Home
        </li>
        <li>
            Nieuws  ▼

            <ul style="display: none;" id="subMenu3393">
                <li>
                    - Wooninc.
                </li>
                <li>
                    - Request maintenance
                </li>
            </ul>
         </li>
        <li>
            SamenVeilig

         </li>
        <li>
            Agenda

         </li>
        <li>
            Vraag & aanbod  ▼

            <ul style="display: none;" id="subMenu3396">
                <li>
                    - Goods/services
                </li>
                <li>
                    - Caregiving/intensive support
                </li>
            </ul>
         </li>
        <li>
            Informatie  ▼

             <ul style="display: none;" id="subMenu3397">
                <li>
                    - Important phone numbers
                </li>
            </ul>
         </li>
        <li>
            Fotoalbum

         </li>
        <li>
            Chat

         </li>
        <li>
            Spelletjes

         </li>
        <li>
            Enquêtes

         </li>
        <li>
            Koffiehuukske

         </li>
        <li>
            Activiteiten

         </li>
        <li>
            Klachtenhoek

         </li>
        <li>
            Digisoos

        </li>
    </ul>

<button class="btn">Change</button></code>```

Body:
There's a website that really wants to be bi-lingual even though the CMS doesn't support it. The system buttons can all be in English or Dutch but the content itself not. So they just write articles that have both the English and Dutch text.

Now I know, this is a trainwreck. But this is what the client wants so it's what he gets. I just don't have access to the CMS so I can't do this properly.

Now, to translate the menu buttons I perform a check if the title of a certain element is "Terms of Service" or "Regelement" which tells me if the website is in Dutch or English. I then have an each function that runs through all the li elements in the menu, checking if the text matches with one of the texts I need to translate, so basically:

if ($(this).text() == 'Nieuws') {
    $(this).text('News');
}

This used to work, but after recently adding in a language switch button at the top of the website the menu's aren't translated anymore, just the sub menu's. The code runs fine, no errors, and I even put a few alerts in to check if it was detecting the language properly, etc. That all works fine.

For some reason only the submenu's get translated now. The jQuery is of course executed at the end of the page, after the content loads. The website in question is https://www.onsplatform.tv/genderhof/ but you can only see the "Vraag & aanbod" button there.

// for snippet purposes
var setlanguage = 'en';

// If language of user is English
if (setlanguage == 'en') {

 // Loop through each main level menu
 $("#menu li a").each(function(){
  // Set text of menu item to variable
  var tempmenutxt = $(this).text();

  // Translate text of menu item if match is found
  if (tempmenutxt == 'Nieuws ▼') { $(this).text('News ▼'); }
   else if (tempmenutxt == 'SamenVeilig') { $(this).text("Camera's"); }
   else if (tempmenutxt == 'Vraag & aanbod ▼') { $(this).text('Marketplace ▼'); }
   else if (tempmenutxt == 'Informatie ▼') { $(this).text('Information ▼'); }
   else if (tempmenutxt == 'Fotoalbum') { $(this).text("Photo's"); }
   else if (tempmenutxt == 'Spelletjes') { $(this).text("Games"); }
   else if (tempmenutxt == 'Enquêtes') { $(this).text("Polls"); }
   else if (tempmenutxt == 'Koffiehuukske') { $(this).text("Coffeecorner"); }
   else if (tempmenutxt == 'Activiteiten') { $(this).text("Activities"); }
   else if (tempmenutxt == 'Klachtenhoek') { $(this).text("Complaints"); }
 });
 // Because "display: none;" items can't be read, make all submenu's visible
 $("#menu li ul").each(function(){
  $(this).css("display","block");
 });
 // Translate text of menu item if match is found
 $("#menu li ul li a").each(function(){
  var tempmenutxt = $(this).text();
  if (tempmenutxt == '- Onderhoud aanvragen') { $(this).text('- Request maintenance'); }
   else if (tempmenutxt == '- Goederen/diensten') { $(this).text("- Goods/services"); }
   else if (tempmenutxt == '- Mantelzorg / I.B.') { $(this).text("- Caregiving/intensive support"); }
   else if (tempmenutxt == '- Belangrijke telefoonnummers') { $(this).text("- Important phone numbers"); }
 });
 // Make all submenu invisible again
 $("#menu li ul").each(function(){
  $(this).css("display","none");
 });
}

/* This CSS is just to illustrate, don't mind it, quick and dirty */

#menu {
  width: 100%;
  list-style: none;
  margin: 0;
  padding: 0;
  background: #FF0000;
}

#menu li {
  display: inline-block;
  position: relative;
  padding: 0;
}

#menu li a {
  display: inline-block;
  height: 30px;
  line-height: 30px;
  padding: 0 10px;
  color: #FFF;
}

#menu li ul {
  display: none;
  width: auto;
  position: absolute;
  top: 30px;
  background: #000;
  z-index: 1000;
  list-style: none;
  margin: 0;
  padding: 0;
}

#menu li:hover ul {
  display: block !important;
}

#menu li ul li {
  display: block;
}

            Home

            Nieuws  ▼

                    - Wooninc.

                    - Request maintenance

            SamenVeilig

            Agenda

            Vraag & aanbod  ▼

                    - Goods/services

                    - Caregiving/intensive support

            Informatie  ▼

                    - Important phone numbers

            Fotoalbum

            Chat

            Spelletjes

            Enquêtes

            Koffiehuukske

            Activiteiten

            Klachtenhoek

            Digisoos

Body:
Use his. This snippet is working

$(".btn").on("click", function() {
 $("a").filter(function(index) {
     if($(this).text().includes("Nieuws")) {
          var text = $(this).text()
          $(this).text(text.replace("Nieuws", "News"))
          }

   });
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="menu">
        <li class="selected">
            <a href="/genderhof/">Home</a>
        </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/nieuws" title="Nieuws">Nieuws  ▼</a>

            <ul style="display: none;" id="subMenu3393">
                <li>
                    <a href="https://www.onsplatform.tv/genderhof/wooninc" title="- Wooninc.">- Wooninc.</a>
                </li>
                <li>
                    <a href="https://www.onsplatform.tv/genderhof/CommunityUser/SendGroupMail/740" title="- Onderhoud aanvragen">- Request maintenance</a>
                </li>
            </ul>
         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/samenveilig" title="SamenVeilig">SamenVeilig </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/agenda" title="Agenda">Agenda </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/marktplaats" title="Vraag &amp; aanbod">Vraag &amp; aanbod  ▼</a>

            <ul style="display: none;" id="subMenu3396">
                <li>
                    <a href="https://www.onsplatform.tv/genderhof/goederen-diensten" title="- Goederen/diensten">- Goods/services</a>
                </li>
                <li>
                    <a href="https://www.onsplatform.tv/genderhof/mantelzorg---i-b" title="- Mantelzorg / I.B.">- Caregiving/intensive support</a>
                </li>
            </ul>
         </li>
        <li>
            <a href="#" title="Informatie">Informatie  ▼</a>

             <ul style="display: none;" id="subMenu3397">
                <li>
                    <a href="https://www.onsplatform.tv/genderhof/belangrijke-telefoonnummers_1" title="- Belangrijke telefoonnummers">- Important phone numbers</a>
                </li>
            </ul>
         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/fotoalbum" title="Fotoalbum" tmp_title="Fotoalbum">Fotoalbum </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/chat" title="Chat" tmp_title="Chat">Chat </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/spelletjes" title="Spelletjes">Spelletjes </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/enqu-tes" title="Enquêtes">Enquêtes </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/koffiehuukske" title="Koffiehuukske">Koffiehuukske </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/digisoos" title="Activiteiten">Activiteiten </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/klachtenhoek_1" title="Klachtenhoek">Klachtenhoek </a>

         </li>
        <li>
            <a href="https://www.onsplatform.tv/genderhof/digisoos_1" title="Digisoos">Digisoos </a>

        </li>
    </ul>

<button class="btn">Change</button>


问:
dispatch_after - GCD in Swift?
I've gone through the iBook from Apple, and couldn't find any definition of it:

Can someone explain the structure of dispatch_after?

```<code>dispatch_after(<#when: dispatch_time_t#>, <#queue: dispatch_queue_t?#>, <#block: dispatch_block_t?#>)
</code>```

答:
This worked for me.

Swift 3:

```<code>let time1 = 8.23
let time2 = 3.42

// Delay 2 seconds

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
    print("Sum of times: \(time1 + time2)")
}
</code>```

Objective-C:

```<code>CGFloat time1 = 3.49;
CGFloat time2 = 8.13;

// Delay 2 seconds

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    CGFloat newTime = time1 + time2;
    NSLog(@"New time: %f", newTime);
});
</code>```

Title: dispatch_after - GCD in Swift?

Body:
I've gone through the iBook from Apple, and couldn't find any definition of it:

Can someone explain the structure of dispatch_after?

dispatch_after(<#when: dispatch_time_t#>, <#queue: dispatch_queue_t?#>, <#block: dispatch_block_t?#>)

Body:
This worked for me.

Swift 3:

let time1 = 8.23
let time2 = 3.42

// Delay 2 seconds

DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
    print("Sum of times: \(time1 + time2)")
}

Objective-C:

CGFloat time1 = 3.49;
CGFloat time2 = 8.13;

// Delay 2 seconds

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    CGFloat newTime = time1 + time2;
    NSLog(@"New time: %f", newTime);
});


问:
Data structures for bioinformatics
What are some data structures that should be known by somebody involved in bioinformatics? I guess that anyone is supposed to know about lists, hashes, balanced trees, etc., but I expect that there are domain specific data structures. Is there any book devoted to this subject?</p>

答:
The most fundamental data structure used in bioinformatics is string. There are also a whole range of different data structures representing strings. And algorithms like string matching are based on the efficient representation/data structures.

A comprehensive work on this is Dan Gusfield's Algorithms on Strings, Trees and Sequences

Title: Data structures for bioinformatics


问:
What should be a component?
I am struggling with myself about what needs to be a component?

For example:

I have a page where everything within is relevant only to itself.

I have a text input on every form control; Do I need to wrap this in a component? But every place will need a different kind of validation and other stuff related only to it, so why do this?

Usually, when it comes to forms, only the style is the same so why we need to wrap this in a component? We can just share the style with CSS.

答:
Reasons where you will want to split into a component:

Reuse code across multiple files/parts of your code.

Encapsulate the complexity of certain code so that fellow developers can use it without needing to understand its implementation details; just need to look at props.

You need to do stuff within specific lifecycle hooks, e.g. do certain stuff in componentDidUpdate when the component updates.

You want to optimize the rendering and have to implement shouldComponentUpdate for certain parts of your code.

Title: What should be a component?


问:
How nginx webserver is configured in open edx Cypress
I went through the etc/nginx/sites-available/default file but didn't find the configuration setup. In many Documentations explained about application but not how the webserver is configured.

https://openedx.atlassian.net/wiki/display/OpenOPS/Open+edX+Operations+Home

http://edx.readthedocs.io/projects/edx-installing-configuring-and-running/en/latest/index.html

答: Open Edx Customized the web server setup within the project folder of openedx ie. After installation of full stack instance. The directory structure as Follows: /etc/nginx/sites-enabled/ have link to another directory as follows: /edx/app/nginx/site-available/ have the lms, cms, xqueue etc.


问:
Modelling a Meals / Recipes / Foods database
I am trying to model a database containing the following tables:

```<code>Meals (MealId)
MealRecipes (MealId, RecipeId)
MealFoods (MealId, FoodId)

Recipes (RecipeId)
RecipeFoods (RecipeId, FoodId)
Foods (FoodId)
</code>```

A Recipe is composed of N Foods (Apple, Salmon, ...)

But when I build a Meal it can contain Recipes (Salmond with vegetables) but also a Food (Apple) ...

My biggest problem is with building the Meal with both Recipes and Foods.

UPDATE

One important thing is the order of the Recipes / Food in a Meal. So another approach would be:

```<code>Meals (MealId)
MealSteps (MealId, StepNumber, RecipeId, FoodId)
</code>```

Where RecipeId or FoodId, either one, could be null. But not both.

答:
Your solution looks fine. A meal is composed of different recipies (e.g. one for the main dish, one for the salad) plus single food (e.g. an apple for dessert).

Another way to model this would be to drop the table MealFoods and make one-food recipies instead. (E.g. an apple by itself is a "recipe" for a simple dessert. Salt on the other hand is not.)

So with this model you even prevent some food to be added to a meal. You could do the same with a mere flag in Foods in your model, too, that allows apple to be added to a meal and salt not. But that would rely on you to consider the flag whenever inserting into MealFoods, whereas in the second model you can only add recipes to meals, which makes this safer.

UPDATE: Here is the proposed model. You see, I've only removed one table. (And I put in the position you have added in yor update). The trick is that you build some "recipes" that have only a single entry in RecipeFoods, e.g. an apple.

Meals (MealId)

MealRecipes (MealId, RecipeId, position)

Recipes (RecipeId)

RecipeFoods (RecipeId, FoodId)

Foods (FoodId)

Body:
I am trying to model a database containing the following tables:

Meals (MealId)
MealRecipes (MealId, RecipeId)
MealFoods (MealId, FoodId)

Recipes (RecipeId)
RecipeFoods (RecipeId, FoodId)
Foods (FoodId)

A Recipe is composed of N Foods (Apple, Salmon, ...)

But when I build a Meal it can contain Recipes (Salmond with vegetables) but also a Food (Apple) ...

My biggest problem is with building the Meal with both Recipes and Foods.

UPDATE

One important thing is the order of the Recipes / Food in a Meal. So another approach would be:

Meals (MealId)
MealSteps (MealId, StepNumber, RecipeId, FoodId)

Where RecipeId or FoodId, either one, could be null. But not both.


问:
How to get distinct data from two tables using SQL Select query
How to get distinct data from two tables using SQL Select query. I need to know how many users started innovation but need distinct data. The below following are two tables. Table_UserInformation is basic registration table, after login he can add many innovations but registration only one for one email id.

Table_UserInformation

```<code>Name      Email             mobile
mazhar    mazar@gmail.com   720000000
rahul     rahul@gmail.com   992000000
raj       raj@gmail.com     700000000
</code>```

Table_Innovation

```<code>Email             Data1                Data2
mazar@gmail.com   aim to achive LD     NA
mazar@gmail.com   Search for LD        NA
rahul@gmail.com   mind tech            Techno
</code>```

I want to know how many users started innovations counts and details like below 2 outputs need.

output: How many users started Innovation base on email need counts.

```<code>counts
 2
</code>```

output: How many users started Innovation base on email need details of users.

```<code> Name      Email             mobile
 mazhar    mazar@gmail.com   720000000
 rahul    rahul@gmail.com   992000000
</code>```

答:
You can try something like this:

```<code>  SELECT
   a.[Name]
  ,a.[Email]
  ,a.[Mobile]
  ,(select count(b.Email) from Table_Innovation as b where b.Email = a.Email)
    as 'Innovat ion Count'
 FROM Table_UserInformation as a
</code>```

Your Result should like this:
Result

Greetz
K4ckr31z

Body:
How to get distinct data from two tables using SQL Select query. I need to know how many users started innovation but need distinct data. The below following are two tables. Table_UserInformation is basic registration table, after login he can add many innovations but registration only one for one email id.

Table_UserInformation

Name      Email             mobile
mazhar    mazar@gmail.com   720000000
rahul     rahul@gmail.com   992000000
raj       raj@gmail.com     700000000

Table_Innovation

Email             Data1                Data2
mazar@gmail.com   aim to achive LD     NA
mazar@gmail.com   Search for LD        NA
rahul@gmail.com   mind tech            Techno

I want to know how many users started innovations counts and details like below 2 outputs need.

output: How many users started Innovation base on email need counts.

counts
 2

output: How many users started Innovation base on email need details of users.

 Name      Email             mobile
 mazhar    mazar@gmail.com   720000000
 rahul    rahul@gmail.com   992000000

Body:
You can try something like this:

  SELECT
   a.[Name]
  ,a.[Email]
  ,a.[Mobile]
  ,(select count(b.Email) from Table_Innovation as b where b.Email = a.Email)
    as 'Innovat ion Count'
 FROM Table_UserInformation as a

Your Result should like this:
Result

Greetz
K4ckr31z


问:
Cumulatively count how many times a condition has ocurred in a row
In a data.table (or a data.frame), how can I count "cumulatively" how many times such condition has occurred in a row?

To illustrate,

```<code>DT <- data.table(A=c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                 B=c(1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1))
</code>```

If I would like to add a column C that indicates

if (A==B), add 1 to the value above current row.

if (A!=B), start again with 0

So the answer would be

```<code>DT <- data.table(A=c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                 B=c(1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1),
                 C=c(1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 1)]
</code>```

It seems simple but I can't seem to do it. I'm guessing that it could build on something like this?

```<code>DT[,C:=ifelse(A==B, ??, 0)]
</code>```

Also, I'm afraid it may be a duplicate question but can't seen to find it.

Body:
In a data.table (or a data.frame), how can I count "cumulatively" how many times such condition has occurred in a row?

To illustrate,

DT <- data.table(A=c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                 B=c(1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1))

If I would like to add a column C that indicates

if (A==B), add 1 to the value above current row.

if (A!=B), start again with 0

So the answer would be

DT <- data.table(A=c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1),
                 B=c(1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1),
                 C=c(1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 1)]

It seems simple but I can't seem to do it. I'm guessing that it could build on something like this?

DT[,C:=ifelse(A==B, ??, 0)]

Also, I'm afraid it may be a duplicate question but can't seen to find it.

Body:
We can do this using rleid to create a grouping variable on 'B', then multiply the sequence of rows with 'B' to create the 'C'

DT[, C := seq_len(.N)*B, .(A, rleid(B))]
DT
#    A B C
# 1: 1 1 1
# 2: 1 0 0
# 3: 1 1 1
# 4: 1 1 2
# 5: 1 0 0
# 6: 1 1 1
# 7: 1 1 2
# 8: 1 1 3
# 9: 1 0 0
#10: 1 1 1
#11: 1 1 2
#12: 1 1 3
#13: 1 1 4
#14: 1 0 0
#15: 1 1 1


问:
C# udpclient.send to fake ip too slow to complete
when i udpclient.send to an fake/unknown ip, the process took a long time to complete(about 2 seconds per call. for 1000 calls it took about 2000 seconds). if i udpclient.send to a known ip, sending 1000 packets took less than 2 seconds.

i was using send for development and this kind of things makes development process took a long time. is there a way to prevent this slowdown? fyi, i did put ip address(not hostname to prevent dns resolve), i did try use udpclient.connect but the problem still persist.

thanks.

答:
As you have guessed by now, this is  DNS problem.

In your local machine, you could write in /etc/hosts (assuming you are developing on Linux), an entry like:

```<code>192.168.1.20    target-develop
</code>```

then the resolution of name "target-develop" will take only a moment.

EDIT

If you send packets to unknown/fake IP and it takes long time, it could be a firewall's configuration problem.

Body:
As you have guessed by now, this is  DNS problem.

In your local machine, you could write in /etc/hosts (assuming you are developing on Linux), an entry like:

192.168.1.20    target-develop

then the resolution of name "target-develop" will take only a moment.

EDIT

If you send packets to unknown/fake IP and it takes long time, it could be a firewall's configuration problem.


问:
Change Text View on button click in ViewPager
I have used a viewpager in my app in which i have a number of pagers. In this pages i have a TextView and a Button and i want to be able to change the textview in the one pager when the button in that pager is clicked.

I have the code below, but the text doesn't change when i click on the button.

```<code>@Override
public Object instantiateItem(ViewGroup collection, int position) {
    View view = null;
    LayoutInflater h = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = h.inflate(R.layout.content, null);

    tvName = (TextView) view.findViewById(R.id.tvName);
    btnView = (Button) view.findViewById(R.id.viewBTN);
    tvName.setText("Original Text")

    btnView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            tvName.setText("new Test")
        }
    });

    collection.addView(view);

    return view;

}
</code>```

答:
just put this line</p>

```<code>view.btnView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        view.tvName.setText("new Test")
    }
});
</code>```

Body:
I have used a viewpager in my app in which i have a number of pagers. In this pages i have a TextView and a Button and i want to be able to change the textview in the one pager when the button in that pager is clicked.

I have the code below, but the text doesn't change when i click on the button.

@Override
public Object instantiateItem(ViewGroup collection, int position) {
    View view = null;
    LayoutInflater h = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = h.inflate(R.layout.content, null);

    tvName = (TextView) view.findViewById(R.id.tvName);
    btnView = (Button) view.findViewById(R.id.viewBTN);
    tvName.setText("Original Text")

    btnView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            tvName.setText("new Test")
        }
    });

    collection.addView(view);

    return view;

}

Body:
just put this line

view.btnView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        view.tvName.setText("new Test")
    }
});


问:
AngularJS ui-router login authentication
I am new to AngularJS, and I am a little confused of how I can use angular-"ui-router" in the following scenario:

I am building a web application which consists of two sections. The first section is the homepage with its login and signup views, and the second section is the dashboard (after successful login).

I have created an index.html for the home section with its angular app and ui-router config to handle /login and /signup views,
and there is another file dashboard.html for the dashboard section with its app and ui-router config to handle many sub views.

Now I finished the dashboard section and don't know how to combine the two sections with their different angular apps. How could I tell the home app to redirect to the dashboard app?

答:
Use $http Interceptor

By using an $http interceptor you can send headers to Back-end or the other way around and do your checks that way.

Great article on $http interceptors

Example:

```<code>$httpProvider.interceptors.push(function ($q) {
        return {
            'response': function (response) {

                // TODO Create check for user authentication. With every request send "headers" or do some other check
                return response;
            },
            'responseError': function (reject) {

                // Forbidden
                if(reject.status == 403) {
                    console.log('This page is forbidden.');
                    window.location = '/';
                // Unauthorized
                } else if(reject.status == 401) {
                    console.log("You're not authorized to view this page.");
                    window.location = '/';
                }

                return $q.reject(reject);
            }
        };
    });
</code>```

Put this in your .config or .run function.

Body:
Use $http Interceptor

By using an $http interceptor you can send headers to Back-end or the other way around and do your checks that way.

Great article on $http interceptors

Example:

$httpProvider.interceptors.push(function ($q) {
        return {
            'response': function (response) {

                // TODO Create check for user authentication. With every request send "headers" or do some other check
                return response;
            },
            'responseError': function (reject) {

                // Forbidden
                if(reject.status == 403) {
                    console.log('This page is forbidden.');
                    window.location = '/';
                // Unauthorized
                } else if(reject.status == 401) {
                    console.log("You're not authorized to view this page.");
                    window.location = '/';
                }

                return $q.reject(reject);
            }
        };
    });

Put this in your .config or .run function.


问:
How to implement a generic method in Java to mange properties of a class?
I have a Container class with two sets: one of type A and the other one of type B. I want to have a single method in my class which can receive an argument of type A or B and add it to the corresponding set.
btw, I'm not sure if the interface Something should be used. Note that I want to avoid checking the class type of the received parameter with getClass() or instanceof since I have lots of sets in my project.

How can I achieve this?

Thanks,

```<code>public class Container{

privte Set<A> a;
privte Set<B> b;

public Container(){
    a = new HashSet<>();
    b = new HashSet<>();
}

//getters and setters

//generic method
public void addAorB(Something instance){
    //add to the coresponding Set
}
}

public class A implements Something{

}

public class B implements Something{

}
</code>```

答:
```<code>public void addAorB(Something instance){
    //add to the coresponding Set
   if instance instanceof A
      a.add(instance);
   else if instance instanceof B
      b.add(instance);
   else
      throw new Exception("class not supported");

    }
}
</code>```

Body:
I have a Container class with two sets: one of type A and the other one of type B. I want to have a single method in my class which can receive an argument of type A or B and add it to the corresponding set.
btw, I'm not sure if the interface Something should be used. Note that I want to avoid checking the class type of the received parameter with getClass() or instanceof since I have lots of sets in my project.

How can I achieve this?

Thanks,

public class Container{

privte Set a;
privte Set b;

public Container(){
    a = new HashSet<>();
    b = new HashSet<>();
}

//getters and setters

//generic method
public void addAorB(Something instance){
    //add to the coresponding Set
}
}

public class A implements Something{

}

public class B implements Something{

}


问:
With Devise, how have two authenticated_root (for two different user models)
My Rails 5 app uses Devise 4.2 to handle authentication for Admin and Agent user types (separate tables). It's all working, except for having the root be different for a logged in Admin vs Agent

In routes.rb I can set authenticated_root for either :admin OR :user, but doing both (as shown below) causes the error when the app is started: ArgumentError: Invalid route name, already in use: 'authenticated_root'

It seems Rails is ignoring that the two uses of authenticated_root occur in two different scenarios.

```<code># routes.rb
devise_for :agents, :skip => [:registrations]
as :agent do
  get 'agents/edit' => 'devise/registrations#edit', :as => 'edit_agent_registration'
  put 'agents' => 'devise/registrations#update', :as => 'agent_registration'
end

devise_for :admins, :skip => [:registrations]
as :admin do
  get 'admins/edit' => 'devise/registrations#edit', :as => 'edit_admin_registration'
  put 'admins' => 'devise/registrations#update', :as => 'admin_registration'
end

authenticated :admin do
  root 'pages#adminhome', as: :authenticated_root
end
authenticated :agent do
  root 'pages#agenthome', as: :authenticated_root
end
</code>```

Should I perhaps be using some sort of lambda to set authenticated_root instead of the normal method documented, and used above?

I tried this approach instead but got the same error:

```<code>root :to => 'pages#adminhome', :constraints => lambda { |request| request.env['warden'].user.class.name == 'Admin' }, as: :authenticated_root
root :to => 'pages#agenthome', :constraints => lambda { |request| request.env['warden'].user.class.name == 'Agent' }, as: :authenticated_root
</code>```

答:
I removed the "as: :authenticated_root" part and it works fine. I'm on rails 5.0.2.

The link below says the "as: :authenticated_root" part is necessary only because rails 4 doesn't allow routes with same name, assuming you already have a root route defined.

Different '/' root path for users depending if they are authenticated (using devise)

Body:
My Rails 5 app uses Devise 4.2 to handle authentication for Admin and Agent user types (separate tables). It's all working, except for having the root be different for a logged in Admin vs Agent

In routes.rb I can set authenticated_root for either :admin OR :user, but doing both (as shown below) causes the error when the app is started: ArgumentError: Invalid route name, already in use: 'authenticated_root'

It seems Rails is ignoring that the two uses of authenticated_root occur in two different scenarios.

# routes.rb
devise_for :agents, :skip => [:registrations]
as :agent do
  get 'agents/edit' => 'devise/registrations#edit', :as => 'edit_agent_registration'
  put 'agents' => 'devise/registrations#update', :as => 'agent_registration'
end

devise_for :admins, :skip => [:registrations]
as :admin do
  get 'admins/edit' => 'devise/registrations#edit', :as => 'edit_admin_registration'
  put 'admins' => 'devise/registrations#update', :as => 'admin_registration'
end

authenticated :admin do
  root 'pages#adminhome', as: :authenticated_root
end
authenticated :agent do
  root 'pages#agenthome', as: :authenticated_root
end

Should I perhaps be using some sort of lambda to set authenticated_root instead of the normal method documented, and used above?

I tried this approach instead but got the same error:

root :to => 'pages#adminhome', :constraints => lambda { |request| request.env['warden'].user.class.name == 'Admin' }, as: :authenticated_root
root :to => 'pages#agenthome', :constraints => lambda { |request| request.env['warden'].user.class.name == 'Agent' }, as: :authenticated_root


问:
js: how to access a class defined inside require from the outside (accessibility issue)
This question is bothering me for a while.
I'm trying to call a class from outside require (accessibility issue), my code looks like the above.

```<code>require(['foo'],
    (foo) => {
        class Bar {
            hello() {
                return "hello";
            }
        }
    });
bar = new Bar();
//uncaught ReferenceError: Chart is not defined
</code>```

I've found one workaround, this is done by using window.Bar = class Bar...

```<code>require(['foo'],
    (foo) => {
        window.Bar = class Bar {
            hello() {
                return "hello";
            }
        }
    });
bar = new Bar();
//OK
</code>```

However, this is not a convenient solution when it comes to converting it using Babel.

Do you know any other more correct way to export/define this class so that it could be called from an upper level?

Thanx in advance

答:
correct way to export/define this class

When you want to "export" things, what you want to do is create a module. To do this, you use the define call, not require. You can then just return what you want exported. For instance:

```<code>define(['foo'], (foo) => {
  class Bar {
    hello() {
      return "hello";
    }
  };

  return Bar;
});
</code>```

If this code is in a file named bar.js and you have your RequireJS configuration set properly so that RequireJS can find it, then you can do require(["bar"], function (Bar) {...}) from somewhere else, or other modules can use it with:

```<code>define(["bar"], function (Bar) {
  const bar = new Bar();
  // do more stuff...
});
</code>```

Both require and define load dependencies and execute their callback with the resolved dependencies, but only define actually defines modules. There's no notion of "exporting" with RequireJS unless you are in a module, which means you use define.

Body:
This question is bothering me for a while.
I'm trying to call a class from outside require (accessibility issue), my code looks like the above.

require(['foo'],
    (foo) => {
        class Bar {
            hello() {
                return "hello";
            }
        }
    });
bar = new Bar();
//uncaught ReferenceError: Chart is not defined

I've found one workaround, this is done by using window.Bar = class Bar...

require(['foo'],
    (foo) => {
        window.Bar = class Bar {
            hello() {
                return "hello";
            }
        }
    });
bar = new Bar();
//OK

However, this is not a convenient solution when it comes to converting it using Babel.

Do you know any other more correct way to export/define this class so that it could be called from an upper level?

Thanx in advance

Body:
correct way to export/define this class

When you want to "export" things, what you want to do is create a module. To do this, you use the define call, not require. You can then just return what you want exported. For instance:

define(['foo'], (foo) => {
  class Bar {
    hello() {
      return "hello";
    }
  };

  return Bar;
});

If this code is in a file named bar.js and you have your RequireJS configuration set properly so that RequireJS can find it, then you can do require(["bar"], function (Bar) {...}) from somewhere else, or other modules can use it with:

define(["bar"], function (Bar) {
  const bar = new Bar();
  // do more stuff...
});

Both require and define load dependencies and execute their callback with the resolved dependencies, but only define actually defines modules. There's no notion of "exporting" with RequireJS unless you are in a module, which means you use define.


问:
Calculating days between two dates in java with time zone
As per this question, I have calculated the days between two dates in java.
The program is below

```<code>SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    Date date1 = myFormat.parse(inputString1);
    Date date2 = myFormat.parse(inputString2);
    long diff = date2.getTime() - date1.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}
</code>```

But I have got issues when the dates are in daylight saving time zone. Like EDT to EST. For example, when we calculate days between (MAR 01, 2017) to (MAR 30, 2017), the actual count should be 29 but the result of the above program is  28.

答:
Possibly what you need is to convert the dates into same timezone before you do a diff on it. The timezone code should look something like this -

myFormat.setTimeZone(TimeZone.getTimeZone("EST"));

Body:
As per this question, I have calculated the days between two dates in java.
The program is below

SimpleDateFormat myFormat = new SimpleDateFormat("dd MM yyyy");
String inputString1 = "23 01 1997";
String inputString2 = "27 04 1997";

try {
    Date date1 = myFormat.parse(inputString1);
    Date date2 = myFormat.parse(inputString2);
    long diff = date2.getTime() - date1.getTime();
    System.out.println ("Days: " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
} catch (ParseException e) {
    e.printStackTrace();
}

But I have got issues when the dates are in daylight saving time zone. Like EDT to EST. For example, when we calculate days between (MAR 01, 2017) to (MAR 30, 2017), the actual count should be 29 but the result of the above program is  28.