问:
Is it possible to deploy a GUI application using Kubernetes?
I have a docker container that runs a GUI application, I can successfully run it, using this command

```<code>sudo docker run --net=host --env="DISPLAY" --volume="$HOME/.Xauthority:/root/.Xauthority:rw" -it test
</code>```

I have already tried to create this deployment file:

```<code>{
  "kind": "Deployment",
  "apiVersion": "extensions/v1beta1",
  "metadata": {
    "name": "test",
    "namespace": "default",
    "selfLink": "/apis/extensions/v1beta1/namespaces/default/deployments/gazebo",
    "uid": "249a12a9-83b8-11e9-8ec2-32ccf6441134",
    "resourceVersion": "6165060",
    "generation": 1,
    "creationTimestamp": "2019-05-31T15:24:12Z",
    "labels": {
      "k8s-app": "test"
    },
    "annotations": {
      "deployment.kubernetes.io/revision": "1"
    }
  },
  "spec": {
    "replicas": 1,
    "selector": {
      "matchLabels": {
        "k8s-app": "test"
      }
    },
    "template": {
      "metadata": {
        "name": "test",
        "creationTimestamp": null,
        "labels": {
          "k8s-app": "test"
        }
      },
      "spec": {
        "volumes": [
          {
            "name": "test",
            "hostPath": {
              "path": "$HOME/.Xauthority:/root/.Xauthority:rw",
              "type": ""
            }
          }
        ],
        "containers": [
          {
            "name": "test",
            "image": "test:1.0.12",
            "env": [
              {
                "name": "DISPLAY",
                "value": ":0"
              }
            ],
            "resources": {},
            "terminationMessagePath": "/dev/termination-log",
            "terminationMessagePolicy": "File",
            "imagePullPolicy": "IfNotPresent",
            "securityContext": {
              "privileged": false,
              "procMount": "Default"
            },
            "stdin": true
          }
        ],
        "restartPolicy": "Always",
        "terminationGracePeriodSeconds": 30,
        "dnsPolicy": "ClusterFirst",
        "nodeSelector": {
          "component": "test"
        },
        "hostNetwork": true,
        "securityContext": {},
        "schedulerName": "default-scheduler"
      }
    },
    "strategy": {
      "type": "RollingUpdate",
      "rollingUpdate": {
        "maxUnavailable": "25%",
        "maxSurge": "25%"
      }
    },
    "revisionHistoryLimit": 10,
    "progressDeadlineSeconds": 600
  },
  "status": {
    "observedGeneration": 1,
    "replicas": 1,
    "updatedReplicas": 1,
    "unavailableReplicas": 1,
    "conditions": [
      {
        "type": "Progressing",
        "status": "True",
        "lastUpdateTime": "2019-05-31T15:24:14Z",
        "lastTransitionTime": "2019-05-31T15:24:12Z",
        "reason": "NewReplicaSetAvailable",
        "message": "ReplicaSet \"test-dbfdb6467\" has successfully progressed."
      },
      {
        "type": "Available",
        "status": "False",
        "lastUpdateTime": "2019-05-31T15:40:21Z",
        "lastTransitionTime": "2019-05-31T15:40:21Z",
        "reason": "MinimumReplicasUnavailable",
        "message": "Deployment does not have minimum availability."
      }
    ]
  }
}
</code>```

I have tried to inspect the resulting containers and I have obtained these results:

For the one deployed with kubernetes the result is

```<code>[
    {
        "Id": "114e1d307b8260eaa02bfcf214031cf34ae522cf55258731a8a6dca535527995",
        "Created": "2019-05-31T15:24:13.320599267Z",
        "Path": "/home/startup.sh",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 10908,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2019-05-31T15:24:13.627542552Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:2b02610511b1d09925b5b0b2471efea087819942c36c0c0bf490d6a28709f54e",
        "ResolvConfPath": "/home/docker/containers/8537a1c6038f5d6b4186d0b56a6b839207477825d0ad99d8610d36f66967495e/resolv.conf",
        "HostnamePath": "/home/docker/containers/8537a1c6038f5d6b4186d0b56a6b839207477825d0ad99d8610d36f66967495e/hostname",
        "HostsPath": "/var/lib/kubelet/pods/249ff7a4-83b8-11e9-8ec2-32ccf6441134/etc-hosts",
        "LogPath": "/home/docker/containers/114e1d307b8260eaa02bfcf214031cf34ae522cf55258731a8a6dca535527995/114e1d307b8260eaa02bfcf214031cf34ae522cf55258731a8a6dca535527995-json.log",
        "Name": "/k8s_gazebo_gazebo-dbfdb6467-fd448_default_249ff7a4-83b8-11e9-8ec2-32ccf6441134_0",
        "RestartCount": 0,
        "Driver": "aufs",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": [
                "/var/lib/kubelet/pods/249ff7a4-83b8-11e9-8ec2-32ccf6441134/volumes/kubernetes.io~secret/default-token-4ncqs:/var/run/secrets/kubernetes.io/serviceaccount:ro",
                "/var/lib/kubelet/pods/249ff7a4-83b8-11e9-8ec2-32ccf6441134/etc-hosts:/etc/hosts",
                "/var/lib/kubelet/pods/249ff7a4-83b8-11e9-8ec2-32ccf6441134/containers/gazebo/f4a9bfa2:/dev/termination-log"
            ],
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "container:8537a1c6038f5d6b4186d0b56a6b839207477825d0ad99d8610d36f66967495e",
            "PortBindings": null,
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Dns": null,
            "DnsOptions": null,
            "DnsSearch": null,
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "container:8537a1c6038f5d6b4186d0b56a6b839207477825d0ad99d8610d36f66967495e",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 1000,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": [
                "seccomp=unconfined"
            ],
            "UTSMode": "host",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 2,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "/kubepods/besteffort/pod249ff7a4-83b8-11e9-8ec2-32ccf6441134",
            "BlkioWeight": 0,
            "BlkioWeightDevice": null,
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 100000,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DiskQuota": 0,
            "KernelMemory": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": 0,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/asound",
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": null,
            "Name": "aufs"
        },
        "Mounts": [
            {
                "Type": "bind",
                "Source": "/var/lib/kubelet/pods/249ff7a4-83b8-11e9-8ec2-32ccf6441134/volumes/kubernetes.io~secret/default-token-4ncqs",
                "Destination": "/var/run/secrets/kubernetes.io/serviceaccount",
                "Mode": "ro",
                "RW": false,
                "Propagation": "rprivate"
            },
            {
                "Type": "bind",
                "Source": "/var/lib/kubelet/pods/249ff7a4-83b8-11e9-8ec2-32ccf6441134/etc-hosts",
                "Destination": "/etc/hosts",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            },
            {
                "Type": "bind",
                "Source": "/var/lib/kubelet/pods/249ff7a4-83b8-11e9-8ec2-32ccf6441134/containers/gazebo/f4a9bfa2",
                "Destination": "/dev/termination-log",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],
        "Config": {
            "Hostname": "davidePC",
            "Domainname": "",
            "User": "0",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": true,
            "StdinOnce": false,
            "Env": [
                "DISPLAY=:0",
                "KUBERNETES_PORT_443_TCP_PROTO=tcp",
                "KUBERNETES_PORT_443_TCP_PORT=443",
                "KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1",
                "KUBERNETES_SERVICE_HOST=10.96.0.1",
                "KUBERNETES_SERVICE_PORT=443",
                "KUBERNETES_SERVICE_PORT_HTTPS=443",
                "KUBERNETES_PORT=tcp://10.96.0.1:443",
                "KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443",
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "LANG=C.UTF-8",
                "LC_ALL=C.UTF-8",
                "ROS_DISTRO=kinetic",
                "ROS_MASTER_URI=http://localhost:11311",
                "ROS_PACKAGE_PATH=/opt/ros/kinetic/share",
                "DEBIAN_FRONTEND=noninteractive",
                "TURTLEBOT_3D_SENSOR=no3d",
                "TURTLEBOT_TOP_PLATE_DEVICE=rplidar",
                "JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64/"
            ],
            "Cmd": [],
            "Healthcheck": {
                "Test": [
                    "NONE"
                ]
            },
            "ArgsEscaped": true,
            "Image": "sha256:2b02610511b1d09925b5b0b2471efea087819942c36c0c0bf490d6a28709f54e",
            "Volumes": null,
            "WorkingDir": "/home",
            "Entrypoint": [
                "/home/startup.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "annotation.io.kubernetes.container.hash": "86f118b",
                "annotation.io.kubernetes.container.restartCount": "0",
                "annotation.io.kubernetes.container.terminationMessagePath": "/dev/termination-log",
                "annotation.io.kubernetes.container.terminationMessagePolicy": "File",
                "annotation.io.kubernetes.pod.terminationGracePeriod": "30",
                "io.kubernetes.container.logpath": "/var/log/pods/default_gazebo-dbfdb6467-fd448_249ff7a4-83b8-11e9-8ec2-32ccf6441134/gazebo/0.log",
                "io.kubernetes.container.name": "gazebo",
                "io.kubernetes.docker.type": "container",
                "io.kubernetes.pod.name": "gazebo-dbfdb6467-fd448",
                "io.kubernetes.pod.namespace": "default",
                "io.kubernetes.pod.uid": "249ff7a4-83b8-11e9-8ec2-32ccf6441134",
                "io.kubernetes.sandbox.id": "8537a1c6038f5d6b4186d0b56a6b839207477825d0ad99d8610d36f66967495e"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {}
        }
    }
]
</code>```

Instead for the one run from CLI, the result is:

```<code>[
    {
        "Id": "ed428815132ac62020e36b1d50421ec7402c3b433907575a4858617d56322366",
        "Created": "2019-05-31T15:13:51.991700539Z",
        "Path": "/home/startup.sh",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 8377,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2019-05-31T15:13:52.469581933Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:2b02610511b1d09925b5b0b2471efea087819942c36c0c0bf490d6a28709f54e",
        "ResolvConfPath": "/home/docker/containers/ed428815132ac62020e36b1d50421ec7402c3b433907575a4858617d56322366/resolv.conf",
        "HostnamePath": "/home/docker/containers/ed428815132ac62020e36b1d50421ec7402c3b433907575a4858617d56322366/hostname",
        "HostsPath": "/home/docker/containers/ed428815132ac62020e36b1d50421ec7402c3b433907575a4858617d56322366/hosts",
        "LogPath": "/home/docker/containers/ed428815132ac62020e36b1d50421ec7402c3b433907575a4858617d56322366/ed428815132ac62020e36b1d50421ec7402c3b433907575a4858617d56322366-json.log",
        "Name": "/youthful_benz",
        "RestartCount": 0,
        "Driver": "aufs",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": [
                "/home/davide/.Xauthority:/root/.Xauthority:rw"
            ],
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "host",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "shareable",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DiskQuota": 0,
            "KernelMemory": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": 0,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": null,
            "Name": "aufs"
        },
        "Mounts": [
            {
                "Type": "bind",
                "Source": "/home/davide/.Xauthority",
                "Destination": "/root/.Xauthority",
                "Mode": "rw",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],
        "Config": {
            "Hostname": "davidePC",
            "Domainname": "",
            "User": "",
            "AttachStdin": true,
            "AttachStdout": true,
            "AttachStderr": true,
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": true,
            "Env": [
                "DISPLAY=:0",
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "LANG=C.UTF-8",
                "LC_ALL=C.UTF-8",
                "ROS_DISTRO=kinetic",
                "ROS_MASTER_URI=http://localhost:11311",
                "ROS_PACKAGE_PATH=/opt/ros/kinetic/share",
                "DEBIAN_FRONTEND=noninteractive",
                "TURTLEBOT_3D_SENSOR=no3d",
                "TURTLEBOT_TOP_PLATE_DEVICE=rplidar",
                "JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64/"
            ],
            "Cmd": [],
            "ArgsEscaped": true,
            "Image": "cpswarm/gazebo-em-ex:1.0.12",
            "Volumes": null,
            "WorkingDir": "/home",
            "Entrypoint": [
                "/home/startup.sh"
            ],
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "70d4cff7200ece8610fdcc04ffed7b2248caea6e61658c4622368a25d0864660",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/default",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {
                "host": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "81ea4770bb3b91fca3383336b35ebd9c6a00c7728180873b99fb663fcbb3ef4f",
                    "EndpointID": "1aa92639019060c8a229a06b86a79b0e6607437ab6a9c5de45f83d797b8e5b9f",
                    "Gateway": "",
                    "IPAddress": "",
                    "IPPrefixLen": 0,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "",
                    "DriverOpts": null
                }
            }
        }
    }
]
</code>```

The result that I obtain is that running from CLI, I can see the GUI of the application running in the docker container. Instead with the container deployed with Kubernetes I see the application running but I cannot see the GUI.

Is there something that I can change in the deployment file to make the deployed container working?

答:
To run GUI application on headless server, you need Xvfb to create a virtual frame buffer as a X-server, and let application connect to the X-server by env DISPLAY.

Example yaml use xvfb docker image:

```<code>...
spec:
  containers:
  - name: test
    image: test:1.0.12
    env:
    - name: DISPLAY
      value: "localhost:1.0"
  - name: xvfb
    image: comiq/xvfb:latest
    env:
    - name: DISPLAY
      value: 1
    - name: SCREEN
      value: 0
    ports:
    - name: xserver
      containerPort: 6001
</code>```

Body:
I have a docker container that runs a GUI application, I can successfully run it, using this command

sudo docker run --net=host --env="DISPLAY" --volume="$HOME/.Xauthority:/root/.Xauthority:rw" -it test

I have already tried to create this deployment file:

{
  "kind": "Deployment",
  "apiVersion": "extensions/v1beta1",
  "metadata": {
    "name": "test",
    "namespace": "default",
    "selfLink": "/apis/extensions/v1beta1/namespaces/default/deployments/gazebo",
    "uid": "249a12a9-83b8-11e9-8ec2-32ccf6441134",
    "resourceVersion": "6165060",
    "generation": 1,
    "creationTimestamp": "2019-05-31T15:24:12Z",
    "labels": {
      "k8s-app": "test"
    },
    "annotations": {
      "deployment.kubernetes.io/revision": "1"
    }
  },
  "spec": {
    "replicas": 1,
    "selector": {
      "matchLabels": {
        "k8s-app": "test"
      }
    },
    "template": {
      "metadata": {
        "name": "test",
        "creationTimestamp": null,
        "labels": {
          "k8s-app": "test"
        }
      },
      "spec": {
        "volumes": [
          {
            "name": "test",
            "hostPath": {
              "path": "$HOME/.Xauthority:/root/.Xauthority:rw",
              "type": ""
            }
          }
        ],
        "containers": [
          {
            "name": "test",
            "image": "test:1.0.12",
            "env": [
              {
                "name": "DISPLAY",
                "value": ":0"
              }
            ],
            "resources": {},
            "terminationMessagePath": "/dev/termination-log",
            "terminationMessagePolicy": "File",
            "imagePullPolicy": "IfNotPresent",
            "securityContext": {
              "privileged": false,
              "procMount": "Default"
            },
            "stdin": true
          }
        ],
        "restartPolicy": "Always",
        "terminationGracePeriodSeconds": 30,
        "dnsPolicy": "ClusterFirst",
        "nodeSelector": {
          "component": "test"
        },
        "hostNetwork": true,
        "securityContext": {},
        "schedulerName": "default-scheduler"
      }
    },
    "strategy": {
      "type": "RollingUpdate",
      "rollingUpdate": {
        "maxUnavailable": "25%",
        "maxSurge": "25%"
      }
    },
    "revisionHistoryLimit": 10,
    "progressDeadlineSeconds": 600
  },
  "status": {
    "observedGeneration": 1,
    "replicas": 1,
    "updatedReplicas": 1,
    "unavailableReplicas": 1,
    "conditions": [
      {
        "type": "Progressing",
        "status": "True",
        "lastUpdateTime": "2019-05-31T15:24:14Z",
        "lastTransitionTime": "2019-05-31T15:24:12Z",
        "reason": "NewReplicaSetAvailable",
        "message": "ReplicaSet \"test-dbfdb6467\" has successfully progressed."
      },
      {
        "type": "Available",
        "status": "False",
        "lastUpdateTime": "2019-05-31T15:40:21Z",
        "lastTransitionTime": "2019-05-31T15:40:21Z",
        "reason": "MinimumReplicasUnavailable",
        "message": "Deployment does not have minimum availability."
      }
    ]
  }
}

I have tried to inspect the resulting containers and I have obtained these results:

For the one deployed with kubernetes the result is

[
    {
        "Id": "114e1d307b8260eaa02bfcf214031cf34ae522cf55258731a8a6dca535527995",
        "Created": "2019-05-31T15:24:13.320599267Z",
        "Path": "/home/startup.sh",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 10908,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2019-05-31T15:24:13.627542552Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:2b02610511b1d09925b5b0b2471efea087819942c36c0c0bf490d6a28709f54e",
        "ResolvConfPath": "/home/docker/containers/8537a1c6038f5d6b4186d0b56a6b839207477825d0ad99d8610d36f66967495e/resolv.conf",
        "HostnamePath": "/home/docker/containers/8537a1c6038f5d6b4186d0b56a6b839207477825d0ad99d8610d36f66967495e/hostname",
        "HostsPath": "/var/lib/kubelet/pods/249ff7a4-83b8-11e9-8ec2-32ccf6441134/etc-hosts",
        "LogPath": "/home/docker/containers/114e1d307b8260eaa02bfcf214031cf34ae522cf55258731a8a6dca535527995/114e1d307b8260eaa02bfcf214031cf34ae522cf55258731a8a6dca535527995-json.log",
        "Name": "/k8s_gazebo_gazebo-dbfdb6467-fd448_default_249ff7a4-83b8-11e9-8ec2-32ccf6441134_0",
        "RestartCount": 0,
        "Driver": "aufs",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": [
                "/var/lib/kubelet/pods/249ff7a4-83b8-11e9-8ec2-32ccf6441134/volumes/kubernetes.io~secret/default-token-4ncqs:/var/run/secrets/kubernetes.io/serviceaccount:ro",
                "/var/lib/kubelet/pods/249ff7a4-83b8-11e9-8ec2-32ccf6441134/etc-hosts:/etc/hosts",
                "/var/lib/kubelet/pods/249ff7a4-83b8-11e9-8ec2-32ccf6441134/containers/gazebo/f4a9bfa2:/dev/termination-log"
            ],
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "container:8537a1c6038f5d6b4186d0b56a6b839207477825d0ad99d8610d36f66967495e",
            "PortBindings": null,
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Dns": null,
            "DnsOptions": null,
            "DnsSearch": null,
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "container:8537a1c6038f5d6b4186d0b56a6b839207477825d0ad99d8610d36f66967495e",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 1000,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": [
                "seccomp=unconfined"
            ],
            "UTSMode": "host",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 2,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "/kubepods/besteffort/pod249ff7a4-83b8-11e9-8ec2-32ccf6441134",
            "BlkioWeight": 0,
            "BlkioWeightDevice": null,
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 100000,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DiskQuota": 0,
            "KernelMemory": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": 0,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/asound",
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": null,
            "Name": "aufs"
        },
        "Mounts": [
            {
                "Type": "bind",
                "Source": "/var/lib/kubelet/pods/249ff7a4-83b8-11e9-8ec2-32ccf6441134/volumes/kubernetes.io~secret/default-token-4ncqs",
                "Destination": "/var/run/secrets/kubernetes.io/serviceaccount",
                "Mode": "ro",
                "RW": false,
                "Propagation": "rprivate"
            },
            {
                "Type": "bind",
                "Source": "/var/lib/kubelet/pods/249ff7a4-83b8-11e9-8ec2-32ccf6441134/etc-hosts",
                "Destination": "/etc/hosts",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            },
            {
                "Type": "bind",
                "Source": "/var/lib/kubelet/pods/249ff7a4-83b8-11e9-8ec2-32ccf6441134/containers/gazebo/f4a9bfa2",
                "Destination": "/dev/termination-log",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],
        "Config": {
            "Hostname": "davidePC",
            "Domainname": "",
            "User": "0",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": true,
            "StdinOnce": false,
            "Env": [
                "DISPLAY=:0",
                "KUBERNETES_PORT_443_TCP_PROTO=tcp",
                "KUBERNETES_PORT_443_TCP_PORT=443",
                "KUBERNETES_PORT_443_TCP_ADDR=10.96.0.1",
                "KUBERNETES_SERVICE_HOST=10.96.0.1",
                "KUBERNETES_SERVICE_PORT=443",
                "KUBERNETES_SERVICE_PORT_HTTPS=443",
                "KUBERNETES_PORT=tcp://10.96.0.1:443",
                "KUBERNETES_PORT_443_TCP=tcp://10.96.0.1:443",
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "LANG=C.UTF-8",
                "LC_ALL=C.UTF-8",
                "ROS_DISTRO=kinetic",
                "ROS_MASTER_URI=http://localhost:11311",
                "ROS_PACKAGE_PATH=/opt/ros/kinetic/share",
                "DEBIAN_FRONTEND=noninteractive",
                "TURTLEBOT_3D_SENSOR=no3d",
                "TURTLEBOT_TOP_PLATE_DEVICE=rplidar",
                "JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64/"
            ],
            "Cmd": [],
            "Healthcheck": {
                "Test": [
                    "NONE"
                ]
            },
            "ArgsEscaped": true,
            "Image": "sha256:2b02610511b1d09925b5b0b2471efea087819942c36c0c0bf490d6a28709f54e",
            "Volumes": null,
            "WorkingDir": "/home",
            "Entrypoint": [
                "/home/startup.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "annotation.io.kubernetes.container.hash": "86f118b",
                "annotation.io.kubernetes.container.restartCount": "0",
                "annotation.io.kubernetes.container.terminationMessagePath": "/dev/termination-log",
                "annotation.io.kubernetes.container.terminationMessagePolicy": "File",
                "annotation.io.kubernetes.pod.terminationGracePeriod": "30",
                "io.kubernetes.container.logpath": "/var/log/pods/default_gazebo-dbfdb6467-fd448_249ff7a4-83b8-11e9-8ec2-32ccf6441134/gazebo/0.log",
                "io.kubernetes.container.name": "gazebo",
                "io.kubernetes.docker.type": "container",
                "io.kubernetes.pod.name": "gazebo-dbfdb6467-fd448",
                "io.kubernetes.pod.namespace": "default",
                "io.kubernetes.pod.uid": "249ff7a4-83b8-11e9-8ec2-32ccf6441134",
                "io.kubernetes.sandbox.id": "8537a1c6038f5d6b4186d0b56a6b839207477825d0ad99d8610d36f66967495e"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {}
        }
    }
]

Instead for the one run from CLI, the result is:

[
    {
        "Id": "ed428815132ac62020e36b1d50421ec7402c3b433907575a4858617d56322366",
        "Created": "2019-05-31T15:13:51.991700539Z",
        "Path": "/home/startup.sh",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 8377,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2019-05-31T15:13:52.469581933Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:2b02610511b1d09925b5b0b2471efea087819942c36c0c0bf490d6a28709f54e",
        "ResolvConfPath": "/home/docker/containers/ed428815132ac62020e36b1d50421ec7402c3b433907575a4858617d56322366/resolv.conf",
        "HostnamePath": "/home/docker/containers/ed428815132ac62020e36b1d50421ec7402c3b433907575a4858617d56322366/hostname",
        "HostsPath": "/home/docker/containers/ed428815132ac62020e36b1d50421ec7402c3b433907575a4858617d56322366/hosts",
        "LogPath": "/home/docker/containers/ed428815132ac62020e36b1d50421ec7402c3b433907575a4858617d56322366/ed428815132ac62020e36b1d50421ec7402c3b433907575a4858617d56322366-json.log",
        "Name": "/youthful_benz",
        "RestartCount": 0,
        "Driver": "aufs",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": [
                "/home/davide/.Xauthority:/root/.Xauthority:rw"
            ],
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "host",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "shareable",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DiskQuota": 0,
            "KernelMemory": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": 0,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": null,
            "Name": "aufs"
        },
        "Mounts": [
            {
                "Type": "bind",
                "Source": "/home/davide/.Xauthority",
                "Destination": "/root/.Xauthority",
                "Mode": "rw",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],
        "Config": {
            "Hostname": "davidePC",
            "Domainname": "",
            "User": "",
            "AttachStdin": true,
            "AttachStdout": true,
            "AttachStderr": true,
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": true,
            "Env": [
                "DISPLAY=:0",
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "LANG=C.UTF-8",
                "LC_ALL=C.UTF-8",
                "ROS_DISTRO=kinetic",
                "ROS_MASTER_URI=http://localhost:11311",
                "ROS_PACKAGE_PATH=/opt/ros/kinetic/share",
                "DEBIAN_FRONTEND=noninteractive",
                "TURTLEBOT_3D_SENSOR=no3d",
                "TURTLEBOT_TOP_PLATE_DEVICE=rplidar",
                "JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64/"
            ],
            "Cmd": [],
            "ArgsEscaped": true,
            "Image": "cpswarm/gazebo-em-ex:1.0.12",
            "Volumes": null,
            "WorkingDir": "/home",
            "Entrypoint": [
                "/home/startup.sh"
            ],
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "70d4cff7200ece8610fdcc04ffed7b2248caea6e61658c4622368a25d0864660",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/default",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {
                "host": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "81ea4770bb3b91fca3383336b35ebd9c6a00c7728180873b99fb663fcbb3ef4f",
                    "EndpointID": "1aa92639019060c8a229a06b86a79b0e6607437ab6a9c5de45f83d797b8e5b9f",
                    "Gateway": "",
                    "IPAddress": "",
                    "IPPrefixLen": 0,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "",
                    "DriverOpts": null
                }
            }
        }
    }
]

The result that I obtain is that running from CLI, I can see the GUI of the application running in the docker container. Instead with the container deployed with Kubernetes I see the application running but I cannot see the GUI.

Is there something that I can change in the deployment file to make the deployed container working?

Body:
To run GUI application on headless server, you need Xvfb to create a virtual frame buffer as a X-server, and let application connect to the X-server by env DISPLAY.

Example yaml use xvfb docker image:

...
spec:
  containers:
  - name: test
    image: test:1.0.12
    env:
    - name: DISPLAY
      value: "localhost:1.0"
  - name: xvfb
    image: comiq/xvfb:latest
    env:
    - name: DISPLAY
      value: 1
    - name: SCREEN
      value: 0
    ports:
    - name: xserver
      containerPort: 6001


来源: stackexchange

问:
how to order column in Multi-columns index for best performance in Mysql
Let's say I have transactions table in a mysql database, I want to create a multi-column index on 3 columns reference, kind and status.
I have this request that I am trying to speed up :
Transaction.where(parent_ref: merchant_ref, kind: 'OFFER',status: 1)                                which performs the following SQL :

```<code>SELECT `merchant_transactions`.* FROM `merchant_transactions`
WHERE `merchant_transactions`.`parent_ref` = '1-0001'
 AND `merchant_transactions`.`kind` = 'BATCH_BET'
 AND `merchant_transactions`.`status` = 1
</code>```

The parent_ref column can take a really wide variety of values so if I have 1M records in that table I will have 500K different references. Status can only take 6 different values and kind only 3.
What will be the best order for the columns in my index for optimal performance.
Does the spread of values in my columns have an impact ? intuitively I would say that I would need to start with the column with the lowest spread of values. In that example I would thus do index(kind, status, reference).
Are there any other factors related to the values in my tables to take into account when figuring out the order of columns for my index ?

答:
In your example, each of 3 columns is tested with =, and they are ANDd together.  So build a 3-column composite with those 3 columns.  The order of the columns will not matter for this query.  Contrary to what others may say, "cardinality" of the individual columns does not matter in a composite INDEX.

See my indexing cookbook

ContentLicense: CC BY-SA 4.0

Body:
Let's say I have transactions table in a mysql database, I want to create a multi-column index on 3 columns reference, kind and status.
I have this request that I am trying to speed up :
Transaction.where(parent_ref: merchant_ref, kind: 'OFFER',status: 1)                                which performs the following SQL :

SELECT `merchant_transactions`.* FROM `merchant_transactions`
WHERE `merchant_transactions`.`parent_ref` = '1-0001'
 AND `merchant_transactions`.`kind` = 'BATCH_BET'
 AND `merchant_transactions`.`status` = 1

The parent_ref column can take a really wide variety of values so if I have 1M records in that table I will have 500K different references. Status can only take 6 different values and kind only 3.
What will be the best order for the columns in my index for optimal performance.
Does the spread of values in my columns have an impact ? intuitively I would say that I would need to start with the column with the lowest spread of values. In that example I would thus do index(kind, status, reference).
Are there any other factors related to the values in my tables to take into account when figuring out the order of columns for my index ?


问:
Keeping track of boolean data
I need to keep track of n samples. The information I am keeping track of is of boolean type, i.e. something is true or false. As soon as I am on sample n+1, i basically want to ignore the oldest sample and record information about the newest one.

So say I keep track of samples, I may have something like

OLDEST 0   0   1   1  0   NEWEST

If the next sample is 1, this will become

OLDEST 0   1   1   0  1   NEWEST

if the next one is 0, this will become...

OLDEST 1   1   0   1  0   NEWEST

So what is the best way to implement this in terms of simplicity and memory?

Some ideas I had:

Vector of bool (this would require shifting elements so seems expensive)
    Storing it as bits...and using bit shifting (memorywise --cheap? but is there a limit on the number of samples?)
    Linked lists? (might be an overkill for the task)

Thanks for the ideas and suggestions :)

答:
From your question, it's not clear what you intend to do with the samples. If all you care about is storing the N most recent samples, you could try the following. I'll do it for "chars" and let you figure out how to optimize for "bool" should you need that.

```<code>char buffer[N];
int samples = 0;

void record_sample( char value )
{
  buffer[samples%N] = value;
  samples = samples + 1;
}
</code>```

Once you've stored N samples (once you've called record_sample N times) you can read the oldest and newest samples like so:

```<code>char oldest_sample()
{
  return buffer[samples%N];
}

char newest_sample()
{
  return buffer[(samples+N-1)%N];
}
</code>```

Things get a little trickier if you intend to read the oldest sample before you've already stored N samples - but not that much trickier. For that, you want a "ring buffer" which you can find in boost and on wikipedia.

ContentLicense: CC BY-SA 3.0

Title: Keeping track of boolean data

Body:
From your question, it's not clear what you intend to do with the samples. If all you care about is storing the N most recent samples, you could try the following. I'll do it for "chars" and let you figure out how to optimize for "bool" should you need that.

char buffer[N];
int samples = 0;

void record_sample( char value )
{
  buffer[samples%N] = value;
  samples = samples + 1;
}

Once you've stored N samples (once you've called record_sample N times) you can read the oldest and newest samples like so:

char oldest_sample()
{
  return buffer[samples%N];
}

char newest_sample()
{
  return buffer[(samples+N-1)%N];
}

Things get a little trickier if you intend to read the oldest sample before you've already stored N samples - but not that much trickier. For that, you want a "ring buffer" which you can find in boost and on wikipedia.


问:
How to use Custom Translator service for new language pair
From Customization page, there is a description as follows:

Custom Translator allows users to customize Microsoft Translator’s advanced neural machine translation for Translator’s supported neural translation languages".

zh-Hant (Chinese Traditional) is definitely supported by Microsoft Translator Neural Translation. But it's not available in the language pair candidate list when creating project in Custom Translator.

Does Custom Translator support building a custimized model for zh-Hant?

(If not, I also wonder why zh-Hant, one of supported neural translation languages,
is excluded in Custom Translator.)

Moreover, from "Custom Translator User Guide", it is said:

Custom allows you to customize a language pair for a specific domain of terminology, or to build
  automatic translation for a language that is not yet supported by Microsoft Translator.

I'd like to ask how to use Custom Translator to build a model for a language unsupported yet.
For example, how to create projects, how to choose lanugage pair in this case?

答: Chinese Traditional (zh-Hant) is now available in Custom Translator. You can select it as a language pair when creating a new project in the Custom Translator portal at https://portal.customtranslator.azure.ai/</p>


问:
NSAttributedString: How do you add BOLD to a customized (e.g., Palatino) font?
Below are some customized extension functions for the NSAttributedString class for the Palatino font:

```<code>extension NSAttributedString {
    class func blueAttributeStringOf(string:NSString) -> NSAttributedString {
        let dict = [NSFontAttributeName: UIFont(name: "Palatino", size: 14.0)!,NSForegroundColorAttributeName:blissBlue]
        let attrString = NSAttributedString(string:string as String, attributes: dict)
        return attrString
    }

    class func standardAttributeStringOf(string:String) -> NSAttributedString {
        let dict = [NSFontAttributeName: UIFont(name: "Palatino", size: 14.0)!]
        let attrString = NSAttributedString(string:string as String, attributes: dict)
        return attrString
    }
}
</code>```

I can't find the bold attribute for the NSAttributedString class.  How do I add the bold attribute to any particular font (e.g., the Palatino font)?

答:
You can bold a string without changing its other attributes by setting the StrokeWidth attribute with a negative value.

```<code>let attrString = NSAttributedString(string: string as String, attributes: [.strokeWidth: NSNumber(value: -3.0)])
</code>```

Body:
Below are some customized extension functions for the NSAttributedString class for the Palatino font:

extension NSAttributedString {
    class func blueAttributeStringOf(string:NSString) -> NSAttributedString {
        let dict = [NSFontAttributeName: UIFont(name: "Palatino", size: 14.0)!,NSForegroundColorAttributeName:blissBlue]
        let attrString = NSAttributedString(string:string as String, attributes: dict)
        return attrString
    }

    class func standardAttributeStringOf(string:String) -> NSAttributedString {
        let dict = [NSFontAttributeName: UIFont(name: "Palatino", size: 14.0)!]
        let attrString = NSAttributedString(string:string as String, attributes: dict)
        return attrString
    }
}

I can't find the bold attribute for the NSAttributedString class.  How do I add the bold attribute to any particular font (e.g., the Palatino font)?

Body:
You can bold a string without changing its other attributes by setting the StrokeWidth attribute with a negative value.

let attrString = NSAttributedString(string: string as String, attributes: [.strokeWidth: NSNumber(value: -3.0)])


问:
Flutter Spacer vs Expanded
What is the difference between Expanded and Spacer in Flutter? Why Flutter team added Spacer when we already have Expanded?

答:
Expanded makes its child widget occupy space.

Spacer occupies space by itself.

If you look at the implementation of Spacer, you'll see that it's a wrapper around Expanded with a dummy child.

Is Spacer really necessary?  Probably not.  In an alternate universe, Expanded could have had an optional child argument instead.

Title: Flutter Spacer vs Expanded


问:
Adding google maps markers by an address instead of coordinates?
In my Flex project, can I add markers by its address instead of this:

```<code>var myGeographicCoordinates:LatLng = new LatLng(myLatitude, myLongitude);
</code>```

for example add marker by "Paris, France"

答:
I don't think you can do so directly. Instead you need to geocode the address and then use a LatLng to store the result.

Check out google's geocoding api here:

http://code.google.com/apis/maps/documentation/geocoding/

Body:
In my Flex project, can I add markers by its address instead of this:

var myGeographicCoordinates:LatLng = new LatLng(myLatitude, myLongitude);

for example add marker by "Paris, France"


问:
Date field from dataframe removes leading 0 after export
I have a Dataframe with the following date field:

463    14-05-2019
535    03-05-2019
570    11-05-2019
577    09-05-2019
628    08-08-2019
630    25-05-2019
Name: Date, dtype: object
```
<p>I have to format it as DDMMAAAA. This is what I'm doing inside a loop (<code>for idx, row in df.iterrows():</code>):</p>
<ul>
<li>I'm removing the <code>\-</code> char using regex:
<blockquote>
<p><code>df.at[idx, 'Date'] = re.sub('\-', '', df.at[idx, 'Date'])</code></p>
</blockquote>
</li>
<li>then using apply to enforce and an 8 digit string with leading zeros
<blockquote>
<p><code>df['Date'] = df['Date'].apply(lambda x: '{0:0>8}'.format(x))</code></p>
</blockquote>
</li>
</ul>
<p>But even though the df['Date'] field has the 8 digits with the leading 0 on the df, whent exporting it to csv the leading zeros are being removed on the exported file like below.</p>
```df.to_csv(path_or_buf=report, header=True, index=False, sep=';')
```
<p>field as in csv:</p>
```Dt_DDMMAAAA
30102019
12052019
7052019
26042019
3052019
22042019
25042019
2062019
```

I know I must be missing the point somewhere along the way here, but I just can't figure out what the issue (or if it's even an issue, rather then a misused method).

答:
Firstly, your method is producing a file which contains leading zeros just as you expect. I reconstructed this minimal working example from your description and it works just fine:

```<code>import pandas
import re

df = pandas.DataFrame([["14-05-2019"],
                       ["03-05-2019"],
                       ["11-05-2019"],
                       ["09-05-2019"],
                       ["08-08-2019"],
                       ["25-05-2019"]], columns=['Date'])

for idx in df.index:
    df.at[idx, 'Date'] = re.sub('\-', '', df.at[idx, 'Date'])
df['Date'] = df['Date'].apply(lambda x: '{0:0>8}'.format(x))

df.to_csv(path_or_buf="report.csv", header=True, index=False, sep=';')
</code>```

At this point report.csv contains this (with leading zeros just as you wanted).

```<code>Date
14052019
03052019
11052019
09052019
08082019
25052019
</code>```

Now as to why you thought it wasn't working. If you are mainly in Pandas, you can stop it from guessing the type of the output by specifying a dtype in read_csv:

```<code>df_readback = pandas.read_csv('report.csv', dtype={'Date': str})

       Date
0  14052019
1  03052019
2  11052019
3  09052019
4  08082019
5  25052019
</code>```

It might also be that you are reading this in Excel (I'm guessing this from the fact that you are using ; separators). Unfortunately there is no way to ensure that Excel reads this field correctly on double-click, but if this is your final target, you can see how to mangle your file for Excel to read correctly in this answer.

Body:
I have a Dataframe with the following date field:

463    14-05-2019
535    03-05-2019
570    11-05-2019
577    09-05-2019
628    08-08-2019
630    25-05-2019
Name: Date, dtype: object

I have to format it as DDMMAAAA. This is what I'm doing inside a loop (for idx, row in df.iterrows():):

I'm removing the \- char using regex:

df.at[idx, 'Date'] = re.sub('\-', '', df.at[idx, 'Date'])

then using apply to enforce and an 8 digit string with leading zeros

df['Date'] = df['Date'].apply(lambda x: '{0:0>8}'.format(x))

But even though the df['Date'] field has the 8 digits with the leading 0 on the df, whent exporting it to csv the leading zeros are being removed on the exported file like below.

df.to_csv(path_or_buf=report, header=True, index=False, sep=';')

field as in csv:

Dt_DDMMAAAA
30102019
12052019
7052019
26042019
3052019
22042019
25042019
2062019

I know I must be missing the point somewhere along the way here, but I just can't figure out what the issue (or if it's even an issue, rather then a misused method).

Body:
Firstly, your method is producing a file which contains leading zeros just as you expect. I reconstructed this minimal working example from your description and it works just fine:

import pandas
import re

df = pandas.DataFrame([["14-05-2019"],
                       ["03-05-2019"],
                       ["11-05-2019"],
                       ["09-05-2019"],
                       ["08-08-2019"],
                       ["25-05-2019"]], columns=['Date'])

for idx in df.index:
    df.at[idx, 'Date'] = re.sub('\-', '', df.at[idx, 'Date'])
df['Date'] = df['Date'].apply(lambda x: '{0:0>8}'.format(x))

df.to_csv(path_or_buf="report.csv", header=True, index=False, sep=';')

At this point report.csv contains this (with leading zeros just as you wanted).

Date
14052019
03052019
11052019
09052019
08082019
25052019

Now as to why you thought it wasn't working. If you are mainly in Pandas, you can stop it from guessing the type of the output by specifying a dtype in read_csv:

df_readback = pandas.read_csv('report.csv', dtype={'Date': str})

       Date
0  14052019
1  03052019
2  11052019
3  09052019
4  08082019
5  25052019

It might also be that you are reading this in Excel (I'm guessing this from the fact that you are using ; separators). Unfortunately there is no way to ensure that Excel reads this field correctly on double-click, but if this is your final target, you can see how to mangle your file for Excel to read correctly in this answer.


问:
Sublime Text 3, how to add to right click?
How do I add Sublime Text just like how Edit with Notepad++ is there it's nothing big but it saves time.

答:
Thanks r-stein for the above answer. But [HKEY_CLASSES_ROOT\Directory\shell\Sublime\command] have some problems. the last argument should \"%V\"" instead \"%1\"".

The full subl.reg is

```<code>Windows Registry Editor Version 5.00

; show in context menu when right click all kinds files
[HKEY_CLASSES_ROOT\*\shell\Sublime]
@="Open with Sublime Text 3"
"Icon"="C:\\Program Files\\Sublime Text 3\\sublime_text.exe,0"

[HKEY_CLASSES_ROOT\*\shell\Sublime\command]
@="\"C:\\Program Files\\Sublime Text 3\\sublime_text.exe\" \"%1\""

; show in context menu when right click empty area of explorer
[HKEY_CLASSES_ROOT\Directory\Background\shell\Sublime]
@="Open with Sublime Text 3"
"Icon"="C:\\Program Files\\Sublime Text 3\\sublime_text.exe,0"

[HKEY_CLASSES_ROOT\Directory\Background\shell\Sublime\command]
@="\"C:\\Program Files\\Sublime Text 3\\sublime_text.exe\" \"%V\""

; show in context menu when right click directory
[HKEY_CLASSES_ROOT\Directory\shell\Sublime]
@="Open with Sublime Text 3"
"Icon"="C:\\Program Files\\Sublime Text 3\\sublime_text.exe,0"

[HKEY_CLASSES_ROOT\Directory\shell\Sublime\command]
@="\"C:\\Program Files\\Sublime Text 3\\sublime_text.exe\" \"%V\""
</code>```

Body:
Thanks r-stein for the above answer. But [HKEY_CLASSES_ROOT\Directory\shell\Sublime\command] have some problems. the last argument should \"%V\"" instead \"%1\"".

The full subl.reg is

Windows Registry Editor Version 5.00

; show in context menu when right click all kinds files
[HKEY_CLASSES_ROOT\*\shell\Sublime]
@="Open with Sublime Text 3"
"Icon"="C:\\Program Files\\Sublime Text 3\\sublime_text.exe,0"

[HKEY_CLASSES_ROOT\*\shell\Sublime\command]
@="\"C:\\Program Files\\Sublime Text 3\\sublime_text.exe\" \"%1\""

; show in context menu when right click empty area of explorer
[HKEY_CLASSES_ROOT\Directory\Background\shell\Sublime]
@="Open with Sublime Text 3"
"Icon"="C:\\Program Files\\Sublime Text 3\\sublime_text.exe,0"

[HKEY_CLASSES_ROOT\Directory\Background\shell\Sublime\command]
@="\"C:\\Program Files\\Sublime Text 3\\sublime_text.exe\" \"%V\""

; show in context menu when right click directory
[HKEY_CLASSES_ROOT\Directory\shell\Sublime]
@="Open with Sublime Text 3"
"Icon"="C:\\Program Files\\Sublime Text 3\\sublime_text.exe,0"

[HKEY_CLASSES_ROOT\Directory\shell\Sublime\command]
@="\"C:\\Program Files\\Sublime Text 3\\sublime_text.exe\" \"%V\""


问:
issues with array.concat()
I'm trying to use a recursive call to concat a return array

Directions to this problem are:
A stream of data is received and needs to be reversed.

Each segment is 8 bits long, meaning the order of these segments needs to be reversed, for example:

11111111  00000000  00001111  10101010
 (byte1)   (byte2)   (byte3)   (byte4)
should become:

10101010  00001111  00000000  11111111
 (byte4)   (byte3)   (byte2)   (byte1)
The total number of bits will always be a multiple of 8.

trying different combinations of things really...

function dataReverse(data) {
  //split incoming array into array values consisting of 8 numbers each.
  //var octGroups = data.length / 8;
  var result = [];
  //recursive call
  function shuffler(array){
    let input = array;
    //base case
    if(input.length === 0){
      return result;
    } else {
      //concat result with 8 values at a time
      let cache = input.splice(-8,8);
      result.concat(cache);
      return shuffler(input);
    }
    return result;
  }

  var reversed = shuffler(data);
//base case is if data.length === 0 return result else
//reverse iterate through array, concating to new return array
//return result
  return reversed;
}

console.log(dataReverse([1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]));```

it is expected to reverse through the input array, concating a result array with 8 values at a time starting at the end, but not reversing the order of the numbers.

My attempt above returns a zero length array. What have I done wrong?

答:
concat returns an array - assign the result:

function dataReverse(data) {
  //split incoming array into array values consisting of 8 numbers each.
  //var octGroups = data.length / 8;
  var result = [];
  //recursive call
  function shuffler(array) {
    let input = array;
    //base case
    if (input.length === 0) {
      return result;
    } else {
      //concat result with 8 values at a time
      let cache = input.splice(-8, 8);
      result = result.concat(cache);
      return shuffler(input);
    }
    return result;
  }

  var reversed = shuffler(data);
  //base case is if data.length === 0 return result else
  //reverse iterate through array, concating to new return array
  //return result
  return reversed;
}

let reversed = dataReverse([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]);

//Code for pretty-printing in groups of 8
reversed = reversed.reduce((acc, curr, i) => {
  const c = Math.floor(i / 8);
  acc[c] = [].concat((acc[c] || []), curr);
  return acc;
}, []);

console.log(reversed.map(e => e.join("")));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {
  max-height: 100% !important;
  top: auto;
}</code>```

(Array chunk from this answer).

Title: issues with array.concat()

Body:
I'm trying to use a recursive call to concat a return array

Directions to this problem are:
A stream of data is received and needs to be reversed.

Each segment is 8 bits long, meaning the order of these segments needs to be reversed, for example:

11111111  00000000  00001111  10101010
 (byte1)   (byte2)   (byte3)   (byte4)
should become:

10101010  00001111  00000000  11111111
 (byte4)   (byte3)   (byte2)   (byte1)
The total number of bits will always be a multiple of 8.

trying different combinations of things really...

function dataReverse(data) {
  //split incoming array into array values consisting of 8 numbers each.
  //var octGroups = data.length / 8;
  var result = [];
  //recursive call
  function shuffler(array){
    let input = array;
    //base case
    if(input.length === 0){
      return result;
    } else {
      //concat result with 8 values at a time
      let cache = input.splice(-8,8);
      result.concat(cache);
      return shuffler(input);
    }
    return result;
  }

  var reversed = shuffler(data);
//base case is if data.length === 0 return result else
//reverse iterate through array, concating to new return array
//return result
  return reversed;
}

console.log(dataReverse([1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,1,0,1,0,1,0]));

it is expected to reverse through the input array, concating a result array with 8 values at a time starting at the end, but not reversing the order of the numbers.

My attempt above returns a zero length array. What have I done wrong?

Body:
concat returns an array - assign the result:

function dataReverse(data) {
  //split incoming array into array values consisting of 8 numbers each.
  //var octGroups = data.length / 8;
  var result = [];
  //recursive call
  function shuffler(array) {
    let input = array;
    //base case
    if (input.length === 0) {
      return result;
    } else {
      //concat result with 8 values at a time
      let cache = input.splice(-8, 8);
      result = result.concat(cache);
      return shuffler(input);
    }
    return result;
  }

  var reversed = shuffler(data);
  //base case is if data.length === 0 return result else
  //reverse iterate through array, concating to new return array
  //return result
  return reversed;
}

let reversed = dataReverse([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]);

//Code for pretty-printing in groups of 8
reversed = reversed.reduce((acc, curr, i) => {
  const c = Math.floor(i / 8);
  acc[c] = [].concat((acc[c] || []), curr);
  return acc;
}, []);

console.log(reversed.map(e => e.join("")));

.as-console-wrapper {
  max-height: 100% !important;
  top: auto;
}

(Array chunk from this answer).


答:
concat returns a new array you need to assign it back to result

```<code>result = result.concat(cache);
</code>```

And if you want each byte as string of 8 characters you can use join

```<code>result = result.concat(cache.join(''));
</code>```

function dataReverse(data) {
  //split incoming array into array values consisting of 8 numbers each.
  //var octGroups = data.length / 8;
  var result = [];
  //recursive call
  function shuffler(array) {
    let input = array;
    //base case
    if (input.length === 0) {
      return result;
    } else {
      //concat result with 8 values at a time
      let cache = input.splice(-8, 8);
      result = result.concat(cache);
      return shuffler(input);
    }
    return result;
  }

  var reversed = shuffler(data);
  //base case is if data.length === 0 return result else
  //reverse iterate through array, concating to new return array
  //return result
  return reversed;
}

console.log(dataReverse([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]));```
</div>
</div>
</p>

<p>You can just loop over array create group of 8 byte each and then reverse and then reduce back to single array</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let dataReverse = (data) => {
  let count = 0
  let temp = []
  let group = data.reduce((op, inp) => {
    temp.push(inp)
    if (count === 8) {
      op.push(temp)
      temp = []
    }
    return op
  }, [])
  if (temp.length) group.push(temp)
  return group.reverse().reduce((op,inp)=>op.concat(inp))
}

console.log(dataReverse([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]));</code>```

Title: issues with array.concat()

Body:
concat returns a new array you need to assign it back to result

result = result.concat(cache);

And if you want each byte as string of 8 characters you can use join

result = result.concat(cache.join(''));

function dataReverse(data) {
  //split incoming array into array values consisting of 8 numbers each.
  //var octGroups = data.length / 8;
  var result = [];
  //recursive call
  function shuffler(array) {
    let input = array;
    //base case
    if (input.length === 0) {
      return result;
    } else {
      //concat result with 8 values at a time
      let cache = input.splice(-8, 8);
      result = result.concat(cache);
      return shuffler(input);
    }
    return result;
  }

  var reversed = shuffler(data);
  //base case is if data.length === 0 return result else
  //reverse iterate through array, concating to new return array
  //return result
  return reversed;
}

console.log(dataReverse([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]));

You can just loop over array create group of 8 byte each and then reverse and then reduce back to single array

let dataReverse = (data) => {
  let count = 0
  let temp = []
  let group = data.reduce((op, inp) => {
    temp.push(inp)
    if (count === 8) {
      op.push(temp)
      temp = []
    }
    return op
  }, [])
  if (temp.length) group.push(temp)
  return group.reverse().reduce((op,inp)=>op.concat(inp))
}

console.log(dataReverse([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]));


答:
Use join instead of concat

function dataReverse(data) {
  //split incoming array into array values consisting of 8 numbers each.
  //var octGroups = data.length / 8;
  var result = [];
  //recursive call
  function shuffler(array) {
    let input = array;
    //base case
    if (input.length === 0) {
      return result;
    } else {
      //concat result with 8 values at a time
      let cache = input.splice(-8, 8);
      result.push(cache.join(''));
      return shuffler(input);
    }
    return result;
  }

  var reversed = shuffler(data);
  //base case is if data.length === 0 return result else
  //reverse iterate through array, concating to new return array
  //return result
  return reversed;
}

console.log(dataReverse([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0]));```

Title: issues with array.concat()


问:
No data response when sending ajax request to php
i want to send a json data to my php but there is no response when i access it to my php.

this is my ajax request

```<code>    var project = {project:"A"};

 var dataPost = JSON.stringify(project);

     $.ajax({
     url: 'fetchDate.php',
     data: {myData: dataPost},
     type: 'POST',
     datatype:'json',
     contentType: "application/json",
     success: function(data) {
         alert(JSON.stringify(data));
     }
 });
</code>```

});

and this is my php where i process the request and return back the data to test

```<code><?php header("Content-Type: application/json; charset=UTF-8");
  $objProject = json_decode($_GET["myData"]);
  echo json_encode($objProject->project); ?>
</code>```

i'm new to ajax so please i need your help

答:
Please try change

$objProject = json_decode($_GET["myData"]);

to

$objProject = json_decode($_POST["myData"]);

because   ajax type : 'POST'

```<code>$.ajax({
 url: 'fetchDate.php',
 data: {myData: dataPost},
 type: 'POST',
 datatype:'json',
 contentType: "application/json",
 success: function(data) {
     alert(JSON.stringify(data));
 }
</code>```

Body:
i want to send a json data to my php but there is no response when i access it to my php.

this is my ajax request

    var project = {project:"A"};

 var dataPost = JSON.stringify(project);

     $.ajax({
     url: 'fetchDate.php',
     data: {myData: dataPost},
     type: 'POST',
     datatype:'json',
     contentType: "application/json",
     success: function(data) {
         alert(JSON.stringify(data));
     }
 });

});

and this is my php where i process the request and return back the data to test

<?php header("Content-Type: application/json; charset=UTF-8");
  $objProject = json_decode($_GET["myData"]);
  echo json_encode($objProject->project); ?>

i'm new to ajax so please i need your help

Body:
Please try change

$objProject = json_decode($_GET["myData"]);

to

$objProject = json_decode($_POST["myData"]);

because   ajax type : 'POST'

$.ajax({
 url: 'fetchDate.php',
 data: {myData: dataPost},
 type: 'POST',
 datatype:'json',
 contentType: "application/json",
 success: function(data) {
     alert(JSON.stringify(data));
 }


问:
Interactive column chart doesn't work in shiny
I created a Shiny APP. The interactive column chart is malfunctioning - Instead of showing two columns, it shows one column. Also, the chart won't update automatically if I select different variables.

I'd greatly appreciate if someone can help resolve it. Thank you so much!!

Here's the code:

```<code>library(shiny)
library(ggplot2)
library(plotly)

a=c("Female","Female","Male","Female","Male")
b=c("Yes","No","No","Yes","No")
c=c("Yes","Yes","Yes","No","No")
Mydata=data.frame(gender=a,SeniorCitizen=b,Churn=c)

ggplot(Mydata)+geom_bar(aes(gender,fill=Churn))+
  ggtitle("Categorical Variable vs Target Variable")+theme(plot.title = element_text(hjust = 0.5))

ui = shinyUI(fluidPage(
  headerPanel(title="Features Review"),
  sidebarPanel(
    selectInput("Variable","Select A Categorical Variable",
                list("gender"="gender","SeniorCitizen"="SeniorCitizen"
                ))),

  mainPanel(
    titlePanel(title="Categorical Variable Visualization"),plotOutput("CPlots"))

  ))

server = shinyServer(function(input, output) {

  output$CPlots = reactivePlot(function(){
    ggplot(Mydata)+geom_bar(aes(input$Variable,fill=Churn))+
      ggtitle("Categorical Variable vs Target Variable")+theme(plot.title = element_text(hjust = 0.5))
  })
})

shinyApp(ui,server)
</code>```

答:
According to your comment and @DSGym's advice, I think the following code is what you need:</p>

```<code>library(shiny)
library(ggplot2)
library(plotly)

a = c("Female", "Female", "Male", "Female", "Male")
b = c("No", "No", "No", "Yes", "No")
c = c("Yes", "Yes", "Yes", "No", "No")
Mydata = data.frame(gender = a,
                    SeniorCitizen = b,
                    Churn = c)

ui = shinyUI(fluidPage(
    headerPanel(title = "Features Review"),
    sidebarPanel(selectInput(
        "Variable",
        "Select A Categorical Variable",
        list("gender" = "gender", "SeniorCitizen" = "SeniorCitizen")
    )),

    mainPanel(
        titlePanel(title = "Categorical Variable Visualization"),
        plotOutput("CPlots")
    )

))

server = shinyServer(function(input, output) {
    output$CPlots = renderPlot(
        ggplot(Mydata, aes(
            x = get(input$Variable), fill = Churn
        )) +
            geom_bar() +
            ggtitle("Categorical Variable vs Target Variable") +
            theme(plot.title = element_text(hjust = 0.5))
    )
})

shinyApp(ui, server)
</code>```

Body:
I created a Shiny APP. The interactive column chart is malfunctioning - Instead of showing two columns, it shows one column. Also, the chart won't update automatically if I select different variables.

I'd greatly appreciate if someone can help resolve it. Thank you so much!!

Here's the code:

library(shiny)
library(ggplot2)
library(plotly)

a=c("Female","Female","Male","Female","Male")
b=c("Yes","No","No","Yes","No")
c=c("Yes","Yes","Yes","No","No")
Mydata=data.frame(gender=a,SeniorCitizen=b,Churn=c)

ggplot(Mydata)+geom_bar(aes(gender,fill=Churn))+
  ggtitle("Categorical Variable vs Target Variable")+theme(plot.title = element_text(hjust = 0.5))

ui = shinyUI(fluidPage(
  headerPanel(title="Features Review"),
  sidebarPanel(
    selectInput("Variable","Select A Categorical Variable",
                list("gender"="gender","SeniorCitizen"="SeniorCitizen"
                ))),

  mainPanel(
    titlePanel(title="Categorical Variable Visualization"),plotOutput("CPlots"))

  ))

server = shinyServer(function(input, output) {

  output$CPlots = reactivePlot(function(){
    ggplot(Mydata)+geom_bar(aes(input$Variable,fill=Churn))+
      ggtitle("Categorical Variable vs Target Variable")+theme(plot.title = element_text(hjust = 0.5))
  })
})

shinyApp(ui,server)

Body:
According to your comment and @DSGym's advice, I think the following code is what you need:

library(shiny)
library(ggplot2)
library(plotly)

a = c("Female", "Female", "Male", "Female", "Male")
b = c("No", "No", "No", "Yes", "No")
c = c("Yes", "Yes", "Yes", "No", "No")
Mydata = data.frame(gender = a,
                    SeniorCitizen = b,
                    Churn = c)

ui = shinyUI(fluidPage(
    headerPanel(title = "Features Review"),
    sidebarPanel(selectInput(
        "Variable",
        "Select A Categorical Variable",
        list("gender" = "gender", "SeniorCitizen" = "SeniorCitizen")
    )),

    mainPanel(
        titlePanel(title = "Categorical Variable Visualization"),
        plotOutput("CPlots")
    )

))

server = shinyServer(function(input, output) {
    output$CPlots = renderPlot(
        ggplot(Mydata, aes(
            x = get(input$Variable), fill = Churn
        )) +
            geom_bar() +
            ggtitle("Categorical Variable vs Target Variable") +
            theme(plot.title = element_text(hjust = 0.5))
    )
})

shinyApp(ui, server)


问:
How to install 'make' and GCC on a Mac
I want to install Eclim on my MacBook Air (2011 version). But there are some problems I faced during the installation. It told me that I did not install make and GCC.

I tried to find the solution for it, but all solutions are talking about using Xcode. In fact, I installed Xcode.

But I still cannot install Eclim because there are no make and GCC installed.

How can I install them so that I can install Eclim?

答:
With Homebrew installed on my Mac, the installation was as simple as running the command

brew install make

It might require root permissions.

Title: How to install 'make' and GCC on a Mac


问:
Creating new columns in DataFrames under some condition
I'm trying to create a new column in my dataframe, but its values must follow some rule. For example, if the value of the variable Venda is less than 200, then the variable Comissão must be 0.

```<code>if (df['Venda']<200):
    df['Comissão']=0
    df['Direito a Bonus']='Não'
elif (df['Venda']>=200) & (df['Venda']<250):
    df['Comissão']=0.5*df['Venda']
    df['Direito a Bonus']='Sim'
else:
    df['Comissão']=0.7*df['Venda']
    df['Direito a Bonus']='Sim'
</code>```

Running this code, I get the error:

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

答:
Use Numpy.select() and Numpy.where():</p>

```<code>c1 = df['Venda']<200
c2 = df['Venda']<250

df['Comissão'] = np.select([c1, c2], [0, 0.5], default=0.7)*df['Venda']
df['Direito a Bonus'] = np.where(c1, 'Não', 'Sim')
</code>```

Body:
I'm trying to create a new column in my dataframe, but its values must follow some rule. For example, if the value of the variable Venda is less than 200, then the variable Comissão must be 0.

if (df['Venda']<200):
    df['Comissão']=0
    df['Direito a Bonus']='Não'
elif (df['Venda']>=200) & (df['Venda']<250):
    df['Comissão']=0.5*df['Venda']
    df['Direito a Bonus']='Sim'
else:
    df['Comissão']=0.7*df['Venda']
    df['Direito a Bonus']='Sim'

Running this code, I get the error:

The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Body:
Use Numpy.select() and Numpy.where():

c1 = df['Venda']<200
c2 = df['Venda']<250

df['Comissão'] = np.select([c1, c2], [0, 0.5], default=0.7)*df['Venda']
df['Direito a Bonus'] = np.where(c1, 'Não', 'Sim')


问:
Selenium Expected Conditions - waiting for an xpath to become available - I dont know how to type it in my code
I'm Scott, still somewhat new to python, still trying to figure out how it all works...LOL

I have a script that logs into a website for work, does some clicking on a few objects, and then pulls a report based on those settings that were clicked

the problem I am having is that sometimes the server is busy, so things take different amounts of time to appear... some items are not clickable until drop down menus have been activated...etc
so I need the script to wait for the xpath of each object to become available

I dont understand the explicit wait usage

currently code is UGLY with my bad usage of time.sleep and other various things..

Code Included below...but heres an example of what I need it to wait for
I need to Insert Explicit waits that will wait for the element to become available

Thanks ahead of time for all your help
I've solved quite a few of my other issues in the script with the help of this forum

```<code>#Close City Arrow
print('Close City')
loc_arrow2 = (browser.find_element_by_xpath('//*[@id="rddlLocation_Arrow"]'))
loc_arrow2.click()

time.sleep(2)

#Category Button
print ('Category Button')
CategoryRadioBtn = browser.find_element_by_id('rbnSearchCategory')
CategoryRadioBtn.click()
WebDriverWait(browser,20)

time.sleep(2)

#L1 Set to 3d_blah_blah_blah
print('L1 Set to 3d_blah_blah_blah')

loc_L1 = (browser.find_element_by_xpath('//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]'))
loc_L1.click()

time.sleep(2)

loc_L2 = (browser.find_element_by_xpath('//*[@id="ctlCategorySelect1_ddlCategory1_Input"]'))
loc_L2.clear()
loc_L2.send_keys('3')
loc_L2.send_keys(u'\ue007')

</code>```

答:
Lets take the below line as sample to explain the EC (Expected Condition).

```<code>loc_L1 = (browser.find_element_by_xpath('//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]'))
</code>```

You have to add below imports to work with Explicit wait using EC.

```<code>from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
</code>```

And here how you have to write the explicit wait

```<code>WebDriverWait(driver,waitTimeInSec).until(EC.presence_of_element_located((By.strategy,"xpath_goes_here")))
# Below is the example
loc_L1 = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,'//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]')))
 # if you want to wait for the element to be clickable then use below.
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]')))
</code>```

In case you get the ElementNotInteractable exception, then use js click as shown below.

```<code>driver.execute_script("arguments[0].click()",loc_L1)
</code>```

Body:
I'm Scott, still somewhat new to python, still trying to figure out how it all works...LOL

I have a script that logs into a website for work, does some clicking on a few objects, and then pulls a report based on those settings that were clicked

the problem I am having is that sometimes the server is busy, so things take different amounts of time to appear... some items are not clickable until drop down menus have been activated...etc
so I need the script to wait for the xpath of each object to become available

I dont understand the explicit wait usage

currently code is UGLY with my bad usage of time.sleep and other various things..

Code Included below...but heres an example of what I need it to wait for
I need to Insert Explicit waits that will wait for the element to become available

Thanks ahead of time for all your help
I've solved quite a few of my other issues in the script with the help of this forum

#Close City Arrow
print('Close City')
loc_arrow2 = (browser.find_element_by_xpath('//*[@id="rddlLocation_Arrow"]'))
loc_arrow2.click()

time.sleep(2)

#Category Button
print ('Category Button')
CategoryRadioBtn = browser.find_element_by_id('rbnSearchCategory')
CategoryRadioBtn.click()
WebDriverWait(browser,20)

time.sleep(2)

#L1 Set to 3d_blah_blah_blah
print('L1 Set to 3d_blah_blah_blah')

loc_L1 = (browser.find_element_by_xpath('//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]'))
loc_L1.click()

time.sleep(2)

loc_L2 = (browser.find_element_by_xpath('//*[@id="ctlCategorySelect1_ddlCategory1_Input"]'))
loc_L2.clear()
loc_L2.send_keys('3')
loc_L2.send_keys(u'\ue007')

Body:
Lets take the below line as sample to explain the EC (Expected Condition).

loc_L1 = (browser.find_element_by_xpath('//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]'))

You have to add below imports to work with Explicit wait using EC.

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By

And here how you have to write the explicit wait

WebDriverWait(driver,waitTimeInSec).until(EC.presence_of_element_located((By.strategy,"xpath_goes_here")))
# Below is the example
loc_L1 = WebDriverWait(driver,10).until(EC.presence_of_element_located((By.XPATH,'//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]')))
 # if you want to wait for the element to be clickable then use below.
WebDriverWait(driver,10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="ctlCategorySelect1_ddlCategory1_Arrow"]')))

In case you get the ElementNotInteractable exception, then use js click as shown below.

driver.execute_script("arguments[0].click()",loc_L1)


问:
Nested Parameterized types in interface
I have following interfaces:

CacheKey interface:

```<code>public interface CacheKey<K extends Serializable> extends Serializable {
    K get();
}
</code>```

CacheValue interface:

```<code>public interface CacheValue<V extends Serializable> extends Serializable {
    V get();
}
</code>```

Cache interface:

```<code>public interface Cache<CacheKey<K extends Serializable>, CacheValue<V extends Serializable>> {
}
</code>```

Cache interface doesn't compile. Error I get is:
[13,35] > expected

i.e. after CacheKey compiler doesn't like another opening angle bracket:

```<code>public interface Cache<CacheKey<
                               ^
</code>```

Is this not possible in Java?

答:
You're missing a crucial step here : the implementation.

It's usually in the implementation that you want to define what the type of ? extends Serializable will be. You don't need to implement this in the Cache interface.

The interface only needs to know what its generics types will be, not the generics of their child : this is for the implementation.

Take a look at the example here below to understand what I exactly mean by that.

Addition : When your define something like Cache<CacheKey, CacheValue> you're not referring to the classes, but you're creation a generic alias. CacheKey could easily be replaced by Blabla and continue to have the same behaviour. The solution is to use extends to make sure we're talking about the type.

This was also the reason why Cache<CacheKey<...>> did not compile, because CacheKey is not referring to the class but is used as an alias

```<code>public interface CacheKey<K extends Serializable> extends Serializable {
    K get();
}

public interface CacheValue<V extends Serializable> extends Serializable {
    V get();
}

public interface Cache<K extends CacheKey<? extends Serializable>, V extends CacheValue<? extends Serializable>> {
    void put(K key, V value);
}

public class CacheImpl implements Cache<CacheKey<String>, CacheValue<String>> {
    @Override
    public void put(CacheKey<String> key, CacheValue<String> value) {
        // do whatever
    }
}
</code>```

Title: Nested Parameterized types in interface

Body:
I have following interfaces:

CacheKey interface:

public interface CacheKey<K extends Serializable> extends Serializable {
    K get();
}

CacheValue interface:

public interface CacheValue<V extends Serializable> extends Serializable {
    V get();
}

Cache interface:

public interface Cache<CacheKey<K extends Serializable>, CacheValue<V extends Serializable>> {
}

Cache interface doesn't compile. Error I get is:
[13,35] > expected

i.e. after CacheKey compiler doesn't like another opening angle bracket:

public interface Cache<CacheKey<
                               ^

Is this not possible in Java?

Body:
You're missing a crucial step here : the implementation.

It's usually in the implementation that you want to define what the type of ? extends Serializable will be. You don't need to implement this in the Cache interface.

The interface only needs to know what its generics types will be, not the generics of their child : this is for the implementation.

Take a look at the example here below to understand what I exactly mean by that.

Addition : When your define something like Cache<CacheKey, CacheValue> you're not referring to the classes, but you're creation a generic alias. CacheKey could easily be replaced by Blabla and continue to have the same behaviour. The solution is to use extends to make sure we're talking about the type.

This was also the reason why Cache<CacheKey<...>> did not compile, because CacheKey is not referring to the class but is used as an alias

public interface CacheKey<K extends Serializable> extends Serializable {
    K get();
}

public interface CacheValue<V extends Serializable> extends Serializable {
    V get();
}

public interface Cache<K extends CacheKey<? extends Serializable>, V extends CacheValue<? extends Serializable>> {
    void put(K key, V value);
}

public class CacheImpl implements Cache<CacheKey<String>, CacheValue<String>> {
    @Override
    public void put(CacheKey<String> key, CacheValue<String> value) {
        // do whatever
    }
}


问:
Update and Select in the same query in MySQL
I would like to update and count in a single query.

My table structure is:

```<code>|----|-------|------------|
| id | views | update     |
|----|-------|------------|
|  1 |     1 | 2019-05-30 |
|----|-------|------------|
</code>```

The desired output is:

```<code>|----|-------|------------|
| id | views | update     |
|----|-------|------------|
|  1 |     2 | 2019-05-31 |
|----|-------|------------|
</code>```

My try is the following:

```<code>UPDATE table
SET views = (
    SELECT COUNT(views)
    FROM table
    WHERE id='1'
) + 1, update='2019-05-31' WHERE id='1';
</code>```

I'm tried to update the view count by adding +1 to the actual count and update the update field with the new date.

But it doesn't work.

What I'm doing wrong ?

Thanks.

答:
Just do this like.</p>

```<code>UPDATE table SET views = views + 1, update='2019-05-31' WHERE id='1';
</code>```

Body:
I would like to update and count in a single query.

My table structure is:

|----|-------|------------|
| id | views | update     |
|----|-------|------------|
|  1 |     1 | 2019-05-30 |
|----|-------|------------|

The desired output is:

|----|-------|------------|
| id | views | update     |
|----|-------|------------|
|  1 |     2 | 2019-05-31 |
|----|-------|------------|

My try is the following:

UPDATE table
SET views = (
    SELECT COUNT(views)
    FROM table
    WHERE id='1'
) + 1, update='2019-05-31' WHERE id='1';

I'm tried to update the view count by adding +1 to the actual count and update the update field with the new date.

But it doesn't work.

What I'm doing wrong ?

Thanks.

Body:
Just do this like.

UPDATE table SET views = views + 1, update='2019-05-31' WHERE id='1';


问:
I am trying to write a code for fahrenheit to celcius using functions in c
I am trying to use a function to convert from Fahrenheit to Celsius. I wish to know where I made a mistake.

```<code>#include <stdio.h>

void degrees_Fto_C(float f){
    float c;
    c=(5/9)*(f–(32));
    printf("%f",c);
}

int main(){
    float temp;
    printf("Enter the temperature in Fahrenheit: \n");
    scanf("%f",&temp);
    degrees_Fto_C(temp);
    return 0;
}
</code>```

The error message is:

```<code>C:\Users\Pranavs\Desktop\Untitled1.cpp  In function 'void degrees_Fto_C(float)':
C:\Users\Pranavs\Desktop\Untitled1.cpp  [Error] 'f' cannot be used as a function
</code>```

答:
You have the wrong character after the f in line 4. c=(5/9)*(f–(32)) needs to be c=(5.0/9) * (f-(32)).  Your minus sign is a unicode character, and you need ASCII. If you backspace it and replace it with a normal minus sign, it will compile.

Also, you're doing integer arithmetic, and you'll always get zero.  It will work better if you add a decimal point after the 5 or the 9.

Here's a working version of your program:

```<code>#include <stdio.h>
void degrees_Fto_C(float f) {
    float c;
    c = (5.0 / 9) * (f - (32));
    printf("%f", c);
}
int main() {
    float temp;
    printf("Enter the temperature in Fahrenheit: \n");
    scanf("%f", &temp);
    degrees_Fto_C(temp);
    return 0;
}
</code>```

Body:
I am trying to use a function to convert from Fahrenheit to Celsius. I wish to know where I made a mistake.

#include <stdio.h>

void degrees_Fto_C(float f){
    float c;
    c=(5/9)*(f–(32));
    printf("%f",c);
}

int main(){
    float temp;
    printf("Enter the temperature in Fahrenheit: \n");
    scanf("%f",&temp);
    degrees_Fto_C(temp);
    return 0;
}

The error message is:

C:\Users\Pranavs\Desktop\Untitled1.cpp  In function 'void degrees_Fto_C(float)':
C:\Users\Pranavs\Desktop\Untitled1.cpp  [Error] 'f' cannot be used as a function

Body:
You have the wrong character after the f in line 4. c=(5/9)*(f–(32)) needs to be c=(5.0/9) * (f-(32)).  Your minus sign is a unicode character, and you need ASCII. If you backspace it and replace it with a normal minus sign, it will compile.

Also, you're doing integer arithmetic, and you'll always get zero.  It will work better if you add a decimal point after the 5 or the 9.

Here's a working version of your program:

#include <stdio.h>
void degrees_Fto_C(float f) {
    float c;
    c = (5.0 / 9) * (f - (32));
    printf("%f", c);
}
int main() {
    float temp;
    printf("Enter the temperature in Fahrenheit: \n");
    scanf("%f", &temp);
    degrees_Fto_C(temp);
    return 0;
}


问:
react-native-image-slider (cannot display local images)
My local images don't display when using react-native-image-slider

```<code>import React, { Component } from "react";
import {
    View,
    Text,
    StyleSheet,
    Button,
    Image,
    TouchableHighlight
} from "react-native";
import ImageSlider from 'react-native-image-slider';

class HomeScreen extends Component {

    render() {
        return (
            <View style={styles.container}>
        <View style={{alignItems: 'center'}}>
            <ImageSlider
                    loopBothSides
                autoPlayWithInterval={3000}
                images={[
                    '../assets/img/art_1.png',
                    '../assets/img/art_2.png',
                    '../assets/img/art_3.png',
                ]}
                style={{width:200, height: 200}}
            />
        </View>
            </View>
        );
    }
}
export default HomeScreen;

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
    justifyContent: 'center'
    }
});
</code>```

The only things that appears on the screen are the circle icons that tell you what image it's currently displaying. The images themselves are not displayed.

答:
For local image, use require;

```<code>images={[
  require('../assets/img/art_1.png'),
  require('../assets/img/art_2.png'),
  require('../assets/img/art_3.png'),
]}
</code>```

Body:
My local images don't display when using react-native-image-slider

import React, { Component } from "react";
import {
    View,
    Text,
    StyleSheet,
    Button,
    Image,
    TouchableHighlight
} from "react-native";
import ImageSlider from 'react-native-image-slider';

class HomeScreen extends Component {

    render() {
        return (
            <View style={styles.container}>
        <View style={{alignItems: 'center'}}>
            <ImageSlider
                    loopBothSides
                autoPlayWithInterval={3000}
                images={[
                    '../assets/img/art_1.png',
                    '../assets/img/art_2.png',
                    '../assets/img/art_3.png',
                ]}
                style={{width:200, height: 200}}
            />
        </View>
            </View>
        );
    }
}
export default HomeScreen;

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
    justifyContent: 'center'
    }
});

The only things that appears on the screen are the circle icons that tell you what image it's currently displaying. The images themselves are not displayed.

Body:
For local image, use require;

images={[
  require('../assets/img/art_1.png'),
  require('../assets/img/art_2.png'),
  require('../assets/img/art_3.png'),
]}


问:
Do all operating systems already have JRE installed for running java applications?
Let say I am not a java developer and an ordinary person, and installing any application that is written in Java. So, do I need to first install the JRE or no all operating systems already have JRE installed on them?</p>

答:
Do all operating systems already have JRE installed for running java applications?

No.

First of all, Java is not necessarily available for all operating systems.  (It is probably available for most operating systems that are targeted by your application ... but it might not be.)

Secondly, most operating system platforms don't have Java installed by default.  Indeed many OS vendors don't support Java at all: Java is provided by a 3rd-party vendor.

So, do I need to first install the JRE or no all operating systems already have JRE installed on them?

Prior to Java 9, the answer is that you have to install a JRE or a JDK.  This can be done by downloading and installing it directly, or installing it via a package management system on some OSes.  It can also be done by embedding a JRE in your application's installer.

From Java 9 onwards, you can also use "jlink" to create an executable that contains a cut-down JRE which is tailored to run your application on a specific target platform.  This is the approach recommended by Oracle for people who want to distribute "consumer grade" Java applications.

And from Java 11 onwards, for some Java vendors (Oracle for example), the JRE option is no longer available.  For these vendors, if you want "full" Java to run your application, you / your users need to install a JDK.