问:
Accessing a private GKE cluster via Cloud VPN
We have setup a GKE cluster using Terraform with private and shared networking:

Network configuration:

```<code>resource "google_compute_subnetwork" "int_kube02" {
  name          = "int-kube02"
  region        = var.region
  project       = "infrastructure"
  network       = "projects/infrastructure/global/networks/net-10-23-0-0-16"
  ip_cidr_range = "10.23.5.0/24"
  secondary_ip_range {
    range_name    = "pods"
    ip_cidr_range = "10.60.0.0/14" # 10.60 - 10.63
  }
  secondary_ip_range {
    range_name    = "services"
    ip_cidr_range = "10.56.0.0/16"
  }
}
</code>```

Cluster configuration:

```<code>resource "google_container_cluster" "gke_kube02" {
  name     = "kube02"
  location = var.region

  initial_node_count = var.gke_kube02_num_nodes

  network    = "projects/ninfrastructure/global/networks/net-10-23-0-0-16"
  subnetwork = "projects/infrastructure/regions/europe-west3/subnetworks/int-kube02"

  master_authorized_networks_config {
    cidr_blocks {
      display_name = "admin vpn"
      cidr_block   = "10.42.255.0/24"
    }
    cidr_blocks {
      display_name = "monitoring server"
      cidr_block   = "10.42.4.33/32"
    }
    cidr_blocks {
      display_name = "cluster nodes"
      cidr_block   = "10.23.5.0/24"
    }
  }

  ip_allocation_policy {
    cluster_secondary_range_name  = "pods"
    services_secondary_range_name = "services"
  }

  private_cluster_config {
    enable_private_nodes    = true
    enable_private_endpoint = true
    master_ipv4_cidr_block  = "192.168.23.0/28"

  }

  node_config {
    machine_type = "e2-highcpu-2"

    tags = ["kube-no-external-ip"]
    metadata = {
      disable-legacy-endpoints = true
    }

    oauth_scopes = [
      "https://www.googleapis.com/auth/logging.write",
      "https://www.googleapis.com/auth/monitoring",
    ]
  }
}
</code>```

The cluster is online and running fine. If I connect to one of the worker nodes i can reach the api using curl:

```<code>curl -k https://192.168.23.2
{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {

  },
  "status": "Failure",
  "message": "forbidden: User \"system:anonymous\" cannot get path \"/\"",
  "reason": "Forbidden",
  "details": {

  },
  "code": 403
}
</code>```

I also see a healthy cluster when using a SSH port forward:

```<code>❯ k get pods --all-namespaces --insecure-skip-tls-verify=true
NAMESPACE     NAME                                               READY   STATUS    RESTARTS   AGE
kube-system   event-exporter-gke-5479fd58c8-mv24r                2/2     Running   0          4h44m
kube-system   fluentbit-gke-ckkwh                                2/2     Running   0          4h44m
kube-system   fluentbit-gke-lblkz                                2/2     Running   0          4h44m
kube-system   fluentbit-gke-zglv2                                2/2     Running   4          4h44m
kube-system   gke-metrics-agent-j72d9                            1/1     Running   0          4h44m
kube-system   gke-metrics-agent-ttrzk                            1/1     Running   0          4h44m
kube-system   gke-metrics-agent-wbqgc                            1/1     Running   0          4h44m
kube-system   kube-dns-697dc8fc8b-rbf5b                          4/4     Running   5          4h44m
kube-system   kube-dns-697dc8fc8b-vnqb4                          4/4     Running   1          4h44m
kube-system   kube-dns-autoscaler-844c9d9448-f6sqw               1/1     Running   0          4h44m
kube-system   kube-proxy-gke-kube02-default-pool-2bf58182-xgp7   1/1     Running   0          4h43m
kube-system   kube-proxy-gke-kube02-default-pool-707f5d51-s4xw   1/1     Running   0          4h43m
kube-system   kube-proxy-gke-kube02-default-pool-bd2c130d-c67h   1/1     Running   0          4h43m
kube-system   l7-default-backend-6654b9bccb-mw6bp                1/1     Running   0          4h44m
kube-system   metrics-server-v0.4.4-857776bc9c-sq9kd             2/2     Running   0          4h43m
kube-system   pdcsi-node-5zlb7                                   2/2     Running   0          4h44m
kube-system   pdcsi-node-kn2zb                                   2/2     Running   0          4h44m
kube-system   pdcsi-node-swhp9                                   2/2     Running   0          4h44m
</code>```

So far so good. Then I setup the Cloud Router to announce the 192.168.23.0/28 network. This was successful and replicated to our local site using BGP. Running show route 192.168.23.2 displays the correct route is advertised and installed.

When trying to reach the API from the monitoring server 10.42.4.33 I just run into timeouts. All three, the Cloud VPN, the Cloud Router and the Kubernetes Cluster run in europe-west3.

When i try to ping one of the workers its working completely fine, so networking in general works:

```<code>[me@monitoring ~]$ ping 10.23.5.216
PING 10.23.5.216 (10.23.5.216) 56(84) bytes of data.
64 bytes from 10.23.5.216: icmp_seq=1 ttl=63 time=8.21 ms
64 bytes from 10.23.5.216: icmp_seq=2 ttl=63 time=7.70 ms
64 bytes from 10.23.5.216: icmp_seq=3 ttl=63 time=5.41 ms
64 bytes from 10.23.5.216: icmp_seq=4 ttl=63 time=7.98 ms
</code>```

Googles Documentation gives no hit what could be missing. From what I understand the Cluster API should be reachable by now.

What could be missing and why is the API not reachable via VPN?

答:
I have been missing the peering configuration documented here:
https://cloud.google.com/kubernetes-engine/docs/how-to/private-clusters#cp-on-prem-routing</p>
```<code>resource "google_compute_network_peering_routes_config" "peer_kube02" {
  peering = google_container_cluster.gke_kube02.private_cluster_config[0].peering_name
  project = "infrastructure"
  network = "net-10-13-0-0-16"

  export_custom_routes = true
  import_custom_routes = false
}

</code>```

Body:
We have setup a GKE cluster using Terraform with private and shared networking:

Network configuration:

resource "google_compute_subnetwork" "int_kube02" {
  name          = "int-kube02"
  region        = var.region
  project       = "infrastructure"
  network       = "projects/infrastructure/global/networks/net-10-23-0-0-16"
  ip_cidr_range = "10.23.5.0/24"
  secondary_ip_range {
    range_name    = "pods"
    ip_cidr_range = "10.60.0.0/14" # 10.60 - 10.63
  }
  secondary_ip_range {
    range_name    = "services"
    ip_cidr_range = "10.56.0.0/16"
  }
}

Cluster configuration:

resource "google_container_cluster" "gke_kube02" {
  name     = "kube02"
  location = var.region

  initial_node_count = var.gke_kube02_num_nodes

  network    = "projects/ninfrastructure/global/networks/net-10-23-0-0-16"
  subnetwork = "projects/infrastructure/regions/europe-west3/subnetworks/int-kube02"

  master_authorized_networks_config {
    cidr_blocks {
      display_name = "admin vpn"
      cidr_block   = "10.42.255.0/24"
    }
    cidr_blocks {
      display_name = "monitoring server"
      cidr_block   = "10.42.4.33/32"
    }
    cidr_blocks {
      display_name = "cluster nodes"
      cidr_block   = "10.23.5.0/24"
    }
  }

  ip_allocation_policy {
    cluster_secondary_range_name  = "pods"
    services_secondary_range_name = "services"
  }

  private_cluster_config {
    enable_private_nodes    = true
    enable_private_endpoint = true
    master_ipv4_cidr_block  = "192.168.23.0/28"

  }

  node_config {
    machine_type = "e2-highcpu-2"

    tags = ["kube-no-external-ip"]
    metadata = {
      disable-legacy-endpoints = true
    }

    oauth_scopes = [
      "https://www.googleapis.com/auth/logging.write",
      "https://www.googleapis.com/auth/monitoring",
    ]
  }
}

The cluster is online and running fine. If I connect to one of the worker nodes i can reach the api using curl:

curl -k https://192.168.23.2
{
  "kind": "Status",
  "apiVersion": "v1",
  "metadata": {

  },
  "status": "Failure",
  "message": "forbidden: User \"system:anonymous\" cannot get path \"/\"",
  "reason": "Forbidden",
  "details": {

  },
  "code": 403
}

I also see a healthy cluster when using a SSH port forward:

❯ k get pods --all-namespaces --insecure-skip-tls-verify=true
NAMESPACE     NAME                                               READY   STATUS    RESTARTS   AGE
kube-system   event-exporter-gke-5479fd58c8-mv24r                2/2     Running   0          4h44m
kube-system   fluentbit-gke-ckkwh                                2/2     Running   0          4h44m
kube-system   fluentbit-gke-lblkz                                2/2     Running   0          4h44m
kube-system   fluentbit-gke-zglv2                                2/2     Running   4          4h44m
kube-system   gke-metrics-agent-j72d9                            1/1     Running   0          4h44m
kube-system   gke-metrics-agent-ttrzk                            1/1     Running   0          4h44m
kube-system   gke-metrics-agent-wbqgc                            1/1     Running   0          4h44m
kube-system   kube-dns-697dc8fc8b-rbf5b                          4/4     Running   5          4h44m
kube-system   kube-dns-697dc8fc8b-vnqb4                          4/4     Running   1          4h44m
kube-system   kube-dns-autoscaler-844c9d9448-f6sqw               1/1     Running   0          4h44m
kube-system   kube-proxy-gke-kube02-default-pool-2bf58182-xgp7   1/1     Running   0          4h43m
kube-system   kube-proxy-gke-kube02-default-pool-707f5d51-s4xw   1/1     Running   0          4h43m
kube-system   kube-proxy-gke-kube02-default-pool-bd2c130d-c67h   1/1     Running   0          4h43m
kube-system   l7-default-backend-6654b9bccb-mw6bp                1/1     Running   0          4h44m
kube-system   metrics-server-v0.4.4-857776bc9c-sq9kd             2/2     Running   0          4h43m
kube-system   pdcsi-node-5zlb7                                   2/2     Running   0          4h44m
kube-system   pdcsi-node-kn2zb                                   2/2     Running   0          4h44m
kube-system   pdcsi-node-swhp9                                   2/2     Running   0          4h44m

So far so good. Then I setup the Cloud Router to announce the 192.168.23.0/28 network. This was successful and replicated to our local site using BGP. Running show route 192.168.23.2 displays the correct route is advertised and installed.

When trying to reach the API from the monitoring server 10.42.4.33 I just run into timeouts. All three, the Cloud VPN, the Cloud Router and the Kubernetes Cluster run in europe-west3.

When i try to ping one of the workers its working completely fine, so networking in general works:

[me@monitoring ~]$ ping 10.23.5.216
PING 10.23.5.216 (10.23.5.216) 56(84) bytes of data.
64 bytes from 10.23.5.216: icmp_seq=1 ttl=63 time=8.21 ms
64 bytes from 10.23.5.216: icmp_seq=2 ttl=63 time=7.70 ms
64 bytes from 10.23.5.216: icmp_seq=3 ttl=63 time=5.41 ms
64 bytes from 10.23.5.216: icmp_seq=4 ttl=63 time=7.98 ms

Googles Documentation gives no hit what could be missing. From what I understand the Cluster API should be reachable by now.

What could be missing and why is the API not reachable via VPN?

Body:
I have been missing the peering configuration documented here:
https://cloud.google.com/kubernetes-engine/docs/how-to/private-clusters#cp-on-prem-routing

resource "google_compute_network_peering_routes_config" "peer_kube02" {
  peering = google_container_cluster.gke_kube02.private_cluster_config[0].peering_name
  project = "infrastructure"
  network = "net-10-13-0-0-16"

  export_custom_routes = true
  import_custom_routes = false
}


来源: stackexchange

问:
Eclipse cant be opened on mac m1
I have installed eclipse aarch64 based on my mac m1.
it was working fine. later i stopped using it for few days but i was just opening and closing it just to make sure it is not crashing as it used to happen with x64 version.
Now even with aarch it is crashing.
As soon as i open it via launch pad it says 'The apllication 'Eclipse'can't be opened.

Here are the details of eclipse and jdk version that i am currently using.
Eclipse: eclipse-java-2021-12-R-macosx-cocoa-aarch64
Jdk: jdk-17_macos-aarch64_bin

答:
I've just had the same problem on the second launch of Eclipse from a fresh installation. The solution was to re-sign the app with an ad-hoc signature:</p>
```<code>sudo codesign --force --deep --sign - /Applications/Eclipse.app
</code>```

ContentLicense: CC BY-SA 4.0

Title: Eclipse cant be opened on mac m1

Body:
I've just had the same problem on the second launch of Eclipse from a fresh installation. The solution was to re-sign the app with an ad-hoc signature:

sudo codesign --force --deep --sign - /Applications/Eclipse.app


问:
Cleaner way of manipulating string to JSON
I have the following invalid JSON string which I'd like to convert into valid JSON (so each "template" will have a vuln-x key before it):

```<code>{"template":"network/vsftpd-detection.yaml","matcher-status":true}{"template":"cves/2018/CVE-2018-15473.yaml","matcher-status":true}{"template":"cves/2016/CVE-2016-6210.yaml","matcher-status":true}
</code>```

I'm currently doing the following in order to format it:

```<code>import json

s1 = '{"template":"network/vsftpd-detection.yaml","matcher-status":true}{"template":"cves/2018/CVE-2018-15473.yaml","matcher-status":true}{"template":"cves/2016/CVE-2016-6210.yaml","matcher-status":true}'

s2 = s1.split('{"template":')
num = s1.count('{"template":')
out_json = "{"

for x in range(num):
        out_json += '"vuln-' + str(x) + '":{"template":' + s2[x+1]

new_json = out_json.replace("true}", "true},")
cleaned_json = new_json[:-1] + "}"

print(cleaned_json)
</code>```

I feel this is incredibly messy and am sure there's a cleaner way to do it - any ideas?

Here's the desired output which I'm getting with my current script:

```<code>{
   "vuln-0":{
      "template":"network/vsftpd-detection.yaml",
      "matcher-status":true
   },
   "vuln-1":{
      "template":"cves/2018/CVE-2018-15473.yaml",
      "matcher-status":true
   },
   "vuln-2":{
      "template":"cves/2016/CVE-2016-6210.yaml",
      "matcher-status":true
   }
}
</code>```

答:
Add a delimiter between the dictionaries to enable easier splitting, then process as dictionaries:

import json

s = '{"template":"network/vsftpd-detection.yaml","matcher-status":true}{"template":"cves/2018/CVE-2018-15473.yaml","matcher-status":true}{"template":"cves/2016/CVE-2016-6210.yaml","matcher-status":true}'

# add a delimiter not used in the string (nul) and split on it.
strings = s.replace('}{', '}\0{').split('\0')

# dict comprehension
data = {f'vuln-{i}': json.loads(v) for i, v in enumerate(strings)}

print(json.dumps(data, indent=2))
```
<p>Output:</p>
<pre class="lang-json prettyprint-override"><code>{
  "vuln-0": {
    "template": "network/vsftpd-detection.yaml",
    "matcher-status": true
  },
  "vuln-1": {
    "template": "cves/2018/CVE-2018-15473.yaml",
    "matcher-status": true
  },
  "vuln-2": {
    "template": "cves/2016/CVE-2016-6210.yaml",
    "matcher-status": true
  }
}
</code>```

Body:
I have the following invalid JSON string which I'd like to convert into valid JSON (so each "template" will have a vuln-x key before it):

{"template":"network/vsftpd-detection.yaml","matcher-status":true}{"template":"cves/2018/CVE-2018-15473.yaml","matcher-status":true}{"template":"cves/2016/CVE-2016-6210.yaml","matcher-status":true}

I'm currently doing the following in order to format it:

import json

s1 = '{"template":"network/vsftpd-detection.yaml","matcher-status":true}{"template":"cves/2018/CVE-2018-15473.yaml","matcher-status":true}{"template":"cves/2016/CVE-2016-6210.yaml","matcher-status":true}'

s2 = s1.split('{"template":')
num = s1.count('{"template":')
out_json = "{"

for x in range(num):
        out_json += '"vuln-' + str(x) + '":{"template":' + s2[x+1]

new_json = out_json.replace("true}", "true},")
cleaned_json = new_json[:-1] + "}"

print(cleaned_json)

I feel this is incredibly messy and am sure there's a cleaner way to do it - any ideas?

Here's the desired output which I'm getting with my current script:

{
   "vuln-0":{
      "template":"network/vsftpd-detection.yaml",
      "matcher-status":true
   },
   "vuln-1":{
      "template":"cves/2018/CVE-2018-15473.yaml",
      "matcher-status":true
   },
   "vuln-2":{
      "template":"cves/2016/CVE-2016-6210.yaml",
      "matcher-status":true
   }
}

Body:
Add a delimiter between the dictionaries to enable easier splitting, then process as dictionaries:

import json

s = '{"template":"network/vsftpd-detection.yaml","matcher-status":true}{"template":"cves/2018/CVE-2018-15473.yaml","matcher-status":true}{"template":"cves/2016/CVE-2016-6210.yaml","matcher-status":true}'

# add a delimiter not used in the string (nul) and split on it.
strings = s.replace('}{', '}\0{').split('\0')

# dict comprehension
data = {f'vuln-{i}': json.loads(v) for i, v in enumerate(strings)}

print(json.dumps(data, indent=2))

Output:

{
  "vuln-0": {
    "template": "network/vsftpd-detection.yaml",
    "matcher-status": true
  },
  "vuln-1": {
    "template": "cves/2018/CVE-2018-15473.yaml",
    "matcher-status": true
  },
  "vuln-2": {
    "template": "cves/2016/CVE-2016-6210.yaml",
    "matcher-status": true
  }
}


问:
Pass model data to javascript function
I have this model @model WebApplication1.Models.Person which has an Id data. I want to pass Id to a javascript function via href="#" onclick=myFunction(idGoesHere)>.

I tried putting @Model.id or passing the value of @Model.id to another variable, but still it doesn't work. Any help would be appreciated.

答:
try to get raw value, and then use it</p>
```<code>var userObj = @Html.Raw(Json.Encode(Model));
</code>```

Title: Pass model data to javascript function

Body:
I have this model @model WebApplication1.Models.Person which has an Id data. I want to pass Id to a javascript function via .

I tried putting @Model.id or passing the value of @Model.id to another variable, but still it doesn't work. Any help would be appreciated.

Body:
try to get raw value, and then use it

var userObj = @Html.Raw(Json.Encode(Model));


问:
Something Easier than jq UI Dialog?
Is it just me, or is Jquery UI Dialog really difficult to grasp.  I am not a javascript developer, and I don't feel like learning the language (not right now anyway... this project is on a deadline!).  Isn't there anything simpler that uses the latest jquery and is relatively simple to use?  Like you know, set an id or a class (id preferably) for the form and call a simple jquery function?  Why does it have to be so hard?  And no simpleDialog.  Some of those scripts conflict with my other scripts and make my other jquery function crap out (I spent 13 hours yesterday trying to figure that one out)...</p>

答:
Not clear what you mean for "simpler" ;) anyway you can give a try to:

http://www.ericmmartin.com/projects/simplemodal/

and here you have a list with 15 alternatives...

http://choosedaily.com/1178/15-jquery-popup-modal-dialog-plugins-tutorials/

ContentLicense: CC BY-SA 3.0

Title: Something Easier than jq UI Dialog?


问:
Loop Through PSOBJECT To Compare Values to a String
Working on a script to get the status of Windows Defender components. Running into a challenge looping through the results from Get-MpComputerStatus as I'm wanting to write out which components are enabled and disabled.

The issue that I'm running into is I'm not able to get the specific value from the PSOBJECT and only get everything.

```<code>#Microsoft Defender Statuses
$DefenderStatus = Get-MpComputerStatus | select-object AMServiceEnabled, AntispywareEnabled, AntivirusEnabled, BehaviorMonitorEnabled, IoavProtectionEnabled, IsTamperProtected, IsVirtualMachine, NISEnabled, OnAccessProtectionEnabled, RealTimeProtectionEnabled

#Write results to a PSOBJECT
$result =  ([ordered]@{

            'Anti-Virus'=$DefenderStatus.AntivirusEnabled
            'Anti-Malware'=$DefenderStatus.AMServiceEnabled
            'Anti-Spyware'=$DefenderStatus.AntispywareEnabled
            'Behavior Monitor'=$DefenderStatus.BehaviorMonitorEnabled
            'Office-Anti-Virus'=$DefenderStatus.IoavProtectionEnabled
            'NIS'=$DefenderStatus.NISEnabled
            'Access Protection'=$DefenderStatus.OnAccessProtectionEnabled
            'R-T Protection'=$DefenderStatus.RealTimeProtectionEnabled

            })

foreach ($Status in $result)
{
   If ($Status.Values -eq $false)
   {
        Write-Host "$Status.Keys is Disabled"
        $Disabled = $Disabled + ", "  + $Status
   }
   Else
   {
        Write-Host "$Status.Keys is Enabled"
        $Enabled = $Enabled + ", "  + $Status

   }
}
</code>```

答:
As Theo comments, you're storing the results in an ordered hash table, if you want to iterate over the Key-Value pairs you could use .GetEnumerator() or .Keys property or .get_Keys() method, for example:

```<code>$result = [ordered]@{
    'Anti-Virus'        = $true
    'Anti-Malware'      = $true
    'Anti-Spyware'      = $false
    'Behavior Monitor'  = $false
    'Office-Anti-Virus' = $true
    'NIS'               = $false
    'Access Protection' = $true
    'R-T Protection'    = $true
}

foreach($pair in $result.GetEnumerator()) {
    # If the Value is $true
    if($pair.Value) {
        "{0} is Enabled" -f $pair.Key
        continue
    }
    # If we're here last condition was $false
    "{0} is Disabled" -f $pair.Key
}
</code>```

However, since $DefenderStatus seem to be an object you could also do the following (if it was an object[] (array of objects) this would need to be changed):

```<code>$DefenderStatus = [PsCustomobject]@{
    'Anti-Virus'        = $true
    'Anti-Malware'      = $true
    'Anti-Spyware'      = $false
    'Behavior Monitor'  = $false
    'Office-Anti-Virus' = $true
    'NIS'               = $false
    'Access Protection' = $true
    'R-T Protection'    = $true
}

foreach($object in $DefenderStatus.PSObject.Properties) {
    # Property Value
    if($object.Value) {
        "{0} is Enabled" -f $object.Name # Property Name
        continue
    }
    "{0} is Disabled" -f $object.Name
}
</code>```

Body:
Working on a script to get the status of Windows Defender components. Running into a challenge looping through the results from Get-MpComputerStatus as I'm wanting to write out which components are enabled and disabled.

The issue that I'm running into is I'm not able to get the specific value from the PSOBJECT and only get everything.

#Microsoft Defender Statuses
$DefenderStatus = Get-MpComputerStatus | select-object AMServiceEnabled, AntispywareEnabled, AntivirusEnabled, BehaviorMonitorEnabled, IoavProtectionEnabled, IsTamperProtected, IsVirtualMachine, NISEnabled, OnAccessProtectionEnabled, RealTimeProtectionEnabled

#Write results to a PSOBJECT
$result =  ([ordered]@{

            'Anti-Virus'=$DefenderStatus.AntivirusEnabled
            'Anti-Malware'=$DefenderStatus.AMServiceEnabled
            'Anti-Spyware'=$DefenderStatus.AntispywareEnabled
            'Behavior Monitor'=$DefenderStatus.BehaviorMonitorEnabled
            'Office-Anti-Virus'=$DefenderStatus.IoavProtectionEnabled
            'NIS'=$DefenderStatus.NISEnabled
            'Access Protection'=$DefenderStatus.OnAccessProtectionEnabled
            'R-T Protection'=$DefenderStatus.RealTimeProtectionEnabled

            })

foreach ($Status in $result)
{
   If ($Status.Values -eq $false)
   {
        Write-Host "$Status.Keys is Disabled"
        $Disabled = $Disabled + ", "  + $Status
   }
   Else
   {
        Write-Host "$Status.Keys is Enabled"
        $Enabled = $Enabled + ", "  + $Status

   }
}

Body:
As Theo comments, you're storing the results in an ordered hash table, if you want to iterate over the Key-Value pairs you could use .GetEnumerator() or .Keys property or .get_Keys() method, for example:

$result = [ordered]@{
    'Anti-Virus'        = $true
    'Anti-Malware'      = $true
    'Anti-Spyware'      = $false
    'Behavior Monitor'  = $false
    'Office-Anti-Virus' = $true
    'NIS'               = $false
    'Access Protection' = $true
    'R-T Protection'    = $true
}

foreach($pair in $result.GetEnumerator()) {
    # If the Value is $true
    if($pair.Value) {
        "{0} is Enabled" -f $pair.Key
        continue
    }
    # If we're here last condition was $false
    "{0} is Disabled" -f $pair.Key
}

However, since $DefenderStatus seem to be an object you could also do the following (if it was an object[] (array of objects) this would need to be changed):

$DefenderStatus = [PsCustomobject]@{
    'Anti-Virus'        = $true
    'Anti-Malware'      = $true
    'Anti-Spyware'      = $false
    'Behavior Monitor'  = $false
    'Office-Anti-Virus' = $true
    'NIS'               = $false
    'Access Protection' = $true
    'R-T Protection'    = $true
}

foreach($object in $DefenderStatus.PSObject.Properties) {
    # Property Value
    if($object.Value) {
        "{0} is Enabled" -f $object.Name # Property Name
        continue
    }
    "{0} is Disabled" -f $object.Name
}


问:
Export to Excel in hh:mm:ss in Webdatarocks web pivot table
If there is a data which is configured as time in webdatarocks, then it is exported correctly in hh:mm:ss format in Excel.
But if we have a calculated value which is obtained by dividing time value by numeric value (to get average) and this calculated value is defined as time, then in web it is shown in correct format, but in export - in seconds.
Below is sample from webdatarocks codepen where I have added new value AVG. It is shown as 00:20:00 on web, but exported as 1200 in excel</p>
```<code>        "Duration": {
            type: "time"
        },
        "Movie Name": {
            type: "string"
        },
  "AVG": {
            type: "time"
        },
        "Rating": {
            type: "number"
        },
        "Genre": {
            type: "string"
        }
    },
    {
        "Movie Name": "Star Wars: The Last Jedi",
        "Rating": 7.2,
        "Genre": "Fantasy",
        "Duration": 9120
    },
    {
        "Movie Name": "Blade Runner 2049",
        "Rating": 7.2,
        "Genre": "Sci-Fi",
        "Duration": 9840
    },
    {
        "Movie Name": "Harry Potter and the Sorcerer's Stone",
        "Rating": 7.6,
        "Genre": "Adventure",
        "Duration": 9120
    },
    {
        "Movie Name": "Incredibles 2",
        "Rating": 8.1,
        "Genre": "Animation",
        "Duration": 7080
    },
    {
        "Movie Name": "Ratatouille",
        "Rating": 8.0,
        "Genre": "Comedy",
        "Duration": 6660
    },
    {
        "Movie Name": "Scott Pilgrim vs. the World",
        "Rating": 7.5,
        "Genre": "Romance",
        "Duration": 6720
    }
];
var pivot = new WebDataRocks({
    container: "wdr-component",
    toolbar: true,
    report: {
        dataSource: {
            data: JSONData
        },
    "slice": {
          "rows": [
              {
                  "uniqueName": "Movie Name"
              }
          ],
          "columns": [
              {
                  "uniqueName": "Genre"
              },
              {
                  "uniqueName": "Duration"
              },
              {
                  "uniqueName": "Measures"
              }
          ],
          "measures": [
              {
                  "uniqueName": "Rating",
                  "aggregation": "sum"
              },
            {
                "uniqueName": "AVG",
                "formula": "sum(\"Duration\") / sum(\"Rating\")",
                "caption": "Avg"
            },
          ],
          "expands": {
              "columns": [
                  {
                      "tuple": [
                          "Genre.Adventure"
                      ]
                  },
                  {
                      "tuple": [
                          "Genre.Animation"
                      ]
                  },
                  {
                      "tuple": [
                          "Genre.Comedy"
                      ]
                  },
                  {
                      "tuple": [
                          "Genre.Fantasy"
                      ]
                  }
              ]
          }
      }
    }
});
</code>```

答: Currently, WebDataRocks does not provide an option of setting a time format of the calculated measures for export.</p>

Body:
If there is a data which is configured as time in webdatarocks, then it is exported correctly in hh:mm:ss format in Excel.
But if we have a calculated value which is obtained by dividing time value by numeric value (to get average) and this calculated value is defined as time, then in web it is shown in correct format, but in export - in seconds.
Below is sample from webdatarocks codepen where I have added new value AVG. It is shown as 00:20:00 on web, but exported as 1200 in excel

        "Duration": {
            type: "time"
        },
        "Movie Name": {
            type: "string"
        },
  "AVG": {
            type: "time"
        },
        "Rating": {
            type: "number"
        },
        "Genre": {
            type: "string"
        }
    },
    {
        "Movie Name": "Star Wars: The Last Jedi",
        "Rating": 7.2,
        "Genre": "Fantasy",
        "Duration": 9120
    },
    {
        "Movie Name": "Blade Runner 2049",
        "Rating": 7.2,
        "Genre": "Sci-Fi",
        "Duration": 9840
    },
    {
        "Movie Name": "Harry Potter and the Sorcerer's Stone",
        "Rating": 7.6,
        "Genre": "Adventure",
        "Duration": 9120
    },
    {
        "Movie Name": "Incredibles 2",
        "Rating": 8.1,
        "Genre": "Animation",
        "Duration": 7080
    },
    {
        "Movie Name": "Ratatouille",
        "Rating": 8.0,
        "Genre": "Comedy",
        "Duration": 6660
    },
    {
        "Movie Name": "Scott Pilgrim vs. the World",
        "Rating": 7.5,
        "Genre": "Romance",
        "Duration": 6720
    }
];
var pivot = new WebDataRocks({
    container: "wdr-component",
    toolbar: true,
    report: {
        dataSource: {
            data: JSONData
        },
    "slice": {
          "rows": [
              {
                  "uniqueName": "Movie Name"
              }
          ],
          "columns": [
              {
                  "uniqueName": "Genre"
              },
              {
                  "uniqueName": "Duration"
              },
              {
                  "uniqueName": "Measures"
              }
          ],
          "measures": [
              {
                  "uniqueName": "Rating",
                  "aggregation": "sum"
              },
            {
                "uniqueName": "AVG",
                "formula": "sum(\"Duration\") / sum(\"Rating\")",
                "caption": "Avg"
            },
          ],
          "expands": {
              "columns": [
                  {
                      "tuple": [
                          "Genre.Adventure"
                      ]
                  },
                  {
                      "tuple": [
                          "Genre.Animation"
                      ]
                  },
                  {
                      "tuple": [
                          "Genre.Comedy"
                      ]
                  },
                  {
                      "tuple": [
                          "Genre.Fantasy"
                      ]
                  }
              ]
          }
      }
    }
});


答:
Based on your comments, the file d3chart.js will run the code to create the chart and apply it to a div with the class name chart-area. The quick and dirty way to have your code working, would be doing the following:

document.addEventListener("DOMContentLoaded", () => {
    document.body.addEventListener("click", e => {
        if (e.target.matches("[data-link]")) {
            e.preventDefault();
            navigateTo(e.target.href);
        }
        // scriptLoad(); <- remove this
    });
    router();
});
```
<p><strong>view1.js</strong></p>
<pre class="lang-js prettyprint-override"><code>import AbstracView from "./AbstractView.js"

export default class extends AbstracView {

    constructor() {
        super();
        this.setTitle("D3 Chart - View1");
    }

    async getHtml() {
        return `
            <h1>D3 Chart</h1>
            <div class="chart-area"></div>
            <script id="d3chart" src="static/js/d3chart.js"></script>
        `;
    }
}
</code>```

This would solve your initial problem but would create a new one, as you might already figured out, it makes an HTTP request every time you load that view! That might be what you want, but if not, you would need to change the structure of your code a bit. The code of the file d3chart.js would need to expose a loadChart function (or whatever you want to call it) and then you would load that script once and call the loadChart function whenever the view needs to be updated.

d3chart.js

function loadChart() {
  // Your code to create the chart and apply it to the an element.
}
```
<p><strong>Template</strong></p>
<pre class="lang-html prettyprint-override"><code><script id="d3chart" src="static/js/d3chart.js"></script>

View 1
View 2

<div id="app"></div>
</code>```

view1.js

import AbstracView from "./AbstractView.js"

export default class extends AbstracView {

    constructor() {
        super();
        this.setTitle("D3 Chart - View1");
    }

    async getHtml() {
        return `

D3 Chart

        `;
    }
}
```

Title: <script> tag only works on page refresh (Single Page Application)

Body:
I'm building a single-page application using plain Javascript + express-JS. I have two views linked to two anchor links so that I can toggle between the views. The problem is, one of the views (the default view) displays a d3 chart, and it only displays it when the site initially loads or on page refresh. If I just click on its own anchor link, theoretically it should do nothing and still display the chart but the chart vanishes but all the other html elements corresponding to that view stay. I'm making sure my script tag for that file is getting loaded into the base html file after all of my content is being loaded in, but still the issue persists. Can someone point out what's going wrong here?.

var tag = document.createElement("script");

function scriptLoad() {
    tag.src = "static/js/d3chart.js";
    tag.id = "d3chart"
    document.getElementsByTagName('head')[0].appendChild(tag);
};

document.addEventListener("DOMContentLoaded", () => {
    document.body.addEventListener("click", e => {
        if (e.target.matches("[data-link]")) {
            e.preventDefault();
            navigateTo(e.target.href);
        }
        scriptLoad();
    });
    router();
});

HTML anchor links in base html file

View 1
View 2

Whole Code

import view1 from "./views/view1.js"
import view2 from "./views/view2.js"

const pathToRegex = path => new RegExp("^" + path.replace(/\//g, "\\/").replace(/:\w+/g, "(.+)") + "$");

const getParams = match => {
    const values = match.result.slice(1);
    const keys = Array.from(match.route.path.matchAll(/:(\w+)/g)).map(result => result[1]);

    return Object.fromEntries(keys.map((key, i) => {
        return [key, values[i]];
    }));
};

const navigateTo = url => {
    history.pushState(null, null, url);
    router();
};

const router = async () => {
    const routes = [
        { path: "/", view: view1 },
        { path: "/view2", view: view2 }
    ];

    // Test each route for potential match
    const potentialMatches = routes.map(route => {
        return {
            route: route,
            result: location.pathname.match(pathToRegex(route.path))
        };
    });

    let match = potentialMatches.find(potentialMatch => potentialMatch.result !== null);

    if (!match) {
        match = {
            route: routes[0],
            result: [location.pathname]
        };
    }

    const view = new match.route.view(getParams(match));

    document.querySelector("#app").innerHTML = await view.getHtml();

};

window.addEventListener("popstate", router);

var tag = document.createElement("script");

function scriptLoad () {
    tag.src = "static/js/d3chart.js";
    tag.id = "d3chart"
    document.getElementsByTagName('body')[0].appendChild(tag);
}

document.addEventListener("DOMContentLoaded", () => {
    document.body.addEventListener("click", e => {
        if (e.target.matches("[data-link]")) {
            e.preventDefault();
            navigateTo(e.target.href);
        }
        scriptLoad();
    });
    router();
});

view1.js file - the default view on start (chart view)

import AbstracView from "./AbstractView.js"

export default class extends AbstracView {

    constructor() {
        super();
        this.setTitle("D3 Chart - View1");
    }

    async getHtml() {
        return `

D3 Chart

        `;
    }
}

Body:
Based on your comments, the file d3chart.js will run the code to create the chart and apply it to a div with the class name chart-area. The quick and dirty way to have your code working, would be doing the following:

document.addEventListener("DOMContentLoaded", () => {
    document.body.addEventListener("click", e => {
        if (e.target.matches("[data-link]")) {
            e.preventDefault();
            navigateTo(e.target.href);
        }
        // scriptLoad(); <- remove this
    });
    router();
});

view1.js

import AbstracView from "./AbstractView.js"

export default class extends AbstracView {

    constructor() {
        super();
        this.setTitle("D3 Chart - View1");
    }

    async getHtml() {
        return `
            <h1>D3 Chart</h1>
            <div class="chart-area"></div>
            <script id="d3chart" src="static/js/d3chart.js"></script>
        `;
    }
}

This would solve your initial problem but would create a new one, as you might already figured out, it makes an HTTP request every time you load that view! That might be what you want, but if not, you would need to change the structure of your code a bit. The code of the file d3chart.js would need to expose a loadChart function (or whatever you want to call it) and then you would load that script once and call the loadChart function whenever the view needs to be updated.

d3chart.js

function loadChart() {
  // Your code to create the chart and apply it to the an element.
}

Template

<script id="d3chart" src="static/js/d3chart.js"></script>

<a href="/" data-link>View 1</a>
<a href="/view2" data-link>View 2</a>

<div id="app"></div>

view1.js

import AbstracView from "./AbstractView.js"

export default class extends AbstracView {

    constructor() {
        super();
        this.setTitle("D3 Chart - View1");
    }

    async getHtml() {
        return `
            <h1>D3 Chart</h1>
            <div class="chart-area"></div>
            <script>loadChart();</script>
        `;
    }
}


问:
How to count special characters, Alphabets and numbers from a string in python?
```<code>string = '98 people are present @ seminar'

def count(string):
    d={}
    for t in string:
        d[t] = string.count(t)
    for k in sorted(d):
        print(k+':' +  str(d[k]))
count(string)
</code>```

here I want to add counters for special characters and numbers. also want to get user input for string. how do I do that?

答:
Python has various string methods to help distinguish alpha and numeric strings. You can test for these and count based on that test.</p>
```<code>def count(string):
    d={'letters': 0, 'numbers': 0, 'other': 0}
    for t in string:
        if t.isalpha():
            d['letters'] += 1
        elif t.isdigit():
            d['numbers'] += 1
        else:
            d['other'] += 1 # this will include spaces
    return d

string = input('enter some text: ')
# 98 people are present @ seminar

counts = count(string)
print(counts)
# {'letters': 23, 'numbers': 2, 'other': 6}
</code>```

Body:
string = '98 people are present @ seminar'

def count(string):
    d={}
    for t in string:
        d[t] = string.count(t)
    for k in sorted(d):
        print(k+':' +  str(d[k]))
count(string)

here I want to add counters for special characters and numbers. also want to get user input for string. how do I do that?

Body:
Python has various string methods to help distinguish alpha and numeric strings. You can test for these and count based on that test.

def count(string):
    d={'letters': 0, 'numbers': 0, 'other': 0}
    for t in string:
        if t.isalpha():
            d['letters'] += 1
        elif t.isdigit():
            d['numbers'] += 1
        else:
            d['other'] += 1 # this will include spaces
    return d

string = input('enter some text: ')
# 98 people are present @ seminar

counts = count(string)
print(counts)
# {'letters': 23, 'numbers': 2, 'other': 6}


问:
SQL Server, subset a table and create new column based on condition
If I have a table in SQL as:

id
code

1
6

1
8

1
4

2
3

2
7

2
4

3
7

3
6

3
7

What I need to do, logically is:

Get the top row of each group when grouped by id, ordered by code

Create a new column to show if the code column contained a 7 anywhere, within the group

Desired result:

id
code
c7

1
4
N

2
3
Y

3
6
Y

I think it needs a "CASE WHEN" statement in the SELECT, but have not worked it out. What query can I execute to get this?

答:
Seems like you can use a MIN and a conditional aggregate:

SELECT id,
       MIN(Code) AS Code,
       CASE WHEN COUNT(CASE code WHEN 7 THEN 1 END) > 0 THEN 'Y' ELSE 'N' END AS C7
FROM dbo.YourTable
GROUP BY id;
```


问:
MongoDB Charts - Cumulative document growth over time
I have an atlas cluster and I connected charts to it. I have zero experience with data visualizations (or building dashboards) and I'd like to chart the number of documents in my database over time. E.g., if in January 10 documents were created, and in February another 10 were created, then the chart should display 10 for January and 20 for February.

I know the _id field has information when the document was created, but I have no idea how to display it in the chart. So far, all I have is document count using _id in the y-axis.

What is the best way to accomplish what I'm trying to do? Is using a bar chart the best visualization to use in this situation?

Also, for some reason whenever I'm creating a chart, I get alerts saying "Query Targeting: Scanned Objects / Returned has gone above 1000". Is there any way to stop this for happening?

答:
Basically you need to do the following:

Since you want to treat the _id field as a date, you need to click the “…” button next to the _id field and choose Convert Type, then choose Date.

Now make sure you have a Column chart selected

Drag the _id field (which should now show as a date) onto the X axis. Keep the “Binning” toggle on and choose the binning period you want (Month is the default, and seems to be what you want).

Now also drag the _id field to the Y axis. Keep the default COUNT aggregation selected. The chart should now show the number of documents created each month.

Finally, enable the “Compare Periods” toggle and leave the deault “Cumulative Total” option selected.

Below is what the results "should" look like.


问:
How can I change a url without reloading the page?
I am using ajax to display my contents. As I display my contents, I want to change the browser url dynamically without reloading the page. How can I proceed?

```<code>window.location.hash="Aboutus";
</code>```

The above code inserts a # sign. I do not want a hash sign in my url since my page can contains a similar id.

答: The HTML5 pushState API should answer your problem.</p>

Body:
I am using ajax to display my contents. As I display my contents, I want to change the browser url dynamically without reloading the page. How can I proceed?

window.location.hash="Aboutus";

The above code inserts a # sign. I do not want a hash sign in my url since my page can contains a similar id.


问:
App rejected due to 3.1.1 - Business - Payments - In-App Purchase
This is what Apple have written back:

Guideline 3.1.1 - Business - Payments - In-App Purchase

Your app or metadata includes an account registration feature, which
  is considered an access to external mechanisms for purchases or
  subscriptions to be used in the app. Specifically, your app
  description contains a link to your website where users can register.

This is what they said to resolve the issue:

To resolve this issue, please remove the account registration feature
  and any other fully qualified links to your site that could indirectly
  provide access to these mechanisms, such as links to web pages for
  support, FAQs, product or program details, etc.

The app I'm developing is a B2B app where in a company can buy a subscription via the website and register its employees as users. What Apple is saying is that this is considered an external mechanism and that you should only use in-app purchases. The thing is that even if in-app purchase is implemented, because it is a B2B app and not a B2C, not every user has to buy a subscription, only a company has to buy one. It would help knowing if someone has gone through similar issues and what it took to resolve them.

答:
In your communication with Apple you can point to the following clauses of the App Store Review Guidelines (https://developer.apple.com/app-store/review/guidelines/), if applicable (it was applicable in my case):

3.1.3 Other Purchase Methods: The following apps may use purchase methods other than in-app purchase. Apps in this section cannot,
within the app, encourage users to use a purchasing method other than
in-app purchase. Developers can send communications outside of the app
to their user base about purchasing methods other than in-app
purchase.

3.1.3(c) Enterprise Services: If your app is only sold directly by you to organizations or groups for their employees or students (for
example professional databases and classroom management tools), you
may allow enterprise users to access previously-purchased content or
subscriptions. Consumer, single user, or family sales must use in-app
purchase.

3.1.3(f) Free Stand-alone Apps: Free apps acting as a stand-alone companion to a paid web based tool (eg. VOIP, Cloud Storage, Email
Services, Web Hosting) do not need to use in-app purchase, provided
there is no purchasing inside the app, or calls to action for purchase
outside of the app.


问:
How to join to tables in order to be able to calculate time difference
My initial table looks as follows:

initial table

There I want to calculate the time difference between login and logout. Therefor I want to create two new tables. One table which contains only logins and the 2nd table only contains logouts:

login-table

logout-table

My idea is now to do in a next step a join to merge these tables in order to be able to create a column with time difference:

joined table

The problem is:
-the blue colored rows are no problem. They can be identified by unique values (System = 2-system;  or day = 2)

-But how can I assign the correct logout time for user john, who does a login twice a day (day 1) and also a logout twice a day?

答:
I don't know if this will work for you but here is an idea.

Add new column in logout table ex: SessionLength (how long from login till logout).

Get the last login from the login table when he tries to logout and just substract the time of logout - when he logged in and just save in SessionLength column. Hope this idea can help


问:
Use Oracle's DBMS_SESSION.set_context in Entity Framework Core
I have the need to show on my .net core program an Oracle view that in the database has some columns filtered by

```<code>... WHERE dictionary.LANGUAGE = SYS_CONTEXT ('CLIENTCONTEXT', 'LANGUAGE');
</code>```

Obviously fetching the data directly on the application makes those columns return a null value.

I would need to implement something like this

```<code>OracleCommand cmd = new OracleCommand(String.Format("BEGIN DBMS_SESSION.SET_CONTEXT('CLIENTCONTEXT', 'LANGUAGE', '{0}'); END;", ActualLanguage), ORACLEconn as OracleConnection);
cmd.ExecuteNonQuery();
</code>```

How would I go about implementing the code using Entity Framework Core? Would I need to call it once on the model creation or every time I create a new DbContext?

Thank you.

答:
If you have a DbContext constructor that's only used when you want the session context set, you can force the connection open, and it will remain open until your DbContext is disposed.  eg

```<code>public Db(DbContextOptions opts) : base(opts)
{
    this.Database.OpenConnection();
    this.Database.ExecuteSqlRaw("BEGIN DBMS_SESSION.SET_CONTEXT('CLIENTCONTEXT', 'LANGUAGE', 'whatever'); END;");
}
</code>```

Or you can use an Interceptor to run the command every time a connection is opened.

Body:
I have the need to show on my .net core program an Oracle view that in the database has some columns filtered by

... WHERE dictionary.LANGUAGE = SYS_CONTEXT ('CLIENTCONTEXT', 'LANGUAGE');

Obviously fetching the data directly on the application makes those columns return a null value.

I would need to implement something like this

OracleCommand cmd = new OracleCommand(String.Format("BEGIN DBMS_SESSION.SET_CONTEXT('CLIENTCONTEXT', 'LANGUAGE', '{0}'); END;", ActualLanguage), ORACLEconn as OracleConnection);
cmd.ExecuteNonQuery();

How would I go about implementing the code using Entity Framework Core? Would I need to call it once on the model creation or every time I create a new DbContext?

Thank you.

Body:
If you have a DbContext constructor that's only used when you want the session context set, you can force the connection open, and it will remain open until your DbContext is disposed.  eg

public Db(DbContextOptions opts) : base(opts)
{
    this.Database.OpenConnection();
    this.Database.ExecuteSqlRaw("BEGIN DBMS_SESSION.SET_CONTEXT('CLIENTCONTEXT', 'LANGUAGE', 'whatever'); END;");
}

Or you can use an Interceptor to run the command every time a connection is opened.


问:
Error: Member not found: 'packageRoot', how to solve ignore: deprecated_member_use in Flutter?
In my flutter project, I have made some updates of plugins and then used flutter upgrade. After that, whenever I am running my flutter project it is showing following error-

```<code>    /C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/platform-3.0.2/lib/src/interface/local_platform.dart:46:19: Error: Member not found: 'packageRoot'.
          io.Platform.packageRoot; // ignore: deprecated_member_use
                      ^^^^^^^^^^^ FAILURE: Build failed with an exception.

* Where: Script 'C:\src\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1102

* What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 20s Exception: Gradle task assembleDebug failed with exit code 1
</code>```

So, I need a suggestion that how can I solve this issue?

答:
If all solutions above doesn't work for you just like me,

If the problem occurs immedately you upgrade your flutter

run fluter downgrade 2.0.1 //2.0.1 means your working previous version of flutter

after downgrading, click on the extensions button or use shorcut Ctrl+SHift+X, then uninstall and re-install Flutter and Dart.

this works for me.

Body:
In my flutter project, I have made some updates of plugins and then used flutter upgrade. After that, whenever I am running my flutter project it is showing following error-

    /C:/src/flutter/flutter/.pub-cache/hosted/pub.dartlang.org/platform-3.0.2/lib/src/interface/local_platform.dart:46:19: Error: Member not found: 'packageRoot'.
          io.Platform.packageRoot; // ignore: deprecated_member_use
                      ^^^^^^^^^^^ FAILURE: Build failed with an exception.

* Where: Script 'C:\src\flutter\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1102

* What went wrong: Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\src\flutter\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try: Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 20s Exception: Gradle task assembleDebug failed with exit code 1

So, I need a suggestion that how can I solve this issue?


问:
Crosshair appear and disappear on mouse-in and mouse-out
In looking at the crosshair example for pyqtgraph, crosshair.py, the crosshair is always visible, and is moved to the position of the mouse when the mouse is over the plot. This means that the crosshair will get stuck at the corners when the cursor exits the plot. Is there a robust way to turn the crosshair on and off when the mouse is over the plot? There are these sigMouseMoved and sigMouseHover signals, but it's possible to move your mouse out of the window fast enough that sigMouseHover won't fire with an empty argument, so I don't think it's hooked up to mouseLeave.

答:
To get mouseLeave event use leaveEvent of PlotWidget which inherits from QWidget.

LeaveEvent is always fired when cursor leaves, even with fast moving mouse cursor.

Opposite to this function is enterEvent, which we can use to show crosshair again.

Here is working example with hiding / showin crosshair.

```<code>import sys

import numpy as np
import pyqtgraph as pg
from PyQt5.QtWidgets import QApplication

class CrosshairPlotWidget(pg.PlotWidget):

    def __init__(self, parent=None, background='default', plotItem=None, **kargs):
        super().__init__(parent=parent, background=background, plotItem=plotItem, **kargs)
        self.vLine = pg.InfiniteLine(angle=90, movable=False)
        self.hLine = pg.InfiniteLine(angle=0, movable=False)
        self.addItem(self.vLine, ignoreBounds=True)
        self.addItem(self.hLine, ignoreBounds=True)
        self.hLine.hide()
        self.vLine.hide()

    def leaveEvent(self, ev):
        """Mouse left PlotWidget"""
        self.hLine.hide()
        self.vLine.hide()

    def enterEvent(self, ev):
        """Mouse enter PlotWidget"""
        self.hLine.show()
        self.vLine.show()

    def mouseMoveEvent(self, ev):
        """Mouse moved in PlotWidget"""
        if self.sceneBoundingRect().contains(ev.pos()):
            mousePoint = self.plotItem.vb.mapSceneToView(ev.pos())
            self.vLine.setPos(mousePoint.x())
            self.hLine.setPos(mousePoint.y())

if __name__ == "__main__":
    app = QApplication(sys.argv)

    x = [0, 1, 2, 3, 4, 5]
    y = np.random.normal(size=6)
    plot = CrosshairPlotWidget()
    plot.plot(x, y)
    plot.show()

    app.exec()
</code>```

Body:
To get mouseLeave event use leaveEvent of PlotWidget which inherits from QWidget.

LeaveEvent is always fired when cursor leaves, even with fast moving mouse cursor.

Opposite to this function is enterEvent, which we can use to show crosshair again.

Here is working example with hiding / showin crosshair.

import sys

import numpy as np
import pyqtgraph as pg
from PyQt5.QtWidgets import QApplication

class CrosshairPlotWidget(pg.PlotWidget):

    def __init__(self, parent=None, background='default', plotItem=None, **kargs):
        super().__init__(parent=parent, background=background, plotItem=plotItem, **kargs)
        self.vLine = pg.InfiniteLine(angle=90, movable=False)
        self.hLine = pg.InfiniteLine(angle=0, movable=False)
        self.addItem(self.vLine, ignoreBounds=True)
        self.addItem(self.hLine, ignoreBounds=True)
        self.hLine.hide()
        self.vLine.hide()

    def leaveEvent(self, ev):
        """Mouse left PlotWidget"""
        self.hLine.hide()
        self.vLine.hide()

    def enterEvent(self, ev):
        """Mouse enter PlotWidget"""
        self.hLine.show()
        self.vLine.show()

    def mouseMoveEvent(self, ev):
        """Mouse moved in PlotWidget"""
        if self.sceneBoundingRect().contains(ev.pos()):
            mousePoint = self.plotItem.vb.mapSceneToView(ev.pos())
            self.vLine.setPos(mousePoint.x())
            self.hLine.setPos(mousePoint.y())

if __name__ == "__main__":
    app = QApplication(sys.argv)

    x = [0, 1, 2, 3, 4, 5]
    y = np.random.normal(size=6)
    plot = CrosshairPlotWidget()
    plot.plot(x, y)
    plot.show()

    app.exec()


问:
Config Navigation bar only work if viewControllers are created inside viewWillAppear in UITabBarController
I have a UITabBarController with 2 ViewControllers: HomeViewController and ProfileViewController

Inside HomeViewController, I have to change the NavigationBar appearance with the following code:

```<code>    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let nav = self.navigationController {
            nav.navigationBar.layer.zPosition = 0
        }
        let logo = UIImage(named: "plentinaText")?.withRenderingMode(.alwaysTemplate)
        let container = UIView(frame: CGRect(x: 0, y: 0, width: 1000, height: 0))
        let imageView = UIImageView(image: logo)

        imageView.tintColor = .white
        imageView.contentMode = .scaleAspectFit
        container.addSubview(imageView)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: container.topAnchor),
            imageView.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: -10),
            imageView.centerXAnchor.constraint(equalTo: container.centerXAnchor),
            imageView.widthAnchor.constraint(equalToConstant: view.frame.width)
        ])
        self.tabBarController?.navigationItem.titleView = container
    }
</code>```

Problem is, this block of code only work if I create HomeViewController ProfileViewController inside viewWillAppear in UITabBarController.

If I put it in ViewDidLoad, it don't even have a NavigationBar. But when I push to another vc and go back to HomeViewController, the Nav bar will work as I wanted.

```<code>//
//  HomeTabbarController.swift
//  Plentina
//
//  Created on 10/29/21.
//

import UIKit

class HomeTabbarController: UITabBarController, UITabBarControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
        UITabBar.appearance().barTintColor = PlenitaColors.buttonBackGround // your color
        if #available(iOS 13.0, *) {
            UITabBar.appearance().unselectedItemTintColor = UIColor.systemGray4
        } else {
            UITabBar.appearance().unselectedItemTintColor = UIColor.lightGray
        }
        UITabBar.appearance().tintColor = .white
        if #available(iOS 15.0, *) {
           let appearance = UITabBarAppearance()
           appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = PlenitaColors.buttonBackGround

            tabBar.standardAppearance = appearance
            tabBar.scrollEdgeAppearance = appearance
        }
        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // tabbar 1
        let storyboard = UIStoryboard(name: "Custom", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "photo") as? HomeViewController
        let item1 = viewController
        let unselectedIcon1 = UIImage(named: "tabbarHome")?.withRenderingMode(.alwaysTemplate)
        let selectedIcon1 = UIImage(named: "tabbarHome")!.withRenderingMode(.alwaysTemplate)
        let icon1 = UITabBarItem(title: "Loans", image: unselectedIcon1, selectedImage: selectedIcon1)
        item1!.tabBarItem = icon1
        // tabbar 2
        let unselectedIcon2 = UIImage(named: "tabbarProfile")?.withRenderingMode(.alwaysTemplate)
        let selectedIcon2 = UIImage(named: "tabbarProfile")!.withRenderingMode(.alwaysTemplate)
        let item2 = ProfileViewController()
        let icon2 = UITabBarItem(title: "Profile", image: unselectedIcon2, selectedImage: selectedIcon2)
        item2.tabBarItem = icon2

        let controllers = [item1!, item2]  // array of the root view controllers displayed by the tab bar interface
        self.viewControllers = controllers
    }

    // Delegate methods
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("Should select viewController: \(viewController.title ?? "") ?")
        return true
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

</code>```

答:
I found a workaround. I just need to leave self.viewControllers = controllers in viewWillAppear and move the rest to ViewDidLoad, but I still don't know why?

```<code>class HomeTabbarController: UITabBarController, UITabBarControllerDelegate {
    var controllers: [Any]?
    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
        UITabBar.appearance().barTintColor = PlenitaColors.buttonBackGround // your color
        if #available(iOS 13.0, *) {
            UITabBar.appearance().unselectedItemTintColor = UIColor.systemGray4
        } else {
            UITabBar.appearance().unselectedItemTintColor = UIColor.lightGray
        }
        UITabBar.appearance().tintColor = .white
        if #available(iOS 15.0, *) {
           let appearance = UITabBarAppearance()
           appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = PlenitaColors.buttonBackGround

            tabBar.standardAppearance = appearance
            tabBar.scrollEdgeAppearance = appearance
        }

        // tabbar 1
        let storyboard = UIStoryboard(name: "Custom", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "photo") as? HomeViewController
        let item1 = viewController
        let unselectedIcon1 = UIImage(named: "tabbarHome")?.withRenderingMode(.alwaysTemplate)
        let selectedIcon1 = UIImage(named: "tabbarHome")!.withRenderingMode(.alwaysTemplate)
        let icon1 = UITabBarItem(title: "Loans", image: unselectedIcon1, selectedImage: selectedIcon1)
        item1!.tabBarItem = icon1
        // tabbar 2
        let unselectedIcon2 = UIImage(named: "tabbarProfile")?.withRenderingMode(.alwaysTemplate)
        let selectedIcon2 = UIImage(named: "tabbarProfile")!.withRenderingMode(.alwaysTemplate)
        let item2 = ProfileViewController()
        let icon2 = UITabBarItem(title: "Profile", image: unselectedIcon2, selectedImage: selectedIcon2)
        item2.tabBarItem = icon2

        controllers = [item1!, item2]  // array of the root view controllers displayed by the tab bar interface
        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.viewControllers = controllers as? [UIViewController]

    }

    // Delegate methods
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("Should select viewController: \(viewController.title ?? "") ?")
        return true
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

</code>```

Body:
I have a UITabBarController with 2 ViewControllers: HomeViewController and ProfileViewController

Inside HomeViewController, I have to change the NavigationBar appearance with the following code:

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if let nav = self.navigationController {
            nav.navigationBar.layer.zPosition = 0
        }
        let logo = UIImage(named: "plentinaText")?.withRenderingMode(.alwaysTemplate)
        let container = UIView(frame: CGRect(x: 0, y: 0, width: 1000, height: 0))
        let imageView = UIImageView(image: logo)

        imageView.tintColor = .white
        imageView.contentMode = .scaleAspectFit
        container.addSubview(imageView)
        imageView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: container.topAnchor),
            imageView.bottomAnchor.constraint(equalTo: container.bottomAnchor, constant: -10),
            imageView.centerXAnchor.constraint(equalTo: container.centerXAnchor),
            imageView.widthAnchor.constraint(equalToConstant: view.frame.width)
        ])
        self.tabBarController?.navigationItem.titleView = container
    }

Problem is, this block of code only work if I create HomeViewController ProfileViewController inside viewWillAppear in UITabBarController.

If I put it in ViewDidLoad, it don't even have a NavigationBar. But when I push to another vc and go back to HomeViewController, the Nav bar will work as I wanted.

//
//  HomeTabbarController.swift
//  Plentina
//
//  Created on 10/29/21.
//

import UIKit

class HomeTabbarController: UITabBarController, UITabBarControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
        UITabBar.appearance().barTintColor = PlenitaColors.buttonBackGround // your color
        if #available(iOS 13.0, *) {
            UITabBar.appearance().unselectedItemTintColor = UIColor.systemGray4
        } else {
            UITabBar.appearance().unselectedItemTintColor = UIColor.lightGray
        }
        UITabBar.appearance().tintColor = .white
        if #available(iOS 15.0, *) {
           let appearance = UITabBarAppearance()
           appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = PlenitaColors.buttonBackGround

            tabBar.standardAppearance = appearance
            tabBar.scrollEdgeAppearance = appearance
        }
        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // tabbar 1
        let storyboard = UIStoryboard(name: "Custom", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "photo") as? HomeViewController
        let item1 = viewController
        let unselectedIcon1 = UIImage(named: "tabbarHome")?.withRenderingMode(.alwaysTemplate)
        let selectedIcon1 = UIImage(named: "tabbarHome")!.withRenderingMode(.alwaysTemplate)
        let icon1 = UITabBarItem(title: "Loans", image: unselectedIcon1, selectedImage: selectedIcon1)
        item1!.tabBarItem = icon1
        // tabbar 2
        let unselectedIcon2 = UIImage(named: "tabbarProfile")?.withRenderingMode(.alwaysTemplate)
        let selectedIcon2 = UIImage(named: "tabbarProfile")!.withRenderingMode(.alwaysTemplate)
        let item2 = ProfileViewController()
        let icon2 = UITabBarItem(title: "Profile", image: unselectedIcon2, selectedImage: selectedIcon2)
        item2.tabBarItem = icon2

        let controllers = [item1!, item2]  // array of the root view controllers displayed by the tab bar interface
        self.viewControllers = controllers
    }

    // Delegate methods
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("Should select viewController: \(viewController.title ?? "") ?")
        return true
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

Body:
I found a workaround. I just need to leave self.viewControllers = controllers in viewWillAppear and move the rest to ViewDidLoad, but I still don't know why?

class HomeTabbarController: UITabBarController, UITabBarControllerDelegate {
    var controllers: [Any]?
    override func viewDidLoad() {
        super.viewDidLoad()
        delegate = self
        UITabBar.appearance().barTintColor = PlenitaColors.buttonBackGround // your color
        if #available(iOS 13.0, *) {
            UITabBar.appearance().unselectedItemTintColor = UIColor.systemGray4
        } else {
            UITabBar.appearance().unselectedItemTintColor = UIColor.lightGray
        }
        UITabBar.appearance().tintColor = .white
        if #available(iOS 15.0, *) {
           let appearance = UITabBarAppearance()
           appearance.configureWithOpaqueBackground()
            appearance.backgroundColor = PlenitaColors.buttonBackGround

            tabBar.standardAppearance = appearance
            tabBar.scrollEdgeAppearance = appearance
        }

        // tabbar 1
        let storyboard = UIStoryboard(name: "Custom", bundle: nil)
        let viewController = storyboard.instantiateViewController(withIdentifier: "photo") as? HomeViewController
        let item1 = viewController
        let unselectedIcon1 = UIImage(named: "tabbarHome")?.withRenderingMode(.alwaysTemplate)
        let selectedIcon1 = UIImage(named: "tabbarHome")!.withRenderingMode(.alwaysTemplate)
        let icon1 = UITabBarItem(title: "Loans", image: unselectedIcon1, selectedImage: selectedIcon1)
        item1!.tabBarItem = icon1
        // tabbar 2
        let unselectedIcon2 = UIImage(named: "tabbarProfile")?.withRenderingMode(.alwaysTemplate)
        let selectedIcon2 = UIImage(named: "tabbarProfile")!.withRenderingMode(.alwaysTemplate)
        let item2 = ProfileViewController()
        let icon2 = UITabBarItem(title: "Profile", image: unselectedIcon2, selectedImage: selectedIcon2)
        item2.tabBarItem = icon2

        controllers = [item1!, item2]  // array of the root view controllers displayed by the tab bar interface
        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.viewControllers = controllers as? [UIViewController]

    }

    // Delegate methods
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("Should select viewController: \(viewController.title ?? "") ?")
        return true
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}


问:
Variable Pyomo bounds
I'm modelling a 100 kWh battery. I have a set containing 24 hours.
Is it possible to have different upper bounds for charging the battery based on the battery's state of charge(SOC) which i don't know yet?
The SOC is decided later by the solver.

eg. at 50 % SOC the charging has an upper bound of 30 kW.
at 20  % SOC the charging has an upper bound of 10 kW.
The upper bound for charging is different for each SOC

```<code>def battery_upper_bound(m,t):
        return m.bat_charing[t] <= max(pyo.value(m.SOC[t]*4.18)),5)
m.battery_Max_charge_c = pyo.Constraint(m.t, rule=battery_upper_bound)
</code>```

My approach with pyo.value(m.SOC[t]) uses the initialized SOC value and is therefore equal in all timesteps and obviously not a feasible solution.

答:
If the relationship between these two variables is linear (or if that is a good enough approximation) as you have coded, then this is easy.  All you need to do is get rid of the max() function because max is a non-linear operation.  This can be done by just breaking your constraint into two constraints

```<code>def battery_charge_lim(m, t):
  return m.bat_charging[t] <= m.SOC[t]*4.18
m.batt_charge_lim = pyo.Constraint(m.t, rule=battery_charge_lim)

def battery_max_rate(m, t):
  return m.bat_charging[t] <= 5
m.battery_max_charge = pyo.Constraint(m.t, rule=battery_max_rate)
</code>```

Title: Variable Pyomo bounds

Body:
I'm modelling a 100 kWh battery. I have a set containing 24 hours.
Is it possible to have different upper bounds for charging the battery based on the battery's state of charge(SOC) which i don't know yet?
The SOC is decided later by the solver.

eg. at 50 % SOC the charging has an upper bound of 30 kW.
at 20  % SOC the charging has an upper bound of 10 kW.
The upper bound for charging is different for each SOC

def battery_upper_bound(m,t):
        return m.bat_charing[t] <= max(pyo.value(m.SOC[t]*4.18)),5)
m.battery_Max_charge_c = pyo.Constraint(m.t, rule=battery_upper_bound)

My approach with pyo.value(m.SOC[t]) uses the initialized SOC value and is therefore equal in all timesteps and obviously not a feasible solution.

Body:
If the relationship between these two variables is linear (or if that is a good enough approximation) as you have coded, then this is easy.  All you need to do is get rid of the max() function because max is a non-linear operation.  This can be done by just breaking your constraint into two constraints

def battery_charge_lim(m, t):
  return m.bat_charging[t] <= m.SOC[t]*4.18
m.batt_charge_lim = pyo.Constraint(m.t, rule=battery_charge_lim)

def battery_max_rate(m, t):
  return m.bat_charging[t] <= 5
m.battery_max_charge = pyo.Constraint(m.t, rule=battery_max_rate)


问:
Where to get Credits used by particular session_id in Snowflake
I am looking for an option to get the credit usage by specific session_id in Snowflake. is it possible to get the same? as i understand all credits are charged based on warehouse level. so curious if we can get those credits OR cost in USD for particular Session_id?</p>

答:
Session_id and credits_used_cloud_services are fields returned from

SELECT * FROM "SNOWFLAKE"."ACCOUNT_USAGE"."QUERY_HISTORY"
WHERE START_TIME > '2022-2-01'


问:
Can i use native javascript for loop within jquery code?
Can i use native javascript for loop within jquery code? I have a construct in which $.each does not seem feasible. How can I loop in this situation?

the code inside the for loop is not working. any advice would be appreciated.

```<code>if (item.relate){
    $(prodHeading).append(item.name);
    if (item.image) {$(prodContent).append(item.image);}
    if (item.description) {
        $(prodContentText).append(item.description);
        $(prodContent).append(prodContentText);
    }
    $(prodBox).append(prodHeading);
    $(prodBox).append(prodContent);

    //going to look for other attached items

    for (j=0; j<10; j++){
        var prodBox = $(document.createElement('div')).attr('class','productBox');
        var prodHeading = $(document.createElement('div')).attr('class','productBoxHeading');
        var prodContent = $(document.createElement('div')).attr('class','productBoxContent');
        var prodContentText = $(document.createElement('div')).attr('class','text');

        if ('item.image'+j) {$(prodContent).append(item.image);}
        if ('item.description'+j) {
            $(prodContentText).append(item.description);
            $(prodContent).append(prodContentText);
        }
        $(prodBox).append(prodHeading);
        $(prodBox).append(prodContent);
    }
}
</code>```

答:
Yes, you can use regular javascript with JQuery.

What is this if statement meant to do?

```<code>if ('item.description'+j)
</code>```

There is no comparison happening, so it will always be true.

Body:
Can i use native javascript for loop within jquery code? I have a construct in which $.each does not seem feasible. How can I loop in this situation?

the code inside the for loop is not working. any advice would be appreciated.

if (item.relate){
    $(prodHeading).append(item.name);
    if (item.image) {$(prodContent).append(item.image);}
    if (item.description) {
        $(prodContentText).append(item.description);
        $(prodContent).append(prodContentText);
    }
    $(prodBox).append(prodHeading);
    $(prodBox).append(prodContent);

    //going to look for other attached items

    for (j=0; j<10; j++){
        var prodBox = $(document.createElement('div')).attr('class','productBox');
        var prodHeading = $(document.createElement('div')).attr('class','productBoxHeading');
        var prodContent = $(document.createElement('div')).attr('class','productBoxContent');
        var prodContentText = $(document.createElement('div')).attr('class','text');

        if ('item.image'+j) {$(prodContent).append(item.image);}
        if ('item.description'+j) {
            $(prodContentText).append(item.description);
            $(prodContent).append(prodContentText);
        }
        $(prodBox).append(prodHeading);
        $(prodBox).append(prodContent);
    }
}

Body:
Yes, you can use regular javascript with JQuery.

What is this if statement meant to do?

if ('item.description'+j)

There is no comparison happening, so it will always be true.


问:
Printing a multidimensional array in C
I am trying to print a 2-D array in C by using pointers but I am not getting the expected output.

Program:-

```<code>#include <stdio.h>
int main()
{
    int arr[2][3] = {{1,2,3},{4,5,6}};
    int* p;
    for ( p = arr; p <= arr+6; p++)
    {
        printf("%d ", *p);
    }
    return 0;
}
</code>```

Output:-

1 2 3 4 5 6 -1116112128 1587637938 0 0 1893963109 32521 -1453950296 32766 -1453805568 1 800797033 21984 -1453949463

Could you tell me where I am wrong as the output should only be:

1 2 3 4 5 6

答:
First, when looping through arrays of size n wth an index i, the condition for continuation should be i < n rather than i <= n, because array indexes in C run from 0 through n-1.

However, your code has a more serious error: 1-dimensional arrays can be 'decayed' into pointers to the elements' type; however, 2-dimensional arrays decay into pointers to 1-dimensional arrays. So, in your case, the type of the pointer used in the arr + 6 expression is a pointer to an array of three integers; further, when the 6 is added, that operation is performed in terms of the size of the pointed-to object, which is sizeof(int) * 3 – so, even when changing the <= to <, you will be running far beyond the actual bounds of the array.

To make the pointer arithmetic work in the correct 'units' (i.e. sizeof(int)), cast the arr to an int* before the addition (and also change the <= to <):

#include <stdio.h>
int main()
{
    int arr[2][3] = { {1,2,3},{4,5,6} };
    int* p;
    for (p = (int*)arr; p < (int*)arr + 6; p++) {
        printf("%d ", *p);
    }
    return 0;
}
```

Title: Printing a multidimensional array in C

Body:
I am trying to print a 2-D array in C by using pointers but I am not getting the expected output.

Program:-

#include <stdio.h>
int main()
{
    int arr[2][3] = {{1,2,3},{4,5,6}};
    int* p;
    for ( p = arr; p <= arr+6; p++)
    {
        printf("%d ", *p);
    }
    return 0;
}

Output:-

1 2 3 4 5 6 -1116112128 1587637938 0 0 1893963109 32521 -1453950296 32766 -1453805568 1 800797033 21984 -1453949463

Could you tell me where I am wrong as the output should only be:

1 2 3 4 5 6


问:
React native touchablehighlight delete view inside
I'm stuck on a strange issue :
I create a component class and inside his render function I wrote this code to setup 2 toggle button at the bottom :

render() {
        return (
            <View style={this.style.container}>
                <View style={this.style.footer_container}>
                    <View style={this.style.left_container}></View>
                    <View style={this.style.right_container}></View>
                </View>
            </View>
        )
    }
```
<p>and it's work</p>
<p><img src="https://i.stack.imgur.com/Bdc9s.png" alt="enter image description here" /></p>
<p>But now I want to add TouchableHighlight arround my 2 button like :</p>
```render() {
        return (
            <View style={this.style.container}>
                <View style={this.style.footer_container}>
                    <TouchableHighlight underlayColor={"rgba(255, 0, 255,0)"} onPress={this.tooglePage}>
                        <View style={this.style.left_container}></View>
                    </TouchableHighlight>
                    <TouchableHighlight underlayColor={"rgba(255, 0, 255,0)"} onPress={this.tooglePage}>
                        <View style={this.style.right_container}></View>
                    </TouchableHighlight>
                </View>
            </View>
        )
    }
```
<p>and now my button are remplaced by this grey line...</p>
<p><img src="https://i.stack.imgur.com/bfAMI.png" alt="enter image description here" /></p>
<p>What did I do wrong ? I got a TouchableHilight item just above these button that work perfectly...</p>
<p>This.style and this.togglePage are already set</p>
<p>Thanks on advance</p>
<p>PS : I'm using expo 43.0.3 with react native 0.64.3</p>
<p>PSS : As Vasyl Nahuliak requirement, I put the entire class here :</p>
```interface toggleFunction {
    togglePage: () => void
}
class Toggle_page extends Component<toggleFunction> {
    gongImage: ImageSourcePropType = {
        uri: "./gongImage.png"
    }

    state: {gongpage:boolean} = {
        gongpage:true
    }

    tooglePage() {
        alert("Toogle !")
    }

    render() {
        return (
            <View style={this.styles.container}>
                <View style={this.styles.footer_container}>
                    <TouchableHighlight underlayColor={"rgba(255, 0, 255,0)"} onPress={this.tooglePage}>
                        <View style={this.styles.left_container}></View>
                    </TouchableHighlight>
                    <TouchableHighlight underlayColor={"rgba(255, 0, 255,0)"} onPress={this.tooglePage}>
                        <View style={this.styles.right_container}></View>
                    </TouchableHighlight>
                </View>
            </View>
        )
    }

    width:number = Dimensions.get("window").width;

    styles = StyleSheet.create({
        container: {
            flex: 1,
        },
        footer_container: {
            flex:1,
            flexDirection: "row",
            backgroundColor: "rgb(87, 87, 87)",
            width: Dimensions.get('window').width
        },
        left_container: {
            backgroundColor: "white",
            flex:1,
        },
        right_container: {
            backgroundColor: "blue",
            flex:1
        }
    })
}
```

答:
Need to add flex: 1 for TouchableHighlight

```<code>  <View style={this.styles.container}>
    <View style={this.styles.footer_container}>
      <TouchableHighlight
        underlayColor={'rgba(255, 0, 255,0)'}
        style={this.styles.button} // <--- add flex: 1
        onPress={this.tooglePage}>
        <View style={this.styles.left_container}></View>
      </TouchableHighlight>
      <TouchableHighlight
        style={this.styles.button} // <--- add flex: 1
        underlayColor={'rgba(255, 0, 255,0)'}
        onPress={this.tooglePage}>
        <View style={this.styles.right_container}></View>
      </TouchableHighlight>
    </View>
  </View>

  ...
  styles = StyleSheet.create({
    button: {
      flex: 1,
    },
  ...
</code>```

Live example here: https://snack.expo.dev/@vasylnahuliak/70908017-two-touchablehighlight

Body:
I'm stuck on a strange issue :
I create a component class and inside his render function I wrote this code to setup 2 toggle button at the bottom :

render() {
        return (
            <View style={this.style.container}>
                <View style={this.style.footer_container}>
                    <View style={this.style.left_container}></View>
                    <View style={this.style.right_container}></View>
                </View>
            </View>
        )
    }

and it's work

But now I want to add TouchableHighlight arround my 2 button like :

render() {
        return (
            <View style={this.style.container}>
                <View style={this.style.footer_container}>
                    <TouchableHighlight underlayColor={"rgba(255, 0, 255,0)"} onPress={this.tooglePage}>
                        <View style={this.style.left_container}></View>
                    </TouchableHighlight>
                    <TouchableHighlight underlayColor={"rgba(255, 0, 255,0)"} onPress={this.tooglePage}>
                        <View style={this.style.right_container}></View>
                    </TouchableHighlight>
                </View>
            </View>
        )
    }

and now my button are remplaced by this grey line...

What did I do wrong ? I got a TouchableHilight item just above these button that work perfectly...

This.style and this.togglePage are already set

Thanks on advance

PS : I'm using expo 43.0.3 with react native 0.64.3

PSS : As Vasyl Nahuliak requirement, I put the entire class here :

interface toggleFunction {
    togglePage: () => void
}
class Toggle_page extends Component<toggleFunction> {
    gongImage: ImageSourcePropType = {
        uri: "./gongImage.png"
    }

    state: {gongpage:boolean} = {
        gongpage:true
    }

    tooglePage() {
        alert("Toogle !")
    }

    render() {
        return (
            <View style={this.styles.container}>
                <View style={this.styles.footer_container}>
                    <TouchableHighlight underlayColor={"rgba(255, 0, 255,0)"} onPress={this.tooglePage}>
                        <View style={this.styles.left_container}></View>
                    </TouchableHighlight>
                    <TouchableHighlight underlayColor={"rgba(255, 0, 255,0)"} onPress={this.tooglePage}>
                        <View style={this.styles.right_container}></View>
                    </TouchableHighlight>
                </View>
            </View>
        )
    }

    width:number = Dimensions.get("window").width;

    styles = StyleSheet.create({
        container: {
            flex: 1,
        },
        footer_container: {
            flex:1,
            flexDirection: "row",
            backgroundColor: "rgb(87, 87, 87)",
            width: Dimensions.get('window').width
        },
        left_container: {
            backgroundColor: "white",
            flex:1,
        },
        right_container: {
            backgroundColor: "blue",
            flex:1
        }
    })
}

Body:
Need to add flex: 1 for TouchableHighlight

  <View style={this.styles.container}>
    <View style={this.styles.footer_container}>
      <TouchableHighlight
        underlayColor={'rgba(255, 0, 255,0)'}
        style={this.styles.button} // <--- add flex: 1
        onPress={this.tooglePage}>
        <View style={this.styles.left_container}></View>
      </TouchableHighlight>
      <TouchableHighlight
        style={this.styles.button} // <--- add flex: 1
        underlayColor={'rgba(255, 0, 255,0)'}
        onPress={this.tooglePage}>
        <View style={this.styles.right_container}></View>
      </TouchableHighlight>
    </View>
  </View>

  ...
  styles = StyleSheet.create({
    button: {
      flex: 1,
    },
  ...

Live example here: https://snack.expo.dev/@vasylnahuliak/70908017-two-touchablehighlight


问:
File counter expression in SSIS using execute process task output variable
I have a console application in c# that downloads files from a website.
I have created a variable named Filecount that counts the number of files downloaded in that instance.

In SSIS, I have set the StandardOutputVariable in the Execute process task configuration as User::FileCount that should pass through the number of files that it has downloaded.

I want to create an SQL task that will truncate the table if the file count is greater than 0.

However, when I try to evaluate my expression, it always comes back as true however, this should not occur as no counts have been passed through yet meaning it should be evaluated as false.

Can someone explain if I have either written the expression wrong or set the variable incorrectly?

int fileCount = 0;

using (var client = new HttpClient(handler))
{
    client.DefaultRequestHeaders.Clear();
    client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
    var response = await client.GetAsync(siteUrl + "/_api/Web/GetFolderByServerRelativeUrl('XXX')/Files");
    response.EnsureSuccessStatusCode();

    json = await response.Content.ReadAsStringAsync();
    Root deserializedResults = JsonConvert.DeserializeObject<Root>(json);

    foreach (Result result in deserializedResults.d.results)
    {
        if (result.TimeCreated > DateTime.Today.AddDays(-7))
        {
            DownloadFileViaRestAPI(siteUrl, credentials, "XXX", result.Name, "XXX");
            fileCount++;
        }
    }
}

Console.Write(fileCount);
```
<p>SSIS Execute Process Task;</p>
```StandardOutVariable = User::FileCount
```
<p>SQL Task expression;</p>
```Property: Disable
Expression: Len(Trim(@[User::FileCount])) > 0 ? False : True
```

答:
tl;dr; What you've described and my implementation work fine so something else is going awry in your situation.

Set up

I built out a simple SSIS package. Execute Package Task -> Script task (to dump variable values to console) -> A Sequence Container that has your disable logic on it => Another script task (to dump to console if the disable works/does not work)

I have your original variable, User::FileCount of type String and added User::HasFile of type Boolean with an expression of Len(Trim(@[User::FileCount])) > 0 to test your logic.

SO_71067359.bat

I created a batch file that will serve as your C# app. When needed, I'll remove line 2 so no output is generated. Contents are

```<code>@echo off
echo 1
</code>```

Results

```<code>C:\ssisdata>SO_71067359.bat
1
</code>```

EPT Download File

Execute Package Task. Working directory set to the location of my batch file. Executable is the batch script. StandardOutputVariable is User::FileCount

SCR Echo Back

This is my standard echo back script and I'll add User::FileCount and User::HasFile. When the package runs, this will dump the values to the Console output which is something I can copy and paste unlike the pretty Results tab most are familiar with

Content in case my blog goes away is

```<code>bool fireAgain = false;
string message = "{0}::{1} : {2}";
foreach (var item in Dts.Variables)
{
    Dts.Events.FireInformation(0, "SCR Echo Back", string.Format(message, item.Namespace, item.Name, item.Value), "", 0, ref fireAgain);
}
</code>```

SEQC Simulate Other

This is a sequence container that has your Disable logic directly added to it. Yes, I have the variable but since you have the inversion of the results, I didn't want to sully the test.

Yes it ran

Inside the sequence container is a copy/paste of the SCR Echo Back except I renamed it to "Yes it ran" and specified the only variable is System::TaskName  If the task runs, the console will print the name of the task.

Test round 1

The output of the batch script will be "1" so we expect to see the Inner task fire. Let's check the console

```<code>SSIS package "C:\Users\bfellows\source\repos\SO_Trash\SO_Trash\SO_71067359.dtsx" starting.
Information: 0x0 at SCR Echo Back, SCR Echo Back: User::FileCount->1
Information: 0x0 at SCR Echo Back, SCR Echo Back: User::HasFiles->True
Information: 0x0 at Yes it ran, SCR Echo Back: System::TaskName->Yes it ran
SSIS package "C:\Users\bfellows\source\repos\SO_Trash\SO_Trash\SO_71067359.dtsx" finished: Success.
The program '[2268] DtsDebugHost.exe: DTS' has exited with code 0 (0x0).
</code>```

Test Round 2

Clearing line 2 of the bat file

```<code>SSIS package "C:\Users\bfellows\source\repos\SO_Trash\SO_Trash\SO_71067359.dtsx" starting.
Information: 0x0 at SCR Echo Back, SCR Echo Back: User::FileCount->
Information: 0x0 at SCR Echo Back, SCR Echo Back: User::HasFiles->False
SSIS package "C:\Users\bfellows\source\repos\SO_Trash\SO_Trash\SO_71067359.dtsx" finished: Success.
The program '[75252] DtsDebugHost.exe: DTS' has exited with code 0 (0x0).
</code>```

Body:
I have a console application in c# that downloads files from a website.
I have created a variable named Filecount that counts the number of files downloaded in that instance.

In SSIS, I have set the StandardOutputVariable in the Execute process task configuration as User::FileCount that should pass through the number of files that it has downloaded.

I want to create an SQL task that will truncate the table if the file count is greater than 0.

However, when I try to evaluate my expression, it always comes back as true however, this should not occur as no counts have been passed through yet meaning it should be evaluated as false.

Can someone explain if I have either written the expression wrong or set the variable incorrectly?

int fileCount = 0;

using (var client = new HttpClient(handler))
{
    client.DefaultRequestHeaders.Clear();
    client.DefaultRequestHeaders.Add("Accept", "application/json;odata=verbose");
    var response = await client.GetAsync(siteUrl + "/_api/Web/GetFolderByServerRelativeUrl('XXX')/Files");
    response.EnsureSuccessStatusCode();

    json = await response.Content.ReadAsStringAsync();
    Root deserializedResults = JsonConvert.DeserializeObject<Root>(json);

    foreach (Result result in deserializedResults.d.results)
    {
        if (result.TimeCreated > DateTime.Today.AddDays(-7))
        {
            DownloadFileViaRestAPI(siteUrl, credentials, "XXX", result.Name, "XXX");
            fileCount++;
        }
    }
}

Console.Write(fileCount);

SSIS Execute Process Task;

StandardOutVariable = User::FileCount

SQL Task expression;

Property: Disable
Expression: Len(Trim(@[User::FileCount])) > 0 ? False : True

Body:
tl;dr; What you've described and my implementation work fine so something else is going awry in your situation.

Set up

I built out a simple SSIS package. Execute Package Task -> Script task (to dump variable values to console) -> A Sequence Container that has your disable logic on it => Another script task (to dump to console if the disable works/does not work)

I have your original variable, User::FileCount of type String and added User::HasFile of type Boolean with an expression of Len(Trim(@[User::FileCount])) > 0 to test your logic.

SO_71067359.bat

I created a batch file that will serve as your C# app. When needed, I'll remove line 2 so no output is generated. Contents are

@echo off
echo 1

Results

C:\ssisdata>SO_71067359.bat
1

EPT Download File

Execute Package Task. Working directory set to the location of my batch file. Executable is the batch script. StandardOutputVariable is User::FileCount

SCR Echo Back

This is my standard echo back script and I'll add User::FileCount and User::HasFile. When the package runs, this will dump the values to the Console output which is something I can copy and paste unlike the pretty Results tab most are familiar with

Content in case my blog goes away is

bool fireAgain = false;
string message = "{0}::{1} : {2}";
foreach (var item in Dts.Variables)
{
    Dts.Events.FireInformation(0, "SCR Echo Back", string.Format(message, item.Namespace, item.Name, item.Value), "", 0, ref fireAgain);
}

SEQC Simulate Other

This is a sequence container that has your Disable logic directly added to it. Yes, I have the variable but since you have the inversion of the results, I didn't want to sully the test.

Yes it ran

Inside the sequence container is a copy/paste of the SCR Echo Back except I renamed it to "Yes it ran" and specified the only variable is System::TaskName  If the task runs, the console will print the name of the task.

Test round 1

The output of the batch script will be "1" so we expect to see the Inner task fire. Let's check the console

SSIS package "C:\Users\bfellows\source\repos\SO_Trash\SO_Trash\SO_71067359.dtsx" starting.
Information: 0x0 at SCR Echo Back, SCR Echo Back: User::FileCount->1
Information: 0x0 at SCR Echo Back, SCR Echo Back: User::HasFiles->True
Information: 0x0 at Yes it ran, SCR Echo Back: System::TaskName->Yes it ran
SSIS package "C:\Users\bfellows\source\repos\SO_Trash\SO_Trash\SO_71067359.dtsx" finished: Success.
The program '[2268] DtsDebugHost.exe: DTS' has exited with code 0 (0x0).

Test Round 2

Clearing line 2 of the bat file

SSIS package "C:\Users\bfellows\source\repos\SO_Trash\SO_Trash\SO_71067359.dtsx" starting.
Information: 0x0 at SCR Echo Back, SCR Echo Back: User::FileCount->
Information: 0x0 at SCR Echo Back, SCR Echo Back: User::HasFiles->False
SSIS package "C:\Users\bfellows\source\repos\SO_Trash\SO_Trash\SO_71067359.dtsx" finished: Success.
The program '[75252] DtsDebugHost.exe: DTS' has exited with code 0 (0x0).