问:
Change kubernetes stroge class mounted value from another pod
I want to publish sonarqube with kubernetes. I did successfully with official packages. But i want to use some plugins old version and some custom plugins. In local with docker-compose files, i created a fly-away container that fills the plugins directory(/opt/sonarqube/extensions/plugins) with plugins. And use that volume with sonarqube container. As a conclusion : Sonarqube extensions volume directory is created (or filled) from different container(do the job and die).

I want to use the same path with kubernetes but couldn't do that. My flyaway container didn't fill the path.

My kubernetes deployments files:

1-) sonar-pvc-extensions.yml

```<code>kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: claim-sonar-extensions
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 8Gi
</code>```

2-) sonarqube-deployment.yml

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: sonarqube
spec:
  replicas: 1
  selector:
    matchLabels:
      name: sonarqube
  template:
    metadata:
      name: sonarqube
      labels:
        name: sonarqube
    spec:
      containers:
        - image: sonarqube:7.9.1-community
          name: sonarqube
          env:
            - name: SONARQUBE_JDBC_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: postgres-pwd
                  key: password
            - name: SONARQUBE_JDBC_URL
              value: jdbc:postgresql://sonar-postgres:5432/sonar
          ports:
            - containerPort: 9000
              name: sonarqube
          volumeMounts:
            - name: data-sonar-extensions
              mountPath: /opt/sonarqube/extensions/plugins
          resources:
            requests:
              memory: 2000Mi
            limits:
              memory: 2000Mi
      volumes:
        - name: data-sonar-extensions
          persistentVolumeClaim:
            claimName: claim-sonar-extensions
      initContainers:
        - name: sysctl
          image: busybox
          imagePullPolicy: IfNotPresent
          command: ['sysctl', '-w', 'vm.max_map_count=262144']
          securityContext:
            privileged: true
</code>```

3-)Sample plugins Dockerfile

```<code>FROM alpine:3.4

RUN apk --no-cache add --repository http://dl-cdn.alpinelinux.org/alpine/edge/community wget ca-certificates

ENV PLUGINS_DIR /opt/sonarqube/extensions/plugins

WORKDIR $PLUGINS_DIR
RUN wget https://github.com/gabrie-allaigre/sonar-gitlab-plugin/releases/download/4.1.0-SNAPSHOT/sonar-gitlab-plugin-4.1.0-SNAPSHOT.jar
RUN wget https://binaries.sonarsource.com/Distribution/sonar-java-plugin/sonar-java-plugin-6.3.0.21585.jar
RUN wget https://github.com/SonarSource/sonar-php/releases/download/3.4.0.5461/sonar-php-plugin-3.4.0.5461.jar
ENV JAVASCRIPT_VERSION 2.20.0.4207

VOLUME $PLUGINS_DIR

CMD ls -asl $PLUGINS_DIR
</code>```

I tried that approach with sonar-plugin-deployment.yml:

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: sonarqube-plugin
spec:
  replicas: 1
  selector:
    matchLabels:
      name: sonarqube-plugin
  template:
    metadata:
      name: sonarqube-plugin
      labels:
        name: sonarqube-plugin
    spec:
      containers:
        - image: my-kubernetes-registry/plugins
          name: sonarqube-plugins
          volumeMounts:
            # This name must match the volumes.name below.
            - name: data-sonar-extensions
              mountPath: /opt/sonarqube/extensions/plugins
      volumes:
        - name: data-sonar-extensions
          persistentVolumeClaim:
            claimName: claim-sonar-extensions
</code>```

But didn't successed. And break something. This time my plugins directory became empty:

```<code>sonarqube@sonarqube-85b98d9845-l2sql:/opt/sonarqube/extensions/plugins$ ls -al
total 24
drwxr-xr-x 3 root      root       4096 May 30 16:19 .
drwxr-xr-x 1 sonarqube sonarqube  4096 May 30 16:39 ..
drwx------ 2 root      root      16384 May 30 16:19 lost+found
</code>```

I am not using persistent volume. PVC is looking to stroge class. So i cant use accessModes as ReadWriteMany.

As a results: I want to change a stroge path with a fly-away container and use that path inside an app.

I am noob to kubernetes if you suggest a different approach i will be apreciated.

答:
When we mount Docker's WORKDIR in Kubernetes, Kubernetes cleans up or override the directory. In such cases, we have to set a different directory from the mount path as WORKDIR in Docker and later in Kubernetes we have to move our contents to mounted directory.

Dockerfile, here I configured WORKDIR as /opt/sonarqube/plugins

```<code>FROM alpine:3.11

RUN apk --no-cache add --repository http://dl-cdn.alpinelinux.org/alpine/edge/community wget ca-certificates

WORKDIR /opt/sonarqube/plugins

RUN wget https://github.com/gabrie-allaigre/sonar-gitlab-plugin/releases/download/4.1.0-SNAPSHOT/sonar-gitlab-plugin-4.1.0-SNAPSHOT.jar &&\
    wget https://binaries.sonarsource.com/Distribution/sonar-java-plugin/sonar-java-plugin-6.3.0.21585.jar &&\
    wget https://github.com/SonarSource/sonar-php/releases/download/3.4.0.5461/sonar-php-plugin-3.4.0.5461.jar
</code>```

sonar.yml, Here I have used postStart lifecycle hook to copy the plugins to mount path. It copies the external plugins to the mount path before pod starts.

```<code>apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: sonarqube
  name: sonarqube
spec:
  containers:
  - image: harik8/demo:latest
    name: sonarqube
    resources: {}
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh","-c", "mv /opt/sonarqube/plugins/*.jar /opt/sonarqube/extensions/plugins"]
    command: ["cat"]
    tty: true
    volumeMounts:
    - name: data-sonar-extensions
      mountPath: /opt/sonarqube/extensions/plugins
  dnsPolicy: ClusterFirst
  restartPolicy: Never
  volumes:
  - name: data-sonar-extensions
    emptyDir: {}
status: {}
</code>```

Once pod starts, exec and list /opt/sonarqube/extensions/plugins directory,

```<code>$ kubectl exec -it sonarqube sh
/opt/sonarqube/extensions/plugins # pwd
/opt/sonarqube/extensions/plugins
/opt/sonarqube/extensions/plugins # ls -la
total 33320
drwxrwxrwx    2 root     root          4096 May 31 20:59 .
drwxr-xr-x    3 root     root          4096 May 31 20:59 ..
-rw-r--r--    1 root     root      10280677 Mar 28  2019 sonar-gitlab-plugin-4.1.0-SNAPSHOT.jar
-rw-r--r--    1 root     root      18712457 Apr  8 13:26 sonar-java-plugin-6.3.0.21585.jar
-rw-r--r--    1 root     root       5114341 May 11 15:24 sonar-php-plugin-3.4.0.5461.jar
/opt/sonarqube/extensions/plugins
</code>```

Body:
I want to publish sonarqube with kubernetes. I did successfully with official packages. But i want to use some plugins old version and some custom plugins. In local with docker-compose files, i created a fly-away container that fills the plugins directory(/opt/sonarqube/extensions/plugins) with plugins. And use that volume with sonarqube container. As a conclusion : Sonarqube extensions volume directory is created (or filled) from different container(do the job and die).

I want to use the same path with kubernetes but couldn't do that. My flyaway container didn't fill the path.

My kubernetes deployments files:

1-) sonar-pvc-extensions.yml

kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: claim-sonar-extensions
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 8Gi

2-) sonarqube-deployment.yml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: sonarqube
spec:
  replicas: 1
  selector:
    matchLabels:
      name: sonarqube
  template:
    metadata:
      name: sonarqube
      labels:
        name: sonarqube
    spec:
      containers:
        - image: sonarqube:7.9.1-community
          name: sonarqube
          env:
            - name: SONARQUBE_JDBC_PASSWORD
              valueFrom:
                secretKeyRef:
                  name: postgres-pwd
                  key: password
            - name: SONARQUBE_JDBC_URL
              value: jdbc:postgresql://sonar-postgres:5432/sonar
          ports:
            - containerPort: 9000
              name: sonarqube
          volumeMounts:
            - name: data-sonar-extensions
              mountPath: /opt/sonarqube/extensions/plugins
          resources:
            requests:
              memory: 2000Mi
            limits:
              memory: 2000Mi
      volumes:
        - name: data-sonar-extensions
          persistentVolumeClaim:
            claimName: claim-sonar-extensions
      initContainers:
        - name: sysctl
          image: busybox
          imagePullPolicy: IfNotPresent
          command: ['sysctl', '-w', 'vm.max_map_count=262144']
          securityContext:
            privileged: true

3-)Sample plugins Dockerfile

FROM alpine:3.4

RUN apk --no-cache add --repository http://dl-cdn.alpinelinux.org/alpine/edge/community wget ca-certificates

ENV PLUGINS_DIR /opt/sonarqube/extensions/plugins

WORKDIR $PLUGINS_DIR
RUN wget https://github.com/gabrie-allaigre/sonar-gitlab-plugin/releases/download/4.1.0-SNAPSHOT/sonar-gitlab-plugin-4.1.0-SNAPSHOT.jar
RUN wget https://binaries.sonarsource.com/Distribution/sonar-java-plugin/sonar-java-plugin-6.3.0.21585.jar
RUN wget https://github.com/SonarSource/sonar-php/releases/download/3.4.0.5461/sonar-php-plugin-3.4.0.5461.jar
ENV JAVASCRIPT_VERSION 2.20.0.4207

VOLUME $PLUGINS_DIR

CMD ls -asl $PLUGINS_DIR

I tried that approach with sonar-plugin-deployment.yml:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: sonarqube-plugin
spec:
  replicas: 1
  selector:
    matchLabels:
      name: sonarqube-plugin
  template:
    metadata:
      name: sonarqube-plugin
      labels:
        name: sonarqube-plugin
    spec:
      containers:
        - image: my-kubernetes-registry/plugins
          name: sonarqube-plugins
          volumeMounts:
            # This name must match the volumes.name below.
            - name: data-sonar-extensions
              mountPath: /opt/sonarqube/extensions/plugins
      volumes:
        - name: data-sonar-extensions
          persistentVolumeClaim:
            claimName: claim-sonar-extensions

But didn't successed. And break something. This time my plugins directory became empty:

sonarqube@sonarqube-85b98d9845-l2sql:/opt/sonarqube/extensions/plugins$ ls -al
total 24
drwxr-xr-x 3 root      root       4096 May 30 16:19 .
drwxr-xr-x 1 sonarqube sonarqube  4096 May 30 16:39 ..
drwx------ 2 root      root      16384 May 30 16:19 lost+found

I am not using persistent volume. PVC is looking to stroge class. So i cant use accessModes as ReadWriteMany.

As a results: I want to change a stroge path with a fly-away container and use that path inside an app.

I am noob to kubernetes if you suggest a different approach i will be apreciated.

Body:
When we mount Docker's WORKDIR in Kubernetes, Kubernetes cleans up or override the directory. In such cases, we have to set a different directory from the mount path as WORKDIR in Docker and later in Kubernetes we have to move our contents to mounted directory.

Dockerfile, here I configured WORKDIR as /opt/sonarqube/plugins

FROM alpine:3.11

RUN apk --no-cache add --repository http://dl-cdn.alpinelinux.org/alpine/edge/community wget ca-certificates

WORKDIR /opt/sonarqube/plugins

RUN wget https://github.com/gabrie-allaigre/sonar-gitlab-plugin/releases/download/4.1.0-SNAPSHOT/sonar-gitlab-plugin-4.1.0-SNAPSHOT.jar &&\
    wget https://binaries.sonarsource.com/Distribution/sonar-java-plugin/sonar-java-plugin-6.3.0.21585.jar &&\
    wget https://github.com/SonarSource/sonar-php/releases/download/3.4.0.5461/sonar-php-plugin-3.4.0.5461.jar

sonar.yml, Here I have used postStart lifecycle hook to copy the plugins to mount path. It copies the external plugins to the mount path before pod starts.

apiVersion: v1
kind: Pod
metadata:
  creationTimestamp: null
  labels:
    run: sonarqube
  name: sonarqube
spec:
  containers:
  - image: harik8/demo:latest
    name: sonarqube
    resources: {}
    lifecycle:
      postStart:
        exec:
          command: ["/bin/sh","-c", "mv /opt/sonarqube/plugins/*.jar /opt/sonarqube/extensions/plugins"]
    command: ["cat"]
    tty: true
    volumeMounts:
    - name: data-sonar-extensions
      mountPath: /opt/sonarqube/extensions/plugins
  dnsPolicy: ClusterFirst
  restartPolicy: Never
  volumes:
  - name: data-sonar-extensions
    emptyDir: {}
status: {}

Once pod starts, exec and list /opt/sonarqube/extensions/plugins directory,

$ kubectl exec -it sonarqube sh
/opt/sonarqube/extensions/plugins # pwd
/opt/sonarqube/extensions/plugins
/opt/sonarqube/extensions/plugins # ls -la
total 33320
drwxrwxrwx    2 root     root          4096 May 31 20:59 .
drwxr-xr-x    3 root     root          4096 May 31 20:59 ..
-rw-r--r--    1 root     root      10280677 Mar 28  2019 sonar-gitlab-plugin-4.1.0-SNAPSHOT.jar
-rw-r--r--    1 root     root      18712457 Apr  8 13:26 sonar-java-plugin-6.3.0.21585.jar
-rw-r--r--    1 root     root       5114341 May 11 15:24 sonar-php-plugin-3.4.0.5461.jar
/opt/sonarqube/extensions/plugins


来源: stackexchange

问:
Stop Macro if MsgBox appears
I have a Macro that performs a few validations. I've simplified the code below for illustration.

If all the validations are successful, then I want it to run the "ActiveWorkbook.SaveAs" line.

If a MsgBox has to popup, then I don't want to run the "ActiveWorkbook.SaveAs" line

How could I tweak my code to make this possible? Thank you for helping me!

```<code>Sub blank()

'Validations
If Cells(10, 4).Value = "" Then
MsgBox "Please fill in Invoice Date"
End If

If Cells(11, 4).Value = "" Then
MsgBox "Please fill in Invoice Number"
End If

'Save As
ActiveWorkbook.SaveAs filename:="Lease Admin Processing Input Form"

End Sub
</code>```

答:
Maybe like this</p>

```<code>Sub blank()

Dim bolChecker as boolean

bolChecker = false

'Validations
If Cells(10, 4).Value = "" Then
MsgBox "Please fill in Invoice Date"
bolChecker = true
End If

If Cells(11, 4).Value = "" Then
MsgBox "Please fill in Invoice Number"
bolChecker = true
End If

'Save As
if bolChecker = false then ActiveWorkbook.SaveAs filename:="Lease Admin Processing Input Form"

End Sub
</code>```

ContentLicense: CC BY-SA 4.0

Title: Stop Macro if MsgBox appears

Body:
I have a Macro that performs a few validations. I've simplified the code below for illustration.

If all the validations are successful, then I want it to run the "ActiveWorkbook.SaveAs" line.

If a MsgBox has to popup, then I don't want to run the "ActiveWorkbook.SaveAs" line

How could I tweak my code to make this possible? Thank you for helping me!

Sub blank()

'Validations
If Cells(10, 4).Value = "" Then
MsgBox "Please fill in Invoice Date"
End If

If Cells(11, 4).Value = "" Then
MsgBox "Please fill in Invoice Number"
End If

'Save As
ActiveWorkbook.SaveAs filename:="Lease Admin Processing Input Form"

End Sub

Body:
Maybe like this

Sub blank()

Dim bolChecker as boolean

bolChecker = false

'Validations
If Cells(10, 4).Value = "" Then
MsgBox "Please fill in Invoice Date"
bolChecker = true
End If

If Cells(11, 4).Value = "" Then
MsgBox "Please fill in Invoice Number"
bolChecker = true
End If

'Save As
if bolChecker = false then ActiveWorkbook.SaveAs filename:="Lease Admin Processing Input Form"

End Sub


答:
You can do this:

```<code>Sub blank()

    If Cells(10, 4).Value = "" Or Cells(11, 4).Value = "" Then
        MsgBox "Please fill in both Invoice Number and Invoice Date"
    Else
        ActiveWorkbook.SaveAs filename:="Lease Admin Processing Input Form"
    End If

End Sub
</code>```

Or this if you have many checks:

```<code>Dim Msg As String

CheckEmpty Cells(10, 4), Msg, "Invoice date is required"
CheckEmpty Cells(11, 4), Msg, "Invoice number is required"
'...more checks

If len(Msg) > 0 Then
    MsgBox "Please correct the following items:" & vblf & Msg
Else
    'save etc
End If

'....

'utility sub for building notification message
Sub CheckEmpty(c as Range, byRef Msg as string, errMsg As String)
    If Len(Trim(c.Value)) = 0 Then
        Msg = Msg & vbLf & " - " & errMsg
    End If
End If
</code>```

Title: Stop Macro if MsgBox appears

Body:
You can do this:

Sub blank()

    If Cells(10, 4).Value = "" Or Cells(11, 4).Value = "" Then
        MsgBox "Please fill in both Invoice Number and Invoice Date"
    Else
        ActiveWorkbook.SaveAs filename:="Lease Admin Processing Input Form"
    End If

End Sub

Or this if you have many checks:

Dim Msg As String

CheckEmpty Cells(10, 4), Msg, "Invoice date is required"
CheckEmpty Cells(11, 4), Msg, "Invoice number is required"
'...more checks

If len(Msg) > 0 Then
    MsgBox "Please correct the following items:" & vblf & Msg
Else
    'save etc
End If

'....

'utility sub for building notification message
Sub CheckEmpty(c as Range, byRef Msg as string, errMsg As String)
    If Len(Trim(c.Value)) = 0 Then
        Msg = Msg & vbLf & " - " & errMsg
    End If
End If


问:
Concatenate two strings in assembly
I need to concatenate two strings and then show it on the screen.
When i run this program the output is not what i was expected.
Can you tell me what is wrong in this code?

example:

expected input

first string = 'my'

second string = 'string'

expected output = 'my string'

```<code>assume  ds:date, cs:cod
date segment

    message1 db "Enter the fisrt string $"
    message2 db 0ah, 0dh , "Enter the second string $"
    message3 db 0ah, 0dh, "The string is $"
    string1 db 20, ?, 20 dup('')
    string2 db 20, ?, 20 dup('')
    string3 db 40 dup('')

date ends
cod segment
start :
mov ax, date
mov ds, ax

    lea dx, message1
    mov ah, 09h
    int 21h

    lea dx, string1
    mov ah, 0ah
    int 21h

    lea dx, message2
    mov ah, 09h
    int 21h

    lea dx, string2
    mov ah, 0ah
    int 21h

    mov si, 2     ; index of the first element
    mov di, 0     ; final string first element index
    mov cl, string1[1]      ; string lenght
    loopp:
        mov bl, string1[si]
        mov string3[di], bl
        inc si
        inc di
        loop loopp

    mov cl, string2[1]  ; second tring lenght
    mov si, 2
    loopp2:
        mov bl, string2[si]
        mov string3[di], bl
        inc si
        inc di
        loop loopp
    mov string3[di], '$'

    lea dx, message3
    mov ah, 09h
    int 21h

    lea dx, string3
    mov ah, 09h
    int 21h

mov ax, 4c00h
int 21h
cod ends
end start
</code>```

答:
```<code>string1 db 20, ?, 20 dup('')
string2 db 20, ?, 20 dup('')
string3 db 40 dup('')
</code>```

You don't have the necessary buffers with the above db directives! What you've placed between the dup parenthesis is the empty string. Not sure if this assigns any memory at all...

This should work:

```<code>string1 db 20, ?, 20 dup(0)
string2 db 20, ?, 20 dup(0)
string3 db 40 dup(0)
</code>```

and this too:

```<code>string1 db 20, ?, 20 dup(' ')   ; ' ' is a space character
string2 db 20, ?, 20 dup(' ')
string3 db 40 dup(' ')
</code>```

The loop instruction uses the whole CX register but your code only fills in the CL part!

Use this:

```<code>mov cl, string1[1]      ; string lenght
mov ch, 0
...
</code>```

If you want a separating space character between my and string, you'll have to write it in between copying both strings.

Title: Concatenate two strings in assembly

Body:
I need to concatenate two strings and then show it on the screen.
When i run this program the output is not what i was expected.
Can you tell me what is wrong in this code?

example:

expected input

first string = 'my'

second string = 'string'

expected output = 'my string'

assume  ds:date, cs:cod
date segment

    message1 db "Enter the fisrt string $"
    message2 db 0ah, 0dh , "Enter the second string $"
    message3 db 0ah, 0dh, "The string is $"
    string1 db 20, ?, 20 dup('')
    string2 db 20, ?, 20 dup('')
    string3 db 40 dup('')

date ends
cod segment
start :
mov ax, date
mov ds, ax

    lea dx, message1
    mov ah, 09h
    int 21h

    lea dx, string1
    mov ah, 0ah
    int 21h

    lea dx, message2
    mov ah, 09h
    int 21h

    lea dx, string2
    mov ah, 0ah
    int 21h

    mov si, 2     ; index of the first element
    mov di, 0     ; final string first element index
    mov cl, string1[1]      ; string lenght
    loopp:
        mov bl, string1[si]
        mov string3[di], bl
        inc si
        inc di
        loop loopp

    mov cl, string2[1]  ; second tring lenght
    mov si, 2
    loopp2:
        mov bl, string2[si]
        mov string3[di], bl
        inc si
        inc di
        loop loopp
    mov string3[di], '$'

    lea dx, message3
    mov ah, 09h
    int 21h

    lea dx, string3
    mov ah, 09h
    int 21h

mov ax, 4c00h
int 21h
cod ends
end start

Body:
string1 db 20, ?, 20 dup('')
string2 db 20, ?, 20 dup('')
string3 db 40 dup('')

You don't have the necessary buffers with the above db directives! What you've placed between the dup parenthesis is the empty string. Not sure if this assigns any memory at all...

This should work:

string1 db 20, ?, 20 dup(0)
string2 db 20, ?, 20 dup(0)
string3 db 40 dup(0)

and this too:

string1 db 20, ?, 20 dup(' ')   ; ' ' is a space character
string2 db 20, ?, 20 dup(' ')
string3 db 40 dup(' ')

The loop instruction uses the whole CX register but your code only fills in the CL part!

Use this:

mov cl, string1[1]      ; string lenght
mov ch, 0
...

If you want a separating space character between my and string, you'll have to write it in between copying both strings.


问:
Shouldnt the x[1] just take the second array in the multidimensional array=
I have trouble understanding the lambda function, I always confuse myself because I overthink everything, here my problem:

```<code>nm = input().split()
n = int(nm[0])
m = int(nm[1])
arr = []

for _ in range(n):
    arr.append(list(map(int, input().rstrip().split())))

k = int(input())

arr.sort(key=lambda x: x[1])
</code>```

What the Code does isn't important right now, but I receive following output if I print my array(for my example):

```<code>[[7, 1, 0], [10, 2, 5], [6, 5, 9], [9, 9, 9], [1, 23, 12]]
</code>```

As you can see it is a multidimensional array, now I want to sort it based on the second element of each list:

```<code>arr.sort(key=lambda x: x[1])
</code>```

So I have the list and I want to sort it with the key lambda and the variable x: x[1] shouldn't my variable x be the multidimensional array? Isnt it the same if I say x = arr,
how exactly does this function know i want to sort all the elements that are at position x[1] from each list, i would have thought using x[1] would only be the second array in the multidimensional array:

```<code>[[1, 2, 3], **[4, 2, 6]** ...
</code>```

Im a beginner so I would appreciate a beginner friendly response to my question,
cheers!

答:
I'll try to explain what this line does in plain language:

arr.sort(key=lambda x: x[1])

It basically says: take each element of arr, call it x, and then use x[1] as the sorting key.

So your input is this:

[[7, 1, 0], [10, 2, 5], [6, 5, 9], [9, 9, 9], [1, 23, 12]]

It is a list of lists, so if you use the sort function, the result is also a list of lists, ordered according to the key defined in the lambda function. Let's go through what the lambda does here:

Set x to the first element of arr: [7, 1, 0]. x[1] is now 1

Set x to the second element of arr:  [10, 2, 5]. x[1] is now 2.

Set x to the third element of arr:  [6, 5, 9]. x[1] is now 5.

Set x to the fourth element of arr:  [9, 9, 9]. x[1] is now 9.

Set x to the fifth element of arr:  [1, 23, 12]. x[1] is now 23.

The keys we have extracted this way are now [1, 2, 5, 9, 23]. It is this list of numbers that determines the sorting order. Since the keys are already in order, sorting arr this way will not change anything.

Body:
I have trouble understanding the lambda function, I always confuse myself because I overthink everything, here my problem:

nm = input().split()
n = int(nm[0])
m = int(nm[1])
arr = []

for _ in range(n):
    arr.append(list(map(int, input().rstrip().split())))

k = int(input())

arr.sort(key=lambda x: x[1])

What the Code does isn't important right now, but I receive following output if I print my array(for my example):

[[7, 1, 0], [10, 2, 5], [6, 5, 9], [9, 9, 9], [1, 23, 12]]

As you can see it is a multidimensional array, now I want to sort it based on the second element of each list:

arr.sort(key=lambda x: x[1])

So I have the list and I want to sort it with the key lambda and the variable x: x[1] shouldn't my variable x be the multidimensional array? Isnt it the same if I say x = arr,
how exactly does this function know i want to sort all the elements that are at position x[1] from each list, i would have thought using x[1] would only be the second array in the multidimensional array:

[[1, 2, 3], **[4, 2, 6]** ...

Im a beginner so I would appreciate a beginner friendly response to my question,
cheers!


问:
Why doesn't JTextfield in java display text at runtime?
Hope you are all well!

Hope you understand my Java question... I have created a JFrame window with text to display, but it doesn't display at run-time (as it should) unless I maximise the Frame window.

Can't understand it?

Here's some code:

```<code>package test;

import javax.swing.*;

class Test{

    private String x;

    private Test() {
        x="150";
    }

    public static void main(String[] args) {

        Test o1 = new Test();

        JTextField l = new JTextField(o1.x, JTextField.CENTER);
        l.setAlignmentX(0);
        l.setAlignmentY(0);

        JFrame window = new JFrame("Hello World!");
        window.setSize(800, 600);
        window.setResizable(true);
        window.setVisible(true);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.add(l);

        }

}
</code>```

答:
Altering the size of the frame (by maximising it) will cause it to be repainted. The reason it needs to be repainted is that you added content to it after you already made it visible.

Instead, you could move window.setVisible(true); to the end, so you don't show the window until you've added everything to it.

Body:
Hope you are all well!

Hope you understand my Java question... I have created a JFrame window with text to display, but it doesn't display at run-time (as it should) unless I maximise the Frame window.

Can't understand it?

Here's some code:

package test;

import javax.swing.*;

class Test{

    private String x;

    private Test() {
        x="150";
    }

    public static void main(String[] args) {

        Test o1 = new Test();

        JTextField l = new JTextField(o1.x, JTextField.CENTER);
        l.setAlignmentX(0);
        l.setAlignmentY(0);

        JFrame window = new JFrame("Hello World!");
        window.setSize(800, 600);
        window.setResizable(true);
        window.setVisible(true);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.add(l);

        }

}


问:
How to match the first value of the grains in saltstack?
I would like to  get the first value of eth0.
I would like to set a variable.

```<code>hardware_interface:
  eth0:
      10.0.2.16
      192.168.34.11
  lo:
      127.0.0.1
</code>```

Below is my variable declaration in state file and it doesn't work. What am I missing?

```<code>{% set interface = grains['hwaddr_interfaces'][0] %}
{% set ip = grains['ipv4'][1] %}
</code>```

答:
You're trying to access a dictionary (hwaddr_interfaces) so you do not have direct access to the value with the index.

```<code>{% set interface = salt['grains.get']("hwaddr_interfaces", []) %}

# {{ interface.keys() }}
# {{ interface.keys() | first }}
# {{ interface.keys()[0] }}
</code>```

This will output the following thing when doing a salt-call -l debug:

```<code>...
# [u'lo', u'virbr0', u'virbr0-nic', u'eth0']
# lo
# lo
...
</code>```

When you are using the .keys() you get an array.
If you want the first element, using the jinja | first should be enough. otherwise interface.keys()[idx]

Once you have the name of the interface you can retrieve the associated array with:

```<code>{% set res = salt['grains.get']("hwaddr_interfaces:"+interface.keys()[0], []) %}
</code>```

For the ipv4 part, it should be working as it is an array:

```<code>{% set ip = salt['grains.get']('ipv4')  %}

# {{ ip }}
# {{ ip | first }}
# {{ ip[1] }}
</code>```

output:

```<code># [u'127.0.0.1', u'192.168.1.34', u'192.168.122.1']
# 127.0.0.1
# 192.168.1.34
</code>```

Body:
I would like to  get the first value of eth0.
I would like to set a variable.

hardware_interface:
  eth0:
      10.0.2.16
      192.168.34.11
  lo:
      127.0.0.1

Below is my variable declaration in state file and it doesn't work. What am I missing?

{% set interface = grains['hwaddr_interfaces'][0] %}
{% set ip = grains['ipv4'][1] %}

Body:
You're trying to access a dictionary (hwaddr_interfaces) so you do not have direct access to the value with the index.

{% set interface = salt['grains.get']("hwaddr_interfaces", []) %}

# {{ interface.keys() }}
# {{ interface.keys() | first }}
# {{ interface.keys()[0] }}

This will output the following thing when doing a salt-call -l debug:

...
# [u'lo', u'virbr0', u'virbr0-nic', u'eth0']
# lo
# lo
...

When you are using the .keys() you get an array.
If you want the first element, using the jinja | first should be enough. otherwise interface.keys()[idx]

Once you have the name of the interface you can retrieve the associated array with:

{% set res = salt['grains.get']("hwaddr_interfaces:"+interface.keys()[0], []) %}

For the ipv4 part, it should be working as it is an array:

{% set ip = salt['grains.get']('ipv4')  %}

# {{ ip }}
# {{ ip | first }}
# {{ ip[1] }}

output:

# [u'127.0.0.1', u'192.168.1.34', u'192.168.122.1']
# 127.0.0.1
# 192.168.1.34


问:
How POCO (de)serialization works in protobuf-net?
Is it possible to (de)serialize a POCO type using neither protobuf-net attributes nor explicitly adding types into the model?</p>

答:
I doubt it. What integer id's would it use for the properties?

You could of course write some reflection based code that adds the types to the model without manually specifying the configuration. But I imagine you'll get versioning problems when you add/remove properties from your types. Since I see no way to create a stable mapping from strings to integers implicitly.

You probably could also define some key-value format inside protobuf so you can use string keys instead of integer keys. But then you lose the advantages protobuf offers. And you could just use json/bson instead.

ContentLicense: CC BY-SA 3.0


问:
Add custom data while creating WooCommerce customer
I am adding woocommerce customer programmatically using wc_create_new_customer function, first name, last name, email is added successfully, but custom fields are not adding.
I have tried two ways
1st one:

```<code>$email= $arr_item->email;
enter code here$username = strstr($arr_item->email, ‘@’, true);
$password = wp_generate_password();

$args = array(
“first_name” => $arr_item->first_name,
“billing_first_name” => $arr_item->first_name,
“last_name” => $arr_item->last_name,
“billing_last_name” => $arr_item->last_name,
“billing_email” => $arr_item->email,
“billing_phone” => $arr_item->phone,
“agency_name” => $arr_item->agency_name,
“billing_company” => $arr_item->agency_name,
“agency_country” => $arr_item->agency_country,
“agency_city” => $arr_item->agency_city,
“agency_state” => $arr_item->agency_state
);
$customer_id = wc_create_new_customer( $email, $username, $password, $args );
</code>```

2nd one

```<code>$customer_id = wc_create_new_customer( $email, $username, $password );
update_user_meta( $customer_id, ‘agency_name’,$arr_item->agency_name);
update_user_meta( $customer_id, ‘billing_company’, $arr_item->agency_name);
update_user_meta( $customer_id, ‘agency_country’, $arr_item->agency_country);
update_user_meta( $customer_id, ‘agency_city’, $arr_item->agency_city);
update_user_meta( $customer_id, ‘agency_state’,$arr_item->agency_state);
</code>```

I am trying to add custom field user meta table while creating a customer using wc_create_new_customer
So that I can access these data using get_user_meta().

Please help if anyone has any ideas.

Thanks in advance

答:
You need to save a customer. Add this 2 lines at the end.</p>

```<code>$customer = get_user_by('id', $customer_id);
$customer->save();
</code>```

Body:
I am adding woocommerce customer programmatically using wc_create_new_customer function, first name, last name, email is added successfully, but custom fields are not adding.
I have tried two ways
1st one:

$email= $arr_item->email;
enter code here$username = strstr($arr_item->email, ‘@’, true);
$password = wp_generate_password();

$args = array(
“first_name” => $arr_item->first_name,
“billing_first_name” => $arr_item->first_name,
“last_name” => $arr_item->last_name,
“billing_last_name” => $arr_item->last_name,
“billing_email” => $arr_item->email,
“billing_phone” => $arr_item->phone,
“agency_name” => $arr_item->agency_name,
“billing_company” => $arr_item->agency_name,
“agency_country” => $arr_item->agency_country,
“agency_city” => $arr_item->agency_city,
“agency_state” => $arr_item->agency_state
);
$customer_id = wc_create_new_customer( $email, $username, $password, $args );

2nd one

$customer_id = wc_create_new_customer( $email, $username, $password );
update_user_meta( $customer_id, ‘agency_name’,$arr_item->agency_name);
update_user_meta( $customer_id, ‘billing_company’, $arr_item->agency_name);
update_user_meta( $customer_id, ‘agency_country’, $arr_item->agency_country);
update_user_meta( $customer_id, ‘agency_city’, $arr_item->agency_city);
update_user_meta( $customer_id, ‘agency_state’,$arr_item->agency_state);

I am trying to add custom field user meta table while creating a customer using wc_create_new_customer
So that I can access these data using get_user_meta().

Please help if anyone has any ideas.

Thanks in advance

Body:
You need to save a customer. Add this 2 lines at the end.

$customer = get_user_by('id', $customer_id);
$customer->save();


问:
Dealing with rejected promises without messy try catch
I have a simple function, which looks similar to the following

```<code>const foo = (bar) => {

return ![val1, val2].includes(bar) ? await apiRequest :
await apiRequest + await apiRequest2

}

</code>```

apiRequest returns a number.

This function is surrounded by a function which handles errors for many functions.

However for this specific function, I don't just want to return an error to the user in the case of one of the apiRequests failing in the second part of the ternary.

```<code>const foo = (bar) => {

return ![val1, val2].includes(bar) ? await apiRequest :
await apiRequest + await apiRequest2

// intended logic for second part of ternary
if apiRequest and apiRequest resolve, return apiRequest + apiRequest2
if apiRequest fails, return apiRequest2
if apiRequest 2 fails, return apiRequest
}
</code>```

I'm not exactly sure of the way I should be going about this. Perhaps I could surround each part with try and catch, and in the catch statement I could then try the next part of the logic?

I feel like I will end up with a super messy function in this case

答:
You can try this

```<code>  defaultval="no value"
    const foo = async (bar,apiCalls,defaultval) => {
        var finalresult= await Promise.allSettled(apiCalls)
    .then(resp=>resp.map(p=>p.status==='fulfilled'?p.value:defaultval))
    .then((res)=>{
        var finalnumber=res.filter(x=>x!='no value')
        return finalnumber.length==0?defaultval:finalnumber.reduce((a, b) => a + b)
    })
        return  ![val1, val2].includes(bar) ? apiRequest : finalresult
    }
</code>```

as answered by @trincol if one of the two promises fail it will add the reminder to the default value, if all promises fail it will throw an error and won't return a value, it won't return a default value.
 So I adjusted the code like this

```<code>defaultval="no value"

async function fulfilled(apiCalls,defaultval) {
    const res = await Promise.allSettled(apiCalls);
    return res.map(p => p.status == "fulfilled" ? p.value:defaultval)
}

const foo = async (bar,defaultval) => {
   var result= await fulfilled([apiRequest, apiRequest2])
   var numb=result.filter(x=>x!=defaultval)
   return ![val1, val2].includes(bar) ? apiRequest :(numb.length==0?defaultval:numb.reduce((a, b) => a + b)
   )
}
</code>```

Body:
I have a simple function, which looks similar to the following

const foo = (bar) => {

return ![val1, val2].includes(bar) ? await apiRequest :
await apiRequest + await apiRequest2

}

apiRequest returns a number.

This function is surrounded by a function which handles errors for many functions.

However for this specific function, I don't just want to return an error to the user in the case of one of the apiRequests failing in the second part of the ternary.

const foo = (bar) => {

return ![val1, val2].includes(bar) ? await apiRequest :
await apiRequest + await apiRequest2

// intended logic for second part of ternary
if apiRequest and apiRequest resolve, return apiRequest + apiRequest2
if apiRequest fails, return apiRequest2
if apiRequest 2 fails, return apiRequest
}

I'm not exactly sure of the way I should be going about this. Perhaps I could surround each part with try and catch, and in the catch statement I could then try the next part of the logic?

I feel like I will end up with a super messy function in this case

Body:
You can try this

  defaultval="no value"
    const foo = async (bar,apiCalls,defaultval) => {
        var finalresult= await Promise.allSettled(apiCalls)
    .then(resp=>resp.map(p=>p.status==='fulfilled'?p.value:defaultval))
    .then((res)=>{
        var finalnumber=res.filter(x=>x!='no value')
        return finalnumber.length==0?defaultval:finalnumber.reduce((a, b) => a + b)
    })
        return  ![val1, val2].includes(bar) ? apiRequest : finalresult
    }

as answered by @trincol if one of the two promises fail it will add the reminder to the default value, if all promises fail it will throw an error and won't return a value, it won't return a default value.
 So I adjusted the code like this

defaultval="no value"

async function fulfilled(apiCalls,defaultval) {
    const res = await Promise.allSettled(apiCalls);
    return res.map(p => p.status == "fulfilled" ? p.value:defaultval)
}

const foo = async (bar,defaultval) => {
   var result= await fulfilled([apiRequest, apiRequest2])
   var numb=result.filter(x=>x!=defaultval)
   return ![val1, val2].includes(bar) ? apiRequest :(numb.length==0?defaultval:numb.reduce((a, b) => a + b)
   )
}


问:
Cannot assign "<QuerySet [<Child: Name>]>": "Mark.MarkOwner" must be a "Child" instance
This is another dumb question. I'm really new at django and I don't know what I need to do. Can someone please help me? Or send some pages of documentation? The goal is to make mark selector assigned to child that it displays for. There is some of my code.

My HTML

```<code>{% if child %}
  {% for c in child  %}
  <tr>
  <th>
  {{c.ChildName}}<br>
  </th>
  <th>
    <form action="{% url 'marks:addmark' class.id sc.id %}" method="POST">
                  {% csrf_token %}
              <select required name="sub">
                      <option value=1>1</option>
                      <option value=2>2</option>
                      <option value=3>3</option>
                      <option value=4>4</option>
                      <option value=5>5</option>
                      <option value=6>6</option>
                      <option value=7>7</option>
                      <option value=8>8</option>
                      <option value=9>9</option>
                      <option value=10>10</option>
                      <option value=11>11</option>
                      <option value=12>12</option>
              </select>
              <button type="submit">готово</button>
              </form>
  </th>
</tr>
{% endfor %}
{% endif %}
</code>```

views.py

```<code>def mlat(request, classid, subjectid):
    a = Class.objects.get( id = classid )
    b = SubjectClas.objects.get( id = subjectid )
    d = Child.objects.filter(ChildClass = a)
    c = Mark.objects.filter(MarkSubjet = b)
    return render(request, 'marks/mlat.html', {'class':a, 'sc':b, 'subjectsyes':c, 'child':d})
def addmark(request, classid, subjectid):
    a = Class.objects.get( id = classid )
    b = SubjectClas.objects.get( id = subjectid )
    d = Child.objects.filter(ChildClass = a)
    c = Mark.objects.filter(MarkSubjet = b)
    Mark.objects.create(Markd = request.POST['sub'], MarkSubjet = a, MarkOwner = d)
    return HttpResponseRedirect(reverse('marks:mlat', args=[b.id, a.id,]))
</code>```

models.py

```<code>class SubjectClas(models.Model):
    subject = models.CharField('Предмет', max_length = 50, default='Алгебра')
    clas = models.ForeignKey(Class, null=True, on_delete= models.SET_NULL)
class Child(models.Model):
    ChildName = models.CharField('Имя ученика', max_length = 50)
    ChildClass = models.ForeignKey(Class, null=True, on_delete= models.SET_NULL)
    def __str__(self):
        return self.ChildName
class Mark(models.Model):
    MarkOwner = models.ForeignKey(Child, null=True, on_delete= models.SET_NULL)
    MarkSubjet = models.ForeignKey(SubjectClas, null=True, on_delete= models.SET_NULL)
    Markd = models.CharField('Оценка', max_length = 2)
    MarkDate = models.DateField('Дата')
    def __str__(self):
        return self.Markd
</code>```

urls.py

```<code>    path('<int:classid>/<int:subjectid>/', views.mlat, name = 'mlat'),
    path('<int:classid>/<int:subjectid>/addmark/', views.addmark, name = 'addmark')
</code>```

Thanks for your help!

答:
the problem is coming from your:
d = Child.objects.filter(ChildClass = a)
.filter returns a queryset and you cannot assign a queryset to Mark.MarkOwner.

change it to:

```<code>d = Child.objects.get(ChildClass = a)
</code>```

to return a Child instance.

But if the Child does not exist this will return an error so I recommend using:

```<code>if Child.objects.filter(ChildClass = a).exists():
    d = Child.objects.get(ChildClass = a)
</code>```

This way you can handle the case where Child does not exist without crashing

Body:
This is another dumb question. I'm really new at django and I don't know what I need to do. Can someone please help me? Or send some pages of documentation? The goal is to make mark selector assigned to child that it displays for. There is some of my code.

My HTML

{% if child %}
  {% for c in child  %}

  {{c.ChildName}}

    <form action="{% url 'marks:addmark' class.id sc.id %}" method="POST">
                  {% csrf_token %}
              <select required name="sub">
                      <option value=1>1</option>
                      <option value=2>2</option>
                      <option value=3>3</option>
                      <option value=4>4</option>
                      <option value=5>5</option>
                      <option value=6>6</option>
                      <option value=7>7</option>
                      <option value=8>8</option>
                      <option value=9>9</option>
                      <option value=10>10</option>
                      <option value=11>11</option>
                      <option value=12>12</option>
              </select>
              <button type="submit">готово</button>
              </form>

{% endfor %}
{% endif %}

views.py

def mlat(request, classid, subjectid):
    a = Class.objects.get( id = classid )
    b = SubjectClas.objects.get( id = subjectid )
    d = Child.objects.filter(ChildClass = a)
    c = Mark.objects.filter(MarkSubjet = b)
    return render(request, 'marks/mlat.html', {'class':a, 'sc':b, 'subjectsyes':c, 'child':d})
def addmark(request, classid, subjectid):
    a = Class.objects.get( id = classid )
    b = SubjectClas.objects.get( id = subjectid )
    d = Child.objects.filter(ChildClass = a)
    c = Mark.objects.filter(MarkSubjet = b)
    Mark.objects.create(Markd = request.POST['sub'], MarkSubjet = a, MarkOwner = d)
    return HttpResponseRedirect(reverse('marks:mlat', args=[b.id, a.id,]))

models.py

class SubjectClas(models.Model):
    subject = models.CharField('Предмет', max_length = 50, default='Алгебра')
    clas = models.ForeignKey(Class, null=True, on_delete= models.SET_NULL)
class Child(models.Model):
    ChildName = models.CharField('Имя ученика', max_length = 50)
    ChildClass = models.ForeignKey(Class, null=True, on_delete= models.SET_NULL)
    def __str__(self):
        return self.ChildName
class Mark(models.Model):
    MarkOwner = models.ForeignKey(Child, null=True, on_delete= models.SET_NULL)
    MarkSubjet = models.ForeignKey(SubjectClas, null=True, on_delete= models.SET_NULL)
    Markd = models.CharField('Оценка', max_length = 2)
    MarkDate = models.DateField('Дата')
    def __str__(self):
        return self.Markd

urls.py

    path('<int:classid>/<int:subjectid>/', views.mlat, name = 'mlat'),
    path('<int:classid>/<int:subjectid>/addmark/', views.addmark, name = 'addmark')

Thanks for your help!

Body:
the problem is coming from your:
d = Child.objects.filter(ChildClass = a)
.filter returns a queryset and you cannot assign a queryset to Mark.MarkOwner.

change it to:

d = Child.objects.get(ChildClass = a)

to return a Child instance.

But if the Child does not exist this will return an error so I recommend using:

if Child.objects.filter(ChildClass = a).exists():
    d = Child.objects.get(ChildClass = a)

This way you can handle the case where Child does not exist without crashing


问:
Git master branch has no upstream branch
I'm trying to push one of my projects to github, and I keep getting this error:

```<code>fatal: The current branch master has no upstream branch.
</code>```

I've never seen this before. I re-initialized my git, re-added my origin, deleted and re-made the repo, and recreated my SSH key.

答:
In case someone is still running into this issue, this command solved it for me</p>

```<code>git push --set-upstream origin master
</code>```

Body:
I'm trying to push one of my projects to github, and I keep getting this error:

fatal: The current branch master has no upstream branch.

I've never seen this before. I re-initialized my git, re-added my origin, deleted and re-made the repo, and recreated my SSH key.

Body:
In case someone is still running into this issue, this command solved it for me

git push --set-upstream origin master


问:
How to switch off Auto Import with IntelliJ/Scala Plugin
Simple Problem: Ever since I switched to Idea 10.5, it has this auto import feature enabled. For a Java developer, this is surely nice, but every time I type thing like var x: Float it automatically adds import java.lang.Float on the beginning of the file. Very often, it even adds imports I did not even want, from unknown packages deep in my jar jungle, and prefers Java over Scala packages.

Played around with the switches in Code completion tab, but it keeps on doing this. How can I get rid of this?

答: Check "Code style" -> "Scala" -> "Imports" and "Editor" -> "Auto import" under Settings</p>


问:
How to find a particular object in DevTools memory snapshot if the type of the object is just "Object"?
queryObjects function returns instances of a given prototype.
I want to inspect retainers of those instances. To do that I need to find them in devtools memory snapshot. One of those instances type is "Object", so searching by class type isn't helpful. They are just too many of them.

How can I find that particular instance in a snapshot?

答:
Add explicit string property e.g. let o = {type:'myType'} and then use ctrl+F in snapshot.

There retainers are all your o objects.


问:
TypeError: Failed to execute 'appendBuffer' on 'SourceBuffer': No function was found that matched the signature provided
Edit: To help illustrate the error I keep getting I have created a CodePen of the issue I am seeing. Open up the console and you will see the error. [https://codepen.io/FifthCloud/pen/eYpqJLN]

I wanted to design my own streaming camera service in my home using React/Node. So far I have gone a long way with a Client/Server approach. The server is a raspberry pi with camera attached to it. Using FFMpeg I can see all the video from it and using websockets I can successfully send the data (I mean I see the data being sent to the client will get into why it will not render).

The issue I am running into is why cannot I append the data to the buffer. For starters, I am using this demo about Media Source as a guide and example on what I am supposed to be doing. http://nickdesaulniers.github.io/netfix/demo/bufferAll.html I got this link from my research about Media Source's here: https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/readyState
Also would like to mention that I have received a lot of inspiration from this post and got really far because of this answer HTML5 Video: Streaming Video with Blob URLs

With that in mind I can successfully create a MediaSource and open the buffer, but what I cannot understand is why am I unable to append to the buffer? The error I am recieving is this:

TypeError: Failed to execute 'appendBuffer' on 'SourceBuffer': No function was found that matched the signature provided.

The client side code is the following

```<code>class ProductDetail extends React.Component {
  constructor(props) {
    super(props);
    this.handleData = this.handleData.bind(this);
    this.handleOpen = this.handleOpen.bind(this);
    this.appendToSourceBuffer = this.appendToSourceBuffer.bind(this);
    this.mediaStreaming = new MediaSource();
    this.blobArr = [];
    this.buffer = null;
    this.myRef = React.createRef();

    console.log("buffer initialized");
    console.log("ReadyState [Initialized]: " + this.mediaStreaming.readyState);
    this.state = {
      msg: "",
      stream: "",
      streaming: URL.createObjectURL(this.mediaStreaming),
    };
  }

  componentDidMount() {
    this.mediaStreaming.addEventListener("sourceopen", () => {
      console.log(
        "ReadyState [Source Open]: " + this.mediaStreaming.readyState
      );
      this.buffer = this.mediaStreaming.addSourceBuffer(
        'video/mp4;codecs="avc1.42E01E"'
      );
      this.buffer.addEventListener("updateend", () => {
        this.mediaStreaming.endOfStream();
        document.getElementById("streaming").play();
        console.log(
          "ReadyState [UpdateEnd]: " + this.mediaStreaming.readyState
        );
      });
    });
  }

  handleData(data) {
    const videoStream = JSON.parse(data);
    if (videoStream.msg === "videoStream") {
      this.blobArr.push(videoStream.chunk.data);
      if (
        this.mediaStreaming.readyState === "open" &&
        this.buffer &&
        this.buffer.updating === false &&
        this.blobArr.length > 0
      ) {
        console.log(
          "ReadyState [AppendBuffer]: " + this.mediaStreaming.readyState
        );
        this.buffer.appendBuffer(this.blobArr.shift()); // Error message shows at this line!
        document.getElementById("streaming").play();
        console.log("Buffer Updating", this.buffer.updating);
      }
    }
  }

  handleOpen() {
    console.log("Status: connected");
  }

  handleClose() {
    console.log("Status: disconnected");
  }

  render() {
    return (
      <div>
        <Websocket
          url="ws://192.168.1.20:5000"
          onMessage={this.handleData}
          onOpen={this.handleOpen}
          onClose={this.handleClose}
          reconnect={true}
          debug={true}
          ref={(Websocket) => {
            this.refWebSocket = Websocket;
          }}
          protocol="stream-protocol"
        />
        <video width="640" height="480" id="streaming" controls autoPlay>
          <source
            ref={this.myRef}
            src={this.state.streaming}
            type="video/mp4"
          />
          Your browser does not support the video tag.
        </video>
      </div>
    );
  }
}
</code>```

The error comes from the handleData event from my WebSocket when the server is sending the next streaming byte array data.

As I mentioned about the example and the guide from the link I have posted I looked at their code and stepped through it. According to them Append Buffer should work fine, however even in their code appendbuffer() is only listed in the proto section see here:https://drive.google.com/open?id=1vOU4oM-XoKe71DofQuLU2THxMdgiown_ and yet the code doesn't complain about their appendbuffer(). When I console log my buffer it looks like theirs https://drive.google.com/open?id=1T4Ix-y124NgQJ9xu97xv4U2yFTn2k7vF. What am I missing?

I feel like the answer is very obvious but it is escaping me as to what I am doing wrong.

答:
I'm building a similar project myself, using several high-end RTSP-enabled IP cameras, and just ran into the same error today. First of all, keep in mind that this API is experimental, according to the Mozilla Developer Network (MDN) documentation (link below).

That being said, I seem to have found the root cause of the issue, even though I'm not a JavaScript expert by any stretch. It turns out that you can't directly pass the "Blob" object from data.data in handleData() into the appendBuffer() method. Instead, you need to convert the Blob to a data type that's supported by the appendBuffer() method first, before passing it in.

Turn you event handler into an async function

Use the Blob.arrayBuffer() to convert the data blobs into a JavaScript ArrayBuffer

Change this:

```<code>  handleData(data) {
    const videoStream = JSON.parse(data);
    if (videoStream.msg === "videoStream") {
      this.blobArr.push(videoStream.chunk.data);
      if (
        this.mediaStreaming.readyState === "open" &&
        this.buffer &&
        this.buffer.updating === false &&
        this.blobArr.length > 0
      ) {
        console.log(
          "ReadyState [AppendBuffer]: " + this.mediaStreaming.readyState
        );
        this.buffer.appendBuffer(this.blobArr.shift()); // Error message shows at this line!
        document.getElementById("streaming").play();
        console.log("Buffer Updating", this.buffer.updating);
      }
    }
  }
</code>```

Into this:

```<code>  async handleData(event) {
    var buffer = await event.data.arrayBuffer(); // convert the message Blob into an ArrayBuffer
    appendBuffer(buffer);
    document.getElementById("streaming").play();
    console.log("Buffer Updating", this.buffer.updating);
  }
</code>```

The problem is, once you do this, you'll start getting a new error, because there is too much data being passed into the SourceBuffer object on the MediaSource. Since it can't keep up with the input stream, you'll see something similar to the following error:

Failed to execute 'appendBuffer' on 'SourceBuffer': This SourceBuffer is still processing an 'appendBuffer' or 'remove' operation

It seems like we need to "buffer the buffers," as odd as that sounds.

I haven't solved this new error yet. If you find a solution, I would love some help.

Related Reading

SourceBuffer.appendBuffer() MDN Docs

MessageEvent (from WebSocket.onmessage event handler)

Blob.arrayBuffer() method

Exceeding the Buffering Quota (Google Dev Docs)

Body:
Edit: To help illustrate the error I keep getting I have created a CodePen of the issue I am seeing. Open up the console and you will see the error. [https://codepen.io/FifthCloud/pen/eYpqJLN]

I wanted to design my own streaming camera service in my home using React/Node. So far I have gone a long way with a Client/Server approach. The server is a raspberry pi with camera attached to it. Using FFMpeg I can see all the video from it and using websockets I can successfully send the data (I mean I see the data being sent to the client will get into why it will not render).

The issue I am running into is why cannot I append the data to the buffer. For starters, I am using this demo about Media Source as a guide and example on what I am supposed to be doing. http://nickdesaulniers.github.io/netfix/demo/bufferAll.html I got this link from my research about Media Source's here: https://developer.mozilla.org/en-US/docs/Web/API/MediaSource/readyState
Also would like to mention that I have received a lot of inspiration from this post and got really far because of this answer HTML5 Video: Streaming Video with Blob URLs

With that in mind I can successfully create a MediaSource and open the buffer, but what I cannot understand is why am I unable to append to the buffer? The error I am recieving is this:

TypeError: Failed to execute 'appendBuffer' on 'SourceBuffer': No function was found that matched the signature provided.

The client side code is the following

class ProductDetail extends React.Component {
  constructor(props) {
    super(props);
    this.handleData = this.handleData.bind(this);
    this.handleOpen = this.handleOpen.bind(this);
    this.appendToSourceBuffer = this.appendToSourceBuffer.bind(this);
    this.mediaStreaming = new MediaSource();
    this.blobArr = [];
    this.buffer = null;
    this.myRef = React.createRef();

    console.log("buffer initialized");
    console.log("ReadyState [Initialized]: " + this.mediaStreaming.readyState);
    this.state = {
      msg: "",
      stream: "",
      streaming: URL.createObjectURL(this.mediaStreaming),
    };
  }

  componentDidMount() {
    this.mediaStreaming.addEventListener("sourceopen", () => {
      console.log(
        "ReadyState [Source Open]: " + this.mediaStreaming.readyState
      );
      this.buffer = this.mediaStreaming.addSourceBuffer(
        'video/mp4;codecs="avc1.42E01E"'
      );
      this.buffer.addEventListener("updateend", () => {
        this.mediaStreaming.endOfStream();
        document.getElementById("streaming").play();
        console.log(
          "ReadyState [UpdateEnd]: " + this.mediaStreaming.readyState
        );
      });
    });
  }

  handleData(data) {
    const videoStream = JSON.parse(data);
    if (videoStream.msg === "videoStream") {
      this.blobArr.push(videoStream.chunk.data);
      if (
        this.mediaStreaming.readyState === "open" &&
        this.buffer &&
        this.buffer.updating === false &&
        this.blobArr.length > 0
      ) {
        console.log(
          "ReadyState [AppendBuffer]: " + this.mediaStreaming.readyState
        );
        this.buffer.appendBuffer(this.blobArr.shift()); // Error message shows at this line!
        document.getElementById("streaming").play();
        console.log("Buffer Updating", this.buffer.updating);
      }
    }
  }

  handleOpen() {
    console.log("Status: connected");
  }

  handleClose() {
    console.log("Status: disconnected");
  }

  render() {
    return (

        <Websocket
          url="ws://192.168.1.20:5000"
          onMessage={this.handleData}
          onOpen={this.handleOpen}
          onClose={this.handleClose}
          reconnect={true}
          debug={true}
          ref={(Websocket) => {
            this.refWebSocket = Websocket;
          }}
          protocol="stream-protocol"
        />
        <video width="640" height="480" id="streaming" controls autoPlay>
          <source
            ref={this.myRef}
            src={this.state.streaming}
            type="video/mp4"
          />
          Your browser does not support the video tag.
        </video>

    );
  }
}

The error comes from the handleData event from my WebSocket when the server is sending the next streaming byte array data.

As I mentioned about the example and the guide from the link I have posted I looked at their code and stepped through it. According to them Append Buffer should work fine, however even in their code appendbuffer() is only listed in the proto section see here:https://drive.google.com/open?id=1vOU4oM-XoKe71DofQuLU2THxMdgiown_ and yet the code doesn't complain about their appendbuffer(). When I console log my buffer it looks like theirs https://drive.google.com/open?id=1T4Ix-y124NgQJ9xu97xv4U2yFTn2k7vF. What am I missing?

I feel like the answer is very obvious but it is escaping me as to what I am doing wrong.

Body:
I'm building a similar project myself, using several high-end RTSP-enabled IP cameras, and just ran into the same error today. First of all, keep in mind that this API is experimental, according to the Mozilla Developer Network (MDN) documentation (link below).

That being said, I seem to have found the root cause of the issue, even though I'm not a JavaScript expert by any stretch. It turns out that you can't directly pass the "Blob" object from data.data in handleData() into the appendBuffer() method. Instead, you need to convert the Blob to a data type that's supported by the appendBuffer() method first, before passing it in.

Turn you event handler into an async function

Use the Blob.arrayBuffer() to convert the data blobs into a JavaScript ArrayBuffer

Change this:

  handleData(data) {
    const videoStream = JSON.parse(data);
    if (videoStream.msg === "videoStream") {
      this.blobArr.push(videoStream.chunk.data);
      if (
        this.mediaStreaming.readyState === "open" &&
        this.buffer &&
        this.buffer.updating === false &&
        this.blobArr.length > 0
      ) {
        console.log(
          "ReadyState [AppendBuffer]: " + this.mediaStreaming.readyState
        );
        this.buffer.appendBuffer(this.blobArr.shift()); // Error message shows at this line!
        document.getElementById("streaming").play();
        console.log("Buffer Updating", this.buffer.updating);
      }
    }
  }

Into this:

  async handleData(event) {
    var buffer = await event.data.arrayBuffer(); // convert the message Blob into an ArrayBuffer
    appendBuffer(buffer);
    document.getElementById("streaming").play();
    console.log("Buffer Updating", this.buffer.updating);
  }

The problem is, once you do this, you'll start getting a new error, because there is too much data being passed into the SourceBuffer object on the MediaSource. Since it can't keep up with the input stream, you'll see something similar to the following error:

Failed to execute 'appendBuffer' on 'SourceBuffer': This SourceBuffer is still processing an 'appendBuffer' or 'remove' operation

It seems like we need to "buffer the buffers," as odd as that sounds.

I haven't solved this new error yet. If you find a solution, I would love some help.

Related Reading

SourceBuffer.appendBuffer() MDN Docs

MessageEvent (from WebSocket.onmessage event handler)

Blob.arrayBuffer() method

Exceeding the Buffering Quota (Google Dev Docs)


问:
Unable to authenticate outlook address via nodemailer
I am trying to authenticate an outlook email account using nodemailer.
But, I continuously get the same message:

{ Error: Invalid login: 535 5.7.3 Authentication unsuccessful [CY1PR03CA0041.namprd03.prod.outlook.com]
      at SMTPConnection._formatError (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:591:19)
      at SMTPConnection._actionAUTHComplete (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:1320:34)
      at SMTPConnection._responseActions.push.str (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:1278:18)
      at SMTPConnection._processResponse (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:747:20)
      at SMTPConnection._onData (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:543:14)
      at TLSSocket._socket.on.chunk (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:694:51)
      at emitOne (events.js:96:13)
      at TLSSocket.emit (events.js:188:7)
      at readableAddChunk (_stream_readable.js:176:18)
      at TLSSocket.Readable.push (_stream_readable.js:134:10)
    code: 'EAUTH',
    response: '535 5.7.3 Authentication unsuccessful [CY1PR03CA0041.namprd03.prod.outlook.com]',
    responseCode: 535,
    command: 'AUTH LOGIN' }

Here is my code for nodemailer:

```<code>const functions = require('firebase-functions');
var nodemailer=require('nodemailer')

var transporter = nodemailer.createTransport("SMTP", {
auth: {
  user: 'username',
  pass: 'password'
},
service: "hotmail"

exports.sendMail
=functions.database.ref('requestedChats').onWrite((event)=>{
const data = {
from: 'username@outlook.com',
to: 'mytest@gmail.com',
subject: 'Hello',
text: 'Test 1235'
}
transporter.sendMail(data, (err, info)=> {
if(err)
  console.log(err)
else
  console.log(info)
})
})'
</code>```

答:
I had the same problem and the issue was this:

I was using credentials provided by my hosting provider. The default setting was that the credentials were secured with GEO security, meaning the credentials wouldn't work outside my country. I was deploying on Heroku whose servers are abroad. That's why I could send emails from localhost but not from deployed app.

After I disabled the GEO security everything worked as it should.

Body:
I am trying to authenticate an outlook email account using nodemailer.
But, I continuously get the same message:

{ Error: Invalid login: 535 5.7.3 Authentication unsuccessful [CY1PR03CA0041.namprd03.prod.outlook.com]
      at SMTPConnection._formatError (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:591:19)
      at SMTPConnection._actionAUTHComplete (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:1320:34)
      at SMTPConnection._responseActions.push.str (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:1278:18)
      at SMTPConnection._processResponse (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:747:20)
      at SMTPConnection._onData (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:543:14)
      at TLSSocket._socket.on.chunk (/user_code/node_modules/nodemailer/lib/smtp-connection/index.js:694:51)
      at emitOne (events.js:96:13)
      at TLSSocket.emit (events.js:188:7)
      at readableAddChunk (_stream_readable.js:176:18)
      at TLSSocket.Readable.push (_stream_readable.js:134:10)
    code: 'EAUTH',
    response: '535 5.7.3 Authentication unsuccessful [CY1PR03CA0041.namprd03.prod.outlook.com]',
    responseCode: 535,
    command: 'AUTH LOGIN' }

Here is my code for nodemailer:

const functions = require('firebase-functions');
var nodemailer=require('nodemailer')

var transporter = nodemailer.createTransport("SMTP", {
auth: {
  user: 'username',
  pass: 'password'
},
service: "hotmail"

exports.sendMail
=functions.database.ref('requestedChats').onWrite((event)=>{
const data = {
from: 'username@outlook.com',
to: 'mytest@gmail.com',
subject: 'Hello',
text: 'Test 1235'
}
transporter.sendMail(data, (err, info)=> {
if(err)
  console.log(err)
else
  console.log(info)
})
})'


问:
Why does my VBA project fail in other computers?
I made a VBA project based on Excel and Access. When I copied to other computers, some methods (left, right, etc) or controls (ComboBox) sometimes disabled. I had to rebuild in that computer. But sometimes it's OK. Why? Is that because of licence issues?</p>

答:
This is a version difference/missing reference issue.
Sometimes it gives you the error on the correct function, and sometimes on completely unrelated functions.

If you are deploying to different versions of Excel you can use late binding instead of early binding to relieve this problem.  When you are developing you can use stuff like

```<code>Dim x As Excel.Application
x = New Excel.Application
</code>```

But for deployment you can change it to the following and then remove the reference altogether.

```<code>Dim x As Object
x = CreateObject("Excel.Application")
</code>```

OwnerDisplayName: unigogo

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: CodeSlave

Body:
This is a version difference/missing reference issue.
Sometimes it gives you the error on the correct function, and sometimes on completely unrelated functions.

If you are deploying to different versions of Excel you can use late binding instead of early binding to relieve this problem.  When you are developing you can use stuff like

Dim x As Excel.Application
x = New Excel.Application

But for deployment you can change it to the following and then remove the reference altogether.

Dim x As Object
x = CreateObject("Excel.Application")

OwnerDisplayName: Will Rickards


问:
Jquery replacing text inside html
Is there a more elegant way replacing a text inside an html element than :</p>

```<code>$el = $("#myDiv");
$el.html( $el.html().replace("something", "something new") );
</code>```

答:
If I understand:

```<code>oldText = $('#myDiv').html();
$('#myDiv').html( oldText.replace('something','something new') );
</code>```

http://jsfiddle.net/wmgBN/

Title: Jquery replacing text inside html

Body:
Is there a more elegant way replacing a text inside an html element than :

$el = $("#myDiv");
$el.html( $el.html().replace("something", "something new") );

Body:
If I understand:

oldText = $('#myDiv').html();
$('#myDiv').html( oldText.replace('something','something new') );

http://jsfiddle.net/wmgBN/


问:
Error syntax near keyword 'primary' while creating table
Could you help in this error while creating table as below in SQL Server please?

```<code>create table employees (
    employeeid int identity(1,1) not null,
    name varchar(150) null,

    constraint pk_employees
         primary key clustered (employeeid asc)
                     with (statistics_norecompute = off, ignore_dup_key = off) on primary
) on primary
</code>```

I get this error:

Msg 156, Level 15, State 1, Line 2448

  Incorrect syntax near the keyword 'primary'

答:
You have multiple file groups When you create a database in MSSQL Server, where storage is created in multiple places, directories or disks. Each file group can be named. The PRIMARY file group is the default one, which is always created, and so the SQL you've given creates your table ON the PRIMARY file group.

Kindly refer Link click here for link

You can create table without file group name:

```<code>  CREATE TABLE EMPLOYEES (
      EMPLOYEEID INT IDENTITY(1,1) NOT NULL,
      NAME VARCHAR(150) NULL,

      CONSTRAINT PK_EMPLOYEES
           PRIMARY KEY CLUSTERED (EMPLOYEEID ASC)
                       WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF)
  )
</code>```

If You want to mention file group name (You have to write file group name between the brackets):-

```<code>  CREATE TABLE EMPLOYEES (
      EMPLOYEEID INT IDENTITY(1,1) NOT NULL,
      NAME VARCHAR(150) NULL,

      CONSTRAINT PK_EMPLOYEES
           PRIMARY KEY CLUSTERED (EMPLOYEEID ASC)
                       WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
  ) ON [PRIMARY]
</code>```

Body:
Could you help in this error while creating table as below in SQL Server please?

create table employees (
    employeeid int identity(1,1) not null,
    name varchar(150) null,

    constraint pk_employees
         primary key clustered (employeeid asc)
                     with (statistics_norecompute = off, ignore_dup_key = off) on primary
) on primary

I get this error:

Msg 156, Level 15, State 1, Line 2448

  Incorrect syntax near the keyword 'primary'

Body:
You have multiple file groups When you create a database in MSSQL Server, where storage is created in multiple places, directories or disks. Each file group can be named. The PRIMARY file group is the default one, which is always created, and so the SQL you've given creates your table ON the PRIMARY file group.

Kindly refer Link click here for link

You can create table without file group name:

  CREATE TABLE EMPLOYEES (
      EMPLOYEEID INT IDENTITY(1,1) NOT NULL,
      NAME VARCHAR(150) NULL,

      CONSTRAINT PK_EMPLOYEES
           PRIMARY KEY CLUSTERED (EMPLOYEEID ASC)
                       WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF)
  )

If You want to mention file group name (You have to write file group name between the brackets):-

  CREATE TABLE EMPLOYEES (
      EMPLOYEEID INT IDENTITY(1,1) NOT NULL,
      NAME VARCHAR(150) NULL,

      CONSTRAINT PK_EMPLOYEES
           PRIMARY KEY CLUSTERED (EMPLOYEEID ASC)
                       WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
  ) ON [PRIMARY]


问:
How to set a variable before calling default constructor in java?
I have the following class:

```<code>public class MyGLSurfaceView extends GLSurfaceView {

    MyRenderer mRenderer;

    public MyGLSurfaceView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }
</code>```

I want to add the following constructor:

```<code>public MyGLSurfaceView(Context context, MyRenderer myRenderer) {
</code>```

I tried:

```<code>public class MyGLSurfaceView extends GLSurfaceView {

    MyRenderer mRenderer;
    static AttributeSet attributeSet = null;

    public MyGLSurfaceView(Context context, MyRenderer mRenderer) {
        this.mRenderer = mRenderer;
        this(context, attributeSet);

    }

    public MyGLSurfaceView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }
</code>```

but it wont let me set the renderer before calling the default constructor of MyGLSurfaceView.

How to set a variable before calling the default constructor?

答: You cant do that since you dont have a object. You can set attribute in a class after you instantiate one of its type.</p>

Body:
I have the following class:

public class MyGLSurfaceView extends GLSurfaceView {

    MyRenderer mRenderer;

    public MyGLSurfaceView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }

I want to add the following constructor:

public MyGLSurfaceView(Context context, MyRenderer myRenderer) {

I tried:

public class MyGLSurfaceView extends GLSurfaceView {

    MyRenderer mRenderer;
    static AttributeSet attributeSet = null;

    public MyGLSurfaceView(Context context, MyRenderer mRenderer) {
        this.mRenderer = mRenderer;
        this(context, attributeSet);

    }

    public MyGLSurfaceView(Context context, AttributeSet attributeSet) {
        super(context, attributeSet);
        init();
    }

but it wont let me set the renderer before calling the default constructor of MyGLSurfaceView.

How to set a variable before calling the default constructor?


问:
Problems with reading and writing to text files in python
I am trying to take an input and write the input to a text file to keep it stored. However, I can't seem to get the user input written over to the text file. Here is my code:

```<code>SaveUsername = open(r"C:\Users\Ty\Desktop\Login_sys\SaveUsername.txt","w+")
SavePassword = open(r"C:\Users\Ty\Desktop\Login_sys\SavePassword.txt","w+")
NewUsername = input("Please enter a username: ")
NewPassword = input("Please enter a password: ")
SaveUsername.write(NewUsername)
print (SaveUsername.readline())
SavePassword.write(NewPassword)
print (SavePassword.readline())
</code>```

I am printing the readline to see if the code gets written and it never does.  Please help, thanks.

答:
Try This</p>

```<code>with open(r"SaveUsername.txt","w+") as SaveUsername:
    NewUsername = input("Please enter a username: ")
    SaveUsername.write(NewUsername)

with open(r"SavePassword.txt","w+") as SavePassword:
    NewPassword = input("Please enter a password: ")
    SavePassword.write(NewPassword)

with open(r"SaveUsername.txt" as SaveUsername:
    print (SaveUsername.readline())

with open(r"SavePassword.txt") as SavePassword:
    print (SavePassword.readline())
</code>```

Body:
I am trying to take an input and write the input to a text file to keep it stored. However, I can't seem to get the user input written over to the text file. Here is my code:

SaveUsername = open(r"C:\Users\Ty\Desktop\Login_sys\SaveUsername.txt","w+")
SavePassword = open(r"C:\Users\Ty\Desktop\Login_sys\SavePassword.txt","w+")
NewUsername = input("Please enter a username: ")
NewPassword = input("Please enter a password: ")
SaveUsername.write(NewUsername)
print (SaveUsername.readline())
SavePassword.write(NewPassword)
print (SavePassword.readline())

I am printing the readline to see if the code gets written and it never does.  Please help, thanks.

Body:
Try This

with open(r"SaveUsername.txt","w+") as SaveUsername:
    NewUsername = input("Please enter a username: ")
    SaveUsername.write(NewUsername)

with open(r"SavePassword.txt","w+") as SavePassword:
    NewPassword = input("Please enter a password: ")
    SavePassword.write(NewPassword)

with open(r"SaveUsername.txt" as SaveUsername:
    print (SaveUsername.readline())

with open(r"SavePassword.txt") as SavePassword:
    print (SavePassword.readline())


问:
How do I know if my serial comms are being closed by GC?
I have a SerialPort object. I have put an event handler on this to monitor disposal, exceptions and received data events:

```<code>mySp.DataReceived += sp_DataReceived;
mySp.ErrorReceived += sp_ErrorReceived;
mySp.Disposed += sp_Disposed;
</code>```

After a few minutes I stop receiving data, but I have good reason to believe this is not an issue with the sender of the serial messages.

I've had issues in this app before with GC disposing things I needed (Threading.Timer objects), so I want to make sure this SerialPort is not being disposed. I attached a Disposed handler, but I've just read GC would not invoke Dispose - so how can I tell if it's GC or an issue elsewhere?

答:
To answer the question "how do I know if my objects are collected":

Inspect the code. Ensure that you keep a reference to the object in question.

You can wrap the object and add a finalizer to the wrapper. If you reach the finalizer you know your object is about to be collected.

Use a memory profiler. This lets you capture a snapshot and search for the number of objects in memory. That way you can see if whatever object you use exists or not. I'm not aware of any competent free alternative, but there are often trial versions of the commercial systems.

Other things to keep in mind:

Ensure you watch for any exceptions and other faults that occur. Some APIs have events or other extension points where you can listen for problems. This might reveal if there is some internal problem causing the messages to stop.

Not sure what you are using for serial communication, but some libraries or even drivers can be unreliable. It might be an idea to switch versions or even hardware to see if this avoids the problem.

Body:
I have a SerialPort object. I have put an event handler on this to monitor disposal, exceptions and received data events:

mySp.DataReceived += sp_DataReceived;
mySp.ErrorReceived += sp_ErrorReceived;
mySp.Disposed += sp_Disposed;

After a few minutes I stop receiving data, but I have good reason to believe this is not an issue with the sender of the serial messages.

I've had issues in this app before with GC disposing things I needed (Threading.Timer objects), so I want to make sure this SerialPort is not being disposed. I attached a Disposed handler, but I've just read GC would not invoke Dispose - so how can I tell if it's GC or an issue elsewhere?


问:
Am I using file_get_contents properly?
Lately, I was messing around with HTML and PHP (which I just started to learn).
I found out, that I can use file_get_contents to fetch the contents of a text file.
So I copied the contents of my HTML file in a plain PHP file and just replaced the text, which was written in the HTML with

```<code>  <?PHP
    $name = file_get_contents('this.txt');
    echo $name;
  ?>
</code>```

I wondered If I could still use the links I which where embedded in the text. I could.

```<code><a href="https://optifine.net/downloads" target="_blank">Optifine</a>
</code>```

This is in the .txt file and works.
But now I don't know if this is the "right" way of doing it.
Obviously it works, but does it always work or is there a better way?

edit/extension:

file_get_contens:

expection: gets the pure contents form a file without prosessing e.g. links etc.

reality: fetches the text from the txt file and handles it as a html file thus prossessingthe links thus showing them properly

include:

expection: gets filecontents and prosesses file according to its extension.

reality: gets contents from textfile and prosesses it as an html file thus showing the links properly.

WHY

答:
file_get_contents() is to fetch data form a file into a variable.

What you want to do is "include" the content from a file into your current file. For that, you should use either include (it won't crash if the file doesn't exist but a warning) or require (it will crash if the file doesn't exist).

<?php
include 'this.html';
```

As you mention that you are new in PHP, I suggest you learn:

How composer works.

How to do a proper separation between the logic and the view in order to decouple the view from the logic behind that produces the data that need to be rendered.

Learning Symfony (or Laravel) framework will help you to understand these concepts very easily :)

Title: Am I using file_get_contents properly?

Body:
Lately, I was messing around with HTML and PHP (which I just started to learn).
I found out, that I can use file_get_contents to fetch the contents of a text file.
So I copied the contents of my HTML file in a plain PHP file and just replaced the text, which was written in the HTML with

  <?PHP
    $name = file_get_contents('this.txt');
    echo $name;
  ?>

I wondered If I could still use the links I which where embedded in the text. I could.

Optifine

This is in the .txt file and works.
But now I don't know if this is the "right" way of doing it.
Obviously it works, but does it always work or is there a better way?

edit/extension:

file_get_contens:

expection: gets the pure contents form a file without prosessing e.g. links etc.

reality: fetches the text from the txt file and handles it as a html file thus prossessingthe links thus showing them properly

include:

expection: gets filecontents and prosesses file according to its extension.

reality: gets contents from textfile and prosesses it as an html file thus showing the links properly.

WHY

Body:
file_get_contents() is to fetch data form a file into a variable.

What you want to do is "include" the content from a file into your current file. For that, you should use either include (it won't crash if the file doesn't exist but a warning) or require (it will crash if the file doesn't exist).

<?php
include 'this.html';

As you mention that you are new in PHP, I suggest you learn:

How composer works.

How to do a proper separation between the logic and the view in order to decouple the view from the logic behind that produces the data that need to be rendered.

Learning Symfony (or Laravel) framework will help you to understand these concepts very easily :)


答:
```<code>$('#myDiv').html(function(index, oldhtml) {
    return oldhtml.replace('something', 'something new');
});
</code>```

Title: Jquery replacing text inside html


问:
Swift Expandable tableView cell buttons are not appearing upon scrolling down
When scrolling off the screen with my custom cell in an expanded state the buttons are being hidden which should not be the case. Beneath the labels, 2 buttons are not appearing when scrolling up again. I'm guessing something needs to happen after the cell has been dequeued. Any help would be much appreciated.

I have a custom cell where initially the height for a row is 80, upon clicking on the cell it expands to 120. By default I have the buttons hidden like so:

```<code>    @IBOutlet weak var followButton: UIButton! {
        didSet {
            followButton.isHidden = true
        }
    }

    @IBOutlet weak var blockButton: UIButton! {
        didSet {
            blockButton.isHidden = true
        }
    }
</code>```

I have an var expandedIndexSet : IndexSet = [] which tracks which cell has been expanded.
The method below updates indexSet accordingly.

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        tableView.beginUpdates()
        let cell = tableView.cellForRow(at: indexPath) as! StackOverflowTableViewCell

        if(expandedIndexSet.contains(indexPath.row)){
            expandedIndexSet.remove(indexPath.row)
        } else {
            expandedIndexSet.insert(indexPath.row)
        }

        cell.blockButton.isHidden = !cell.blockButton.isHidden
        cell.followButton.isHidden = !cell.followButton.isHidden

        tableView.endUpdates()
    }
</code>```

The height gets adjusted like so:

```<code>    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if expandedIndexSet.contains(indexPath.row) {
            return 140
        }
        else {
            return 80
        }
    }

</code>```

答:
The following snippet might be helpful, please try.</p>

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = ....

         cell.followButton.isHidden = !expandedIndexSet.contains(indexPath.row)
         cell.blockButton.isHidden = cell.followButton.isHidden

         return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        // Update View Model
        if(expandedIndexSet.contains(indexPath.row)){
            expandedIndexSet.remove(indexPath.row)
        } else {
            expandedIndexSet.insert(indexPath.row)
        }

        // Table View Animation
        tableView.beginUpdates()
        tableView.reloadRows(at: indexPaths, with: .automatic)
        tableView.endUpdates()
}
</code>```

Body:
When scrolling off the screen with my custom cell in an expanded state the buttons are being hidden which should not be the case. Beneath the labels, 2 buttons are not appearing when scrolling up again. I'm guessing something needs to happen after the cell has been dequeued. Any help would be much appreciated.

I have a custom cell where initially the height for a row is 80, upon clicking on the cell it expands to 120. By default I have the buttons hidden like so:

    @IBOutlet weak var followButton: UIButton! {
        didSet {
            followButton.isHidden = true
        }
    }

    @IBOutlet weak var blockButton: UIButton! {
        didSet {
            blockButton.isHidden = true
        }
    }

I have an var expandedIndexSet : IndexSet = [] which tracks which cell has been expanded.
The method below updates indexSet accordingly.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        tableView.beginUpdates()
        let cell = tableView.cellForRow(at: indexPath) as! StackOverflowTableViewCell

        if(expandedIndexSet.contains(indexPath.row)){
            expandedIndexSet.remove(indexPath.row)
        } else {
            expandedIndexSet.insert(indexPath.row)
        }

        cell.blockButton.isHidden = !cell.blockButton.isHidden
        cell.followButton.isHidden = !cell.followButton.isHidden

        tableView.endUpdates()
    }

The height gets adjusted like so:

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if expandedIndexSet.contains(indexPath.row) {
            return 140
        }
        else {
            return 80
        }
    }

Body:
The following snippet might be helpful, please try.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
         let cell = ....

         cell.followButton.isHidden = !expandedIndexSet.contains(indexPath.row)
         cell.blockButton.isHidden = cell.followButton.isHidden

         return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        // Update View Model
        if(expandedIndexSet.contains(indexPath.row)){
            expandedIndexSet.remove(indexPath.row)
        } else {
            expandedIndexSet.insert(indexPath.row)
        }

        // Table View Animation
        tableView.beginUpdates()
        tableView.reloadRows(at: indexPaths, with: .automatic)
        tableView.endUpdates()
}


问:
Is a std::function member variable of the class type allowed (incomplete type)?
I am wondering if this is fine to do, it compiles fine for me but I am not sure if it actually is ok:

```<code>class Foo {
  std::function<Foo(Foo& f)> my_function;
};
</code>```

The function my_function takes a Foo reference and returns a Foo. It is a member variable inside Foo, and usually these incomplete types are not allowed. For example:

```<code>class Foo {
   std::vector<Foo> foos;
};
</code>```

Would not work I don't think (a benefit of boost is that it does work for boost::container::vector).

答:
It is true that, in general, it is invalid to instantiate templates from the standard library with arguments that are incomplete types:

[res.on.functions]/2 In particular, the effects are undefined in the following cases:

  (2.5) — if an incomplete type (6.9) is used as a template argument when instantiating a template component, unless specifically allowed for that component.

However, Foo(Foo& f) is not an incomplete type, even if Foo is:

[basic.types]/5 A class that has been declared but not defined, an enumeration type in certain contexts (10.2), or an array of unknown bound or of incomplete element type, is an incompletely-defined object type. Incompletely-defined object types and cv void are incomplete types...

Foo(Foo& f) is a function type. It's not listed in this definition, so cannot possibly be incomplete.

std::vector is specifically allowed to be instantiated with an argument that is an incomplete type:

[vector.overview]/3 An incomplete type T may be used when instantiating vector if the allocator satisfies the allocator completeness requirements (20.5.3.5.1). T shall be complete before any member of the resulting specialization of vector is referenced.

Body:
I am wondering if this is fine to do, it compiles fine for me but I am not sure if it actually is ok:

class Foo {
  std::function<Foo(Foo& f)> my_function;
};

The function my_function takes a Foo reference and returns a Foo. It is a member variable inside Foo, and usually these incomplete types are not allowed. For example:

class Foo {
   std::vector<Foo> foos;
};

Would not work I don't think (a benefit of boost is that it does work for boost::container::vector).


问:
How to clear cookies when error deserialize a user using passport.js?
When I use passport.deserializeUser handler:

```<code>passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});
</code>```

If done was called with an err, do I got a chance to clear the cookies and redirect users to /login page? Does that functionality depends on the strategy I'm using? E.g. using failureRedirect option of local strategy?

答:
Like @amanuel2 noted, you can use req to destroy the session.  Passport will pass req to deserializeUser if you ask for it:

```<code>passport.deserializeUser(function(req, id, done) {
    User.findById(id, function(err, user) {
        if (err) {
            req.session.destroy(function() {
               return done(err)
            }
        }
        done(null, user);
    });
});
</code>```

So you can destroy the session, redirect, etc if there is a problem deserializing the session.

Body:
When I use passport.deserializeUser handler:

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

If done was called with an err, do I got a chance to clear the cookies and redirect users to /login page? Does that functionality depends on the strategy I'm using? E.g. using failureRedirect option of local strategy?

Body:
Like @amanuel2 noted, you can use req to destroy the session.  Passport will pass req to deserializeUser if you ask for it:

passport.deserializeUser(function(req, id, done) {
    User.findById(id, function(err, user) {
        if (err) {
            req.session.destroy(function() {
               return done(err)
            }
        }
        done(null, user);
    });
});

So you can destroy the session, redirect, etc if there is a problem deserializing the session.


问:
Pandas handling local time change slow for `read_csv`
When reading from a large CSV file with a change in the time zone offset (daylight saving) the parse_dates becomes slow. Can you suggest how I should handle this? For some work, I do convert to 'UTC' but I also need to work with the original local time. Is there a way to force the parsing of the column to datetime64[ns] and not  datetime64[ns, <offset>]? I think that adding the column time offset might have been an improvement https://github.com/pandas-dev/pandas/issues/16898. I might need the original naive timestamp.

```<code>pd.__version__
'0.24.2'
</code>```

With time offset change

```<code>import pandas as pd
from io import StringIO

data = StringIO("""date_time
2018-11-27 04:57:10+01:00
2018-11-27 04:57:10+02:00
2018-11-27 04:57:10+02:00
2018-11-27 04:57:10+02:00""")

df = pd.read_csv(data, sep=",", parse_dates =['date_time'])
</code>```

Output

```<code>df.date_time

0    2018-11-27 04:57:10+01:00
1    2018-11-27 04:57:10+02:00
2    2018-11-27 04:57:10+02:00
3    2018-11-27 04:57:10+02:00
Name: date_time, dtype: object
</code>```

I think I want dtype: datetime64[ns]

No time offset change

```<code>import pandas as pd
from io import StringIO

data = StringIO("""date_time
2018-11-27 04:57:10+02:00
2018-11-27 04:57:10+02:00
2018-11-27 04:57:10+02:00
2018-11-27 04:57:10+02:00""")

df = pd.read_csv(data, sep=",", parse_dates =['date_time'])
</code>```

Output

```<code>df.date_time

0   2018-11-27 04:57:10+02:00
1   2018-11-27 04:57:10+02:00
2   2018-11-27 04:57:10+02:00
3   2018-11-27 04:57:10+02:00
Name: date_time, dtype: datetime64[ns, pytz.FixedOffset(120)]
</code>```

答:
When your data changes hour offset in the middle, a regular string-based parsing approach will simply relay those offset changes as different unnamed time zones. The issue with Pandas is that it can't represent a column as containing more than one time zone, instead representing the column as object. To fix this, we need to explicitly convert each value to a single named time zone. This enables Pandas to use, e.g., datetime64[ns, America/New_York] as the type for the column, which it will do automatically if all the values in the column have the same time zone. The changing hour offsets are defined by that time zone definition, so the information is preserved. The downside is that you have to know the named time zone to go with your data.

I've played with a few approaches to evaluate the speed differences. For whatever reason, the built-in Pandas function to_datetime() is very slow. I would, instead, suggest an alternative approach depending on your data, performing the text-to-datetime conversion yourself. Create a Python datetime object in your favorite way, apply a time zone, then convert to Pandas Timestamp type. If you're comfortable with the external ciso8601 library, which has fast string-to-ISO8601 parsing, you can use the approach below. You'll also need the popular pytz library with its time zone definitions.

Let's assume you have a CSV file named filename and it has a Timestamp column with ISO8601 timestamps in it.

import ciso8601
import pandas as pd
import pytz

TIME_ZONE = 'America/New_York'

def custom_parse(val):
    iso_time = ciso8601.parse_datetime(val)
    tz_time = iso_time.astimezone(pytz.timezone(TIME_ZONE))
    pd_time = pd.Timestamp(tz_time)
    return pd_time

dt = pd.read_csv(filename, parse_dates=['Timestamp'], date_parser=custom_parse)
```

If you don't want to use ciso8601, you could substitute the iso_time = step with a regex-based parsing step, or datetime.datetime.strptime(), etc. Almost anything will be faster than to_datetime() provided by Pandas.

Body:
When reading from a large CSV file with a change in the time zone offset (daylight saving) the parse_dates becomes slow. Can you suggest how I should handle this? For some work, I do convert to 'UTC' but I also need to work with the original local time. Is there a way to force the parsing of the column to datetime64[ns] and not  datetime64[ns, <offset>]? I think that adding the column time offset might have been an improvement https://github.com/pandas-dev/pandas/issues/16898. I might need the original naive timestamp.

pd.__version__
'0.24.2'

With time offset change

import pandas as pd
from io import StringIO

data = StringIO("""date_time
2018-11-27 04:57:10+01:00
2018-11-27 04:57:10+02:00
2018-11-27 04:57:10+02:00
2018-11-27 04:57:10+02:00""")

df = pd.read_csv(data, sep=",", parse_dates =['date_time'])

Output

df.date_time

0    2018-11-27 04:57:10+01:00
1    2018-11-27 04:57:10+02:00
2    2018-11-27 04:57:10+02:00
3    2018-11-27 04:57:10+02:00
Name: date_time, dtype: object

I think I want dtype: datetime64[ns]

No time offset change

import pandas as pd
from io import StringIO

data = StringIO("""date_time
2018-11-27 04:57:10+02:00
2018-11-27 04:57:10+02:00
2018-11-27 04:57:10+02:00
2018-11-27 04:57:10+02:00""")

df = pd.read_csv(data, sep=",", parse_dates =['date_time'])

Output

df.date_time

0   2018-11-27 04:57:10+02:00
1   2018-11-27 04:57:10+02:00
2   2018-11-27 04:57:10+02:00
3   2018-11-27 04:57:10+02:00
Name: date_time, dtype: datetime64[ns, pytz.FixedOffset(120)]

Body:
When your data changes hour offset in the middle, a regular string-based parsing approach will simply relay those offset changes as different unnamed time zones. The issue with Pandas is that it can't represent a column as containing more than one time zone, instead representing the column as object. To fix this, we need to explicitly convert each value to a single named time zone. This enables Pandas to use, e.g., datetime64[ns, America/New_York] as the type for the column, which it will do automatically if all the values in the column have the same time zone. The changing hour offsets are defined by that time zone definition, so the information is preserved. The downside is that you have to know the named time zone to go with your data.

I've played with a few approaches to evaluate the speed differences. For whatever reason, the built-in Pandas function to_datetime() is very slow. I would, instead, suggest an alternative approach depending on your data, performing the text-to-datetime conversion yourself. Create a Python datetime object in your favorite way, apply a time zone, then convert to Pandas Timestamp type. If you're comfortable with the external ciso8601 library, which has fast string-to-ISO8601 parsing, you can use the approach below. You'll also need the popular pytz library with its time zone definitions.

Let's assume you have a CSV file named filename and it has a Timestamp column with ISO8601 timestamps in it.

import ciso8601
import pandas as pd
import pytz

TIME_ZONE = 'America/New_York'

def custom_parse(val):
    iso_time = ciso8601.parse_datetime(val)
    tz_time = iso_time.astimezone(pytz.timezone(TIME_ZONE))
    pd_time = pd.Timestamp(tz_time)
    return pd_time

dt = pd.read_csv(filename, parse_dates=['Timestamp'], date_parser=custom_parse)

If you don't want to use ciso8601, you could substitute the iso_time = step with a regex-based parsing step, or datetime.datetime.strptime(), etc. Almost anything will be faster than to_datetime() provided by Pandas.