问:
HostPath assign persistentVolume to the specific work node in cluster
Using kubeadm to create a cluster, I have a master and work node.

Now I want to share a persistentVolume in the work node, which will be bound with Postgres pod.

Expecting the code will create persistentVolume in the path /postgres of work node, but it seems the hostPath will not work in a cluster, how should I assign this property to the specific node?

```<code>kind: PersistentVolume
apiVersion: v1
metadata:
  name: pv-postgres
  labels:
    type: local
spec:
  capacity:
    storage: 2Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/postgres"
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: pvc-postgres
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  selector:
    matchLabels:
      app: postgres
  replicas: 1
  strategy: {}
  template:
    metadata:
      labels:
        app: postgres
    spec:
      dnsPolicy: ClusterFirstWithHostNet
      hostNetwork: true
      volumes:
      - name: vol-postgres
        persistentVolumeClaim:
          claimName: pvc-postgres
      containers:
      - name: postgres
        image: postgres:12
        imagePullPolicy: Always
        env:
        - name: DB_USER
          value: postgres
        - name: DB_PASS
          value: postgres
        - name: DB_NAME
          value: postgres
        ports:
        - name: postgres
          containerPort: 5432
        volumeMounts:
        - mountPath: "/postgres"
          name: vol-postgres
        livenessProbe:
          exec:
            command:
            - pg_isready
            - -h
            - localhost
            - -U
            - postgres
          initialDelaySeconds: 30
          timeoutSeconds: 5
        readinessProbe:
          exec:
            command:
            - pg_isready
            - -h
            - localhost
            - -U
            - postgres
          initialDelaySeconds: 5
          timeoutSeconds: 1
---
apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  ports:
  - name: postgres
    port: 5432
    targetPort: postgres
  selector:
    app: postgres
</code>```

答:
As per docs.

A hostPath volume mounts a file or directory from the host node’s filesystem into your Pod. This is not something that most Pods will need, but it offers a powerful escape hatch for some applications.

In short, hostPath type refers to node (machine or VM) resource, where you will schedule pod. It mean that you already need to have this folder on this node.
To assign resources to specify node you have to use nodeSelector in your Deployment, PV.

Depends on the scenario, using hostPath is not the best idea, however I will provide below example YAMLs which might show you concept. Based on your YAMLs but with nginx image.

```<code>kind: PersistentVolume
apiVersion: v1
metadata:
  name: pv-postgres
spec:
  capacity:
    storage: 2Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/tmp/postgres" ## this folder need exist on your node. Keep in minds also who have permissions to folder. Used tmp as it have 3x rwx
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - ubuntu18-kubeadm-worker1

---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: pvc-postgres
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  selector:
    matchLabels:
      app: postgres
  replicas: 1
  strategy: {}
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
      - image: nginx
        name: nginx
        volumeMounts:
        - mountPath: /home    ## path to folder inside container
          name: vol-postgres
      affinity:               ## specified affinity to schedule all pods on this specific node with name ubuntu18-kubeadm-worker1
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: kubernetes.io/hostname
                operator: In
                values:
                - ubuntu18-kubeadm-worker1
      dnsPolicy: ClusterFirstWithHostNet
      hostNetwork: true
      volumes:
      - name: vol-postgres
        persistentVolumeClaim:
          claimName: pvc-postgres

persistentvolume/pv-postgres created
persistentvolumeclaim/pvc-postgres created
deployment.apps/postgres created
</code>```

Unfortunately PV is bounded to PVC in 1:1 relationship, so for each time, you would need to create PV and PVC.

However if you are using hostPath it's enough to specify nodeAffinity, volumeMounts and volumes in Deployment YAML without PV and PVC.

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  selector:
    matchLabels:
      app: postgres
  replicas: 1
  strategy: {}
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
      - image: nginx:latest
        name: nginx
        volumeMounts:
        - mountPath: /home
          name: vol-postgres
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: kubernetes.io/hostname
                operator: In
                values:
                - ubuntu18-kubeadm-worker1
      dnsPolicy: ClusterFirstWithHostNet
      hostNetwork: true
      volumes:
      - name: vol-postgres
        hostPath:
          path: /tmp/postgres

deployment.apps/postgres created

user@ubuntu18-kubeadm-master:~$ kubectl get pods
NAME                        READY   STATUS    RESTARTS   AGE
postgres-77bc9c4566-jgxqq   1/1     Running   0          9s
user@ubuntu18-kubeadm-master:~$ kk exec -ti postgres-77bc9c4566-jgxqq /bin/bash
root@ubuntu18-kubeadm-worker1:/# cd home
root@ubuntu18-kubeadm-worker1:/home# ls
test.txt  txt.txt
</code>```

Body:
Using kubeadm to create a cluster, I have a master and work node.

Now I want to share a persistentVolume in the work node, which will be bound with Postgres pod.

Expecting the code will create persistentVolume in the path /postgres of work node, but it seems the hostPath will not work in a cluster, how should I assign this property to the specific node?

kind: PersistentVolume
apiVersion: v1
metadata:
  name: pv-postgres
  labels:
    type: local
spec:
  capacity:
    storage: 2Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/postgres"
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: pvc-postgres
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  selector:
    matchLabels:
      app: postgres
  replicas: 1
  strategy: {}
  template:
    metadata:
      labels:
        app: postgres
    spec:
      dnsPolicy: ClusterFirstWithHostNet
      hostNetwork: true
      volumes:
      - name: vol-postgres
        persistentVolumeClaim:
          claimName: pvc-postgres
      containers:
      - name: postgres
        image: postgres:12
        imagePullPolicy: Always
        env:
        - name: DB_USER
          value: postgres
        - name: DB_PASS
          value: postgres
        - name: DB_NAME
          value: postgres
        ports:
        - name: postgres
          containerPort: 5432
        volumeMounts:
        - mountPath: "/postgres"
          name: vol-postgres
        livenessProbe:
          exec:
            command:
            - pg_isready
            - -h
            - localhost
            - -U
            - postgres
          initialDelaySeconds: 30
          timeoutSeconds: 5
        readinessProbe:
          exec:
            command:
            - pg_isready
            - -h
            - localhost
            - -U
            - postgres
          initialDelaySeconds: 5
          timeoutSeconds: 1
---
apiVersion: v1
kind: Service
metadata:
  name: postgres
spec:
  ports:
  - name: postgres
    port: 5432
    targetPort: postgres
  selector:
    app: postgres

Body:
As per docs.

A hostPath volume mounts a file or directory from the host node’s filesystem into your Pod. This is not something that most Pods will need, but it offers a powerful escape hatch for some applications.

In short, hostPath type refers to node (machine or VM) resource, where you will schedule pod. It mean that you already need to have this folder on this node.
To assign resources to specify node you have to use nodeSelector in your Deployment, PV.

Depends on the scenario, using hostPath is not the best idea, however I will provide below example YAMLs which might show you concept. Based on your YAMLs but with nginx image.

kind: PersistentVolume
apiVersion: v1
metadata:
  name: pv-postgres
spec:
  capacity:
    storage: 2Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/tmp/postgres" ## this folder need exist on your node. Keep in minds also who have permissions to folder. Used tmp as it have 3x rwx
  nodeAffinity:
    required:
      nodeSelectorTerms:
      - matchExpressions:
        - key: kubernetes.io/hostname
          operator: In
          values:
          - ubuntu18-kubeadm-worker1

---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: pvc-postgres
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  selector:
    matchLabels:
      app: postgres
  replicas: 1
  strategy: {}
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
      - image: nginx
        name: nginx
        volumeMounts:
        - mountPath: /home    ## path to folder inside container
          name: vol-postgres
      affinity:               ## specified affinity to schedule all pods on this specific node with name ubuntu18-kubeadm-worker1
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: kubernetes.io/hostname
                operator: In
                values:
                - ubuntu18-kubeadm-worker1
      dnsPolicy: ClusterFirstWithHostNet
      hostNetwork: true
      volumes:
      - name: vol-postgres
        persistentVolumeClaim:
          claimName: pvc-postgres

persistentvolume/pv-postgres created
persistentvolumeclaim/pvc-postgres created
deployment.apps/postgres created

Unfortunately PV is bounded to PVC in 1:1 relationship, so for each time, you would need to create PV and PVC.

However if you are using hostPath it's enough to specify nodeAffinity, volumeMounts and volumes in Deployment YAML without PV and PVC.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  selector:
    matchLabels:
      app: postgres
  replicas: 1
  strategy: {}
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
      - image: nginx:latest
        name: nginx
        volumeMounts:
        - mountPath: /home
          name: vol-postgres
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: kubernetes.io/hostname
                operator: In
                values:
                - ubuntu18-kubeadm-worker1
      dnsPolicy: ClusterFirstWithHostNet
      hostNetwork: true
      volumes:
      - name: vol-postgres
        hostPath:
          path: /tmp/postgres

deployment.apps/postgres created

user@ubuntu18-kubeadm-master:~$ kubectl get pods
NAME                        READY   STATUS    RESTARTS   AGE
postgres-77bc9c4566-jgxqq   1/1     Running   0          9s
user@ubuntu18-kubeadm-master:~$ kk exec -ti postgres-77bc9c4566-jgxqq /bin/bash
root@ubuntu18-kubeadm-worker1:/# cd home
root@ubuntu18-kubeadm-worker1:/home# ls
test.txt  txt.txt


来源: stackexchange

问:
mongoengine get method does not work for id with string value
I have specified mongoengine model class with _id field as a StringField:

```<code>class Store(DynamicDocument):
    _id = StringField(primary_key=True, min_length=1)
</code>```

And now when I query document by _id field I get document properly:

I can get it by pk too:

but I cannot get it by id:

As you can see at the first screen there's id and pk fields initialized successfully. So I just can't make it out why mongoengine behaves like this. What am I doing wrong?

答:
Try to declare your "_id" as "id":</p>

```<code>class Store(DynamicDocument):
    id = StringField(primary_key=True, min_length=1)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have specified mongoengine model class with _id field as a StringField:

class Store(DynamicDocument):
    _id = StringField(primary_key=True, min_length=1)

And now when I query document by _id field I get document properly:

I can get it by pk too:

but I cannot get it by id:

As you can see at the first screen there's id and pk fields initialized successfully. So I just can't make it out why mongoengine behaves like this. What am I doing wrong?

Body:
Try to declare your "_id" as "id":

class Store(DynamicDocument):
    id = StringField(primary_key=True, min_length=1)


问:
Efficient way to redraw hundreds of particles in flash?
I am just starting to learn flash/actionscript 3 and decided to code up a simple particle simulator.

The very initial design simply involves filling the screen with a buncha particles which scatter away from the cursor if you were to click.

This works, but is a bit unresponsive. I am using graphics.drawCircle() to draw the particles, and each particle is inherited from Sprite.

Listener for mouseclick event:

```<code>private function mouseClick(e:MouseEvent):void
{
    trace("click");
    var now:Date = new Date();
    trace("Before: "+now.getTime());
    for each (var p:Particle in particleList)
    {
        var dist:Number = distance(e.localX,e.localY,p.x,p.y);
        if (dist < 50)
        {
            var xVel:Number = p.x - e.localX;
            var yVel:Number = p.y - e.localY;

            xVel *=  Math.max(0,50 - dist) * 0.05;
            yVel *=  Math.max(0,50 - dist) * 0.05;
            p.xVel +=  xVel;
            p.yVel +=  yVel;
        }
    }

    var later:Date = new Date();
    trace("After: "+later.getTime());
    trace("Total: "+(later.getTime()-now.getTime()));

    //e.
}
</code>```

In Particle, there is a frame listener that runs this every frame:

```<code>public function loop(e:Event):void
{
    if (xVel != 0 || yVel != 0 || setup)
    {
        setup = false;
        x +=  xVel;
        y +=  yVel;

        if (x < 0)
        {
            x = 0;
            xVel =  -  xVel;
        }
        if (x > stageRef.stageWidth)
        {
            x = stageRef.stageWidth;
            xVel =  -  xVel;
        }
        if (y < 0)
        {
            y = 0;
            yVel =  -  yVel;
        }
        if (y > stageRef.stageHeight)
        {
            y = stageRef.stageHeight;
            yVel =  -  yVel;
        }

        graphics.clear();
        graphics.lineStyle(.25,0xFFFFFF,0.5);
        graphics.drawCircle(0,0,1);

        xVel *=  Engine.friction;
        yVel *=  Engine.friction;
    }

    if (xVel < 0.01 && xVel > -0.01)
    {
        xVel = 0;
    }

    if (yVel < 0.01 && yVel > -0.01)
    {
        yVel = 0;
    }
}
</code>```

How should I make this more efficient? I plan on doing collision detection and other physics interactions later, and this is already a bit slow even without the hefty number crunching code I intend to add later.

答:
Using graphics is quite slow for too many shapes... Without much change in your code you could try to, each frame, draw your shapes in a BitmapData (either draw them first in a single shape, or in many shapes, and then use BitmapData draw followed by clearing all your graphics). I think you should get a small improvement. The basic code is this:

```<code>for(...) {
   shape.graphics.drawCircle(0,0,1);
}
bitmapData.draw(shape);
shape.graphics.clear();
</code>```

On the other hand, the fastest way I know for 1 pixel particles is using BitmapData and setPixel for each particle:

```<code>bitmapData.fillRect(bitmapData.rect, 0);
bitmapData.lock();
for(...) {
   bitmapData.setPixel(x,y,0xFFFFFF);
}
bitmapData.unlock();
</code>```

For bigger or more complex particles, I've heard copyPixels is the way to go, but you need to blitt all of your different particles beforehand (I don't have much experience with this one though, and I've found many situations when it has been better to use BitmapData draw, or even having each bitmapData in a different sprite):

```<code>bitmapData.fillRect(bitmapData.rect, 0);
for(...) {
   bitmapData.copyPixels(myParticle10, myParticle10.rect, new Point(tx, ty));
}
</code>```

I hope this helps.

ContentLicense: CC BY-SA 3.0

Body:
I am just starting to learn flash/actionscript 3 and decided to code up a simple particle simulator.

The very initial design simply involves filling the screen with a buncha particles which scatter away from the cursor if you were to click.

This works, but is a bit unresponsive. I am using graphics.drawCircle() to draw the particles, and each particle is inherited from Sprite.

Listener for mouseclick event:

private function mouseClick(e:MouseEvent):void
{
    trace("click");
    var now:Date = new Date();
    trace("Before: "+now.getTime());
    for each (var p:Particle in particleList)
    {
        var dist:Number = distance(e.localX,e.localY,p.x,p.y);
        if (dist < 50)
        {
            var xVel:Number = p.x - e.localX;
            var yVel:Number = p.y - e.localY;

            xVel *=  Math.max(0,50 - dist) * 0.05;
            yVel *=  Math.max(0,50 - dist) * 0.05;
            p.xVel +=  xVel;
            p.yVel +=  yVel;
        }
    }

    var later:Date = new Date();
    trace("After: "+later.getTime());
    trace("Total: "+(later.getTime()-now.getTime()));

    //e.
}

In Particle, there is a frame listener that runs this every frame:

public function loop(e:Event):void
{
    if (xVel != 0 || yVel != 0 || setup)
    {
        setup = false;
        x +=  xVel;
        y +=  yVel;

        if (x < 0)
        {
            x = 0;
            xVel =  -  xVel;
        }
        if (x > stageRef.stageWidth)
        {
            x = stageRef.stageWidth;
            xVel =  -  xVel;
        }
        if (y < 0)
        {
            y = 0;
            yVel =  -  yVel;
        }
        if (y > stageRef.stageHeight)
        {
            y = stageRef.stageHeight;
            yVel =  -  yVel;
        }

        graphics.clear();
        graphics.lineStyle(.25,0xFFFFFF,0.5);
        graphics.drawCircle(0,0,1);

        xVel *=  Engine.friction;
        yVel *=  Engine.friction;
    }

    if (xVel < 0.01 && xVel > -0.01)
    {
        xVel = 0;
    }

    if (yVel < 0.01 && yVel > -0.01)
    {
        yVel = 0;
    }
}

How should I make this more efficient? I plan on doing collision detection and other physics interactions later, and this is already a bit slow even without the hefty number crunching code I intend to add later.

Body:
Using graphics is quite slow for too many shapes... Without much change in your code you could try to, each frame, draw your shapes in a BitmapData (either draw them first in a single shape, or in many shapes, and then use BitmapData draw followed by clearing all your graphics). I think you should get a small improvement. The basic code is this:

for(...) {
   shape.graphics.drawCircle(0,0,1);
}
bitmapData.draw(shape);
shape.graphics.clear();

On the other hand, the fastest way I know for 1 pixel particles is using BitmapData and setPixel for each particle:

bitmapData.fillRect(bitmapData.rect, 0);
bitmapData.lock();
for(...) {
   bitmapData.setPixel(x,y,0xFFFFFF);
}
bitmapData.unlock();

For bigger or more complex particles, I've heard copyPixels is the way to go, but you need to blitt all of your different particles beforehand (I don't have much experience with this one though, and I've found many situations when it has been better to use BitmapData draw, or even having each bitmapData in a different sprite):

bitmapData.fillRect(bitmapData.rect, 0);
for(...) {
   bitmapData.copyPixels(myParticle10, myParticle10.rect, new Point(tx, ty));
}

I hope this helps.


问:
Install SourceTree without an Atlassian account?
I'm trying to use SourceTree for a class that I'm teaching.  In order to do that we need to install SourceTree onto the school's Windows computers.

When we try to install SourceTree (Version 1.9.10.0) it demands an Atlassian account before it will start.  Obviously this is wrong - since we're trying to install SourceTree onto a shared computer (into a VM, to be specific) we don't have just one account (and, on top of that, we're using SourceTree with GitLab, not BitBucket/Atlassian, so we don't need their account anyways).

Is it possible to install SourceTree but skip the 'create an Atlassian account' step during the install process?

(We'd be ok with having the students create accounts later on, when they first start using it - we just don't want all the students to share a single BitBucket account by default)

答: You can create a temp account by using a temp email. Then you can delete the account once its installed and use your own corporation git ids. It is the easiest way.</p>


问:
Desugaring of a Fragment inside a library is failing
I have a fragment VideoPlayerBaseFragment inside a library project.
I am using this library inside my app using artifactory build
implementation

```<code>"com.mindvalley.module_videoplayer:module_videoplayer:1.9.3.6"
</code>```

When I am building my app it is throwing following error :

Default method desugaring of
  com.mindvalley.module_videoplayer.base.fragment.VideoPlayerBaseFragment
  failed because its super class androidx.fragment.app.Fragment is
  missing

My library module implements exoplayer library

api "com.google.android.exoplayer:exoplayer:2.10.5"

I am unable to find the reason for this. It works fine with other libraries I have created and they also have fragment in them.

答:
I also encountered this issue. The solution in my case turned out to be rather simple. I had to disable desugaring with D8 in my project's gradle.properties file. This can be done with the 2 lines below:

```<code>android.enableD8=false
android.enableD8.desugaring=false
</code>```

You can then sync the project files, clean your project and build a debug apk. I encountered this issue when trying to build a debug apk or run instrumentation tests on an emulator running API 16, I never had when building release apk.

Body:
I have a fragment VideoPlayerBaseFragment inside a library project.
I am using this library inside my app using artifactory build
implementation

"com.mindvalley.module_videoplayer:module_videoplayer:1.9.3.6"

When I am building my app it is throwing following error :

Default method desugaring of
  com.mindvalley.module_videoplayer.base.fragment.VideoPlayerBaseFragment
  failed because its super class androidx.fragment.app.Fragment is
  missing

My library module implements exoplayer library

api "com.google.android.exoplayer:exoplayer:2.10.5"

I am unable to find the reason for this. It works fine with other libraries I have created and they also have fragment in them.

Body:
I also encountered this issue. The solution in my case turned out to be rather simple. I had to disable desugaring with D8 in my project's gradle.properties file. This can be done with the 2 lines below:

android.enableD8=false
android.enableD8.desugaring=false

You can then sync the project files, clean your project and build a debug apk. I encountered this issue when trying to build a debug apk or run instrumentation tests on an emulator running API 16, I never had when building release apk.


问:
Python strings, algorithms (like (as in facebook like) system)
Here's what I need to do:
Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:

```<code>likes [] // must be "no one likes this"
likes ["Peter"] // must be "Peter likes this"
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"
</code>```

Here's my code so far, only the 1st and second examples are correct, and I can't figure out how to convert ['Peter'] to 'Peter' and how to only put 'and' in the end(between last two people/values:

```<code>def likes(names):
    if names == []:
        return str("no one likes this")
    elif len(names) == 1:
        return (str(names)) + " likes this"
    elif 1<len(names)<=3:
        return " and ".join(map(str,names)) + " like this"
    else:
        return ", ".join(map(str,names)) + " and " + str(len(names)-2)+" others like this"
</code>```

The output for the first case is:
     "['Peter'] likes this" (should equal 'Peter likes this')
and for the last 2 cases:
    'Max and John and Mark like this' (should equal 'Max, John and Mark like this'),
    'Alex and Jacob and Mark and Max and 2 others like this' (should equal 'Alex, Jacob and 2 others like
    this')

I think I am quite close and would greatly appreciate any clarification!

答:
You might want to look at the str.join() method:

```<code>>>> ",".join(["stack", "overflow"])
>>> 'stack,overflow'
</code>```

And this special case of slicing:

```<code>>>> l = [1,2,3]
>>> l[:-1]
[1, 2]
</code>```

Body:
Here's what I need to do:
Implement a function likes :: [String] -> String, which must take in input array, containing the names of people who like an item. It must return the display text as shown in the examples:

likes [] // must be "no one likes this"
likes ["Peter"] // must be "Peter likes this"
likes ["Jacob", "Alex"] // must be "Jacob and Alex like this"
likes ["Max", "John", "Mark"] // must be "Max, John and Mark like this"
likes ["Alex", "Jacob", "Mark", "Max"] // must be "Alex, Jacob and 2 others like this"

Here's my code so far, only the 1st and second examples are correct, and I can't figure out how to convert ['Peter'] to 'Peter' and how to only put 'and' in the end(between last two people/values:

def likes(names):
    if names == []:
        return str("no one likes this")
    elif len(names) == 1:
        return (str(names)) + " likes this"
    elif 1<len(names)<=3:
        return " and ".join(map(str,names)) + " like this"
    else:
        return ", ".join(map(str,names)) + " and " + str(len(names)-2)+" others like this"

The output for the first case is:
     "['Peter'] likes this" (should equal 'Peter likes this')
and for the last 2 cases:
    'Max and John and Mark like this' (should equal 'Max, John and Mark like this'),
    'Alex and Jacob and Mark and Max and 2 others like this' (should equal 'Alex, Jacob and 2 others like
    this')

I think I am quite close and would greatly appreciate any clarification!

Body:
You might want to look at the str.join() method:

>>> ",".join(["stack", "overflow"])
>>> 'stack,overflow'

And this special case of slicing:

>>> l = [1,2,3]
>>> l[:-1]
[1, 2]


答:
You should consider using Pandas for that.

```<code>python -m pip install pandas
</code>```

Then you need to import pandas to you code.

```<code>import pandas as pd
</code>```

then you need to locate the file and import it as a dataframe.

```<code>df = pd.read_fwf(YOURPATH + 'data.txt')
#And try to print its head to see if import was successfull
print(df.head())
</code>```

At last, you should filter 'ADAM' on the dataframe's first column.

```<code>df.loc[df['column_name'] == ADAM]
</code>```

Title: convert values in text file to array in python

Body:
I have a text file data.txt which looks as such:

ADMAS      8.046E+03 8.206E-03 1.532E+04 1.066E-01 6.982E+06-2.820E+00 \n
ADMAS     -6.868E-03 2.009E+05 1.454E-02 9.516E+05-1.209E+00 6.058E+06 \n
ADMAS      1.543E+04 9.179E-01 1.459E+06 5.463E+00 3.918E+07-2.904E+01 \n
ADMAS     -2.267E-01 9.537E+05 3.902E+00 3.071E+07-1.344E+02 1.073E+08 \n
ADMAS      7.005E+06 2.260E+01 3.978E+07 6.296E+01 7.586E+09-2.125E+03 \n
ADMAS      1.093E+00 6.052E+06-6.178E+00 1.065E+08-1.416E+03 1.941E+09 \n
FAMP       3.824E+03 7.120E-02 1.848E+05 7.317E-01 5.406E+06 4.096E+00 \n
FEPS       9.039E+01 3.571E+02 2.838E+00 3.580E+02 4.098E+01 1.892E+02 \n

(etc. In a recurring pattern). I want to have only the ADMAS values and put them in a 6x6 array.
I tried the following:

filename = "data.txt"
string_fnd_1 = "ADMAS"
textfile = open(filename, 'r')
file_lines = textfile.readlines()
textfile.close()
matches_admas = [line for line in file_lines if string_fnd_1 in line]

I get the following:

['ADMAS      8.046E+03 8.206E-03 1.532E+04 1.066E-01 6.982E+06-2.820E+00\n', 'ADMAS     -6.868E-03 2.009E+05 1.454E-02 9.516E+05-1.209E+00 6.058E+06\n',....]

Now, I want to get rid of the string "ADMAS", convert the values to float and reshape into a 6x6 array. Does someone know how to do this? Help would be appreciated.

Body:
You should consider using Pandas for that.

python -m pip install pandas

Then you need to import pandas to you code.

import pandas as pd

then you need to locate the file and import it as a dataframe.

df = pd.read_fwf(YOURPATH + 'data.txt')
#And try to print its head to see if import was successfull
print(df.head())

At last, you should filter 'ADAM' on the dataframe's first column.

df.loc[df['column_name'] == ADAM]


问:
What is the simplest way to do upsert with Ecto (MySQL)
Doing upsert is common in my app and I want to implement the cleanest and simple way to implement upsert.

Should I use fragments to implement native sql upsert?

Any idiomatic ecto way to do upsert?

答:
In my case insert_or_update raised an error due to the unique index constraint

What did work for me was Postgres v9.5 upsert through on_conflict parameter:

(considering unique column is called user_id)

```<code>changeset
|> MyRepo.insert(
    on_conflict: :replace_all,
    conflict_target: :user_id
)
</code>```

Body:
In my case insert_or_update raised an error due to the unique index constraint

What did work for me was Postgres v9.5 upsert through on_conflict parameter:

(considering unique column is called user_id)

changeset
|> MyRepo.insert(
    on_conflict: :replace_all,
    conflict_target: :user_id
)


问:
svg interfering with the button
I use a svg in the background of my page, but this svg is interfering with the style of a button. The button should be all green, but the svg lines are appearing inside the button.
The svg and the button are in separate divs.
I've tried using z-index to throw svg behind all components, but it didn't work.

How the button looks:

How the button should look:

HTML code:

```<code>export default function LoginPage() {
  return (
    <Container>
      <PositionLoginImage>
        <Login color="#fff" />
      </PositionLoginImage>
      <Content>
        <CardLogin>
          <PositionLogo>
            <Logo color={theme.colors.marketplace} />
          </PositionLogo>
          <PositionInputUser>
            <p>Usuário</p>
            <Input>
              <span>
                <IconUsers color={theme.colors.marketplace} />
              </span>
              <input type="text" placeholder="Usuário" />
            </Input>
          </PositionInputUser>
          <PositionInputPassword>
            <p>Senha</p>
            <Input>
              <span>
                <IconKey color={theme.colors.marketplace} />
              </span>
              <input type="password" placeholder="Senha" />
            </Input>
          </PositionInputPassword>
          <PositionButton>
            <Link to="/dashboard">
              <Button>Entrar</Button>
            </Link>
          </PositionButton>
        </CardLogin>
      </Content>
    </Container>
  );
}
</code>```

CSS:

```<code>const Container = styled.div`
  min-height: 100vh;
  background-color: ${props => props.theme.colors.marketplace};
  display: flex;
  align-items: center;
  justify-content: center;
`;

const Content = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
`;

const PositionLoginImage = styled.div`
  position: absolute;
  top: 147px;
  left: -0.00048828125px;

  svg {
    width: 100vw;
    height: 40vw;
  }
`;

const PositionLogo = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 40px;
`;

const CardLogin = styled.div`
  width: 581px;
  height: 722px;
  background: #fff;
  box-shadow: 0px 4px 16px #455b630f;
  border-radius: 10px;
`;

const PositionInputUser = styled.div`
  display: grid;
  align-items: center;
  justify-content: center;
  margin-top: 90px;

  p {
    font-size: 20px;
    font-weight: 600;
    color: ${props => props.theme.colors.textTitle};
  }
`;

const PositionInputPassword = styled.div`
  display: grid;
  align-items: center;
  justify-content: center;
  margin-top: 35px;

  p {
    font-size: 20px;
    font-weight: 600;
    color: ${props => props.theme.colors.textTitle};
  }
`;

const PositionButton = styled.div`
  display: grid;
  align-items: center;
  justify-content: center;
  margin-top: 90px;
`;

export const Button = styled.button`
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding-top: 4px;
  padding-left: 15px;
  padding-right: 15px;
  width: 206px;
  height: 54px;
  border-radius: 10px;
  border: 1px solid ${props => props.theme.colors.marketplace};
  background-color: ${props => props.theme.colors.marketplace};

  font-size: 18px;
  line-height: 22px;
  color: #fff;
`;

export const Input = styled.div`
  display: grid;
  grid-template-columns: 64px 1fr;
  width: 445px;
  height: 55px;
  border-radius: 10px;

  span {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f8f8f8;
  }

  input {
    background-color: #f8f8f8;
  }

  input::-webkit-input-placeholder {
    color: ${props => props.theme.colors.primary};
    opacity: 0.3;
  }
`;
</code>```

答:
You need to give PositionButton a solid background color, explicitly:

```<code>const PositionButton = styled.div`
  display: grid;
  align-items: center;
  justify-content: center;
  margin-top: 90px;
  background-color: rgb(14, 211, 156);
`;
</code>```

Title: svg interfering with the button

Body:
I use a svg in the background of my page, but this svg is interfering with the style of a button. The button should be all green, but the svg lines are appearing inside the button.
The svg and the button are in separate divs.
I've tried using z-index to throw svg behind all components, but it didn't work.

How the button looks:

How the button should look:

HTML code:

export default function LoginPage() {
  return (
    <Container>
      <PositionLoginImage>
        <Login color="#fff" />
      </PositionLoginImage>
      <Content>
        <CardLogin>
          <PositionLogo>
            <Logo color={theme.colors.marketplace} />
          </PositionLogo>
          <PositionInputUser>

Usuário

            <Input>

                <IconUsers color={theme.colors.marketplace} />

              <input type="text" placeholder="Usuário" />
            </Input>
          </PositionInputUser>
          <PositionInputPassword>

Senha

            <Input>

                <IconKey color={theme.colors.marketplace} />

              <input type="password" placeholder="Senha" />
            </Input>
          </PositionInputPassword>
          <PositionButton>
            <Link to="/dashboard">
              <Button>Entrar</Button>
            </Link>
          </PositionButton>
        </CardLogin>
      </Content>
    </Container>
  );
}

CSS:

const Container = styled.div`
  min-height: 100vh;
  background-color: ${props => props.theme.colors.marketplace};
  display: flex;
  align-items: center;
  justify-content: center;
`;

const Content = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
`;

const PositionLoginImage = styled.div`
  position: absolute;
  top: 147px;
  left: -0.00048828125px;

  svg {
    width: 100vw;
    height: 40vw;
  }
`;

const PositionLogo = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 40px;
`;

const CardLogin = styled.div`
  width: 581px;
  height: 722px;
  background: #fff;
  box-shadow: 0px 4px 16px #455b630f;
  border-radius: 10px;
`;

const PositionInputUser = styled.div`
  display: grid;
  align-items: center;
  justify-content: center;
  margin-top: 90px;

  p {
    font-size: 20px;
    font-weight: 600;
    color: ${props => props.theme.colors.textTitle};
  }
`;

const PositionInputPassword = styled.div`
  display: grid;
  align-items: center;
  justify-content: center;
  margin-top: 35px;

  p {
    font-size: 20px;
    font-weight: 600;
    color: ${props => props.theme.colors.textTitle};
  }
`;

const PositionButton = styled.div`
  display: grid;
  align-items: center;
  justify-content: center;
  margin-top: 90px;
`;

export const Button = styled.button`
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding-top: 4px;
  padding-left: 15px;
  padding-right: 15px;
  width: 206px;
  height: 54px;
  border-radius: 10px;
  border: 1px solid ${props => props.theme.colors.marketplace};
  background-color: ${props => props.theme.colors.marketplace};

  font-size: 18px;
  line-height: 22px;
  color: #fff;
`;

export const Input = styled.div`
  display: grid;
  grid-template-columns: 64px 1fr;
  width: 445px;
  height: 55px;
  border-radius: 10px;

  span {
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #f8f8f8;
  }

  input {
    background-color: #f8f8f8;
  }

  input::-webkit-input-placeholder {
    color: ${props => props.theme.colors.primary};
    opacity: 0.3;
  }
`;

Body:
You need to give PositionButton a solid background color, explicitly:

const PositionButton = styled.div`
  display: grid;
  align-items: center;
  justify-content: center;
  margin-top: 90px;
  background-color: rgb(14, 211, 156);
`;


问:
Blazor: How to change the URL dynamically?
I have a page which takes a string bookingReference as its route parameter Booking/{bookingReference}.

This page is the parent component, with a child component inside where booking details are managed. The child component calls back to the parent when booking details are updated.

```<code>@page "/Booking/{bookingReference}"

<div class="header">
   <h1> @Booking.BookingReference </h1>
</div>

<div>
   <BookingDetails Booking="Booking" OnUpdateBooking="UpdateBooking" />
</div>

@code {

    [Parameter]
    public string BookingReference { get; set; }

    private Booking Booking { get; set; }

    void UpdateBooking(Booking booking)
    {
        Booking = booking;
        StateHasChanged();
    }
}
</code>```

The BookingDetails component looks like this:

```<code><EditForm Model="FormState" OnValidSubmit="@saveChanges">
   //inputs etc.
</EditForm>

@code {
    [Parameter]
    public Booking Booking { get; set; }

    [Parameter]
    public EventCallback<Booking> OnUpdateBooking { get; set; }

private async Task saveChanges()
{
        // update booking object
        Booking.BookingReference = FormState.BookingReference;

        try
        {
            Booking = await BookingService.UpdateBooking(Booking);
            await OnUpdateBooking.InvokeAsync(Booking);
            Toaster.Success("Booking updated successfully");
        }
        catch
        {
            Toaster.Error("Failed to update booking");
        }
    }
}
</code>```

The user can update the booking reference from the child component, and thus, change the header of the page - that works fine, all good.

However, I would also like to change the URL to the updated bookingReference - is there any way I can achieve this without forcing a refresh?

答:
If by "forcing a refresh", you mean reloading the page, then the answer is positive. You don't have to reload your page, but you have to re-render the page in order to refresh the view ( not reloading but re-rendering). When you reload a page, the page component and the embedded components are created anew. When you re-render your page the page components and the embedded components are not destroyed, and only Html diffs are applied to reflect this.

You did not post the code for the BookingDetails component, so my answer here is only based on a guess

```<code><BookingDetails Booking="Booking" OnUpdateBooking="UpdateBooking" />

Your BookingDetails component should define a property named OnUpdateBooking
of type *EventCallback<Booking>* like this:

[Parameter]
public EventCallback<Booking> OnUpdateBooking {get; set;}
</code>```

It also should define a parameter property named Booking, which is an object passed from the parent component.

```<code>// Supporting variable
private Booking booking;

[Parameter]
public Booking Booking
{
  get => booking;
set
{
   if( booking != value)
   {
      booking = value;
      OnUpdateBooking.InvokeAsync(value);
   }
}
</code>```

Note: The Booking property stores the value passed from the parent component. When its value changes by code in the child component, you should invoke the OnUpdateBooking 'delegate', passing it the newly updated value. This value is passed back to the UpdateBooking method defined in the parent component, assign the passed value to the private Booking field, and then re-render the parent page. Now you should see the url changes to reflect this.

Note: Remove the call to StateHasChanged method from the UpdateBooking. It is not necessary.

Body:
I have a page which takes a string bookingReference as its route parameter Booking/{bookingReference}.

This page is the parent component, with a child component inside where booking details are managed. The child component calls back to the parent when booking details are updated.

@page "/Booking/{bookingReference}"

 @Booking.BookingReference

   <BookingDetails Booking="Booking" OnUpdateBooking="UpdateBooking" />

@code {

    [Parameter]
    public string BookingReference { get; set; }

    private Booking Booking { get; set; }

    void UpdateBooking(Booking booking)
    {
        Booking = booking;
        StateHasChanged();
    }
}

The BookingDetails component looks like this:

<EditForm Model="FormState" OnValidSubmit="@saveChanges">
   //inputs etc.
</EditForm>

@code {
    [Parameter]
    public Booking Booking { get; set; }

    [Parameter]
    public EventCallback<Booking> OnUpdateBooking { get; set; }

private async Task saveChanges()
{
        // update booking object
        Booking.BookingReference = FormState.BookingReference;

        try
        {
            Booking = await BookingService.UpdateBooking(Booking);
            await OnUpdateBooking.InvokeAsync(Booking);
            Toaster.Success("Booking updated successfully");
        }
        catch
        {
            Toaster.Error("Failed to update booking");
        }
    }
}

The user can update the booking reference from the child component, and thus, change the header of the page - that works fine, all good.

However, I would also like to change the URL to the updated bookingReference - is there any way I can achieve this without forcing a refresh?

Body:
If by "forcing a refresh", you mean reloading the page, then the answer is positive. You don't have to reload your page, but you have to re-render the page in order to refresh the view ( not reloading but re-rendering). When you reload a page, the page component and the embedded components are created anew. When you re-render your page the page components and the embedded components are not destroyed, and only Html diffs are applied to reflect this.

You did not post the code for the BookingDetails component, so my answer here is only based on a guess

<BookingDetails Booking="Booking" OnUpdateBooking="UpdateBooking" />

Your BookingDetails component should define a property named OnUpdateBooking
of type *EventCallback<Booking>* like this:

[Parameter]
public EventCallback<Booking> OnUpdateBooking {get; set;}

It also should define a parameter property named Booking, which is an object passed from the parent component.

// Supporting variable
private Booking booking;

[Parameter]
public Booking Booking
{
  get => booking;
set
{
   if( booking != value)
   {
      booking = value;
      OnUpdateBooking.InvokeAsync(value);
   }
}

Note: The Booking property stores the value passed from the parent component. When its value changes by code in the child component, you should invoke the OnUpdateBooking 'delegate', passing it the newly updated value. This value is passed back to the UpdateBooking method defined in the parent component, assign the passed value to the private Booking field, and then re-render the parent page. Now you should see the url changes to reflect this.

Note: Remove the call to StateHasChanged method from the UpdateBooking. It is not necessary.


问:
How to properly set HPKP header (Public-Key-Pinning Header)?
I am absolutely confused about the header Public-Key-Pinning. How do you add it in Apache?

What I did:

Took the public key hash from my domain cert, intermediate cert and the root certs separately and added this to apache, mod_headers is enabled. But ssllabs says "No Chain. Check Backup Pins"

```
Header always set Public-Key-Pins "pin-sha256=\"Root-SSL-Public-Key\"; pin-sha256=\"Intermediate-SSL-Public-Key\"; pin-sha256=\"Domain-SSL-Public-Key\"; max-age=2592000; includeSubDomains"
```

答:
HPKP is a bad idea. It’s way too easy to brick your site using it and the protection it provides is fairly small given that.

Almost all browsers have dropped support for HPKP because of this.

One of the things the spec includes to mitigate breaking your site is you must have at least one pin that is NOT in your current cert and chain. That is you must have two completely independent pins - one from a backup key/cert/CA so if you lose control of your primary one you can still connect. If you have only pinned your cert, intermediate and root then they are all from the same chain and so do not meet this requirement.

Fix that and it should be accepted by SSLLabs. But honestly why bother given browser support and the risk versus reward profile?

Body:
I am absolutely confused about the header Public-Key-Pinning. How do you add it in Apache?

What I did:

Took the public key hash from my domain cert, intermediate cert and the root certs separately and added this to apache, mod_headers is enabled. But ssllabs says "No Chain. Check Backup Pins"

Header always set Public-Key-Pins "pin-sha256=\"Root-SSL-Public-Key\"; pin-sha256=\"Intermediate-SSL-Public-Key\"; pin-sha256=\"Domain-SSL-Public-Key\"; max-age=2592000; includeSubDomains"


问:
Exctract html table from dynamically loaded websites
I was developing a script to extract html table from dynamic websites. Below is my script:

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import time
import sys

driver = webdriver.Chrome()
driver.implicitly_wait(20)

URL = 'https://www.ccee.org.br/portal/faces/pages_publico/o-que-fazemos/como_ccee_atua/precos/precos_medios?_adf.ctrl-state=7e1fw5zdn_14&_afrLoop=19197915280379#!%40%40%3F_afrLoop%3D19197915280379%26_adf.ctrl-state%3D7e1fw5zdn_18'

driver.get(URL)
time.sleep(50)
soup = BeautifulSoup(driver.page_source, "html.parser")
table = soup.find('html')

list_of_rows = []
for row in table.findAll('tr'):
    list_of_cells = []
    for cell in row.findAll(["td"]):
        text = cell.text
        list_of_cells.append(text)
    list_of_rows.append(list_of_cells)

for item in list_of_rows:
    ' '.join(item)

Data = pd.DataFrame(list_of_rows)

Data.to_csv('Data.csv' ,index = False)

driver.quit()
</code>```

I have used Selenium to extract but failed to get the table which is in URL web page. When I run this script I get the table as below:

```<code>          0         1         2     3     4     5
0
1                                None  None  None
2                                None  None  None
3                  OK        OK              None
4        OK                None  None  None  None
5                                            None
6                          None  None  None  None
7                                None  None  None
8            OKCancel  OKCancel              None
9  OKCancel                None  None  None  None
</code>```

答:
I have modified your code and I can export the table correctly now.

The main issue was probably that your table is in an iframe which
you need to switch to before any further interaction with the page.

The BeatifulSoup cell.text includes "\n","\t" characters which i
removed using regex

See further comment inline and let me know if you have questions

Solution:

```<code>import pandas as pd
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import re

driver = webdriver.Chrome()
URL = 'https://www.ccee.org.br/portal/faces/pages_publico/o-que-fazemos/como_ccee_atua/precos/precos_medios?_adf.ctrl-state=7e1fw5zdn_14&_afrLoop=19197915280379#!%40%40%3F_afrLoop%3D19197915280379%26_adf.ctrl-state%3D7e1fw5zdn_18'

driver.get(URL)

WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.ID,'pt1:myFrame')))   #wait for iframe to load
iframe=driver.switch_to.frame('pt1:myFrame')

WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.XPATH,"//table//thead/tr/th")))  # wait for table header to load
soup = BeautifulSoup(driver.page_source, "html.parser")
table = soup.find('html')

list_of_rows = []
for row in table.findAll('tr'):
    list_of_cells = []
    for cell in row.findAll(["td"]):
        text = re.sub(r'\n\t+', '', cell.text)   #replace new line and tab with ''
        list_of_cells.append(text)
    list_of_rows.append(list_of_cells)

for item in list_of_rows:
    ' '.join(item)

data = pd.DataFrame(list_of_rows)
data.dropna(axis = 0, how='any', inplace = True)   # drop empty lines
header=['Mes','SE/CO','S','NE','N']
data.to_csv('Datax.csv', header=header, index = False)

driver.quit()
</code>```

Body:
I was developing a script to extract html table from dynamic websites. Below is my script:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import time
import sys

driver = webdriver.Chrome()
driver.implicitly_wait(20)

URL = 'https://www.ccee.org.br/portal/faces/pages_publico/o-que-fazemos/como_ccee_atua/precos/precos_medios?_adf.ctrl-state=7e1fw5zdn_14&_afrLoop=19197915280379#!%40%40%3F_afrLoop%3D19197915280379%26_adf.ctrl-state%3D7e1fw5zdn_18'

driver.get(URL)
time.sleep(50)
soup = BeautifulSoup(driver.page_source, "html.parser")
table = soup.find('html')

list_of_rows = []
for row in table.findAll('tr'):
    list_of_cells = []
    for cell in row.findAll(["td"]):
        text = cell.text
        list_of_cells.append(text)
    list_of_rows.append(list_of_cells)

for item in list_of_rows:
    ' '.join(item)

Data = pd.DataFrame(list_of_rows)

Data.to_csv('Data.csv' ,index = False)

driver.quit()

I have used Selenium to extract but failed to get the table which is in URL web page. When I run this script I get the table as below:

          0         1         2     3     4     5
0
1                                None  None  None
2                                None  None  None
3                  OK        OK              None
4        OK                None  None  None  None
5                                            None
6                          None  None  None  None
7                                None  None  None
8            OKCancel  OKCancel              None
9  OKCancel                None  None  None  None

Body:
I have modified your code and I can export the table correctly now.

The main issue was probably that your table is in an iframe which
you need to switch to before any further interaction with the page.

The BeatifulSoup cell.text includes "\n","\t" characters which i
removed using regex

See further comment inline and let me know if you have questions

Solution:

import pandas as pd
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from bs4 import BeautifulSoup
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import re

driver = webdriver.Chrome()
URL = 'https://www.ccee.org.br/portal/faces/pages_publico/o-que-fazemos/como_ccee_atua/precos/precos_medios?_adf.ctrl-state=7e1fw5zdn_14&_afrLoop=19197915280379#!%40%40%3F_afrLoop%3D19197915280379%26_adf.ctrl-state%3D7e1fw5zdn_18'

driver.get(URL)

WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.ID,'pt1:myFrame')))   #wait for iframe to load
iframe=driver.switch_to.frame('pt1:myFrame')

WebDriverWait(driver, 60).until(EC.visibility_of_element_located((By.XPATH,"//table//thead/tr/th")))  # wait for table header to load
soup = BeautifulSoup(driver.page_source, "html.parser")
table = soup.find('html')

list_of_rows = []
for row in table.findAll('tr'):
    list_of_cells = []
    for cell in row.findAll(["td"]):
        text = re.sub(r'\n\t+', '', cell.text)   #replace new line and tab with ''
        list_of_cells.append(text)
    list_of_rows.append(list_of_cells)

for item in list_of_rows:
    ' '.join(item)

data = pd.DataFrame(list_of_rows)
data.dropna(axis = 0, how='any', inplace = True)   # drop empty lines
header=['Mes','SE/CO','S','NE','N']
data.to_csv('Datax.csv', header=header, index = False)

driver.quit()


问:
Error: Node Sass does not yet support your current environment: Windows 64-bit with false
```<code>E:\A Prem World\Team_Work_Tasks\Anjali\Anjali_20160524\QuizApp_20160524_01_Anj>ionic serve -l
(node:4772) fs: re-evaluating native module sources is not supported. If you are using the graceful-fs module, please update it to a more recent version.
There is an error in your gulpfile:
Error: Node Sass does not yet support your current environment: Windows 64-bit with false
For more information on which environments are supported please see:
TODO URL
    at Object.<anonymous> (E:\A Prem World\Team_Work_Tasks\Anjali\Anjali_20160524\QuizApp_20160524_01_Anj\node_modules\node-sass\lib\index.js:12:11)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:456:32)
    at tryModuleLoad (module.js:415:12)
    at Function.Module._load (module.js:407:3)
    at Module.require (module.js:466:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (E:\A Prem World\Team_Work_Tasks\Anjali\Anjali_20160524\QuizApp_20160524_01_Anj\node_modules\gulp-sass\index.js:187:21)
    at Module._compile (module.js:541:32)
</code>```

答:
I got this error when I updated node using NVM.
to remove this run;
npm rebuild node-sass


问:
Comparing doubles to double literals?

Possible Duplicate:

  How should I do floating point comparison?

Is it not recommended to compare for equality a double and a double literal in C++, because I guess it is compiler dependent?

To be more precise it is not OK to compare a double which is hard-coded (a literal in the source code) and a double which should be computed, as the last number of the resultant of the calculation can vary from one compiler to another. Is this not standardized?

I heard this is mentioned in Knuth's TeXbook, is that right?

If this is all true, what is the solution?

答: The key problem is how floating point arithmetic works - it includes rounding that can lead to comparison for equality evaluated wrong. This applies to all floating point numbers regardless of whether variable is declared const or not.

Title: Comparing doubles to double literals?


问:
Why are results of CRT and VS memory profiling so different?
Traditionally I have used the CRT memory reporting functions like this:

```<code>    _CrtMemState state[3];
    _CrtMemCheckpoint(&state[0]);
    foo();
    _CrtMemCheckpoint(&state[1]);
    int const diff = _CrtMemDifference(&state[2], &state[0], &state[1]);
    _CrtMemDumpStatistics(&state[2]);
</code>```

More recently I have used Visual Studio's builtin heap profiling tool with snapshots. Create first snapshot before foo(), second snapshot after foo(), then look at the diff output.

Now I used both at the same time and compared the results. I expected both results to be pretty much the same, if not exactly the same. But this is not the case. Memory sizes vary wildly. The only thing they share is the number of allocations. I don't know what to make of this. How should I interpret those results? What causes the difference? Whom should I trust?

Note that the CRT results are the same indepedently of heap profiling being enabled or not.

答:
So it seems that memory profiling is neither an exact science nor a very popular one.

Short answer to my own question: Just pick any type of measurement, then stick with it and compare the abstract numbers for every measurement you take. But never start wondering what those numbers could mean.

FYI, here's what I explored:

Snapshot diffing by _CrtMemCheckpoint / _CrtMemDifference.

In addition _CrtSetAllocHook to track total allocations during the task, because _CrtMemState's lHighWaterCount (peak since app start, not since last snapshot) and lTotalCount (overflows, sometimes weird glitches) are not reliable. Sadly, _CrtSetAllocHook does not enable you to match allocs and de-allocs.

GetProcessHeap / HeapSummary to inspect the default process heap.

GetProcessMemoryInfo yields similar numbers as HeapSummary, but of course not the same. Occasionally, there's even a large gap between the two. Apparently GetProcessMemoryInfo is also providing the values you see in Windows' TaskManager.

In the end, I used _CrtMemCheckpoint, _CrtMemDifference and _CrtSetAllocHook in debug, because I felt that I could interpret those numbers. However, these functions are not available in release, so I used GetProcessMemoryInfo there. Had no clue how to interpret those numbers, but everytime they went down because of my optimizations, they gave me a happy face.

Body:
Traditionally I have used the CRT memory reporting functions like this:

    _CrtMemState state[3];
    _CrtMemCheckpoint(&state[0]);
    foo();
    _CrtMemCheckpoint(&state[1]);
    int const diff = _CrtMemDifference(&state[2], &state[0], &state[1]);
    _CrtMemDumpStatistics(&state[2]);

More recently I have used Visual Studio's builtin heap profiling tool with snapshots. Create first snapshot before foo(), second snapshot after foo(), then look at the diff output.

Now I used both at the same time and compared the results. I expected both results to be pretty much the same, if not exactly the same. But this is not the case. Memory sizes vary wildly. The only thing they share is the number of allocations. I don't know what to make of this. How should I interpret those results? What causes the difference? Whom should I trust?

Note that the CRT results are the same indepedently of heap profiling being enabled or not.


问:
searching an unsorted list of elements in python
Apart from Binary search - do we have any other algorithm having lesser number of comparisons.
Further Binary search would work on a Sorted list. what if the elements are unsorted ?

if Number of elements (= n) is a big number. Then the run time would be high, if I opt to sort it and then run a binary search on the same.

is there any other alternative.

答:
Sorting has a cost of O(n*log(n)) in the mean case if you use Timsort, Python's default sorting algorithm, so it's only worth ordering if you are gonna perform many searches and the array is not gonna have new elements since you'll have to reorder which has cost O(n).

On the other hand, since you have to look every value individually, I don't think there are better ways unless you use parallel programing, that way several threads could look in different values at the same time.


问:
Result of the V$tablespace is confusing-
Lately, I am checking the information about tablespaces for that I executed a query on v$tablespace. Everything is understandable except two things that confuse me –

First the column TS# according to the documentation this column shows “Number of Tablespaces” I don’t understand what that means – I only have 5 tablespaces but it does not correspond to that. What numbers it is showing?

Second, the query repeating the names of tablespaces, I don’t understand why?
By the way, I am connected to my database using the “Sys” user through “CDB$ROOT” database.
The query I am using

```<code>SELECT * FROM v$database;
</code>```

Here is the result that it returns

答:
First the column TS# .... What numbers it is showing?

It's the ID of the tablespace.

I am connected to my database using the “Sys” user through “CDB$ROOT” database.

This is the key point: you are seeing information about tablespaces defined for all the database containers.

If you had connected as say the SYSTEM user for a particular pluggable DB you would only have seen five rows in a query on V$TABLESPACE.

the query repeating the names of tablespaces, I don’t understand why

The answer lies in the value of CON_ID. Let's decode it and see what the results tell us:

```<code>select ts.*
       ,case
          when ts.con_id = 0 then 'CDB'
          when ts.con_id = 1 then 'Root'
          when ts.con_id = 2 then 'Seed'
          else 'PDB' end as scope
from v$tablespace ts
order by ts.con_id
        ,ts.ts#
/
</code>```

Output

```<code>       TS# NAME                           INC BIG FLA ENC     CON_ID SCOP
---------- ------------------------------ --- --- --- --- ---------- ----
         0 SYSTEM                         YES NO  YES              1 Root
         1 SYSAUX                         YES NO  YES              1 Root
         2 UNDOTBS1                       YES NO  YES              1 Root
         3 TEMP                           NO  NO  YES              1 Root
         4 USERS                          YES NO  YES              1 Root
         0 SYSTEM                         YES NO  YES              2 Seed
         1 SYSAUX                         YES NO  YES              2 Seed
         2 UNDOTBS1                       YES NO  YES              2 Seed
         3 TEMP                           NO  NO  YES              2 Seed
         0 SYSTEM                         YES NO  YES              3 PDB
         1 SYSAUX                         YES NO  YES              3 PDB
         2 UNDOTBS1                       YES NO  YES              3 PDB
         3 TEMP                           NO  NO  YES              3 PDB
         5 USERS                          YES NO  YES              3 PDB
</code>```

It's all covered in the documentation. Find out more.

Body:
Lately, I am checking the information about tablespaces for that I executed a query on v$tablespace. Everything is understandable except two things that confuse me –

First the column TS# according to the documentation this column shows “Number of Tablespaces” I don’t understand what that means – I only have 5 tablespaces but it does not correspond to that. What numbers it is showing?

Second, the query repeating the names of tablespaces, I don’t understand why?
By the way, I am connected to my database using the “Sys” user through “CDB$ROOT” database.
The query I am using

SELECT * FROM v$database;

Here is the result that it returns

Body:
First the column TS# .... What numbers it is showing?

It's the ID of the tablespace.

I am connected to my database using the “Sys” user through “CDB$ROOT” database.

This is the key point: you are seeing information about tablespaces defined for all the database containers.

If you had connected as say the SYSTEM user for a particular pluggable DB you would only have seen five rows in a query on V$TABLESPACE.

the query repeating the names of tablespaces, I don’t understand why

The answer lies in the value of CON_ID. Let's decode it and see what the results tell us:

select ts.*
       ,case
          when ts.con_id = 0 then 'CDB'
          when ts.con_id = 1 then 'Root'
          when ts.con_id = 2 then 'Seed'
          else 'PDB' end as scope
from v$tablespace ts
order by ts.con_id
        ,ts.ts#
/

Output

       TS# NAME                           INC BIG FLA ENC     CON_ID SCOP
---------- ------------------------------ --- --- --- --- ---------- ----
         0 SYSTEM                         YES NO  YES              1 Root
         1 SYSAUX                         YES NO  YES              1 Root
         2 UNDOTBS1                       YES NO  YES              1 Root
         3 TEMP                           NO  NO  YES              1 Root
         4 USERS                          YES NO  YES              1 Root
         0 SYSTEM                         YES NO  YES              2 Seed
         1 SYSAUX                         YES NO  YES              2 Seed
         2 UNDOTBS1                       YES NO  YES              2 Seed
         3 TEMP                           NO  NO  YES              2 Seed
         0 SYSTEM                         YES NO  YES              3 PDB
         1 SYSAUX                         YES NO  YES              3 PDB
         2 UNDOTBS1                       YES NO  YES              3 PDB
         3 TEMP                           NO  NO  YES              3 PDB
         5 USERS                          YES NO  YES              3 PDB

It's all covered in the documentation. Find out more.


答:
It won't stop the problem from happening but you can catch and recover cleanly or more cleanly.  Add a catch and null out all your references (and kill any worker threads this spawns):

```<code>} catch (Exception ignored) {//I think this is an ERROR not an exception here.
   photoFile = null;//Might want to also close this.
   data = null;
   intent = null
} catch (Error ignored) {
   photoFile = null;//Might want to also close this.
   data = null;
   intent = null
}
</code>```

Title: Native crash of RenderThread with signal 6 (SIGABRT)

Body:
Updates!

See below

Situation

We're having a difficult to diagnose issue with our app. When we attempt to use an intent to have the camera app return a picture, we receive a low-level crash situation that we are unsure how to debug. This is occurring on Nexus 5x devices on bother Android 6.0 and Android 7.0.

Here is the stack trace from the monitor:

10-17 11:59:41.208 9925-9925/? A/DEBUG: *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
10-17 11:59:41.208 9925-9925/? A/DEBUG: Build fingerprint: 'google/bullhead/bullhead:7.0/NBD90W/3239497:user/release-keys'
10-17 11:59:41.208 9925-9925/? A/DEBUG: Revision: 'rev_1.0'
10-17 11:59:41.208 9925-9925/? A/DEBUG: ABI: 'arm64'
10-17 11:59:41.208 9925-9925/? A/DEBUG: pid: 5791, tid: 6054, name: RenderThread  >>> com.ourapp <<<
10-17 11:59:41.209 9925-9925/? A/DEBUG: signal 6 (SIGABRT), code -6 (SI_TKILL), fault addr --------
10-17 11:59:41.230 9925-9925/? A/DEBUG: Abort message: 'Leaked 2 GPU objects!'
10-17 11:59:41.230 9925-9925/? A/DEBUG:     x0   0000000000000000  x1   00000000000017a6  x2   0000000000000006  x3   0000000000000008
10-17 11:59:41.230 9925-9925/? A/DEBUG:     x4   00006e6174736e69  x5   0000000000000000  x6   0000007629a9f000  x7   0000000000000000
10-17 11:59:41.230 9925-9925/? A/DEBUG:     x8   0000000000000083  x9   ffffffffffffffdf  x10  0000000000000000  x11  0000000000000001
10-17 11:59:41.230 9925-9925/? A/DEBUG:     x12  0000000000000018  x13  0000000000000000  x14  0000000000000000  x15  000850a8eb6af8af
10-17 11:59:41.231 9925-9925/? A/DEBUG:     x16  000000762948eed0  x17  0000007629438a2c  x18  0000000000000400  x19  00000076093b84f8
10-17 11:59:41.231 9925-9925/? A/DEBUG:     x20  0000000000000006  x21  00000076093b8450  x22  000000000000000b  x23  000000762933c040
10-17 11:59:41.231 9925-9925/? A/DEBUG:     x24  00000000ffffffff  x25  00000075f9d71490  x26  7fffffffffffffff  x27  00000075f2c54060
10-17 11:59:41.231 9925-9925/? A/DEBUG:     x28  0000007625c83238  x29  00000076093b7ae0  x30  0000007629435e58
10-17 11:59:41.231 9925-9925/? A/DEBUG:     sp   00000076093b7ac0  pc   0000007629438a34  pstate 0000000060000000
10-17 11:59:41.237 3715-9157/? E/mm-camera-sensor: port_sensor_handle_aec_update:443miss aec update window, skip
10-17 11:59:41.253 9925-9925/? A/DEBUG: backtrace:
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #00 pc 000000000006ba34  /system/lib64/libc.so (tgkill+8)
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #01 pc 0000000000068e54  /system/lib64/libc.so (pthread_kill+64)
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #02 pc 0000000000023ed8  /system/lib64/libc.so (raise+24)
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #03 pc 000000000001c790  /system/lib64/libc.so (abort+52)
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #04 pc 00000000000107f4  /system/lib64/libcutils.so (__android_log_assert+224)
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #05 pc 0000000000054cc0  /system/lib64/libhwui.so
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #06 pc 00000000000350f8  /system/lib64/libhwui.so
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #07 pc 00000000000328c8  /system/lib64/libhwui.so
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #08 pc 0000000000037348  /system/lib64/libhwui.so
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #09 pc 0000000000038434  /system/lib64/libhwui.so
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #10 pc 0000000000039890  /system/lib64/libhwui.so (_ZN7android10uirenderer12renderthread12RenderThread10threadLoopEv+152)
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #11 pc 0000000000012460  /system/lib64/libutils.so (_ZN7android6Thread11_threadLoopEPv+272)
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #12 pc 000000000009bc4c  /system/lib64/libandroid_runtime.so (_ZN7android14AndroidRuntime15javaThreadShellEPv+116)
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #13 pc 000000000006863c  /system/lib64/libc.so (_ZL15__pthread_startPv+208)
10-17 11:59:41.254 9925-9925/? A/DEBUG:     #14 pc 000000000001d9fc  /system/lib64/libc.so (__start_thread+16)

We can reliably trigger this when we use an intent to call up the camera app to retrieve a picture with the following code:

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

if (intent.resolveActivity(fragmentContext.getPackageManager()) == null) {
   return;
}

try {
   File photoFile = FileUtils.createImageFile(fragmentContext);

   data.addFileUpload(photoFile.getAbsolutePath());
   Uri photoUri = FileProvider.getUriForFile(fragmentContext, OurApplication.FILE_PROVIDER, photoFile);

   intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);

   startActivityForResult(intent, REQUEST_TAKE_PHOTO);
} catch (IOException ignored) {
}

As shown, there isn't anything usual here.

Environment

We are able to trigger this on our test devices which are Nexus 5x. One device is Android 6 and the other is Android 7. They both produce similar stack traces (the one shown is from Android 7.0).

Triggering Context

It seems that we are able to trigger this event given either of the following two situations:

The Google Maps is loaded in the activity that starts the camera

A low memory situation (which we triggered with Chrome loaded with a tab or two of cnn.com)

What we've tried

We've tried to piece-wise remove functionality from the app until we could not longer trigger this crash but we've always been able to trigger it given a low memory situation.

Questions

Has anyone run in to this before and found a way to solve it?

Suggestions on how to further debug this issue?

Any links for hints?

Updates

2016/11/02 - There is an open bug report as noted in the comments. Different device/builds (Nexus 5x, 6P and Pixel with Android 6, 7.0 and 7.1) are reporting the same problem with various different types of situations as well. I'll continue to post updates with more information. The situation has been classified as a defect with priority of small. I would consider staring that bug and raising your concerns there.

2016/12/14 - I'm personally still having this issue even with the various security updates that have been applied. There isn't any more information other than other people reporting the same issues across various devices. Please check out the linked bug report, star and comment there. If I find anything that works, I'll post here!

2017/07/31 - For people that are still experiencing this issue, one user has attempted doing staged roll outs to their user base and removing various features to attempt to diagnose what the issue is. In their situation, by removing com.google.android.gms:play-services-maps:11.0.1, their situation has appeared to have been resolved. Unfortunately, maps are a core component of our applications; thus, this is not acceptable in our situation. In my opinion, this still appears to have to do with consumption of ram in various situations that causes the issue when resuming the activity.

2017/12/05 - No changes or real acknowledgement from Google. From what I've found, this issue appears to have been resolved in Android 8.0 and on some devices running various updates to Android 7.x

Body:
It won't stop the problem from happening but you can catch and recover cleanly or more cleanly.  Add a catch and null out all your references (and kill any worker threads this spawns):

} catch (Exception ignored) {//I think this is an ERROR not an exception here.
   photoFile = null;//Might want to also close this.
   data = null;
   intent = null
} catch (Error ignored) {
   photoFile = null;//Might want to also close this.
   data = null;
   intent = null
}


问:
CloudFormation Template to accept parameter from external file
I am trying to achieve the same thing but for Parameter Store. My scenario is, Developers will provide a .json file with key/value. That file should be used by the CloudFormation template to create Parameter Store resources based on the entry made as a json file.

Main template -

```<code>    {
"AWSTemplateFormatVersion": "2010-09-09",
"Parameters": {
    "SSMParameterStore": {
        "Description": "SSM Parameter Store",
        "Type": "String"
    }
},
"Resources": {
        "InputParameters": {
            "Type": "AWS::SSM::Parameter",
            "Properties": {
                "Name": {"Ref": "ParameterKey"},
                "Type": "String",
                "Value": {"Ref": "ParameterValue"}
            }
        }
    }
}
</code>```

Input Template -

```<code>[{
"ParameterKey": "KeyPairName",
"ParameterValue": "MyKey"
},
{
"ParameterKey": "InstanceType",
"ParameterValue": "m1.micro"
}
]
</code>```

Command:

```<code>aws cloudformation create-stack --stack-name test --template-body file:///home/user/Documents/Work/training/test/templt.json --parameters file:///home/user/Documents/Work/training/test/test.json --region us-east-1
</code>```

Output:

```<code>An error occurred (ValidationError) when calling the CreateStack operation: Parameters: [SSMParameterStore] must have values
</code>```

Not sure what is missing here.

答: Your template has a parameter of SSMParameterStore but you are passing in KeyPairName and InstanceType.

Body:
I am trying to achieve the same thing but for Parameter Store. My scenario is, Developers will provide a .json file with key/value. That file should be used by the CloudFormation template to create Parameter Store resources based on the entry made as a json file.

Main template -

    {
"AWSTemplateFormatVersion": "2010-09-09",
"Parameters": {
    "SSMParameterStore": {
        "Description": "SSM Parameter Store",
        "Type": "String"
    }
},
"Resources": {
        "InputParameters": {
            "Type": "AWS::SSM::Parameter",
            "Properties": {
                "Name": {"Ref": "ParameterKey"},
                "Type": "String",
                "Value": {"Ref": "ParameterValue"}
            }
        }
    }
}

Input Template -

[{
"ParameterKey": "KeyPairName",
"ParameterValue": "MyKey"
},
{
"ParameterKey": "InstanceType",
"ParameterValue": "m1.micro"
}
]

Command:

aws cloudformation create-stack --stack-name test --template-body file:///home/user/Documents/Work/training/test/templt.json --parameters file:///home/user/Documents/Work/training/test/test.json --region us-east-1

Output:

An error occurred (ValidationError) when calling the CreateStack operation: Parameters: [SSMParameterStore] must have values

Not sure what is missing here.


问:
Is it normal for bokeh serve on Kubernetes to restart periodically?
I have a bokeh dashboard served in a docker container, which is running on kubernetes. I can access my dashboard remotely, no problems. But I noticed my pod containing the bokeh serve code restarts a lot, i.e. 14 times in the past 2 hours. Sometimes the status will come back as 'CrashLoopBackOff' and sometimes it will be 'Running' normally.

My question is, is there something about the way bokeh serve works that requires kubernetes to restart it so frequently? Is it something to do with memory (OOMKilled)?

Here is a section of my describe pod:

```<code>Name:               bokeh-744d4bc9d-5pkzq
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               10.183.226.51/10.183.226.51
Start Time:         Tue, 18 Feb 2020 11:55:44 +0000
Labels:             name=bokeh
                    pod-template-hash=744d4bc9d
Annotations:        kubernetes.io/psp: xyz-privileged-psp
Status:             Running
IP:                 172.30.255.130
Controlled By:      ReplicaSet/bokeh-744d4bc9d
Containers:
  dashboard-application:
    Container ID:   containerd://16d10dc5dd89235b0xyz2b5b31f8e313f3f0bb7efe82a12e00c1f01708e2f894
    Image:          us.icr.io/oss-data-science-np-dal/bokeh:118
    Image ID:       us.icr.io/oss-data-science-np-dal/bokeh@sha256:037a5b52a6e7c792fdxy80b01e29772dbfc33b10e819774462bee650cf0da
    Port:           5006/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Tue, 18 Feb 2020 14:25:36 +0000
    Last State:     Terminated
      Reason:       OOMKilled
      Exit Code:    137
      Started:      Tue, 18 Feb 2020 14:15:26 +0000
      Finished:     Tue, 18 Feb 2020 14:23:54 +0000
    Ready:          True
    Restart Count:  17
    Limits:
      cpu:     800m
      memory:  600Mi
    Requests:
      cpu:        600m
      memory:     400Mi
    Liveness:     http-get http://:5006/ delay=10s timeout=1s period=10s #success=1 #failure=3
    Readiness:    http-get http://:5006/ delay=10s timeout=1s period=3s #success=1 #failure=3
    Environment:  <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-cjhfk (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  default-token-cjhfk:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-cjhfk
    Optional:    false
QoS Class:       Burstable
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 600s
                 node.kubernetes.io/unreachable:NoExecute for 600s
Events:
  Type     Reason     Age                    From                    Message
  ----     ------     ----                   ----                    -------
  Warning  Unhealthy  36m (x219 over 150m)   kubelet, 10.183.226.51  Liveness probe failed: Get http://172.30.255.130:5006/: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
  Warning  BackOff    21m (x34 over 134m)    kubelet, 10.183.226.51  Back-off restarting failed container
  Warning  Unhealthy  10m (x72 over 150m)    kubelet, 10.183.226.51  Readiness probe failed: Get http://172.30.255.130:5006/RCA: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
  Warning  Unhealthy  6m4s (x957 over 150m)  kubelet, 10.183.226.51  Readiness probe failed: Get http://172.30.255.130:5006/: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
  Warning  Unhealthy  68s (x23 over 147m)    kubelet, 10.183.226.51  Liveness probe failed: Get http://172.30.255.130:5006/RCA: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
</code>```

I'm new to k8s, so any information you have to spare on this kind of issue will be much appreciated!

答:
OOMKill means your pod is consuming too much RAM and was killed in order to avoid disruption of the other workload running on the node.

You can either edit your code to use less RAM if feasible, or increase limits.memory.

You generally want to have requests = limits, except if your pod run some heavy stuff at the beginning and then does nothing.

You may want to take a look at the official documentation.

Body:
I have a bokeh dashboard served in a docker container, which is running on kubernetes. I can access my dashboard remotely, no problems. But I noticed my pod containing the bokeh serve code restarts a lot, i.e. 14 times in the past 2 hours. Sometimes the status will come back as 'CrashLoopBackOff' and sometimes it will be 'Running' normally.

My question is, is there something about the way bokeh serve works that requires kubernetes to restart it so frequently? Is it something to do with memory (OOMKilled)?

Here is a section of my describe pod:

Name:               bokeh-744d4bc9d-5pkzq
Namespace:          default
Priority:           0
PriorityClassName:  <none>
Node:               10.183.226.51/10.183.226.51
Start Time:         Tue, 18 Feb 2020 11:55:44 +0000
Labels:             name=bokeh
                    pod-template-hash=744d4bc9d
Annotations:        kubernetes.io/psp: xyz-privileged-psp
Status:             Running
IP:                 172.30.255.130
Controlled By:      ReplicaSet/bokeh-744d4bc9d
Containers:
  dashboard-application:
    Container ID:   containerd://16d10dc5dd89235b0xyz2b5b31f8e313f3f0bb7efe82a12e00c1f01708e2f894
    Image:          us.icr.io/oss-data-science-np-dal/bokeh:118
    Image ID:       us.icr.io/oss-data-science-np-dal/bokeh@sha256:037a5b52a6e7c792fdxy80b01e29772dbfc33b10e819774462bee650cf0da
    Port:           5006/TCP
    Host Port:      0/TCP
    State:          Running
      Started:      Tue, 18 Feb 2020 14:25:36 +0000
    Last State:     Terminated
      Reason:       OOMKilled
      Exit Code:    137
      Started:      Tue, 18 Feb 2020 14:15:26 +0000
      Finished:     Tue, 18 Feb 2020 14:23:54 +0000
    Ready:          True
    Restart Count:  17
    Limits:
      cpu:     800m
      memory:  600Mi
    Requests:
      cpu:        600m
      memory:     400Mi
    Liveness:     http-get http://:5006/ delay=10s timeout=1s period=10s #success=1 #failure=3
    Readiness:    http-get http://:5006/ delay=10s timeout=1s period=3s #success=1 #failure=3
    Environment:  <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from default-token-cjhfk (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  default-token-cjhfk:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  default-token-cjhfk
    Optional:    false
QoS Class:       Burstable
Node-Selectors:  <none>
Tolerations:     node.kubernetes.io/not-ready:NoExecute for 600s
                 node.kubernetes.io/unreachable:NoExecute for 600s
Events:
  Type     Reason     Age                    From                    Message
  ----     ------     ----                   ----                    -------
  Warning  Unhealthy  36m (x219 over 150m)   kubelet, 10.183.226.51  Liveness probe failed: Get http://172.30.255.130:5006/: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
  Warning  BackOff    21m (x34 over 134m)    kubelet, 10.183.226.51  Back-off restarting failed container
  Warning  Unhealthy  10m (x72 over 150m)    kubelet, 10.183.226.51  Readiness probe failed: Get http://172.30.255.130:5006/RCA: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
  Warning  Unhealthy  6m4s (x957 over 150m)  kubelet, 10.183.226.51  Readiness probe failed: Get http://172.30.255.130:5006/: net/http: request canceled (Client.Timeout exceeded while awaiting headers)
  Warning  Unhealthy  68s (x23 over 147m)    kubelet, 10.183.226.51  Liveness probe failed: Get http://172.30.255.130:5006/RCA: net/http: request canceled (Client.Timeout exceeded while awaiting headers)

I'm new to k8s, so any information you have to spare on this kind of issue will be much appreciated!


问:
Python multilevel inheritence
```<code>class A:
    def foo(self):
        print("original")
class B(A):
    def foo(self):
        super().foo()
        print("override")
class C(B):
    def foo(self):
      super().foo()
       print("override")

o = c()
</code>```

<p>Now after defining this object, I want to, access the foo of class A through same object, how do I do that??? </p>

答:
So now if I want to access that function with the same name from sub-subclass, of the base class, how do I do it???

super().<method_name>(<params>) is how you call a method "in the parent class" in order to delegate upwards.

class A:
    def foo(self):
        print("original")
class B(A):
    def foo(self):
        super().foo()
        print("override")
```

Calling B().foo() will print "original" then "override".

Title: Python multilevel inheritence

Body:
class A:
    def foo(self):
        print("original")
class B(A):
    def foo(self):
        super().foo()
        print("override")
class C(B):
    def foo(self):
      super().foo()
       print("override")

o = c()

Now after defining this object, I want to, access the foo of class A through same object, how do I do that???

Body:
So now if I want to access that function with the same name from sub-subclass, of the base class, how do I do it???

super().<method_name>(<params>) is how you call a method "in the parent class" in order to delegate upwards.

class A:
    def foo(self):
        print("original")
class B(A):
    def foo(self):
        super().foo()
        print("override")

Calling B().foo() will print "original" then "override".


问:
Disable Password List suggestion pick in chrome
In html code i have try to use this:

```<code><input type="password" name="password" autocomplete="new-password">
<input type="password" name="password" autocomplete="new">
<input type="password" name="password" autocomplete="off">
<input type="password" name="password" autocomplete="nope">
</code>```

Update test diferent name tag:

```<code><input type="password" name="p1" autocomplete="nope">
<input type="password" name="p2" autocomplete="nope">
<input type="password" name="ahgsfkhas" autocomplete="nope">
</code>```

To prevent chrome to show suggestion picker List, but none of this work, this is the result:

some way to disable this through an HTML or JQuery / javascript tag, I don't have access to all Chrome installations on PCs, like to edit this feature

this is not an offer to save password; this is a select picker from password stored (Password Manager). this breaks into the Interface of a Web Page, and I see no way to deactivate it from the web page, since I don't have access to the browser settings.

答:
it's relative to the browser
settings => automatic entry => password => Offer to save passwords (no)</p>

Body:
In html code i have try to use this:

<input type="password" name="password" autocomplete="new-password">
<input type="password" name="password" autocomplete="new">
<input type="password" name="password" autocomplete="off">
<input type="password" name="password" autocomplete="nope">

Update test diferent name tag:

<input type="password" name="p1" autocomplete="nope">
<input type="password" name="p2" autocomplete="nope">
<input type="password" name="ahgsfkhas" autocomplete="nope">

To prevent chrome to show suggestion picker List, but none of this work, this is the result:

some way to disable this through an HTML or JQuery / javascript tag, I don't have access to all Chrome installations on PCs, like to edit this feature

this is not an offer to save password; this is a select picker from password stored (Password Manager). this breaks into the Interface of a Web Page, and I see no way to deactivate it from the web page, since I don't have access to the browser settings.


问:
SQL Developer missing a library
I'm fairly new to Oracle SQL developer. As I'm trying to make a new connection via TNS, I'm getting this error down below which I've been looking to solve for a while fruitlessly.

Error Message:

Statut : échec -Echec du test : no ocijdbc18 in java.library.path

答:
Assuming MySQL is a typo (You are using port 1521, which is the default port for Oracle database, also its giving you ODBC error, so I assume its an Oracle database. Remember that you can connect SQL developer to a MySQL database, so please clarify if you want to connect to a MySQL database rather than Oracle) your problem is due to lack of Oracle Data Base Connector driver (ODBC). From this link download the latest version of Oracle Instant client and install it on your machine. Then define ORACLE_HOME to the path of Instant client installation (To the actual installation folder, the one that contains folders like bin, network and so on) and restart SQL Developer, then you should be good to go.

P.S. : as @thatjeffsmith has mentioned correctly in the comments, it's not necessary to have Oracle Client and/or ODBC (or similar) drivers in order to connect to an Oracle database. Using basic as the connection type and adding the correct connection info would suffice. This Article in Oracle Magazine has extensively talked about the different connection types.

Title: SQL Developer missing a library


问:
Javascript Binary Search algorithm unable to find number in the list
The following code seems to be unable to find the number in the list. Why might this be?

Trying this with the number to search for as '9' and the array of numbers consisting of numbers between 1-10 inclusively.

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
count = 0;

function binarySearch(array, number) {
    mid = Math.floor(array.length / 2);
    if (number === array[mid]) {
        return count;
    }

    else if (number < array[mid] && array.length > 1) {
        count++;
        arrayFirst = array.splice(0, array[mid]);
        console.log("Tried: ", array[mid])
        console.log(arrayFirst);
        return binarySearch(arrayFirst, number);
    }

    else if (number > array[mid] && array.length > 1) {
        count++;
        arraySecond = array.splice(array[mid], array.length);
        console.log("Tried: ", array[mid])
        console.log(arraySecond);
        return binarySearch(arraySecond, number);
    }

    else {
        return 'number doesnt exist';
    }

}
console.log(binarySearch(array, 4));```
</div>
</div>

The code is now struggling with finding the number 10
New Edit:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>       array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13,14,15,16,17,18,19,20];
    count = 0;

    function binarySearch(array, number) {
        mid = Math.floor(array.length/ 2);
        if (number === array[mid]) {
            return count;
        }

        else if (number < array[mid] && array.length > 1) {
            count++;
            arrayFirst = array.splice(0, mid);
            console.log("Tried: ", array[mid])
            console.log(arrayFirst);
            return binarySearch(arrayFirst, number);
        }

        else if (number > array[mid] && array.length > 1) {
            count++;
            arraySecond = array.splice(array[mid], mid);
            console.log("Tried: ", array[mid])
            console.log(arraySecond);
            return binarySearch(arraySecond, number);
        }

        else {
            return 'number doesnt exist';
        }

    }

    console.log(binarySearch(array, 10));</code>```

答:
This:

```<code>array = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
</code>```

is not an array, it's interpreted as a list of initialization, like this:

```<code> array = 1, x = 2, y = 3...;
</code>```

and so your array is just 1, and not the entire list. Also keep in mind that it is Not Recommended to declare a variable without var keyword. It can accidently overwrite an existing global variable. Instead you should use var, let or const based on the use of that variable

Instead, this should be your array:

```<code>array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
</code>```

Body:
The following code seems to be unable to find the number in the list. Why might this be?

Trying this with the number to search for as '9' and the array of numbers consisting of numbers between 1-10 inclusively.

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
count = 0;

function binarySearch(array, number) {
    mid = Math.floor(array.length / 2);
    if (number === array[mid]) {
        return count;
    }

    else if (number < array[mid] && array.length > 1) {
        count++;
        arrayFirst = array.splice(0, array[mid]);
        console.log("Tried: ", array[mid])
        console.log(arrayFirst);
        return binarySearch(arrayFirst, number);
    }

    else if (number > array[mid] && array.length > 1) {
        count++;
        arraySecond = array.splice(array[mid], array.length);
        console.log("Tried: ", array[mid])
        console.log(arraySecond);
        return binarySearch(arraySecond, number);
    }

    else {
        return 'number doesnt exist';
    }

}
console.log(binarySearch(array, 4));

The code is now struggling with finding the number 10
New Edit:

       array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,13,14,15,16,17,18,19,20];
    count = 0;

    function binarySearch(array, number) {
        mid = Math.floor(array.length/ 2);
        if (number === array[mid]) {
            return count;
        }

        else if (number < array[mid] && array.length > 1) {
            count++;
            arrayFirst = array.splice(0, mid);
            console.log("Tried: ", array[mid])
            console.log(arrayFirst);
            return binarySearch(arrayFirst, number);
        }

        else if (number > array[mid] && array.length > 1) {
            count++;
            arraySecond = array.splice(array[mid], mid);
            console.log("Tried: ", array[mid])
            console.log(arraySecond);
            return binarySearch(arraySecond, number);
        }

        else {
            return 'number doesnt exist';
        }

    }

    console.log(binarySearch(array, 10));

Body:
This:

array = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;

is not an array, it's interpreted as a list of initialization, like this:

 array = 1, x = 2, y = 3...;

and so your array is just 1, and not the entire list. Also keep in mind that it is Not Recommended to declare a variable without var keyword. It can accidently overwrite an existing global variable. Instead you should use var, let or const based on the use of that variable

Instead, this should be your array:

array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];


问:
Shell Object with minimized execution in VBA
I would like to minimize the execution of the shell window and the execution of the python script with the code below:

Sub RunPython()
    Dim oShell, oExec as Object
    Dim sriptPath, scriptName, datas, oCmd as String
    Dim weekNumber as Integer

    Set oShell = CreateObject("WScript.Shell")
    oCmd = "python.exe " & scriptPath & scriptName & " " & datas & " " & Str(weekNumber)
    Set oExec = oShell.Exec(oCmd)
    'We are waiting for the Shell script to be executed'
    While oExec.Status = 0
    Wend
    MsgBox "Hagrid notebook update completed"
End Sub
```

It is imperative to keep the status information of the oExec object. I tried to insert the notion vbMinimizedFocus, but it doesn't work. Do you have an idea to solve this difficulty?

答:
According to my tests, both of these versions make .Status available.

Option 1.  Using pythonw.exe instead of python.exe - it does not minimize the window, but runs it completely in the background.

Option 2. You could add 2 lines at the beginning of the python script:

import ctypes
ctypes.windll.user32.ShowWindow( ctypes.windll.kernel32.GetConsoleWindow(), 6 )
```

Body:
I would like to minimize the execution of the shell window and the execution of the python script with the code below:

Sub RunPython()
    Dim oShell, oExec as Object
    Dim sriptPath, scriptName, datas, oCmd as String
    Dim weekNumber as Integer

    Set oShell = CreateObject("WScript.Shell")
    oCmd = "python.exe " & scriptPath & scriptName & " " & datas & " " & Str(weekNumber)
    Set oExec = oShell.Exec(oCmd)
    'We are waiting for the Shell script to be executed'
    While oExec.Status = 0
    Wend
    MsgBox "Hagrid notebook update completed"
End Sub

It is imperative to keep the status information of the oExec object. I tried to insert the notion vbMinimizedFocus, but it doesn't work. Do you have an idea to solve this difficulty?