问:
How to transform a categorical variable in Spark into a set of columns coded as {0,1}?
I'm trying to perform a logistic regression (LogisticRegressionWithLBFGS) with Spark MLlib (with Scala) on a dataset which contains categorical variables. I discover Spark was not able to work with that kind of variable.

In R there is a simple way to deal with that kind of problem : I transform the variable in factor (categories), so R creates a set of columns coded as {0,1} indicator variables.

How can I perform this with Spark?

答:
If the categories can fit in the driver memory, here is my suggestion:</p>

```<code>import org.apache.spark.ml.feature.StringIndexer
import org.apache.spark.sql.functions._
import org.apache.spark.sql._

val df = Seq((0, "a"),(1, "b"),(2, "c"),(3, "a"),(4, "a"),(5, "c"),(6,"c"),(7,"d"),(8,"b"))
            .toDF("id", "category")
val indexer = new StringIndexer()
                   .setInputCol("category")
                   .setOutputCol("categoryIndex")
                   .fit(df)

val indexed = indexer.transform(df)

val categoriesIndecies = indexed.select("category","categoryIndex").distinct
val categoriesMap: scala.collection.Map[String,Double] = categoriesIndecies.map(x=>(x(0).toString,x(1).toString.toDouble)).collectAsMap()

def getCategoryIndex(catMap: scala.collection.Map[String,Double], expectedValue: Double) = udf((columnValue: String) =>
if (catMap(columnValue) == expectedValue) 1 else 0)

val newDf:DataFrame =categoriesMap.keySet.toSeq.foldLeft[DataFrame](indexed)(
     (acc,c) =>
          acc.withColumn(c,getCategoryIndex(categoriesMap,categoriesMap(c))($"category"))
     )

newDf.show

+---+--------+-------------+---+---+---+---+
| id|category|categoryIndex|  b|  d|  a|  c|
+---+--------+-------------+---+---+---+---+
|  0|       a|          0.0|  0|  0|  1|  0|
|  1|       b|          2.0|  1|  0|  0|  0|
|  2|       c|          1.0|  0|  0|  0|  1|
|  3|       a|          0.0|  0|  0|  1|  0|
|  4|       a|          0.0|  0|  0|  1|  0|
|  5|       c|          1.0|  0|  0|  0|  1|
|  6|       c|          1.0|  0|  0|  0|  1|
|  7|       d|          3.0|  0|  1|  0|  0|
|  8|       b|          2.0|  1|  0|  0|  0|
+---+--------+-------------+---+---+---+---+
</code>```

Body:
If the categories can fit in the driver memory, here is my suggestion:

import org.apache.spark.ml.feature.StringIndexer
import org.apache.spark.sql.functions._
import org.apache.spark.sql._

val df = Seq((0, "a"),(1, "b"),(2, "c"),(3, "a"),(4, "a"),(5, "c"),(6,"c"),(7,"d"),(8,"b"))
            .toDF("id", "category")
val indexer = new StringIndexer()
                   .setInputCol("category")
                   .setOutputCol("categoryIndex")
                   .fit(df)

val indexed = indexer.transform(df)

val categoriesIndecies = indexed.select("category","categoryIndex").distinct
val categoriesMap: scala.collection.Map[String,Double] = categoriesIndecies.map(x=>(x(0).toString,x(1).toString.toDouble)).collectAsMap()

def getCategoryIndex(catMap: scala.collection.Map[String,Double], expectedValue: Double) = udf((columnValue: String) =>
if (catMap(columnValue) == expectedValue) 1 else 0)

val newDf:DataFrame =categoriesMap.keySet.toSeq.foldLeft[DataFrame](indexed)(
     (acc,c) =>
          acc.withColumn(c,getCategoryIndex(categoriesMap,categoriesMap(c))($"category"))
     )

newDf.show

+---+--------+-------------+---+---+---+---+
| id|category|categoryIndex|  b|  d|  a|  c|
+---+--------+-------------+---+---+---+---+
|  0|       a|          0.0|  0|  0|  1|  0|
|  1|       b|          2.0|  1|  0|  0|  0|
|  2|       c|          1.0|  0|  0|  0|  1|
|  3|       a|          0.0|  0|  0|  1|  0|
|  4|       a|          0.0|  0|  0|  1|  0|
|  5|       c|          1.0|  0|  0|  0|  1|
|  6|       c|          1.0|  0|  0|  0|  1|
|  7|       d|          3.0|  0|  1|  0|  0|
|  8|       b|          2.0|  1|  0|  0|  0|
+---+--------+-------------+---+---+---+---+


来源: stackexchange

问:
Using arrays to generate a players score
I'm trying to use the array method to keep track of scores on my game, I'm having difficulty in doing so when I try to compile and run.</p>

```<code>import java.util.Scanner;
import java.io.*;

public class score
{

    public static void main (String[]args)
    {

    Scanner scan = new Scanner(System.in);

    int [] arrPlayer = new int[7];

    System.out.println("Please Enter Your Score");
    arrPlayer[0]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[1]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[2]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[3]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[4]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[5]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[6]=scan.nextInt();

    System.out.println("Player 1 : Score: "arrPlayer[0];
    System.out.println("Player 1 : Score: "arrPlayer[1];
    System.out.println("Player 1 : Score: "arrPlayer[2];
    System.out.println("Player 1 : Score: "arrPlayer[3];
    System.out.println("Player 1 : Score: "arrPlayer[4];
    System.out.println("Player 1 : Score: "arrPlayer[5];
    System.out.println("Player 1 : Score: "arrPlayer[6];

    for(int i=0;i<7;i++);

    }

}
</code>```

答: for(int i=0; i<7; i++){System.out.println("player score:"+arrayplayer[i]);}</p>

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to use the array method to keep track of scores on my game, I'm having difficulty in doing so when I try to compile and run.

import java.util.Scanner;
import java.io.*;

public class score
{

    public static void main (String[]args)
    {

    Scanner scan = new Scanner(System.in);

    int [] arrPlayer = new int[7];

    System.out.println("Please Enter Your Score");
    arrPlayer[0]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[1]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[2]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[3]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[4]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[5]=scan.nextInt();
    System.out.println("Please Enter Your Score");
    arrPlayer[6]=scan.nextInt();

    System.out.println("Player 1 : Score: "arrPlayer[0];
    System.out.println("Player 1 : Score: "arrPlayer[1];
    System.out.println("Player 1 : Score: "arrPlayer[2];
    System.out.println("Player 1 : Score: "arrPlayer[3];
    System.out.println("Player 1 : Score: "arrPlayer[4];
    System.out.println("Player 1 : Score: "arrPlayer[5];
    System.out.println("Player 1 : Score: "arrPlayer[6];

    for(int i=0;i<7;i++);

    }

}


问:
How to check a SQL Server view dependencies
I need to modify a SQL Server view in a large database and need to know what other objects in this database use this view. How can I do that?

I tried viewing dependencies in SQL Server Management Studio but that does not list the objects that depend on this view (I know of at least one stored procedure that depends on this view, and it is not listed as a dependency).

The other option that I considered is scripting the whole database and doing the text search in it, but I want to see if there is an automated way to do this.

答:
Try to query syscomments table and find the usage.

```<code>select o.name,o.type from sys.syscomments c
inner join sys.objects o
on o. object_id = c.id
where c.text like '%your view name%'
</code>```

Update #1

```<code>select o.name,o.type from sys.sql_modules m
inner join sys.objects o
on o.object_id = m.object_id
where m.definition like '%your view name%'
</code>```

Body:
Try to query syscomments table and find the usage.

select o.name,o.type from sys.syscomments c
inner join sys.objects o
on o. object_id = c.id
where c.text like '%your view name%'

Update #1

select o.name,o.type from sys.sql_modules m
inner join sys.objects o
on o.object_id = m.object_id
where m.definition like '%your view name%'


问:
Why doing someVar in someArray in an If always give false value
I was just working on something in AngularJS. I noticed that by using the attached style of if condition, I always get a false result. Why so? Am I missing something? I tried to google it but didn't find anything.

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    var allowedExtensions = [".jpg",".pdf", ".png"];
    var testExt = ".jpg";

    if(testExt in allowedExtensions){
       $scope.isAllowed = true;
    }else{
       //will always go here why?
       $scope.isAllowed = false;
    }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head></head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
  Is Extension Allowed : {{isAllowed}}
</div>
</body>
</html></code>```

I am from .NET background so we use LINQ in that kinda same like that. Is this type of syntax not supported in JS?

EDIT
I know about index of and other ways to find if it is in the array. But I was confused why in operator is not working.

Thank you for your time and help.

答:
It's an array, therefore in only works on indices or property name; from the docs:

The in operator returns true` if the specified property is in the specified object or its prototype chain.

Try allowedExtensions.includes(testExt) or perhaps allowedExtensions.indexOf(testExt) != -1 instead.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in

Body:
I was just working on something in AngularJS. I noticed that by using the attached style of if condition, I always get a false result. Why so? Am I missing something? I tried to google it but didn't find anything.

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    var allowedExtensions = [".jpg",".pdf", ".png"];
    var testExt = ".jpg";

    if(testExt in allowedExtensions){
       $scope.isAllowed = true;
    }else{
       //will always go here why?
       $scope.isAllowed = false;
    }
}

  Is Extension Allowed : {{isAllowed}}

I am from .NET background so we use LINQ in that kinda same like that. Is this type of syntax not supported in JS?

EDIT
I know about index of and other ways to find if it is in the array. But I was confused why in operator is not working.

Thank you for your time and help.


问:
Ansible 2.3 and Cisco IOS SSH Key Authentication
Ansible Version: 2.3.2.0
Paramiko Version: 2.2.1

Trying to get Ansible to work against a Cisco IOS-based switch using SSH RSA Key authentication.

Added the private key to the switch:

```<code>ip ssh pubkey-chain
   key-hash ssh-rsa 090A4713055CB0CBE097FFF2FFC8065B root@ansible
</code>```

Verified SSHv2 and Key:

```<code>SSH Enabled - version 2.0
Authentication timeout: 120 secs; Authentication retries: 3
Minimum expected Diffie Hellman key size : 1024 bits
IOS Keys in SECSH format(ssh-rsa, base64 encoded):
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCqIKfBqGXuVdv0TbDT6fsPXC+zQ0/aeXBowhrgt4iV
b43PtLxIxZgJaw+Ubc8QJ1pMToK+pABZnub4xbtTR8WoMDh5ruL1XRIDhPxc38DQ5YNfTalyUGL2rlXJ
mZMeRWZ3R0NS6crat/ehC+vTl815yqbyEC7YWIVrRwfnDa2bjAD4ZB+i4E5zqAG1FqduW89h2jZmu7ww
icOnjAg16nOUiI8QJdbsBue6zepcX+uWCTLb4ZBZsCTRfjqt7O/HVEDl9U0K7D4/d6lLijagsozVXYaZ
wQSjlQ6FqXlgplo8rtFAMtH/SHr0ndfejeJmcp2+WRrZnMfMLCmLZNUHumAH
</code>```

I have the connection: local set:

```<code>- hosts: ios
  gather_facts: no
  connection: local
  roles:
    - cisco_switch
</code>```

Here are my vars for provider:

```<code>cli:
  host: "{{ inventory_hostname }}"
  username: root
  authorize: yes
  auth_pass: ansible
</code>```

Here is the actual task I'm trying to execute:

```<code>- name: System Settings
  ios_system:
    provider: "{{ cli }}"
    hostname: "{{ inventory_hostname }}"
    domain_name: homelab.lan
    domain_search:
      - homelab.lan
    name_servers:
      - ns1.homelab.lan
</code>```

Verified I can login using ssh-agent and the key manually using ssh root@c3750e

However, running the playbook fails with the following:

```<code>2017-08-16 13:51:27,483 p=1524 u=root |    1533 1502891487.48368: starting attempt loop
2017-08-16 13:51:27,483 p=1524 u=root |    1533 1502891487.48382: running the handler
2017-08-16 13:51:27,484 p=1524 u=root |    1533 1502891487.48477: Loading Connection 'persistent' from /usr/lib/python2.7/site-packages/ansible/plugins/connection/persistent.py
2017-08-16 13:51:27,485 p=1524 u=root |    1533 1502891487.48505: Loading ShellModule 'csh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/csh.py (found_in_cache=True, class_only=False)
2017-08-16 13:51:27,485 p=1524 u=root |    1533 1502891487.48520: Loading ShellModule 'fish' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/fish.py (found_in_cache=True, class_only=False)
2017-08-16 13:51:27,485 p=1524 u=root |    1533 1502891487.48534: Loading ShellModule 'powershell' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/powershell.py (found_in_cache=True, class_only=False)
2017-08-16 13:51:27,485 p=1524 u=root |    1533 1502891487.48551: Loading ShellModule 'sh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/sh.py (found_in_cache=True, class_only=False)
2017-08-16 13:51:27,485 p=1524 u=root |    1533 1502891487.48565: Loading ShellModule 'sh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/sh.py (found_in_cache=True, class_only=False)
2017-08-16 13:51:27,486 p=1524 u=root |    1533 1502891487.48620: Loading Connection 'ssh' from /usr/lib/python2.7/site-packages/ansible/plugins/connection/ssh.py (found_in_cache=False, class_only=True)
2017-08-16 13:51:27,874 p=1534 u=root |    1534 1502891487.87418: Loading Connection 'ssh' from /usr/lib/python2.7/site-packages/ansible/plugins/connection/ssh.py (found_in_cache=False, class_only=True)
2017-08-16 13:51:27,886 p=1534 u=root |  creating new control socket for host c3750e.homelab.lan:22 as user root
2017-08-16 13:51:27,886 p=1534 u=root |  control socket path is /root/.ansible/pc/b7f0dc1e86
2017-08-16 13:51:27,886 p=1534 u=root |  current working directory is /root/infra_playbook
2017-08-16 13:51:27,887 p=1534 u=root |  using connection plugin network_cli
  1542 1502891487.94495: Loading Connection 'network_cli' from /usr/lib/python2.7/site-packages/ansible/plugins/connection/network_cli.py
2017-08-16 13:51:27,945 p=1534 u=root |    1542 1502891487.94495: Loading Connection 'network_cli' from /usr/lib/python2.7/site-packages/ansible/plugins/connection/network_cli.py
  1542 1502891487.94620: Loading ShellModule 'csh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/csh.py
2017-08-16 13:51:27,946 p=1534 u=root |    1542 1502891487.94620: Loading ShellModule 'csh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/csh.py
  1542 1502891487.94650: Loading ShellModule 'fish' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/fish.py
2017-08-16 13:51:27,946 p=1534 u=root |    1542 1502891487.94650: Loading ShellModule 'fish' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/fish.py
  1542 1502891487.94694: Loading ShellModule 'powershell' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/powershell.py
2017-08-16 13:51:27,946 p=1534 u=root |    1542 1502891487.94694: Loading ShellModule 'powershell' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/powershell.py
  1542 1502891487.94714: Loading ShellModule 'sh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/sh.py
2017-08-16 13:51:27,947 p=1534 u=root |    1542 1502891487.94714: Loading ShellModule 'sh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/sh.py
  1542 1502891487.94740: Loading ShellModule 'sh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/sh.py (found_in_cache=True, class_only=False)
2017-08-16 13:51:27,947 p=1534 u=root |    1542 1502891487.94740: Loading ShellModule 'sh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/sh.py (found_in_cache=True, class_only=False)
2017-08-16 13:51:27,978 paramiko.transport starting thread (client mode): 0x2d7f8d0L
2017-08-16 13:51:27,978 paramiko.transport Local version/idstring: SSH-2.0-paramiko_2.2.1
2017-08-16 13:51:27,980 paramiko.transport Remote version/idstring: SSH-2.0-Cisco-1.25
2017-08-16 13:51:27,980 paramiko.transport Connected (version 2.0, client Cisco-1.25)
2017-08-16 13:51:27,985 paramiko.transport kex algos:[u'diffie-hellman-group-exchange-sha1', u'diffie-hellman-group14-sha1', u'diffie-hellman-group1-sha1'] server key:[u'ssh-rsa'] client encrypt:[u'aes128-cbc', u'3des-cbc', u'aes192-cbc', u'aes256-cbc'] server encrypt:[u'aes128-cbc', u'3des-cbc', u'aes192-cbc', u'aes256-cbc'] client mac:[u'hmac-sha1', u'hmac-sha1-96', u'hmac-md5', u'hmac-md5-96'] server mac:[u'hmac-sha1', u'hmac-sha1-96', u'hmac-md5', u'hmac-md5-96'] client compress:[u'none'] server compress:[u'none'] client lang:[u''] server lang:[u''] kex follows?False
2017-08-16 13:51:27,985 paramiko.transport Kex agreed: diffie-hellman-group-exchange-sha1
2017-08-16 13:51:27,985 paramiko.transport HostKey agreed: ssh-rsa
2017-08-16 13:51:27,985 paramiko.transport Cipher agreed: aes128-cbc
2017-08-16 13:51:27,985 paramiko.transport MAC agreed: hmac-sha1
2017-08-16 13:51:27,985 paramiko.transport Compression agreed: none
2017-08-16 13:51:27,991 paramiko.transport Got server p (2048 bits)
2017-08-16 13:51:29,278 paramiko.transport kex engine KexGex specified hash_algo <built-in function openssl_sha1>
2017-08-16 13:51:29,279 paramiko.transport Switch to new keys ...
2017-08-16 13:51:29,281 paramiko.transport Trying discovered key 090a4713055cb0cbe097fff2ffc8065b in /root/.ssh/id_rsa
2017-08-16 13:51:29,482 paramiko.transport userauth is OK
2017-08-16 13:51:29,489 paramiko.transport Exception: Illegal info request from server
2017-08-16 13:51:29,490 paramiko.transport Traceback (most recent call last):
2017-08-16 13:51:29,490 paramiko.transport   File "/usr/lib/python2.7/site-packages/paramiko/transport.py", line 1860, in run
2017-08-16 13:51:29,490 paramiko.transport     handler(self.auth_handler, m)
2017-08-16 13:51:29,490 paramiko.transport   File "/usr/lib/python2.7/site-packages/paramiko/auth_handler.py", line 624, in _parse_userauth_info_request
2017-08-16 13:51:29,490 paramiko.transport     raise SSHException('Illegal info request from server')
2017-08-16 13:51:29,490 paramiko.transport SSHException: Illegal info request from server
2017-08-16 13:51:29,490 paramiko.transport
2017-08-16 13:51:29,497 p=1534 u=root |  connecting to host c3750e.homelab.lan returned an error
2017-08-16 13:51:29,497 p=1534 u=root |  Illegal info request from server
2017-08-16 13:51:57,896 p=1534 u=root |  number of connection attempts exceeded, unable to connect to control socket
2017-08-16 13:51:57,896 p=1534 u=root |  persistent_connect_interval=1, persistent_connect_retries=30
2017-08-16 13:51:57,912 p=1524 u=root |  open_shell() returned 255   1534 1502891487.87418: Loading Connection 'ssh' from /usr/lib/python2.7/site-packages/ansible/plugins/connection/ssh.py (found_in_cache=False, class_only=True)
 failed to connect to control socket
2017-08-16 13:51:57,912 p=1524 u=root |    1533 1502891517.91286: handler run complete
2017-08-16 13:51:57,913 p=1524 u=root |    1533 1502891517.91303: attempt loop complete, returning result
2017-08-16 13:51:57,913 p=1524 u=root |    1533 1502891517.91316: _execute() done
2017-08-16 13:51:57,913 p=1524 u=root |    1533 1502891517.91328: dumping result to json
2017-08-16 13:51:57,913 p=1524 u=root |    1533 1502891517.91342: done dumping result, returning
2017-08-16 13:51:57,913 p=1524 u=root |    1533 1502891517.91358: done running TaskExecutor() for c3750e.homelab.lan/TASK: cisco_switch : System Settings [c6e4c8ff-dea8-390a-92f3-00000000004d]
2017-08-16 13:51:57,913 p=1524 u=root |    1533 1502891517.91377: sending task result for task c6e4c8ff-dea8-390a-92f3-00000000004d
2017-08-16 13:51:57,914 p=1524 u=root |    1533 1502891517.91418: done sending task result for task c6e4c8ff-dea8-390a-92f3-00000000004d
2017-08-16 13:51:57,914 p=1524 u=root |    1533 1502891517.91430: WORKER PROCESS EXITING
2017-08-16 13:51:57,915 p=1524 u=root |    1524 1502891517.91541: marking c3750e.homelab.lan as failed
2017-08-16 13:51:57,915 p=1524 u=root |    1524 1502891517.91562: marking host c3750e.homelab.lan failed, current state: HOST STATE: block=2, task=1, rescue=0, always=0, run_state=ITERATING_TASKS, fail_state=FAILED_NONE, pending_setup=False, tasks child state? (None), rescue child state? (None), always child state? (None), did rescue? False, did start at task? False
2017-08-16 13:51:57,915 p=1524 u=root |    1524 1502891517.91574: ^ failed state is now: HOST STATE: block=2, task=1, rescue=0, always=0, run_state=ITERATING_COMPLETE, fail_state=FAILED_TASKS, pending_setup=False, tasks child state? (None), rescue child state? (None), always child state? (None), did rescue? False, did start at task? False
2017-08-16 13:51:57,915 p=1524 u=root |    1524 1502891517.91585: getting the next task for host c3750e.homelab.lan
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91596: host c3750e.homelab.lan is done iterating, returning
2017-08-16 13:51:57,916 p=1524 u=root |  fatal: [c3750e.homelab.lan]: FAILED! => {
    "changed": false,
    "failed": true,
    "msg": "unable to open shell. Please see: https://docs.ansible.com/ansible/network_debug_troubleshooting.html#unable-to-open-shell",
    "rc": 255
}
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91630: no more pending results, returning what we have
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91641: results queue empty
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91651: checking for any_errors_fatal
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91661: done checking for any_errors_fatal
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91670: checking for max_fail_percentage
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91679: done checking for max_fail_percentage
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91688: checking to see if all hosts have failed and the running result is not ok
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91697: done checking to see if all hosts have failed
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91706: getting the remaining hosts for this loop
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91717: done getting the remaining hosts for this loop
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91729: building list of next tasks for hosts
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91738: getting the next task for host c3750e.homelab.lan
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91748: host c3750e.homelab.lan is done iterating, returning
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91757: done building task lists
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91766: counting tasks in each state of execution
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91775: done counting tasks in each state of execution:
    num_setups: 0
    num_tasks: 0
    num_rescue: 0
    num_always: 0
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91785: all hosts are done, so returning None's for all hosts
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91795: done queuing things up, now waiting for results queue to drain
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91804: results queue empty
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91813: checking for any_errors_fatal
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91822: done checking for any_errors_fatal
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91830: checking for max_fail_percentage
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91839: done checking for max_fail_percentage
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91848: checking to see if all hosts have failed and the running result is not ok
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91857: done checking to see if all hosts have failed
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91869: getting the next task for host c3750e.homelab.lan
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91879: host c3750e.homelab.lan is done iterating, returning
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91888: running handlers
2017-08-16 13:51:57,920 p=1524 u=root |     to retry, use: --limit @/root/infra_playbook/site.retry

2017-08-16 13:51:57,920 p=1524 u=root |  PLAY RECAP ***************************************************************************************************************************
2017-08-16 13:51:57,921 p=1524 u=root |  c3750e.homelab.lan         : ok=0    changed=0    unreachable=0    failed=1
2017-08-16 13:51:57,921 p=1524 u=root |    1524 1502891517.92111: RUNNING CLEANUP
</code>```

Tried various fixes, including the Network Debug and Troubleshooting guide from Ansible, without any of them working. Tried changing provider var to transport: ssh and transport: cli without it working.

答:
$ansible --version
ansible 2.4.0.0

This worked for me:
Playbook:

```<code>    ---
    - hosts: device.r1
      gather_facts: yes
      connection: local
      ignore_errors: yes

      tasks:
      - name: Load {{ inventory_hostname }} vars file
        include_vars: host_vars/{{ inventory_hostname }}.yml

      - name: obtain login credentials
        include_vars: ../auth/user.yml

      - name: define authentication provider
        set_fact:
          provider:
            host: "{{ inventory_hostname }}"
            username: "{{ creds['username'] }}"
            ssh_keyfile: "{{ creds['ssh_keyfile'] }}"

      - name: Gather Facts
        vyos_facts:
          gather_subset: all
          provider: "{{ creds }}"
        register: vyos_response

      - name: version
        debug: msg="{{ vyos_response.ansible_facts.ansible_net_version }}"
</code>```

For ../auth/user.yml:

```<code>---
creds:
 username: ansible_user
 ssh_keyfile: /home/ansible_user/.ssh/id_rsa_ansible_user
</code>```

Body:
Ansible Version: 2.3.2.0
Paramiko Version: 2.2.1

Trying to get Ansible to work against a Cisco IOS-based switch using SSH RSA Key authentication.

Added the private key to the switch:

ip ssh pubkey-chain
   key-hash ssh-rsa 090A4713055CB0CBE097FFF2FFC8065B root@ansible

Verified SSHv2 and Key:

SSH Enabled - version 2.0
Authentication timeout: 120 secs; Authentication retries: 3
Minimum expected Diffie Hellman key size : 1024 bits
IOS Keys in SECSH format(ssh-rsa, base64 encoded):
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCqIKfBqGXuVdv0TbDT6fsPXC+zQ0/aeXBowhrgt4iV
b43PtLxIxZgJaw+Ubc8QJ1pMToK+pABZnub4xbtTR8WoMDh5ruL1XRIDhPxc38DQ5YNfTalyUGL2rlXJ
mZMeRWZ3R0NS6crat/ehC+vTl815yqbyEC7YWIVrRwfnDa2bjAD4ZB+i4E5zqAG1FqduW89h2jZmu7ww
icOnjAg16nOUiI8QJdbsBue6zepcX+uWCTLb4ZBZsCTRfjqt7O/HVEDl9U0K7D4/d6lLijagsozVXYaZ
wQSjlQ6FqXlgplo8rtFAMtH/SHr0ndfejeJmcp2+WRrZnMfMLCmLZNUHumAH

I have the connection: local set:

- hosts: ios
  gather_facts: no
  connection: local
  roles:
    - cisco_switch

Here are my vars for provider:

cli:
  host: "{{ inventory_hostname }}"
  username: root
  authorize: yes
  auth_pass: ansible

Here is the actual task I'm trying to execute:

- name: System Settings
  ios_system:
    provider: "{{ cli }}"
    hostname: "{{ inventory_hostname }}"
    domain_name: homelab.lan
    domain_search:
      - homelab.lan
    name_servers:
      - ns1.homelab.lan

Verified I can login using ssh-agent and the key manually using ssh root@c3750e

However, running the playbook fails with the following:

2017-08-16 13:51:27,483 p=1524 u=root |    1533 1502891487.48368: starting attempt loop
2017-08-16 13:51:27,483 p=1524 u=root |    1533 1502891487.48382: running the handler
2017-08-16 13:51:27,484 p=1524 u=root |    1533 1502891487.48477: Loading Connection 'persistent' from /usr/lib/python2.7/site-packages/ansible/plugins/connection/persistent.py
2017-08-16 13:51:27,485 p=1524 u=root |    1533 1502891487.48505: Loading ShellModule 'csh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/csh.py (found_in_cache=True, class_only=False)
2017-08-16 13:51:27,485 p=1524 u=root |    1533 1502891487.48520: Loading ShellModule 'fish' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/fish.py (found_in_cache=True, class_only=False)
2017-08-16 13:51:27,485 p=1524 u=root |    1533 1502891487.48534: Loading ShellModule 'powershell' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/powershell.py (found_in_cache=True, class_only=False)
2017-08-16 13:51:27,485 p=1524 u=root |    1533 1502891487.48551: Loading ShellModule 'sh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/sh.py (found_in_cache=True, class_only=False)
2017-08-16 13:51:27,485 p=1524 u=root |    1533 1502891487.48565: Loading ShellModule 'sh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/sh.py (found_in_cache=True, class_only=False)
2017-08-16 13:51:27,486 p=1524 u=root |    1533 1502891487.48620: Loading Connection 'ssh' from /usr/lib/python2.7/site-packages/ansible/plugins/connection/ssh.py (found_in_cache=False, class_only=True)
2017-08-16 13:51:27,874 p=1534 u=root |    1534 1502891487.87418: Loading Connection 'ssh' from /usr/lib/python2.7/site-packages/ansible/plugins/connection/ssh.py (found_in_cache=False, class_only=True)
2017-08-16 13:51:27,886 p=1534 u=root |  creating new control socket for host c3750e.homelab.lan:22 as user root
2017-08-16 13:51:27,886 p=1534 u=root |  control socket path is /root/.ansible/pc/b7f0dc1e86
2017-08-16 13:51:27,886 p=1534 u=root |  current working directory is /root/infra_playbook
2017-08-16 13:51:27,887 p=1534 u=root |  using connection plugin network_cli
  1542 1502891487.94495: Loading Connection 'network_cli' from /usr/lib/python2.7/site-packages/ansible/plugins/connection/network_cli.py
2017-08-16 13:51:27,945 p=1534 u=root |    1542 1502891487.94495: Loading Connection 'network_cli' from /usr/lib/python2.7/site-packages/ansible/plugins/connection/network_cli.py
  1542 1502891487.94620: Loading ShellModule 'csh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/csh.py
2017-08-16 13:51:27,946 p=1534 u=root |    1542 1502891487.94620: Loading ShellModule 'csh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/csh.py
  1542 1502891487.94650: Loading ShellModule 'fish' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/fish.py
2017-08-16 13:51:27,946 p=1534 u=root |    1542 1502891487.94650: Loading ShellModule 'fish' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/fish.py
  1542 1502891487.94694: Loading ShellModule 'powershell' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/powershell.py
2017-08-16 13:51:27,946 p=1534 u=root |    1542 1502891487.94694: Loading ShellModule 'powershell' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/powershell.py
  1542 1502891487.94714: Loading ShellModule 'sh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/sh.py
2017-08-16 13:51:27,947 p=1534 u=root |    1542 1502891487.94714: Loading ShellModule 'sh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/sh.py
  1542 1502891487.94740: Loading ShellModule 'sh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/sh.py (found_in_cache=True, class_only=False)
2017-08-16 13:51:27,947 p=1534 u=root |    1542 1502891487.94740: Loading ShellModule 'sh' from /usr/lib/python2.7/site-packages/ansible/plugins/shell/sh.py (found_in_cache=True, class_only=False)
2017-08-16 13:51:27,978 paramiko.transport starting thread (client mode): 0x2d7f8d0L
2017-08-16 13:51:27,978 paramiko.transport Local version/idstring: SSH-2.0-paramiko_2.2.1
2017-08-16 13:51:27,980 paramiko.transport Remote version/idstring: SSH-2.0-Cisco-1.25
2017-08-16 13:51:27,980 paramiko.transport Connected (version 2.0, client Cisco-1.25)
2017-08-16 13:51:27,985 paramiko.transport kex algos:[u'diffie-hellman-group-exchange-sha1', u'diffie-hellman-group14-sha1', u'diffie-hellman-group1-sha1'] server key:[u'ssh-rsa'] client encrypt:[u'aes128-cbc', u'3des-cbc', u'aes192-cbc', u'aes256-cbc'] server encrypt:[u'aes128-cbc', u'3des-cbc', u'aes192-cbc', u'aes256-cbc'] client mac:[u'hmac-sha1', u'hmac-sha1-96', u'hmac-md5', u'hmac-md5-96'] server mac:[u'hmac-sha1', u'hmac-sha1-96', u'hmac-md5', u'hmac-md5-96'] client compress:[u'none'] server compress:[u'none'] client lang:[u''] server lang:[u''] kex follows?False
2017-08-16 13:51:27,985 paramiko.transport Kex agreed: diffie-hellman-group-exchange-sha1
2017-08-16 13:51:27,985 paramiko.transport HostKey agreed: ssh-rsa
2017-08-16 13:51:27,985 paramiko.transport Cipher agreed: aes128-cbc
2017-08-16 13:51:27,985 paramiko.transport MAC agreed: hmac-sha1
2017-08-16 13:51:27,985 paramiko.transport Compression agreed: none
2017-08-16 13:51:27,991 paramiko.transport Got server p (2048 bits)
2017-08-16 13:51:29,278 paramiko.transport kex engine KexGex specified hash_algo <built-in function openssl_sha1>
2017-08-16 13:51:29,279 paramiko.transport Switch to new keys ...
2017-08-16 13:51:29,281 paramiko.transport Trying discovered key 090a4713055cb0cbe097fff2ffc8065b in /root/.ssh/id_rsa
2017-08-16 13:51:29,482 paramiko.transport userauth is OK
2017-08-16 13:51:29,489 paramiko.transport Exception: Illegal info request from server
2017-08-16 13:51:29,490 paramiko.transport Traceback (most recent call last):
2017-08-16 13:51:29,490 paramiko.transport   File "/usr/lib/python2.7/site-packages/paramiko/transport.py", line 1860, in run
2017-08-16 13:51:29,490 paramiko.transport     handler(self.auth_handler, m)
2017-08-16 13:51:29,490 paramiko.transport   File "/usr/lib/python2.7/site-packages/paramiko/auth_handler.py", line 624, in _parse_userauth_info_request
2017-08-16 13:51:29,490 paramiko.transport     raise SSHException('Illegal info request from server')
2017-08-16 13:51:29,490 paramiko.transport SSHException: Illegal info request from server
2017-08-16 13:51:29,490 paramiko.transport
2017-08-16 13:51:29,497 p=1534 u=root |  connecting to host c3750e.homelab.lan returned an error
2017-08-16 13:51:29,497 p=1534 u=root |  Illegal info request from server
2017-08-16 13:51:57,896 p=1534 u=root |  number of connection attempts exceeded, unable to connect to control socket
2017-08-16 13:51:57,896 p=1534 u=root |  persistent_connect_interval=1, persistent_connect_retries=30
2017-08-16 13:51:57,912 p=1524 u=root |  open_shell() returned 255   1534 1502891487.87418: Loading Connection 'ssh' from /usr/lib/python2.7/site-packages/ansible/plugins/connection/ssh.py (found_in_cache=False, class_only=True)
 failed to connect to control socket
2017-08-16 13:51:57,912 p=1524 u=root |    1533 1502891517.91286: handler run complete
2017-08-16 13:51:57,913 p=1524 u=root |    1533 1502891517.91303: attempt loop complete, returning result
2017-08-16 13:51:57,913 p=1524 u=root |    1533 1502891517.91316: _execute() done
2017-08-16 13:51:57,913 p=1524 u=root |    1533 1502891517.91328: dumping result to json
2017-08-16 13:51:57,913 p=1524 u=root |    1533 1502891517.91342: done dumping result, returning
2017-08-16 13:51:57,913 p=1524 u=root |    1533 1502891517.91358: done running TaskExecutor() for c3750e.homelab.lan/TASK: cisco_switch : System Settings [c6e4c8ff-dea8-390a-92f3-00000000004d]
2017-08-16 13:51:57,913 p=1524 u=root |    1533 1502891517.91377: sending task result for task c6e4c8ff-dea8-390a-92f3-00000000004d
2017-08-16 13:51:57,914 p=1524 u=root |    1533 1502891517.91418: done sending task result for task c6e4c8ff-dea8-390a-92f3-00000000004d
2017-08-16 13:51:57,914 p=1524 u=root |    1533 1502891517.91430: WORKER PROCESS EXITING
2017-08-16 13:51:57,915 p=1524 u=root |    1524 1502891517.91541: marking c3750e.homelab.lan as failed
2017-08-16 13:51:57,915 p=1524 u=root |    1524 1502891517.91562: marking host c3750e.homelab.lan failed, current state: HOST STATE: block=2, task=1, rescue=0, always=0, run_state=ITERATING_TASKS, fail_state=FAILED_NONE, pending_setup=False, tasks child state? (None), rescue child state? (None), always child state? (None), did rescue? False, did start at task? False
2017-08-16 13:51:57,915 p=1524 u=root |    1524 1502891517.91574: ^ failed state is now: HOST STATE: block=2, task=1, rescue=0, always=0, run_state=ITERATING_COMPLETE, fail_state=FAILED_TASKS, pending_setup=False, tasks child state? (None), rescue child state? (None), always child state? (None), did rescue? False, did start at task? False
2017-08-16 13:51:57,915 p=1524 u=root |    1524 1502891517.91585: getting the next task for host c3750e.homelab.lan
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91596: host c3750e.homelab.lan is done iterating, returning
2017-08-16 13:51:57,916 p=1524 u=root |  fatal: [c3750e.homelab.lan]: FAILED! => {
    "changed": false,
    "failed": true,
    "msg": "unable to open shell. Please see: https://docs.ansible.com/ansible/network_debug_troubleshooting.html#unable-to-open-shell",
    "rc": 255
}
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91630: no more pending results, returning what we have
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91641: results queue empty
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91651: checking for any_errors_fatal
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91661: done checking for any_errors_fatal
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91670: checking for max_fail_percentage
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91679: done checking for max_fail_percentage
2017-08-16 13:51:57,916 p=1524 u=root |    1524 1502891517.91688: checking to see if all hosts have failed and the running result is not ok
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91697: done checking to see if all hosts have failed
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91706: getting the remaining hosts for this loop
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91717: done getting the remaining hosts for this loop
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91729: building list of next tasks for hosts
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91738: getting the next task for host c3750e.homelab.lan
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91748: host c3750e.homelab.lan is done iterating, returning
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91757: done building task lists
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91766: counting tasks in each state of execution
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91775: done counting tasks in each state of execution:
    num_setups: 0
    num_tasks: 0
    num_rescue: 0
    num_always: 0
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91785: all hosts are done, so returning None's for all hosts
2017-08-16 13:51:57,917 p=1524 u=root |    1524 1502891517.91795: done queuing things up, now waiting for results queue to drain
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91804: results queue empty
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91813: checking for any_errors_fatal
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91822: done checking for any_errors_fatal
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91830: checking for max_fail_percentage
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91839: done checking for max_fail_percentage
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91848: checking to see if all hosts have failed and the running result is not ok
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91857: done checking to see if all hosts have failed
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91869: getting the next task for host c3750e.homelab.lan
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91879: host c3750e.homelab.lan is done iterating, returning
2017-08-16 13:51:57,918 p=1524 u=root |    1524 1502891517.91888: running handlers
2017-08-16 13:51:57,920 p=1524 u=root |     to retry, use: --limit @/root/infra_playbook/site.retry

2017-08-16 13:51:57,920 p=1524 u=root |  PLAY RECAP ***************************************************************************************************************************
2017-08-16 13:51:57,921 p=1524 u=root |  c3750e.homelab.lan         : ok=0    changed=0    unreachable=0    failed=1
2017-08-16 13:51:57,921 p=1524 u=root |    1524 1502891517.92111: RUNNING CLEANUP

Tried various fixes, including the Network Debug and Troubleshooting guide from Ansible, without any of them working. Tried changing provider var to transport: ssh and transport: cli without it working.

Body:
$ansible --version
ansible 2.4.0.0

This worked for me:
Playbook:

    ---
    - hosts: device.r1
      gather_facts: yes
      connection: local
      ignore_errors: yes

      tasks:
      - name: Load {{ inventory_hostname }} vars file
        include_vars: host_vars/{{ inventory_hostname }}.yml

      - name: obtain login credentials
        include_vars: ../auth/user.yml

      - name: define authentication provider
        set_fact:
          provider:
            host: "{{ inventory_hostname }}"
            username: "{{ creds['username'] }}"
            ssh_keyfile: "{{ creds['ssh_keyfile'] }}"

      - name: Gather Facts
        vyos_facts:
          gather_subset: all
          provider: "{{ creds }}"
        register: vyos_response

      - name: version
        debug: msg="{{ vyos_response.ansible_facts.ansible_net_version }}"

For ../auth/user.yml:

---
creds:
 username: ansible_user
 ssh_keyfile: /home/ansible_user/.ssh/id_rsa_ansible_user


问:
Show/hide optgroup based on checkboxes
So basically I want a solution like in this question here but with the "master" being <checkbox> not <select>.

So for example I have four checkboxes and a select with four optgroups. I want to show only these optgroups which are selected with the checkboxes.

I am very new to javascript and can't think of a solution. I tried adapting the solution of the question I posted but without success. I also couldn't find the exact same problem on the internet.

Thanks for your help.

Edit:

Here is the code (though redundant imo):

```<code><input type="checkbox" id="1" name="serviceType" checked="checked" />
<label for="1">Application</label>
<input type="checkbox" id="2" name="serviceType" />
<label for="2">Infrastructure Service</label>
<input type="checkbox" id="3" name="serviceType" />
<label for="3">Platform</label>
<input type="checkbox" id="4" name="serviceType" checked="checked" />
<label for="4">Software</label>

<select name="services">
    <optgroup label="Application">                      <!-- Shown -->
        <option value="Office">Office</option>
        <option value="SAP">SAP</option>
    </optgroup>
    <optgroup label="Infrastructure Service">           <!-- Hidden -->
        <option value="Router">Router</option>
        <option value="Switch">Switch</option>
    </optgroup>
    <optgroup label="Platform">                         <!-- Hidden -->
        <option value="Server">Server</option>
        <option value="Client">Client</option>
    </optgroup>
    <optgroup label="Software">                         <!-- Shown -->
        <option value="Word">Word</option>
        <option value="Excel">Excel</option>
    </optgroup>
</select>
</code>```

And of course it should adjust itself based on changed selections.

And here the Javascript (ctrl + c, ctrl + v from other question):

```<code>$(document).ready(function () {
    $("checkbox[name='serviceType']:eq(0)").on("change",
        function () {
            console.log(this.value);
            $("select[name='services']:eq(0)")
                .find("optgroup,option")
                .hide()
                .filter("[label='" + this.value + "'],[label = '" + this.value + "'] > *")
                .show();
        });
});
</code>```

答:
CSS alternative (but I recommend using valid identifiers instead of numbers) :

[id="1"]:not(:checked) ~ select > [label=Application],
[id="2"]:not(:checked) ~ select > [label="Infrastructure Service"],
[id="3"]:not(:checked) ~ select > [label=Platform],
[id="4"]:not(:checked) ~ select > [label=Software] { display: none; }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" id="1" name="serviceType" checked>
<label for="1">Application</label>
<input type="checkbox" id="2" name="serviceType">
<label for="2">Infrastructure Service</label>
<input type="checkbox" id="3" name="serviceType">
<label for="3">Platform</label>
<input type="checkbox" id="4" name="serviceType" checked>
<label for="4">Software</label>
<br>
<select name="services" size=10 style="width: 166px">
    <optgroup label="Application">                      <!-- Shown -->
        <option value="Office">Office</option>
        <option value="SAP">SAP</option>
    </optgroup>
    <optgroup label="Infrastructure Service">           <!-- Hidden -->
        <option value="Router">Router</option>
        <option value="Switch">Switch</option>
    </optgroup>
    <optgroup label="Platform">                         <!-- Hidden -->
        <option value="Server">Server</option>
        <option value="Client">Client</option>
    </optgroup>
    <optgroup label="Software">                         <!-- Shown -->
        <option value="Word">Word</option>
        <option value="Excel">Excel</option>
    </optgroup>
</select></code>```

JavaScript might be needed to deselect options that are not displayed:

services.value = ''
document.onclick = function(e) { if (e.target.checked === false) services.value = '' }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[id="1"]:not(:checked) ~ select > [label=Application],
[id="2"]:not(:checked) ~ select > [label="Infrastructure Service"],
[id="3"]:not(:checked) ~ select > [label=Platform],
[id="4"]:not(:checked) ~ select > [label=Software] { display: none; }</code>```

<input type="checkbox" id="1" name="serviceType" checked>
Application
<input type="checkbox" id="2" name="serviceType">
Infrastructure Service
<input type="checkbox" id="3" name="serviceType">
Platform
<input type="checkbox" id="4" name="serviceType" checked>
Software

<select id="services">
    <optgroup label="Application">
        <option value="Office">Office</option>
        <option value="SAP">SAP</option>
    </optgroup>
    <optgroup label="Infrastructure Service">
        <option value="Router">Router</option>
        <option value="Switch">Switch</option>
    </optgroup>
    <optgroup label="Platform">
        <option value="Server">Server</option>
        <option value="Client">Client</option>
    </optgroup>
    <optgroup label="Software">
        <option value="Word">Word</option>
        <option value="Excel">Excel</option>
    </optgroup>
</select>```

Title: Show/hide optgroup based on checkboxes

Body:
So basically I want a solution like in this question here but with the "master" being <checkbox> not <select>.

So for example I have four checkboxes and a select with four optgroups. I want to show only these optgroups which are selected with the checkboxes.

I am very new to javascript and can't think of a solution. I tried adapting the solution of the question I posted but without success. I also couldn't find the exact same problem on the internet.

Thanks for your help.

Edit:

Here is the code (though redundant imo):

<input type="checkbox" id="1" name="serviceType" checked="checked" />
Application
<input type="checkbox" id="2" name="serviceType" />
Infrastructure Service
<input type="checkbox" id="3" name="serviceType" />
Platform
<input type="checkbox" id="4" name="serviceType" checked="checked" />
Software

<select name="services">
    <optgroup label="Application">
        <option value="Office">Office</option>
        <option value="SAP">SAP</option>
    </optgroup>
    <optgroup label="Infrastructure Service">
        <option value="Router">Router</option>
        <option value="Switch">Switch</option>
    </optgroup>
    <optgroup label="Platform">
        <option value="Server">Server</option>
        <option value="Client">Client</option>
    </optgroup>
    <optgroup label="Software">
        <option value="Word">Word</option>
        <option value="Excel">Excel</option>
    </optgroup>
</select>

And of course it should adjust itself based on changed selections.

And here the Javascript (ctrl + c, ctrl + v from other question):

$(document).ready(function () {
    $("checkbox[name='serviceType']:eq(0)").on("change",
        function () {
            console.log(this.value);
            $("select[name='services']:eq(0)")
                .find("optgroup,option")
                .hide()
                .filter("[label='" + this.value + "'],[label = '" + this.value + "'] > *")
                .show();
        });
});

Body:
CSS alternative (but I recommend using valid identifiers instead of numbers) :

[id="1"]:not(:checked) ~ select > [label=Application],
[id="2"]:not(:checked) ~ select > [label="Infrastructure Service"],
[id="3"]:not(:checked) ~ select > [label=Platform],
[id="4"]:not(:checked) ~ select > [label=Software] { display: none; }

<input type="checkbox" id="1" name="serviceType" checked>
<label for="1">Application</label>
<input type="checkbox" id="2" name="serviceType">
<label for="2">Infrastructure Service</label>
<input type="checkbox" id="3" name="serviceType">
<label for="3">Platform</label>
<input type="checkbox" id="4" name="serviceType" checked>
<label for="4">Software</label>
<br>
<select name="services" size=10 style="width: 166px">
    <optgroup label="Application">                      <!-- Shown -->
        <option value="Office">Office</option>
        <option value="SAP">SAP</option>
    </optgroup>
    <optgroup label="Infrastructure Service">           <!-- Hidden -->
        <option value="Router">Router</option>
        <option value="Switch">Switch</option>
    </optgroup>
    <optgroup label="Platform">                         <!-- Hidden -->
        <option value="Server">Server</option>
        <option value="Client">Client</option>
    </optgroup>
    <optgroup label="Software">                         <!-- Shown -->
        <option value="Word">Word</option>
        <option value="Excel">Excel</option>
    </optgroup>
</select>

JavaScript might be needed to deselect options that are not displayed:

services.value = ''
document.onclick = function(e) { if (e.target.checked === false) services.value = '' }

[id="1"]:not(:checked) ~ select > [label=Application],
[id="2"]:not(:checked) ~ select > [label="Infrastructure Service"],
[id="3"]:not(:checked) ~ select > [label=Platform],
[id="4"]:not(:checked) ~ select > [label=Software] { display: none; }

<input type="checkbox" id="1" name="serviceType" checked>
<label for="1">Application</label>
<input type="checkbox" id="2" name="serviceType">
<label for="2">Infrastructure Service</label>
<input type="checkbox" id="3" name="serviceType">
<label for="3">Platform</label>
<input type="checkbox" id="4" name="serviceType" checked>
<label for="4">Software</label>
<br>
<select id="services">
    <optgroup label="Application">                      <!-- Shown -->
        <option value="Office">Office</option>
        <option value="SAP">SAP</option>
    </optgroup>
    <optgroup label="Infrastructure Service">           <!-- Hidden -->
        <option value="Router">Router</option>
        <option value="Switch">Switch</option>
    </optgroup>
    <optgroup label="Platform">                         <!-- Hidden -->
        <option value="Server">Server</option>
        <option value="Client">Client</option>
    </optgroup>
    <optgroup label="Software">                         <!-- Shown -->
        <option value="Word">Word</option>
        <option value="Excel">Excel</option>
    </optgroup>
</select>


问:
Highest appearance of a value within each group
I'm having a table with an user-ID and the Webside-IDs he navigated through. The table looks like this:

```<code>| user-ID | website-ID |
|       1 |          1 |
|       1 |          2 |
|       1 |          1 |
|       1 |          4 |
|       2 |          1 |
|       2 |          2 |
|       2 |          5 |
|       2 |          2 |
</code>```

I'd like to select the website-ID each user has been into the most. As you can see, a min, max or avg won't work here.  Any ideas?

答:
Work it out, piece-meal - step by step.

Note that the data shown does not have a primary key; there are repeated rows.  Presumably the full data set has other information such as time of visit that makes the rows unique.  It doesn't matter too much for the question at hand, but you aim to have tables with primary keys whenever possible (which is essentially always).

Note too that the identifiers 'user-ID' and 'website-ID' are not valid in standard SQL unless treated as delimited identifier; for the purposes at hand, the dashes are changed to underscores.

This treatment uses basic SQL.  It does not use ROLAP extensions, and it does not use WITH clauses that give names to common expressions.

How many times has each user been to each web site?

```<code>SELECT User_ID, Website_ID, COUNT(*) AS NumberOfVisits
  FROM WebSitesVisited
 GROUP BY User_ID, Website_ID;
</code>```

Which is the maximum number of times a user visited any web site?

```<code>SELECT User_ID, MAX(NumberOfVisits) AS MaxNumberOfVisits
  FROM (SELECT User_ID, Website_ID, COUNT(*) AS NumberOfVisits
          FROM WebSitesVisited
         GROUP BY User_ID, Website_ID
       ) AS V
 GROUP BY User_ID;
</code>```

Which web sites did a given user visit the most times?

```<code>SELECT V.User_ID, V.Website_ID, V.NumberOfVisits
  FROM (SELECT User_ID, MAX(NumberOfVisits) AS MaxNumberOfVisits
          FROM (SELECT User_ID, Website_ID, COUNT(*) AS NumberOfVisits
                  FROM WebSitesVisited
                 GROUP BY User_ID, Website_ID
               ) AS V2
         GROUP BY User_ID
       ) AS M
  JOIN (SELECT User_ID, Website_ID, COUNT(*) AS NumberOfVisits
          FROM WebSitesVisited
         GROUP BY User_ID, Website_ID
       ) AS V
    ON M.User_ID = V.User_ID AND M.NumberOfVisits = V.MaxNumberOfVisits
 ORDER BY V.User_ID;
</code>```

Note that if user X visited both site Y and site Z the same number of times (and that number of times was the most that user X visited any site) then both Y and Z will appear in the list for user X.

ContentLicense: CC BY-SA 2.5

Body:
I'm having a table with an user-ID and the Webside-IDs he navigated through. The table looks like this:

| user-ID | website-ID |
|       1 |          1 |
|       1 |          2 |
|       1 |          1 |
|       1 |          4 |
|       2 |          1 |
|       2 |          2 |
|       2 |          5 |
|       2 |          2 |

I'd like to select the website-ID each user has been into the most. As you can see, a min, max or avg won't work here.  Any ideas?

Body:
Work it out, piece-meal - step by step.

Note that the data shown does not have a primary key; there are repeated rows.  Presumably the full data set has other information such as time of visit that makes the rows unique.  It doesn't matter too much for the question at hand, but you aim to have tables with primary keys whenever possible (which is essentially always).

Note too that the identifiers 'user-ID' and 'website-ID' are not valid in standard SQL unless treated as delimited identifier; for the purposes at hand, the dashes are changed to underscores.

This treatment uses basic SQL.  It does not use ROLAP extensions, and it does not use WITH clauses that give names to common expressions.

How many times has each user been to each web site?

SELECT User_ID, Website_ID, COUNT(*) AS NumberOfVisits
  FROM WebSitesVisited
 GROUP BY User_ID, Website_ID;

Which is the maximum number of times a user visited any web site?

SELECT User_ID, MAX(NumberOfVisits) AS MaxNumberOfVisits
  FROM (SELECT User_ID, Website_ID, COUNT(*) AS NumberOfVisits
          FROM WebSitesVisited
         GROUP BY User_ID, Website_ID
       ) AS V
 GROUP BY User_ID;

Which web sites did a given user visit the most times?

SELECT V.User_ID, V.Website_ID, V.NumberOfVisits
  FROM (SELECT User_ID, MAX(NumberOfVisits) AS MaxNumberOfVisits
          FROM (SELECT User_ID, Website_ID, COUNT(*) AS NumberOfVisits
                  FROM WebSitesVisited
                 GROUP BY User_ID, Website_ID
               ) AS V2
         GROUP BY User_ID
       ) AS M
  JOIN (SELECT User_ID, Website_ID, COUNT(*) AS NumberOfVisits
          FROM WebSitesVisited
         GROUP BY User_ID, Website_ID
       ) AS V
    ON M.User_ID = V.User_ID AND M.NumberOfVisits = V.MaxNumberOfVisits
 ORDER BY V.User_ID;

Note that if user X visited both site Y and site Z the same number of times (and that number of times was the most that user X visited any site) then both Y and Z will appear in the list for user X.


问:
Rails 3. Leaving wrong value of integer attributes in a form
I have model 'Human' and this model has integer attribute :age.

For example, I use validation for this integer attribute :age.

When I add new 'Human' with wrong value of :age (e.g. "2aaa3") it is render me back with error, but it is also cut :age like "2". But I don't want it. I want to leave last wrong value "2aaa3".

So, question is "How can I do it?"

答:
Hi everybody who is interested in my question.

I am glad to say I've created solution by myself.
But I have several remarks to that. ))

First, the solution is:

```<code>class ApplicationController < ActionController::Base
...
...
  after_filter :restore_int_value, :only => [:create, :update]
...
...
  private
...
...
  def restore_int_value
    response.body = response.body.gsub(/(numeric.*<input id=")([^_]*)(_)([^"]*)(.*value=")(\d+)(")/){$1 + $2 + $3 + $4 + $5 + params[$2][$4] + $7}
  end
...
...
end
</code>```

Second, remarks are:

1) the solution works along such gems as 'Formtastic' and 'Simple_form'. These gems build the forms wraped in detailed html and give us possibility to use regex.
If you don't use such gems you can just wrap all your integer attributes, for example, in 'p' tag with 'numeric' class like following and I think my solution will work for this too:

```<code><p class="numeric"> <%= text_field(:human, :age) %> </p>
</code>```

2)  I think my solution will not work for integer fields of nested models in multiple-models-form. (Ryan Bates describes such kind of work in "Handle Multiple Models in One Form" from "Advanced Rails Recipes").
But if you read Ryan Bates' article you will see that he already uses JavaScript. So, working with nested models in form you need JavaScript. Then you can use JavaScript for validation too (as Kunday told). And you will not have a problem. ;)
But if you have static number of nested models in form and do not use JavaScript, then I think you can create new particular regex for your needs (similar to the one I created). I hope you will manage with this. ;)

I hope I've covered all scenarios where you can have such problem and my solution will be useful for somebody, besides me. ;)

Body:
Hi everybody who is interested in my question.

I am glad to say I've created solution by myself.
But I have several remarks to that. ))

First, the solution is:

class ApplicationController < ActionController::Base
...
...
  after_filter :restore_int_value, :only => [:create, :update]
...
...
  private
...
...
  def restore_int_value
    response.body = response.body.gsub(/(numeric.*<input id=")([^_]*)(_)([^"]*)(.*value=")(\d+)(")/){$1 + $2 + $3 + $4 + $5 + params[$2][$4] + $7}
  end
...
...
end

Second, remarks are:

1) the solution works along such gems as 'Formtastic' and 'Simple_form'. These gems build the forms wraped in detailed html and give us possibility to use regex.
If you don't use such gems you can just wrap all your integer attributes, for example, in 'p' tag with 'numeric' class like following and I think my solution will work for this too:

<p class="numeric"> <%= text_field(:human, :age) %> </p>

2)  I think my solution will not work for integer fields of nested models in multiple-models-form. (Ryan Bates describes such kind of work in "Handle Multiple Models in One Form" from "Advanced Rails Recipes").
But if you read Ryan Bates' article you will see that he already uses JavaScript. So, working with nested models in form you need JavaScript. Then you can use JavaScript for validation too (as Kunday told). And you will not have a problem. ;)
But if you have static number of nested models in form and do not use JavaScript, then I think you can create new particular regex for your needs (similar to the one I created). I hope you will manage with this. ;)

I hope I've covered all scenarios where you can have such problem and my solution will be useful for somebody, besides me. ;)


问:
If value is in another dataframe, replace multiple columns with NA
I have two data.frames like this:

```<code>#df1
ID     a1      a2     a3      b1      b2      b3     Date
3xy    Evan    Greg   Ryan   Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    Randy    Mark    Seth   12/5

#df2
Name
Evan
Mark
</code>```

If a name from any of the "a" columns appears in df2$Name, I want to replace all of the "a" columns with NA. Same for the "b" columns. My desired output would look like this:

```<code>ID     a1      a2     a3      b1      b2      b3     Date
3xy    NA      NA     NA     Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    NA       NA      NA     12/5
</code>```

I've found several other posts that appear to be on similar topics, but I haven't found a way to get this to work. I've been able to replace the names in df1 that appear in df2 with NA using the code below, but haven't figured out how to replace the other columns that begin with the same letter:

```<code>df1[apply(df1, 2, function(df1) df1 %in% df2$Name)] <- NA
</code>```

Gives me an output like this:

```<code>ID     a1      a2     a3      b1      b2      b3     Date
3xy    NA      Greg   Ryan   Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    Randy    NA      Seth   12/5
</code>```

I also keep trying different ifelse statements, but no success.

答:
```<code>library(tidyverse)
df3 <- df1 %>%
  gather(key, value, -ID, -Date) %>%
  mutate(group = substr(key, 1, 1)) %>%
  select(group, ID, value) %>%
  inner_join(df2, by = c("value" = "Name")) %>%
  select(group, ID)

df1 %>%
  gather(key, value, -ID, -Date) %>%
  mutate(group = substr(key, 1, 1)) %>%
  anti_join(df3) %>%
  select(-group) %>%
  spread(key, value) %>%
  select(ID, matches("^a"), matches("^b"), Date)
</code>```

<p>Output: </p>

```<code># A tibble: 2 x 8
     ID    a1    a2    a3    b1    b2    b3  Date
* <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1   3xy  <NA>  <NA>  <NA>   Ben   Bob  Alex  12/3
2   4lm  John  Bill   Sue  <NA>  <NA>  <NA>  12/5
</code>```

Body:
I have two data.frames like this:

#df1
ID     a1      a2     a3      b1      b2      b3     Date
3xy    Evan    Greg   Ryan   Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    Randy    Mark    Seth   12/5

#df2
Name
Evan
Mark

If a name from any of the "a" columns appears in df2$Name, I want to replace all of the "a" columns with NA. Same for the "b" columns. My desired output would look like this:

ID     a1      a2     a3      b1      b2      b3     Date
3xy    NA      NA     NA     Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    NA       NA      NA     12/5

I've found several other posts that appear to be on similar topics, but I haven't found a way to get this to work. I've been able to replace the names in df1 that appear in df2 with NA using the code below, but haven't figured out how to replace the other columns that begin with the same letter:

df1[apply(df1, 2, function(df1) df1 %in% df2$Name)] <- NA

Gives me an output like this:

ID     a1      a2     a3      b1      b2      b3     Date
3xy    NA      Greg   Ryan   Ben      Bob     Alex   12/3
4lm    John    Bill   Sue    Randy    NA      Seth   12/5

I also keep trying different ifelse statements, but no success.

Body:
library(tidyverse)
df3 <- df1 %>%
  gather(key, value, -ID, -Date) %>%
  mutate(group = substr(key, 1, 1)) %>%
  select(group, ID, value) %>%
  inner_join(df2, by = c("value" = "Name")) %>%
  select(group, ID)

df1 %>%
  gather(key, value, -ID, -Date) %>%
  mutate(group = substr(key, 1, 1)) %>%
  anti_join(df3) %>%
  select(-group) %>%
  spread(key, value) %>%
  select(ID, matches("^a"), matches("^b"), Date)

Output:

# A tibble: 2 x 8
     ID    a1    a2    a3    b1    b2    b3  Date
* <chr> <chr> <chr> <chr> <chr> <chr> <chr> <chr>
1   3xy  <NA>  <NA>  <NA>   Ben   Bob  Alex  12/3
2   4lm  John  Bill   Sue  <NA>  <NA>  <NA>  12/5


问:
How to create a dind docker image with azure-cli on Alpine linux?
I am trying to install the azure-cli in the dind:latest image based on alpine.

For context, I want to use it to connect to AKS and deploy an app to Kubernetes via Gitlab.

In my gitlab-ci.yml file I start with this

```<code>image: docker:latest
services:
  - docker:dind
</code>```

and then I try to install the azure-cli

```<code>deploy-to-k8s--dev: # k8s namespace "dev"
  stage: deploy-to-k8s
#  image: microsoft/azure-cli
  script:
    # I need the azure cli in the dind:latest container
    # so install bash,curl and finally the cli
    - apk update
    - apk upgrade
    - apk add bash
    - apk add --no-cache curl

    - curl -L https://aka.ms/InstallAzureCli | bash
    - az
</code>```

and I get the following error

```<code>$ curl -L https://aka.ms/InstallAzureCli | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100   167  100   167    0     0    167      0  0:00:01 --:--:--  0:00:01   644

100  1367  100  1367    0     0   1367      0  0:00:01 --:--:--  0:00:01  1367
mktemp: Invalid argument
ERROR: Job failed: error executing remote command: command terminated with non-zero exit code: Error executing in Docker Container: 1
</code>```

It is the first time that I try to work with Alpine Linux and I have no idea how it is built and what tools it uses...

Has anyone any suggestion?

EDIT

based on the accepted answer this is the final code that works

```<code>deploy-to-k8s--dev: # k8s namespace "dev"
  stage: deploy-to-k8s
  script:
    # I need the azure cli in the dind:latest container
    # so install bash,curl and finally the cli
    - apk update
    - apk upgrade
    - apk add bash make py-pip
    - apk add --virtual=build gcc libffi-dev musl-dev openssl-dev python2-dev
    - pip install azure-cli
    - apk del --purge build
    - az -h
</code>```

答:
This helped me in one of my alpine based image</p>

```<code>apk update
apk add bash py-pip
apk add --virtual=build gcc libffi-dev musl-dev openssl-dev python- dev
pip install azure-cli
apk del --purge build
</code>```

Body:
I am trying to install the azure-cli in the dind:latest image based on alpine.

For context, I want to use it to connect to AKS and deploy an app to Kubernetes via Gitlab.

In my gitlab-ci.yml file I start with this

image: docker:latest
services:
  - docker:dind

and then I try to install the azure-cli

deploy-to-k8s--dev: # k8s namespace "dev"
  stage: deploy-to-k8s
#  image: microsoft/azure-cli
  script:
    # I need the azure cli in the dind:latest container
    # so install bash,curl and finally the cli
    - apk update
    - apk upgrade
    - apk add bash
    - apk add --no-cache curl

    - curl -L https://aka.ms/InstallAzureCli | bash
    - az

and I get the following error

$ curl -L https://aka.ms/InstallAzureCli | bash
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100   167  100   167    0     0    167      0  0:00:01 --:--:--  0:00:01   644

100  1367  100  1367    0     0   1367      0  0:00:01 --:--:--  0:00:01  1367
mktemp: Invalid argument
ERROR: Job failed: error executing remote command: command terminated with non-zero exit code: Error executing in Docker Container: 1

It is the first time that I try to work with Alpine Linux and I have no idea how it is built and what tools it uses...

Has anyone any suggestion?

EDIT

based on the accepted answer this is the final code that works

deploy-to-k8s--dev: # k8s namespace "dev"
  stage: deploy-to-k8s
  script:
    # I need the azure cli in the dind:latest container
    # so install bash,curl and finally the cli
    - apk update
    - apk upgrade
    - apk add bash make py-pip
    - apk add --virtual=build gcc libffi-dev musl-dev openssl-dev python2-dev
    - pip install azure-cli
    - apk del --purge build
    - az -h

Body:
This helped me in one of my alpine based image

apk update
apk add bash py-pip
apk add --virtual=build gcc libffi-dev musl-dev openssl-dev python- dev
pip install azure-cli
apk del --purge build

ContentLicense: CC BY-SA 4.0


问:
Bash preserve whitespaces and newlines from file content to variable
I have this code

```<code>TOKEN=$(cat ./config/token)

echo "$TOKEN"

cat > variables.env <<EOF
TOKEN=`echo "$TOKEN"`
EOF
</code>```

I am trying to get the content of a file and output it in a new file prefixed by some text. The first echo in the console echoes the output I want, keeping the whitespaces and newlines.

However, in the new file the output is just the first line of the original string, while I'd like the same output I can see in the console with the first echo.

答:
you are doing it in a very convoluted way, there are easier methods

```<code>sed '1s/./TOKEN=&/' file > newfile
</code>```

will insert TOKEN= on the first line.  This has an additional benefit of not modifying empty files (at least one char should exist in the original file).  If that's not intended you can use unconditional insert.

Body:
I have this code

TOKEN=$(cat ./config/token)

echo "$TOKEN"

cat > variables.env <<EOF
TOKEN=`echo "$TOKEN"`
EOF

I am trying to get the content of a file and output it in a new file prefixed by some text. The first echo in the console echoes the output I want, keeping the whitespaces and newlines.

However, in the new file the output is just the first line of the original string, while I'd like the same output I can see in the console with the first echo.

Body:
you are doing it in a very convoluted way, there are easier methods

sed '1s/./TOKEN=&/' file > newfile

will insert TOKEN= on the first line.  This has an additional benefit of not modifying empty files (at least one char should exist in the original file).  If that's not intended you can use unconditional insert.


问:
Calling Navigation Menu from Master class in the Default Page
I have my navigation menu declared in the master class. I want to use it in the Default page but for some reason is not picking it up! Just to note the menu items are declared in the SiteMap file!

Here is the Master class menu I am trying to call:

```<code><asp:Menu ID="NavigationSiteMapMenu" runat="server" CssClass="menu"
        Orientation="Horizontal"  DataSourceID="SiteMapDataSource1">
</code>```

Here is the code I am using it in Default Page (In the Page Load Method) :

```<code>        Dim testMenu As Menu = CType(Master.FindControl("NavigationSiteMapMenu"), Menu)
</code>```

And here I am testing if it returns list of items but it doesn't the count is 0.

```<code>        Dim test = testMenu.Items
</code>```

Do you guys have any idea why my above code is not working, the logic seems perfect to me but clearly not to VB.NET!

答:
This is the correct syntax:

```<code>  Dim testMenu As Menu = CType(Master.FindControl("NavigationSiteMapMenu"), Menu)
</code>```

My problem was that on one of the aspx pages I wasn't referencing the Master page. So please make sure the Master Page is referenced in all the required pages.

All the best and Good Luck!

Body:
I have my navigation menu declared in the master class. I want to use it in the Default page but for some reason is not picking it up! Just to note the menu items are declared in the SiteMap file!

Here is the Master class menu I am trying to call:

<asp:Menu ID="NavigationSiteMapMenu" runat="server" CssClass="menu"
        Orientation="Horizontal"  DataSourceID="SiteMapDataSource1">

Here is the code I am using it in Default Page (In the Page Load Method) :

        Dim testMenu As Menu = CType(Master.FindControl("NavigationSiteMapMenu"), Menu)

And here I am testing if it returns list of items but it doesn't the count is 0.

        Dim test = testMenu.Items

Do you guys have any idea why my above code is not working, the logic seems perfect to me but clearly not to VB.NET!

Body:
This is the correct syntax:

  Dim testMenu As Menu = CType(Master.FindControl("NavigationSiteMapMenu"), Menu)

My problem was that on one of the aspx pages I wasn't referencing the Master page. So please make sure the Master Page is referenced in all the required pages.

All the best and Good Luck!


问:
Convert DataTable to List<T>
I have an strongly typed DataTable of type MyType, I'd like convert it in a List<MyType>.

How can I do this ?

Thanks.

答:
There is a little example that you can use </p>

```<code>            DataTable dt = GetCustomersDataTable(null);

            IEnumerable<SelectListItem> lstCustomer = dt.AsEnumerable().Select(x => new SelectListItem()
            {
                Value = x.Field<string>("CustomerId"),
                Text = x.Field<string>("CustomerDescription")
            }).ToList();

            return lstCustomer;
</code>```

Title: Convert DataTable to List<T>

Body:
There is a little example that you can use

            DataTable dt = GetCustomersDataTable(null);

            IEnumerable<SelectListItem> lstCustomer = dt.AsEnumerable().Select(x => new SelectListItem()
            {
                Value = x.Field<string>("CustomerId"),
                Text = x.Field<string>("CustomerDescription")
            }).ToList();

            return lstCustomer;


问:
How to convert a c program to 8051 microcontroller assembly code
I looked through several sites ,but, I am not able to find a suitable answer. It seems really hard to convert my c programme to assembly code...</p>

答:
if you use keil uvision ,than
1. goto Debug >> click "start/stop Debug Session" it'll start simulator if ide 2.
2. view >> click Disassembly Window and you can see the assembly.

if not then go to below link and download it DIS8051 Cross-Disassembler V2.1 (you need hex file to convert your program to assembly of 8051)
http://bit.kuas.edu.tw/~8051/


问:
How do I combine working days of a month with annual holidays in SQL?
I have a table that contains a list of public holidays for the current year. Now, the working days here are Monday-Saturday. So, I am trying to link the annual holidays table with my query in such a way that I get the list of Working Days for a given interval(Year, Month, Week etc)
I have the code that gives me working days including Saturday but I am not able to subtract(link) the annual holidays.

Code for getting working days:

```<code>DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2017-12-01 10:00:00.000'
SET @EndDate = '2017-12-31 00:00:00.000'

SELECT
   (DATEDIFF(dd, @StartDate, @EndDate) + 1)
  -(DATEDIFF(wk, @StartDate, @EndDate))
  -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END) AS WorkingDays
</code>```

The table AnnualHolidays has the layout :

```<code>Id                  Date                                Description
----------- -----------------------                -------------------
50          2017-10-21 00:00:00.000                    Holiday 1
49          2017-10-20 00:00:00.000                    Holiday 2
</code>```

So, Is there any way that I can subtract the annual holiday coming in the Interval of @StartDate and @EndDate such that I can get the actual Working days of the specified interval

答:
One way would be to generate the valid range and than subtract the the holidays and count the result. I'm using a recursive function for the date range, but there are more ways to do this that can be more effective on larger ranges.</p>

```<code>DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2017-12-01 10:00:00.000'
SET @EndDate = '2017-12-31 00:00:00.000'

;WITH Dates AS (
        SELECT
            [Date] = @StartDate

        UNION ALL

        SELECT
            [Date] = DATEADD(DAY, 1, [Date])
        FROM
            Dates
        WHERE
            Date <= @EndDate
)
SELECT COUNT(*)
from
(
    SELECT
        [Date]
    FROM
        Dates
    WHERE
        DATENAME(dw, [Date]) != 'Sunday'

    EXCEPT

    select
        [Date]
    from
        AnnualHolidays
) tbl
</code>```

Body:
I have a table that contains a list of public holidays for the current year. Now, the working days here are Monday-Saturday. So, I am trying to link the annual holidays table with my query in such a way that I get the list of Working Days for a given interval(Year, Month, Week etc)
I have the code that gives me working days including Saturday but I am not able to subtract(link) the annual holidays.

Code for getting working days:

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2017-12-01 10:00:00.000'
SET @EndDate = '2017-12-31 00:00:00.000'

SELECT
   (DATEDIFF(dd, @StartDate, @EndDate) + 1)
  -(DATEDIFF(wk, @StartDate, @EndDate))
  -(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday' THEN 1 ELSE 0 END) AS WorkingDays

The table AnnualHolidays has the layout :

Id                  Date                                Description
----------- -----------------------                -------------------
50          2017-10-21 00:00:00.000                    Holiday 1
49          2017-10-20 00:00:00.000                    Holiday 2

So, Is there any way that I can subtract the annual holiday coming in the Interval of @StartDate and @EndDate such that I can get the actual Working days of the specified interval

Body:
One way would be to generate the valid range and than subtract the the holidays and count the result. I'm using a recursive function for the date range, but there are more ways to do this that can be more effective on larger ranges.

DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2017-12-01 10:00:00.000'
SET @EndDate = '2017-12-31 00:00:00.000'

;WITH Dates AS (
        SELECT
            [Date] = @StartDate

        UNION ALL

        SELECT
            [Date] = DATEADD(DAY, 1, [Date])
        FROM
            Dates
        WHERE
            Date <= @EndDate
)
SELECT COUNT(*)
from
(
    SELECT
        [Date]
    FROM
        Dates
    WHERE
        DATENAME(dw, [Date]) != 'Sunday'

    EXCEPT

    select
        [Date]
    from
        AnnualHolidays
) tbl


问:
How to check if template argument is a callable with a given signature
Basically, what I want to achieve is compile-time verification (with possibly nice error message) that registered callable (either a function, a lambda, a struct with call operator) has correct signature. Example (contents of the static_assert are to be filled):

```<code>struct A {
  using Signature = void(int, double);

  template <typename Callable>
  void Register(Callable &&callable) {
    static_assert(/* ... */);
    callback = callable;
  }

  std::function<Signature> callback;
};
</code>```

答:
Most of the answers are focused on basically answering the question: can you call the given function object with values of these types. This is not the same as matching the signature, as it allows many implicit conversions that you say you don't want. In order to get a more strict match we have to do a bunch of TMP. First, this answer: Call function with part of variadic arguments shows how to get the exact types of the arguments and return type of a callable. Code reproduced here:

```<code>template <typename T>
struct function_traits : public function_traits<decltype(&T::operator())>
{};

template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const>
{
    using result_type = ReturnType;
    using arg_tuple = std::tuple<Args...>;
    static constexpr auto arity = sizeof...(Args);
};

template <typename R, typename ... Args>
struct function_traits<R(&)(Args...)>
{
    using result_type = R;
    using arg_tuple = std::tuple<Args...>;
    static constexpr auto arity = sizeof...(Args);
};
</code>```

Having done that, you can now put a series of static asserts in your code:

```<code>struct A {
  using Signature = void(int, double);

  template <typename Callable>
  void Register(Callable &&callable) {
    using ft = function_traits<Callable>;
    static_assert(std::is_same<int,
        std::decay_t<std::tuple_element_t<0, typename ft::arg_tuple>>>::value, "");
    static_assert(std::is_same<double,
        std::decay_t<std::tuple_element_t<1, typename ft::arg_tuple>>>::value, "");
    static_assert(std::is_same<void,
        std::decay_t<typename ft::result_type>>::value, "");

    callback = callable;
  }

  std::function<Signature> callback;
};
</code>```

Since you are passing by value this is basically all you need. If you are passing by reference, I would add an additional static assert where you use one of the other answers; probably songyuanyao's answer. This would take care of cases where for example the base type was the same, but the const qualification went in the wrong direction.

You could of course make this all generic over the type Signature, instead of doing what I do (simply repeating the types in the static assert). This would be nicer but it would have added even more complex TMP to an already non-trivial answer; if you feel like you will use this with many different Signatures or that it is changing often it is probably worth adding that code as well.

Here's a live example: http://coliru.stacked-crooked.com/a/cee084dce9e8dc09. In particular, my example:

```<code>void foo(int, double) {}
void foo2(double, double) {}

int main()
{
    A a;
    // compiles
    a.Register([] (int, double) {});
    // doesn't
    //a.Register([] (int, double) { return true; });
    // works
    a.Register(foo);
    // doesn't
    //a.Register(foo2);
}
</code>```

Body:
Basically, what I want to achieve is compile-time verification (with possibly nice error message) that registered callable (either a function, a lambda, a struct with call operator) has correct signature. Example (contents of the static_assert are to be filled):

struct A {
  using Signature = void(int, double);

  template <typename Callable>
  void Register(Callable &&callable) {
    static_assert(/* ... */);
    callback = callable;
  }

  std::function<Signature> callback;
};

Body:
Most of the answers are focused on basically answering the question: can you call the given function object with values of these types. This is not the same as matching the signature, as it allows many implicit conversions that you say you don't want. In order to get a more strict match we have to do a bunch of TMP. First, this answer: Call function with part of variadic arguments shows how to get the exact types of the arguments and return type of a callable. Code reproduced here:

template <typename T>
struct function_traits : public function_traits<decltype(&T::operator())>
{};

template <typename ClassType, typename ReturnType, typename... Args>
struct function_traits<ReturnType(ClassType::*)(Args...) const>
{
    using result_type = ReturnType;
    using arg_tuple = std::tuple<Args...>;
    static constexpr auto arity = sizeof...(Args);
};

template <typename R, typename ... Args>
struct function_traits<R(&)(Args...)>
{
    using result_type = R;
    using arg_tuple = std::tuple<Args...>;
    static constexpr auto arity = sizeof...(Args);
};

Having done that, you can now put a series of static asserts in your code:

struct A {
  using Signature = void(int, double);

  template <typename Callable>
  void Register(Callable &&callable) {
    using ft = function_traits<Callable>;
    static_assert(std::is_same<int,
        std::decay_t<std::tuple_element_t<0, typename ft::arg_tuple>>>::value, "");
    static_assert(std::is_same<double,
        std::decay_t<std::tuple_element_t<1, typename ft::arg_tuple>>>::value, "");
    static_assert(std::is_same<void,
        std::decay_t<typename ft::result_type>>::value, "");

    callback = callable;
  }

  std::function<Signature> callback;
};

Since you are passing by value this is basically all you need. If you are passing by reference, I would add an additional static assert where you use one of the other answers; probably songyuanyao's answer. This would take care of cases where for example the base type was the same, but the const qualification went in the wrong direction.

You could of course make this all generic over the type Signature, instead of doing what I do (simply repeating the types in the static assert). This would be nicer but it would have added even more complex TMP to an already non-trivial answer; if you feel like you will use this with many different Signatures or that it is changing often it is probably worth adding that code as well.

Here's a live example: http://coliru.stacked-crooked.com/a/cee084dce9e8dc09. In particular, my example:

void foo(int, double) {}
void foo2(double, double) {}

int main()
{
    A a;
    // compiles
    a.Register([] (int, double) {});
    // doesn't
    //a.Register([] (int, double) { return true; });
    // works
    a.Register(foo);
    // doesn't
    //a.Register(foo2);
}


问:
JavaScript logic error
I am trying to get JavaScript to generate a table with data from an array for me however when I run this code it enters the same data twice. Does anyone know what mistake I am making?

The HTML:

```<code><body>
<div class="container">
    <h1 class="page-header">Bookings</h1>
    <table id="bookTable" class="table table-bordered">
        <thead>
            <tr>
            <th>First Name</th>
            <th>Second Name</th>
            <th>Email</th>
            <th>From</th>
            <th>To</th>
        </tr>
        <tr>
            <td type="text" id="firstName"></td>
            <td type="text" id="secondName"></td>
            <td type="text" id="email"></td>
            <td type="text"id="dateFrom"></td>
            <td type="text"id="dateTo"></td>
        </tr>
    </thead>
  </table>
</div>
</code>```

The JavaScript is using a guide I found that I have adapted. In reality, the array comes from a python file that is fed in as a variable when Flask displays the template. I have used the same data that python prints out when looking at the contents of the variable that is passed.

```<code><script>
    var listOfBookings = [John`Doe`jd@gmail.com`03/01/2018`18/01/2018`John`Doe`jd@gmail.com`26/12/2017`27/12/2017]
    var array = listOfBookings.split("`");
    var count = 1
    for (var i = 0; i < array.length; i++){
        if (1%(i+1) == 0){
            var firstName = array[i];
            }
        if (2%(i+1) == 0){
            var secondName = array[i];
            }
        if (3%(i+1) == 0){
            var email = array[i];
            }
        if (4%(i+1) == 0){
            var dateFrom = array[i];
            }
        if (5%(i+1) == 0){
            var dateTo = array[i];
            }

        // Addapted from http://talkerscode.com/webtricks/add-edit-and-
delete-rows-from-table-dynamically-using-javascript.php
        if(count%5 == 0){
            var table=document.getElementById("bookTable");
            var table_len=(table.rows.length)-1;
            var row = table.insertRow(table_len).outerHTML="<tr
id='row"+table_len+"'><td id='date_row"+table_len+"'>"+firstName+"</td><td
id='name_row"+table_len+"'>"+secondName+"</td><td
id='country_row"+table_len+"'>"+email+"</td><td
id='country_row"+table_len+"'>"+dateFrom+"</td><td
id='country_row"+table_len+"'>"+dateTo+"</td></tr>";
        }
        count += 1
    }
</script>
</code>```

答:
Your array seems to have 10 values and from all your if statements none of them will have their condition equal true when i is bigger then 4.

All the variables (firstName, secondName, email, dataFrom, dateTo) will have the same value when count is 10 as they had when it was 5

You could do something like this:

var array = ["John","Doe","jd@gmail.com","03/01/2018","18/01/2018","John","Doe","jd@gmail.com","26/12/2017","27/12/2017"];
var table=document.getElementById("bookTable");

for (var i = 0; array.length % 5 === 0 && i < array.length;){
     var firstName = array[i++];
     var secondName = array[i++];
     var email = array[i++];
     var dateFrom = array[i++];
     var dateTo = array[i++];
     var table_len = (table.rows.length)-1;
     var row = table.insertRow(table_len).outerHTML="
"+firstName+"	"+secondName+"	"+email+"	"+dateFrom+"	"+dateTo+"
";
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
<div class="container">
    <h1 class="page-header">Bookings</h1>
    <table id="bookTable" class="table table-bordered">
        <thead>
            <tr>
            <th>First Name</th>
            <th>Second Name</th>
            <th>Email</th>
            <th>From</th>
            <th>To</th>
        </tr>
        <tr>
            <td type="text" id="firstName"></td>
            <td type="text" id="secondName"></td>
            <td type="text" id="email"></td>
            <td type="text"id="dateFrom"></td>
            <td type="text"id="dateTo"></td>
        </tr>
    </thead>
  </table>
</div></code>```

Title: JavaScript logic error

Body:
I am trying to get JavaScript to generate a table with data from an array for me however when I run this code it enters the same data twice. Does anyone know what mistake I am making?

The HTML:

Bookings

            First Name
            Second Name
            Email
            From
            To

The JavaScript is using a guide I found that I have adapted. In reality, the array comes from a python file that is fed in as a variable when Flask displays the template. I have used the same data that python prints out when looking at the contents of the variable that is passed.

Body:
Your array seems to have 10 values and from all your if statements none of them will have their condition equal true when i is bigger then 4.

All the variables (firstName, secondName, email, dataFrom, dateTo) will have the same value when count is 10 as they had when it was 5

You could do something like this:

var array = ["John","Doe","jd@gmail.com","03/01/2018","18/01/2018","John","Doe","jd@gmail.com","26/12/2017","27/12/2017"];
var table=document.getElementById("bookTable");

for (var i = 0; array.length % 5 === 0 && i < array.length;){
     var firstName = array[i++];
     var secondName = array[i++];
     var email = array[i++];
     var dateFrom = array[i++];
     var dateTo = array[i++];
     var table_len = (table.rows.length)-1;
     var row = table.insertRow(table_len).outerHTML="<tr id='row"+table_len+"'><td id='date_row"+table_len+"'>"+firstName+"</td><td id='name_row"+table_len+"'>"+secondName+"</td><td id='country_row"+table_len+"'>"+email+"</td><td id='country_row"+table_len+"'>"+dateFrom+"</td><td id='country_row"+table_len+"'>"+dateTo+"</td></tr>";
    }

<body>
<div class="container">
    <h1 class="page-header">Bookings</h1>
    <table id="bookTable" class="table table-bordered">
        <thead>
            <tr>
            <th>First Name</th>
            <th>Second Name</th>
            <th>Email</th>
            <th>From</th>
            <th>To</th>
        </tr>
        <tr>
            <td type="text" id="firstName"></td>
            <td type="text" id="secondName"></td>
            <td type="text" id="email"></td>
            <td type="text"id="dateFrom"></td>
            <td type="text"id="dateTo"></td>
        </tr>
    </thead>
  </table>
</div>


问:
android How to get image path from GridView through onItemClick listener
Got stuck a bit since i cannot understand how to get the path from
a picture i click in the GridView.

This listener is the problem since i load the GridView with images from a folder on the sdcard.

```<code>public void onItemClick(AdapterView parent, View v, int position, long id)
</code>```

I can only see example on how to use the "position" when the GridView is loaded from resources.

Can anyone give me a hint how to do this.
Im reading and trying this

```<code>String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection,
null,
null,
null)
</code>```

But that will give me all images from sdcard root.
My folder is "sdcard/PTPPservice"

I will from here send an intent to show the image like:

```<code>      Intent intent = new Intent(getApplicationContext(), ViewImage.class);
      intent.putExtra("filename", imagePath);
      startActivity(intent);
</code>```

答:
Found the solution, so i answer my own quesion.
The orgPath is a string i added and saves the path during loadind of images</p>

```<code>public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

    ImageAdapter i = (ImageAdapter)parent.getAdapter();
    LoadedImage l = (LoadedImage)i.getItem(position);

    Intent intent = new Intent(getApplicationContext(), ViewImage.class);
    intent.putExtra("filename", l.orgPath);
    startActivity(intent);
    return;

}
</code>```

Body:
Got stuck a bit since i cannot understand how to get the path from
a picture i click in the GridView.

This listener is the problem since i load the GridView with images from a folder on the sdcard.

public void onItemClick(AdapterView parent, View v, int position, long id)

I can only see example on how to use the "position" when the GridView is loaded from resources.

Can anyone give me a hint how to do this.
Im reading and trying this

String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
projection,
null,
null,
null)

But that will give me all images from sdcard root.
My folder is "sdcard/PTPPservice"

I will from here send an intent to show the image like:

      Intent intent = new Intent(getApplicationContext(), ViewImage.class);
      intent.putExtra("filename", imagePath);
      startActivity(intent);

Body:
Found the solution, so i answer my own quesion.
The orgPath is a string i added and saves the path during loadind of images

public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

    ImageAdapter i = (ImageAdapter)parent.getAdapter();
    LoadedImage l = (LoadedImage)i.getItem(position);

    Intent intent = new Intent(getApplicationContext(), ViewImage.class);
    intent.putExtra("filename", l.orgPath);
    startActivity(intent);
    return;

}