问:
Azure AKS use secrets to override ConfigMap keys
I want to add or override key values in ConfigMap and Statefulset files. I use Azure Key Vault and AKS and my goal is to deploy Redis and Postgres. The point is that I want to use secrets from key vault for Redis password and Postgres credentials. I was already create SecretProvider and everything works. I just don't understand how to use it. I was experimented with different types of files like yaml and json because I use Azure DevOps CI/CD and there has a functionality to override json files.

```<code>{
  "apiVersion": "storage.k8s.io/v1",
  "kind": "StorageClass",
  "metadata": {
    "name": "staging"
  },
  "provisioner": "kubernetes.io/azure-disk",
  "reclaimPolicy": "Retain",
  "volumeBindingMode": "Immediate",
  "allowVolumeExpansion": true,
  "parameters": {
    "storageaccounttype": "Standard_LRS",
    "kind": "managed"
  }
}
</code>```

This is a SecretProviderClass example using system-assigned identity to access your key vault

```<code>apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
  name: az-kv-sp-dev
spec:
  provider: azure
  parameters:
    usePodIdentity: "false"
    useVMManagedIdentity: "true"    # Set to true for using managed identity
    userAssignedIdentityID: ""      # If empty, then defaults to use the system assigned identity on the VM
    keyvaultName: eui-kv
    cloudName: "AzurePublicCloud"                   # [OPTIONAL for Azure] if not provided, the Azure environment defaults to AzurePublicCloud
    objects:  |
      array:
        - |
          objectName: psql-conn-str-dev
          objectType: secret        # object types: secret, key, or cert
          objectVersion: ""         # [OPTIONAL] object versions, default to latest if empty
    tenantId: xxxx-xxxxx-xxxxxx          # The tenant ID of the key vault

{
  "apiVersion": "v1",
  "kind": "PersistentVolumeClaim",
  "metadata": {
    "name": "pvc-staging"
  },
  "spec": {
    "accessModes": [
      "ReadWriteOnce"
    ],
    "storageClassName": "staging",
    "resources": {
      "requests": {
        "storage": "5Gi"
      }
    }
  }
}

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: redis
  namespace: dev
spec:
  serviceName: redis
  replicas: 3
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
    spec:
      initContainers:
      - name: config
        image: redis:6.2.3-alpine
        command: [ "sh", "-c" ]
        args:
          - |
            cp /tmp/redis/redis.conf /etc/redis/redis.conf

            echo "finding master..."
            MASTER_FDQN=`hostname  -f | sed -e 's/redis-[0-9]\./redis-0./'`
            if [ "$(redis-cli -h sentinel -p 5000 ping)" != "PONG" ]; then
              echo "master not found, defaulting to redis-0"

              if [ "$(hostname)" == "redis-0" ]; then
                echo "this is redis-0, not updating config..."
              else
                echo "updating redis.conf..."
                echo "slaveof $MASTER_FDQN 6379" >> /etc/redis/redis.conf
              fi
            else
              echo "sentinel found, finding master"
              MASTER="$(redis-cli -h sentinel -p 5000 sentinel get-master-addr-by-name mymaster | grep -E '(^redis-\d{1,})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})')"
              echo "master found : $MASTER, updating redis.conf"
              echo "slaveof $MASTER 6379" >> /etc/redis/redis.conf
            fi
        volumeMounts:
        - name: redis-config
          mountPath: /etc/redis/
        - name: config
          mountPath: /tmp/redis/
      containers:
      - name: redis
        image: redis:6.2.3-alpine
        command: ["redis-server"]
        args: ["/etc/redis/redis.conf"]
        ports:
        - containerPort: 6379
          name: redis
        volumeMounts:
        - name: data
          mountPath: /data
        - name: redis-config
          mountPath: /etc/redis/
      volumes:
      - name: redis-config
        emptyDir: {}
      - name: config
        configMap:
          name: redis-config
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: "dev" # change default deppends on storage class name (AKS namepsace)
      resources:
        requests:
          storage: 50Mi
---
apiVersion: v1
kind: Service
metadata:
  name: redis
  namespace: dev
spec:
  clusterIP: None
  ports:
  - port: 6379
    targetPort: 6379
    name: redis
  selector:
    app: redis
</code>```

And the Sentinel file where maybe is good idea to override the REDIS_PASSWORD from Key Vault

```<code>apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: sentinel
spec:
  serviceName: sentinel
  replicas: 3
  selector:
    matchLabels:
      app: sentinel
  template:
    metadata:
      labels:
        app: sentinel
    spec:
      initContainers:
      - name: config
        image: redis:6.2.3-alpine
        command: [ "sh", "-c" ]
        args:
          - |
            REDIS_PASSWORD=a-very-complex-password-here
            nodes=redis-0.redis,redis-1.redis,redis-2.redis
            for i in ${nodes//,/ }
            do
                echo "finding master at $i"
                MASTER=$(redis-cli --no-auth-warning --raw -h $i -a $REDIS_PASSWORD info replication | awk '{print $1}' | grep master_host: | cut -d ":" -f2)
                if [ "$MASTER" = "" ]; then
                    echo "no master found"
                    MASTER=
                else
                    echo "found $MASTER"
                    break
                fi
            done
            echo "sentinel monitor mymaster $MASTER 6379 2" >> /tmp/master
            echo "port 5000
            sentinel resolve-hostnames yes
            sentinel announce-hostnames yes
            $(cat /tmp/master)
            sentinel down-after-milliseconds mymaster 5000
            sentinel failover-timeout mymaster 60000
            sentinel parallel-syncs mymaster 1
            sentinel auth-pass mymaster $REDIS_PASSWORD
            " > /etc/redis/sentinel.conf
            cat /etc/redis/sentinel.conf
        volumeMounts:
        - name: redis-config
          mountPath: /etc/redis/
      containers:
      - name: sentinel
        image: redis:6.2.3-alpine
        command: ["redis-sentinel"]
        args: ["/etc/redis/sentinel.conf"]
        ports:
        - containerPort: 5000
          name: sentinel
        volumeMounts:
        - name: redis-config
          mountPath: /etc/redis/
        - name: data
          mountPath: /data
      volumes:
      - name: redis-config
        emptyDir: {}
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: "dev"
      resources:
        requests:
          storage: 50Mi
---
apiVersion: v1
kind: Service
metadata:
  name: sentinel
spec:
  clusterIP: None
  ports:
  - port: 5000
    targetPort: 5000
    name: sentinel
  selector:
    app: sentinel
</code>```

Body:
I want to add or override key values in ConfigMap and Statefulset files. I use Azure Key Vault and AKS and my goal is to deploy Redis and Postgres. The point is that I want to use secrets from key vault for Redis password and Postgres credentials. I was already create SecretProvider and everything works. I just don't understand how to use it. I was experimented with different types of files like yaml and json because I use Azure DevOps CI/CD and there has a functionality to override json files.

{
  "apiVersion": "storage.k8s.io/v1",
  "kind": "StorageClass",
  "metadata": {
    "name": "staging"
  },
  "provisioner": "kubernetes.io/azure-disk",
  "reclaimPolicy": "Retain",
  "volumeBindingMode": "Immediate",
  "allowVolumeExpansion": true,
  "parameters": {
    "storageaccounttype": "Standard_LRS",
    "kind": "managed"
  }
}

This is a SecretProviderClass example using system-assigned identity to access your key vault

apiVersion: secrets-store.csi.x-k8s.io/v1
kind: SecretProviderClass
metadata:
  name: az-kv-sp-dev
spec:
  provider: azure
  parameters:
    usePodIdentity: "false"
    useVMManagedIdentity: "true"    # Set to true for using managed identity
    userAssignedIdentityID: ""      # If empty, then defaults to use the system assigned identity on the VM
    keyvaultName: eui-kv
    cloudName: "AzurePublicCloud"                   # [OPTIONAL for Azure] if not provided, the Azure environment defaults to AzurePublicCloud
    objects:  |
      array:
        - |
          objectName: psql-conn-str-dev
          objectType: secret        # object types: secret, key, or cert
          objectVersion: ""         # [OPTIONAL] object versions, default to latest if empty
    tenantId: xxxx-xxxxx-xxxxxx          # The tenant ID of the key vault

{
  "apiVersion": "v1",
  "kind": "PersistentVolumeClaim",
  "metadata": {
    "name": "pvc-staging"
  },
  "spec": {
    "accessModes": [
      "ReadWriteOnce"
    ],
    "storageClassName": "staging",
    "resources": {
      "requests": {
        "storage": "5Gi"
      }
    }
  }
}

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: redis
  namespace: dev
spec:
  serviceName: redis
  replicas: 3
  selector:
    matchLabels:
      app: redis
  template:
    metadata:
      labels:
        app: redis
    spec:
      initContainers:
      - name: config
        image: redis:6.2.3-alpine
        command: [ "sh", "-c" ]
        args:
          - |
            cp /tmp/redis/redis.conf /etc/redis/redis.conf

            echo "finding master..."
            MASTER_FDQN=`hostname  -f | sed -e 's/redis-[0-9]\./redis-0./'`
            if [ "$(redis-cli -h sentinel -p 5000 ping)" != "PONG" ]; then
              echo "master not found, defaulting to redis-0"

              if [ "$(hostname)" == "redis-0" ]; then
                echo "this is redis-0, not updating config..."
              else
                echo "updating redis.conf..."
                echo "slaveof $MASTER_FDQN 6379" >> /etc/redis/redis.conf
              fi
            else
              echo "sentinel found, finding master"
              MASTER="$(redis-cli -h sentinel -p 5000 sentinel get-master-addr-by-name mymaster | grep -E '(^redis-\d{1,})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})')"
              echo "master found : $MASTER, updating redis.conf"
              echo "slaveof $MASTER 6379" >> /etc/redis/redis.conf
            fi
        volumeMounts:
        - name: redis-config
          mountPath: /etc/redis/
        - name: config
          mountPath: /tmp/redis/
      containers:
      - name: redis
        image: redis:6.2.3-alpine
        command: ["redis-server"]
        args: ["/etc/redis/redis.conf"]
        ports:
        - containerPort: 6379
          name: redis
        volumeMounts:
        - name: data
          mountPath: /data
        - name: redis-config
          mountPath: /etc/redis/
      volumes:
      - name: redis-config
        emptyDir: {}
      - name: config
        configMap:
          name: redis-config
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: "dev" # change default deppends on storage class name (AKS namepsace)
      resources:
        requests:
          storage: 50Mi
---
apiVersion: v1
kind: Service
metadata:
  name: redis
  namespace: dev
spec:
  clusterIP: None
  ports:
  - port: 6379
    targetPort: 6379
    name: redis
  selector:
    app: redis

And the Sentinel file where maybe is good idea to override the REDIS_PASSWORD from Key Vault

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: sentinel
spec:
  serviceName: sentinel
  replicas: 3
  selector:
    matchLabels:
      app: sentinel
  template:
    metadata:
      labels:
        app: sentinel
    spec:
      initContainers:
      - name: config
        image: redis:6.2.3-alpine
        command: [ "sh", "-c" ]
        args:
          - |
            REDIS_PASSWORD=a-very-complex-password-here
            nodes=redis-0.redis,redis-1.redis,redis-2.redis
            for i in ${nodes//,/ }
            do
                echo "finding master at $i"
                MASTER=$(redis-cli --no-auth-warning --raw -h $i -a $REDIS_PASSWORD info replication | awk '{print $1}' | grep master_host: | cut -d ":" -f2)
                if [ "$MASTER" = "" ]; then
                    echo "no master found"
                    MASTER=
                else
                    echo "found $MASTER"
                    break
                fi
            done
            echo "sentinel monitor mymaster $MASTER 6379 2" >> /tmp/master
            echo "port 5000
            sentinel resolve-hostnames yes
            sentinel announce-hostnames yes
            $(cat /tmp/master)
            sentinel down-after-milliseconds mymaster 5000
            sentinel failover-timeout mymaster 60000
            sentinel parallel-syncs mymaster 1
            sentinel auth-pass mymaster $REDIS_PASSWORD
            " > /etc/redis/sentinel.conf
            cat /etc/redis/sentinel.conf
        volumeMounts:
        - name: redis-config
          mountPath: /etc/redis/
      containers:
      - name: sentinel
        image: redis:6.2.3-alpine
        command: ["redis-sentinel"]
        args: ["/etc/redis/sentinel.conf"]
        ports:
        - containerPort: 5000
          name: sentinel
        volumeMounts:
        - name: redis-config
          mountPath: /etc/redis/
        - name: data
          mountPath: /data
      volumes:
      - name: redis-config
        emptyDir: {}
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: [ "ReadWriteOnce" ]
      storageClassName: "dev"
      resources:
        requests:
          storage: 50Mi
---
apiVersion: v1
kind: Service
metadata:
  name: sentinel
spec:
  clusterIP: None
  ports:
  - port: 5000
    targetPort: 5000
    name: sentinel
  selector:
    app: sentinel


来源: stackexchange

问:
How do I implement the Mollie API on my Reactjs website?
I'm currently building a webshop as a hobby project and I wanted to implement Mollie as a payment method. I don't really have a lot of experience with APIs yet though so I hope someone can guide me a bit so I can continue my journey. Something as simple as a video that explains clearly what I need to know would be highly appreciated.

I've been reading through their docs (https://docs.mollie.com/ and https://docs.mollie.com/reference/v2/payments-api/create-payment), looking for examples, and just looking up general information about APIs but no luck so far. This is what I've got so far, it has just been me trying a lot of different things. I know I'm supposed to use my API key somewhere, but I would have no clue where I would have to put that.

```<code>const mollie = () => {
  const makePayment = async () => {
    try {
      const res = await fetch(`https://api.mollie.com/v2/payments/`, {
        method: 'POST',
      });
      const data = await res.json();
      console.log(data);
    } catch (err) {
      alert(err);
    }
  };

  return (
    <div>
      <button onClick={makePayment}>Pay</button>
    </div>
  );
};
</code>```

If I try to run this I get this error Access to fetch at 'https://api.mollie.com/v2/payments/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. but I highly doubt that's helpful.

ContentLicense: CC BY-SA 4.0

Body:
I'm currently building a webshop as a hobby project and I wanted to implement Mollie as a payment method. I don't really have a lot of experience with APIs yet though so I hope someone can guide me a bit so I can continue my journey. Something as simple as a video that explains clearly what I need to know would be highly appreciated.

I've been reading through their docs (https://docs.mollie.com/ and https://docs.mollie.com/reference/v2/payments-api/create-payment), looking for examples, and just looking up general information about APIs but no luck so far. This is what I've got so far, it has just been me trying a lot of different things. I know I'm supposed to use my API key somewhere, but I would have no clue where I would have to put that.

const mollie = () => {
  const makePayment = async () => {
    try {
      const res = await fetch(`https://api.mollie.com/v2/payments/`, {
        method: 'POST',
      });
      const data = await res.json();
      console.log(data);
    } catch (err) {
      alert(err);
    }
  };

  return (

      <button onClick={makePayment}>Pay</button>

  );
};

If I try to run this I get this error Access to fetch at 'https://api.mollie.com/v2/payments/' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. but I highly doubt that's helpful.


问:
Turning off the hover effect in elementor
This is my first post. Please let me know if I am in the wrong section of the forum with my question.

I would like to know how I can turn off the hover effect in elementor?

I googled it. One recommendation is to enter a CSS code in the CSS customize editor, but it didn't work. The other recommendation is to go to the inspector and turn off the opacity, copy the code and then enter it in the CSS customize editor, but the inspector does show the opacity code line.

I'm running out of options ):


问:
Difference between pandas functions: df.assign() vs df.reset_index()
So lets say I have a DataFrame:

```<code>    stuff  temp
id
1       3  20.0
1       6  20.1
1       7  21.4
2       1  30.2
2       3   0.0
2       2  34.0
3       7   0.0
3       6   0.0
3       2  14.4
</code>```

And I want to drop the index; what method is better to use?

There is df.reset_index(drop=True), which is what I will usually use

But there is also df.assign(Index=range(len(df))).set_index('Index'), which I don't usually use

And, is there any other methods?

Well, I want to find the most efficient/best way to drop the index of a pd.DataFrame. Can you give me a clear explanation. I'm doing a efficient code-writing project and I want to know the best options. Thanks.

Body:
So lets say I have a DataFrame:

    stuff  temp
id
1       3  20.0
1       6  20.1
1       7  21.4
2       1  30.2
2       3   0.0
2       2  34.0
3       7   0.0
3       6   0.0
3       2  14.4

And I want to drop the index; what method is better to use?

There is df.reset_index(drop=True), which is what I will usually use

But there is also df.assign(Index=range(len(df))).set_index('Index'), which I don't usually use

And, is there any other methods?

Well, I want to find the most efficient/best way to drop the index of a pd.DataFrame. Can you give me a clear explanation. I'm doing a efficient code-writing project and I want to know the best options. Thanks.


问:
Vuetify <v-data-table> - type check failed for prop "item". Expected Object, got Array
While learning vue.js I am building an app to upload Excel tables to the browser and display results in a more fashion and graphic way (dashboard). This thread is intended to solve some issues that I am facing with the Excel input and table-data rendering but also to listen to any tips on the aproach (maybe there is a more elegant way to do what I am trying). I have built the project with Nuxt and I am using Vuetify as a UI Framework.

To upload my Excel file I am using npm read-excel-file which I use with a function at @change within an input. Once the function is executed, the rows ff the Excel file are stored into an array of arrays (excelData) previously created at data.

Then I want to present the data as a table using Vuetify v-data-table which in its basic version, just requires the items and the headers to be called as props. In order to display the table just when the array has been updated I have used a v-if condition for excelData.length > 0.

As this app is intended to be used with a variety of Excel forms, I want the headers to adapt to the specific headers of every single Excel file and I am doing this by looping the first row of the imported data which is the original headers of the Excel file.

The problem that I am facing here is that even if the rendering for v-data-table is working I am getting the following error, which is not pleasant to my eyes:

**Invalid prop: type check failed for prop "item". Expected Object, got Array **

Here the code of my component:

```<code><template>
    <div>
        <h1>EXCEL</h1>
        <input id="excelFile" type="file" @change="uploadExcel()"/>
        <v-data-table
            v-if="excelData.length > 0"
            :headers="excelHeaders"
            :items="excelData"
        >
        </v-data-table>`your text`
    </div>
</template>

<script>
import readXlsFile from 'read-excel-file' //requires npm install read-excel-file

export default {
    data() {
        return {
            excelData: [],
            excelHeaders: [],
        }
    },
    methods: {
        uploadExcel() {
            console.log("GetElementbyID")
            const input = document.getElementById('excelFile')
            readXlsFile(input.files[0]).then((rows) => {
                this.excelData = rows;
                console.log("Rows upladed, now iterate rows[0]")
                console.log(this.excelData)
                this.excelData[0].forEach((el, i) => {
                    this.excelHeaders[i] = {text: this.excelData[0][i], value: i.toString()}
            })
            })
            console.log(this.excelHeaders)
        },
}
</script>

</code>```

What am I doing wrong? Also as I said, a different and more elegant approach would be welcome.

Thank you in advance,

Body:
While learning vue.js I am building an app to upload Excel tables to the browser and display results in a more fashion and graphic way (dashboard). This thread is intended to solve some issues that I am facing with the Excel input and table-data rendering but also to listen to any tips on the aproach (maybe there is a more elegant way to do what I am trying). I have built the project with Nuxt and I am using Vuetify as a UI Framework.

To upload my Excel file I am using npm read-excel-file which I use with a function at @change within an input. Once the function is executed, the rows ff the Excel file are stored into an array of arrays (excelData) previously created at data.

Then I want to present the data as a table using Vuetify v-data-table which in its basic version, just requires the items and the headers to be called as props. In order to display the table just when the array has been updated I have used a v-if condition for excelData.length > 0.

As this app is intended to be used with a variety of Excel forms, I want the headers to adapt to the specific headers of every single Excel file and I am doing this by looping the first row of the imported data which is the original headers of the Excel file.

The problem that I am facing here is that even if the rendering for v-data-table is working I am getting the following error, which is not pleasant to my eyes:

**Invalid prop: type check failed for prop "item". Expected Object, got Array **

Here the code of my component:

<template>

EXCEL

        <input id="excelFile" type="file" @change="uploadExcel()"/>
        <v-data-table
            v-if="excelData.length > 0"
            :headers="excelHeaders"
            :items="excelData"
        >
        </v-data-table>`your text`

</template>

What am I doing wrong? Also as I said, a different and more elegant approach would be welcome.

Thank you in advance,


问:
SwiftUI - How to add gestures conditionally according to some variables?
I am building a drawing app where users can:

Add a background and images on a canvas.

Users can perform a magnification gesture on the canvas, depending on the current edit mode, it will either

zoom in/out everything on the canvas

zoom in/out the images only.

Users can also pan the canvas, moving everything in parallel.

Here is my first attempt:

struct Canvas: View {
    @State var zoomEverything = false

    var body: some View {
        ZStack {
            images // View that render images
            background // View that render the background
        }
        .gesture(gesturePanEverything().simultaneously(with: zoomEverything ? gestureZoomEverything() : gestureZoomImagesOnly()))
    }

    private func gestureZoomEverything() -> some Gesture {
        MagnificationGesture()
            .onChanged { value in updateBackgroundScale(value) }
            .onEnded { value in updateBackgroundScale(value)  }
    }

    private func gestureZoomImagesOnly() -> some Gesture {
        MagnificationGesture()
            .onChanged { value in updateImagesScale(value) }
            .onEnded { value in updateImagesScale(value) }
    }

    private func gesturePanEverything() -> some Gesture { DragGesture() }
    private func updateImagesScale(_ value: CGFloat) { /* ... */ }
    private func updateBackgroundScale(_ value: CGFloat) { /* ... */ }
    var images: some View { EmptyView() }
    var background: some View { EmptyView() }
}
```

(Detail logics are replaced by dummy codes, but I think it is enough for demonstrate the problem)

Unfortunately the compiler complained:

Result values in '? :' expression have mismatching types 'some Gesture' (result of 'Canvas.gestureZoomEverything()') and 'some Gesture' (result of 'Canvas.gestureZoomImagesOnly()')

I understand why this error happens - two function's return type are different, and the compiler cannot decide which one should be used, but I cannot find an elegant way to get rid of this error.

Body:
I am building a drawing app where users can:

Add a background and images on a canvas.

Users can perform a magnification gesture on the canvas, depending on the current edit mode, it will either

zoom in/out everything on the canvas

zoom in/out the images only.

Users can also pan the canvas, moving everything in parallel.

Here is my first attempt:

struct Canvas: View {
    @State var zoomEverything = false

    var body: some View {
        ZStack {
            images // View that render images
            background // View that render the background
        }
        .gesture(gesturePanEverything().simultaneously(with: zoomEverything ? gestureZoomEverything() : gestureZoomImagesOnly()))
    }

    private func gestureZoomEverything() -> some Gesture {
        MagnificationGesture()
            .onChanged { value in updateBackgroundScale(value) }
            .onEnded { value in updateBackgroundScale(value)  }
    }

    private func gestureZoomImagesOnly() -> some Gesture {
        MagnificationGesture()
            .onChanged { value in updateImagesScale(value) }
            .onEnded { value in updateImagesScale(value) }
    }

    private func gesturePanEverything() -> some Gesture { DragGesture() }
    private func updateImagesScale(_ value: CGFloat) { /* ... */ }
    private func updateBackgroundScale(_ value: CGFloat) { /* ... */ }
    var images: some View { EmptyView() }
    var background: some View { EmptyView() }
}

(Detail logics are replaced by dummy codes, but I think it is enough for demonstrate the problem)

Unfortunately the compiler complained:

Result values in '? :' expression have mismatching types 'some Gesture' (result of 'Canvas.gestureZoomEverything()') and 'some Gesture' (result of 'Canvas.gestureZoomImagesOnly()')

I understand why this error happens - two function's return type are different, and the compiler cannot decide which one should be used, but I cannot find an elegant way to get rid of this error.


问:
Changing Linked Tables Location upon start isn't working (Access VBA)
I have this code that I run upon the start of my application.  This way we can have a test environment and when we move the front end, it will automatically connect to the correct backend.  I use similar code in other applications to change the SQL backend but in this we are changing the Access backend database.

The code looks correct, when I run it using the msgbox, it shows the correct location that it should be updated to and I do not receive an error.  However, after the code runs it is still connected to the previous backend (it never changes).  What am I missing?

I have looked at other links here and my code looks correct from them. Here is my code:

```<code>Private Sub ChangeEnvironments()

    Dim connServer As String
    'MsgBox CurrentDb.TableDefs("LostToCompany").Connect
    Dim currDatabase As String: currDatabase = "MS Access;DATABASE=" & CurrentProject.Path & "\UNDERWRI.MDB"
    'MsgBox CurrentDb.TableDefs("LostToCompany").Connect & vbCrLf & vbCrLf & currDatabase
    CurrentDb.TableDefs("LostToCompany").Connect = currDatabase
    CurrentDb.TableDefs("LostToCompany").RefreshLink

End Sub
</code>```

Body:
I have this code that I run upon the start of my application.  This way we can have a test environment and when we move the front end, it will automatically connect to the correct backend.  I use similar code in other applications to change the SQL backend but in this we are changing the Access backend database.

The code looks correct, when I run it using the msgbox, it shows the correct location that it should be updated to and I do not receive an error.  However, after the code runs it is still connected to the previous backend (it never changes).  What am I missing?

I have looked at other links here and my code looks correct from them. Here is my code:

Private Sub ChangeEnvironments()

    Dim connServer As String
    'MsgBox CurrentDb.TableDefs("LostToCompany").Connect
    Dim currDatabase As String: currDatabase = "MS Access;DATABASE=" & CurrentProject.Path & "\UNDERWRI.MDB"
    'MsgBox CurrentDb.TableDefs("LostToCompany").Connect & vbCrLf & vbCrLf & currDatabase
    CurrentDb.TableDefs("LostToCompany").Connect = currDatabase
    CurrentDb.TableDefs("LostToCompany").RefreshLink

End Sub


问:
EventBus Unable to start activity in java android
I'm building a treatment in an Android app and I want to send an EventBus from my Service class to my Activity.

So I put Event bus in onCreate() methode :

```<code>EventBus.getDefault().register(this);
</code>```

And I have this function that call the function showNFCAction that start the activity:

```<code>@Subscribe(threadMode = ThreadMode.MAIN, priority = 0)
public void onEventMainThread(NoSubscriberEvent event)
{
   Logger.d("No suscriber !");
   Intent intent = ((Intent) event.originalEvent);
      app.showNFCAction(intent);

}
</code>```

The function showNFCAction:

```<code>showNFCAction(Intent intent)  {
Intent intent = new Intent(Settings.ACTION_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
</code>```

But the new activity doesn't start.

Body:
I'm building a treatment in an Android app and I want to send an EventBus from my Service class to my Activity.

So I put Event bus in onCreate() methode :

EventBus.getDefault().register(this);

And I have this function that call the function showNFCAction that start the activity:

@Subscribe(threadMode = ThreadMode.MAIN, priority = 0)
public void onEventMainThread(NoSubscriberEvent event)
{
   Logger.d("No suscriber !");
   Intent intent = ((Intent) event.originalEvent);
      app.showNFCAction(intent);

}

The function showNFCAction:

showNFCAction(Intent intent)  {
Intent intent = new Intent(Settings.ACTION_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}

But the new activity doesn't start.


问:
How to make a bootstrap3 panel collapsible and expandable when clicking panel header?
I am using bootstrap v3.3.5 and I have the below code to make the panel collapse or expand upon clicking the panel heading.

What is wrong with this code? The bootstrap3 can't be upgraded in this project because of some limitations. Thanks for any suggestions!

```<code><div class="panel panel-default">
    <div class="panel-heading"
            data-toggle="collapse"
            data-target="#collapseOne" aria-controls="collapseOne" aria-expanded="true">

            View Content
    </div>
    <div id="collapseOne" class="collapse">
        <div class="panel-body">
            All the hidden content
        </div>
    </div>
</div>
</code>```

Body:
I am using bootstrap v3.3.5 and I have the below code to make the panel collapse or expand upon clicking the panel heading.

What is wrong with this code? The bootstrap3 can't be upgraded in this project because of some limitations. Thanks for any suggestions!

            View Content

            All the hidden content


问:
How to detect screen orientation size or view port on Using Bootstrap5?
As I am new to bootstrap, Just now I developed the videoCall layout, which is responsive, but I've checked the inspect tools using dimensions in some device viewport orientations that are not responsive.

body{
    margin: 0;
    transition: all 0.3s ease;
    overflow-y: hidden;
  }
  /* main video */
  .main-video video{
    transition: all 0.3s ease-in-out;
    position: absolute;
    object-fit: contain;
    height: 100vh;
    width: 100%;
    right: 0;
    left: 0;
    bottom: 0;
    z-index: -1;
  }

  #main-video{
    transition: all 0.3s ease-in-out;
  }

  .videoWrap{
    position: relative;
  max-width: 320px;
  display: inline-block;
  }
  .videoWrap #logo{
  position: absolute;
  bottom: 2rem;
  right: 1rem;
  }
  .videoWrap #logo img{
  width: 40px;
  }

  .video-list video{

  transition: all 0.3s ease-in-out;
  max-width: 320px;
  margin: 0 1rem 1rem 0;
  border-radius: 1.25rem;
  z-index: 2;
  }
  .user-name{
  color: #fff;
  float: left;
  padding: 0.125rem 0.25rem;
  background: #000;
  border-radius: 0.5rem;
  margin: 0.5rem 0 0 1rem;
  }
  @media screen and (max-width:768px){
  .videoWrap,
  .video-list video{
      max-width: 217px;
  }
  }

  @media only screen and (min-device-width: 200px) and (max-device-width: 992px) and (orientation:landscape) {
    .videoWrap,
    .video-list video{
        max-width: 150px;
    }
   .videoWrap, #dropDown {
      margin: -0.8rem 0.2rem -1.8rem -0.3rem;
      left: 31px;
      bottom: 4px;
    }
    .videoWrap .user-name{
      margin: -0.8rem 0.2rem -1.8rem -0.3rem;
      left: 31px;
      bottom: 4px;
    }
  }

  @media screen and (max-width:480px){
  .videoWrap,
  .video-list video{
      max-width: 149px;
      bottom: 4rem;
  }
  .videoWrap #logo{
    bottom: 1.5rem;
  }
  .videoWrap #logo img{
    width: 30px;
  }
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./style.css" />

<link rel="stylesheet" href="./bootstrap/bootstrap.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Document</title>
  </head>
  <body>

<div  class="container-fluid m-0" id="videos m-0">

      <div class="row vh-100 align-items-end align-items-lg-center m-0" >
  <div class="col-12 offset-lg-10 col-lg-2 text-center text-lg-end ">
        <div  id="Media">

      <div  class=" main-video mainVideoWrap" id="cardvideo_localstream">
         <video id="video-main" class="video1" src="https://www.dropbox.com/s/ve0apo59semvv70/example-video-1.mp4?raw=1 " muted autoplay loop type="video/mp4" ></video>
        <div class="card-img-overlay p-0  " id="mainCard">
          <div>
            <span class="text-capitalize user-name">
              <i class="icon-user pe-1"></i>videoBg
            </span>
            <div id="dropDown" class="dropdown float-end">
              <button class="btn btn-sm btn-danger me-3 mt-2 dropdown-toggle" type="button"  id="userMenu"   data-bs-toggle="dropdown"   aria-expanded="false">
                <i class="icon-dot"></i>
              </button>
              <ul id="drop"  class="dropdown-menu dropdown-menu-end"   aria-labelledby="userMenu"  >
                <li>

                    <i class="bi bi-mic-mute m-1"></i>Start Audio</a >
                  </li>
                <li>
                  <i class="bi bi-camera-video-off m-1"></i>Stop Video</a >
                </li>
                <li>
                  <i class="bi bi-person-x m-1"></i>Remove
                </li>
              </ul>
            </div>
          </div>

        </div>
      </div>

      <!-- <div class="row vh-100 align-items-end align-items-lg-center m-0"> -->
        <div class=" video-list listofvideos">
          <div class="position-relative videoWrap" id="cardvideo_remotestream">
            <video  src=" https://www.dropbox.com/s/se8r4svvnt2qpfu/example-video-2.mp4?raw=1 " muted  autoplay loop type="video/mp4" ></video>
            <div class="card-img-overlay p-0  " id="imgCard">
              <div>
                <span class="text-capitalize user-name">
                  <i class="icon-user pe-1"></i>videolist1
                </span>
                <div id="dropDown" class="dropdown float-end">
                  <button class="btn btn-sm btn-danger me-3 mt-2 dropdown-toggle"  type="button"  id="userMenu"  data-bs-toggle="dropdown"   aria-expanded="false">
                    <i class="icon-dot"></i>
                  </button>
                  <ul id="drop" class="dropdown-menu dropdown-menu-end" aria-labelledby="userMenu" >
                    <li>
                      id="dropdown_items" class="dropdown-item" href="#"  ><i class="bi bi-mic-mute m-1"></i>Start Audio</a  >
                    </li>
                    <li>
                      id="dropdown_items" class="dropdown-item" href="#"   ><i class="bi bi-camera-video-off m-1"></i>Stop Video</a >
                    </li>
                    <li>
                      id="dropdown_items" class="dropdown-item" href="#"  ><i class="bi bi-person-x m-1"></i>Remove</a  >
                    </li>
                  </ul>
                </div>
              </div>

            </div>
          </div>

          <div class="position-relative videoWrap" id="cardvideo_remotestream">
            <video   src=" https://www.dropbox.com/s/se8r4svvnt2qpfu/example-video-2.mp4?raw=1 "  muted  ></video>
            <div class="card-img-overlay p-0  " id="imgCard">
              <div>
                <span class="text-capitalize user-name">
                  <i class="icon-user pe-1"></i>videolist2
                </span>
                <div id="dropDown" class="dropdown float-end">
                  <button class="btn btn-sm btn-danger me-3 mt-2 dropdown-toggle"  type="button"   id="userMenu"  data-bs-toggle="dropdown"   aria-expanded="false" >
                    <i class="icon-dot"></i>
                  </button>
                  <ul  id="drop"   class="dropdown-menu dropdown-menu-end" aria-labelledby="userMenu" >
                    <li>
                 id="dropdown_items" class="dropdown-item" href="#"  ><i class="bi bi-mic-mute m-1"></i>Start Audio</a  >
                    </li>
                    <li>
                      id="dropdown_items" class="dropdown-item" href="#"  ><i class="bi bi-camera-video-off m-1"></i>Stop Video</a >
                    </li>
                    <li>
                      id="dropdown_items" class="dropdown-item" href="#"   ><i class="bi bi-person-x m-1"></i>Remove</a >
                    </li>
                  </ul>
                </div>
              </div>

            </div>
          </div>

          <div class="position-relative videoWrap" id="cardvideo_remotestream">
            <video  src=" https://www.dropbox.com/s/se8r4svvnt2qpfu/example-video-2.mp4?raw=1 "  muted  autoplay loop type="video/mp4"></video>
            <div class="card-img-overlay p-0  " id="imgCard">
              <div>
                <span class="text-capitalize user-name">
                  <i class="icon-user pe-1"></i>videolist3
                </span>
                <div id="dropDown" class="dropdown float-end">
                  <button class="btn btn-sm btn-danger me-3 mt-2 dropdown-toggle" type="button"  id="userMenu" data-bs-toggle="dropdown" aria-expanded="false" >
                    <i class="icon-dot"></i>
                  </button>
                  <ul id="drop" class="dropdown-menu dropdown-menu-end" aria-labelledby="userMenu">
                    <li>
                      id="dropdown_items" class="dropdown-item" href="#" ><i class="bi bi-mic-mute m-1"></i>Start Audio
                    </li>
                    <li>
                      id="dropdown_items" class="dropdown-item" href="#"><i class="bi bi-camera-video-off m-1"></i>Stop Video</a >
                    </li>
                    <li>
                      id="dropdown_items" class="dropdown-item" href="#" ><i class="bi bi-person-x m-1"></i>Remove
                    </li>
                  </ul>
                </div>
              </div>

            </div>
          </div>

          <div class="position-relative videoWrap" id="cardvideo_remotestream">
            <video  src=" https://www.dropbox.com/s/se8r4svvnt2qpfu/example-video-2.mp4?raw=1 " muted  autoplay loop type="video/mp4"></video>
            <div class="card-img-overlay p-0 " id="imgCard">
              <div>
                <span class="text-capitalize user-name">
                  <i class="icon-user pe-1"></i>videolist4
                </span>
                <div id="dropDown" class="dropdown float-end">
                  <button  class="btn btn-sm btn-danger me-3 mt-2 dropdown-toggle" type="button" id="userMenu" data-bs-toggle="dropdown" aria-expanded="false"
                  >
                    <i class="icon-dot"></i>
                  </button>
                  <ul  id="drop"  class="dropdown-menu dropdown-menu-end"  aria-labelledby="userMenu" >
                    <li>
                      id="dropdown_items" class="dropdown-item" href="#" ><i class="bi bi-mic-mute m-1"></i>Start Audio</a >
                    </li>
                    <li>  id="dropdown_items" class="dropdown-item" href="#"
                        ><i class="bi bi-camera-video-off m-1"></i>Stop Video</a  >
                    </li>
                    <li>
                      id="dropdown_items" class="dropdown-item" href="#"
                        ><i class="bi bi-person-x m-1"></i>Remove</a  >
                    </li>
                  </ul>
                </div>
              </div>

            </div>
          </div>
        <!-- </div> -->
      </div>

      <!-- row column -->
    </div>
    </div>

  </div>
  </div>
  </body>
  <script src="./bootstrap/bootstrap.bundle.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

</html></code>```

I need to,

while in landscape orientation the list of videos(class name -> videolists) align vertically in right side corner, while in portrait orientation the list of videos will be aligned horizontally bottom,

How to detect screen orientation size  Bootstrap5?

Body:
As I am new to bootstrap, Just now I developed the videoCall layout, which is responsive, but I've checked the inspect tools using dimensions in some device viewport orientations that are not responsive.

body{
    margin: 0;
    transition: all 0.3s ease;
    overflow-y: hidden;
  }
  /* main video */
  .main-video video{
    transition: all 0.3s ease-in-out;
    position: absolute;
    object-fit: contain;
    height: 100vh;
    width: 100%;
    right: 0;
    left: 0;
    bottom: 0;
    z-index: -1;
  }

  #main-video{
    transition: all 0.3s ease-in-out;
  }

  .videoWrap{
    position: relative;
  max-width: 320px;
  display: inline-block;
  }
  .videoWrap #logo{
  position: absolute;
  bottom: 2rem;
  right: 1rem;
  }
  .videoWrap #logo img{
  width: 40px;
  }

  .video-list video{

  transition: all 0.3s ease-in-out;
  max-width: 320px;
  margin: 0 1rem 1rem 0;
  border-radius: 1.25rem;
  z-index: 2;
  }
  .user-name{
  color: #fff;
  float: left;
  padding: 0.125rem 0.25rem;
  background: #000;
  border-radius: 0.5rem;
  margin: 0.5rem 0 0 1rem;
  }
  @media screen and (max-width:768px){
  .videoWrap,
  .video-list video{
      max-width: 217px;
  }
  }

  @media only screen and (min-device-width: 200px) and (max-device-width: 992px) and (orientation:landscape) {
    .videoWrap,
    .video-list video{
        max-width: 150px;
    }
   .videoWrap, #dropDown {
      margin: -0.8rem 0.2rem -1.8rem -0.3rem;
      left: 31px;
      bottom: 4px;
    }
    .videoWrap .user-name{
      margin: -0.8rem 0.2rem -1.8rem -0.3rem;
      left: 31px;
      bottom: 4px;
    }
  }

  @media screen and (max-width:480px){
  .videoWrap,
  .video-list video{
      max-width: 149px;
      bottom: 4rem;
  }
  .videoWrap #logo{
    bottom: 1.5rem;
  }
  .videoWrap #logo img{
    width: 30px;
  }
  }

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="./style.css" />

<link rel="stylesheet" href="./bootstrap/bootstrap.min.css">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

    <title>Document</title>

         <video id="video-main" class="video1" src="https://www.dropbox.com/s/ve0apo59semvv70/example-video-1.mp4?raw=1 " muted autoplay loop type="video/mp4" ></video>

              videoBg

              <button class="btn btn-sm btn-danger me-3 mt-2 dropdown-toggle" type="button"  id="userMenu"   data-bs-toggle="dropdown"   aria-expanded="false">

              </button>

                    Start Audio

                  Stop Video

                  Remove

            <video  src=" https://www.dropbox.com/s/se8r4svvnt2qpfu/example-video-2.mp4?raw=1 " muted  autoplay loop type="video/mp4" ></video>

                  videolist1

                  <button class="btn btn-sm btn-danger me-3 mt-2 dropdown-toggle"  type="button"  id="userMenu"  data-bs-toggle="dropdown"   aria-expanded="false">

                  </button>

                      Start Audio

                      Stop Video

                      Remove

            <video   src=" https://www.dropbox.com/s/se8r4svvnt2qpfu/example-video-2.mp4?raw=1 "  muted  ></video>

                  videolist2

                  <button class="btn btn-sm btn-danger me-3 mt-2 dropdown-toggle"  type="button"   id="userMenu"  data-bs-toggle="dropdown"   aria-expanded="false" >

                  </button>

                 Start Audio

                      Stop Video

                      Remove

            <video  src=" https://www.dropbox.com/s/se8r4svvnt2qpfu/example-video-2.mp4?raw=1 "  muted  autoplay loop type="video/mp4"></video>

                  videolist3

                  <button class="btn btn-sm btn-danger me-3 mt-2 dropdown-toggle" type="button"  id="userMenu" data-bs-toggle="dropdown" aria-expanded="false" >

                  </button>

                      Start Audio

                      Stop Video

                      Remove

            <video  src=" https://www.dropbox.com/s/se8r4svvnt2qpfu/example-video-2.mp4?raw=1 " muted  autoplay loop type="video/mp4"></video>

                  videolist4

                  <button  class="btn btn-sm btn-danger me-3 mt-2 dropdown-toggle" type="button" id="userMenu" data-bs-toggle="dropdown" aria-expanded="false"
                  >

                  </button>

                      Start Audio

  Stop Video

                      Remove

I need to,

while in landscape orientation the list of videos(class name -> videolists) align vertically in right side corner, while in portrait orientation the list of videos will be aligned horizontally bottom,

How to detect screen orientation size  Bootstrap5?


问:
ModuleNotFoundError in tests in GitLab pipeline for AWS SAM
I have a GitLab pipeline for AWS SAM that deploys API and Lambdas in one stage and in another stage I want to run tests. Deployment works and tests work on my machine but when I try to run those tests in the GitLab pipeline I'm getting ModuleNotFoundError when trying to import either the lambda_handlers in unit tests or layer dependencies in integration tests.
That's the SAM app structure:

```<code>api
├── dependencies
│   └── responses.py
├── lambdas
│   └── files
│       └── s3_files.py
└── tests
    ├── integ
    │   └── test_s3_files.py
    └── unit
        └── test_s3_files.py
</code>```

Import in s3_files.py Lambda:

```<code>from responses import ok_response, internal_error_response, invalid_request_response
</code>```

Imports in tests/unit/test_s3_files.py:

```<code>from lambdas.files.s3_files import lambda_handler
from dependencies.responses import ok_response, invalid_request_response
</code>```

When I run python -m pytest tests/unit -v from api/locally it works fine. But when I try that in the GitLab pipeline I get this output relating to rootdir and the following error:

```<code>rootdir: /builds/<my-user>/<project-name>/api/tests, configfile: pytest.ini
...
ImportError while importing test module '/builds/<my-user>/<project-name>/api/tests/unit/test_s3_files.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/var/lang/lib/python3.9/importlib/__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/unit/test_s3_files.py:1: in <module>
    from lambdas.files.s3_files import lambda_handler
lambdas/files/s3_files.py:1: in <module>
    from responses import ok_response, internal_error_response, invalid_request_response
E   ModuleNotFoundError: No module named 'responses'
</code>```

What I tried:

changed the s3_files.py import to from dependencies.responses import ok_response ...
but that leads to error when testing with sam local start-api, specifically: Runtime.ImportModuleError Unable to import module 's3_files': No module named 'dependencies'

providing variable PYTHONPATH:$PWD/dependencies in the .gitlab.ci script for the testing stage, locally the PYTHONPATH points to $PWD/dependencies in order to get pytest working when in api/ folder

specifying GitLabs jobs artifacts to

```<code>artifacts:
   paths:
     - /builds/<my-user>/<project-name>/api
</code>```

I figured that the error is related to either the PYTHONPATH variable or the rootdir. When running the test I'm importing the s3_files.lambda_handler which in its turn tries to import responses from responses.py. Could it be related to the rootdir in the GitLab runner environment? How can one specify different root directory or PYTHONPATH in jobs? Or is the problem somewhere else?

Body:
I have a GitLab pipeline for AWS SAM that deploys API and Lambdas in one stage and in another stage I want to run tests. Deployment works and tests work on my machine but when I try to run those tests in the GitLab pipeline I'm getting ModuleNotFoundError when trying to import either the lambda_handlers in unit tests or layer dependencies in integration tests.
That's the SAM app structure:

api
├── dependencies
│   └── responses.py
├── lambdas
│   └── files
│       └── s3_files.py
└── tests
    ├── integ
    │   └── test_s3_files.py
    └── unit
        └── test_s3_files.py

Import in s3_files.py Lambda:

from responses import ok_response, internal_error_response, invalid_request_response

Imports in tests/unit/test_s3_files.py:

from lambdas.files.s3_files import lambda_handler
from dependencies.responses import ok_response, invalid_request_response

When I run python -m pytest tests/unit -v from api/locally it works fine. But when I try that in the GitLab pipeline I get this output relating to rootdir and the following error:

rootdir: /builds/<my-user>/<project-name>/api/tests, configfile: pytest.ini
...
ImportError while importing test module '/builds/<my-user>/<project-name>/api/tests/unit/test_s3_files.py'.
Hint: make sure your test modules/packages have valid Python names.
Traceback:
/var/lang/lib/python3.9/importlib/__init__.py:127: in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
tests/unit/test_s3_files.py:1: in <module>
    from lambdas.files.s3_files import lambda_handler
lambdas/files/s3_files.py:1: in <module>
    from responses import ok_response, internal_error_response, invalid_request_response
E   ModuleNotFoundError: No module named 'responses'

What I tried:

changed the s3_files.py import to from dependencies.responses import ok_response ...
but that leads to error when testing with sam local start-api, specifically: Runtime.ImportModuleError Unable to import module 's3_files': No module named 'dependencies'

providing variable PYTHONPATH:$PWD/dependencies in the .gitlab.ci script for the testing stage, locally the PYTHONPATH points to $PWD/dependencies in order to get pytest working when in api/ folder

specifying GitLabs jobs artifacts to

artifacts:
   paths:
     - /builds/<my-user>/<project-name>/api

I figured that the error is related to either the PYTHONPATH variable or the rootdir. When running the test I'm importing the s3_files.lambda_handler which in its turn tries to import responses from responses.py. Could it be related to the rootdir in the GitLab runner environment? How can one specify different root directory or PYTHONPATH in jobs? Or is the problem somewhere else?


问:
use spark streaming by python to computed the data from local file system
Python version is 3.11.1
pyspark version is 3.3.1
the scala version is 2.12.15
the openJDK 64-Bit Server Vm is 17.0.2

```<code>

import movie_rate_system.sparkClient.sparkApplication as sparkUtil

ratingsDict = "file:///D:/movieRateProject/MovieRate/movie_rate_system/resource/streaming"

# movieRateStream = sparkUtil.SparkStreaming.textFileStream(movieFile)
def consumerData(line):
    if line.isEmpty():
        print(line.collect())

if __name__ == "__main__":
    # movieRateStream = sparkUtil.SparkStreaming.textFileStream(movieFile)
    sparkStream = sparkUtil.SparkStreaming

    fileStream = sparkStream.textFileStream(ratingsDict)
    #
    # lines = fileStream.flatMap(lambda line: line.split(","))
    lines.foreachRDD(lambda rdd : consumerData(rdd))
    sparkStream.start()
    sparkStream.awaitTermination()
</code>```

movie_rate_system.sparkClient.sparkApplication as sparkUtil,the main code is quoted by above are as follows

```<code>
SparkSession = pyspark.sql.SparkSession.builder.appName("movieRate").master("local[2]").getOrCreate()
SparkStreaming = StreamingContext(SparkSession.sparkContext, 5)

def GetSparkSession():
    return SparkSession

def GetSparkStreaming():
    return SparkStreaming
</code>```

when i use spark streaming to complete the type of transformations operation, the programming always catch this error to me. I cant understand why this error can occur by thiss programming.
enter image description here

I think the key error is this:
enter image description here

To my confused,when i delete the fileStream.flatMap,which is equal to delete the transformations operation,i run this programming which only to execute the foreachRDD method,the key source code  are as follows.

```<code> #movieRateStream = sparkUtil.SparkStreaming.textFileStream(movieFile)
def consumerData(line):
    if line.isEmpty():
        print(line.collect())

if __name__ == "__main__":
    # movieRateStream = sparkUtil.SparkStreaming.textFileStream(movieFile)
    sparkStream = sparkUtil.SparkStreaming

    fileStream = sparkStream.textFileStream(ratingsDict)
    #
    # lines = fileStream.flatMap(lambda line: line.split(","))
    fileStream.foreachRDD(lambda rdd : consumerData(rdd))
    sparkStream.start()
    sparkStream.awaitTermination()
</code>```

Obviously,the programming can successfully run.
enter image description here

Body:
Python version is 3.11.1
pyspark version is 3.3.1
the scala version is 2.12.15
the openJDK 64-Bit Server Vm is 17.0.2

import movie_rate_system.sparkClient.sparkApplication as sparkUtil

ratingsDict = "file:///D:/movieRateProject/MovieRate/movie_rate_system/resource/streaming"

# movieRateStream = sparkUtil.SparkStreaming.textFileStream(movieFile)
def consumerData(line):
    if line.isEmpty():
        print(line.collect())

if __name__ == "__main__":
    # movieRateStream = sparkUtil.SparkStreaming.textFileStream(movieFile)
    sparkStream = sparkUtil.SparkStreaming

    fileStream = sparkStream.textFileStream(ratingsDict)
    #
    # lines = fileStream.flatMap(lambda line: line.split(","))
    lines.foreachRDD(lambda rdd : consumerData(rdd))
    sparkStream.start()
    sparkStream.awaitTermination()

movie_rate_system.sparkClient.sparkApplication as sparkUtil,the main code is quoted by above are as follows

SparkSession = pyspark.sql.SparkSession.builder.appName("movieRate").master("local[2]").getOrCreate()
SparkStreaming = StreamingContext(SparkSession.sparkContext, 5)

def GetSparkSession():
    return SparkSession

def GetSparkStreaming():
    return SparkStreaming

when i use spark streaming to complete the type of transformations operation, the programming always catch this error to me. I cant understand why this error can occur by thiss programming.
enter image description here

I think the key error is this:
enter image description here

To my confused,when i delete the fileStream.flatMap,which is equal to delete the transformations operation,i run this programming which only to execute the foreachRDD method,the key source code  are as follows.

 #movieRateStream = sparkUtil.SparkStreaming.textFileStream(movieFile)
def consumerData(line):
    if line.isEmpty():
        print(line.collect())

if __name__ == "__main__":
    # movieRateStream = sparkUtil.SparkStreaming.textFileStream(movieFile)
    sparkStream = sparkUtil.SparkStreaming

    fileStream = sparkStream.textFileStream(ratingsDict)
    #
    # lines = fileStream.flatMap(lambda line: line.split(","))
    fileStream.foreachRDD(lambda rdd : consumerData(rdd))
    sparkStream.start()
    sparkStream.awaitTermination()

Obviously,the programming can successfully run.
enter image description here


问:
Angular compile scss on html change
I want to know if there is a way to tell the Angular compiler to compile a components style file when the template file is modified?

For example, when I change app.component.html then app.component.scss should also be compiled.

The reason is, I want to use tailwind in a component which set its encapsulation to ViewEncapsulation.ShadowDom, so when I set a new tailwind class in my app.component.html then nothing happens until I also save my app.component.scss file which contains my tailwind imports.

Code example

app.component.html

```<code><div class="text-5xl">Hello World</div>
</code>```

app.component.ts

```<code>import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  encapsulation: ViewEncapsulation.ShadowDom,
})
export class AppComponent {
  title = 'Test';
}
</code>```

app.component.scss

```<code>@tailwind base;
@tailwind components;
@tailwind utilities;

html,
body {
    height: 100%;
}

body {
    margin: 0;
    font-family: Roboto, "Helvetica Neue", sans-serif;
}
</code>```

I looked up if there is a flag which can be set in angular.json or tsconfig.json and I found the flag allowEmptyCodegenFiles, but it didn't work. Maybe it can be done through webpack, but my webpack knowledge is very limited.

Title: Angular compile scss on html change

Body:
I want to know if there is a way to tell the Angular compiler to compile a components style file when the template file is modified?

For example, when I change app.component.html then app.component.scss should also be compiled.

The reason is, I want to use tailwind in a component which set its encapsulation to ViewEncapsulation.ShadowDom, so when I set a new tailwind class in my app.component.html then nothing happens until I also save my app.component.scss file which contains my tailwind imports.

Code example

app.component.html

Hello World

app.component.ts

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
  encapsulation: ViewEncapsulation.ShadowDom,
})
export class AppComponent {
  title = 'Test';
}

app.component.scss

@tailwind base;
@tailwind components;
@tailwind utilities;

html,
body {
    height: 100%;
}

body {
    margin: 0;
    font-family: Roboto, "Helvetica Neue", sans-serif;
}

I looked up if there is a flag which can be set in angular.json or tsconfig.json and I found the flag allowEmptyCodegenFiles, but it didn't work. Maybe it can be done through webpack, but my webpack knowledge is very limited.


问:
Is there more efficient way to get a value of existing row in Sequelize when creating a new object and using retrieved object's value as FK?
I have a collection of countries in Sequelize, in a table that has the following columns:

id

alpha2

countryCode

I have another model, the Address that has a relation to the country:

```<code>const Address = sequelize.define('Address', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true
  },
  street: {
    type: Sequelize.STRING
  },
  country: {
    type: Sequelize.INTEGER
  }
});
</code>```

When creating a new row in the address table, I would like to retrieve an ID of the specific country by retrieving it by it's country code, and store it in the country column:

```<code>await Address.create(
  country: await Country.findOne({
    where: {alpha2: 'HR'},
    attributes: ['id']
  }).then(result => result.id),
  street: req.body.street
)
</code>```

This works, but I'm not sure if it is the most efficient way, and if this a best practice.
Is there a way to write something that would in SQL look like this:

```<code>INSERT INTO Address (country, street) VALUES
((SELECT ID FROM Country WHERE alpha2 = 'HR'), 'Some street');
</code>```

And if it is possible, is it worth it doing it that way, or it would add more code complexity without many benefits?

Thanks in advance!

Body:
I have a collection of countries in Sequelize, in a table that has the following columns:

id

alpha2

countryCode

I have another model, the Address that has a relation to the country:

const Address = sequelize.define('Address', {
  id: {
    type: Sequelize.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true
  },
  street: {
    type: Sequelize.STRING
  },
  country: {
    type: Sequelize.INTEGER
  }
});

When creating a new row in the address table, I would like to retrieve an ID of the specific country by retrieving it by it's country code, and store it in the country column:

await Address.create(
  country: await Country.findOne({
    where: {alpha2: 'HR'},
    attributes: ['id']
  }).then(result => result.id),
  street: req.body.street
)

This works, but I'm not sure if it is the most efficient way, and if this a best practice.
Is there a way to write something that would in SQL look like this:

INSERT INTO Address (country, street) VALUES
((SELECT ID FROM Country WHERE alpha2 = 'HR'), 'Some street');

And if it is possible, is it worth it doing it that way, or it would add more code complexity without many benefits?

Thanks in advance!


问:
Fabric Js: How to implement custom control correctly in Angular JS?
I am trying to implement custom controls for polyline object in Fabric.js. I am taking the reference for the control from one of their demo for polygon as found here: http://fabricjs.com/custom-controls-polygon

I am new to the fabric js and trying to understand how can I define the custom control inside my Angular app. So far I have tried structuring the code as below:

```<code>constructor () {
fabric.Object.prototype.addControlPoints = function() {
      var lastControl = this.points.length - 1;
      this.cornerStyle = 'circle';
      this.cornerColor = 'rgba(255,255,255,1)';
      this.cornerSize = 12;
      this.cornerStrokeColor = 'rgba(255,255,255,1)';
      this.controls = this.points.reduce(function(acc, point, index) {
        acc['p' + index] = new fabric.Control({
          positionHandler: polygonPositionHandler,
          actionHandler: anchorWrapper(index > 0 ? index - 1 : lastControl, actionHandler),
          actionName: 'modifyPolygon',
          pointIndex: index
        });
        return acc;
      }, { });
      console.log("Done")
    };

    function polygonPositionHandler(dim, finalMatrix, fabricObject) {
      var x = (fabricObject.points[this.pointIndex].x - fabricObject.pathOffset.x),
          y = (fabricObject.points[this.pointIndex].y - fabricObject.pathOffset.y);
      return fabric.util.transformPoint(
        { x: x, y: y },
        fabric.util.multiplyTransformMatrices(
          fabricObject.canvas.viewportTransform,
          fabricObject.calcTransformMatrix()
        )
      );
    }

    function getObjectSizeWithStroke(object) {
      var stroke = new fabric.Point(
        object.strokeUniform ? 1 / object.scaleX : 1,
        object.strokeUniform ? 1 / object.scaleY : 1
      ).multiply(object.strokeWidth);
      return new fabric.Point(object.width + stroke.x, object.height + stroke.y);
    }

    function actionHandler(eventData, transform, x, y) {
      var polygon = transform.target,
          currentControl = polygon.controls[polygon.__corner],
          mouseLocalPosition = polygon.toLocalPoint(new fabric.Point(x, y), 'center', 'center'),
          polygonBaseSize = getObjectSizeWithStroke(polygon),
          size = polygon._getTransformedDimensions(0, 0),
          finalPointPosition = {
            x: mouseLocalPosition.x * polygonBaseSize.x / size.x + polygon.pathOffset.x,
            y: mouseLocalPosition.y * polygonBaseSize.y / size.y + polygon.pathOffset.y
          };
      polygon.points[currentControl.pointIndex] = finalPointPosition;
      return true;
    }

    function anchorWrapper(anchorIndex, fn) {
      return function(eventData, transform, x, y) {
        var fabricObject = transform.target,
            absolutePoint = fabric.util.transformPoint({
                x: (fabricObject.points[anchorIndex].x - fabricObject.pathOffset.x),
                y: (fabricObject.points[anchorIndex].y - fabricObject.pathOffset.y),
            }, fabricObject.calcTransformMatrix()),
            actionPerformed = fn(eventData, transform, x, y),
            newDim = fabricObject._setPositionDimensions({}),
            polygonBaseSize = getObjectSizeWithStroke(fabricObject),
            newX = (fabricObject.points[anchorIndex].x - fabricObject.pathOffset.x) / polygonBaseSize.x,
            newY = (fabricObject.points[anchorIndex].y - fabricObject.pathOffset.y) / polygonBaseSize.y;
        fabricObject.setPositionByOrigin(absolutePoint, newX + 0.5, newY + 0.5);
        return actionPerformed;
      }
    }
}

addPolyLine() {
    var poly = new fabric.Polyline(points, {
      strokeWidth: 2,
      fill: '',
      stroke: 'red',
      originX: 'center',
      originY: 'center',
      hasRotatingPoint: false,
      selection: true,
      hasBorders: false,
      hasControls: true,
      perPixelTargetFind: true,
      lockUniScaling: true,
      cornerColor: '#FFF',
      cornerSize: 10,
      cornerStyle: 'circle',
      lockMovementX: true,
      lockMovementY: true,
      lockScalingX: true,
      lockScalingY: true,
      hidden: false
    });
    this.canvas.selection = false;

    poly.addControlPoints();  // <----- THIS IS WHERE I AM APPLYING THE CUSTOM CONTROL

    this.canvas.add(poly);

    this.canvas.sendToBack(poly);

    poly.setCoords();

    this.canvas.renderAll();
  }
</code>```

The problem I am facing is whenever I draw the polyline, the controls are not showing but after drawing when I click on the polyline, the controls appear. Any idea how can I show the controls upon polyline draw ????? Is the structuring of my custom control correct ??? Please help.

Thanks.

Body:
I am trying to implement custom controls for polyline object in Fabric.js. I am taking the reference for the control from one of their demo for polygon as found here: http://fabricjs.com/custom-controls-polygon

I am new to the fabric js and trying to understand how can I define the custom control inside my Angular app. So far I have tried structuring the code as below:

constructor () {
fabric.Object.prototype.addControlPoints = function() {
      var lastControl = this.points.length - 1;
      this.cornerStyle = 'circle';
      this.cornerColor = 'rgba(255,255,255,1)';
      this.cornerSize = 12;
      this.cornerStrokeColor = 'rgba(255,255,255,1)';
      this.controls = this.points.reduce(function(acc, point, index) {
        acc['p' + index] = new fabric.Control({
          positionHandler: polygonPositionHandler,
          actionHandler: anchorWrapper(index > 0 ? index - 1 : lastControl, actionHandler),
          actionName: 'modifyPolygon',
          pointIndex: index
        });
        return acc;
      }, { });
      console.log("Done")
    };

    function polygonPositionHandler(dim, finalMatrix, fabricObject) {
      var x = (fabricObject.points[this.pointIndex].x - fabricObject.pathOffset.x),
          y = (fabricObject.points[this.pointIndex].y - fabricObject.pathOffset.y);
      return fabric.util.transformPoint(
        { x: x, y: y },
        fabric.util.multiplyTransformMatrices(
          fabricObject.canvas.viewportTransform,
          fabricObject.calcTransformMatrix()
        )
      );
    }

    function getObjectSizeWithStroke(object) {
      var stroke = new fabric.Point(
        object.strokeUniform ? 1 / object.scaleX : 1,
        object.strokeUniform ? 1 / object.scaleY : 1
      ).multiply(object.strokeWidth);
      return new fabric.Point(object.width + stroke.x, object.height + stroke.y);
    }

    function actionHandler(eventData, transform, x, y) {
      var polygon = transform.target,
          currentControl = polygon.controls[polygon.__corner],
          mouseLocalPosition = polygon.toLocalPoint(new fabric.Point(x, y), 'center', 'center'),
          polygonBaseSize = getObjectSizeWithStroke(polygon),
          size = polygon._getTransformedDimensions(0, 0),
          finalPointPosition = {
            x: mouseLocalPosition.x * polygonBaseSize.x / size.x + polygon.pathOffset.x,
            y: mouseLocalPosition.y * polygonBaseSize.y / size.y + polygon.pathOffset.y
          };
      polygon.points[currentControl.pointIndex] = finalPointPosition;
      return true;
    }

    function anchorWrapper(anchorIndex, fn) {
      return function(eventData, transform, x, y) {
        var fabricObject = transform.target,
            absolutePoint = fabric.util.transformPoint({
                x: (fabricObject.points[anchorIndex].x - fabricObject.pathOffset.x),
                y: (fabricObject.points[anchorIndex].y - fabricObject.pathOffset.y),
            }, fabricObject.calcTransformMatrix()),
            actionPerformed = fn(eventData, transform, x, y),
            newDim = fabricObject._setPositionDimensions({}),
            polygonBaseSize = getObjectSizeWithStroke(fabricObject),
            newX = (fabricObject.points[anchorIndex].x - fabricObject.pathOffset.x) / polygonBaseSize.x,
            newY = (fabricObject.points[anchorIndex].y - fabricObject.pathOffset.y) / polygonBaseSize.y;
        fabricObject.setPositionByOrigin(absolutePoint, newX + 0.5, newY + 0.5);
        return actionPerformed;
      }
    }
}

addPolyLine() {
    var poly = new fabric.Polyline(points, {
      strokeWidth: 2,
      fill: '',
      stroke: 'red',
      originX: 'center',
      originY: 'center',
      hasRotatingPoint: false,
      selection: true,
      hasBorders: false,
      hasControls: true,
      perPixelTargetFind: true,
      lockUniScaling: true,
      cornerColor: '#FFF',
      cornerSize: 10,
      cornerStyle: 'circle',
      lockMovementX: true,
      lockMovementY: true,
      lockScalingX: true,
      lockScalingY: true,
      hidden: false
    });
    this.canvas.selection = false;

    poly.addControlPoints();  // <----- THIS IS WHERE I AM APPLYING THE CUSTOM CONTROL

    this.canvas.add(poly);

    this.canvas.sendToBack(poly);

    poly.setCoords();

    this.canvas.renderAll();
  }

The problem I am facing is whenever I draw the polyline, the controls are not showing but after drawing when I click on the polyline, the controls appear. Any idea how can I show the controls upon polyline draw ????? Is the structuring of my custom control correct ??? Please help.

Thanks.


问:
Error while performing ridge regression with dummy variables
I'm new to R and I'm analyzing a dataset with qualitative and quantitative variables.The dataset is this one. I want to perform a Ridge regression, so I did this:

```<code>library(caret)

set.seed(3)
train_index <- sample(1:nrow(Data1), round(nrow(Data1) * 0.7))

train <- Data1[train_index, ]
nrow(train) / nrow(Data1)

test <- Data1[-train_index, ]
nrow(test) / nrow(Data1)
</code>```

and then, to transform the qualitative variables with dummy:

```<code>train_mat <- dummyVars(`Time spent on social media` ~ ., data = train, fullRank = F) %>%
  predict(newdata = train) %>%
  as.matrix()

test_mat <- dummyVars(`Time spent on social media` ~ ., data = test, fullRank = F) %>%
  predict(newdata = test) %>%
  as.matrix()
</code>```

The problem is that the train and test matrix have different numbers of variables and I don't understand why.

I thought there could be some problem with the dummy transformation so I used also dummy-cols but nothing changed

Body:
I'm new to R and I'm analyzing a dataset with qualitative and quantitative variables.The dataset is this one. I want to perform a Ridge regression, so I did this:

library(caret)

set.seed(3)
train_index <- sample(1:nrow(Data1), round(nrow(Data1) * 0.7))

train <- Data1[train_index, ]
nrow(train) / nrow(Data1)

test <- Data1[-train_index, ]
nrow(test) / nrow(Data1)

and then, to transform the qualitative variables with dummy:

train_mat <- dummyVars(`Time spent on social media` ~ ., data = train, fullRank = F) %>%
  predict(newdata = train) %>%
  as.matrix()

test_mat <- dummyVars(`Time spent on social media` ~ ., data = test, fullRank = F) %>%
  predict(newdata = test) %>%
  as.matrix()

The problem is that the train and test matrix have different numbers of variables and I don't understand why.

I thought there could be some problem with the dummy transformation so I used also dummy-cols but nothing changed


问:
Vagrant provisioning script installs software (Pyenv) which requires shell restart
I am using Vagrant to spin up an Ubuntu box and run a shell script which configures the VM to use Pyenv. The Pyenv docs recommend restarting the shell after installation & configuration.

Having exec "$SHELL" in the middle of the script interrupts Vagrant's provisioning, so I opted to split the commands across two files.

vagrantfile:

```<code>Vagrant.configure("2") do |config|

  config.vm.box = "hashicorp/bionic64"

  config.vm.synced_folder ".", "/vagrant", disabled: true

  config.vm.provision "shell", path: "one.sh", privileged: false
  config.vm.provision "shell", path: "two.sh", privileged: false

end
</code>```

one.sh:

```<code>#!/bin/bash

# Install PyEnv

curl https://pyenv.run | bash
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc

exec "$SHELL"
</code>```

two.sh:

```<code>#!/bin/bash

# install python build deps
sudo apt update && sudo apt install -y make build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev \
libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev python-openssl git

pyenv install 3.10

ten=$(pyenv latest 3.10)

pyenv global $ten

# Install Poetry
curl -sSL https://install.python-poetry.org | python3.10 -
export PATH="/home/vagrant/.local/bin:$PATH"

# Install Nox
python3.10 -m pip install --user --upgrade nox
</code>```

FWIW the vagrant command I run is:

vagrant up --provider=hyperv

When the second script attempts to execute the pyenv commands, its not found:

default: /tmp/vagrant-shell: line 12: pyenv: command not found
However, I am then able to vagrant ssh into the VM where I can manually execute everything as I would expect.

```<code>vagrant ssh
vagrant@ubuntu-18:~$ pyenv --version
pyenv 2.3.9
</code>```

I would expect the second provision script to 'pick up' where the last one stopped, or at the very least not have a differently configured environment to when I subsequently vagrant ssh into the VM.

I have tried with each of the 'reset' and 'reboot' options set to true on the first provisioning script. result was the same.

Body:
I am using Vagrant to spin up an Ubuntu box and run a shell script which configures the VM to use Pyenv. The Pyenv docs recommend restarting the shell after installation & configuration.

Having exec "$SHELL" in the middle of the script interrupts Vagrant's provisioning, so I opted to split the commands across two files.

vagrantfile:

Vagrant.configure("2") do |config|

  config.vm.box = "hashicorp/bionic64"

  config.vm.synced_folder ".", "/vagrant", disabled: true

  config.vm.provision "shell", path: "one.sh", privileged: false
  config.vm.provision "shell", path: "two.sh", privileged: false

end

one.sh:

#!/bin/bash

# Install PyEnv

curl https://pyenv.run | bash
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc

exec "$SHELL"

two.sh:

#!/bin/bash

# install python build deps
sudo apt update && sudo apt install -y make build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev \
libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev python-openssl git

pyenv install 3.10

ten=$(pyenv latest 3.10)

pyenv global $ten

# Install Poetry
curl -sSL https://install.python-poetry.org | python3.10 -
export PATH="/home/vagrant/.local/bin:$PATH"

# Install Nox
python3.10 -m pip install --user --upgrade nox

FWIW the vagrant command I run is:

vagrant up --provider=hyperv

When the second script attempts to execute the pyenv commands, its not found:

default: /tmp/vagrant-shell: line 12: pyenv: command not found
However, I am then able to vagrant ssh into the VM where I can manually execute everything as I would expect.

vagrant ssh
vagrant@ubuntu-18:~$ pyenv --version
pyenv 2.3.9

I would expect the second provision script to 'pick up' where the last one stopped, or at the very least not have a differently configured environment to when I subsequently vagrant ssh into the VM.

I have tried with each of the 'reset' and 'reboot' options set to true on the first provisioning script. result was the same.


问:
Spark on Kubernetes processing in Azure Redis 250 milion records from parquet files - how to configure it correctly?
I'm running Spark drivers on AKS cluster pods. Spark job is to pick up 250 milions of records from Azure Storage from given location >> create dataframe from them >> select one column >> create a list by Pandas toList() method >> take list and check existance of each record from list in Redis DB >> return results to driver for further processing

Provided data is splitted in 50 parquet files, each one containing 5 milion of records.

DAG from job failing:

DAG from job failing

Stage failing:

Stage failing

Because of node specification I have limited compute power. For now, this is configuration of Spark, that I have:

```<code>    spark.driver.maxResultSize=5G
    spark.driver.memory=10G
    spark.executor.memory=8G
    spark.executor.cores=3
    spark.driver.cores=3
    spark.executor.instances=10
    spark.sql.sources.partitionOverwriteMode=dynamic
    spark.driver.memoryOverhead=0
    spark.executor.memoryOverhead=2G

</code>```

and defined in code:

```<code>spark_conf.set('spark.default.parallelism', num_executors * executor_cores)
spark_conf.set('spark.sql.shuffle.partitions', num_executors * executor_cores)
</code>```

Error received on driver Pod:

```<code>[Stage 1:======================================================>  (38 + 2) / 40]

[Stage 1:=======================================================> (39 + 1) / 40]

[Stage 2:>                                                        (0 + 24) / 30]

[Stage 2:>                                                        (0 + 25) / 30]

[Stage 2:>                                                        (0 + 27) / 30]

[Stage 2:>                                                        (0 + 28) / 30]

[Stage 2:>                                                        (0 + 29) / 30]

[Stage 2:>                                                        (0 + 30) / 30]

[Stage 2:=>                                                       (1 + 29) / 30]
[2022-12-28 15:28:45,156: ERROR/ForkPoolWorker-1] Exception while sending command.
2022-12-28T16:28:45+01:00 Traceback (most recent call last):
2022-12-28T16:28:45+01:00   File "/opt/spark/python/pyspark/sql/pandas/conversion.py", line 241, in _collect_as_arrow
2022-12-28T16:28:45+01:00     results = list(_load_from_socket((port, auth_secret), ArrowCollectSerializer()))
2022-12-28T16:28:45+01:00   File "/opt/spark/python/pyspark/sql/pandas/serializers.py", line 60, in load_stream
2022-12-28T16:28:45+01:00     for batch in self.serializer.load_stream(stream):
2022-12-28T16:28:45+01:00   File "/opt/spark/python/pyspark/sql/pandas/serializers.py", line 99, in load_stream
2022-12-28T16:28:45+01:00     for batch in reader:
2022-12-28T16:28:45+01:00   File "pyarrow/ipc.pxi", line 436, in __iter__
2022-12-28T16:28:45+01:00   File "pyarrow/ipc.pxi", line 468, in pyarrow.lib.RecordBatchReader.read_next_batch
2022-12-28T16:28:45+01:00   File "pyarrow/error.pxi", line 99, in pyarrow.lib.check_status
2022-12-28T16:28:45+01:00 OSError: Expected to be able to read 449936 bytes for message body, got 442208
</code>```

Running different Spark configuration is leading to different errors, but each of them seems to be caused by insuffitient memory (SIGKILL, Java Heap Size, etc.)

Is Pandas method bottlenecking somehow whole process by its usage of memory here?
I was able to run such process for 1,5 milion records - can you advise me how to configure and tune up Spark to process the amount of data mentioned in the beginning? - is it possible to do so with these resources available?

Body:
I'm running Spark drivers on AKS cluster pods. Spark job is to pick up 250 milions of records from Azure Storage from given location >> create dataframe from them >> select one column >> create a list by Pandas toList() method >> take list and check existance of each record from list in Redis DB >> return results to driver for further processing

Provided data is splitted in 50 parquet files, each one containing 5 milion of records.

DAG from job failing:

DAG from job failing

Stage failing:

Stage failing

Because of node specification I have limited compute power. For now, this is configuration of Spark, that I have:

    spark.driver.maxResultSize=5G
    spark.driver.memory=10G
    spark.executor.memory=8G
    spark.executor.cores=3
    spark.driver.cores=3
    spark.executor.instances=10
    spark.sql.sources.partitionOverwriteMode=dynamic
    spark.driver.memoryOverhead=0
    spark.executor.memoryOverhead=2G

and defined in code:

spark_conf.set('spark.default.parallelism', num_executors * executor_cores)
spark_conf.set('spark.sql.shuffle.partitions', num_executors * executor_cores)

Error received on driver Pod:

[Stage 1:======================================================>  (38 + 2) / 40]

[Stage 1:=======================================================> (39 + 1) / 40]

[Stage 2:>                                                        (0 + 24) / 30]

[Stage 2:>                                                        (0 + 25) / 30]

[Stage 2:>                                                        (0 + 27) / 30]

[Stage 2:>                                                        (0 + 28) / 30]

[Stage 2:>                                                        (0 + 29) / 30]

[Stage 2:>                                                        (0 + 30) / 30]

[Stage 2:=>                                                       (1 + 29) / 30]
[2022-12-28 15:28:45,156: ERROR/ForkPoolWorker-1] Exception while sending command.
2022-12-28T16:28:45+01:00 Traceback (most recent call last):
2022-12-28T16:28:45+01:00   File "/opt/spark/python/pyspark/sql/pandas/conversion.py", line 241, in _collect_as_arrow
2022-12-28T16:28:45+01:00     results = list(_load_from_socket((port, auth_secret), ArrowCollectSerializer()))
2022-12-28T16:28:45+01:00   File "/opt/spark/python/pyspark/sql/pandas/serializers.py", line 60, in load_stream
2022-12-28T16:28:45+01:00     for batch in self.serializer.load_stream(stream):
2022-12-28T16:28:45+01:00   File "/opt/spark/python/pyspark/sql/pandas/serializers.py", line 99, in load_stream
2022-12-28T16:28:45+01:00     for batch in reader:
2022-12-28T16:28:45+01:00   File "pyarrow/ipc.pxi", line 436, in __iter__
2022-12-28T16:28:45+01:00   File "pyarrow/ipc.pxi", line 468, in pyarrow.lib.RecordBatchReader.read_next_batch
2022-12-28T16:28:45+01:00   File "pyarrow/error.pxi", line 99, in pyarrow.lib.check_status
2022-12-28T16:28:45+01:00 OSError: Expected to be able to read 449936 bytes for message body, got 442208

Running different Spark configuration is leading to different errors, but each of them seems to be caused by insuffitient memory (SIGKILL, Java Heap Size, etc.)

Is Pandas method bottlenecking somehow whole process by its usage of memory here?
I was able to run such process for 1,5 milion records - can you advise me how to configure and tune up Spark to process the amount of data mentioned in the beginning? - is it possible to do so with these resources available?


问:
Getting "incorrect orientation" when trying to merge two FPDF classes with multiple inheritance
I have written a few classes that use the fpdf2 library (version 2.5.7). I want to merge two of them to create a pdf with the methods from the two classes.

How can I do that?

Here is a basic example of my tentative:

EDIT

```<code>class SWISS_BILL(FPDF) :
    def __init__(self, path_image) :
        self.interligne         = 4
        self.path_image         = path_image

    def pdf_swissbill(self, data) :
        self.set_font('Arial', 'B', 16)
        self.cell(40, 10, data)

class QR_BILL(FPDF) :
    def __init__(self, ref_y_start) :
        self.loc_y_ref_bill         = ref_y_start
        self.interligne_9pt         = 9     # in pt

    def pdf_qr(self, data) :
        self.set_font('Arial', 'B', 16)
        self.cell(40, 10, data)

class TOTAL(QR_BILL, SWISS_BILL) :
    def __init__(self, path_image, ref_y_start, orientation, unit, format) :
        QR_BILL.__init__(ref_y_start)
        SWISS_BILL.__init__(path_image)
        self.orientation        = orientation
        self.unit               = unit
        self.format             = format

pdf = TOTAL('path_image', 60, 'P', 'mm', 'A4')
pdf.add_page()
pdf.pdf_qr('bonjour')
pdf.ln(h=60)
pdf.pdf_swissbill('merci')
pdf.output('test_merge_two_class2.pdf')
</code>```

The error :

```<code>    QR_BILL.__init__(ref_y_start)
TypeError: QR_BILL.__init__() missing 1 required positional argument: 'ref_y_start'
</code>```

Body:
I have written a few classes that use the fpdf2 library (version 2.5.7). I want to merge two of them to create a pdf with the methods from the two classes.

How can I do that?

Here is a basic example of my tentative:

EDIT

class SWISS_BILL(FPDF) :
    def __init__(self, path_image) :
        self.interligne         = 4
        self.path_image         = path_image

    def pdf_swissbill(self, data) :
        self.set_font('Arial', 'B', 16)
        self.cell(40, 10, data)

class QR_BILL(FPDF) :
    def __init__(self, ref_y_start) :
        self.loc_y_ref_bill         = ref_y_start
        self.interligne_9pt         = 9     # in pt

    def pdf_qr(self, data) :
        self.set_font('Arial', 'B', 16)
        self.cell(40, 10, data)

class TOTAL(QR_BILL, SWISS_BILL) :
    def __init__(self, path_image, ref_y_start, orientation, unit, format) :
        QR_BILL.__init__(ref_y_start)
        SWISS_BILL.__init__(path_image)
        self.orientation        = orientation
        self.unit               = unit
        self.format             = format

pdf = TOTAL('path_image', 60, 'P', 'mm', 'A4')
pdf.add_page()
pdf.pdf_qr('bonjour')
pdf.ln(h=60)
pdf.pdf_swissbill('merci')
pdf.output('test_merge_two_class2.pdf')

The error :

    QR_BILL.__init__(ref_y_start)
TypeError: QR_BILL.__init__() missing 1 required positional argument: 'ref_y_start'


问:
Dialogflow Agent gives Busy Error while calling
I tried testing my Dialogflow Agent by Calling on the Dialgflow Provided Number, But It says "the number you are trying to call is currently busy".

I tried testing my Dialogflow Agent by Calling on the Dialgflow Provided Number, But It says "the number you are trying to call is currently busy". I created another agent and tried on it, and it was working but this one stopped working.


问:
Problem regarding binding ObservableCollection to ListView
today I've been struggling with proper binding and it seems like i can't figure out what is wrong with my approach. I have one basic window with ListView as it's main component. When I try to bind ListView's ItemSource to the ObservableCollection<> through XML, it seems like it doesn't work, but if I change the property through C# code, it works just fine. My guess would be it has something to do with visibility of the ObservableCollection<>, but whenever i try to make it public i get error that base class is less visible than the other class. Could anyone explain what am I missing here?

```<code>public partial class MainWindow : Window
    {
        public ObservableCollection<dataModel> items;
        public MainWindow()
        {
            items = new ObservableCollection<dataModel>();

            InitializeComponent();
            populateData();

            //LV1.ItemsSource = items; <= works with this uncommented
        }
</code>```

and XAML:

```<code><ListView x:Name="LV1" HorizontalAlignment="Left" Height="264" Margin="55,59,0,0" VerticalAlignment="Top" Width="552" ItemsSource="{Binding items}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="title" Width="200" DisplayMemberBinding="{Binding title}"></GridViewColumn>

                </GridView>
            </ListView.View>
        </ListView>
</code>```

dataModel.cs:

```<code>public class dataModel
    {
        public string title { get; set;}
        public bool isDone {get;set;}

    }
</code>```

Body:
today I've been struggling with proper binding and it seems like i can't figure out what is wrong with my approach. I have one basic window with ListView as it's main component. When I try to bind ListView's ItemSource to the ObservableCollection<> through XML, it seems like it doesn't work, but if I change the property through C# code, it works just fine. My guess would be it has something to do with visibility of the ObservableCollection<>, but whenever i try to make it public i get error that base class is less visible than the other class. Could anyone explain what am I missing here?

public partial class MainWindow : Window
    {
        public ObservableCollection<dataModel> items;
        public MainWindow()
        {
            items = new ObservableCollection<dataModel>();

            InitializeComponent();
            populateData();

            //LV1.ItemsSource = items; <= works with this uncommented
        }

and XAML:

<ListView x:Name="LV1" HorizontalAlignment="Left" Height="264" Margin="55,59,0,0" VerticalAlignment="Top" Width="552" ItemsSource="{Binding items}">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="title" Width="200" DisplayMemberBinding="{Binding title}"></GridViewColumn>

                </GridView>
            </ListView.View>
        </ListView>

dataModel.cs:

public class dataModel
    {
        public string title { get; set;}
        public bool isDone {get;set;}

    }


问:
Can't get environment variable after eas build
After eas build can't access to name of channel of build`

```<code>"staging": {
  "node": "14.21.1",
  "channel": "staging",
  "distribution": "internal",
  "env": {
    "APP_ENV": "staging"
  }
}
</code>```

that settings from my eas.json to env which I'm trying to build.

```<code>const config = getConfig(process.env.APP_ENV)
</code>```

`
And I'm trying to get env depend on build, but it doesn't work(process.env.APP_ENV=undefined instead of "staging")

I already tried to get access by Contants

Body:
After eas build can't access to name of channel of build`

"staging": {
  "node": "14.21.1",
  "channel": "staging",
  "distribution": "internal",
  "env": {
    "APP_ENV": "staging"
  }
}

that settings from my eas.json to env which I'm trying to build.

const config = getConfig(process.env.APP_ENV)

`
And I'm trying to get env depend on build, but it doesn't work(process.env.APP_ENV=undefined instead of "staging")

I already tried to get access by Contants


问:
How to give solr user permissions per collection
Here is the security.json file I generated:

{
  "authentication":{
    "blockUnknown":true,
    "class":"solr.BasicAuthPlugin",
    "credentials":{
      "solr":"IV0EHq1OnNrj6gvRCwvFwTrZ1+z1oBbnQdiVC3otuq0= Ndd7LKvVBAaZIF0QAVi1ekCfAJXr1GGfLtRUXhgrF8c=",
      "project-1":"QUYURq8j9DfpPWo8X9lEhIdNzW/BZUCabISt4C9NSdo= +QBNDGAaKrzYb2tCoKw6YBvZvs40ikPiyeX7kp4foGw=",
      "project-2":"LskXmhFtq0Gy2ECt2OjcNDSSAKdMXSOm6kpfGwVXGq4= 0vCTvHC7RYu3sLyEXlfy+xwdmMBRSDlqECP7UeVkFuQ="
    }
  },
  "authorization":{
    "class":"solr.RuleBasedAuthorizationPlugin",
    "permissions":[
      {
        "collection":"project-1-collection-1",
        "name": "all",
        "role":"project-1"
      },
      {
        "name":"all",
        "role":"admin"
      }
    ],
    "user-role":{
      "solr":["admin"],
      "project-1":["project-1"]
    }
  }
}
```
<p>I would expect that from this configuration:</p>
<ul>
<li><code>solr</code> user is the administrator and have access everywhere</li>
<li><code>project-1</code> user has only access to <code>project-1-collection-1</code></li>
<li><code>project-2</code> user has no access to anything</li>
</ul>
<p>But the actual effect is different:</p>
<ul>
<li><code>solr</code> user has access everywhere ✓</li>
<li><code>project-1</code> user has access to api, but does not have access to GUI of <code>collection-1</code> ❌</li>
<li><code>project-2</code> user has access to <code>collection-1</code> (it should not) ❌</li>
</ul>
<p>I am checking the API by running</p>
```curl --user "solr:SolrRocks" "http://${HOST}:${PORT}/solr/project-1-collection-1/select?wt=json&q=*:*"
curl --user "project-1:password-1" "http://${HOST}:${PORT}/solr/project-1-collection-1/select?wt=json&q=*:*"
curl --user "project-2:password-1" "http://${HOST}:${PORT}/solr/project-1-collection-1/select?wt=json&q=*:*"
```
<p>And GUI by accessing following url:</p>
```http://localhost:8906/solr/#/project-1-collection-1/query
```

What am I doing wrong?

Body:
Here is the security.json file I generated:

{
  "authentication":{
    "blockUnknown":true,
    "class":"solr.BasicAuthPlugin",
    "credentials":{
      "solr":"IV0EHq1OnNrj6gvRCwvFwTrZ1+z1oBbnQdiVC3otuq0= Ndd7LKvVBAaZIF0QAVi1ekCfAJXr1GGfLtRUXhgrF8c=",
      "project-1":"QUYURq8j9DfpPWo8X9lEhIdNzW/BZUCabISt4C9NSdo= +QBNDGAaKrzYb2tCoKw6YBvZvs40ikPiyeX7kp4foGw=",
      "project-2":"LskXmhFtq0Gy2ECt2OjcNDSSAKdMXSOm6kpfGwVXGq4= 0vCTvHC7RYu3sLyEXlfy+xwdmMBRSDlqECP7UeVkFuQ="
    }
  },
  "authorization":{
    "class":"solr.RuleBasedAuthorizationPlugin",
    "permissions":[
      {
        "collection":"project-1-collection-1",
        "name": "all",
        "role":"project-1"
      },
      {
        "name":"all",
        "role":"admin"
      }
    ],
    "user-role":{
      "solr":["admin"],
      "project-1":["project-1"]
    }
  }
}

I would expect that from this configuration:

solr user is the administrator and have access everywhere

project-1 user has only access to project-1-collection-1

project-2 user has no access to anything

But the actual effect is different:

solr user has access everywhere ✓

project-1 user has access to api, but does not have access to GUI of collection-1 ❌

project-2 user has access to collection-1 (it should not) ❌

I am checking the API by running

curl --user "solr:SolrRocks" "http://${HOST}:${PORT}/solr/project-1-collection-1/select?wt=json&q=*:*"
curl --user "project-1:password-1" "http://${HOST}:${PORT}/solr/project-1-collection-1/select?wt=json&q=*:*"
curl --user "project-2:password-1" "http://${HOST}:${PORT}/solr/project-1-collection-1/select?wt=json&q=*:*"

And GUI by accessing following url:

http://localhost:8906/solr/#/project-1-collection-1/query

What am I doing wrong?