问:
Kubectl keeps restarting container when ran
I'm currently trying to move our company's squid server to a dockerized version and I'm struggling to get it working with Kubernetes.

I have built a Docker image that works perfectly fine when run with "docker run".
The complete Docker Run command is:

sudo docker run -d -i -t --privileged --volume=/proc/sys/net/ipv4/ip_nonlocal_bind:/var/proc/sys/net/ipv4/ip_nonlocal_bind --net=host --cap-add=SYS_MODULE --cap-add=NET_ADMIN --cap-add=NET_RAW -v /dev:/dev -v /lib/modules:/lib/modules -p80:80 -p8080:8080 -p53:53/udp -p5353:5353/udp -p5666:5666/udp -p4500:4500/udp -p500:500/udp -p3306:3306 --name=edge crossense/edge:latest /bin/bash

When I try to run the Image with Kubernetes, with the something like:

kubectl run --image=crossense/edge:latest --port=80 --port=8080 --port=53 --port=5353 --port=5666 --port=4500 --port=500 --port=3306 edge

seems like Kubernetes tries to get the container up and running, but without any success...

```<code>$kubectl get po
NAME         READY     REASON    RESTARTS   AGE
edge-sz7wp   0/1       Running   10         15m
</code>```

And the $kubectl describe pod edge command gives me lots of these:

```<code>Thu, 09 Nov 2017 17:13:05 +0000 Thu, 09 Nov 2017 17:13:05 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id abcc2ff25a624a998871e02bcb62d42d6f39e9db0a39f601efa4d357dd8334aa
Thu, 09 Nov 2017 17:13:15 +0000 Thu, 09 Nov 2017 17:13:15 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 878778836bd3cc25bdf1e3b9cc2f2f6fa22b75b938a481172f08a6ec50571582
Thu, 09 Nov 2017 17:13:15 +0000 Thu, 09 Nov 2017 17:13:15 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 878778836bd3cc25bdf1e3b9cc2f2f6fa22b75b938a481172f08a6ec50571582
Thu, 09 Nov 2017 17:13:25 +0000 Thu, 09 Nov 2017 17:13:25 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id aa51e94536216b905ff9ba07951fedbc0007476b55dfdb2e5106418fb6aee05c
Thu, 09 Nov 2017 17:13:25 +0000 Thu, 09 Nov 2017 17:13:25 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id aa51e94536216b905ff9ba07951fedbc0007476b55dfdb2e5106418fb6aee05c
Thu, 09 Nov 2017 17:13:35 +0000 Thu, 09 Nov 2017 17:13:35 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id f4661e5ea33471cd1ba30816b40c8ba2d204fa22509b973da4af6eedb64c592e
Thu, 09 Nov 2017 17:13:35 +0000 Thu, 09 Nov 2017 17:13:35 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id f4661e5ea33471cd1ba30816b40c8ba2d204fa22509b973da4af6eedb64c592e
Thu, 09 Nov 2017 17:13:45 +0000 Thu, 09 Nov 2017 17:13:45 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 75f83dcb9b4f8af5134d6fd2edcd9342ecf56111e132a45f4e9787e83466e28b
Thu, 09 Nov 2017 17:13:45 +0000 Thu, 09 Nov 2017 17:13:45 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 75f83dcb9b4f8af5134d6fd2edcd9342ecf56111e132a45f4e9787e83466e28b
Thu, 09 Nov 2017 17:13:55 +0000 Thu, 09 Nov 2017 17:13:55 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id c9d0535b3962ec9da29c068dbb0a6b64426a5ac3e52f72e79bcbaf03c9f3d403
Thu, 09 Nov 2017 17:13:55 +0000 Thu, 09 Nov 2017 17:13:55 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id c9d0535b3962ec9da29c068dbb0a6b64426a5ac3e52f72e79bcbaf03c9f3d403
Thu, 09 Nov 2017 17:14:05 +0000 Thu, 09 Nov 2017 17:14:05 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 579f4428e9804404bd746cceee88bb6c73066a33263202bb5f1eb15f6ff26d7b
Thu, 09 Nov 2017 17:14:05 +0000 Thu, 09 Nov 2017 17:14:05 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 579f4428e9804404bd746cceee88bb6c73066a33263202bb5f1eb15f6ff26d7b
Thu, 09 Nov 2017 17:14:15 +0000 Thu, 09 Nov 2017 17:14:15 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id d36b2c9ddf0b1a05d86b43d2a92eb3c00ae92d00e155d5a1be1da8e2682f901b
Thu, 09 Nov 2017 17:14:15 +0000 Thu, 09 Nov 2017 17:14:15 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id d36b2c9ddf0b1a05d86b43d2a92eb3c00ae92d00e155d5a1be1da8e2682f901b
Thu, 09 Nov 2017 17:14:25 +0000 Thu, 09 Nov 2017 17:14:25 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 2d7b24537414f5e6f2981bf5f01596b19ea1abdb0eb4b81508fc7f44e8c34609
Thu, 09 Nov 2017 17:14:25 +0000 Thu, 09 Nov 2017 17:14:25 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 2d7b24537414f5e6f2981bf5f01596b19ea1abdb0eb4b81508fc7f44e8c34609
Thu, 09 Nov 2017 17:14:35 +0000 Thu, 09 Nov 2017 17:14:35 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id fdae44c599b77d44839e4897b750203c183001a6053c926432ef5a3c7f4deb38
Thu, 09 Nov 2017 17:14:35 +0000 Thu, 09 Nov 2017 17:14:35 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id fdae44c599b77d44839e4897b750203c183001a6053c926432ef5a3c7f4deb38
Thu, 09 Nov 2017 17:14:45 +0000 Thu, 09 Nov 2017 17:14:45 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 544351dda838d698e3bc125840edb6ad71cd0165a970cce46825df03b826eb38
Thu, 09 Nov 2017 17:14:45 +0000 Thu, 09 Nov 2017 17:14:45 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 544351dda838d698e3bc125840edb6ad71cd0165a970cce46825df03b826eb38
Thu, 09 Nov 2017 17:14:55 +0000 Thu, 09 Nov 2017 17:14:55 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 00fe4c286c1cc9b905c9c0927f82b39d45d41295a9dd0852131bba087bb19610
Thu, 09 Nov 2017 17:14:55 +0000 Thu, 09 Nov 2017 17:14:55 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 00fe4c286c1cc9b905c9c0927f82b39d45d41295a9dd0852131bba087bb19610
</code>```

Any help would be much appreciated!

答:
For all the poor souls out there, who couldn't find out the answer,
the reason for the pod to keep restarting is that the command executed by it has exited with code 0 (meaning successfully).

In my case, I was running /bin/bash as the entrypoint command, as specified in my pod configuration .yaml file:

```<code>apiVersion: v1
kind: Pod
metadata:
 name: edge
spec:
 containers:
   - name: edge
     image: "crossense/edge:production"
     command:
       - /bin/bash
     securityContext:
       capabilities:
         add:
           - NET_ADMIN
           - SYS_MODULE
           - NET_RAW
     volumeMounts:
       - name: ip-nonlocal-bind
         mountPath: /host/proc/sys/net/ipv4
       - name: dev
         mountPath: /host/dev
       - name: modules
         mountPath: /host/lib/modules

....
</code>```

The solution was simply adding a non exiting command to the
  entrypoint. This can be any process run on foreground or simply a
  /bin/sleep

For the sake of example and future learning, my final pod configuration file looked like this:

```<code>apiVersion: v1
kind: Pod
metadata:
 name: edge
spec:
 hostNetwork: true
 containers:
   - name: edge
     image: "crossense/edge:production"
     command: ["/bin/bash", "-c"]
     args: ["service rsyslog restart; service proxysql start; service mongodb start; service pdns-recursor start; service supervisor start; service danted start; touch /var/run/squid.pid; chown proxy /var/run/squid.pid; service squid restart; service ipsec start; /sbin/iptables-restore < /etc/iptables/rules.v4; sleep infinity"]
     securityContext:
       privileged: true
       capabilities:
         add:
           - NET_ADMIN
           - SYS_MODULE
           - NET_RAW
     volumeMounts:
       - mountPath: /dev/shm
         name: dshm
       - name: ip-nonlocal-bind
         mountPath: /host/proc/sys/net/ipv4
       - name: dev
         mountPath: /dev
       - name: modules
         mountPath: /lib/modules
     ports:
       - containerPort: 80
       - containerPort: 8080
       - containerPort: 53
         protocol: UDP
       - containerPort: 5353
         protocol: UDP
       - containerPort: 5666
       - containerPort: 4500
       - containerPort: 500
       - containerPort: 3306
 volumes:
   - name: dshm
     emptyDir:
       medium: Memory
   - name: ip-nonlocal-bind
     hostPath:
       path: /proc/sys/net/ipv4
   - name: dev
     hostPath:
       path: /dev
       type: Directory
   - name: modules
     hostPath:
       path: /lib/modules
       type: Directory
</code>```

For any questions, feel free to comment of this thread, or ask me at max.vlashchuk@gmail.com :)

Body:
I'm currently trying to move our company's squid server to a dockerized version and I'm struggling to get it working with Kubernetes.

I have built a Docker image that works perfectly fine when run with "docker run".
The complete Docker Run command is:

sudo docker run -d -i -t --privileged --volume=/proc/sys/net/ipv4/ip_nonlocal_bind:/var/proc/sys/net/ipv4/ip_nonlocal_bind --net=host --cap-add=SYS_MODULE --cap-add=NET_ADMIN --cap-add=NET_RAW -v /dev:/dev -v /lib/modules:/lib/modules -p80:80 -p8080:8080 -p53:53/udp -p5353:5353/udp -p5666:5666/udp -p4500:4500/udp -p500:500/udp -p3306:3306 --name=edge crossense/edge:latest /bin/bash

When I try to run the Image with Kubernetes, with the something like:

kubectl run --image=crossense/edge:latest --port=80 --port=8080 --port=53 --port=5353 --port=5666 --port=4500 --port=500 --port=3306 edge

seems like Kubernetes tries to get the container up and running, but without any success...

$kubectl get po
NAME         READY     REASON    RESTARTS   AGE
edge-sz7wp   0/1       Running   10         15m

And the $kubectl describe pod edge command gives me lots of these:

Thu, 09 Nov 2017 17:13:05 +0000 Thu, 09 Nov 2017 17:13:05 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id abcc2ff25a624a998871e02bcb62d42d6f39e9db0a39f601efa4d357dd8334aa
Thu, 09 Nov 2017 17:13:15 +0000 Thu, 09 Nov 2017 17:13:15 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 878778836bd3cc25bdf1e3b9cc2f2f6fa22b75b938a481172f08a6ec50571582
Thu, 09 Nov 2017 17:13:15 +0000 Thu, 09 Nov 2017 17:13:15 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 878778836bd3cc25bdf1e3b9cc2f2f6fa22b75b938a481172f08a6ec50571582
Thu, 09 Nov 2017 17:13:25 +0000 Thu, 09 Nov 2017 17:13:25 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id aa51e94536216b905ff9ba07951fedbc0007476b55dfdb2e5106418fb6aee05c
Thu, 09 Nov 2017 17:13:25 +0000 Thu, 09 Nov 2017 17:13:25 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id aa51e94536216b905ff9ba07951fedbc0007476b55dfdb2e5106418fb6aee05c
Thu, 09 Nov 2017 17:13:35 +0000 Thu, 09 Nov 2017 17:13:35 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id f4661e5ea33471cd1ba30816b40c8ba2d204fa22509b973da4af6eedb64c592e
Thu, 09 Nov 2017 17:13:35 +0000 Thu, 09 Nov 2017 17:13:35 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id f4661e5ea33471cd1ba30816b40c8ba2d204fa22509b973da4af6eedb64c592e
Thu, 09 Nov 2017 17:13:45 +0000 Thu, 09 Nov 2017 17:13:45 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 75f83dcb9b4f8af5134d6fd2edcd9342ecf56111e132a45f4e9787e83466e28b
Thu, 09 Nov 2017 17:13:45 +0000 Thu, 09 Nov 2017 17:13:45 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 75f83dcb9b4f8af5134d6fd2edcd9342ecf56111e132a45f4e9787e83466e28b
Thu, 09 Nov 2017 17:13:55 +0000 Thu, 09 Nov 2017 17:13:55 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id c9d0535b3962ec9da29c068dbb0a6b64426a5ac3e52f72e79bcbaf03c9f3d403
Thu, 09 Nov 2017 17:13:55 +0000 Thu, 09 Nov 2017 17:13:55 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id c9d0535b3962ec9da29c068dbb0a6b64426a5ac3e52f72e79bcbaf03c9f3d403
Thu, 09 Nov 2017 17:14:05 +0000 Thu, 09 Nov 2017 17:14:05 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 579f4428e9804404bd746cceee88bb6c73066a33263202bb5f1eb15f6ff26d7b
Thu, 09 Nov 2017 17:14:05 +0000 Thu, 09 Nov 2017 17:14:05 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 579f4428e9804404bd746cceee88bb6c73066a33263202bb5f1eb15f6ff26d7b
Thu, 09 Nov 2017 17:14:15 +0000 Thu, 09 Nov 2017 17:14:15 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id d36b2c9ddf0b1a05d86b43d2a92eb3c00ae92d00e155d5a1be1da8e2682f901b
Thu, 09 Nov 2017 17:14:15 +0000 Thu, 09 Nov 2017 17:14:15 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id d36b2c9ddf0b1a05d86b43d2a92eb3c00ae92d00e155d5a1be1da8e2682f901b
Thu, 09 Nov 2017 17:14:25 +0000 Thu, 09 Nov 2017 17:14:25 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 2d7b24537414f5e6f2981bf5f01596b19ea1abdb0eb4b81508fc7f44e8c34609
Thu, 09 Nov 2017 17:14:25 +0000 Thu, 09 Nov 2017 17:14:25 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 2d7b24537414f5e6f2981bf5f01596b19ea1abdb0eb4b81508fc7f44e8c34609
Thu, 09 Nov 2017 17:14:35 +0000 Thu, 09 Nov 2017 17:14:35 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id fdae44c599b77d44839e4897b750203c183001a6053c926432ef5a3c7f4deb38
Thu, 09 Nov 2017 17:14:35 +0000 Thu, 09 Nov 2017 17:14:35 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id fdae44c599b77d44839e4897b750203c183001a6053c926432ef5a3c7f4deb38
Thu, 09 Nov 2017 17:14:45 +0000 Thu, 09 Nov 2017 17:14:45 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 544351dda838d698e3bc125840edb6ad71cd0165a970cce46825df03b826eb38
Thu, 09 Nov 2017 17:14:45 +0000 Thu, 09 Nov 2017 17:14:45 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 544351dda838d698e3bc125840edb6ad71cd0165a970cce46825df03b826eb38
Thu, 09 Nov 2017 17:14:55 +0000 Thu, 09 Nov 2017 17:14:55 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           created     Created with docker id 00fe4c286c1cc9b905c9c0927f82b39d45d41295a9dd0852131bba087bb19610
Thu, 09 Nov 2017 17:14:55 +0000 Thu, 09 Nov 2017 17:14:55 +0000 1   {kubelet 127.0.0.1} spec.containers{edge}           started     Started with docker id 00fe4c286c1cc9b905c9c0927f82b39d45d41295a9dd0852131bba087bb19610

Any help would be much appreciated!

Body:
For all the poor souls out there, who couldn't find out the answer,
the reason for the pod to keep restarting is that the command executed by it has exited with code 0 (meaning successfully).

In my case, I was running /bin/bash as the entrypoint command, as specified in my pod configuration .yaml file:

apiVersion: v1
kind: Pod
metadata:
 name: edge
spec:
 containers:
   - name: edge
     image: "crossense/edge:production"
     command:
       - /bin/bash
     securityContext:
       capabilities:
         add:
           - NET_ADMIN
           - SYS_MODULE
           - NET_RAW
     volumeMounts:
       - name: ip-nonlocal-bind
         mountPath: /host/proc/sys/net/ipv4
       - name: dev
         mountPath: /host/dev
       - name: modules
         mountPath: /host/lib/modules

....

The solution was simply adding a non exiting command to the
  entrypoint. This can be any process run on foreground or simply a
  /bin/sleep

For the sake of example and future learning, my final pod configuration file looked like this:

apiVersion: v1
kind: Pod
metadata:
 name: edge
spec:
 hostNetwork: true
 containers:
   - name: edge
     image: "crossense/edge:production"
     command: ["/bin/bash", "-c"]
     args: ["service rsyslog restart; service proxysql start; service mongodb start; service pdns-recursor start; service supervisor start; service danted start; touch /var/run/squid.pid; chown proxy /var/run/squid.pid; service squid restart; service ipsec start; /sbin/iptables-restore < /etc/iptables/rules.v4; sleep infinity"]
     securityContext:
       privileged: true
       capabilities:
         add:
           - NET_ADMIN
           - SYS_MODULE
           - NET_RAW
     volumeMounts:
       - mountPath: /dev/shm
         name: dshm
       - name: ip-nonlocal-bind
         mountPath: /host/proc/sys/net/ipv4
       - name: dev
         mountPath: /dev
       - name: modules
         mountPath: /lib/modules
     ports:
       - containerPort: 80
       - containerPort: 8080
       - containerPort: 53
         protocol: UDP
       - containerPort: 5353
         protocol: UDP
       - containerPort: 5666
       - containerPort: 4500
       - containerPort: 500
       - containerPort: 3306
 volumes:
   - name: dshm
     emptyDir:
       medium: Memory
   - name: ip-nonlocal-bind
     hostPath:
       path: /proc/sys/net/ipv4
   - name: dev
     hostPath:
       path: /dev
       type: Directory
   - name: modules
     hostPath:
       path: /lib/modules
       type: Directory

For any questions, feel free to comment of this thread, or ask me at max.vlashchuk@gmail.com :)


来源: stackexchange

问:
How to concatenate arrays when button is selected
So I'm working on a quiz-app and I want to give the user an option screen before starting the quiz, where the user can choose which categories the quiz should have.

Its currently only working with 1 category at a time but I want to be able to concatenate the questionArrays when the user selects button in the option screen.

At this time the user selects a button and depending on the sender.tag an Int gets passed through the var called 'pickedCategory' which then decides which of the arrays to base the questions on. This happens in the prepare for segue:

```<code>    let selectedCategory = quizCategories[pickedCategory]
    secondVC.allQuestions = selectedCategory.questions
</code>```

quizCategories is declared at the top:

```<code>    var quizCategories = [QuestionArray]()
</code>```

What I would like to do is have 4 buttons and whenever one is selected, concatenate an array to the selectedCategory

For instance, button 1 & 2 is selected, i.e. the user wants to have questions based on 2 categories. Resulting in something like this?

```<code>let selectedCategory = quizCategories[0].questions + quizCategories[1].questions
</code>```

and if 3 buttons selected, add another quizCategories array to the final array etc etc

Please note, its not HOW to concatenate I'm looking for, its how to automatically do this depending on buttons selected..

This is my first question posted and I am very new to Swift.. hope I didn't confuse u guys.. thanks  :)

答:
You can track which button is selected and when you want to start quizz, concatenate the corresponding arrays.

Your code could look like this:

```<code>import UIKit

class QuizzSelection: UIViewController
{
  @IBAction func firstButtonAction(_ sender: Any)
  {
    firstButtonWasClicked()
  }

  @IBAction func secondButtonAction(_ sender: Any)
  {
    secondButtonWasClicked()
  }

  @IBAction func goForwardWithQuizz(_ sender: Any)
  {
    startQuizzWasClicked()
  }

  var isFirstCategorySelected = false
  var isSecondCategorySelected = false
  let firstCategoryQuestions = ["Question Cat 1"]
  let secondCategoryQuestions = ["Question Cat 2"]
  var emptyArrayOfQuestions = [String]()

  func firstButtonWasClicked()
  {
    if isFirstCategorySelected == true{
      isFirstCategorySelected = false
    } else{
      isFirstCategorySelected = true
    }
  }

  func secondButtonWasClicked()
  {
    if isSecondCategorySelected == true{
      isSecondCategorySelected = false
    } else{
      isSecondCategorySelected = true
    }
  }

  func startQuizzWasClicked()
  {
    if isFirstCategorySelected == true{
      emptyArrayOfQuestions += firstCategoryQuestions
    }
    if isSecondCategorySelected == true{
      emptyArrayOfQuestions += secondCategoryQuestions
    }
  }
}
</code>```

EDIT

Improved code for six categories:

```<code>import UIKit

class QuizzSelection: UIViewController
{
  @IBAction func firstButtonAction(_ sender: Any)
  {
    firstButtonWasClicked()
  }

  @IBAction func secondButtonAction(_ sender: Any)
  {
    secondButtonWasClicked()
  }

  // Four mour button actions

  @IBAction func goForwardWithQuizz(_ sender: Any)
  {
    startQuizzWasClicked()
  }

  var wichCategoryAreSelected = [false, false, false, false, false, false] //six categories
  var arrayOfQuestions = [["Question 1 Cat 1","Question 2 Cat 1"], ["Question 1 Cat 2", "Question 2 Cat 2"], ...]
  var emptyArrayOfQuestions = [String]()

  func firstButtonWasClicked()
  {
    wichCategoryAreSelected[0] = !wichCategoryAreSelected[0]
  }

  func secondButtonWasClicked()
  {
    wichCategoryAreSelected[1] = !wichCategoryAreSelected[1]
  }

  func startQuizzWasClicked()
  {
    for i in 0...(wichCategoryAreSelected.count-1)
    {
      if wichCategoryAreSelected[i]
      {
        emptyArrayOfQuestions += arrayOfQuestions[i]
      }
    }
  }

}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So I'm working on a quiz-app and I want to give the user an option screen before starting the quiz, where the user can choose which categories the quiz should have.

Its currently only working with 1 category at a time but I want to be able to concatenate the questionArrays when the user selects button in the option screen.

At this time the user selects a button and depending on the sender.tag an Int gets passed through the var called 'pickedCategory' which then decides which of the arrays to base the questions on. This happens in the prepare for segue:

    let selectedCategory = quizCategories[pickedCategory]
    secondVC.allQuestions = selectedCategory.questions

quizCategories is declared at the top:

    var quizCategories = [QuestionArray]()

What I would like to do is have 4 buttons and whenever one is selected, concatenate an array to the selectedCategory

For instance, button 1 & 2 is selected, i.e. the user wants to have questions based on 2 categories. Resulting in something like this?

let selectedCategory = quizCategories[0].questions + quizCategories[1].questions

and if 3 buttons selected, add another quizCategories array to the final array etc etc

Please note, its not HOW to concatenate I'm looking for, its how to automatically do this depending on buttons selected..

This is my first question posted and I am very new to Swift.. hope I didn't confuse u guys.. thanks  :)

Body:
You can track which button is selected and when you want to start quizz, concatenate the corresponding arrays.

Your code could look like this:

import UIKit

class QuizzSelection: UIViewController
{
  @IBAction func firstButtonAction(_ sender: Any)
  {
    firstButtonWasClicked()
  }

  @IBAction func secondButtonAction(_ sender: Any)
  {
    secondButtonWasClicked()
  }

  @IBAction func goForwardWithQuizz(_ sender: Any)
  {
    startQuizzWasClicked()
  }

  var isFirstCategorySelected = false
  var isSecondCategorySelected = false
  let firstCategoryQuestions = ["Question Cat 1"]
  let secondCategoryQuestions = ["Question Cat 2"]
  var emptyArrayOfQuestions = [String]()

  func firstButtonWasClicked()
  {
    if isFirstCategorySelected == true{
      isFirstCategorySelected = false
    } else{
      isFirstCategorySelected = true
    }
  }

  func secondButtonWasClicked()
  {
    if isSecondCategorySelected == true{
      isSecondCategorySelected = false
    } else{
      isSecondCategorySelected = true
    }
  }

  func startQuizzWasClicked()
  {
    if isFirstCategorySelected == true{
      emptyArrayOfQuestions += firstCategoryQuestions
    }
    if isSecondCategorySelected == true{
      emptyArrayOfQuestions += secondCategoryQuestions
    }
  }
}

EDIT

Improved code for six categories:

import UIKit

class QuizzSelection: UIViewController
{
  @IBAction func firstButtonAction(_ sender: Any)
  {
    firstButtonWasClicked()
  }

  @IBAction func secondButtonAction(_ sender: Any)
  {
    secondButtonWasClicked()
  }

  // Four mour button actions

  @IBAction func goForwardWithQuizz(_ sender: Any)
  {
    startQuizzWasClicked()
  }

  var wichCategoryAreSelected = [false, false, false, false, false, false] //six categories
  var arrayOfQuestions = [["Question 1 Cat 1","Question 2 Cat 1"], ["Question 1 Cat 2", "Question 2 Cat 2"], ...]
  var emptyArrayOfQuestions = [String]()

  func firstButtonWasClicked()
  {
    wichCategoryAreSelected[0] = !wichCategoryAreSelected[0]
  }

  func secondButtonWasClicked()
  {
    wichCategoryAreSelected[1] = !wichCategoryAreSelected[1]
  }

  func startQuizzWasClicked()
  {
    for i in 0...(wichCategoryAreSelected.count-1)
    {
      if wichCategoryAreSelected[i]
      {
        emptyArrayOfQuestions += arrayOfQuestions[i]
      }
    }
  }

}


问:
How do you open an SDF database file in SQL Server Object Explorer?
I have created database using EF6 code first but can not figure out how to open sdf database file in SQL Server Object Explorer. Connection string: "Data Source=|DataDirectory|AlgebraDB.sdf".
Using Visual Studio 2017.

答: You cannot open a SQL Server Compact (.sdf) database file in SQL Server Object Explorer. In Visual Studio 2017, install the SQLite and SQL Server Compact Toolbox extension, and use that to open and explore the file (I am the author of the Toolbox)</p>


问:
Replacing missing quarter and missing data per quarter

Background

I've a quarterly data set where certain quarters and corresponding values are missing. The characteristics of the data set are:

Each group should have the same number of quarters but in practe quarters are missing

For missing quarter values are unknown

This is to be resolved by sourcing imputing next available value; for instance, as available via na.locf function

Example data

```<code># Packages
Vectorize(require)(package = c("tidyverse", "zoo", "magrittr"),
                   character.only = TRUE)

# Seed
set.seed(123)

# Dummy data
dta <- data.frame(group = rep(LETTERS[1:5], 10)) %>%
    group_by(group) %>%
    mutate(qrtr = seq(
        from = as.Date("01/01/2012", "%d/%m/%Y"),
        to = as.Date("31/5/2014", "%d/%m/%Y"),
        by = "quarter"
    )) %>%
    ungroup() %>%
    mutate(qrtr = as.yearqtr(qrtr)) %>%
    arrange(group, qrtr) %>%
    mutate(value = sample(1:10, 50, replace = TRUE))

# Remove random rows
dta[sample(1:dim(dta)[1], 10), c(2, 3)] <- NA
dta %<>% na.omit()
</code>```

Preview

```<code># A tibble: 40 x 3
   group          qrtr value
   <chr> <S3: yearqtr> <int>
 1     A       2012 Q1     3
 2     A       2012 Q2     8
 3     A       2012 Q4     9
 4     A       2013 Q1    10
 5     A       2013 Q3     6
 6     A       2013 Q4     9
 7     A       2014 Q1     6
 8     B       2012 Q1    10
 9     B       2012 Q2     5
10     B       2012 Q3     7
# ... with 30 more rows
</code>```

Problem

Create add rows within each group where quarter are missing. Total number of quarter is derived from sequence min(qrtr) to max(qrtr), in the context of existing code:

```<code>seq(from = as.Date("01/01/2012", "%d/%m/%Y"),
    to = as.Date("31/5/2014", "%d/%m/%Y"),
    by = "quarter")
</code>```

First non-missing value should be carried forward for the missing value.

Desired results:

```<code>>> dta
# A tibble: 50 x 3
   group          qrtr value
   <chr> <S3: yearqtr> <int>
 1     A       2012 Q1     3
 2     A       2012 Q2     8
 3     A       2012 Q3     8
 4     A       2012 Q4     9
 5     A       2013 Q1    10
 6     A       2013 Q2    10
 7     A       2013 Q3     6
 8     A       2013 Q4     9
 9     A       2014 Q1     6
10     A       2015 Q1     6
# ... with 40 more rows
</code>```

Proposed approaches

One approach would rely on making use of the expand, in order to convert implicitly missing values to explicitly missing values. This so far creates missing quarters but there is no clear way of creating missing observations for value column for where given quarter is missing.

```<code>dta %>%
    # Append mixing quarters
    expand(group, qrtr) %>%
    left_join(data.frame(qrtr = as.yearqtr(
        seq(
            from = as.Date("01/01/2012", "%d/%m/%Y"),
            to = as.Date("31/5/2014", "%d/%m/%Y"),
            by = "quarter"
        )
    )), by = "qrtr") %>%
    # TODO
    # mutate(value = na.locf(value)) %>%
    arrange(group, qrtr) -> dta_fixed
</code>```

答:
Use read.zoo to create a multivariate time series z with one column per group; merge that with a zero width series of quarters, run na.locf and then convert that back to long form.

We can omit:

the line with the merge if there is no quarter missing from every group -- in the example data in the question this is the case. i.e. for the data in the question we could omit the merge (although if we left it in it would not cause a problem)

the last line (the one with fortify.zoo) if we can work with the 10 x 5 multivariate time series z directly, which may actually be more convenient, e.g. library(ggplot); autoplot(z, facet = NULL) + scale_x_yearqtr() or the same without the facet argument will plot it using ggplot2 graphics using 1 or 5 panels.

This does not use any packages that the question is not already using anyways and works directly with the index in the original "yearqtr" class without conversion.

```<code>library(zoo)

z <- read.zoo(dat, index = "qrtr", split = "group")
z <- merge(z, zoo(, seq(start(z), end(z), 1/4))
z <- na.locf(z)
fortify.zoo(z, melt = TRUE)
</code>```

This could alternately be expressed as the following pipeline:

```<code>library(dplyr) # or library(magrittr)
library(zoo)

dta %>%
    read.zoo(index = "qrtr", split = "group") %>%
    merge(zoo(, start(z), end(z), 1/4)) %>%
    na.locf %>%
    fortify.zoo(melt = TRUE)
</code>```

Updates  Have added pipeline and made a number of wording improvements and clarifications.

Body:
Background

I've a quarterly data set where certain quarters and corresponding values are missing. The characteristics of the data set are:

Each group should have the same number of quarters but in practe quarters are missing

For missing quarter values are unknown

This is to be resolved by sourcing imputing next available value; for instance, as available via na.locf function

Example data

# Packages
Vectorize(require)(package = c("tidyverse", "zoo", "magrittr"),
                   character.only = TRUE)

# Seed
set.seed(123)

# Dummy data
dta <- data.frame(group = rep(LETTERS[1:5], 10)) %>%
    group_by(group) %>%
    mutate(qrtr = seq(
        from = as.Date("01/01/2012", "%d/%m/%Y"),
        to = as.Date("31/5/2014", "%d/%m/%Y"),
        by = "quarter"
    )) %>%
    ungroup() %>%
    mutate(qrtr = as.yearqtr(qrtr)) %>%
    arrange(group, qrtr) %>%
    mutate(value = sample(1:10, 50, replace = TRUE))

# Remove random rows
dta[sample(1:dim(dta)[1], 10), c(2, 3)] <- NA
dta %<>% na.omit()

Preview

# A tibble: 40 x 3
   group          qrtr value
   <chr> <S3: yearqtr> <int>
 1     A       2012 Q1     3
 2     A       2012 Q2     8
 3     A       2012 Q4     9
 4     A       2013 Q1    10
 5     A       2013 Q3     6
 6     A       2013 Q4     9
 7     A       2014 Q1     6
 8     B       2012 Q1    10
 9     B       2012 Q2     5
10     B       2012 Q3     7
# ... with 30 more rows

Problem

Create add rows within each group where quarter are missing. Total number of quarter is derived from sequence min(qrtr) to max(qrtr), in the context of existing code:

seq(from = as.Date("01/01/2012", "%d/%m/%Y"),
    to = as.Date("31/5/2014", "%d/%m/%Y"),
    by = "quarter")

First non-missing value should be carried forward for the missing value.

Desired results:

>> dta
# A tibble: 50 x 3
   group          qrtr value
   <chr> <S3: yearqtr> <int>
 1     A       2012 Q1     3
 2     A       2012 Q2     8
 3     A       2012 Q3     8
 4     A       2012 Q4     9
 5     A       2013 Q1    10
 6     A       2013 Q2    10
 7     A       2013 Q3     6
 8     A       2013 Q4     9
 9     A       2014 Q1     6
10     A       2015 Q1     6
# ... with 40 more rows

Proposed approaches

One approach would rely on making use of the expand, in order to convert implicitly missing values to explicitly missing values. This so far creates missing quarters but there is no clear way of creating missing observations for value column for where given quarter is missing.

dta %>%
    # Append mixing quarters
    expand(group, qrtr) %>%
    left_join(data.frame(qrtr = as.yearqtr(
        seq(
            from = as.Date("01/01/2012", "%d/%m/%Y"),
            to = as.Date("31/5/2014", "%d/%m/%Y"),
            by = "quarter"
        )
    )), by = "qrtr") %>%
    # TODO
    # mutate(value = na.locf(value)) %>%
    arrange(group, qrtr) -> dta_fixed

Body:
Use read.zoo to create a multivariate time series z with one column per group; merge that with a zero width series of quarters, run na.locf and then convert that back to long form.

We can omit:

the line with the merge if there is no quarter missing from every group -- in the example data in the question this is the case. i.e. for the data in the question we could omit the merge (although if we left it in it would not cause a problem)

the last line (the one with fortify.zoo) if we can work with the 10 x 5 multivariate time series z directly, which may actually be more convenient, e.g. library(ggplot); autoplot(z, facet = NULL) + scale_x_yearqtr() or the same without the facet argument will plot it using ggplot2 graphics using 1 or 5 panels.

This does not use any packages that the question is not already using anyways and works directly with the index in the original "yearqtr" class without conversion.

library(zoo)

z <- read.zoo(dat, index = "qrtr", split = "group")
z <- merge(z, zoo(, seq(start(z), end(z), 1/4))
z <- na.locf(z)
fortify.zoo(z, melt = TRUE)

This could alternately be expressed as the following pipeline:

library(dplyr) # or library(magrittr)
library(zoo)

dta %>%
    read.zoo(index = "qrtr", split = "group") %>%
    merge(zoo(, start(z), end(z), 1/4)) %>%
    na.locf %>%
    fortify.zoo(melt = TRUE)

Updates  Have added pipeline and made a number of wording improvements and clarifications.


问:
R - instead of plotting, just show the table
this is my R code:

```<code>output$heatmap_viewed_ads <- renderPlotly({
  plot_ly(  x = c(1,2,3,4,5), y = casted_viewed_ads$FEED, z = as.matrix(casted_viewed_ads[2:15]), type = "heatmap",colors = "Greens"  )%>%
  layout(title =  "#Views", xaxis=list(title="Position of Display"))})
</code>```

I am plotting right here this data. I do now want to just show the matrix that is generated by

```<code>as.matrix(casted_viewed_ads[2:15])
</code>```

Can someone help me please? I'm new to R. I'm using Shiny and Plotly.

Thanks!

答:
You can use renderTable to display your matrix in the Shiny app.

Server

```<code>output$matrix <- renderTable({

yourmatrix <- as.matrix(casted_viewed_ads[2:15])

yourmatrix

})
</code>```

UI

```<code>mainPanel(
plotOutput("heatmap_viewed_ads"), #you can eliminate this line if you just want to show the table
tableOutput("matrix")
)
</code>```

Body:
this is my R code:

output$heatmap_viewed_ads <- renderPlotly({
  plot_ly(  x = c(1,2,3,4,5), y = casted_viewed_ads$FEED, z = as.matrix(casted_viewed_ads[2:15]), type = "heatmap",colors = "Greens"  )%>%
  layout(title =  "#Views", xaxis=list(title="Position of Display"))})

I am plotting right here this data. I do now want to just show the matrix that is generated by

as.matrix(casted_viewed_ads[2:15])

Can someone help me please? I'm new to R. I'm using Shiny and Plotly.

Thanks!

Body:
You can use renderTable to display your matrix in the Shiny app.

Server

output$matrix <- renderTable({

yourmatrix <- as.matrix(casted_viewed_ads[2:15])

yourmatrix

})

UI

mainPanel(
plotOutput("heatmap_viewed_ads"), #you can eliminate this line if you just want to show the table
tableOutput("matrix")
)


问:
In C, when would type casting a char to an integer not return a value between 0 and 127?
A common interview question asks to write an algorithm that detects duplicates in a string.
Using a character array of length 128 to keep track of the characters already seen is a good way to solve this problem in linear time.

In C we would type something like

```<code>char seen_chars[128];
unsigned char c;

/* set seen_chars to all zeros, assign c */

seen_chars[ c ] = 1;
</code>```

To mark character c as seen. Of course this relies on

```<code>(int) c
</code>```

returning a value between 0 and 127.

I'm wondering when would this fail? What are the assumptions that make this code work correctly?

答:
The code will fail (and cause undefined behavior) every time when the integer value of the given char c is not between 0 and 127 (inclusive).

C does in no way limit the maximum range of char - you are only guaranteed that it can hold at least 256 distinct values - so in any given C implementation a valid char value can be out of that boundary. On most desktop systems a char can hold values from -128 to 127, or from 0 to 255. However, as an example:

```<code>char aFunction(void);
char c = aFunction();
if ((int)c > 1000000000)
    printf("This could be true on some systems\n").
</code>```

The following would be valid (although it may exhaust your stack on systems with large chars):

```<code>#include <limits.h>
_Bool seen[1<<CHAR_BIT] = {0};
seen[(unsigned char)c] = 1;
/* etc. */
</code>```

ContentLicense: CC BY-SA 2.5

Body:
A common interview question asks to write an algorithm that detects duplicates in a string.
Using a character array of length 128 to keep track of the characters already seen is a good way to solve this problem in linear time.

In C we would type something like

char seen_chars[128];
unsigned char c;

/* set seen_chars to all zeros, assign c */

seen_chars[ c ] = 1;

To mark character c as seen. Of course this relies on

(int) c

returning a value between 0 and 127.

I'm wondering when would this fail? What are the assumptions that make this code work correctly?

Body:
The code will fail (and cause undefined behavior) every time when the integer value of the given char c is not between 0 and 127 (inclusive).

C does in no way limit the maximum range of char - you are only guaranteed that it can hold at least 256 distinct values - so in any given C implementation a valid char value can be out of that boundary. On most desktop systems a char can hold values from -128 to 127, or from 0 to 255. However, as an example:

char aFunction(void);
char c = aFunction();
if ((int)c > 1000000000)
    printf("This could be true on some systems\n").

The following would be valid (although it may exhaust your stack on systems with large chars):

#include <limits.h>
_Bool seen[1<<CHAR_BIT] = {0};
seen[(unsigned char)c] = 1;
/* etc. */


问:
How do I add a border header of a link on my navigation bar while removing the div's border?
This is what it looks like at the moment:
I want to remove the gray border under the 'active' class element (i.e. the Home in this picture), while having the orange thicker bottom-border replace it. How do I go about doing that?

* {
    font-family: 'Asap', sans-serif;
    margin: 0;
}

div.header {
    background-color: rgba(0, 0, 0, 0.1);
    position: absolute;
    width: 100%;
    border-bottom: solid rgba(0, 0, 0, 0.1) 2px;
}

div.header a.text {
    text-decoration: none;
    color: gray;
    padding: 20px;
    text-transform: capitalize;
    float: left;
    transition: 0.1s;
}

div.header a.text:hover {
    color: rgba(0, 0, 0, 0.7);
    background-color: rgba(0, 0, 0, 0.1);
}

div.header a.text.active {
    color: #ff5e00;
    border-bottom: solid #ff5e00;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE>
<html>
    <head>
        <title>Ant Arni's Crappy Site!</title>
        <link href="css/main.css" type="text/css" rel=stylesheet>
        <link href="https://fonts.googleapis.com/css?family=Asap" rel="stylesheet">
    </head>
    <body>
        <div class=header>
            Home
            Members
            Handbook
            Apply
            Staff
        </div>
    </body>
</html></code>```

答:
This is the easiest way. Add to active link:

```<code>margin: 0 0 -2px;
</code>```

* {
    font-family: 'Asap', sans-serif;
    margin: 0;
}

div.header {
    background-color: rgba(0, 0, 0, 0.1);
    position: absolute;
    width: 100%;
    border-bottom: solid rgba(0, 0, 0, 0.1) 2px;
}

div.header a.text {
    text-decoration: none;
    color: gray;
    padding: 20px;
    text-transform: capitalize;
    float: left;
    transition: 0.1s;
}

div.header a.text:hover {
    color: rgba(0, 0, 0, 0.7);
    background-color: rgba(0, 0, 0, 0.1);
}

div.header a.text.active {
    color: #ff5e00;
    border-bottom: solid #ff5e00;
    margin: 0 0 -2px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE>
<html>
    <head>
        <title>Ant Arni's Crappy Site!</title>
        <link href="css/main.css" type="text/css" rel=stylesheet>
        <link href="https://fonts.googleapis.com/css?family=Asap" rel="stylesheet">
    </head>
    <body>
        <div class=header>
            Home
            Members
            Handbook
            Apply
            Staff
        </div>
    </body>
</html></code>```

Body:
This is what it looks like at the moment:
I want to remove the gray border under the 'active' class element (i.e. the Home in this picture), while having the orange thicker bottom-border replace it. How do I go about doing that?

* {
    font-family: 'Asap', sans-serif;
    margin: 0;
}

div.header {
    background-color: rgba(0, 0, 0, 0.1);
    position: absolute;
    width: 100%;
    border-bottom: solid rgba(0, 0, 0, 0.1) 2px;
}

div.header a.text {
    text-decoration: none;
    color: gray;
    padding: 20px;
    text-transform: capitalize;
    float: left;
    transition: 0.1s;
}

div.header a.text:hover {
    color: rgba(0, 0, 0, 0.7);
    background-color: rgba(0, 0, 0, 0.1);
}

div.header a.text.active {
    color: #ff5e00;
    border-bottom: solid #ff5e00;

<!DOCTYPE>

        <title>Ant Arni's Crappy Site!</title>
        <link href="css/main.css" type="text/css" rel=stylesheet>
        <link href="https://fonts.googleapis.com/css?family=Asap" rel="stylesheet">

            Home
            Members
            Handbook
            Apply
            Staff

Body:
This is the easiest way. Add to active link:

margin: 0 0 -2px;

* {
    font-family: 'Asap', sans-serif;
    margin: 0;
}

div.header {
    background-color: rgba(0, 0, 0, 0.1);
    position: absolute;
    width: 100%;
    border-bottom: solid rgba(0, 0, 0, 0.1) 2px;
}

div.header a.text {
    text-decoration: none;
    color: gray;
    padding: 20px;
    text-transform: capitalize;
    float: left;
    transition: 0.1s;
}

div.header a.text:hover {
    color: rgba(0, 0, 0, 0.7);
    background-color: rgba(0, 0, 0, 0.1);
}

div.header a.text.active {
    color: #ff5e00;
    border-bottom: solid #ff5e00;
    margin: 0 0 -2px;
}

<!DOCTYPE>
<html>
    <head>
        <title>Ant Arni's Crappy Site!</title>
        <link href="css/main.css" type="text/css" rel=stylesheet>
        <link href="https://fonts.googleapis.com/css?family=Asap" rel="stylesheet">
    </head>
    <body>
        <div class=header>
            <a href=# class="text active">Home</a>
            <a href=# class=text>Members</a>
            <a href=# class=text>Handbook</a>
            <a href=# class=text>Apply</a>
            <a href=# class=text>Staff</a>
        </div>
    </body>
</html>


问:
How to check whether id value is already present in array of objects?
I am trying to check whether an object with a certain id property is already present in the array:

```<code>var items  =[{id:1,name:'ted'},{id:2,name:'john'}]
</code>```

How can I do this with jquery or vanilla js in a compact way? I know I can just create a for loop but is there anything else you can use?

答:
Use array.prototype.some:

var items  =[{id:1,name:'ted'},{id:2,name:'john'},{id:3, name:'tod'}];
var id = 2;
var exists = items.some(item => item.id === id)
console.log(exists);```

Body:
I am trying to check whether an object with a certain id property is already present in the array:

var items  =[{id:1,name:'ted'},{id:2,name:'john'}]

How can I do this with jquery or vanilla js in a compact way? I know I can just create a for loop but is there anything else you can use?


问:
Why did mysql data ownership change to systemd-journal-remote after running a docker container
I have the mysql database stored in /home/mysql instead of /var/lib/mysql. The directory used to be owned by mysql. However, when I run the command docker-compose up with this yml file:

```<code>version: '3'
services:
  mariadb:
    image: mariadb
    restart: always
    volumes:
     - /home/mysql:/var/lib/mysql
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:5.6.4
    environment:
      - "ES_JAVA_OPTS=-Xms750m -Xmx750m"
      - bootstrap.memory_lock=false
  site:
    build: .
    volumes:
      - "./app:/app"
    links:
      - mariadb:mysql
    environment:
      - DOCKER_IP=172.19.0.2
    depends_on: ['elasticsearch','mariadb']
    ports:
      - "3000:3000"
</code>```

The docker container is able to run, but the entire folder and files in /home/mysql are owned by systemd-journal-remote, which causes the node server fails to connect to mariadb. I have to stop the docker instance, restore the mysql folder ownership and delete ib_logfile0 and ib_logfile1.

Why does mounting /home/mysql cause such a fatal problem?

Update:

My solution is to add user: "mysql":

```<code>version: '3'
services:
  mariadb:
    image: mariadb
    restart: always
    volumes:
     - /home/mysql:/var/lib/mysql
    user: "mysql"
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:5.6.4
    environment:
      - "ES_JAVA_OPTS=-Xms750m -Xmx750m"
      - bootstrap.memory_lock=false
  site:
    build: .
    volumes:
      - "./app:/app"
    links:
      - mariadb:mysql
    environment:
      - DOCKER_IP=172.19.0.2
    depends_on: ['elasticsearch','mariadb']
    ports:
      - "3000:3000"
</code>```

答: You should start Docker's container with --user parameter. If you do this and set the same uid:gid as owner of the MySQL storage you will no have problems with permissions. You have to check how exactly to do this in Docker Compose because I show you example for normal command line execution

Body:
I have the mysql database stored in /home/mysql instead of /var/lib/mysql. The directory used to be owned by mysql. However, when I run the command docker-compose up with this yml file:

version: '3'
services:
  mariadb:
    image: mariadb
    restart: always
    volumes:
     - /home/mysql:/var/lib/mysql
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:5.6.4
    environment:
      - "ES_JAVA_OPTS=-Xms750m -Xmx750m"
      - bootstrap.memory_lock=false
  site:
    build: .
    volumes:
      - "./app:/app"
    links:
      - mariadb:mysql
    environment:
      - DOCKER_IP=172.19.0.2
    depends_on: ['elasticsearch','mariadb']
    ports:
      - "3000:3000"

The docker container is able to run, but the entire folder and files in /home/mysql are owned by systemd-journal-remote, which causes the node server fails to connect to mariadb. I have to stop the docker instance, restore the mysql folder ownership and delete ib_logfile0 and ib_logfile1.

Why does mounting /home/mysql cause such a fatal problem?

Update:

My solution is to add user: "mysql":

version: '3'
services:
  mariadb:
    image: mariadb
    restart: always
    volumes:
     - /home/mysql:/var/lib/mysql
    user: "mysql"
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:5.6.4
    environment:
      - "ES_JAVA_OPTS=-Xms750m -Xmx750m"
      - bootstrap.memory_lock=false
  site:
    build: .
    volumes:
      - "./app:/app"
    links:
      - mariadb:mysql
    environment:
      - DOCKER_IP=172.19.0.2
    depends_on: ['elasticsearch','mariadb']
    ports:
      - "3000:3000"


问:
Read dead tuples data
Is it possible to read the dead tuples from a table using xmin or xmax column or by changing any catalog parameters? Is there any way to read the old data which was updated?

Thanks in Advance

答:
There is a hidden debugging variable --
I'm not going to post it here, because I believe that it's dangerous.

Google: greenplum+show+deleted

It's only good until VACUUM, after which those tuples are deleted.

This debugging GUC is for viewing only -- if  you mess with the xmin, xmax, ctid, ... trying to undelete something, you are certainly going to cause corruption.

You can, however, export those rows without the hidden columns, then re-import.

Title: Read dead tuples data


问:
Dynamically instantiate multiple copies of a MC
I have aa question re:AS 3. I made a Post-It note movie clip that is draggable. I want to create a whole pad of notes, or at least simulate this. I thought the best way to do this would be to add another Post-It whenever the startDrag() is triggered.

I first tried creating the Post-It with symbols but didn't think I could dynamically create new ones this way. I then created a class and added it to the stage:

...
addChild(new PostItNote());

But I wasn't able to (or don't know how) to set the x, y position on the stage.

Anyone have suggestions on the best way to accomplish this or even another way altogether?

EDIT:

```<code>package  {

 import flash.display.MovieClip;
 import flash.display.Sprite;
 import flash.events.MouseEvent;
 import flash.events.Event;
 import flash.text.TextField;
 import flash.media.Sound;
 import flash.media.SoundChannel;
 import flash.text.TextFormat;

 public class CoinHitTest extends MovieClip {

  var count:Number = 0;
  var total_count:TextField;
  var hitting:Boolean = false;
  var coinSnd:Sound = new coin_drop();
  var myMoney:TextFormat = new TextFormat();
  var noteStack:Vector.<PostItNotes> = new Vector.<PostItNotes>();

public function CoinHitTest(){
    for(var $i:int = 0; $i <5;$i++)
{
    var newPostIt:PostItNotes = new PostItNotes();
    this.addChild(newPostIt);
    this.noteStack.push(newPostIt);
}
// constructor code
   coin.addEventListener(MouseEvent.MOUSE_DOWN, __handleCoinDown);
   coin.addEventListener(MouseEvent.MOUSE_UP, __handleCoinUp);

   total_count = new TextField();
   total_count.x = 795.20;
   total_count.y = 506.15;
   total_count.mouseEnabled = false;

   myMoney.size = 28;
   total_count.defaultTextFormat = myMoney;
   total_count.text = String("$" + count);
   addChild(total_count);
  }

  private function __handleCoinDown($evt:MouseEvent):void {

   coin.startDrag(true);
     coin.scaleX = 1.5;
     coin.scaleY = 1.5;
   addEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __handleCoinUp($evt:MouseEvent):void {
   coin.stopDrag();
     coin.scaleX = 1;
     coin.scaleY = 1;
   removeEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __checkHit($evt:Event):void {
    if (this.coffee.hitTestPoint(coin.x,coin.y, false))
    {
        // do our in-circle check
        if((coffee.x - coin.x) * 2 + (coffee.y - coin.y) * 2 <= (coffee.width/2 + coin.width/2) * 2)
        {
            stopDrag();
            coin.scaleX = 1;
     coin.scaleY = 1;
            removeChild(coin);
            coin.x = 116;
     coin.y = 380.1;
      addChild(coin);

        }
    }
    else
    {
        trace("Didn't Hit Mug");
    }
   if (this.coin.hitTestObject(target)) {
     if (!hitting) {
         coinSnd.play();
     count++;
       total_count.text = String("$" + count);
       coin.stopDrag();

     removeChild(coin);
     hitting = !hitting;

     coin.x = 116;
     coin.y = 380.1;
      addChild(coin);
     coin.scaleX = 1;
     coin.scaleY = 1;

}
   } else {
    hitting = false;
   }
  }

   }
}
</code>```

EDIT:

```<code>package  {
    import flash.display.MovieClip;
public class PostItNotes extends Sprite{

        public function PostItNotes() {
            // constructor code
        }

    }

}
</code>```

答:
try creating a vector to hold references to your PostItNote objects...

Something like this:

```<code>var noteStack:Vector.<PostItNote> = new Vector.<PostItNote>();
for(var $i:int = 0; $i <5;$i++)
{
    var newPostIt:PostItNote = new PostItNote();
    this.addChild(newPostIt);
    this.noteStack.push(newPostIt);
}
</code>```

And then you can just refer to an element in the vector whenever you want to be able to modify the properties of the PostItNote (x/y/z/whatever)

```<code>this.noteStack[0].x = 24;
</code>```

Body:
I have aa question re:AS 3. I made a Post-It note movie clip that is draggable. I want to create a whole pad of notes, or at least simulate this. I thought the best way to do this would be to add another Post-It whenever the startDrag() is triggered.

I first tried creating the Post-It with symbols but didn't think I could dynamically create new ones this way. I then created a class and added it to the stage:

...
addChild(new PostItNote());

But I wasn't able to (or don't know how) to set the x, y position on the stage.

Anyone have suggestions on the best way to accomplish this or even another way altogether?

EDIT:

package  {

 import flash.display.MovieClip;
 import flash.display.Sprite;
 import flash.events.MouseEvent;
 import flash.events.Event;
 import flash.text.TextField;
 import flash.media.Sound;
 import flash.media.SoundChannel;
 import flash.text.TextFormat;

 public class CoinHitTest extends MovieClip {

  var count:Number = 0;
  var total_count:TextField;
  var hitting:Boolean = false;
  var coinSnd:Sound = new coin_drop();
  var myMoney:TextFormat = new TextFormat();
  var noteStack:Vector.<PostItNotes> = new Vector.<PostItNotes>();

public function CoinHitTest(){
    for(var $i:int = 0; $i <5;$i++)
{
    var newPostIt:PostItNotes = new PostItNotes();
    this.addChild(newPostIt);
    this.noteStack.push(newPostIt);
}
// constructor code
   coin.addEventListener(MouseEvent.MOUSE_DOWN, __handleCoinDown);
   coin.addEventListener(MouseEvent.MOUSE_UP, __handleCoinUp);

   total_count = new TextField();
   total_count.x = 795.20;
   total_count.y = 506.15;
   total_count.mouseEnabled = false;

   myMoney.size = 28;
   total_count.defaultTextFormat = myMoney;
   total_count.text = String("$" + count);
   addChild(total_count);
  }

  private function __handleCoinDown($evt:MouseEvent):void {

   coin.startDrag(true);
     coin.scaleX = 1.5;
     coin.scaleY = 1.5;
   addEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __handleCoinUp($evt:MouseEvent):void {
   coin.stopDrag();
     coin.scaleX = 1;
     coin.scaleY = 1;
   removeEventListener(Event.ENTER_FRAME, __checkHit);
  }

  private function __checkHit($evt:Event):void {
    if (this.coffee.hitTestPoint(coin.x,coin.y, false))
    {
        // do our in-circle check
        if((coffee.x - coin.x) * 2 + (coffee.y - coin.y) * 2 <= (coffee.width/2 + coin.width/2) * 2)
        {
            stopDrag();
            coin.scaleX = 1;
     coin.scaleY = 1;
            removeChild(coin);
            coin.x = 116;
     coin.y = 380.1;
      addChild(coin);

        }
    }
    else
    {
        trace("Didn't Hit Mug");
    }
   if (this.coin.hitTestObject(target)) {
     if (!hitting) {
         coinSnd.play();
     count++;
       total_count.text = String("$" + count);
       coin.stopDrag();

     removeChild(coin);
     hitting = !hitting;

     coin.x = 116;
     coin.y = 380.1;
      addChild(coin);
     coin.scaleX = 1;
     coin.scaleY = 1;

}
   } else {
    hitting = false;
   }
  }

   }
}

EDIT:

package  {
    import flash.display.MovieClip;
public class PostItNotes extends Sprite{

        public function PostItNotes() {
            // constructor code
        }

    }

}

Body:
try creating a vector to hold references to your PostItNote objects...

Something like this:

var noteStack:Vector.<PostItNote> = new Vector.<PostItNote>();
for(var $i:int = 0; $i <5;$i++)
{
    var newPostIt:PostItNote = new PostItNote();
    this.addChild(newPostIt);
    this.noteStack.push(newPostIt);
}

And then you can just refer to an element in the vector whenever you want to be able to modify the properties of the PostItNote (x/y/z/whatever)

this.noteStack[0].x = 24;


答:
Tags are not the best way to identify buttons, but I'll ignore that.

Don't use buttons, use UISwitches. Have a switch for each category.

Say you have a constant switchTagBase, with a value of 100:

```<code>let switchTagBase = 100
</code>```

So the switch for your first category has a tag of 100, the next one has a tag of 101, etc.

You already have an array of categories, which is good.

Now, when it's time to build your array of selected questions, simply go through the categories, figure out which switches are on, and add in those categories

```<code>var selectedCategories = [QuestionArray]()
for (index, array) in quizCategories.enumerated() {
  let thisTag = index + switchTagBase
  guard let thisSwitch = view.viewWithTag(thisTag),
    thisSwitch.isOn else { continue }
  selectedCategories += quizCategories[index]
}
</code>```

(Note that you should really maintain an array of selection states based on the switches the user activates, and iterate through that array rather than looping through the switches directly, but in the interest of brevity I fetched switch states directly.)

Title: How to concatenate arrays when button is selected

Body:
Tags are not the best way to identify buttons, but I'll ignore that.

Don't use buttons, use UISwitches. Have a switch for each category.

Say you have a constant switchTagBase, with a value of 100:

let switchTagBase = 100

So the switch for your first category has a tag of 100, the next one has a tag of 101, etc.

You already have an array of categories, which is good.

Now, when it's time to build your array of selected questions, simply go through the categories, figure out which switches are on, and add in those categories

var selectedCategories = [QuestionArray]()
for (index, array) in quizCategories.enumerated() {
  let thisTag = index + switchTagBase
  guard let thisSwitch = view.viewWithTag(thisTag),
    thisSwitch.isOn else { continue }
  selectedCategories += quizCategories[index]
}

(Note that you should really maintain an array of selection states based on the switches the user activates, and iterate through that array rather than looping through the switches directly, but in the interest of brevity I fetched switch states directly.)


问:
Android bitmap image size in XML
In my XML file, I'm using bitmap as the following

```<code><bitmap
    android:src="@drawable/Icon"
    android:gravity="center"/>
</code>```

Here the image width of the icon exceeds the screen.

I tried android:width="100dp" and all. But it isn't working.

Complete XML file:

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
      <shape android:shape="rectangle">
            <stroke android:width="3dp" android:color="@color/black" />
            <solid android:color="@color/bg_green" />
        </shape>
   </item>
   <item>
    <bitmap
        android:src="@drawable/Icon"
        android:gravity="center"/>
    </item>
</layer-list>
</code>```

How can I reduce the width and height of the above bitmap?

答:
Only API 23 or later

Just use

```<code><item
    android:width="200dp"
    android:height="200dp"
    android:drawable="@drawable/splash_background"
    android:gravity="center" />
</code>```

instead

```<code><item
    android:left="200dp"
    android:right="200dp">

    <bitmap
        android:src="@drawable/splash_background"
        android:gravity="center" />

</item>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Android bitmap image size in XML

Body:
In my XML file, I'm using bitmap as the following

<bitmap
    android:src="@drawable/Icon"
    android:gravity="center"/>

Here the image width of the icon exceeds the screen.

I tried android:width="100dp" and all. But it isn't working.

Complete XML file:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
      <shape android:shape="rectangle">
            <stroke android:width="3dp" android:color="@color/black" />
            <solid android:color="@color/bg_green" />
        </shape>
   </item>
   <item>
    <bitmap
        android:src="@drawable/Icon"
        android:gravity="center"/>
    </item>
</layer-list>

How can I reduce the width and height of the above bitmap?

Body:
Only API 23 or later

Just use

<item
    android:width="200dp"
    android:height="200dp"
    android:drawable="@drawable/splash_background"
    android:gravity="center" />

instead

<item
    android:left="200dp"
    android:right="200dp">

    <bitmap
        android:src="@drawable/splash_background"
        android:gravity="center" />

</item>


问:
EF Inheritance Identity 2 access trouble
I'm trying to get TPH model database inheritance from ApplicationUser:

```<code>public class Customer:ApplicationUser
    {
        public DateTime? AddeDateTime { get; set; }

        public int? DietLenght { get; set; }
        public int? ConsultationCount { get; set; }
        public int? PlannedWeight { get; set; }
        public int? Age { get; set; }
        public int? Height { get; set; }
</code>```

How to access those properties ? I tried:

```<code>var customerUser = await _context.Users.FirstOrDefaultAsync(x => x.Id == user.Id);
</code>```

but i got ApplicationUser. And ApplicationUser doesn't have the properties to set up, so i can't make it like that.

```<code>customerUser .ConsultationCount = model.ConsultationCount;
customerUser .DietLenght = model.DietLenght;
customerUser .Height = model.Height;
customerUser .Age = model.Age;
</code>```

I also tried:

```<code>var dataUser = user as Customer;
</code>```

but it didn't work either.

Need it to create new User in my app

```<code>if (ModelState.IsValid)
            {
                var currentlyLogInUser = _userManager.GetUserAsync(HttpContext.User).Result;
                var currentlyLogInUserId = currentlyLogInUser.Id;
                var user = new ApplicationUser
                {
                    UserName = model.Email,
                    Email = model.Email,
                    Name = model.Name,
                    Surname = model.Surname
                };
                var result = await _userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var resultRole = await _userManager.AddToRoleAsync(user, "Customers");
                    if (resultRole.Succeeded)
                    {
                        _logger.LogInformation("User created a new account with password.");

                            var customer = (Customer) user;
                            customer.DieticianId = currentlyLogInUserId;
                            customer.AddeDateTime = DateTime.Today;
                            customer.ConsultationCount = model.ConsultationCount;
                            customer.DietLenght = model.DietLenght;
                            customer.Height = model.Height;
                            customer.Age = model.Age;
                            _context.Users.Update(customer);
                            await _context.SaveChangesAsync();

                    }

                    return RedirectToLocal(returnUrl);
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View();
        }
</code>```

答:
The Users property of the context is a DbSet<ApplicationUser>, so it will only ever return ApplicationUser instances. You need a DbSet<Customer> to get back a Customer.

Alternatively, you can simply cast to the right type after the fact. The entity returned is still a Customer; it was simply upcast to ApplicationUser by the DbSet type-constraint. As a result you can do:

```<code>if (user is Customer)
{
    var customer = (Customer)user;
    // work with `customer`
}
</code>```

With C# 7's pattern matching you can simplify that to:

```<code>if (user is Customer customer)
{
    // work with `customer`
}
</code>```

Or if you have have multiple different user types, you can employ a switch statement with pattern matching:

```<code>switch (user)
{
    case Customer customer:
        // work with `customer`
        break;
    case AnotherUserType another:
        // work with `another`
        break;
    // etc.
}
</code>```

Body:
I'm trying to get TPH model database inheritance from ApplicationUser:

public class Customer:ApplicationUser
    {
        public DateTime? AddeDateTime { get; set; }

        public int? DietLenght { get; set; }
        public int? ConsultationCount { get; set; }
        public int? PlannedWeight { get; set; }
        public int? Age { get; set; }
        public int? Height { get; set; }

How to access those properties ? I tried:

var customerUser = await _context.Users.FirstOrDefaultAsync(x => x.Id == user.Id);

but i got ApplicationUser. And ApplicationUser doesn't have the properties to set up, so i can't make it like that.

customerUser .ConsultationCount = model.ConsultationCount;
customerUser .DietLenght = model.DietLenght;
customerUser .Height = model.Height;
customerUser .Age = model.Age;

I also tried:

var dataUser = user as Customer;

but it didn't work either.

Need it to create new User in my app

if (ModelState.IsValid)
            {
                var currentlyLogInUser = _userManager.GetUserAsync(HttpContext.User).Result;
                var currentlyLogInUserId = currentlyLogInUser.Id;
                var user = new ApplicationUser
                {
                    UserName = model.Email,
                    Email = model.Email,
                    Name = model.Name,
                    Surname = model.Surname
                };
                var result = await _userManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    var resultRole = await _userManager.AddToRoleAsync(user, "Customers");
                    if (resultRole.Succeeded)
                    {
                        _logger.LogInformation("User created a new account with password.");

                            var customer = (Customer) user;
                            customer.DieticianId = currentlyLogInUserId;
                            customer.AddeDateTime = DateTime.Today;
                            customer.ConsultationCount = model.ConsultationCount;
                            customer.DietLenght = model.DietLenght;
                            customer.Height = model.Height;
                            customer.Age = model.Age;
                            _context.Users.Update(customer);
                            await _context.SaveChangesAsync();

                    }

                    return RedirectToLocal(returnUrl);
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return View();
        }

Body:
The Users property of the context is a DbSet<ApplicationUser>, so it will only ever return ApplicationUser instances. You need a DbSet<Customer> to get back a Customer.

Alternatively, you can simply cast to the right type after the fact. The entity returned is still a Customer; it was simply upcast to ApplicationUser by the DbSet type-constraint. As a result you can do:

if (user is Customer)
{
    var customer = (Customer)user;
    // work with `customer`
}

With C# 7's pattern matching you can simplify that to:

if (user is Customer customer)
{
    // work with `customer`
}

Or if you have have multiple different user types, you can employ a switch statement with pattern matching:

switch (user)
{
    case Customer customer:
        // work with `customer`
        break;
    case AnotherUserType another:
        // work with `another`
        break;
    // etc.
}


问:
Apply drop caps to each word in a link
I'd like to recreate the menu effect seen at http://www.thedecoratorsource.co.uk using CSS fonts and drop caps.

I know that I can use

```<code>p.introduction:first-letter {
font-size : 300%;
}
</code>```

which will give me the first word with a larger first characerer but I want to apply it to each word. I'm guessing there isn't a way to do this with CSS(3). Would my best bet with javascript? I've already got Moo on the page so this would be my preferred method.

I don't want to add extra HTML to my links to achieve this.

Thanks

答:
Why not try this in your menu:</p>

```<code>li {text-transform: uppercase;}
li:first-letter { font-size:150%; }
</code>```

Title: Apply drop caps to each word in a link

Body:
I'd like to recreate the menu effect seen at http://www.thedecoratorsource.co.uk using CSS fonts and drop caps.

I know that I can use

p.introduction:first-letter {
font-size : 300%;
}

which will give me the first word with a larger first characerer but I want to apply it to each word. I'm guessing there isn't a way to do this with CSS(3). Would my best bet with javascript? I've already got Moo on the page so this would be my preferred method.

I don't want to add extra HTML to my links to achieve this.

Thanks

Body:
Why not try this in your menu:

li {text-transform: uppercase;}
li:first-letter { font-size:150%; }


问:
Could not access pidfile for Cassandra
I were working with cassandra with no problem last hour ,but now I can't access to cassandra when I ran cqlsh it gave me this:

```<code>Connection error: Could not connect to localhost:9160
</code>```

So I tried this:

```<code>sudo service cassandra status
</code>```

And it gave me this:

xss =  -ea -javaagent:/usr/share/cassandra/lib/jamm-0.2.5.jar -XX:+UseThreadPriorities -
  XX:ThreadPriorityPolicy=42 -Xms1024M -Xmx1024M -Xmn200M -XX:+HeapDumpOnOutOfMemoryError -Xss256k

could not access pidfile for Cassandra

what can I do to resolve this problem?

Thanks in advance,

答:
I encountered the same issue. I was doing some testing, and when I abruptly shut down the system and rebooted, I got this error when I tried checking Cassandra's status.

The pid file has the process ID of Cassandra's service that was running before shut down. This happens when Cassandra is not stopped properly.
So, I force killed the zombie process this way and started cassandra again.

```<code>kill -9 `ps -ef | grep cassandra | grep -v grep | awk {'print $2'}`
service cassandra start
</code>```

Hope its helpful!

Title: Could not access pidfile for Cassandra

Body:
I were working with cassandra with no problem last hour ,but now I can't access to cassandra when I ran cqlsh it gave me this:

Connection error: Could not connect to localhost:9160

So I tried this:

sudo service cassandra status

And it gave me this:

xss =  -ea -javaagent:/usr/share/cassandra/lib/jamm-0.2.5.jar -XX:+UseThreadPriorities -
  XX:ThreadPriorityPolicy=42 -Xms1024M -Xmx1024M -Xmn200M -XX:+HeapDumpOnOutOfMemoryError -Xss256k

could not access pidfile for Cassandra

what can I do to resolve this problem?

Thanks in advance,

Body:
I encountered the same issue. I was doing some testing, and when I abruptly shut down the system and rebooted, I got this error when I tried checking Cassandra's status.

The pid file has the process ID of Cassandra's service that was running before shut down. This happens when Cassandra is not stopped properly.
So, I force killed the zombie process this way and started cassandra again.

kill -9 `ps -ef | grep cassandra | grep -v grep | awk {'print $2'}`
service cassandra start

Hope its helpful!


问:
Auto scrolling of cursor on the R studio console
When I execute my codes on the R console, you expect your codes to be executed and cursor to move on the very next line.

However, when I try and read a data in R, the cursor skips the very next line and jumps to the line after that.

The cursor keeps moving down automatically even if no codes are executed.

I cannot understand the reason for it. Posting two images to explain the same.

This is how it looks like on R console:

答:
After a lot of research and experimentation, I discovered the bug to exist in the command file.choose which causes the addition of trailing spaces at regular intervals. Please try the same and validate my findings.

```<code>data<-file.choose()
</code>```

Body:
After a lot of research and experimentation, I discovered the bug to exist in the command file.choose which causes the addition of trailing spaces at regular intervals. Please try the same and validate my findings.

data<-file.choose()


问:
Images load on each other masonry-filter
```<code>$('.item-filter').on('click', 'a', function(e) {
    e.preventDefault();
    var selector = $(this).data('filter');
    $(".item-filter a").removeClass("active");
    $(this).addClass("active");

     $(".item").not(selector).hide ();
     $('.masonry-list').masonry();
     $(selector).show ()
};
</code>```

<p>Images load over each other..
it doesnt load it when i do not click it twice
..  dualgroup.org/arcadis/projects.html here u can check it
just the first time when u filter it loads the images right . without click it twice it doesnt load ?? </p>

答:
i have figured it out<br>
I have change the javascript code to this </p>

```<code>    /*-- MASONRY --*/
var getMasonry = $('.masonry-list');
getMasonry.imagesLoaded(function () {
    getMasonry.masonry({
        itemSelector: '.grid-sizer',

        columnWidth: '.grid-sizer',
        isAnimated: true
</code>```

Body:
$('.item-filter').on('click', 'a', function(e) {
    e.preventDefault();
    var selector = $(this).data('filter');
    $(".item-filter a").removeClass("active");
    $(this).addClass("active");

     $(".item").not(selector).hide ();
     $('.masonry-list').masonry();
     $(selector).show ()
};

Images load over each other..
it doesnt load it when i do not click it twice
..  dualgroup.org/arcadis/projects.html here u can check it
just the first time when u filter it loads the images right . without click it twice it doesnt load ??

Body:
i have figured it out

I have change the javascript code to this

    /*-- MASONRY --*/
var getMasonry = $('.masonry-list');
getMasonry.imagesLoaded(function () {
    getMasonry.masonry({
        itemSelector: '.grid-sizer',

        columnWidth: '.grid-sizer',
        isAnimated: true


问:
Android EditText with different floating label and placeholder
How can i create an editText that looks like this?

答:
You can use following code (in kotlin). It will show placeholder after 200 ms delay (to avoid overlapping hint and placeholder).

```<code>class PlaceholderEditText : TextInputEditText {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    private val placeholder = hint

    init {
        hint = ""
        onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                postDelayed({ hint = placeholder }, 200)
            } else {
                hint = ""
            }
        }
    }
}
</code>```

and then in layout xml class:

```<code>    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="ALWAYS VISIBLE LABEL">

        <com.myapp.widget.PlaceholderEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="DISAPPEARING PLACEHOLDER" />

    </android.support.design.widget.TextInputLayout>
</code>```

Body:
You can use following code (in kotlin). It will show placeholder after 200 ms delay (to avoid overlapping hint and placeholder).

class PlaceholderEditText : TextInputEditText {

    constructor(context: Context) : super(context)
    constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr)

    private val placeholder = hint

    init {
        hint = ""
        onFocusChangeListener = OnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                postDelayed({ hint = placeholder }, 200)
            } else {
                hint = ""
            }
        }
    }
}

and then in layout xml class:

    <android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="ALWAYS VISIBLE LABEL">

        <com.myapp.widget.PlaceholderEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="DISAPPEARING PLACEHOLDER" />

    </android.support.design.widget.TextInputLayout>


问:
Differences between Stacked inline and Tabular inline
This is my models.py file

  from django.db import models

```<code># Create your models here.
class Item(models.Model):
    name=models.CharField(max_length=250)
    description = model.TextField()

    class Meta:
        oredering['name']
    def __unicode__(self):
        return self.name
    @permalink
    def get_absolute_url:
        retun ('item_detail',None,{'object_id':self_id})
class Photo(models.Model):
    item = models.ForiegnKey(Item)
    title=models.ChaField(max_length=250)

    image=models.IMageField(upload_to='photos')
    caption=models.TextField(blank=True)

    class Meta:
        ordering=['title']
    def __unicode__(self):
        return self.title
    @permalink
    def get_absolute_url(self):
        retun ('photo_detail',None,{'object_id':self_id})
</code>```

And this is my admin.py :

```<code>from django.contrib import admin
from  models import Item
from  models import Photo

# Register your models here.
class PhotoInline(admin.StackedInline):
    model = Photo

class ItemAdmin(admin.ModelAdmin):
    inlines = [PhotoInline]

admin.site.register(Item, ItemAdmin)
admin.site.register(Photo)
</code>```

But, I can't understand what is StackedInline and TabularInline, I referred to Django documentation but still couldn't understand what exactly it was.

Also, I can't see those models in my admin panel when I started the server, I don't understand why my models aren't registered on my admin page.

答:
I see two different questions:

I cant understand what is stacked inline and tabular inline

Basically, both allow you to edit models on the same page as a parent model. In other words, it is sometimes preferable for a user to have the possibility to edit a certain model while editing another one instead of having to manually add another instance somewhere else in your interface. In your particular case, you can use it to facilitate user experience by allowing the user to add photos linked to a parent item simultaneously whitout having to constantly change between your admin forms.

Now, the difference between the two is really simple to understand: Layout. Indeed, both works exactly the same behind the scenes, the only difference is the template used for rendering. It can be seen here in the source code. So, picking one for your project is only a matter of preference regarding the interface layout

I cant see those models in my admin panel

This can be a lot of things, but often it's because you forgot to run your migrations with makemigrations and migrate. If you did, another thing that a lot of users forget is to install their app. So, in

Setting.py

```<code>INSTALLED_APPS = ['Myproject.apps.Myapp']
</code>```

Body:
This is my models.py file

  from django.db import models

# Create your models here.
class Item(models.Model):
    name=models.CharField(max_length=250)
    description = model.TextField()

    class Meta:
        oredering['name']
    def __unicode__(self):
        return self.name
    @permalink
    def get_absolute_url:
        retun ('item_detail',None,{'object_id':self_id})
class Photo(models.Model):
    item = models.ForiegnKey(Item)
    title=models.ChaField(max_length=250)

    image=models.IMageField(upload_to='photos')
    caption=models.TextField(blank=True)

    class Meta:
        ordering=['title']
    def __unicode__(self):
        return self.title
    @permalink
    def get_absolute_url(self):
        retun ('photo_detail',None,{'object_id':self_id})

And this is my admin.py :

from django.contrib import admin
from  models import Item
from  models import Photo

# Register your models here.
class PhotoInline(admin.StackedInline):
    model = Photo

class ItemAdmin(admin.ModelAdmin):
    inlines = [PhotoInline]

admin.site.register(Item, ItemAdmin)
admin.site.register(Photo)

But, I can't understand what is StackedInline and TabularInline, I referred to Django documentation but still couldn't understand what exactly it was.

Also, I can't see those models in my admin panel when I started the server, I don't understand why my models aren't registered on my admin page.

Body:
I see two different questions:

I cant understand what is stacked inline and tabular inline

Basically, both allow you to edit models on the same page as a parent model. In other words, it is sometimes preferable for a user to have the possibility to edit a certain model while editing another one instead of having to manually add another instance somewhere else in your interface. In your particular case, you can use it to facilitate user experience by allowing the user to add photos linked to a parent item simultaneously whitout having to constantly change between your admin forms.

Now, the difference between the two is really simple to understand: Layout. Indeed, both works exactly the same behind the scenes, the only difference is the template used for rendering. It can be seen here in the source code. So, picking one for your project is only a matter of preference regarding the interface layout

I cant see those models in my admin panel

This can be a lot of things, but often it's because you forgot to run your migrations with makemigrations and migrate. If you did, another thing that a lot of users forget is to install their app. So, in

Setting.py

INSTALLED_APPS = ['Myproject.apps.Myapp']


问:
What is the difference between dictionary(Of String, String) and IDictionary(Of String, String)
Can I do anything more or less with IDictionary? How do these two collections differ?</p>

答:
I think everyone has already pointed out that IDictionary(Of String, String) is an interface that cannot be instantiated as an object and that Dictionary(Of String, String) is a class that can be instantiated as an object.  However, it's important to know why you might use one versus another.

Let's say you are going to define a method to search a dictionary and return the value associated with the key; if you don't find a value, you want to return an emtpy string.  You need a dictionary, so you decide to go ahead and use .NET's Dictionary class for your implementation:

```<code>Function GetValueFromKey(ByVal dict As Dictionary(Of String, String),
                         ByVal key As String) As String
    If ''//you find the value in the dictionary
         return theValue
    Else ''//you can't find the value in the ditionary
         return String.Empty
    End If
End Function
</code>```

You implement the code and your method is working great.  However, after a few months, you notice that your program is starting to slow down.  As you dig deep into the problem, you realize that .NET's implementation of Dictionary isn't ideal when your key data is 50,000 characters in length (NOTE: I honestly don't know if there are any real issues with .NET's Dictionary implementation; this is just an example), and all of your key strings are over 50,000 characters in length.

So now you have to figure out a new way of looking up the data without using .NET's Dictionary class.  You're going to have to use a new data type and then everywhere in your code that you have GetValueFromKey(...), you're going to have to make modifications to use the new datatype.  This isn't the end of the world, but maybe there's a better way.

When you first coded your GetValueFromKey method, you might have thought "I need to retrieve a value from a dictionary.  It doesn't matter what kind of dictionary it is, but I need to get the value out of it."  In that case, you could choose to use the IDictionary interface like so:

```<code>Function GetValueFromKey(ByVal dict As IDictionary(Of String, String),
                         ByVal key As String) As String
    If ''//you find the value in the dictionary
         return theValue
    Else ''//you can't find the value in the ditionary
         return String.Empty
    End If
End Function
</code>```

Everything about that function looks the same except that Dictionary was changed to IDictionary?  Did your implementation of the function change? No.  IDictionary is simply a contract that defines the properties and methods a dictionary needs to have.  All your function cares about is calling the properties and methods of dictionaries.  Your function doesn't care how it is implemented.

In this way, if you had programmed to an IDictionary interface instead of to a Dictionary implementation, when your program slowed down and you were forced to change your implementation of your dictionary, you could have simply written your own dictionary class that implements IDictionary.  As long as your new class follows the contract specified in IDictionary, none of your other code needs to change in order to deal with the new dictionary class that you created.

The design principle "Program to an interface and not to an implementation" helps you to deal with change.  If you start to learn how to use interfaces in your code, you'll be better prepared to deal with change.

Body:
I think everyone has already pointed out that IDictionary(Of String, String) is an interface that cannot be instantiated as an object and that Dictionary(Of String, String) is a class that can be instantiated as an object.  However, it's important to know why you might use one versus another.

Let's say you are going to define a method to search a dictionary and return the value associated with the key; if you don't find a value, you want to return an emtpy string.  You need a dictionary, so you decide to go ahead and use .NET's Dictionary class for your implementation:

Function GetValueFromKey(ByVal dict As Dictionary(Of String, String),
                         ByVal key As String) As String
    If ''//you find the value in the dictionary
         return theValue
    Else ''//you can't find the value in the ditionary
         return String.Empty
    End If
End Function

You implement the code and your method is working great.  However, after a few months, you notice that your program is starting to slow down.  As you dig deep into the problem, you realize that .NET's implementation of Dictionary isn't ideal when your key data is 50,000 characters in length (NOTE: I honestly don't know if there are any real issues with .NET's Dictionary implementation; this is just an example), and all of your key strings are over 50,000 characters in length.

So now you have to figure out a new way of looking up the data without using .NET's Dictionary class.  You're going to have to use a new data type and then everywhere in your code that you have GetValueFromKey(...), you're going to have to make modifications to use the new datatype.  This isn't the end of the world, but maybe there's a better way.

When you first coded your GetValueFromKey method, you might have thought "I need to retrieve a value from a dictionary.  It doesn't matter what kind of dictionary it is, but I need to get the value out of it."  In that case, you could choose to use the IDictionary interface like so:

Function GetValueFromKey(ByVal dict As IDictionary(Of String, String),
                         ByVal key As String) As String
    If ''//you find the value in the dictionary
         return theValue
    Else ''//you can't find the value in the ditionary
         return String.Empty
    End If
End Function

Everything about that function looks the same except that Dictionary was changed to IDictionary?  Did your implementation of the function change? No.  IDictionary is simply a contract that defines the properties and methods a dictionary needs to have.  All your function cares about is calling the properties and methods of dictionaries.  Your function doesn't care how it is implemented.

In this way, if you had programmed to an IDictionary interface instead of to a Dictionary implementation, when your program slowed down and you were forced to change your implementation of your dictionary, you could have simply written your own dictionary class that implements IDictionary.  As long as your new class follows the contract specified in IDictionary, none of your other code needs to change in order to deal with the new dictionary class that you created.

The design principle "Program to an interface and not to an implementation" helps you to deal with change.  If you start to learn how to use interfaces in your code, you'll be better prepared to deal with change.


问:
PHP error reporting destination: error log file vs. web page
In the following code, I get the 'AAA' on the web page output (only), while the 'BBB' goes to the error.log file (only).
I want both to go to the error.log file, so the user doesn't see potential errors while I do. How?

```<code><?php
ini_set('display_errors','1');
ini_set('error_log','error.log');
error_reporting(-1); // all
trigger_error('AAA');
error_log('BBB');
?>
</code>```

(Note: This is similar to http://stackoverflow.com/questions/9921643/how-to-make-provoke-an-php-error-in-php-error-log but not the same.)

答:
Set ini_set('display_errors', 0);

OR

Create your own error handler function and add it before calling trigger_error function with set_error_handler function.

This function can be used for defining your own way of handling errors
  during runtime, for example in applications in which you need to do
  cleanup of data/files when a critical error happens, or when you need
  to trigger an error under certain conditions (using trigger_error()).

Body:
In the following code, I get the 'AAA' on the web page output (only), while the 'BBB' goes to the error.log file (only).
I want both to go to the error.log file, so the user doesn't see potential errors while I do. How?

<?php
ini_set('display_errors','1');
ini_set('error_log','error.log');
error_reporting(-1); // all
trigger_error('AAA');
error_log('BBB');
?>

(Note: This is similar to http://stackoverflow.com/questions/9921643/how-to-make-provoke-an-php-error-in-php-error-log but not the same.)


问:
Formula to convert Local coordinates to world coordinates
Can someone give me the formula?
I have a vector3d which represents the position of a vertex in local coordinates, I have a Matrix3d that represents the rotation and position of the object which this vertex is part of it's geometry, how do I convert the local position of this vertex to the coordinates of the world?</p>

答:
now it's working, I had a problem with keeping the original vertex3d, and I played with the order and this is working, thank you very much, here is the code, I did have to use m2.invert(); here is the code:

```<code>var m3d:Matrix3D = new Matrix3D();
obj.Transform.copyToMatrix3D(m3d);
var m2:Matrix3D = new Matrix3D();
m2.append(m3d);
m2.invert();
m2.prependTranslation(obj.BoundingBox[i].x,obj.BoundingBox[i].y,obj.BoundingBox[i].z);
obj.BoundingBox[i] = new Vector3D(m2.position.x,m2.position.y,m2.position.z);
</code>```

in fact as I did it in the first place was also OK:

```<code>var m3d:Matrix3D = new Matrix3D();
obj.Transform.copyToMatrix3D(m3d);
m3d.invert();
obj.BoundingBox[i] = m3d.transformVector(obj.BoundingBox[i]);
</code>```

The only thing I was missing was the invert(); and I wish I knew what it is for...
Some people told me I have to append (or prepend) the object matrix and then the world matrix, which makes sense, but adding the world matrix only caused me problems,  while the invert(); made it good, but why?

Vesper, you are the one suggested it, thanks but why?

I know why, someone experienced gave me the answer: the camera shows everything mirrored, when you go left the world seems to be moving right, so you need to invert.

Body:
now it's working, I had a problem with keeping the original vertex3d, and I played with the order and this is working, thank you very much, here is the code, I did have to use m2.invert(); here is the code:

var m3d:Matrix3D = new Matrix3D();
obj.Transform.copyToMatrix3D(m3d);
var m2:Matrix3D = new Matrix3D();
m2.append(m3d);
m2.invert();
m2.prependTranslation(obj.BoundingBox[i].x,obj.BoundingBox[i].y,obj.BoundingBox[i].z);
obj.BoundingBox[i] = new Vector3D(m2.position.x,m2.position.y,m2.position.z);

in fact as I did it in the first place was also OK:

var m3d:Matrix3D = new Matrix3D();
obj.Transform.copyToMatrix3D(m3d);
m3d.invert();
obj.BoundingBox[i] = m3d.transformVector(obj.BoundingBox[i]);

The only thing I was missing was the invert(); and I wish I knew what it is for...
Some people told me I have to append (or prepend) the object matrix and then the world matrix, which makes sense, but adding the world matrix only caused me problems,  while the invert(); made it good, but why?

Vesper, you are the one suggested it, thanks but why?

I know why, someone experienced gave me the answer: the camera shows everything mirrored, when you go left the world seems to be moving right, so you need to invert.


问:
How to concatenate arrays when button is selected
So I'm working on a quiz-app and I want to give the user an option screen before starting the quiz, where the user can choose which categories the quiz should have.

Its currently only working with 1 category at a time but I want to be able to concatenate the questionArrays when the user selects button in the option screen.

At this time the user selects a button and depending on the sender.tag an Int gets passed through the var called 'pickedCategory' which then decides which of the arrays to base the questions on. This happens in the prepare for segue:

```<code>    let selectedCategory = quizCategories[pickedCategory]
    secondVC.allQuestions = selectedCategory.questions
</code>```

quizCategories is declared at the top:

```<code>    var quizCategories = [QuestionArray]()
</code>```

What I would like to do is have 4 buttons and whenever one is selected, concatenate an array to the selectedCategory

For instance, button 1 & 2 is selected, i.e. the user wants to have questions based on 2 categories. Resulting in something like this?

```<code>let selectedCategory = quizCategories[0].questions + quizCategories[1].questions
</code>```

and if 3 buttons selected, add another quizCategories array to the final array etc etc

Please note, its not HOW to concatenate I'm looking for, its how to automatically do this depending on buttons selected..

This is my first question posted and I am very new to Swift.. hope I didn't confuse u guys.. thanks  :)

答:
What I would suggest is for each category button, keep track of which is selected (and even deselected if the user decides they don't want that category), by adding or removing from an array of categoryIDs. Then, once the "Done" button (or whatever final decision button is tapped), take the array of categoryIDs they selected, and flatMap over them to produce the ultimate array of questions.

let questions = categoryIDs.flatMap { quizCategories[$0].questions }

Now, you'd have your array of questions to present to the user. Use flatMap vs map, because you'd want to flatten the returned array of arrays into a single array.

Body:
So I'm working on a quiz-app and I want to give the user an option screen before starting the quiz, where the user can choose which categories the quiz should have.

Its currently only working with 1 category at a time but I want to be able to concatenate the questionArrays when the user selects button in the option screen.

At this time the user selects a button and depending on the sender.tag an Int gets passed through the var called 'pickedCategory' which then decides which of the arrays to base the questions on. This happens in the prepare for segue:

    let selectedCategory = quizCategories[pickedCategory]
    secondVC.allQuestions = selectedCategory.questions

quizCategories is declared at the top:

    var quizCategories = [QuestionArray]()

What I would like to do is have 4 buttons and whenever one is selected, concatenate an array to the selectedCategory

For instance, button 1 & 2 is selected, i.e. the user wants to have questions based on 2 categories. Resulting in something like this?

let selectedCategory = quizCategories[0].questions + quizCategories[1].questions

and if 3 buttons selected, add another quizCategories array to the final array etc etc

Please note, its not HOW to concatenate I'm looking for, its how to automatically do this depending on buttons selected..

This is my first question posted and I am very new to Swift.. hope I didn't confuse u guys.. thanks  :)


问:
c++ language oops
Why do we declare constructor's as public?

答:
In the below code line, initialization should take place via constructor. If the constructor is private in this case, how is it going to be accessed outside the class scope. Moreover, foo::foo(int num) is going to be called by default while instantiation of obj.

```<code>foo *obj = new foo(5);
</code>```

Title: c++ language oops

Body:
In the below code line, initialization should take place via constructor. If the constructor is private in this case, how is it going to be accessed outside the class scope. Moreover, foo::foo(int num) is going to be called by default while instantiation of obj.

foo *obj = new foo(5);


问:
Zxing lib. does not work above Android M
I have successfully integrated zxing core.jar library below android Marshmallow, but while integrating this into above Marshmallow, it gives me following error:

```<code>android.content.ActivityNotFoundException: NO activity found to handle
intent{act=com.google.zxing.client.android.SCAN}
</code>```

Thanks in advance.

答: I think the problem may be in runtime permission of Camera. Try to give an access it to your app in code or manually</p>

Body:
I have successfully integrated zxing core.jar library below android Marshmallow, but while integrating this into above Marshmallow, it gives me following error:

android.content.ActivityNotFoundException: NO activity found to handle
intent{act=com.google.zxing.client.android.SCAN}

Thanks in advance.