问:
Flutter TextFormField not updating it's value
i'va made a TimePicker that will pop up when user taps on textFormField it's working fine but the only problem is that i want to update textFormField value by the one selected from timePicker
I've declared a controller and initilize a selectedTimer

```<code>  TimeOfDay selectedTime = TimeOfDay(hour: 0, minute: 0);
  TextEditingController _timeController = TextEditingController();
</code>```

And this is the code of TextFormField

```<code> TextFormField(
      controller: _timeController,
      onTap: () {
         FocusScope.of(context).requestFocus(new FocusNode());
         _selectTime(context);
      },
  ),
</code>```

And this is the code for the method _selectTime

```<code>_selectTime(BuildContext context) async {
    final TimeOfDay? timeOfDay = await showTimePicker(
      context: context,
      initialTime: selectedTime,
      initialEntryMode: TimePickerEntryMode.dial,
    );
    if (timeOfDay != null && timeOfDay != selectedTime) {
      setState(() {
        selectedTime = timeOfDay;
        TextEditingValue(text: timeOfDay.toString());
      });
    }
  }
</code>```

答:
```<code> selectTime(BuildContext context) async {
final TimeOfDay? timeOfDay = await showTimePicker(
  context: context,
  initialTime: selectedTime,
  initialEntryMode: TimePickerEntryMode.dial,
);
if (timeOfDay != null && timeOfDay != selectedTime) {
  setState(() {
    selectedTime = timeOfDay;
    _timeController.text=timeOfDay.toString();
    TextEditingValue(text: timeOfDay.toString());
  });
}
</code>```
<p>}</p>

Body:
i'va made a TimePicker that will pop up when user taps on textFormField it's working fine but the only problem is that i want to update textFormField value by the one selected from timePicker
I've declared a controller and initilize a selectedTimer

  TimeOfDay selectedTime = TimeOfDay(hour: 0, minute: 0);
  TextEditingController _timeController = TextEditingController();

And this is the code of TextFormField

 TextFormField(
      controller: _timeController,
      onTap: () {
         FocusScope.of(context).requestFocus(new FocusNode());
         _selectTime(context);
      },
  ),

And this is the code for the method _selectTime

_selectTime(BuildContext context) async {
    final TimeOfDay? timeOfDay = await showTimePicker(
      context: context,
      initialTime: selectedTime,
      initialEntryMode: TimePickerEntryMode.dial,
    );
    if (timeOfDay != null && timeOfDay != selectedTime) {
      setState(() {
        selectedTime = timeOfDay;
        TextEditingValue(text: timeOfDay.toString());
      });
    }
  }

Body:
 selectTime(BuildContext context) async {
final TimeOfDay? timeOfDay = await showTimePicker(
  context: context,
  initialTime: selectedTime,
  initialEntryMode: TimePickerEntryMode.dial,
);
if (timeOfDay != null && timeOfDay != selectedTime) {
  setState(() {
    selectedTime = timeOfDay;
    _timeController.text=timeOfDay.toString();
    TextEditingValue(text: timeOfDay.toString());
  });
}

}


来源: stackexchange

问:
How to replace existing object in array only modifying its props and not affect to other items?
I'm trying to add item to the cart. If it is in cart, I want to replace this item with updated count and total accordingly, but I don't want to affect to other items. If it is not in cart I add it (logic of if statement). How to implement logic of else statement?

```<code>class ProductProvider extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cart: [],
      modalOpen: false,
      modalProduct: {},
      cartTotal: 0,
    };
  }

  addToCart = (product) => {
    const index = this.state.cart.findIndex((item) => item.id === product.id);
    if (index === -1) {
      const tempProduct = { ...product };
      tempProduct.inCart = true;
      tempProduct.count = 1;
      const price = product.prices[0].amount;
      tempProduct.total = price;

      this.setState(
        () => {
          return { cart: [...this.state.cart, tempProduct] };
        },
        () => {
          this.addTotal();
        }
      );
    } else {
            // solution must be here
    }
  };

    addTotal = () => {
    let total = 0;
    this.state.cart.map((item) => (total += item.total));

    this.setState(() => {
      return {
        cartTotal: parseFloat(total.toFixed(2)),
      };
    });
  };
}
</code>```

Seems like this approach, I'm currently trying to apply in other component works well. I need to test it and adapt for previous case.

```<code>constructor(props) {
    super(props);
    this.state = {
      readMore: false,
      activeID: null,
      activeAtt: null,
      selectedAttributes: [],
    };
  }

  setAttributes = (name, value) => {
    const index = this.state.selectedAttributes.findIndex(
      (item) => item.name === name
    );
    if (index === -1) {
      const newAttribute = { name, value };

      this.setState(() => {
        return {
          selectedAttributes: [...this.state.selectedAttributes, newAttribute],
        };
      });
    } else {
      const tempAttributes = [...this.state.selectedAttributes];
      const selectedAttribute = tempAttributes.find(
        (attribute) => attribute.name === name
      );
      selectedAttribute.value = value;
      this.setState(() => {
        return { selectedAttributes: [...tempAttributes] };
      });
    }
</code>```

答:
```<code>else {
      const tempCart = [...this.state.cart];
      const selectedItem = tempCart.find((item) => item.id === product.id);
      selectedItem.selectedAttributes = attributes;
      selectedItem.count = selectedItem.count + 1;
      const price = product.prices[0].amount;
      selectedItem.total = selectedItem.total + price;

      this.setState(
        () => {
          return { cart: [...tempCart] };
        },
        () => {
          this.addTotal();
        }
      );
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to add item to the cart. If it is in cart, I want to replace this item with updated count and total accordingly, but I don't want to affect to other items. If it is not in cart I add it (logic of if statement). How to implement logic of else statement?

class ProductProvider extends Component {
  constructor(props) {
    super(props);
    this.state = {
      cart: [],
      modalOpen: false,
      modalProduct: {},
      cartTotal: 0,
    };
  }

  addToCart = (product) => {
    const index = this.state.cart.findIndex((item) => item.id === product.id);
    if (index === -1) {
      const tempProduct = { ...product };
      tempProduct.inCart = true;
      tempProduct.count = 1;
      const price = product.prices[0].amount;
      tempProduct.total = price;

      this.setState(
        () => {
          return { cart: [...this.state.cart, tempProduct] };
        },
        () => {
          this.addTotal();
        }
      );
    } else {
            // solution must be here
    }
  };

    addTotal = () => {
    let total = 0;
    this.state.cart.map((item) => (total += item.total));

    this.setState(() => {
      return {
        cartTotal: parseFloat(total.toFixed(2)),
      };
    });
  };
}

Seems like this approach, I'm currently trying to apply in other component works well. I need to test it and adapt for previous case.

constructor(props) {
    super(props);
    this.state = {
      readMore: false,
      activeID: null,
      activeAtt: null,
      selectedAttributes: [],
    };
  }

  setAttributes = (name, value) => {
    const index = this.state.selectedAttributes.findIndex(
      (item) => item.name === name
    );
    if (index === -1) {
      const newAttribute = { name, value };

      this.setState(() => {
        return {
          selectedAttributes: [...this.state.selectedAttributes, newAttribute],
        };
      });
    } else {
      const tempAttributes = [...this.state.selectedAttributes];
      const selectedAttribute = tempAttributes.find(
        (attribute) => attribute.name === name
      );
      selectedAttribute.value = value;
      this.setState(() => {
        return { selectedAttributes: [...tempAttributes] };
      });
    }


问:
Should I dispose a Mutex?
I'm working on 2 Windows Services that have a common database which I want to lock (cross-process) with a system Mutex.

Now I'm wondering whether it's ok to just call WaitOne() and ReleaseMutex() in a try-finally block or should I also dispose the Mutex (e.g. in a using block). If so I guess I should always catch the AbandonedMutexException on the WaitOne() method or am I wrong here?

答:
According to this a named Mutex is automatically destroyed when the last process holding a HANDLE of that Mutex ends.

In non-managed terms MSDN says

Use the CloseHandle function to close the handle. The system closes the handle automatically when the process terminates. The mutex object is destroyed when its last handle has been closed.

In .NET you should call .Close() on the Mutex - this releases the HANDLE... since every process gets its own HANDLE when accessing even the same named Mutex this is consistent practice... not calling Close() won't leave any problems behing once the process is no more (finalizers and all)...

ContentLicense: CC BY-SA 3.0

Title: Should I dispose a Mutex?


问:
How to setup letsencrypt on kubernetes on azure?
I am learning kubernetes and trying to setup letsencrypt for my web app.

I have bought a domain from amazon route 53. Lets just called it example.com

Then I go and create a cluster in azure, install all applications that needed:

Install helm choco install kubernetes-helm

helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx

helm repo update

Apply deployment.yml file

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp1-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: myapp1
  template:
    metadata:
      name: myapp1-pod
      labels: # Dictionary
        app: myapp1
    spec:
      containers: # List
        - name: myapp1-container
          image: stacksimplify/kubenginx:1.0.0
          ports:
            - containerPort: 80
</code>```

Apply service.yml

```<code>apiVersion: v1
kind: Service
metadata:
  name: myapp1-loadbalancer
  labels:
    app: myapp1
spec:
  selector:
    app: myapp1
  ports:
    - port: 80
      targetPort: 80
</code>```

Apply ingress.yml

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: myapp-ingress-demo
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/cluster-issuer: cluster-issuer-name
    cert-manager.io/acme-challenge-type: http01
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - host: "example.com"
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: myapp1-loadbalancer
            port:
              number: 80
  tls:
    - hosts:
      - example.com
      secretName: secret-name
</code>```

In Azure portal, look for public Ip that is associated with the cluster that you created at the beginning. By default, when an k8 cluster is created, azure will create one public ip associated to this cluster. Look for it, go to front end configuration, and take note of the ip.

Run this command below, replace the ip that you have

```<code># Use Helm to deploy an NGINX ingress controller
helm install ingress-nginx ingress-nginx/ingress-nginx
    --set controller.replicaCount=2 \
    --set controller.nodeSelector."beta\.kubernetes\.io/os"=linux \
    --set defaultBackend.nodeSelector."beta\.kubernetes\.io/os"=linux \
    --set controller.service.externalTrafficPolicy=Local \
    --set controller.service.loadBalancerIP="YOUR IP"
</code>```
```<code>9. If done correctly, you should have load balancer service running now. Verify it with kubernetes: `kubectl get svc`. Take note of this ip address for the load balancer
</code>```

Go to Amazon route 53 dashboard, add a record with the ip address that you have at step 9 for your domain name that you have in ingress.yml

Enjoy your work :)

Thank you

I have update my questions with steps on how to product the result. Thanks SOF for awesome support. Hopefully that if someone run into this issue again, they know how to configure it properly.

答:
You are missing few minor things which you might need to do and try updating once again.

URL in cluster issue is not for Prod you are using staging, i would recommend using the prod URL only for any case instead of the staging.

```<code>apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-staging
spec:
  acme:
    server: https://acme-staging-v02.api.letsencrypt.org/directory
    email: abc@abc.com
    privateKeySecretRef:
      name: letsencrypt-staging
    solvers:
    - http01:
        ingress:
          class: nginx
</code>```

Use : https://acme-v02.api.letsencrypt.org/directory

Second :

You have not attached your secret to ingress which ideally will be storing your TLS cert.

How process work is like,

cert-manager get the certificate and store it inside the kubernetes secret, in your case it will be, letsencrypt-staging you have mentioned in clusterissuer.

This secret also should be attached to ingress so that when anyone hits endpoint ingress use this cert for HTTPS traffic.

Full reference example:

```<code>apiVersion: cert-manager.io/v1alpha2
kind: ClusterIssuer
metadata:
  name: cluster-issuer-name
  namespace: development
spec:
  acme:
    server: https://acme-v02.api.letsencrypt.org/directory
    email: harsh@example.com
    privateKeySecretRef:
      name: secret-name
    solvers:
    - http01:
        ingress:
          class: nginx-class-name
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx-class-name
    cert-manager.io/cluster-issuer: cluster-issuer-name
    nginx.ingress.kubernetes.io/rewrite-target: /
  name: example-ingress
spec:
  rules:
  - host: sub.example.com
    http:
      paths:
      - path: /api
        backend:
          serviceName: service-name
          servicePort: 80
  tls:
  - hosts:
    - sub.example.com
    secretName: secret-name
</code>```

in above example i have used the annotatino in ingress : cert-manager.io/cluster-issuer: cluster-issuer-name

it will trigger clusterissuer to generate cert whenever ingress is created, once cert is created it will be stored in K8s secret. so to attach SSL/TLS cert secret with ingress i have added TLS block at last of ingress YAML.

If you are applying my suggested changes you wont need to create this

```<code>apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: ssl-cert-staging
  namespace: default
spec:
  secretName: ssl-cert-staging
  issuerRef:
    name: letsencrypt-staging
    kind: ClusterIssuer
  dnsNames:
  - example.com
</code>```

cert-manager will auto-create for you, you can remove this also and just apply above example snippet with minor changes required of name and etc.

Body:
I am learning kubernetes and trying to setup letsencrypt for my web app.

I have bought a domain from amazon route 53. Lets just called it example.com

Then I go and create a cluster in azure, install all applications that needed:

Install helm choco install kubernetes-helm

helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx

helm repo update

Apply deployment.yml file

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myapp1-deployment
spec:
  replicas: 3
  selector:
    matchLabels:
      app: myapp1
  template:
    metadata:
      name: myapp1-pod
      labels: # Dictionary
        app: myapp1
    spec:
      containers: # List
        - name: myapp1-container
          image: stacksimplify/kubenginx:1.0.0
          ports:
            - containerPort: 80

Apply service.yml

apiVersion: v1
kind: Service
metadata:
  name: myapp1-loadbalancer
  labels:
    app: myapp1
spec:
  selector:
    app: myapp1
  ports:
    - port: 80
      targetPort: 80

Apply ingress.yml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: myapp-ingress-demo
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/cluster-issuer: cluster-issuer-name
    cert-manager.io/acme-challenge-type: http01
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - host: "example.com"
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: myapp1-loadbalancer
            port:
              number: 80
  tls:
    - hosts:
      - example.com
      secretName: secret-name

In Azure portal, look for public Ip that is associated with the cluster that you created at the beginning. By default, when an k8 cluster is created, azure will create one public ip associated to this cluster. Look for it, go to front end configuration, and take note of the ip.

Run this command below, replace the ip that you have

# Use Helm to deploy an NGINX ingress controller
helm install ingress-nginx ingress-nginx/ingress-nginx
    --set controller.replicaCount=2 \
    --set controller.nodeSelector."beta\.kubernetes\.io/os"=linux \
    --set defaultBackend.nodeSelector."beta\.kubernetes\.io/os"=linux \
    --set controller.service.externalTrafficPolicy=Local \
    --set controller.service.loadBalancerIP="YOUR IP"

9. If done correctly, you should have load balancer service running now. Verify it with kubernetes: `kubectl get svc`. Take note of this ip address for the load balancer

Go to Amazon route 53 dashboard, add a record with the ip address that you have at step 9 for your domain name that you have in ingress.yml

Enjoy your work :)

Thank you

I have update my questions with steps on how to product the result. Thanks SOF for awesome support. Hopefully that if someone run into this issue again, they know how to configure it properly.

Body:
You are missing few minor things which you might need to do and try updating once again.

URL in cluster issue is not for Prod you are using staging, i would recommend using the prod URL only for any case instead of the staging.

apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-staging
spec:
  acme:
    server: https://acme-staging-v02.api.letsencrypt.org/directory
    email: abc@abc.com
    privateKeySecretRef:
      name: letsencrypt-staging
    solvers:
    - http01:
        ingress:
          class: nginx

Use : https://acme-v02.api.letsencrypt.org/directory

Second :

You have not attached your secret to ingress which ideally will be storing your TLS cert.

How process work is like,

cert-manager get the certificate and store it inside the kubernetes secret, in your case it will be, letsencrypt-staging you have mentioned in clusterissuer.

This secret also should be attached to ingress so that when anyone hits endpoint ingress use this cert for HTTPS traffic.

Full reference example:

apiVersion: cert-manager.io/v1alpha2
kind: ClusterIssuer
metadata:
  name: cluster-issuer-name
  namespace: development
spec:
  acme:
    server: https://acme-v02.api.letsencrypt.org/directory
    email: harsh@example.com
    privateKeySecretRef:
      name: secret-name
    solvers:
    - http01:
        ingress:
          class: nginx-class-name
---
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx-class-name
    cert-manager.io/cluster-issuer: cluster-issuer-name
    nginx.ingress.kubernetes.io/rewrite-target: /
  name: example-ingress
spec:
  rules:
  - host: sub.example.com
    http:
      paths:
      - path: /api
        backend:
          serviceName: service-name
          servicePort: 80
  tls:
  - hosts:
    - sub.example.com
    secretName: secret-name

in above example i have used the annotatino in ingress : cert-manager.io/cluster-issuer: cluster-issuer-name

it will trigger clusterissuer to generate cert whenever ingress is created, once cert is created it will be stored in K8s secret. so to attach SSL/TLS cert secret with ingress i have added TLS block at last of ingress YAML.

If you are applying my suggested changes you wont need to create this

apiVersion: cert-manager.io/v1
kind: Certificate
metadata:
  name: ssl-cert-staging
  namespace: default
spec:
  secretName: ssl-cert-staging
  issuerRef:
    name: letsencrypt-staging
    kind: ClusterIssuer
  dnsNames:
  - example.com

cert-manager will auto-create for you, you can remove this also and just apply above example snippet with minor changes required of name and etc.


问:
Can I do data augmentation with gaussian blur on my tf.Dataset using my GPU?
I would like to change my old queue based pipeline to the new dataset API on tensorflow for reasons of performance. However, once my code changed, it runs in 8 hours instead of 2.

The use of my GPU was about 30/40% and it's now between 0 and 6%.

I found the line which making it so slow, and it's when I apply gaussian blur on my dataset :

```<code>def gaussian_blur(imgs,lbls):
   imgs = tf.nn.conv2d(imgs,k_conv,
                                   strides=[1, 1, 1, 1],
                                   padding='SAME',
                                   data_format='NHWC'
                                   )
   return imgs, lbls

ds = ds.map(gaussian_blur)
</code>```

With my old queue-based pipeline, this line almost doesn't slow my program.

I think it's because this line used to run on the GPU but the new dataset API forces it to run on the CPU which is way slower and already 100% used.

Do you have any idea on how can I apply gaussian blur with out decreasing so much the performance? Should I keep my old queue based pipeline?

答:
Although I have not tried this on a tf dataset, this should be applicable. I found this combination to be highly performant and simplistic:

```<code>import tensorflow as tf
import tensorflow_addons as tfa

dummy_dataset = tf.ones((1000, 224, 224, 3))
blurred_dummy_dataset = tf.map_fn(tfa.image.gaussian_filter2d, dummy_dataset)
# ~ 3 second runtime in Google Colab on a Tesla K80
</code>```

https://www.tensorflow.org/addons/api_docs/python/tfa/image/gaussian_filter2d
https://www.tensorflow.org/api_docs/python/tf/map_fn

Body:
I would like to change my old queue based pipeline to the new dataset API on tensorflow for reasons of performance. However, once my code changed, it runs in 8 hours instead of 2.

The use of my GPU was about 30/40% and it's now between 0 and 6%.

I found the line which making it so slow, and it's when I apply gaussian blur on my dataset :

def gaussian_blur(imgs,lbls):
   imgs = tf.nn.conv2d(imgs,k_conv,
                                   strides=[1, 1, 1, 1],
                                   padding='SAME',
                                   data_format='NHWC'
                                   )
   return imgs, lbls

ds = ds.map(gaussian_blur)

With my old queue-based pipeline, this line almost doesn't slow my program.

I think it's because this line used to run on the GPU but the new dataset API forces it to run on the CPU which is way slower and already 100% used.

Do you have any idea on how can I apply gaussian blur with out decreasing so much the performance? Should I keep my old queue based pipeline?

Body:
Although I have not tried this on a tf dataset, this should be applicable. I found this combination to be highly performant and simplistic:

import tensorflow as tf
import tensorflow_addons as tfa

dummy_dataset = tf.ones((1000, 224, 224, 3))
blurred_dummy_dataset = tf.map_fn(tfa.image.gaussian_filter2d, dummy_dataset)
# ~ 3 second runtime in Google Colab on a Tesla K80

https://www.tensorflow.org/addons/api_docs/python/tfa/image/gaussian_filter2d
https://www.tensorflow.org/api_docs/python/tf/map_fn


问:
Equivalent for FETCH FIRST WITH TIES in Postgres 11 with comparable performance
Given the following DDL

```<code>CREATE TABLE numbers (
    id     BIGSERIAL PRIMARY KEY,
    number BIGINT
);
CREATE INDEX ON numbers (number);
</code>```

In PostgreSQL 13 I can use the following query:

```<code>SELECT *
FROM numbers
WHERE number > 1
ORDER BY number
FETCH FIRST 1000 ROWS WITH TIES
</code>```

It produces a very effective query plan and performs well enough with large tables:

Limit  (cost=...)
  ->  Index Scan using numbers_number_idx on numbers  (cost=...)
        Index Cond: (number > 1)
```
<p>Is there an equivalent for that in PostgreSQL 11 that gives a similar query plan and comparable performance for large (10TB+) tables?</p>
<p>This answer suggests to use the following query:</p>
```WITH cte AS (
    SELECT *, RANK() OVER (ORDER BY number) AS rnk
    FROM numbers
    WHERE number > 1
)
SELECT *
FROM cte
WHERE rnk <= 1000;
```
<p>But it is not really usable for large tables because performance is many times worse.</p>
<pre class="lang-none prettyprint-override"><code>Subquery Scan on cte  (cost=...)
  Filter: (cte.rnk <= 1000)
  ->  WindowAgg  (cost=...)
        ->  Index Scan using numbers_number_idx on numbers  (cost=...)
              Index Cond: (number > 1)
</code>```

答:
I got pretty good results with the following select query. Not as fast as the other answer, but the query is also a lot simpler. the offset value has to be 1 less than the number of rows desired (999 for 1000) since offset starts at 0.

-- query 1
select *
from numbers
where number <= (
  select number
  from numbers
  where number > 1
  order by number
  offset 999 limit 1
  )
  and number > 1
```
<hr />
<h3>Performance</h3>
<p>test was run with the table as defined in the question, and the following insert statement.</p>
<pre class="lang-sql prettyprint-override"><code>INSERT INTO numbers (n)
SELECT floor(random() * 100000000)
FROM generate_series(1, 100000000);
</code>```

I'll admit its not very scientific, as this is done on my puny windows 10 laptop & running on a postgresql 13 cluster on wsl with all default settings on battery power. i didn't restart the server between runs or do anything to prevent optimization due to data present in cache.

Explain analyze results, where query 1 refers to the query above, query 2 refers to the simple query in question, query 3 refers to query in other answer and query 4 is the elegant with ties variant.

query
execution time
factor slower

1
80.642 ms
63.6

2
142142.026 ms
112011

3
59.551 ms
46.9

4
1.269 ms
1

Explain analyze query plans

```<code>-- query 1
 Gather  (cost=10965.26..1178206.10 rows=500000 width=16) (actual time=64.157..79.186 rows=1000 loops=1)
   Workers Planned: 2
   Params Evaluated: $0
   Workers Launched: 2
   InitPlan 1 (returns $0)
     ->  Limit  (cost=27.66..27.69 rows=1 width=8) (actual time=63.613..63.615 rows=1 loops=1)
           ->  Index Only Scan using numbers_n_idx on numbers numbers_1  (cost=0.57..2712066.05 rows=100000085 width=8) (actual time=0.029..0.318 rows=1000 loops=1)
                 Index Cond: (number > 1)
                 Heap Fetches: 0
   ->  Parallel Bitmap Heap Scan on numbers  (cost=9937.57..1127178.41 rows=208333 width=16) (actual time=0.090..0.498 rows=333 loops=3)
         Recheck Cond: ((number <= $0) AND (number > 1))
         Heap Blocks: exact=1000
         ->  Bitmap Index Scan on numbers_n_idx  (cost=0.00..9812.57 rows=500000 width=0) (actual time=0.135..0.135 rows=1000 loops=1)
               Index Cond: ((number <= $0) AND (number > 1))
 Planning Time: 0.230 ms
 JIT:
   Functions: 18
   Options: Inlining true, Optimization true, Expressions true, Deforming true
   Timing: Generation 1.936 ms, Inlining 44.863 ms, Optimization 12.045 ms, Emission 6.182 ms, Total 65.026 ms
 Execution Time: 80.642 ms
(20 rows)
</code>```
```<code>-- query 2
 Subquery Scan on cte  (cost=8472029.70..22868689.85 rows=33333362 width=24) (actual time=40001.966..142074.323 rows=1000 loops=1)
   Filter: (cte.rnk <= 1000)
   Rows Removed by Filter: 99998999
   ->  WindowAgg  (cost=8472029.70..21618688.79 rows=100000085 width=24) (actual time=40001.964..129209.141 rows=99999999 loops=1)
         ->  Gather Merge  (cost=8472029.70..20118687.52 rows=100000085 width=16) (actual time=40001.921..75176.460 rows=99999999 loops=1)
               Workers Planned: 2
               Workers Launched: 2
               ->  Sort  (cost=8471029.68..8575196.43 rows=41666702 width=16) (actual time=39707.316..46741.888 rows=33333333 loops=3)
                     Sort Key: numbers.number
                     Sort Method: external merge  Disk: 856888kB
                     Worker 0:  Sort Method: external merge  Disk: 839696kB
                     Worker 1:  Sort Method: external merge  Disk: 847688kB
                     ->  Parallel Seq Scan on numbers  (cost=0.00..1061374.79 rows=41666702 width=16) (actual time=60.334..13404.824 rows=33333333 loops=3)
                           Filter: (number > 1)
                           Rows Removed by Filter: 0
 Planning Time: 0.179 ms
 JIT:
   Functions: 16
   Options: Inlining true, Optimization true, Expressions true, Deforming true
   Timing: Generation 1.773 ms, Inlining 90.193 ms, Optimization 55.148 ms, Emission 34.709 ms, Total 181.823 ms
 Execution Time: 142142.026 ms
(21 rows)
</code>```
```<code>-- query 3
 Append  (cost=2497.62..2628.54 rows=1005 width=24) (actual time=12.881..59.360 rows=1000 loops=1)
   CTE cte
     ->  Limit  (cost=1004.33..2497.62 rows=1000 width=24) (actual time=12.877..58.683 rows=1000 loops=1)
           ->  WindowAgg  (cost=1004.33..149329948.33 rows=100000085 width=24) (actual time=12.875..58.435 rows=1000 loops=1)
                 ->  Gather Merge  (cost=1004.33..147579946.84 rows=100000085 width=16) (actual time=12.858..57.988 rows=1001 loops=1)
                       Workers Planned: 2
                       Workers Launched: 2
                       ->  Incremental Sort  (cost=4.31..136036455.76 rows=41666702 width=16) (actual time=0.147..29.746 rows=366 loops=3)
                             Sort Key: numbers.number, numbers.id
                             Presorted Key: numbers.number
                             Full-sort Groups: 13  Sort Method: quicksort  Average Memory: 26kB  Peak Memory: 26kB
                             Worker 0:  Full-sort Groups: 15  Sort Method: quicksort  Average Memory: 26kB  Peak Memory: 26kB
                             Worker 1:  Full-sort Groups: 8  Sort Method: quicksort  Average Memory: 26kB  Peak Memory: 26kB
                             ->  Parallel Index Scan using numbers_n_idx on numbers  (cost=0.57..134359882.50 rows=41666702 width=16) (actual time=0.042..29.576 rows=393 loops=3)
                                   Index Cond: (number > 1)
   ->  CTE Scan on cte  (cost=0.00..20.00 rows=1000 width=24) (actual time=12.880..14.618 rows=1000 loops=1)
   ->  WindowAgg  (cost=105.75..105.85 rows=5 width=24) (actual time=0.079..0.081 rows=0 loops=1)
         ->  Sort  (cost=105.75..105.76 rows=5 width=16) (actual time=0.077..0.079 rows=0 loops=1)
               Sort Key: n.id
               Sort Method: quicksort  Memory: 25kB
               ->  Nested Loop  (cost=0.57..105.69 rows=5 width=16) (actual time=0.070..0.071 rows=0 loops=1)
                     ->  CTE Scan on cte cte_1  (cost=0.00..22.50 rows=5 width=16) (actual time=0.051..0.051 rows=1 loops=1)
                           Filter: (rn = 1000)
                           Rows Removed by Filter: 999
                     ->  Index Scan using numbers_n_idx on numbers n  (cost=0.57..16.63 rows=1 width=16) (actual time=0.015..0.016 rows=0 loops=1)
                           Index Cond: (number = cte_1.number)
                           Filter: (id > cte_1.id)
                           Rows Removed by Filter: 1
 Planning Time: 0.202 ms
 Execution Time: 59.551 ms
(30 rows)
</code>```
```<code>-- query 4
Limit  (cost=0.57..1350.00 rows=1000 width=16) (actual time=0.013..1.113 rows=1000 loops=1)
   ->  Index Scan using numbers_n_idx on numbers  (cost=0.57..134943216.33 rows=100000085 width=16) (actual time=0.012..0.869 rows=1001 loops=1)
         Index Cond: (number > 1)
 Planning Time: 0.142 ms
 Execution Time: 1.269 ms
(5 rows)
</code>```

Body:
Given the following DDL

CREATE TABLE numbers (
    id     BIGSERIAL PRIMARY KEY,
    number BIGINT
);
CREATE INDEX ON numbers (number);

In PostgreSQL 13 I can use the following query:

SELECT *
FROM numbers
WHERE number > 1
ORDER BY number
FETCH FIRST 1000 ROWS WITH TIES

It produces a very effective query plan and performs well enough with large tables:

Limit  (cost=...)
  ->  Index Scan using numbers_number_idx on numbers  (cost=...)
        Index Cond: (number > 1)

Is there an equivalent for that in PostgreSQL 11 that gives a similar query plan and comparable performance for large (10TB+) tables?

This answer suggests to use the following query:

WITH cte AS (
    SELECT *, RANK() OVER (ORDER BY number) AS rnk
    FROM numbers
    WHERE number > 1
)
SELECT *
FROM cte
WHERE rnk <= 1000;

But it is not really usable for large tables because performance is many times worse.

Subquery Scan on cte  (cost=...)
  Filter: (cte.rnk <= 1000)
  ->  WindowAgg  (cost=...)
        ->  Index Scan using numbers_number_idx on numbers  (cost=...)
              Index Cond: (number > 1)

Body:
I got pretty good results with the following select query. Not as fast as the other answer, but the query is also a lot simpler. the offset value has to be 1 less than the number of rows desired (999 for 1000) since offset starts at 0.

-- query 1
select *
from numbers
where number <= (
  select number
  from numbers
  where number > 1
  order by number
  offset 999 limit 1
  )
  and number > 1

Performance

test was run with the table as defined in the question, and the following insert statement.

INSERT INTO numbers (n)
SELECT floor(random() * 100000000)
FROM generate_series(1, 100000000);

I'll admit its not very scientific, as this is done on my puny windows 10 laptop & running on a postgresql 13 cluster on wsl with all default settings on battery power. i didn't restart the server between runs or do anything to prevent optimization due to data present in cache.

Explain analyze results, where query 1 refers to the query above, query 2 refers to the simple query in question, query 3 refers to query in other answer and query 4 is the elegant with ties variant.

query
execution time
factor slower

1
80.642 ms
63.6

2
142142.026 ms
112011

3
59.551 ms
46.9

4
1.269 ms
1

Explain analyze query plans

-- query 1
 Gather  (cost=10965.26..1178206.10 rows=500000 width=16) (actual time=64.157..79.186 rows=1000 loops=1)
   Workers Planned: 2
   Params Evaluated: $0
   Workers Launched: 2
   InitPlan 1 (returns $0)
     ->  Limit  (cost=27.66..27.69 rows=1 width=8) (actual time=63.613..63.615 rows=1 loops=1)
           ->  Index Only Scan using numbers_n_idx on numbers numbers_1  (cost=0.57..2712066.05 rows=100000085 width=8) (actual time=0.029..0.318 rows=1000 loops=1)
                 Index Cond: (number > 1)
                 Heap Fetches: 0
   ->  Parallel Bitmap Heap Scan on numbers  (cost=9937.57..1127178.41 rows=208333 width=16) (actual time=0.090..0.498 rows=333 loops=3)
         Recheck Cond: ((number <= $0) AND (number > 1))
         Heap Blocks: exact=1000
         ->  Bitmap Index Scan on numbers_n_idx  (cost=0.00..9812.57 rows=500000 width=0) (actual time=0.135..0.135 rows=1000 loops=1)
               Index Cond: ((number <= $0) AND (number > 1))
 Planning Time: 0.230 ms
 JIT:
   Functions: 18
   Options: Inlining true, Optimization true, Expressions true, Deforming true
   Timing: Generation 1.936 ms, Inlining 44.863 ms, Optimization 12.045 ms, Emission 6.182 ms, Total 65.026 ms
 Execution Time: 80.642 ms
(20 rows)

-- query 2
 Subquery Scan on cte  (cost=8472029.70..22868689.85 rows=33333362 width=24) (actual time=40001.966..142074.323 rows=1000 loops=1)
   Filter: (cte.rnk <= 1000)
   Rows Removed by Filter: 99998999
   ->  WindowAgg  (cost=8472029.70..21618688.79 rows=100000085 width=24) (actual time=40001.964..129209.141 rows=99999999 loops=1)
         ->  Gather Merge  (cost=8472029.70..20118687.52 rows=100000085 width=16) (actual time=40001.921..75176.460 rows=99999999 loops=1)
               Workers Planned: 2
               Workers Launched: 2
               ->  Sort  (cost=8471029.68..8575196.43 rows=41666702 width=16) (actual time=39707.316..46741.888 rows=33333333 loops=3)
                     Sort Key: numbers.number
                     Sort Method: external merge  Disk: 856888kB
                     Worker 0:  Sort Method: external merge  Disk: 839696kB
                     Worker 1:  Sort Method: external merge  Disk: 847688kB
                     ->  Parallel Seq Scan on numbers  (cost=0.00..1061374.79 rows=41666702 width=16) (actual time=60.334..13404.824 rows=33333333 loops=3)
                           Filter: (number > 1)
                           Rows Removed by Filter: 0
 Planning Time: 0.179 ms
 JIT:
   Functions: 16
   Options: Inlining true, Optimization true, Expressions true, Deforming true
   Timing: Generation 1.773 ms, Inlining 90.193 ms, Optimization 55.148 ms, Emission 34.709 ms, Total 181.823 ms
 Execution Time: 142142.026 ms
(21 rows)

-- query 3
 Append  (cost=2497.62..2628.54 rows=1005 width=24) (actual time=12.881..59.360 rows=1000 loops=1)
   CTE cte
     ->  Limit  (cost=1004.33..2497.62 rows=1000 width=24) (actual time=12.877..58.683 rows=1000 loops=1)
           ->  WindowAgg  (cost=1004.33..149329948.33 rows=100000085 width=24) (actual time=12.875..58.435 rows=1000 loops=1)
                 ->  Gather Merge  (cost=1004.33..147579946.84 rows=100000085 width=16) (actual time=12.858..57.988 rows=1001 loops=1)
                       Workers Planned: 2
                       Workers Launched: 2
                       ->  Incremental Sort  (cost=4.31..136036455.76 rows=41666702 width=16) (actual time=0.147..29.746 rows=366 loops=3)
                             Sort Key: numbers.number, numbers.id
                             Presorted Key: numbers.number
                             Full-sort Groups: 13  Sort Method: quicksort  Average Memory: 26kB  Peak Memory: 26kB
                             Worker 0:  Full-sort Groups: 15  Sort Method: quicksort  Average Memory: 26kB  Peak Memory: 26kB
                             Worker 1:  Full-sort Groups: 8  Sort Method: quicksort  Average Memory: 26kB  Peak Memory: 26kB
                             ->  Parallel Index Scan using numbers_n_idx on numbers  (cost=0.57..134359882.50 rows=41666702 width=16) (actual time=0.042..29.576 rows=393 loops=3)
                                   Index Cond: (number > 1)
   ->  CTE Scan on cte  (cost=0.00..20.00 rows=1000 width=24) (actual time=12.880..14.618 rows=1000 loops=1)
   ->  WindowAgg  (cost=105.75..105.85 rows=5 width=24) (actual time=0.079..0.081 rows=0 loops=1)
         ->  Sort  (cost=105.75..105.76 rows=5 width=16) (actual time=0.077..0.079 rows=0 loops=1)
               Sort Key: n.id
               Sort Method: quicksort  Memory: 25kB
               ->  Nested Loop  (cost=0.57..105.69 rows=5 width=16) (actual time=0.070..0.071 rows=0 loops=1)
                     ->  CTE Scan on cte cte_1  (cost=0.00..22.50 rows=5 width=16) (actual time=0.051..0.051 rows=1 loops=1)
                           Filter: (rn = 1000)
                           Rows Removed by Filter: 999
                     ->  Index Scan using numbers_n_idx on numbers n  (cost=0.57..16.63 rows=1 width=16) (actual time=0.015..0.016 rows=0 loops=1)
                           Index Cond: (number = cte_1.number)
                           Filter: (id > cte_1.id)
                           Rows Removed by Filter: 1
 Planning Time: 0.202 ms
 Execution Time: 59.551 ms
(30 rows)

-- query 4
Limit  (cost=0.57..1350.00 rows=1000 width=16) (actual time=0.013..1.113 rows=1000 loops=1)
   ->  Index Scan using numbers_n_idx on numbers  (cost=0.57..134943216.33 rows=100000085 width=16) (actual time=0.012..0.869 rows=1001 loops=1)
         Index Cond: (number > 1)
 Planning Time: 0.142 ms
 Execution Time: 1.269 ms
(5 rows)


问:
Flutter - Keyboard not showing up in android 12 devices
Keyboard is not showing up for android 12 devices, overlay comes indicating keyboard is on but nothing is shown. It is working properly for older android versions.

Keyboard is working fine in other apps & also works fine with simulator having android version other than Android 12. Tried with physical device also Pixel with android 12 facing the same issue.

flutter doctor code -

```<code>flutter doctor -v
[✓] Flutter (Channel stable, 2.2.3, on macOS 11.4 20F71 darwin-x64, locale en-IN)
    • Flutter version 2.2.3 at /Users/uable/Downloads/flutter
    • Framework revision f4abaa0735 (4 months ago), 2021-07-01 12:46:11 -0700
    • Engine revision 241c87ad80
    • Dart version 2.13.4

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    • Android SDK at /Users/uable/Library/Android/sdk
    • Platform android-31, build-tools 31.0.0
    • ANDROID_HOME = /Users/uable/Library/Android/sdk
    • ANDROID_SDK_ROOT = /Users/uable/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
    • All Android licenses accepted.

[!] Xcode - develop for iOS and macOS
    ✗ Xcode installation is incomplete; a full installation is necessary for iOS development.
      Download at: https://developer.apple.com/xcode/download/
      Or install Xcode via the App Store.
      Once installed, run:
        sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
        sudo xcodebuild -runFirstLaunch
    • CocoaPods version 1.10.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)

[✓] Connected device (2 available)
    • sdk gphone64 x86 64 (mobile) • emulator-5554 • android-x64    • Android 12 (API 31) (emulator)
    • Chrome (web)                 • chrome        • web-javascript • Google Chrome 95.0.4638.54

! Doctor found issues in 1 category.
</code>```

Below is an image of simple text field with keyboard on have tried changing all properties of text field also. Its an existing application so tried testing the existing textfields even in those its showing the same behaviour.

android gradle settings

```<code>    minSdkVersion 24
    targetSdkVersion 30
</code>```

答:
as official document of webview flutter
put

```<code>if (Platform.isAndroid) WebView.platform = AndroidWebView();
</code>```

in your Main.dart

enter image description here

Body:
Keyboard is not showing up for android 12 devices, overlay comes indicating keyboard is on but nothing is shown. It is working properly for older android versions.

Keyboard is working fine in other apps & also works fine with simulator having android version other than Android 12. Tried with physical device also Pixel with android 12 facing the same issue.

flutter doctor code -

flutter doctor -v
[✓] Flutter (Channel stable, 2.2.3, on macOS 11.4 20F71 darwin-x64, locale en-IN)
    • Flutter version 2.2.3 at /Users/uable/Downloads/flutter
    • Framework revision f4abaa0735 (4 months ago), 2021-07-01 12:46:11 -0700
    • Engine revision 241c87ad80
    • Dart version 2.13.4

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0)
    • Android SDK at /Users/uable/Library/Android/sdk
    • Platform android-31, build-tools 31.0.0
    • ANDROID_HOME = /Users/uable/Library/Android/sdk
    • ANDROID_SDK_ROOT = /Users/uable/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)
    • All Android licenses accepted.

[!] Xcode - develop for iOS and macOS
    ✗ Xcode installation is incomplete; a full installation is necessary for iOS development.
      Download at: https://developer.apple.com/xcode/download/
      Or install Xcode via the App Store.
      Once installed, run:
        sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer
        sudo xcodebuild -runFirstLaunch
    • CocoaPods version 1.10.2

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
       https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
       https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 1.8.0_242-release-1644-b3-6222593)

[✓] Connected device (2 available)
    • sdk gphone64 x86 64 (mobile) • emulator-5554 • android-x64    • Android 12 (API 31) (emulator)
    • Chrome (web)                 • chrome        • web-javascript • Google Chrome 95.0.4638.54

! Doctor found issues in 1 category.

Below is an image of simple text field with keyboard on have tried changing all properties of text field also. Its an existing application so tried testing the existing textfields even in those its showing the same behaviour.

android gradle settings

    minSdkVersion 24
    targetSdkVersion 30

Body:
as official document of webview flutter
put

if (Platform.isAndroid) WebView.platform = AndroidWebView();

in your Main.dart

enter image description here


问:
Protect API Routes with Sanctum
Is there any way to secure (access from outside the application) an api route using Sanctum without needing to email and password.</p>

答:
You can use API tokens. You still need at least one user assigned, then you can assign a token and only send the token in the HttpRequest.

https://laravel.com/docs/8.x/sanctum#api-token-authentication

Title: Protect API Routes with Sanctum


问:
Filtering a Wave
I am trying to write a function filter_wave(wave,1) and this will produce a new wave which is a smoothed version of the input wave. Following the rules below:

In the new wave, for every position i, it is the weighted sum of three positions of the original wave. Specifically, the new wave value in position i will be equal to

```<code>new_wave[i] = wave[i-1] * 0.2 + wave[i]*0.6 + wave[i+1]*0.2
</code>```

some of the conditions:

Let len(wave) be L. The above method will access wave[-1] and wave[L] which do NOT exist in the original wave. So, you can deem the values of wave[-1] and wave[L] as 0.

All the numbers in the new wave will be integers.

I have written the following code but not sure what are the issues exactly since the program keeps returning 0

```<code>def filter_wave(wave,times):
    new_wave = []
    for i in range(len(wave)):
        if wave[i-1] < wave[0]:
            return 0
        if wave[i+1] > len(wave):
            return 0
    new_wave = wave[i-1] * 0.2 + wave[i]*0.6 + wave[i+1]*0.2
    new_wave.insert(i,int(new_wave))
    return new_wave
</code>```

答:
I wonder if this will work.

def filter_wave(wave, times):
    L = len(wave)
    new_wave = []

    for i in range(times):
        for j in range(L):
            if j == 0:                        #wave[-1] = 0
                new_wave[j] = int(wave[j] * 0.6 + wave[j + 1] * 0.2)
            elif j == L - 1:                  #wave[L] = 0
                new_wave[j] = int(wave[j - 1] * 0.2 + wave[j] * 0.6)
            else:
                new_wave[j] = int(wave[j - 1] * 0.2 + wave[j] * 0.6 + wave[j + 1] * 0.2)

    return new_wave
```

Title: Filtering a Wave

Body:
I am trying to write a function filter_wave(wave,1) and this will produce a new wave which is a smoothed version of the input wave. Following the rules below:

In the new wave, for every position i, it is the weighted sum of three positions of the original wave. Specifically, the new wave value in position i will be equal to

new_wave[i] = wave[i-1] * 0.2 + wave[i]*0.6 + wave[i+1]*0.2

some of the conditions:

Let len(wave) be L. The above method will access wave[-1] and wave[L] which do NOT exist in the original wave. So, you can deem the values of wave[-1] and wave[L] as 0.

All the numbers in the new wave will be integers.

I have written the following code but not sure what are the issues exactly since the program keeps returning 0

def filter_wave(wave,times):
    new_wave = []
    for i in range(len(wave)):
        if wave[i-1] < wave[0]:
            return 0
        if wave[i+1] > len(wave):
            return 0
    new_wave = wave[i-1] * 0.2 + wave[i]*0.6 + wave[i+1]*0.2
    new_wave.insert(i,int(new_wave))
    return new_wave


问:
How to handle a price change in DB just when a customer is placing an order online?
I have a Product database table with columns such as product_id, price, and inventory_count.

A user clicks to buy a certain product at a certain price. My program generates a confirmation page listing the product and the price. Everything is fine and the user clicks "Confirm". My program updates the inventory_count of that product and charges the user's credit card the amount listed in the product's price.

But during the time after the confirmation page is generated but before the user clicks "Confirm", the price of that product has been changed. So the user might have seen a price of $10 in the confirmation page but after he clicks "Confirm" the price in the Product table has already been changed to $11 and that's what he will be charged.

What's the best way to handle a situation like this? I'm using  MySQL and Python if that's relevant.

答:
You definitely should carry over the price from the time the customer last had the chance to change his mind. I'm sure that's also a legal issue in which you'd not look so good.

Anyway, can't be to hard to implement one last check after the customer has confirmed, right? Maybe you then could show a notice that the price has changed.


答:
It rather looks like you want to merge the data. As your intervals are disjoint, this is a perfect use case for merge_asof.

First ensure to have datetime type and that the data is sorted on the merging dates:

```<code>df1['date_start'] = pd.to_datetime(df1['date_start'])
df1['date_expiry'] = pd.to_datetime(df1['date_expiry'])
df2['transaction_datetime'] = pd.to_datetime(df2['transaction_datetime'])

df1 = df1.sort_values(by='date_start')
df2 = df2.sort_values(by='transaction_datetime')
</code>```

Then perform the merge:

```<code>df3 = (
 pd.merge_asof(df2, df1, by='code',
               left_on='transaction_datetime',
               right_on='date_start',
               )
   .sort_values(by='code')
   .drop(['date_start', 'date_expiry'], axis=1)
 )
</code>```

Output:

```<code>   code transaction_datetime  amount tier
0     1  2020-01-02 13:45:05      20    A
1     1  2020-06-22 12:34:41     230    C
3     2  2020-11-12 15:47:35      50    C
2     3  2020-09-03 18:20:34      10    B
</code>```

Title: pandas merge two dataframe by key + datetime and an interval

Body:
I need to sort transaction records by time interval and the data is from two data files but I have no idea how can do this. There has some example and my expected output.

tier_history_data:

code,date_start,date_expiry,tier
1,"2020-01-01 15:15:15","2020-12-31 15:15:15",A
1,"2020-05-23 08:24:57","2021-05-22 08:24:57",C
2,"2020-03-01 10:47:15","2021-02-27 10:47:15",B
2,"2020-09-17 23:14:23","2021-09-16 23:14:23",C
3,"2020-05-01 20:26:19","2021-04-30 20:26:19",C
3,"2020-08-31 12:46:02","2021-08-30 12:46:02",B

transaction_data:

code,transaction_datetime,amount
1,"2020-01-02 13:45:05",20
1,"2020-06-22 12:34:41",230
2,"2020-11-12 15:47:35",50
3,"2020-09-03 18:20:34",10

expected output:

code,tramsaction_datetime,amount,tier
1,"2020-01-02 13:45:05",20,A
1,"2020-06-22 12:34:41",230,C
2,"2020-11-12 15:47:35",50,C
3,"2020-09-03 18:20:34",10,B

Thanks in advance

Body:
It rather looks like you want to merge the data. As your intervals are disjoint, this is a perfect use case for merge_asof.

First ensure to have datetime type and that the data is sorted on the merging dates:

df1['date_start'] = pd.to_datetime(df1['date_start'])
df1['date_expiry'] = pd.to_datetime(df1['date_expiry'])
df2['transaction_datetime'] = pd.to_datetime(df2['transaction_datetime'])

df1 = df1.sort_values(by='date_start')
df2 = df2.sort_values(by='transaction_datetime')

Then perform the merge:

df3 = (
 pd.merge_asof(df2, df1, by='code',
               left_on='transaction_datetime',
               right_on='date_start',
               )
   .sort_values(by='code')
   .drop(['date_start', 'date_expiry'], axis=1)
 )

Output:

   code transaction_datetime  amount tier
0     1  2020-01-02 13:45:05      20    A
1     1  2020-06-22 12:34:41     230    C
3     2  2020-11-12 15:47:35      50    C
2     3  2020-09-03 18:20:34      10    B


问:
React-native : Unable to use react-native-fast-image
My apps app/build gradle:

```<code>android:compileSdkVersion 23,  buildToolsVersion '26'
</code>```

android/build gradle:

```<code>subprojects { subproject ->
    afterEvaluate{
        if((subproject.plugins.hasPlugin('android') || subproject.plugins.hasPlugin('android-library'))) {
            android {
                compileSdkVersion 25
                buildToolsVersion "25.0.1"
            }
        }
    }
}
</code>```

package json dependencies:

"react-native-fast-image": "^1.0.0",
   "react": "16.0.0-alpha.12",
  "react-native": "0.45.1",

I have installed react-native-fast-image, and linked with react-native.
Then while running on android , I am getting this error:

```<code>:react-native-fast-image:compileReleaseJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
D:\React Practice\MyProject\MyProject\node_modules\react-native-fast-image\android\src\main\java\com\dylanvann\fastimage\FastImageViewPackage.java:14: error: FastImageViewPackage is not abstract and does not override abstract method createJSModules() in ReactPackage
public class FastImageViewPackage implements ReactPackage {
       ^
Note: D:\React Practice\MyProject\MyProject\node_modules\react-native-fast-image\android\src\main\java\com\dylanvann\fastimage\FastImageViewManager.java uses unchecked or un
safe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
:react-native-fast-image:compileReleaseJavaWithJavac FAILED
</code>```

答:
you can update JDK 11.0.11

brew install --cask adoptopenjdk/openjdk/adoptopenjdk11

choco install -y nodejs-lts openjdk11

Body:
My apps app/build gradle:

android:compileSdkVersion 23,  buildToolsVersion '26'

android/build gradle:

subprojects { subproject ->
    afterEvaluate{
        if((subproject.plugins.hasPlugin('android') || subproject.plugins.hasPlugin('android-library'))) {
            android {
                compileSdkVersion 25
                buildToolsVersion "25.0.1"
            }
        }
    }
}

package json dependencies:

"react-native-fast-image": "^1.0.0",
   "react": "16.0.0-alpha.12",
  "react-native": "0.45.1",

I have installed react-native-fast-image, and linked with react-native.
Then while running on android , I am getting this error:

:react-native-fast-image:compileReleaseJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
D:\React Practice\MyProject\MyProject\node_modules\react-native-fast-image\android\src\main\java\com\dylanvann\fastimage\FastImageViewPackage.java:14: error: FastImageViewPackage is not abstract and does not override abstract method createJSModules() in ReactPackage
public class FastImageViewPackage implements ReactPackage {
       ^
Note: D:\React Practice\MyProject\MyProject\node_modules\react-native-fast-image\android\src\main\java\com\dylanvann\fastimage\FastImageViewManager.java uses unchecked or un
safe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
:react-native-fast-image:compileReleaseJavaWithJavac FAILED


问:
How to use my company's PPT slide layouts while creating a PPT using python-pptx?
If I write and execute this code

```<code>from pptx import Presentation
prs = Presentation()
slide_layout = prs.slide_layouts[0]
prs.save("Final.pptx")
</code>```

It creates a PPT with just one slide, which is an unedited standard title slide.

But in MS Powerpoint I can see many layouts of my company. And I want to use their layout. Please tell me how to do it.

答:
Documentation ref

To use a “template” for a presentation you simply create a presentation with all the styles, logo, and layouts you want, delete all the slides (or leave some in if it suits), and then load that as your starting place.

```<code>from pptx import Presentation
prs = Presentation('custom-lay.pptx')
</code>```

Body:
If I write and execute this code

from pptx import Presentation
prs = Presentation()
slide_layout = prs.slide_layouts[0]
prs.save("Final.pptx")

It creates a PPT with just one slide, which is an unedited standard title slide.

But in MS Powerpoint I can see many layouts of my company. And I want to use their layout. Please tell me how to do it.

Body:
Documentation ref

To use a “template” for a presentation you simply create a presentation with all the styles, logo, and layouts you want, delete all the slides (or leave some in if it suits), and then load that as your starting place.

from pptx import Presentation
prs = Presentation('custom-lay.pptx')


问:
Getting py4j.protocol.Py4JJavaError: An error occurred while calling o65.jdbc. : java.sql.SQLException: Unsupported type TIMESTAMP_WITH_TIMEZONE
I am making JDBC connection to Denodo database using pyspark. The table that i am connecting to contains "TIMESTAMP_WITH_TIMEZONE" datatype for 2 columns. Since spark provides builtin jdbc connection to a handful of dbs only of which denodo is not a part, it is not able to recognize "TIMESTAMP_WITH_TIMEZONE" datatype and hence not able to map to any of its spark sql dataype.
To overcome this i am providing my custom schema(c_schema here) but this is not working as well and i am getting the same error. Below is the code snippet.

```<code>c_schema="game start date TIMESTAMP,game end date TIMESTAMP"

df = spark.read.jdbc("jdbc_url", "schema.table_name",properties={"user": "user_name", "password": "password","customSchema":c_schema,"driver": "com.denodo.vdp.jdbc.Driver"})
</code>```

Please let me know how shall i fix this.

答:
For anyone else facing this issue while connecting to denodo using spark,use CAST function to convert the datatype "TIMESTAMP_WITH_TIMEZONE" into any other datatype like String,Date or Timestamp etc. I had posted this question on denodo community page too and i have attached its official response.

```<code>CAST("PLANNED START DATE" as DATE) as "PLANNED_START_DATE"
</code>```

Body:
I am making JDBC connection to Denodo database using pyspark. The table that i am connecting to contains "TIMESTAMP_WITH_TIMEZONE" datatype for 2 columns. Since spark provides builtin jdbc connection to a handful of dbs only of which denodo is not a part, it is not able to recognize "TIMESTAMP_WITH_TIMEZONE" datatype and hence not able to map to any of its spark sql dataype.
To overcome this i am providing my custom schema(c_schema here) but this is not working as well and i am getting the same error. Below is the code snippet.

c_schema="game start date TIMESTAMP,game end date TIMESTAMP"

df = spark.read.jdbc("jdbc_url", "schema.table_name",properties={"user": "user_name", "password": "password","customSchema":c_schema,"driver": "com.denodo.vdp.jdbc.Driver"})

Please let me know how shall i fix this.

Body:
For anyone else facing this issue while connecting to denodo using spark,use CAST function to convert the datatype "TIMESTAMP_WITH_TIMEZONE" into any other datatype like String,Date or Timestamp etc. I had posted this question on denodo community page too and i have attached its official response.

CAST("PLANNED START DATE" as DATE) as "PLANNED_START_DATE"


问:
Azure Data Factory (V2) Copy Activity - advanced editor missing
Background, Trying to copy data from SQLDB to Blob parquet file. This is being prevented due to a complex column type (geography). I would like to convert this to string data type.

There seems to be a way to do this by checking the "Map complex values to string" box and if that doesn't work use the advanced editor.

Such as seen here:

however, this does not exist in my Azure data factory:

ideas:

These features need to be turned on?

but I can't find any documentation on how...

They are available in v1 but not yet in v2

I will have to use different method (e.g. dataflow.. powerquery) to copy or different sink dataset type (it works fine with csv but I was hoping to keep the schema.

Your ideas or general thought would be appreciated.

答:
I would suggest looking into the official MS docs Data type mapping

Also, I don't see the Data Type geography under currently supported ones.

I would suggest you try Data flow for same, using derived column and dynamic expression to set string data type.


问:
JavaScript files that are concatenated fail
I have been looking at combining my JavaScript files into one file, to gain some performance. Mostly it worked like a charm, but not for the jquery.templates, knockout.js and knockout.mapping.js libraries.

I have tried something as simple as manually copy/pasting the content of the three files into one file. As soon as I reference that new file instead of the three original files it fails - with undefined is not a function, but the error is not as important as why there is any difference at all.

Any idea why this happens?

答:
Probably there is no line break at the start or the end of the files, which can lead to problems when they are concatenated.

Also, it can be that the order of the files must be correct. For example when file 1 contains function "Test" and file 2 uses this function.


问:
Why the local variable problem happens in python
I got this error

```<code>increment = lambda x : x + 1

def make_repeater(h, n):
    def f(x):
        value = x
        while n > 0 :
            value = h(value)
            n = n - 1

        return value
    return f

    a = make_repeater(increment,5)
    b = a(1)
</code>```

UnboundLocalError: local variable 'n' referenced before assignment

while when I write like this , it runs well

```<code>increment = lambda x : x + 1

def make_repeater(h, n):
    def f(x):
        i = n
        value = x
        while i > 0 :
            value = h(value)
            i = i - 1

        return value
    return f

    a = make_repeater(increment, 5)
    b = a(1)
</code>```

答: In python, if a variable in a function has the same name as a global variable, when changing the value of that variable, it will become a local variable. So the reference before the assignment problem will happen.</p>

Body:
I got this error

increment = lambda x : x + 1

def make_repeater(h, n):
    def f(x):
        value = x
        while n > 0 :
            value = h(value)
            n = n - 1

        return value
    return f

    a = make_repeater(increment,5)
    b = a(1)

UnboundLocalError: local variable 'n' referenced before assignment

while when I write like this , it runs well

increment = lambda x : x + 1

def make_repeater(h, n):
    def f(x):
        i = n
        value = x
        while i > 0 :
            value = h(value)
            i = i - 1

        return value
    return f

    a = make_repeater(increment, 5)
    b = a(1)


问:
Can I define my html body class as .body in css?
CSS

```<code>.body {
    background: linear-gradient(-45deg, rgb(255, 0, 0), rgba(216, 29, 29, 0.856), #fdfdfdd7, #234cd5, #ffffff);
  background-size: 400% 400%;
  background-repeat:no-repeat;
    animation: gradient 35s ease infinite;
    height: 100vh;
}
</code>```

HTML

```<code><!DOCTYPE html>
<html>
<link rel="stylesheet" href="style.css">
<script src="nui://game/ui/jquery.js" type="text/javascript"></script>
<script src="./listener.js" type="text/javascript"></script>
<body class="body">
<div id="container">
      <title>Police 10 Codes</title>
      <h1>LSPD Ten Codes</h1>
      <img src="https://i.ibb.co/2vNZgd9/lspd-removebg-preview.png" alt="LSPD Image"style="width:150px;height:150px;">
      <div class="dropdown">
        <button class="dropbtn">Non-Serious</button>
        <div class="dropdown-content">
          <a href="#">10-1 Unable to Copy / Weak Signal</a>
          <a href="#">10-3 Stop Transmitting</a>
          <a href="#">10-4 Affirmative / Understood</a>
          <a href="#">10-7 Out of Service</a>
          <a href="#">10-8 In Service</a>
          <a href="#">10-12 Stand by</a>
          <a href="#">10-17 En-route to Scene</a>
          <a href="#">10-19 Return to Station/Location</a>
          <a href="#">10-20 Location</a>
          <a href="#">10-22 Disregard</a>
          <a href="#">10-23 Arrived at Scene</a>
          <a href="#">10-24 Assignment Complete</a>
          <a href="#">10-30 Traffic Stop</a>
          <a href="#">10-36 Correct Time</a>
          <a href="#">10-37 Suspicious Vehicle</a>
          <a href="#">10-40 Run Silent No Lights/Siren</a>
          <a href="#">10-53 Road Blocked</a>
          <a href="#">10-56 Intoxicated Pedestrian</a>
          <a href="#">10-58 Direct Traffic</a>
          <a href="#">10-59 Convoy / Escort</a>
          <a href="#">10-60 In the Area</a>
          <a href="#">10-61 Clear for Radio Traffic</a>
          <a href="#">10-74 Negative</a>
          <a href="#">10-77 ETA</a>
          <a href="#">10-68 Dispatch Information</a>
          <a href="#">10-92 Improper parking</a>
        </div>
      </div>
      <div class="dropdown2">
        <button class="dropbtn2">Medium</button>
        <div class="dropdown2-content">
          <a href="#">10-0 Use Caution</a>
          <a href="#">10-10 Fight in Progress</a>
          <a href="#">10-25 Report in person</a>
          <a href="#">10-26 Detaining/Arresting Subject</a>
          <a href="#">10-29 Warrant Check</a>
          <a href="#">10-31 Crime in progress</a>
          <a href="#">10-50 Traffic Crash</a>
          <a href="#">10-55 DUI</a>
          <a href="#">10-57 Hit & Run</a>
          <a href="#">10-78 Requesting backup</a>
          <a href="#">10-80 Fire Alarm</a>
          <a href="#">10-94 Street Racing</a>
          <a href="#">10-96 Mental Patient</a>
        </div>
      </div>
      <div class="dropdown3">
        <button class="dropbtn3">Serious</button>
        <div class="dropdown3-content">
          <a href="#">10-18 Urgent</a>
          <a href="#">10-32 Person with Gun</a>
          <a href="#">10-39 Run with Lights/Siren</a>
          <a href="#">10-67 Report of Death</a>
          <a href="#">10-80 Pursuit in Progress</a>
          <a href="#">10-82 Fire in Progress</a>
          <a href="#">10-89 Bomb Threat</a>
          <a href="#">10-90 Bank Alarm</a>
        </div>
      </div>
    </div>
  </div>
</div>
</body>
</html>
</code>```

When I view this, the size of the .body class crops and adjusts. I have a #container id class added where I'm trying to have the full UI open/close. Currently the UI does it's job, only issue I'm having is the size of the .body class keeps adjusting. Would like the size to stay at what its currently set at, 400% 400% or just fit for full screen view. Any help is appreciated, thank you.

答:
It's because your html is invalid. All HTML elements must be children of the body but you have
 as the body's parent. Kindly move it inside the body.

Try this code

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>LSPD Ten Codes</title>
    <link rel="stylesheet" href="style.css">

      <title>Police 10 Codes</title>

LSPD Ten Codes

        <button class="dropbtn">Non-Serious</button>

          10-1 Unable to Copy / Weak Signal
          10-3 Stop Transmitting
          10-4 Affirmative / Understood
          10-7 Out of Service
          10-8 In Service
          10-12 Stand by
          10-17 En-route to Scene
          10-19 Return to Station/Location
          10-20 Location
          10-22 Disregard
          10-23 Arrived at Scene
          10-24 Assignment Complete
          10-30 Traffic Stop
          10-36 Correct Time
          10-37 Suspicious Vehicle
          10-40 Run Silent No Lights/Siren
          10-53 Road Blocked
          10-56 Intoxicated Pedestrian
          10-58 Direct Traffic
          10-59 Convoy / Escort
          10-60 In the Area
          10-61 Clear for Radio Traffic
          10-74 Negative
          10-77 ETA
          10-68 Dispatch Information
          10-92 Improper parking

        <button class="dropbtn2">Medium</button>

          10-0 Use Caution
          10-10 Fight in Progress
          10-25 Report in person
          10-26 Detaining/Arresting Subject
          10-29 Warrant Check
          10-31 Crime in progress
          10-50 Traffic Crash
          10-55 DUI
          10-57 Hit & Run
          10-78 Requesting backup
          10-80 Fire Alarm
          10-94 Street Racing
          10-96 Mental Patient

        <button class="dropbtn3">Serious</button>

          10-18 Urgent
          10-32 Person with Gun
          10-39 Run with Lights/Siren
          10-67 Report of Death
          10-80 Pursuit in Progress
          10-82 Fire in Progress
          10-89 Bomb Threat
          10-90 Bank Alarm

```

Body:
CSS

.body {
    background: linear-gradient(-45deg, rgb(255, 0, 0), rgba(216, 29, 29, 0.856), #fdfdfdd7, #234cd5, #ffffff);
  background-size: 400% 400%;
  background-repeat:no-repeat;
    animation: gradient 35s ease infinite;
    height: 100vh;
}

HTML

<!DOCTYPE html>

<link rel="stylesheet" href="style.css">

      <title>Police 10 Codes</title>

LSPD Ten Codes

        <button class="dropbtn">Non-Serious</button>

          10-1 Unable to Copy / Weak Signal
          10-3 Stop Transmitting
          10-4 Affirmative / Understood
          10-7 Out of Service
          10-8 In Service
          10-12 Stand by
          10-17 En-route to Scene
          10-19 Return to Station/Location
          10-20 Location
          10-22 Disregard
          10-23 Arrived at Scene
          10-24 Assignment Complete
          10-30 Traffic Stop
          10-36 Correct Time
          10-37 Suspicious Vehicle
          10-40 Run Silent No Lights/Siren
          10-53 Road Blocked
          10-56 Intoxicated Pedestrian
          10-58 Direct Traffic
          10-59 Convoy / Escort
          10-60 In the Area
          10-61 Clear for Radio Traffic
          10-74 Negative
          10-77 ETA
          10-68 Dispatch Information
          10-92 Improper parking

        <button class="dropbtn2">Medium</button>

          10-0 Use Caution
          10-10 Fight in Progress
          10-25 Report in person
          10-26 Detaining/Arresting Subject
          10-29 Warrant Check
          10-31 Crime in progress
          10-50 Traffic Crash
          10-55 DUI
          10-57 Hit & Run
          10-78 Requesting backup
          10-80 Fire Alarm
          10-94 Street Racing
          10-96 Mental Patient

        <button class="dropbtn3">Serious</button>

          10-18 Urgent
          10-32 Person with Gun
          10-39 Run with Lights/Siren
          10-67 Report of Death
          10-80 Pursuit in Progress
          10-82 Fire in Progress
          10-89 Bomb Threat
          10-90 Bank Alarm

When I view this, the size of the .body class crops and adjusts. I have a #container id class added where I'm trying to have the full UI open/close. Currently the UI does it's job, only issue I'm having is the size of the .body class keeps adjusting. Would like the size to stay at what its currently set at, 400% 400% or just fit for full screen view. Any help is appreciated, thank you.

Body:
It's because your html is invalid. All HTML elements must be children of the body but you have <div id="container"> as the body's parent. Kindly move it inside the body.

Try this code

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>LSPD Ten Codes</title>
    <link rel="stylesheet" href="style.css">
    <script src="nui://game/ui/jquery.js" type="text/javascript"></script>
    <script src="./listener.js" type="text/javascript"></script>
    <style type="text/css">
        .body {
            background: linear-gradient(-45deg, rgb(255, 0, 0), rgba(216, 29, 29, 0.856), #fdfdfdd7, #234cd5, #ffffff);
            background-size: 400% 400%;
            background-repeat:no-repeat;
            animation: gradient 35s ease infinite;
            height: 100vh;
        }
    </style>
</head>
<body class="body">
    <div id="container">
      <title>Police 10 Codes</title>
      <h1>LSPD Ten Codes</h1>
      <img src="https://i.ibb.co/2vNZgd9/lspd-removebg-preview.png" alt="LSPD Image"style="width:150px;height:150px;">
      <div class="dropdown">
        <button class="dropbtn">Non-Serious</button>
        <div class="dropdown-content">
          <a href="#">10-1 Unable to Copy / Weak Signal</a>
          <a href="#">10-3 Stop Transmitting</a>
          <a href="#">10-4 Affirmative / Understood</a>
          <a href="#">10-7 Out of Service</a>
          <a href="#">10-8 In Service</a>
          <a href="#">10-12 Stand by</a>
          <a href="#">10-17 En-route to Scene</a>
          <a href="#">10-19 Return to Station/Location</a>
          <a href="#">10-20 Location</a>
          <a href="#">10-22 Disregard</a>
          <a href="#">10-23 Arrived at Scene</a>
          <a href="#">10-24 Assignment Complete</a>
          <a href="#">10-30 Traffic Stop</a>
          <a href="#">10-36 Correct Time</a>
          <a href="#">10-37 Suspicious Vehicle</a>
          <a href="#">10-40 Run Silent No Lights/Siren</a>
          <a href="#">10-53 Road Blocked</a>
          <a href="#">10-56 Intoxicated Pedestrian</a>
          <a href="#">10-58 Direct Traffic</a>
          <a href="#">10-59 Convoy / Escort</a>
          <a href="#">10-60 In the Area</a>
          <a href="#">10-61 Clear for Radio Traffic</a>
          <a href="#">10-74 Negative</a>
          <a href="#">10-77 ETA</a>
          <a href="#">10-68 Dispatch Information</a>
          <a href="#">10-92 Improper parking</a>
        </div>
      </div>
      <div class="dropdown2">
        <button class="dropbtn2">Medium</button>
        <div class="dropdown2-content">
          <a href="#">10-0 Use Caution</a>
          <a href="#">10-10 Fight in Progress</a>
          <a href="#">10-25 Report in person</a>
          <a href="#">10-26 Detaining/Arresting Subject</a>
          <a href="#">10-29 Warrant Check</a>
          <a href="#">10-31 Crime in progress</a>
          <a href="#">10-50 Traffic Crash</a>
          <a href="#">10-55 DUI</a>
          <a href="#">10-57 Hit & Run</a>
          <a href="#">10-78 Requesting backup</a>
          <a href="#">10-80 Fire Alarm</a>
          <a href="#">10-94 Street Racing</a>
          <a href="#">10-96 Mental Patient</a>
        </div>
      </div>
      <div class="dropdown3">
        <button class="dropbtn3">Serious</button>
        <div class="dropdown3-content">
          <a href="#">10-18 Urgent</a>
          <a href="#">10-32 Person with Gun</a>
          <a href="#">10-39 Run with Lights/Siren</a>
          <a href="#">10-67 Report of Death</a>
          <a href="#">10-80 Pursuit in Progress</a>
          <a href="#">10-82 Fire in Progress</a>
          <a href="#">10-89 Bomb Threat</a>
          <a href="#">10-90 Bank Alarm</a>
        </div>
      </div>
    </div>
</body>
</html>


问:
Are there any constantly updating RSS feed services to use for testing, or just very active RSS feeds?
I'm trying to test a service that consumes RSS feeds and turns them into push notifications, and it would be nice if there was a very regularly updated publicly available RSS feed I could point it at.

I know I can just use a news feed like CNN, but I'm wondering if there's something more "Lorem Ipsum" style for RSS.

答:
Busy subreddits are the best option if you figure out how to get their RSS feed.
For example, here is one of them:
https://www.reddit.com/r/AskReddit/new/.rss

For more information: https://www.reddit.com/wiki/rss


问:
How do I use the For loop in Firebird?
Can someone explain to me the syntax of the For loop in Firebird?

Here is the code I have so far:

```<code>As
Declare variable Var1 integer;
begin
Insert into table1
-- Select query to insert some enteries in table 1 - Done successfully.
FOR SELECT table1.Column1 from table1 into :Var1
Do
Begin
Update tableabc.column1 = (select tablexyz. column1 from tablexyz where tablexyz.ID = :Var1) where tableabc.ID = :Var1
End
</code>```

Update : Thanks for giving it a try but i dont see any major difference between the query that i wrote and query included in answers. Although above query runs successfully at my end but when i see data in table there occurs no update.

Actually i was making a v.dumb mistake, i was executing alter stored procedure query - which runs successfully and i was assuming this would make the necessary changes. later i executed the stored procedure and it worked pefectly . Thanks all for sparing your time :) ..

答:
For operator in Firebird is not like For, say, in Pascal where it increments loop variable and executes a block of code until finish value will be met.

In Firebird For operator takes a set of records (result of execution of a query) and loops through them. For every record a block of code will be executed. Optionally values of some fields from the record could be put into local variables enlisted in INTO section. Values of such variables could be used inside a block of code.

In your example a query:

```<code>SELECT table1.Column1 from table1 into :Var1
</code>```

Will be executed and for every record in result set will be executed operator:

```<code>Update tableabc.column1 =
  (select tablexyz. column1 from tablexyz where tablexyz.ID = :Var1)
where tableabc.ID = :Var1
</code>```

For it variable :Var will contain value of table1.Column1 of current record.

Title: How do I use the For loop in Firebird?

Body:
Can someone explain to me the syntax of the For loop in Firebird?

Here is the code I have so far:

As
Declare variable Var1 integer;
begin
Insert into table1
-- Select query to insert some enteries in table 1 - Done successfully.
FOR SELECT table1.Column1 from table1 into :Var1
Do
Begin
Update tableabc.column1 = (select tablexyz. column1 from tablexyz where tablexyz.ID = :Var1) where tableabc.ID = :Var1
End

Update : Thanks for giving it a try but i dont see any major difference between the query that i wrote and query included in answers. Although above query runs successfully at my end but when i see data in table there occurs no update.

Actually i was making a v.dumb mistake, i was executing alter stored procedure query - which runs successfully and i was assuming this would make the necessary changes. later i executed the stored procedure and it worked pefectly . Thanks all for sparing your time :) ..

Body:
For operator in Firebird is not like For, say, in Pascal where it increments loop variable and executes a block of code until finish value will be met.

In Firebird For operator takes a set of records (result of execution of a query) and loops through them. For every record a block of code will be executed. Optionally values of some fields from the record could be put into local variables enlisted in INTO section. Values of such variables could be used inside a block of code.

In your example a query:

SELECT table1.Column1 from table1 into :Var1

Will be executed and for every record in result set will be executed operator:

Update tableabc.column1 =
  (select tablexyz. column1 from tablexyz where tablexyz.ID = :Var1)
where tableabc.ID = :Var1

For it variable :Var will contain value of table1.Column1 of current record.


问:
tabBarOptions not applied to project (React Native)
I am creating a small app that has a to-do list and a calendar. At the bottom is a bottom tab navigator. Everything works and is functional, however, when I try to add style: {} inside tabBarOptions it isn't being applied. Changing activeTintColor, inactiveTintColor and labelStyle works just fine.

I tried to create a stylesheet and replace everything inside tabBarOptions, but that didn't work. My main goal is to simply create a slightly larger bar along the bottom of the screen. I don't even want a crazy custom navigation bar, just slightly larger so I can make the items inside a little bigger.

MainContainer Class:

```<code>import React from 'react';
import {StyleSheet} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons'

//screens
import Calendar from './screens/Calendar';
import ToDoList from './screens/ToDoList';

// Screen names
const calendarName = 'Calendar';
const ToDoListName = 'To Do List';

const Tab = createBottomTabNavigator();

export default function MainContainer() {
    return (
        <NavigationContainer>
            <Tab.Navigator
                tabBarOptions={{
                    activeTintColor: 'tomato',
                    inactiveTintColor: 'black',
                    labelStyle: {paddingBottom: 10, fontSize: 10},
                    style: {padding: 10, height: 70},
                }}
                initialRouteName={ToDoListName}
                           screenOptions={({route}) => ({
                               tabBarIcon: ({focused, color, size}) => {
                                   let iconName;
                                   let rn = route.name;

                                   if (rn === ToDoListName) {
                                       iconName = focused ? 'list' : 'list-outline'; //icons in package. Change later.
                                   } else if (rn === calendarName) {
                                       iconName = focused ? 'calendar' : 'calendar-outline'
                                   }
                                   return <Ionicons name={iconName} size={size} color={color}/>
                               },
                           })}>

                <Tab.Screen name={ToDoListName} component={ToDoList}/>
                <Tab.Screen name={calendarName} component={Calendar}/>

            </Tab.Navigator>
        </NavigationContainer>
    )
}

</code>```

For reference here is my ToDoList class

```<code>import { KeyboardAvoidingView, StyleSheet, Text, View, TextInput, TouchableOpacity, Platform, Keyboard } from 'react-native';
import Task from '../../components/Task';
import React, { useState } from 'react';
import { ScrollView } from 'react-native-web';

export default function ToDoList() {
    const [task, setTask] = useState();
    const [taskItems, setTaskItems] = useState([]);

    const handleAddTask = () => {
        Keyboard.dismiss();
        setTaskItems([...taskItems, task])
        setTask(null);
    }

    const completeTask = (index) => {
        let itemsCopy = [...taskItems];
        itemsCopy.splice(index, 1);
        setTaskItems(itemsCopy)
    }

    return (
        <View style={styles.container}>
            {/* Scroll View when list gets longer than page */}
            <ScrollView contentContainerStyle={{
                flexGrow: 1
            }} keyboardShouldPersistTaps='handled'>

                {/*Today's Tasks */}
                <View style={styles.tasksWrapper}>
                    <Text style={styles.sectionTitle}>Today's Tasks</Text>
                    <View style={styles.items}>
                        {/* This is where the tasks will go*/}
                        {
                            taskItems.map((item, index) => {
                                return (
                                    <TouchableOpacity key={index} onPress={() => completeTask(index)}>
                                        <Task text={item} />
                                    </TouchableOpacity>
                                )
                            })
                        }
                    </View>
                </View>

            </ScrollView>

            {/* Write a task section */}
            {/* Uses a keyboard avoiding view which ensures the keyboard does not cover the items on screen */}
            <KeyboardAvoidingView
                behavior={Platform.OS === "ios" ? "padding" : "height"}
                style={styles.writeTaskWrapper}>
                <TextInput style={styles.input} placeholder={'Write a task'} value={task} onChangeText={text => setTask(text)} />
                <TouchableOpacity onPress={() => handleAddTask()}>
                    <View style={styles.addWrapper}>
                        <Text style={styles.addText}>+</Text>
                    </View>
                </TouchableOpacity>
            </KeyboardAvoidingView>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#E8EAED',
    },
    tasksWrapper: {
        paddingTop: 20,
        paddingHorizontal: 20,
    },
    sectionTitle: {
        fontSize: 24,
        fontWeight: 'bold',
    },
    items: {
        marginTop: 30,
    },
    writeTaskWrapper: {
        position: 'absolute',
        bottom: 20,
        paddingLeft: 10,
        paddingRight: 10,
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center'
    },
    input: {
        paddingVertical: 15,
        width: 250,
        paddingHorizontal: 15,
        backgroundColor: '#FFF',
        borderRadius: 60,
        borderColor: '#C0C0C0',
        borderWidth: 1,
    },
    addWrapper: {
        width: 60,
        height: 60,
        backgroundColor: '#FFF',
        borderRadius: 60,
        justifyContent: 'center',
        alignItems: 'center',
        borderColor: '#C0C0C0',
        borderWidth: 1,
    },
    addText: {

    },

});

</code>```

And my Calendar class

```<code>import * as React from 'react';
import { View, Text } from 'react-native';
export default function Calendar(){

    return(
        <View>
            <Text>Calendar Will go here</Text>
        </View>
    )

}
</code>```

I made a Task component for the ToDoList. Not sure if you need it to solve this but I'll paste it here anyway.

```<code>import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { TouchableOpacity } from 'react-native-web';

const Task = (props) => {
    return (
        <View style={styles.item}>
            <View style={styles.itemLeft}>
                <View style={styles.square}></View>
                <Text style={styles.itemText}>{props.text}</Text>
            </View>
            <View style={styles.circular}></View>
        </View>
    )
}

const styles = StyleSheet.create({
    item: {
        backgroundColor: '#FFF',
        padding: 15,
        borderRadius: 10,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginBottom: 20,

    },
    itemLeft: {
        flexDirection: 'row',
        alignItems: 'center',
        flexWrap: 'wrap',
    },
    square: {
        width: 24,
        height: 24,
        backgroundColor: '#55BCF6',
        opacity: .4,
        borderRadius: 5,
        marginRight: 15,
    },
    itemText: {
        maxWidth: '80%',

    },
    circular: {
        width: 12,
        height: 12,
        borderColor: '#55BCF6',
        borderWidth: 2,
        borderRadius: 5
    },
});

export default Task;
</code>```

答:
It sounds like you are looking for the tabBarStyle property. You should be able to rename style (which is not a supported prop of the tab navigator) to tabBarStyle.

Here's the spot in the docs that mentions this. https://reactnavigation.org/docs/bottom-tab-navigator#tabbarstyle

Body:
I am creating a small app that has a to-do list and a calendar. At the bottom is a bottom tab navigator. Everything works and is functional, however, when I try to add style: {} inside tabBarOptions it isn't being applied. Changing activeTintColor, inactiveTintColor and labelStyle works just fine.

I tried to create a stylesheet and replace everything inside tabBarOptions, but that didn't work. My main goal is to simply create a slightly larger bar along the bottom of the screen. I don't even want a crazy custom navigation bar, just slightly larger so I can make the items inside a little bigger.

MainContainer Class:

import React from 'react';
import {StyleSheet} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons'

//screens
import Calendar from './screens/Calendar';
import ToDoList from './screens/ToDoList';

// Screen names
const calendarName = 'Calendar';
const ToDoListName = 'To Do List';

const Tab = createBottomTabNavigator();

export default function MainContainer() {
    return (
        <NavigationContainer>
            <Tab.Navigator
                tabBarOptions={{
                    activeTintColor: 'tomato',
                    inactiveTintColor: 'black',
                    labelStyle: {paddingBottom: 10, fontSize: 10},
                    style: {padding: 10, height: 70},
                }}
                initialRouteName={ToDoListName}
                           screenOptions={({route}) => ({
                               tabBarIcon: ({focused, color, size}) => {
                                   let iconName;
                                   let rn = route.name;

                                   if (rn === ToDoListName) {
                                       iconName = focused ? 'list' : 'list-outline'; //icons in package. Change later.
                                   } else if (rn === calendarName) {
                                       iconName = focused ? 'calendar' : 'calendar-outline'
                                   }
                                   return <Ionicons name={iconName} size={size} color={color}/>
                               },
                           })}>

                <Tab.Screen name={ToDoListName} component={ToDoList}/>
                <Tab.Screen name={calendarName} component={Calendar}/>

            </Tab.Navigator>
        </NavigationContainer>
    )
}

For reference here is my ToDoList class

import { KeyboardAvoidingView, StyleSheet, Text, View, TextInput, TouchableOpacity, Platform, Keyboard } from 'react-native';
import Task from '../../components/Task';
import React, { useState } from 'react';
import { ScrollView } from 'react-native-web';

export default function ToDoList() {
    const [task, setTask] = useState();
    const [taskItems, setTaskItems] = useState([]);

    const handleAddTask = () => {
        Keyboard.dismiss();
        setTaskItems([...taskItems, task])
        setTask(null);
    }

    const completeTask = (index) => {
        let itemsCopy = [...taskItems];
        itemsCopy.splice(index, 1);
        setTaskItems(itemsCopy)
    }

    return (
        <View style={styles.container}>
            {/* Scroll View when list gets longer than page */}
            <ScrollView contentContainerStyle={{
                flexGrow: 1
            }} keyboardShouldPersistTaps='handled'>

                {/*Today's Tasks */}
                <View style={styles.tasksWrapper}>
                    <Text style={styles.sectionTitle}>Today's Tasks</Text>
                    <View style={styles.items}>
                        {/* This is where the tasks will go*/}
                        {
                            taskItems.map((item, index) => {
                                return (
                                    <TouchableOpacity key={index} onPress={() => completeTask(index)}>
                                        <Task text={item} />
                                    </TouchableOpacity>
                                )
                            })
                        }
                    </View>
                </View>

            </ScrollView>

            {/* Write a task section */}
            {/* Uses a keyboard avoiding view which ensures the keyboard does not cover the items on screen */}
            <KeyboardAvoidingView
                behavior={Platform.OS === "ios" ? "padding" : "height"}
                style={styles.writeTaskWrapper}>
                <TextInput style={styles.input} placeholder={'Write a task'} value={task} onChangeText={text => setTask(text)} />
                <TouchableOpacity onPress={() => handleAddTask()}>
                    <View style={styles.addWrapper}>
                        <Text style={styles.addText}>+</Text>
                    </View>
                </TouchableOpacity>
            </KeyboardAvoidingView>
        </View>
    );
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#E8EAED',
    },
    tasksWrapper: {
        paddingTop: 20,
        paddingHorizontal: 20,
    },
    sectionTitle: {
        fontSize: 24,
        fontWeight: 'bold',
    },
    items: {
        marginTop: 30,
    },
    writeTaskWrapper: {
        position: 'absolute',
        bottom: 20,
        paddingLeft: 10,
        paddingRight: 10,
        width: '100%',
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center'
    },
    input: {
        paddingVertical: 15,
        width: 250,
        paddingHorizontal: 15,
        backgroundColor: '#FFF',
        borderRadius: 60,
        borderColor: '#C0C0C0',
        borderWidth: 1,
    },
    addWrapper: {
        width: 60,
        height: 60,
        backgroundColor: '#FFF',
        borderRadius: 60,
        justifyContent: 'center',
        alignItems: 'center',
        borderColor: '#C0C0C0',
        borderWidth: 1,
    },
    addText: {

    },

});

And my Calendar class

import * as React from 'react';
import { View, Text } from 'react-native';
export default function Calendar(){

    return(
        <View>
            <Text>Calendar Will go here</Text>
        </View>
    )

}

I made a Task component for the ToDoList. Not sure if you need it to solve this but I'll paste it here anyway.

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { TouchableOpacity } from 'react-native-web';

const Task = (props) => {
    return (
        <View style={styles.item}>
            <View style={styles.itemLeft}>
                <View style={styles.square}></View>
                <Text style={styles.itemText}>{props.text}</Text>
            </View>
            <View style={styles.circular}></View>
        </View>
    )
}

const styles = StyleSheet.create({
    item: {
        backgroundColor: '#FFF',
        padding: 15,
        borderRadius: 10,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        marginBottom: 20,

    },
    itemLeft: {
        flexDirection: 'row',
        alignItems: 'center',
        flexWrap: 'wrap',
    },
    square: {
        width: 24,
        height: 24,
        backgroundColor: '#55BCF6',
        opacity: .4,
        borderRadius: 5,
        marginRight: 15,
    },
    itemText: {
        maxWidth: '80%',

    },
    circular: {
        width: 12,
        height: 12,
        borderColor: '#55BCF6',
        borderWidth: 2,
        borderRadius: 5
    },
});

export default Task;


答:
 cannot be outside of . Body tag needs to come first, then the Div, All HTML elements should be inside . Try setting body height like -

```<code>HTML,
body {
    height: 100%;
}
</code>```

OR -

```<code>html {
  height: 100%;
}
body {
  min-height: 100%;
}
</code>```

Orignal answer at stackoverflow - Make body have 100% of the browser height

Title: Can I define my html body class as .body in css?

Body:
<div> cannot be outside of <body>. Body tag needs to come first, then the Div, All HTML elements should be inside <body>. Try setting body height like -

HTML,
body {
    height: 100%;
}

OR -

html {
  height: 100%;
}
body {
  min-height: 100%;
}

Orignal answer at stackoverflow - Make body have 100% of the browser height


问:
Why do the contents in a Bootstrap grid float left? Is there a way to get the contents in a Bootstrap grid to be in the center?
I have tried using text-align: center;, but this does not change the text inside of the Bootstrap grid. Is the float-left the default setting or is there a way I can change it? My code looks something like this:

```<code>    <div style="margin-top: 10px; margin-bottom: 20px; margin-right: 20%; margin-left: 20%; text-align: center; font-family: 'Share Tech Mono', monospace; background-color: white;   border-radius: 50px;">
        <h1 style="padding-top: 10px;">Code Example</h1>
        <br>
        <br>
        <div class="row">
            <div class="col-sm-4 "><a style="color: black;">Column 1</a></div>
            <div class="col-sm-4"><a style="color: black;">Column 2</a></div>
            <div class="col-sm-4"><a style="color: black;">Column 3</a></div>
        <div style="height: 50px;"></div>

        </div>
    </div>

</code>```

答: I just found out that padding-left can be used. Not sure if this is the best solution, but it is something at least.

Body:
I have tried using text-align: center;, but this does not change the text inside of the Bootstrap grid. Is the float-left the default setting or is there a way I can change it? My code looks something like this:

Code Example

Column 1

Column 2

Column 3


问:
Flutter. How to disable "Double tap to activate, double tap and hold to long press" hint in accessibility mode
Currently, I'm working with Accessibility in Flutter and on android devices it's pronouncing this hint: "double tap to activate, double tap and hold to long press".
As far as I know this hint pronounced if widget is clickable, so I tried wrapping child of this widget with BlockSemantics (didn't work), also wrapped this clickable widget with Semantics and set property button: false but that also didn't help.
This how my widget looks.

```<code>  return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () => widget.onItemSelect(),
        onLongPress: () => widget.onItemLongPress(),
        child: childWidget,
       );
</code>```

How can I disable this?

答: GestureDetector has a excludeSemantics property, so I set it to true. It will NOT block child widget's semantics, it will just disable semantics for GestureDetector widget itself, and as a result Android accessibility hint also turn off

Body:
Currently, I'm working with Accessibility in Flutter and on android devices it's pronouncing this hint: "double tap to activate, double tap and hold to long press".
As far as I know this hint pronounced if widget is clickable, so I tried wrapping child of this widget with BlockSemantics (didn't work), also wrapped this clickable widget with Semantics and set property button: false but that also didn't help.
This how my widget looks.

  return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () => widget.onItemSelect(),
        onLongPress: () => widget.onItemLongPress(),
        child: childWidget,
       );

How can I disable this?