问:
Python JSON serialize a Decimal object
I have a Decimal('3.9') as part of an object, and wish to encode this to a JSON string which should look like {'x': 3.9}. I don't care about precision on the client side, so a float is fine.

Is there a good way to serialize this? JSONDecoder doesn't accept Decimal objects, and converting to a float beforehand yields {'x': 3.8999999999999999} which is wrong, and will be a big waste of bandwidth.

答:
For Django users:

Recently came across TypeError: Decimal('2337.00') is not JSON serializable
while JSON encoding i.e. json.dumps(data)

Solution:

```<code># converts Decimal, Datetime, UUIDs to str for Encoding
from django.core.serializers.json import DjangoJSONEncoder

json.dumps(response.data, cls=DjangoJSONEncoder)
</code>```

But, now the Decimal value will be a string, now we can explicitly set the decimal/float value parser when decoding data, using parse_float option in json.loads:

```<code>import decimal

data = json.loads(data, parse_float=decimal.Decimal) # default is float(num_str)
</code>```

Title: Python JSON serialize a Decimal object

Body:
For Django users:

Recently came across TypeError: Decimal('2337.00') is not JSON serializable
while JSON encoding i.e. json.dumps(data)

Solution:

# converts Decimal, Datetime, UUIDs to str for Encoding
from django.core.serializers.json import DjangoJSONEncoder

json.dumps(response.data, cls=DjangoJSONEncoder)

But, now the Decimal value will be a string, now we can explicitly set the decimal/float value parser when decoding data, using parse_float option in json.loads:

import decimal

data = json.loads(data, parse_float=decimal.Decimal) # default is float(num_str)


来源: stackexchange

问:
Trying to Select the sum of cells that are round number amounts
I am trying to SUM a column only IF the cell is a round number. Doesn't matter what the number is.

I am unsure of what wildcard to put and if I need to put it into parenthesis or not.

```<code>SELECT
SUM(CASE WHEN(TXN_AMOUNT_BASE = '%0.00'
        THEN TXN_AMOUNT_BASE ELSE 0 END))AS
       Round_Dollar_Wires
  FROM IDP_PRD_INTERFACE.AML_L3_HPT_GRP.V_TRANSACTIONS
  GROUP BY ACCOUNT_SOURCE_REF_ID
 LIMIT 100;
</code>```

I am looking to get the sum of every transaction that is a round dollar amount. (So sum every transaction that looks like $1000.00, $100.00, $50.00, $ $1500.00. But not $1555.00, $50.45, or $125.)

答:
I resolved the issue as follows: </p>

```<code> select
 CUSTOMER_SOURCE_UNIQUE_ID
 ,ACCOUNT_SOURCE_REF_ID
 ,CASE WHEN TXN_AMOUNT_BASE LIKE '%00.00' THEN 1 ELSE NULL END as Round_Dollar
from IDP_PRD_INTERFACE.AML_L3_HPT_GRP.V_TRANSACTIONS
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to SUM a column only IF the cell is a round number. Doesn't matter what the number is.

I am unsure of what wildcard to put and if I need to put it into parenthesis or not.

SELECT
SUM(CASE WHEN(TXN_AMOUNT_BASE = '%0.00'
        THEN TXN_AMOUNT_BASE ELSE 0 END))AS
       Round_Dollar_Wires
  FROM IDP_PRD_INTERFACE.AML_L3_HPT_GRP.V_TRANSACTIONS
  GROUP BY ACCOUNT_SOURCE_REF_ID
 LIMIT 100;

I am looking to get the sum of every transaction that is a round dollar amount. (So sum every transaction that looks like $1000.00, $100.00, $50.00, $ $1500.00. But not $1555.00, $50.45, or $125.)

Body:
I resolved the issue as follows:

 select
 CUSTOMER_SOURCE_UNIQUE_ID
 ,ACCOUNT_SOURCE_REF_ID
 ,CASE WHEN TXN_AMOUNT_BASE LIKE '%00.00' THEN 1 ELSE NULL END as Round_Dollar
from IDP_PRD_INTERFACE.AML_L3_HPT_GRP.V_TRANSACTIONS


问:
How to get Google Sheets bound code.js to read and act on JavaScript from an uncontained remote .js file?
I have a Google Sheets on a GSuite Drive that I own. This Google Sheets has a bound code.js script file. I also have a remote .js file that contains the function I want to execute on my sheet (in a normal situation this function would simply reside within the code.js file).

I have created button images on the sheet that trigger scripts inside the code.js file. When I click a button my code.js script executes successfully:

the button triggers the code.js script which fetches the remote js file via URL and stores it into a variable (this remote file could just as easily be a text file but to keep my OCD in check I named it .js)

I use console.log(variable) to confirm that indeed the entire.js file has been retrieved.

I use eval(variable) but nothing happens

If I paste the console.log(variable) output directly into the code.js file, it works as expected.

Is eval() the wrong call? Or is it not as powerful as I am hoping?

```<code>function countStuffButton() { //Counts the number of current stuffs
    var url = "http://my.website/js/countStuff.js";
    var javascript = UrlFetchApp.fetch(url).getContentText();
    console.log(javascript);
    eval(javascript);
}
</code>```

console.log that I get back:

```<code>function countStuff() {
    // bunch of code that works when paste directly into code.js
}
</code>```

What I am hoping/expecting is that I can store a JavaScript function on a server in a .js file and then fetch the content of the function to be processed locally within the code.js bound script of my Google Sheets, resulting in a Google Sheets that is a pure "front end" making script and HTML calls to files that I fully own and control on my server.

答:
The eval(code) function you know it executes JavaScript code from a string.

However code needs to be a string that contains the JavaScript expression to be evaluated or the statements to be executed.

In your case the variable javascript contains the countStuff function declaration.

Function declarations are statements as they perform the action of creating a variable whose value is that of the function.

To fix that you can:

Change your remote countStuff function to become an immediately-invoked Function Expression :

```<code>function countStuff() {
//bunch of code that works when paste directly into code.js
}()
</code>```

Invoke the function yourself eval('new ' + javascript + '()')

To understand this second scenario and why new is needed have a look at this answer.

countStuff becomes available so you can also call it after eval()'s execution like countStuff()

Body:
I have a Google Sheets on a GSuite Drive that I own. This Google Sheets has a bound code.js script file. I also have a remote .js file that contains the function I want to execute on my sheet (in a normal situation this function would simply reside within the code.js file).

I have created button images on the sheet that trigger scripts inside the code.js file. When I click a button my code.js script executes successfully:

the button triggers the code.js script which fetches the remote js file via URL and stores it into a variable (this remote file could just as easily be a text file but to keep my OCD in check I named it .js)

I use console.log(variable) to confirm that indeed the entire.js file has been retrieved.

I use eval(variable) but nothing happens

If I paste the console.log(variable) output directly into the code.js file, it works as expected.

Is eval() the wrong call? Or is it not as powerful as I am hoping?

function countStuffButton() { //Counts the number of current stuffs
    var url = "http://my.website/js/countStuff.js";
    var javascript = UrlFetchApp.fetch(url).getContentText();
    console.log(javascript);
    eval(javascript);
}

console.log that I get back:

function countStuff() {
    // bunch of code that works when paste directly into code.js
}

What I am hoping/expecting is that I can store a JavaScript function on a server in a .js file and then fetch the content of the function to be processed locally within the code.js bound script of my Google Sheets, resulting in a Google Sheets that is a pure "front end" making script and HTML calls to files that I fully own and control on my server.

Body:
The eval(code) function you know it executes JavaScript code from a string.

However code needs to be a string that contains the JavaScript expression to be evaluated or the statements to be executed.

In your case the variable javascript contains the countStuff function declaration.

Function declarations are statements as they perform the action of creating a variable whose value is that of the function.

To fix that you can:

Change your remote countStuff function to become an immediately-invoked Function Expression :

function countStuff() {
//bunch of code that works when paste directly into code.js
}()

Invoke the function yourself eval('new ' + javascript + '()')

To understand this second scenario and why new is needed have a look at this answer.

countStuff becomes available so you can also call it after eval()'s execution like countStuff()


问:
How to move image in VrPanoramaView dynamically
I am using following image in VrPanoramaView

When i load it in the view, it looks like this.

But i want it to move the image to left side dynamically before opening the image, like this.

I can move the image with finger, but i want it to set its angle at the loading time.

This is my code.

```<code>VrPanoramaView.Options options = new VrPanoramaView.Options();
InputStream inputStream = null;
AssetManager assetManager = getAssets();

inputStream = assetManager.open("test_2"+ ".jpg");
options.inputType = VrPanoramaView.Options.TYPE_MONO;

mVrPanoramaView.loadImageFromBitmap(BitmapFactory.decodeStream(inputStream), options);

mVrPanoramaView.setStereoModeButtonEnabled(false);
mVrPanoramaView.setInfoButtonEnabled(false);
mVrPanoramaView.setPureTouchTracking(true);
mVrPanoramaView.setFullscreenButtonEnabled(true);
</code>```

I tried mVrPanoramaView.setPivotX(100);, but it does not make any impact. I need to know how to translate image in panorama view with using any hand gesture.

I am using GoogleVrSDK

```<code>implementation 'com.google.vr:sdk-base:1.160.0'
implementation 'com.google.vr:sdk-panowidget:1.170.0'
</code>```

答:
I think, you should switch to Video360:

There are more signs this component is not under development any more.

Set initial angle of VrPanoramaView

There are no plans to add more functionality to the VrView widgets.
  But you more complex controls for a 360 media player, consider using
  the Video360 sample as a starting point. See #510 for more info.

VR View for Android

Warning: These components were removed in v1.190 of the GVR SDK for
  Android. The Video360 sample should be used as a basis for creating
  360 photo and video viewers. If you still want to use these widgets,
  you will need to use SDK v1.180 or earlier.

Body:
I am using following image in VrPanoramaView

When i load it in the view, it looks like this.

But i want it to move the image to left side dynamically before opening the image, like this.

I can move the image with finger, but i want it to set its angle at the loading time.

This is my code.

VrPanoramaView.Options options = new VrPanoramaView.Options();
InputStream inputStream = null;
AssetManager assetManager = getAssets();

inputStream = assetManager.open("test_2"+ ".jpg");
options.inputType = VrPanoramaView.Options.TYPE_MONO;

mVrPanoramaView.loadImageFromBitmap(BitmapFactory.decodeStream(inputStream), options);

mVrPanoramaView.setStereoModeButtonEnabled(false);
mVrPanoramaView.setInfoButtonEnabled(false);
mVrPanoramaView.setPureTouchTracking(true);
mVrPanoramaView.setFullscreenButtonEnabled(true);

I tried mVrPanoramaView.setPivotX(100);, but it does not make any impact. I need to know how to translate image in panorama view with using any hand gesture.

I am using GoogleVrSDK

implementation 'com.google.vr:sdk-base:1.160.0'
implementation 'com.google.vr:sdk-panowidget:1.170.0'


问:
PyQt5 error "PyCapsule_GetPointer called with incorrect name"
I've just built PyQt5 in a pyenv virtualenv with python 3.6.3 on OpenSUSE leap, the build went fine, but when I import

```<code>>>> from PyQt5 import QtCore
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: PyCapsule_GetPointer called with incorrect name
</code>```

I can import PyQt5, but then I cannot use the modules under it

```<code>>>> import PyQt5
>>> PyQt5.QtCore
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'PyQt5' has no attribute 'QtCore'
</code>```

I've read here that the cause could be another sip on the system for example of a PyQt4 installation, I tried to uninstall PyQt4 from the package manager but it didn't help.

I have no idea what to do, any ideas?

If I install the python3-qt5 package and use the system python it works

Edit:

I had the same problem with PyQt4 on another machine on OpenSUSE Leap 15, the solution was to configure sip with:

```<code>python configure.py --sip-module PyQt4.sip --no-dist-info --no-tools
</code>```

as stated in the PyQt4 doc

答: I downgraded the PyQt5 to 5.7.1 and it worked for me.</p>

Body:
I've just built PyQt5 in a pyenv virtualenv with python 3.6.3 on OpenSUSE leap, the build went fine, but when I import

>>> from PyQt5 import QtCore
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: PyCapsule_GetPointer called with incorrect name

I can import PyQt5, but then I cannot use the modules under it

>>> import PyQt5
>>> PyQt5.QtCore
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'PyQt5' has no attribute 'QtCore'

I've read here that the cause could be another sip on the system for example of a PyQt4 installation, I tried to uninstall PyQt4 from the package manager but it didn't help.

I have no idea what to do, any ideas?

If I install the python3-qt5 package and use the system python it works

Edit:

I had the same problem with PyQt4 on another machine on OpenSUSE Leap 15, the solution was to configure sip with:

python configure.py --sip-module PyQt4.sip --no-dist-info --no-tools

as stated in the PyQt4 doc


问:
How to expose an external IP address for a sample Istio application
I am trying to set up the bookinfo sample application for Istio and Kubernetes on a small cluster.
The cluster consists of two machines, a master and a worker, running on Ubuntu 18.04 on two Amazon AWS EC2 instances.
Each of the instances has an external IP address assigned.

What I'm unable to do is figure out how to expose the bookinfo service to the outside world.

I am confused as to whether I need to expose the Istio ingress gateway or each one of the bookinfo services separately.

When listing the ingress gateway, the external IP field just says pending.
Also, when describing the worker node, there's no mention of an external IP address in the output.

I've gone through google but can't really find a proper solution.
Describing the ingress gateway only gives internal (i.e. 10.x.x.x) addresses.

Output from get and describe commands:

```<code>kubectl get svc istio-ingressgateway -n istio-system
NAME                   TYPE           CLUSTER-IP   EXTERNAL-IP   PORT(S)                                                                                AGE
istio-ingressgateway   LoadBalancer   10.96.39.4   <pending>     15020:31451/TCP,80:31380/TCP,443:31390/TCP,31400:31400/TCP,15029:31075/TCP,15030:32093/TCP,15031:31560/TCP,15032:30526/TCP,15443:31526/TCP   68m

kubectl describe  svc istio-ingressgateway  -n istio-system
Name:                     istio-ingressgateway
Namespace:                istio-system
Labels:                   app=istio-ingressgateway
                          chart=gateways
                          heritage=Tiller
                          istio=ingressgateway
                          release=istio
Annotations:              kubectl.kubernetes.io/last-applied-configuration:
                            {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"labels":{"app":"istio-ingressgateway","chart":"gateways","heritage":"Til...
Selector:                 app=istio-ingressgateway,istio=ingressgateway,release=istio
Type:                     LoadBalancer
IP:                       10.96.39.4
Port:                     status-port  15020/TCP
TargetPort:               15020/TCP
NodePort:                 status-port  31451/TCP
Endpoints:                10.244.1.6:15020
Port:                     http2  80/TCP
TargetPort:               80/TCP
NodePort:                 http2  31380/TCP
Endpoints:                10.244.1.6:80
Port:                     https  443/TCP
TargetPort:               443/TCP
NodePort:                 https  31390/TCP
Endpoints:                10.244.1.6:443
Port:                     tcp  31400/TCP
TargetPort:               31400/TCP
NodePort:                 tcp  31400/TCP
Endpoints:                10.244.1.6:31400
Port:                     https-kiali  15029/TCP
TargetPort:               15029/TCP
NodePort:                 https-kiali  31075/TCP
Endpoints:                10.244.1.6:15029
Port:                     https-prometheus  15030/TCP
TargetPort:               15030/TCP
NodePort:                 https-prometheus  32093/TCP
Endpoints:                10.244.1.6:15030
Port:                     https-grafana  15031/TCP
TargetPort:               15031/TCP
NodePort:                 https-grafana  31560/TCP
Endpoints:                10.244.1.6:15031
Port:                     https-tracing  15032/TCP
TargetPort:               15032/TCP
NodePort:                 https-tracing  30526/TCP
Endpoints:                10.244.1.6:15032
Port:                     tls  15443/TCP
TargetPort:               15443/TCP
NodePort:                 tls  31526/TCP
Endpoints:                10.244.1.6:15443
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>
</code>```

Any help appreciated.

答:
Quoting Istio's official documentation:

If your cluster is running in an environment that does not support an
  external load balancer (e.g., minikube), the EXTERNAL-IP of
  istio-ingressgateway will say -pending-. To access the gateway, use
  the service’s NodePort, or use port-forwarding instead.

Your cluster seems to fall into 'Custom (cloud)' way of setting up Kubernetes, which by default does not support Load Balancer.

Solution for you:

You must allow inbound traffic to your AWS EC2 instance serving worker role

(in other words you have to open NodePort of istio-ingressgateway's service on firewall, see below how to get this port number)

Get NodePort of istio-ingressgateway:

with command:

```<code>export INGRESS_PORT=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.spec.ports[?(@.name=="http2")].nodePort}')
</code>```

Get EXTERNAL_IP of your worker node

with command:

```<code>export INGRESS_HOST=$(kubectl get nodes --selector='!node-role.kubernetes.io/master' -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}')
</code>```

and follow the remaining part of bookinfo sample without any changes.

Body:
I am trying to set up the bookinfo sample application for Istio and Kubernetes on a small cluster.
The cluster consists of two machines, a master and a worker, running on Ubuntu 18.04 on two Amazon AWS EC2 instances.
Each of the instances has an external IP address assigned.

What I'm unable to do is figure out how to expose the bookinfo service to the outside world.

I am confused as to whether I need to expose the Istio ingress gateway or each one of the bookinfo services separately.

When listing the ingress gateway, the external IP field just says pending.
Also, when describing the worker node, there's no mention of an external IP address in the output.

I've gone through google but can't really find a proper solution.
Describing the ingress gateway only gives internal (i.e. 10.x.x.x) addresses.

Output from get and describe commands:

kubectl get svc istio-ingressgateway -n istio-system
NAME                   TYPE           CLUSTER-IP   EXTERNAL-IP   PORT(S)                                                                                AGE
istio-ingressgateway   LoadBalancer   10.96.39.4   <pending>     15020:31451/TCP,80:31380/TCP,443:31390/TCP,31400:31400/TCP,15029:31075/TCP,15030:32093/TCP,15031:31560/TCP,15032:30526/TCP,15443:31526/TCP   68m

kubectl describe  svc istio-ingressgateway  -n istio-system
Name:                     istio-ingressgateway
Namespace:                istio-system
Labels:                   app=istio-ingressgateway
                          chart=gateways
                          heritage=Tiller
                          istio=ingressgateway
                          release=istio
Annotations:              kubectl.kubernetes.io/last-applied-configuration:
                            {"apiVersion":"v1","kind":"Service","metadata":{"annotations":{},"labels":{"app":"istio-ingressgateway","chart":"gateways","heritage":"Til...
Selector:                 app=istio-ingressgateway,istio=ingressgateway,release=istio
Type:                     LoadBalancer
IP:                       10.96.39.4
Port:                     status-port  15020/TCP
TargetPort:               15020/TCP
NodePort:                 status-port  31451/TCP
Endpoints:                10.244.1.6:15020
Port:                     http2  80/TCP
TargetPort:               80/TCP
NodePort:                 http2  31380/TCP
Endpoints:                10.244.1.6:80
Port:                     https  443/TCP
TargetPort:               443/TCP
NodePort:                 https  31390/TCP
Endpoints:                10.244.1.6:443
Port:                     tcp  31400/TCP
TargetPort:               31400/TCP
NodePort:                 tcp  31400/TCP
Endpoints:                10.244.1.6:31400
Port:                     https-kiali  15029/TCP
TargetPort:               15029/TCP
NodePort:                 https-kiali  31075/TCP
Endpoints:                10.244.1.6:15029
Port:                     https-prometheus  15030/TCP
TargetPort:               15030/TCP
NodePort:                 https-prometheus  32093/TCP
Endpoints:                10.244.1.6:15030
Port:                     https-grafana  15031/TCP
TargetPort:               15031/TCP
NodePort:                 https-grafana  31560/TCP
Endpoints:                10.244.1.6:15031
Port:                     https-tracing  15032/TCP
TargetPort:               15032/TCP
NodePort:                 https-tracing  30526/TCP
Endpoints:                10.244.1.6:15032
Port:                     tls  15443/TCP
TargetPort:               15443/TCP
NodePort:                 tls  31526/TCP
Endpoints:                10.244.1.6:15443
Session Affinity:         None
External Traffic Policy:  Cluster
Events:                   <none>

Any help appreciated.

Body:
Quoting Istio's official documentation:

If your cluster is running in an environment that does not support an
  external load balancer (e.g., minikube), the EXTERNAL-IP of
  istio-ingressgateway will say -pending-. To access the gateway, use
  the service’s NodePort, or use port-forwarding instead.

Your cluster seems to fall into 'Custom (cloud)' way of setting up Kubernetes, which by default does not support Load Balancer.

Solution for you:

You must allow inbound traffic to your AWS EC2 instance serving worker role

(in other words you have to open NodePort of istio-ingressgateway's service on firewall, see below how to get this port number)

Get NodePort of istio-ingressgateway:

with command:

export INGRESS_PORT=$(kubectl -n istio-system get service istio-ingressgateway -o jsonpath='{.spec.ports[?(@.name=="http2")].nodePort}')

Get EXTERNAL_IP of your worker node

with command:

export INGRESS_HOST=$(kubectl get nodes --selector='!node-role.kubernetes.io/master' -o jsonpath='{.items[*].status.addresses[?(@.type=="ExternalIP")].address}')

and follow the remaining part of bookinfo sample without any changes.


问:
How can I delete specific files in a folder but not the sub folders?
I have a huge folder structure and I want to delete some specific files only from main folders and leave sub folders intact.

Example:

```<code>Folder A/Sub-folderB/
</code>```

Now , I want to delete files from Folder A ONLY , and this should continue until the last folder N.

This is the code i have tried ,

```<code>Get-Childitem C:\serverfolders\users\* | Where-Object {-Not $_.PSIsContainer} | Foreach-Object {Remove-Item $_.FullName}
</code>```

Any help would be greatly appreciated.

答:
You can use the -Depth parameter of Get-ChildItem to limit the number of subdirectory levels to include in the recursion. In your case, you only want 1 level deep in order to leave any subfolders intact.

```<code>Get-ChildItem -Path 'C:\serverfolders\users' -Depth 1 -File -Recurse | Remove-Item -WhatIf
</code>```

You say you want to delete some specific files only, and for that you can use the -Include parameter of

Get-ChildItem like this:

```<code>Get-ChildItem -Path 'C:\serverfolders\users' -Depth 1 -File -Recurse -Include '*.txt', '*.pdf', '*.doc*' | Remove-Item -WhatIf
</code>```

When satisfied with the results on screen, remove the -WhatIf switch

Body:
I have a huge folder structure and I want to delete some specific files only from main folders and leave sub folders intact.

Example:

Folder A/Sub-folderB/

Now , I want to delete files from Folder A ONLY , and this should continue until the last folder N.

This is the code i have tried ,

Get-Childitem C:\serverfolders\users\* | Where-Object {-Not $_.PSIsContainer} | Foreach-Object {Remove-Item $_.FullName}

Any help would be greatly appreciated.

Body:
You can use the -Depth parameter of Get-ChildItem to limit the number of subdirectory levels to include in the recursion. In your case, you only want 1 level deep in order to leave any subfolders intact.

Get-ChildItem -Path 'C:\serverfolders\users' -Depth 1 -File -Recurse | Remove-Item -WhatIf

You say you want to delete some specific files only, and for that you can use the -Include parameter of

Get-ChildItem like this:

Get-ChildItem -Path 'C:\serverfolders\users' -Depth 1 -File -Recurse -Include '*.txt', '*.pdf', '*.doc*' | Remove-Item -WhatIf

When satisfied with the results on screen, remove the -WhatIf switch


问:
CSS error: Image CSS set permanently to 'display:none ! important;
Well, basically i created a image inside a div using the img tag in a HTML file that i've been writing and the image just wont show up on the browser. Inspect says the image cannot be loaded and it's CSS is set to 'display: none!important'.I wasn't able to untick it even in inspect. Can you help me?

No class was declared on the img tag and the div holding it.

I haven't written the 'display:none!important' css anywhere on the page.
3.There are other images in the same page which is displaying perfectly fine. I placed another image on the div which is holding my problem-image and even it is showing up. Renaming the image works too [Although i would like to know why].

The code used:

```<code><div class="col-1"><img src="../Home-Page/images/twitter-logo-silhouette.png" alt="twitter"></div>
</code>```

Any other image will work fine,The image is now kept renamed by finding it in finder, the error is gone now. But i still would like to know why it is so. If i rename it back. The error will appear once again.

答:
Your adblocker is blocking the image out, i guess.

If you try to rename your file and alt tag without naming twitter it will work, as you mentioned above

Body:
Well, basically i created a image inside a div using the img tag in a HTML file that i've been writing and the image just wont show up on the browser. Inspect says the image cannot be loaded and it's CSS is set to 'display: none!important'.I wasn't able to untick it even in inspect. Can you help me?

No class was declared on the img tag and the div holding it.

I haven't written the 'display:none!important' css anywhere on the page.
3.There are other images in the same page which is displaying perfectly fine. I placed another image on the div which is holding my problem-image and even it is showing up. Renaming the image works too [Although i would like to know why].

The code used:

Any other image will work fine,The image is now kept renamed by finding it in finder, the error is gone now. But i still would like to know why it is so. If i rename it back. The error will appear once again.


问:
how to eliminate 3 letter words or 4 letter words from a column of a dataframe
I have a dataframe  as below:

```<code>import pandas as pd
import dask.dataframe as dd
a = {'b':['category','categorical','cater pillar','coming and going','bat','No Data','calling','cal'],
     'c':['strd1','strd2','strd3', 'strd4','strd5','strd6','strd7', 'strd8']
    }
df11 = pd.DataFrame(a,index=['x1','x2','x3','x4','x5','x6','x7','x8'])
</code>```

I wanted to remove words whose length of each value is three.
I expect results to be like:

```<code>   b                         c
category                   strd1
categorical                strd2
cater pillar               strd3
coming and going           strd4
NaN                        strd5
No Data                    strd6
calling                    strd7
NaN                        strd8
</code>```

答:
Use str.len to get the length of each string and then conditionally replace them toNaN with np.where if the length is equal to 3:

```<code>df11['b'] = np.where(df11['b'].str.len().eq(3), np.NaN, df11['b'])

                  b      c
0          category  strd1
1       categorical  strd2
2      cater pillar  strd3
3  coming and going  strd4
4               NaN  strd5
5           No Data  strd6
6           calling  strd7
7               NaN  strd8
</code>```

Body:
I have a dataframe  as below:

import pandas as pd
import dask.dataframe as dd
a = {'b':['category','categorical','cater pillar','coming and going','bat','No Data','calling','cal'],
     'c':['strd1','strd2','strd3', 'strd4','strd5','strd6','strd7', 'strd8']
    }
df11 = pd.DataFrame(a,index=['x1','x2','x3','x4','x5','x6','x7','x8'])

I wanted to remove words whose length of each value is three.
I expect results to be like:

   b                         c
category                   strd1
categorical                strd2
cater pillar               strd3
coming and going           strd4
NaN                        strd5
No Data                    strd6
calling                    strd7
NaN                        strd8

Body:
Use str.len to get the length of each string and then conditionally replace them toNaN with np.where if the length is equal to 3:

df11['b'] = np.where(df11['b'].str.len().eq(3), np.NaN, df11['b'])

                  b      c
0          category  strd1
1       categorical  strd2
2      cater pillar  strd3
3  coming and going  strd4
4               NaN  strd5
5           No Data  strd6
6           calling  strd7
7               NaN  strd8


问:
MySQL ORDER By one Specific value in column (having comma separated values)
I want to sort the user record according to city (chosen from the drop-down list). like if I pass city_id 22 in my query then i want all the row first which are having city_ids 22 then the rest of the rows.

I know WHERE find_in_set('22',city_ids) will give me the correct result but it will not return the all rows so I want to achieve it using some ORDER BY .

I have tried ORDER BY FIND_IN_SET('22',city_ids) but its not working. How do I fix this, any best way?

User Table:

```<code>Id    Name     city_ids
1     AAAAA    10,22,30
2     BBBBB    11,28
3     CCCCC    15,22,44
4     DDDDD    19,99,
5     EEEEE    55,27,22
</code>```

Want Sorted Output like below:

```<code>Id    Name     city_ids
1     AAAAA    10,22,30
3     CCCCC    15,22,44
5     EEEEE    55,27,22
2     BBBBB    11,28
4     DDDDD    19,99,
</code>```

答:
You can do:

```<code>ORDER BY (FIND_IN_SET('22', city_ids) > 0) DESC
</code>```

This puts matches first.

Then you should fix your data model.  It is broken, broken, broken.  Storing lists of ids in a string is wrong for many reasons:

The data types are (presumably) wrong.  The ids are numbers and should not be stored as strings.

Storing multiple values in a column is not the SQL way to store things.

Ids should have properly declared foreign key relationships, which you cannot declare.

SQL does not have very good functions for processing strings.

The resulting queries cannot take advantage of indexes or partitioning, impeding performance.

SQL has this really great data structure for storing lists of things.  It is called a table, not a string column.

Body:
I want to sort the user record according to city (chosen from the drop-down list). like if I pass city_id 22 in my query then i want all the row first which are having city_ids 22 then the rest of the rows.

I know WHERE find_in_set('22',city_ids) will give me the correct result but it will not return the all rows so I want to achieve it using some ORDER BY .

I have tried ORDER BY FIND_IN_SET('22',city_ids) but its not working. How do I fix this, any best way?

User Table:

Id    Name     city_ids
1     AAAAA    10,22,30
2     BBBBB    11,28
3     CCCCC    15,22,44
4     DDDDD    19,99,
5     EEEEE    55,27,22

Want Sorted Output like below:

Id    Name     city_ids
1     AAAAA    10,22,30
3     CCCCC    15,22,44
5     EEEEE    55,27,22
2     BBBBB    11,28
4     DDDDD    19,99,

Body:
You can do:

ORDER BY (FIND_IN_SET('22', city_ids) > 0) DESC

This puts matches first.

Then you should fix your data model.  It is broken, broken, broken.  Storing lists of ids in a string is wrong for many reasons:

The data types are (presumably) wrong.  The ids are numbers and should not be stored as strings.

Storing multiple values in a column is not the SQL way to store things.

Ids should have properly declared foreign key relationships, which you cannot declare.

SQL does not have very good functions for processing strings.

The resulting queries cannot take advantage of indexes or partitioning, impeding performance.

SQL has this really great data structure for storing lists of things.  It is called a table, not a string column.


问:
Data fetch from api works with https api but not with http api
I am working on an application and made I had to make an API get request and show the data in RecyclerView(I used retrofit for the purpose) When I finished the code, I found that the data fetch is working fine with HTTPS APIs but when I put a HTTP API in my BASE_URL it doesn't work.

The following API is the one with which it works fine:
https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php

But using an HTTP API, output doesn't show up.

MainActivity

package com.example.parsaniahardik.json_recycler_retrofit;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class MainActivity extends AppCompatActivity {

    private RetrofitAdapter retrofitAdapter;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recycler);

        fetchJSON();

    }

    private void fetchJSON(){

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RecyclerInterface.JSONURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        RecyclerInterface api = retrofit.create(RecyclerInterface.class);

        Call<String> call = api.getString();

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        writeRecycler(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

    private void writeRecycler(String response){

        try {
            //getting the whole json object from the response
            JSONObject obj = new JSONObject(response);
            if(obj.optString("status").equals("true")){

                ArrayList<ModelRecycler> modelRecyclerArrayList = new ArrayList<>();
                JSONArray dataArray  = obj.getJSONArray("data");

                for (int i = 0; i < dataArray.length(); i++) {

                    ModelRecycler modelRecycler = new ModelRecycler();
                    JSONObject dataobj = dataArray.getJSONObject(i);

                    modelRecycler.setName(dataobj.getString("name"));
                    modelRecycler.setCountry(dataobj.getString("country"));
                    modelRecycler.setCity(dataobj.getString("city"));

                    modelRecyclerArrayList.add(modelRecycler);

                }

                retrofitAdapter = new RetrofitAdapter(this,modelRecyclerArrayList);
                recyclerView.setAdapter(retrofitAdapter);
                recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

            }else {
                Toast.makeText(MainActivity.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
```

<p>Adapter </p>

<pre class="lang-java prettyprint-override"><code>public class RetrofitAdapter extends RecyclerView.Adapter<RetrofitAdapter.MyViewHolder> {

    private LayoutInflater inflater;
    private ArrayList<ModelRecycler> dataModelArrayList;

    public RetrofitAdapter(Context ctx, ArrayList<ModelRecycler> dataModelArrayList){

        inflater = LayoutInflater.from(ctx);
        this.dataModelArrayList = dataModelArrayList;
    }

    @Override
    public RetrofitAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = inflater.inflate(R.layout.retro_item, parent, false);
        MyViewHolder holder = new MyViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(RetrofitAdapter.MyViewHolder holder, int position) {

        holder.name.setText(dataModelArrayList.get(position).getName());
        holder.country.setText(dataModelArrayList.get(position).getCountry());
        holder.city.setText(dataModelArrayList.get(position).getCity());
    }

    @Override
    public int getItemCount() {
        return dataModelArrayList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{

        TextView country, name, city;

        public MyViewHolder(View itemView) {
            super(itemView);

            country = (TextView) itemView.findViewById(R.id.country);
            name = (TextView) itemView.findViewById(R.id.name);
            city = (TextView) itemView.findViewById(R.id.city);
    }

    }
}
</code>```

ApiInterface

public interface RecyclerInterface {

    String JSONURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/";

    @GET("json_parsing.php")
    Call<String> getString();
}
```

<p>ModelClass</p>

<pre class="lang-java prettyprint-override"><code>public class ModelRecycler {

    private String name, country, city;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}
</code>```

I want hat my API fetch works with both HTTPS APIs and also HTTP APIs

答:
SOLVED:
As mentioned by @DEVV911, this problem is encountered if you are testing the app on Android 9(Pie).
If you encounter the same problem then just make a new Android Resource Directory in the res folder and name it "xml" with resource type XML. In the "xml" folder make a new XML resource file by the name of "network_security_config". Inside it type this

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">YourDomainName.com</domain>
    </domain-config>
</network-security-config>
```

<p>After this go to your manifest file and inside the application tag type: </p>

<pre class="lang-xml prettyprint-override"><code><android:networkSecurityConfig="@xml/network_security_config"
</code>```

And then it works fine.

Body:
I am working on an application and made I had to make an API get request and show the data in RecyclerView(I used retrofit for the purpose) When I finished the code, I found that the data fetch is working fine with HTTPS APIs but when I put a HTTP API in my BASE_URL it doesn't work.

The following API is the one with which it works fine:
https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php

But using an HTTP API, output doesn't show up.

MainActivity

package com.example.parsaniahardik.json_recycler_retrofit;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

public class MainActivity extends AppCompatActivity {

    private RetrofitAdapter retrofitAdapter;
    private RecyclerView recyclerView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recycler);

        fetchJSON();

    }

    private void fetchJSON(){

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RecyclerInterface.JSONURL)
                .addConverterFactory(ScalarsConverterFactory.create())
                .build();

        RecyclerInterface api = retrofit.create(RecyclerInterface.class);

        Call<String> call = api.getString();

        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Responsestring", response.body().toString());
                //Toast.makeText()
                if (response.isSuccessful()) {
                    if (response.body() != null) {
                        Log.i("onSuccess", response.body().toString());

                        String jsonresponse = response.body().toString();
                        writeRecycler(jsonresponse);

                    } else {
                        Log.i("onEmptyResponse", "Returned empty response");//Toast.makeText(getContext(),"Nothing returned",Toast.LENGTH_LONG).show();
                    }
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {

            }
        });
    }

    private void writeRecycler(String response){

        try {
            //getting the whole json object from the response
            JSONObject obj = new JSONObject(response);
            if(obj.optString("status").equals("true")){

                ArrayList<ModelRecycler> modelRecyclerArrayList = new ArrayList<>();
                JSONArray dataArray  = obj.getJSONArray("data");

                for (int i = 0; i < dataArray.length(); i++) {

                    ModelRecycler modelRecycler = new ModelRecycler();
                    JSONObject dataobj = dataArray.getJSONObject(i);

                    modelRecycler.setName(dataobj.getString("name"));
                    modelRecycler.setCountry(dataobj.getString("country"));
                    modelRecycler.setCity(dataobj.getString("city"));

                    modelRecyclerArrayList.add(modelRecycler);

                }

                retrofitAdapter = new RetrofitAdapter(this,modelRecyclerArrayList);
                recyclerView.setAdapter(retrofitAdapter);
                recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

            }else {
                Toast.makeText(MainActivity.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show();
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Adapter

public class RetrofitAdapter extends RecyclerView.Adapter<RetrofitAdapter.MyViewHolder> {

    private LayoutInflater inflater;
    private ArrayList<ModelRecycler> dataModelArrayList;

    public RetrofitAdapter(Context ctx, ArrayList<ModelRecycler> dataModelArrayList){

        inflater = LayoutInflater.from(ctx);
        this.dataModelArrayList = dataModelArrayList;
    }

    @Override
    public RetrofitAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = inflater.inflate(R.layout.retro_item, parent, false);
        MyViewHolder holder = new MyViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(RetrofitAdapter.MyViewHolder holder, int position) {

        holder.name.setText(dataModelArrayList.get(position).getName());
        holder.country.setText(dataModelArrayList.get(position).getCountry());
        holder.city.setText(dataModelArrayList.get(position).getCity());
    }

    @Override
    public int getItemCount() {
        return dataModelArrayList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{

        TextView country, name, city;

        public MyViewHolder(View itemView) {
            super(itemView);

            country = (TextView) itemView.findViewById(R.id.country);
            name = (TextView) itemView.findViewById(R.id.name);
            city = (TextView) itemView.findViewById(R.id.city);
    }

    }
}

ApiInterface

public interface RecyclerInterface {

    String JSONURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/";

    @GET("json_parsing.php")
    Call<String> getString();
}

ModelClass

public class ModelRecycler {

    private String name, country, city;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}

I want hat my API fetch works with both HTTPS APIs and also HTTP APIs

Body:
SOLVED:
As mentioned by @DEVV911, this problem is encountered if you are testing the app on Android 9(Pie).
If you encounter the same problem then just make a new Android Resource Directory in the res folder and name it "xml" with resource type XML. In the "xml" folder make a new XML resource file by the name of "network_security_config". Inside it type this

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        <domain includeSubdomains="true">YourDomainName.com</domain>
    </domain-config>
</network-security-config>

After this go to your manifest file and inside the application tag type:

<android:networkSecurityConfig="@xml/network_security_config"

And then it works fine.


答:
Use series.str.len() to identify the length of the string in a series and then compare with series.eq(), then using df.loc[] you can assign the values of b as np.nan where the condition matches:

```<code>df11.loc[df11.b.str.len().eq(3),'b']=np.nan
</code>```

```<code>                   b      c
x1          category  strd1
x2       categorical  strd2
x3      cater pillar  strd3
x4  coming and going  strd4
x5               NaN  strd5
x6           No Data  strd6
x7           calling  strd7
x8               NaN  strd8
</code>```

Title: how to eliminate 3 letter words or 4 letter words from a column of a dataframe

Body:
Use series.str.len() to identify the length of the string in a series and then compare with series.eq(), then using df.loc[] you can assign the values of b as np.nan where the condition matches:

df11.loc[df11.b.str.len().eq(3),'b']=np.nan

                   b      c
x1          category  strd1
x2       categorical  strd2
x3      cater pillar  strd3
x4  coming and going  strd4
x5               NaN  strd5
x6           No Data  strd6
x7           calling  strd7
x8               NaN  strd8


问:
Recognize vertical text using google cloud vision
I'm trying to recognize vertical text using google cloud vision. Image example:

I use Try This API on https://cloud.google.com/vision/docs/ocr to test the engine.

Request body:

```<code>{
  "requests": [
    {
      "features": [
        {
          "type": "DOCUMENT_TEXT_DETECTION"
        }
      ],
      "image": {
        "source": {
          "imageUri": "https://i.stack.imgur.com/3wwYp.jpg"
        }
      }
    }
  ]
}
</code>```

The result is

```<code>{
  "responses": [
    {}
  ]
}
</code>```

Am I missing something? Thank you.

答:
You can try to set "model": "builtin/latest" as per the documentation, that will give you some results. I believe recognising vertical text is something that is being worked on now, so you should not expect 100% accuracy at this moment.

Another issue is that single character detection is currently not supported by the Vision API.There is a feature request submitted with regard to character recognition here. Please star it so that you could receive updates about this feature request and do not hesitate to add additional comments to provide details of the desired implementation.

You can also have a look at this post, where people discuss vertical text recognition.

I have tried my first suggestion with your image, and for some reason A is not recognised, perhaps the Vision API sees it as "being separate" from the rest of the letters, which form a sequence, and is not being recognised since it is treated as a single character in that case.

Body:
I'm trying to recognize vertical text using google cloud vision. Image example:

I use Try This API on https://cloud.google.com/vision/docs/ocr to test the engine.

Request body:

{
  "requests": [
    {
      "features": [
        {
          "type": "DOCUMENT_TEXT_DETECTION"
        }
      ],
      "image": {
        "source": {
          "imageUri": "https://i.stack.imgur.com/3wwYp.jpg"
        }
      }
    }
  ]
}

The result is

{
  "responses": [
    {}
  ]
}

Am I missing something? Thank you.


问:
Output displayed on compiler is different from expected value. But correct value is obtained when copy-pasting this value to Excel
Output displayed in the compiler is incorrect but when copied from the compiler and pasted to Ms Excel, it magically appears to become the correct output. what might be the reasons for it and how can I correct this issue.

I am solving Project Euler #2 on HackerRank. The problem demands summation of even fibonacci number under the given limit. I passed all test cases except test case 3. Going through the discussions, I realised that due to the involvement of arithmetic operations on very large numbers, it might be causing a issue. Therefore I took the given boundary condition of N = 4*10^16 and obtained a solution through my code and compared the answer with my manually calculated answer in excel.

expected answer (Excel) :

```<code>49597426547377700
</code>```

whereas compiler output is (HackerRank) :

```<code>49597426547377738
</code>```

Things got interesting when I copied the compiler output in excel, then I got the paste in scientific notation 4.95974E+16 . upon converting the cell from general to number type on the number tap, voila!  I got the correct expected answer.

What might be causing this and how do I deal with this?

```<code>
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

unsigned long prep_fibonnaci[100] =

{

1, 1, 2, 3 ,5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074, 32951280099, 53316291173, 86267571272, 139583862445, 225851433717, 365435296162, 591286729879, 956722026041, 1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723, 17167680177565, 27777890035288, 44945570212853, 72723460248141, 117669030460994, 190392490709135, 308061521170129, 498454011879264, 806515533049393, 1304969544928650, 2111485077978050, 3416454622906700, 5527939700884750, 8944394323791460, 14472334024676200, 23416728348467600, 37889062373143900,61305790721611500

};

long T;
long N;

int main()

{

    cin >> T;

    for (long i=0 ; i < T ; i++)
    {

      cin >> N;

      long highest_fib;
      int index;
      long sum = 0;

      for (int j = 0; j <= 82; j++)
      {

            if (prep_fibonnaci[j] > N)

            {
            index = j - 1;
            //cout <<"index: " << index << "\n";
            highest_fib = prep_fibonnaci[index];
            //cout <<"highest_fib: " <<highest_fib <<"\n";
            break;
            }

      }

      for (int k = 2; k <= index; k = k+3)

      {
            sum = sum+prep_fibonnaci[k];
            //cout << "sum: " << sum << "\n";
      }

       cout << sum << "\n";

    }

    return 0;
}

</code>```

答: How did you calculate your prep_fibonacci array? The values starting with 1304969544928650 are wrong -- I think this is your issue.

Body:
Output displayed in the compiler is incorrect but when copied from the compiler and pasted to Ms Excel, it magically appears to become the correct output. what might be the reasons for it and how can I correct this issue.

I am solving Project Euler #2 on HackerRank. The problem demands summation of even fibonacci number under the given limit. I passed all test cases except test case 3. Going through the discussions, I realised that due to the involvement of arithmetic operations on very large numbers, it might be causing a issue. Therefore I took the given boundary condition of N = 4*10^16 and obtained a solution through my code and compared the answer with my manually calculated answer in excel.

expected answer (Excel) :

49597426547377700

whereas compiler output is (HackerRank) :

49597426547377738

Things got interesting when I copied the compiler output in excel, then I got the paste in scientific notation 4.95974E+16 . upon converting the cell from general to number type on the number tap, voila!  I got the correct expected answer.

What might be causing this and how do I deal with this?

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

unsigned long prep_fibonnaci[100] =

{

1, 1, 2, 3 ,5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946, 17711, 28657, 46368, 75025, 121393, 196418, 317811, 514229, 832040, 1346269, 2178309, 3524578, 5702887, 9227465, 14930352, 24157817, 39088169, 63245986, 102334155, 165580141, 267914296, 433494437, 701408733, 1134903170, 1836311903, 2971215073, 4807526976, 7778742049, 12586269025, 20365011074, 32951280099, 53316291173, 86267571272, 139583862445, 225851433717, 365435296162, 591286729879, 956722026041, 1548008755920, 2504730781961, 4052739537881, 6557470319842, 10610209857723, 17167680177565, 27777890035288, 44945570212853, 72723460248141, 117669030460994, 190392490709135, 308061521170129, 498454011879264, 806515533049393, 1304969544928650, 2111485077978050, 3416454622906700, 5527939700884750, 8944394323791460, 14472334024676200, 23416728348467600, 37889062373143900,61305790721611500

};

long T;
long N;

int main()

{

    cin >> T;

    for (long i=0 ; i < T ; i++)
    {

      cin >> N;

      long highest_fib;
      int index;
      long sum = 0;

      for (int j = 0; j <= 82; j++)
      {

            if (prep_fibonnaci[j] > N)

            {
            index = j - 1;
            //cout <<"index: " << index << "\n";
            highest_fib = prep_fibonnaci[index];
            //cout <<"highest_fib: " <<highest_fib <<"\n";
            break;
            }

      }

      for (int k = 2; k <= index; k = k+3)

      {
            sum = sum+prep_fibonnaci[k];
            //cout << "sum: " << sum << "\n";
      }

       cout << sum << "\n";

    }

    return 0;
}


问:
I have problem using thread passing argument
I'm trying to solve readers/writers problem using binary semaphore.

The result I expected was I'm writer2 , data is 1. I'm reader3, data is 2.

But, result is I'm writer0 , and I'm reader0 data1 , data2 ~ data5.
How can I fix my code?

```<code>int data = 0; // global variable.
void main()
{
    //other code is omitted.

    int i;
    for(i=0; i<5; i++)
            pthread_create(&w[i], NULL, writer, &i);

    for(i=0; i<20; i++)
            pthread_create(&r[i], NULL, reader, &i);

    for(i=0; i<5; i++)
            pthread_join(w[i], NULL);

    for(i=0; i<20; i++)
            pthread_join(r[i], NULL);
}
</code>```

答:
Your problem probably concerns the value of i which does not have the right value for the threads, there are two reasons for that

first you do not have synchronization so the main can change the value of i before a thread reads it

second the access from an other thread of a local variable is not guaranty :

C11 draft standard n1570: 6.2.4 Storage durations of objects 5 An object whose identifier is declared with no linkage and without the storage-class specifier static has automatic storage duration, as do some compound literals. The result of attempting to indirectly access an object with automatic storage duration from a thread other than the one with which the object is associated is implementation-defined

So a good way it to allocate memory and give its address, for instance :

```<code>for(i=0; i<5; i++) {
  int * p = malloc(sizeof(int));

  *p = i;
  pthread_create(&w[i], NULL, writer, p);
}
</code>```

and of course the created thread is responsible to free the memory

Body:
I'm trying to solve readers/writers problem using binary semaphore.

The result I expected was I'm writer2 , data is 1. I'm reader3, data is 2.

But, result is I'm writer0 , and I'm reader0 data1 , data2 ~ data5.
How can I fix my code?

int data = 0; // global variable.
void main()
{
    //other code is omitted.

    int i;
    for(i=0; i<5; i++)
            pthread_create(&w[i], NULL, writer, &i);

    for(i=0; i<20; i++)
            pthread_create(&r[i], NULL, reader, &i);

    for(i=0; i<5; i++)
            pthread_join(w[i], NULL);

    for(i=0; i<20; i++)
            pthread_join(r[i], NULL);
}

Body:
Your problem probably concerns the value of i which does not have the right value for the threads, there are two reasons for that

first you do not have synchronization so the main can change the value of i before a thread reads it

second the access from an other thread of a local variable is not guaranty :

C11 draft standard n1570: 6.2.4 Storage durations of objects 5 An object whose identifier is declared with no linkage and without the storage-class specifier static has automatic storage duration, as do some compound literals. The result of attempting to indirectly access an object with automatic storage duration from a thread other than the one with which the object is associated is implementation-defined

So a good way it to allocate memory and give its address, for instance :

for(i=0; i<5; i++) {
  int * p = malloc(sizeof(int));

  *p = i;
  pthread_create(&w[i], NULL, writer, p);
}

and of course the created thread is responsible to free the memory


问:
Cannot cast cell as Custom cell
I made a custom cell but it's not getting called or casted.

I tried different ways of calling the identifier, registering the cell, and nothing worked, I've got an example project that it's working and I have it exactly the same. So I don't know what could be causing this.

Currently these are my functions. Debugging, I found out that it never enters the if condition inside the cellForRowAt so therein lies the problem, but can't figure out what's causing it.

```<code>func registerCell() {
        let cellNib = UINib(nibName: FAQTableViewCell.reuseIdentifier, bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: FAQTableViewCell.reuseIdentifier)
    }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: FAQTableViewCell.reuseIdentifier, for: indexPath)
        if let cell = cell as? FAQTableViewCell {
            cell.preguntaLabel.text = arrayTitulo[indexPath.row] as? String
            cell.respuestaLabel.text = arrayDesc[indexPath.row] as? String
        }

        return cell
    }
</code>```

I checked everything, the .xib of the cell, the cell.swift the controller.swift, everything, it's all matching. I don't know what else to do.

FAQTableViewCell:

```<code>import AEAccordion

final class FAQTableViewCell: AccordionTableViewCell {

    static let reuseIdentifier = "FAQTableViewCell"

    @IBOutlet weak var headerView: UIView!
    @IBOutlet weak var detailView: UIView!
    @IBOutlet weak var preguntaLabel: UILabel!
    @IBOutlet weak var respuestaLabel: UILabel!

    // MARK: Override

    override func setExpanded(_ expanded: Bool, animated: Bool) {
        super.setExpanded(expanded, animated: animated)

        if animated {
            UIView.transition(with: detailView, duration: 0.3, animations: {
                self.detailView.isHidden = !expanded
            }, completion: nil)
        } else {
            detailView.isHidden = !expanded
        }
    }

    private func toggleCell() {
        detailView.isHidden = !expanded
    }
}
</code>```

FIXED IT: I just removed the .xib and made the custom cell inside the
TableViewController on Main.storyboard

答:
According to the debbugging fact "I found out that it never enters the if in cellForRowAt".

Check the returned vale of func tableView(_: UITableView, numberOfRowsInSection _: Int) -> Int is != Zero

and

the value of func numberOfSections(in tableView: UITableView) -> Int only if it is implemented as that its default is 1 if not implemented

Title: Cannot cast cell as Custom cell

Body:
I made a custom cell but it's not getting called or casted.

I tried different ways of calling the identifier, registering the cell, and nothing worked, I've got an example project that it's working and I have it exactly the same. So I don't know what could be causing this.

Currently these are my functions. Debugging, I found out that it never enters the if condition inside the cellForRowAt so therein lies the problem, but can't figure out what's causing it.

func registerCell() {
        let cellNib = UINib(nibName: FAQTableViewCell.reuseIdentifier, bundle: nil)
        tableView.register(cellNib, forCellReuseIdentifier: FAQTableViewCell.reuseIdentifier)
    }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: FAQTableViewCell.reuseIdentifier, for: indexPath)
        if let cell = cell as? FAQTableViewCell {
            cell.preguntaLabel.text = arrayTitulo[indexPath.row] as? String
            cell.respuestaLabel.text = arrayDesc[indexPath.row] as? String
        }

        return cell
    }

I checked everything, the .xib of the cell, the cell.swift the controller.swift, everything, it's all matching. I don't know what else to do.

FAQTableViewCell:

import AEAccordion

final class FAQTableViewCell: AccordionTableViewCell {

    static let reuseIdentifier = "FAQTableViewCell"

    @IBOutlet weak var headerView: UIView!
    @IBOutlet weak var detailView: UIView!
    @IBOutlet weak var preguntaLabel: UILabel!
    @IBOutlet weak var respuestaLabel: UILabel!

    // MARK: Override

    override func setExpanded(_ expanded: Bool, animated: Bool) {
        super.setExpanded(expanded, animated: animated)

        if animated {
            UIView.transition(with: detailView, duration: 0.3, animations: {
                self.detailView.isHidden = !expanded
            }, completion: nil)
        } else {
            detailView.isHidden = !expanded
        }
    }

    private func toggleCell() {
        detailView.isHidden = !expanded
    }
}

FIXED IT: I just removed the .xib and made the custom cell inside the
TableViewController on Main.storyboard


问:
Symfony 3.4.11 doctrine Notice: Uninitialized string offset: 0
I am using Symfony and I upgrade to 3.4.11.

But I have a big problem. When I run the command:

```<code>php bin/console doctrine:schema:update  --dump-sql
</code>```

in the terminal I have the next error:

```<code>In ClassMetadataInfo.php line 1400:

  Notice: Uninitialized string offset: 0
</code>```

Really, I was search and readed the docs and I can't found the error.

Thanks very much

UPDATE

```<code>$ php bin/console doc:sch:va  -vvv

Mapping
-------

In ClassMetadataInfo.php line 1400:

  [Symfony\Component\Debug\Exception\ContextErrorException]
  Notice: Uninitialized string offset: 0

Exception trace:
 Doctrine\ORM\Mapping\ClassMetadataInfo->_validateAndCompleteFieldMapping() at /home/devel/tests4/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php:2355

 Doctrine\ORM\Mapping\ClassMetadataInfo->mapField() at /home/devel/tests4/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php:333

 Doctrine\ORM\Mapping\Driver\AnnotationDriver->loadMetadataForClass() at /home/devel/tests4/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/MappingDriverChain.php:102

 Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain->loadMetadataForClass() at /home/devel/tests4/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:151

 Doctrine\ORM\Mapping\ClassMetadataFactory->doLoadMetadata() at /home/devel/tests4/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:333

 Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->loadMetadata() at /home/devel/tests4/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:78

 Doctrine\ORM\Mapping\ClassMetadataFactory->loadMetadata() at /home/devel/tests4/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:217

 Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getMetadataFor() at /home/devel/tests4/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:115

 Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getAllMetadata() at /home/devel/tests4/vendor/doctrine/orm/lib/Doctrine/ORM/Tools/SchemaValidator.php:68

 Doctrine\ORM\Tools\SchemaValidator->validateMapping() at /home/devel/tests4/vendor/doctrine/orm/lib/Doctrine/ORM/Tools/Console/Command/ValidateSchemaCommand.php:69

 Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand->execute() at /home/devel/tests4/vendor/doctrine/doctrine-bundle/Command/Proxy/ValidateSchemaCommand.php:34

 Doctrine\Bundle\DoctrineBundle\Command\Proxy\ValidateSchemaCommand->execute() at /home/devel/tests4/vendor/symfony/console/Command/Command.php:251

 Symfony\Component\Console\Command\Command->run() at /home/devel/tests4/vendor/symfony/console/Application.php:964

 Symfony\Component\Console\Application->doRunCommand() at /home/devel/tests4/vendor/symfony/framework-bundle/Console/Application.php:86

 Symfony\Bundle\FrameworkBundle\Console\Application->doRunCommand() at /home/devel/tests4/vendor/symfony/console/Application.php:248

 Symfony\Component\Console\Application->doRun() at /home/devel/tests4/vendor/symfony/framework-bundle/Console/Application.php:74

 Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at /home/devel/tests4/vendor/symfony/console/Application.php:148

 Symfony\Component\Console\Application->run() at /home/devel/tests4/bin/console:39
</code>```

答:
I also experienced the "Uninitialized string offset: 0" with doctrine, from Symfony console.

```<code>In MySqlSchemaManager.php line 223:
    Notice: Uninitialized string offset: 0
</code>```

In my case it was a MariaDB version mismatch between doctrine config and (local) server version. I saw @Samuel Åslund's suggestion to update MariaDB and found that a bit excessive, but it did point me in the direction of a database-version issue.

In doctrine.yaml (Symfony 4+)

```<code> doctrine:
    dbal:
        server_version: 'mariadb-10.1.36'
</code>```

After installing via symfony-console it was pre-configured with:

```<code> doctrine:
    dbal:
        server_version: 'mariadb-10.3.11'
</code>```

Body:
I am using Symfony and I upgrade to 3.4.11.

But I have a big problem. When I run the command:

php bin/console doctrine:schema:update  --dump-sql

in the terminal I have the next error:

In ClassMetadataInfo.php line 1400:

  Notice: Uninitialized string offset: 0

Really, I was search and readed the docs and I can't found the error.

Thanks very much

UPDATE

$ php bin/console doc:sch:va  -vvv

Mapping
-------

In ClassMetadataInfo.php line 1400:

  [Symfony\Component\Debug\Exception\ContextErrorException]
  Notice: Uninitialized string offset: 0

Exception trace:
 Doctrine\ORM\Mapping\ClassMetadataInfo->_validateAndCompleteFieldMapping() at /home/devel/tests4/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataInfo.php:2355

 Doctrine\ORM\Mapping\ClassMetadataInfo->mapField() at /home/devel/tests4/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/AnnotationDriver.php:333

 Doctrine\ORM\Mapping\Driver\AnnotationDriver->loadMetadataForClass() at /home/devel/tests4/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/Driver/MappingDriverChain.php:102

 Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain->loadMetadataForClass() at /home/devel/tests4/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:151

 Doctrine\ORM\Mapping\ClassMetadataFactory->doLoadMetadata() at /home/devel/tests4/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:333

 Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->loadMetadata() at /home/devel/tests4/vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/ClassMetadataFactory.php:78

 Doctrine\ORM\Mapping\ClassMetadataFactory->loadMetadata() at /home/devel/tests4/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:217

 Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getMetadataFor() at /home/devel/tests4/vendor/doctrine/common/lib/Doctrine/Common/Persistence/Mapping/AbstractClassMetadataFactory.php:115

 Doctrine\Common\Persistence\Mapping\AbstractClassMetadataFactory->getAllMetadata() at /home/devel/tests4/vendor/doctrine/orm/lib/Doctrine/ORM/Tools/SchemaValidator.php:68

 Doctrine\ORM\Tools\SchemaValidator->validateMapping() at /home/devel/tests4/vendor/doctrine/orm/lib/Doctrine/ORM/Tools/Console/Command/ValidateSchemaCommand.php:69

 Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand->execute() at /home/devel/tests4/vendor/doctrine/doctrine-bundle/Command/Proxy/ValidateSchemaCommand.php:34

 Doctrine\Bundle\DoctrineBundle\Command\Proxy\ValidateSchemaCommand->execute() at /home/devel/tests4/vendor/symfony/console/Command/Command.php:251

 Symfony\Component\Console\Command\Command->run() at /home/devel/tests4/vendor/symfony/console/Application.php:964

 Symfony\Component\Console\Application->doRunCommand() at /home/devel/tests4/vendor/symfony/framework-bundle/Console/Application.php:86

 Symfony\Bundle\FrameworkBundle\Console\Application->doRunCommand() at /home/devel/tests4/vendor/symfony/console/Application.php:248

 Symfony\Component\Console\Application->doRun() at /home/devel/tests4/vendor/symfony/framework-bundle/Console/Application.php:74

 Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at /home/devel/tests4/vendor/symfony/console/Application.php:148

 Symfony\Component\Console\Application->run() at /home/devel/tests4/bin/console:39

Body:
I also experienced the "Uninitialized string offset: 0" with doctrine, from Symfony console.

In MySqlSchemaManager.php line 223:
    Notice: Uninitialized string offset: 0

In my case it was a MariaDB version mismatch between doctrine config and (local) server version. I saw @Samuel Åslund's suggestion to update MariaDB and found that a bit excessive, but it did point me in the direction of a database-version issue.

In doctrine.yaml (Symfony 4+)

 doctrine:
    dbal:
        server_version: 'mariadb-10.1.36'

After installing via symfony-console it was pre-configured with:

 doctrine:
    dbal:
        server_version: 'mariadb-10.3.11'


问:
Calculate rate by group with sapply
I have a data like this:

This is just a fake data I create:

```<code># dt
Col1      Col2   Col3   Col4
2014/1/1  A        10   1
2014/4/1  A        15   1.5
2015/1/1  A        15   3
2015/4/1  A        30   4
2014/1/1  B        20   2
2014/4/1  B        30   6
2015/1/1  B        40   10
2015/4/1  B        80   16
</code>```

What I want:

```<code>Col1      Col2   Col3   Col4   Col3.R   Col4.R
2014/1/1  A        10   1      1        1
2014/4/1  A        15   1.5    1.5      1.5
2015/1/1  A        15   3      1.5      3
2015/4/1  A        30   4      3        4
2014/1/1  B        20   2      1        1
2014/4/1  B        30   6      3/2      3
2015/1/1  B        40   10     2        5
2015/4/1  B        80   16     4        8
</code>```

The new column Col3.R is calculated by the value of col3 under each group Col2 divide the first value in each group. Same as col4.R.

I try the code below:

```<code>dt[, sapply(.SD, function(x) R = x / x[1]), .SDcols = 3:4, by = .(Col2)]
</code>```

How to keep the original columns? Do I need to use argument on for data.table?

Data:

```<code>dt <- fread("    Col1      Col2   Col3   Col4
2014/1/1  A        10   1
2014/4/1  A        15   1.5
2015/1/1  A        15   3
2015/4/1  A        30   4
2014/1/1  B        20   2
2014/4/1  B        30   6
2015/1/1  B        40   10
2015/4/1  B        80   16", header = T)
dt$Col3 <- as.numeric(dt$Col3)
</code>```

Title: Calculate rate by group with sapply

Body:
I have a data like this:

This is just a fake data I create:

# dt
Col1      Col2   Col3   Col4
2014/1/1  A        10   1
2014/4/1  A        15   1.5
2015/1/1  A        15   3
2015/4/1  A        30   4
2014/1/1  B        20   2
2014/4/1  B        30   6
2015/1/1  B        40   10
2015/4/1  B        80   16

What I want:

Col1      Col2   Col3   Col4   Col3.R   Col4.R
2014/1/1  A        10   1      1        1
2014/4/1  A        15   1.5    1.5      1.5
2015/1/1  A        15   3      1.5      3
2015/4/1  A        30   4      3        4
2014/1/1  B        20   2      1        1
2014/4/1  B        30   6      3/2      3
2015/1/1  B        40   10     2        5
2015/4/1  B        80   16     4        8

The new column Col3.R is calculated by the value of col3 under each group Col2 divide the first value in each group. Same as col4.R.

I try the code below:

dt[, sapply(.SD, function(x) R = x / x[1]), .SDcols = 3:4, by = .(Col2)]

How to keep the original columns? Do I need to use argument on for data.table?

Data:

dt <- fread("    Col1      Col2   Col3   Col4
2014/1/1  A        10   1
2014/4/1  A        15   1.5
2015/1/1  A        15   3
2015/4/1  A        30   4
2014/1/1  B        20   2
2014/4/1  B        30   6
2015/1/1  B        40   10
2015/4/1  B        80   16", header = T)
dt$Col3 <- as.numeric(dt$Col3)

Body:
Use lapply and paste0 to create new columns

library(data.table)

dt[, paste0("col", 3:4, ".R") := lapply(.SD,
           function(x) x / x[1]), .SDcols = 3:4, by = .(Col2)]

dt
#       Col1 Col2 Col3 Col4 col3.R col4.R
#1: 2014/1/1    A   10  1.0    1.0    1.0
#2: 2014/4/1    A   15  1.5    1.5    1.5
#3: 2015/1/1    A   15  3.0    1.5    3.0
#4: 2015/4/1    A   30  4.0    3.0    4.0
#5: 2014/1/1    B   20  2.0    1.0    1.0
#6: 2014/4/1    B   30  6.0    1.5    3.0
#7: 2015/1/1    B   40 10.0    2.0    5.0
#8: 2015/4/1    B   80 16.0    4.0    8.0


问:
How to fix Null-Pointer exeption by RapidClipse auto generated code
With RapidClipse I build a page with three elements.
A drop-down field, a XdevTable and a XDevfieldGroup.

The drop-down field is filled by database table content (works fine)

The table should be filled after selecting a value out of drop-down field (works fine)

After selecting a value out of the XDevTable the related row should be editable by the fieldgroup.

After selecting  a row in the table I get a null-pointer exeption:

Mai 27, 2019 4:41:19 PM com.vaadin.server.DefaultErrorHandler doDefault
    SCHWERWIEGEND:
    java.lang.NullPointerException
at
com.xdev.ui.entitycomponent.table.AbstractBeanTable.getSelectedItem(AbstractBeanTable.java:180)
at com.xdev.ui.masterdetail.FieldGroupMasterDetailConnection.lambda$0(FieldGroupMasterDetailConnection.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:510)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:200)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:163)
at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:1015)
at com.vaadin.ui.AbstractField.fireValueChange(AbstractField.java:1161)
at com.vaadin.ui.AbstractField.setValue(AbstractField.java:571)
at com.vaadin.ui.AbstractSelect.setValue(AbstractSelect.java:735)
at com.vaadin.ui.AbstractField.setValue(AbstractField.java:468)
at com.vaadin.ui.AbstractSelect.changeVariables(AbstractSelect.java:547)
at com.vaadin.ui.Table.changeVariables(Table.java:2933)
at com.vaadin.server.communication.ServerRpcHandler.changeVariables(ServerRpcHandler.java:616)
at com.vaadin.server.communication.ServerRpcHandler.handleInvocation(ServerRpcHandler.java:463)
at com.vaadin.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:406)
at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:273)
at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:90)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1435)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:380)
at com.xdev.communication.XdevServlet.service(XdevServlet.java:212)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:660)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:808)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
```

<p>If I am right, I assume, that there is a leak identifying the item which is selected in the table. <br>But I still did what/how is described in RapidClipse Training. <br>So the connection between table and fieldgroup is done by the property "ConnectedForm" inside the table.
<br><br>
The connection from drop-down field to table is done by following code:<br></p>

```private void comboBox_valueChange(final Property.ValueChangeEvent event) {

    try {

        Integer varMainClass = 0;
        varMainClass = this.comboBox.getSelectedItem().getBean().getId();

        Notification.show("Kuck a mole: ", this.comboBox.getSelectedItem().getBean().getGroupName()
                , Notification.Type.ERROR_MESSAGE);

        final BeanItemContainer<TGroup> mySubClasses = new BeanItemContainer<>(TGroup.class);
        mySubClasses.addAll(new TGroupDAO().getAllSubClassByMainClassId(varMainClass));
        this.table.setContainerDataSource(mySubClasses);
        this.table.setVisibleColumns("id", "groupName");
        this.table.setVisible(true);
    } catch (final Exception e) {
        e.printStackTrace();
        final String stackTrace = Throwables.getStackTraceAsString(e);
        this.textAreaErr.setValue(stackTrace);
        this.textAreaErr.setVisible(true);
        Notification.show("Do isch was falsch, Nachricht: ", e.getMessage(), Notification.Type.ERROR_MESSAGE);

    }

}
```

<p><br>
In table event valueChange are just a notification for testing purpose:</p>

```private void table_valueChange(final Property.ValueChangeEvent event) {
    Notification.show("Kuck a mole: ", this.table.getSelectedItem().getBean().getGroupName()
            , Notification.Type.ERROR_MESSAGE);

}
```

```All help would be appreciated
Thanks in advance
```

答:
I am happy, because I found a solution with a help of my friend!

It was still my fault (as expected :-) ). I used the wrong container type:

I used:

```<code>            final BeanItemContainer<TGroup> mySubClasses = new BeanItemContainer<>(TGroup.class);
</code>```

But it was the wrong container!

I should use instead:

```<code>final XdevBeanItemContainer<TGroup> mySubClasses = new XdevBeanItemContainer<>(TGroup.class);
</code>```

After I changed it, everything worked fine.

I also searched in the documentation for a hint how I could prevent this for future, but without success.

Body:
With RapidClipse I build a page with three elements.
A drop-down field, a XdevTable and a XDevfieldGroup.

The drop-down field is filled by database table content (works fine)

The table should be filled after selecting a value out of drop-down field (works fine)

After selecting a value out of the XDevTable the related row should be editable by the fieldgroup.

After selecting  a row in the table I get a null-pointer exeption:

Mai 27, 2019 4:41:19 PM com.vaadin.server.DefaultErrorHandler doDefault
    SCHWERWIEGEND:
    java.lang.NullPointerException
at
com.xdev.ui.entitycomponent.table.AbstractBeanTable.getSelectedItem(AbstractBeanTable.java:180)
at com.xdev.ui.masterdetail.FieldGroupMasterDetailConnection.lambda$0(FieldGroupMasterDetailConnection.java:64)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.vaadin.event.ListenerMethod.receiveEvent(ListenerMethod.java:510)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:200)
at com.vaadin.event.EventRouter.fireEvent(EventRouter.java:163)
at com.vaadin.server.AbstractClientConnector.fireEvent(AbstractClientConnector.java:1015)
at com.vaadin.ui.AbstractField.fireValueChange(AbstractField.java:1161)
at com.vaadin.ui.AbstractField.setValue(AbstractField.java:571)
at com.vaadin.ui.AbstractSelect.setValue(AbstractSelect.java:735)
at com.vaadin.ui.AbstractField.setValue(AbstractField.java:468)
at com.vaadin.ui.AbstractSelect.changeVariables(AbstractSelect.java:547)
at com.vaadin.ui.Table.changeVariables(Table.java:2933)
at com.vaadin.server.communication.ServerRpcHandler.changeVariables(ServerRpcHandler.java:616)
at com.vaadin.server.communication.ServerRpcHandler.handleInvocation(ServerRpcHandler.java:463)
at com.vaadin.server.communication.ServerRpcHandler.handleInvocations(ServerRpcHandler.java:406)
at com.vaadin.server.communication.ServerRpcHandler.handleRpc(ServerRpcHandler.java:273)
at com.vaadin.server.communication.UidlRequestHandler.synchronizedHandleRequest(UidlRequestHandler.java:90)
at com.vaadin.server.SynchronizedRequestHandler.handleRequest(SynchronizedRequestHandler.java:41)
at com.vaadin.server.VaadinService.handleRequest(VaadinService.java:1435)
at com.vaadin.server.VaadinServlet.service(VaadinServlet.java:380)
at com.xdev.communication.XdevServlet.service(XdevServlet.java:212)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:493)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:660)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:798)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:808)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1498)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

If I am right, I assume, that there is a leak identifying the item which is selected in the table.
But I still did what/how is described in RapidClipse Training.
So the connection between table and fieldgroup is done by the property "ConnectedForm" inside the table.

The connection from drop-down field to table is done by following code:

private void comboBox_valueChange(final Property.ValueChangeEvent event) {

    try {

        Integer varMainClass = 0;
        varMainClass = this.comboBox.getSelectedItem().getBean().getId();

        Notification.show("Kuck a mole: ", this.comboBox.getSelectedItem().getBean().getGroupName()
                , Notification.Type.ERROR_MESSAGE);

        final BeanItemContainer<TGroup> mySubClasses = new BeanItemContainer<>(TGroup.class);
        mySubClasses.addAll(new TGroupDAO().getAllSubClassByMainClassId(varMainClass));
        this.table.setContainerDataSource(mySubClasses);
        this.table.setVisibleColumns("id", "groupName");
        this.table.setVisible(true);
    } catch (final Exception e) {
        e.printStackTrace();
        final String stackTrace = Throwables.getStackTraceAsString(e);
        this.textAreaErr.setValue(stackTrace);
        this.textAreaErr.setVisible(true);
        Notification.show("Do isch was falsch, Nachricht: ", e.getMessage(), Notification.Type.ERROR_MESSAGE);

    }

}

In table event valueChange are just a notification for testing purpose:

private void table_valueChange(final Property.ValueChangeEvent event) {
    Notification.show("Kuck a mole: ", this.table.getSelectedItem().getBean().getGroupName()
            , Notification.Type.ERROR_MESSAGE);

}

All help would be appreciated
Thanks in advance

Body:
I am happy, because I found a solution with a help of my friend!

It was still my fault (as expected :-) ). I used the wrong container type:

I used:

            final BeanItemContainer<TGroup> mySubClasses = new BeanItemContainer<>(TGroup.class);

But it was the wrong container!

I should use instead:

final XdevBeanItemContainer<TGroup> mySubClasses = new XdevBeanItemContainer<>(TGroup.class);

After I changed it, everything worked fine.

I also searched in the documentation for a hint how I could prevent this for future, but without success.


问:
HTTP Error 404.3-Not Found in IIS 10
I use IIS version 10 and Windows 10 and VisualStudio 2015.

After I add WEB application  to IIS site and open it I get error:

```<code>HTTP Error 404.3 - Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.
</code>```

I installed IIS sub components from:

```<code>Control Panel -> Programs and Features -> Turn Windows features on or off
</code>```

As described in this post by Mekanik.

Here is screenshot of installed sub components:

But it didn't helped me and still I get the same error.

Any Idea why I keep getting this error above maybe it has something to do with version of IIS 10?

答:
I understand that this is an old issue but in case anyone else comes across it:

It is related to Handler mapping, you need the svc-integrated mapping for the site in question:

Handler mapping in question

In order to make sure this mapping appears you need to go to control panel -> turn windows features on or off -> .NET Framework 4.7 Advanced Services (or equiv .net ver) -> WCF Services -> HTTP Activation

Turn on Http Activation and refresh IIS. This should add the mapping and fix the error.

Http Activation Feature Location

ContentLicense: CC BY-SA 3.0

Title: HTTP Error 404.3-Not Found in IIS 10

Body:
I use IIS version 10 and Windows 10 and VisualStudio 2015.

After I add WEB application  to IIS site and open it I get error:

HTTP Error 404.3 - Not Found

The page you are requesting cannot be served because of the extension configuration. If the page is a script, add a handler. If the file should be downloaded, add a MIME map.

I installed IIS sub components from:

Control Panel -> Programs and Features -> Turn Windows features on or off

As described in this post by Mekanik.

Here is screenshot of installed sub components:

But it didn't helped me and still I get the same error.

Any Idea why I keep getting this error above maybe it has something to do with version of IIS 10?


问:
What databases support UNION JOINs?
First of all, this item is like a curiosity to me.

I was writing some code for a utility library and was adding methods to run different kinds of SQL join statements. All good, but at some point I came across the obscure UNION JOIN clause included in the SQL-92 spec (page 179).

I don't know how useful it can be (I never used it) and it's implemented (AFAIK) in HyperSQL only.

For the record, here's how it works. If we have two tables T and U with any numbers of colums/rows:

```<code>====== T =====       === U ===

   a    b    c          d    e
---- ---- ----       ---- ----
   1    2    3         10   11
   4    5    6         12   13
</code>```

Then:

```<code>select * from T union join U
</code>```

Produces (in no particular row order):

```<code>   a    b    c    d    e
---- ---- ---- ---- ----
   1    2    3 null null
   4    5    6 null null
null null null   10   11
null null null   12   13
</code>```

Anyway, I wanted to know which databases do actually support it, or if you have seen it in the wild.

I was thinking about also asking what it can be good for, but I don't want this question to be closed as "Primarily Opinion Based".

答:
In theory, ANY SQL supports it

As documented in "SQL Problems and Solutions" by Moiseenko:

This join type have been introduced in SQL-92 language standard, but disappeared in later versions of SQL standard. Particularly, it is absent from SQL2003 (ANSI and ISO). As many other structures of SQL, UNION JOIN is excessive because it can be expressed as substraction of full outer join and inner join. Formally, we can write this expression as follows:

```<code>A UNION JOIN B :=
(A FULL JOIN B)
EXCEPT
(A INNER JOIN B)
</code>```

If DBMS does not support FULL JOIN (MySQL), it can be obtained via union of left and right outer joins. So our formula takes the form

```<code>A UNION JOIN B :=
((A LEFT JOIN B)
UNION
(A RIGHT JOIN B))
EXCEPT
(A INNER JOIN B)
</code>```

In practice, SAS supports it, at least version 9.3. Ref: http://support.sas.com/documentation/cdl/en/sqlproc/63043/HTML/default/viewer.htm#p0o4a5ac71mcchn1kc1zhxdnm139.htm

Title: What databases support UNION JOINs?

Body:
First of all, this item is like a curiosity to me.

I was writing some code for a utility library and was adding methods to run different kinds of SQL join statements. All good, but at some point I came across the obscure UNION JOIN clause included in the SQL-92 spec (page 179).

I don't know how useful it can be (I never used it) and it's implemented (AFAIK) in HyperSQL only.

For the record, here's how it works. If we have two tables T and U with any numbers of colums/rows:

====== T =====       === U ===

   a    b    c          d    e
---- ---- ----       ---- ----
   1    2    3         10   11
   4    5    6         12   13

Then:

select * from T union join U

Produces (in no particular row order):

   a    b    c    d    e
---- ---- ---- ---- ----
   1    2    3 null null
   4    5    6 null null
null null null   10   11
null null null   12   13

Anyway, I wanted to know which databases do actually support it, or if you have seen it in the wild.

I was thinking about also asking what it can be good for, but I don't want this question to be closed as "Primarily Opinion Based".

Body:
In theory, ANY SQL supports it

As documented in "SQL Problems and Solutions" by Moiseenko:

This join type have been introduced in SQL-92 language standard, but disappeared in later versions of SQL standard. Particularly, it is absent from SQL2003 (ANSI and ISO). As many other structures of SQL, UNION JOIN is excessive because it can be expressed as substraction of full outer join and inner join. Formally, we can write this expression as follows:

A UNION JOIN B :=
(A FULL JOIN B)
EXCEPT
(A INNER JOIN B)

If DBMS does not support FULL JOIN (MySQL), it can be obtained via union of left and right outer joins. So our formula takes the form

A UNION JOIN B :=
((A LEFT JOIN B)
UNION
(A RIGHT JOIN B))
EXCEPT
(A INNER JOIN B)

In practice, SAS supports it, at least version 9.3. Ref: http://support.sas.com/documentation/cdl/en/sqlproc/63043/HTML/default/viewer.htm#p0o4a5ac71mcchn1kc1zhxdnm139.htm


问:
How to add days to Date?
How to add days to current Date using JavaScript? Does JavaScript have a built in function like .NET's AddDay()?

答:
You can create one with:-

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

var date = new Date();

console.log(date.addDays(5));```

This takes care of automatically incrementing the month if necessary. For example:

8/31 + 1 day will become 9/1.

The problem with using setDate directly is that it's a mutator and that sort of thing is best avoided. ECMA saw fit to treat Date as a mutable class rather than an immutable structure.

OwnerDisplayName: Ashesh

Title: How to add days to Date?

Body:
You can create one with:-

Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date;
}

var date = new Date();

console.log(date.addDays(5));

This takes care of automatically incrementing the month if necessary. For example:

8/31 + 1 day will become 9/1.

The problem with using setDate directly is that it's a mutator and that sort of thing is best avoided. ECMA saw fit to treat Date as a mutable class rather than an immutable structure.

OwnerDisplayName: AnthonyWJones


问:
How to set default values for fields in records in Clojure?
I am creating records in Clojure and would like to set some fields up with a default value. How can I do this?</p>

答:
You can pass initial values to a record pretty easily when you construct it though an extension map:

```<code>(defrecord Foo [])

(def foo (Foo. nil {:bar 1 :baz 2}))
</code>```

In light of this, I usually create a constructor function that merges in some default values (which you can override as you want):

```<code>(defn make-foo [values-map]
  (let [default-values {:bar 1 :baz 2}]
    (Foo. nil (merge default-values values-map))))

(make-foo {:fiz 3 :bar 8})
=> #:user.Foo{:fiz 3, :bar 8, :baz 2}
</code>```

Body:
You can pass initial values to a record pretty easily when you construct it though an extension map:

(defrecord Foo [])

(def foo (Foo. nil {:bar 1 :baz 2}))

In light of this, I usually create a constructor function that merges in some default values (which you can override as you want):

(defn make-foo [values-map]
  (let [default-values {:bar 1 :baz 2}]
    (Foo. nil (merge default-values values-map))))

(make-foo {:fiz 3 :bar 8})
=> #:user.Foo{:fiz 3, :bar 8, :baz 2}