问:
Azure ARM template - set application settings and diagnostic log setitngs
I ran into an issue running arm template for an app service where II want to configure application settings and diagnostic log settings.

```<code>{

            "type": "Microsoft.Web/sites",
            "name": "[parameters('azureWebsiteName')]",
            "apiVersion": "[variables('appServiceApiVersion')]",
            "location": "[variables('location')]",
            "tags": {
                "Solution": "[parameters('solutionType')]",
                "Sku": "[parameters('solutionSku')]"
            },
            "properties": {
                "enabled": true,
                "clientAffinityEnabled": false,
                "serverFarmId": "[variables('hostingPlanName')]",
                "siteConfig": {
                    "alwaysOn": true,
                    "siteAuthEnabled": true,
                    "siteAuthSettings": {
                        "clientId": "[parameters('aadClientId')]",
                        "clientSecret": "[parameters('aadClientSecret')]",
                        "unauthenticatedClientAction": "[parameters('apiSiteUnauthenticatedClientAction')]",
                        "defaultProvider": "[parameters('apiSiteDefaultProvider')]",
                        "allowedAudiences": [
                            "[parameters('aadAppIdUri')]"
                        ]
                    },
                    "appSettings": [ ]
                }
            },
            "identity": {
                "type": "SystemAssigned"
            },
            "dependsOn": [
                "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]"
            ],
            "resources": [
                {
                    "type": "config",
                    "name": "appsettings",
                    "apiVersion": "[variables('appServiceApiVersion')]",
                    "dependsOn": [
                        "[resourceId('Microsoft.Web/sites/', parameters('azureWebsiteName'))]",
                        "[resourceId('Microsoft.Web/sites/config/', parameters('azureWebsiteName'), 'logs')]",
                        "[resourceId('microsoft.insights/components/', parameters('appInsightsName'))]",
                        "Microsoft.ApplicationInsights.AzureWebSites",
                        "[resourceId('Microsoft.KeyVault/vaults/', parameters('keyVaultName'))]",
                        "[resourceId('Microsoft.KeyVault/vaults/secrets', parameters('keyVaultName'), variables('storageAccountConnectionString'))]",
                        "[resourceId('Microsoft.KeyVault/vaults/secrets', parameters('keyVaultName'), variables('documentDBAccessKey'))]"
                    ],
                    "properties": {
                        "AzureWebJobsStorage": "[concat('@Microsoft.KeyVault(SecretUri=', reference(variables('storageAccountConnectionString')).secretUriWithVersion, ')')]"
                }
                },
                {
                    "type": "config",
                    "name": "logs",
                    "apiVersion": "[variables('appServiceApiVersion')]",
                    "dependsOn": [
                        "[resourceId('Microsoft.Web/sites/', parameters('azureWebsiteName'))]",
                        "[resourceId('Microsoft.Storage/storageAccounts/', parameters('storageName'))]",
                        "[concat('Microsoft.Storage/storageAccounts/', parameters('storageName'), '/blobServices/default/containers/', variables('appLogsContainerName'))]",
                        "[concat('Microsoft.Storage/storageAccounts/', parameters('storageName'), '/blobServices/default/containers/', variables('webServerLogsContainerName'))]"
                    ],
                    "properties": {
                        "httpLogs": {
                            "azureBlobStorage": {
                                "sasUrl": "[concat('https://',parameters('storageName'),'.blob.core.windows.net/',variables('webServerLogsContainerName'),'?',listServiceSas(parameters('storageName'), '2018-11-01', variables('webServerLogsSasProperties')).serviceSasToken)]",
                                "retentionInDays": "[parameters('diagnosticsLogsRetentionInDays')]",
                                "enabled": true
                            }
                        },
                        "failedRequestsTracing": {
                            "enabled": true
                        },
                        "detailedErrorMessages": {
                            "enabled": true
                        }
                    }
                },
                {
                    "type": "siteextensions",
                    "name": "Microsoft.ApplicationInsights.AzureWebSites",
                    "apiVersion": "[variables('appServiceApiVersion')]",
                    "dependsOn": [
                        "[resourceId('Microsoft.Web/Sites', parameters('azureWebsiteName'))]"
                    ],
                    "properties": {}
                }
            ]
        }
</code>```

The problem is when I deploy this, the logs config is set temporarily set then somehow gets un-set.
I believe it has something to do with multiple config objects(one for app-settings and one for logs) f I were to remove the app-settings config, the logs are correctly set and remain set.

Can someone help me understand what is happening?
Thanks!

答:
Figured it out. I needed to add a dependency in logs on app settings.

```<code>"dependsOn": [
...
"[resourceId('Microsoft.Web/sites/config/', parameters('azureWebsiteName'), 'appsettings')]"
...
]
</code>```

So the logs config will look like

```<code>        {
            "type": "config",
            "name": "logs",
            "apiVersion": "[variables('appServiceApiVersion')]",
            "dependsOn": [
                "[resourceId('Microsoft.Web/sites/', parameters('azureWebsiteName'))]",
                "[resourceId('Microsoft.Web/sites/config/', parameters('azureWebsiteName'), 'appsettings')]",
                "[resourceId('Microsoft.Storage/storageAccounts/', parameters('storageName'))]",
                "[concat('Microsoft.Storage/storageAccounts/', parameters('storageName'), '/blobServices/default/containers/', variables('appLogsContainerName'))]",
                "[concat('Microsoft.Storage/storageAccounts/', parameters('storageName'), '/blobServices/default/containers/', variables('webServerLogsContainerName'))]"
            ],
            "properties": {
                "applicationLogs": {
                    "azureBlobStorage": {
                        "level": "[parameters('diagnosticsLogsLevel')]",
                        "sasUrl": "[concat(reference(concat('Microsoft.Storage/storageAccounts/', parameters('storageName'))).primaryEndpoints.blob, variables('appLogsContainerName'), '?', listAccountSas(parameters('storageName'), variables('storageApiVersion'), variables('listAccountSasRequestContent')).accountSasToken)]",
                        "retentionInDays": "[parameters('diagnosticsLogsRetentionInDays')]"
                    }
                },
                "httpLogs": {
                    "azureBlobStorage": {
                        "sasUrl": "[concat(reference(concat('Microsoft.Storage/storageAccounts/', parameters('storageName'))).primaryEndpoints.blob, variables('webServerLogsContainerName'), '?', listAccountSas(parameters('storageName'), variables('storageApiVersion'), variables('listAccountSasRequestContent')).accountSasToken)]",
                        "retentionInDays": "[parameters('diagnosticsLogsRetentionInDays')]",
                        "enabled": true
                    }
                },
                "failedRequestsTracing": {
                    "enabled": true
                },
                "detailedErrorMessages": {
                    "enabled": true
                }
            }
        },
</code>```

Body:
I ran into an issue running arm template for an app service where II want to configure application settings and diagnostic log settings.

{

            "type": "Microsoft.Web/sites",
            "name": "[parameters('azureWebsiteName')]",
            "apiVersion": "[variables('appServiceApiVersion')]",
            "location": "[variables('location')]",
            "tags": {
                "Solution": "[parameters('solutionType')]",
                "Sku": "[parameters('solutionSku')]"
            },
            "properties": {
                "enabled": true,
                "clientAffinityEnabled": false,
                "serverFarmId": "[variables('hostingPlanName')]",
                "siteConfig": {
                    "alwaysOn": true,
                    "siteAuthEnabled": true,
                    "siteAuthSettings": {
                        "clientId": "[parameters('aadClientId')]",
                        "clientSecret": "[parameters('aadClientSecret')]",
                        "unauthenticatedClientAction": "[parameters('apiSiteUnauthenticatedClientAction')]",
                        "defaultProvider": "[parameters('apiSiteDefaultProvider')]",
                        "allowedAudiences": [
                            "[parameters('aadAppIdUri')]"
                        ]
                    },
                    "appSettings": [ ]
                }
            },
            "identity": {
                "type": "SystemAssigned"
            },
            "dependsOn": [
                "[resourceId('Microsoft.Web/serverfarms', variables('hostingPlanName'))]"
            ],
            "resources": [
                {
                    "type": "config",
                    "name": "appsettings",
                    "apiVersion": "[variables('appServiceApiVersion')]",
                    "dependsOn": [
                        "[resourceId('Microsoft.Web/sites/', parameters('azureWebsiteName'))]",
                        "[resourceId('Microsoft.Web/sites/config/', parameters('azureWebsiteName'), 'logs')]",
                        "[resourceId('microsoft.insights/components/', parameters('appInsightsName'))]",
                        "Microsoft.ApplicationInsights.AzureWebSites",
                        "[resourceId('Microsoft.KeyVault/vaults/', parameters('keyVaultName'))]",
                        "[resourceId('Microsoft.KeyVault/vaults/secrets', parameters('keyVaultName'), variables('storageAccountConnectionString'))]",
                        "[resourceId('Microsoft.KeyVault/vaults/secrets', parameters('keyVaultName'), variables('documentDBAccessKey'))]"
                    ],
                    "properties": {
                        "AzureWebJobsStorage": "[concat('@Microsoft.KeyVault(SecretUri=', reference(variables('storageAccountConnectionString')).secretUriWithVersion, ')')]"
                }
                },
                {
                    "type": "config",
                    "name": "logs",
                    "apiVersion": "[variables('appServiceApiVersion')]",
                    "dependsOn": [
                        "[resourceId('Microsoft.Web/sites/', parameters('azureWebsiteName'))]",
                        "[resourceId('Microsoft.Storage/storageAccounts/', parameters('storageName'))]",
                        "[concat('Microsoft.Storage/storageAccounts/', parameters('storageName'), '/blobServices/default/containers/', variables('appLogsContainerName'))]",
                        "[concat('Microsoft.Storage/storageAccounts/', parameters('storageName'), '/blobServices/default/containers/', variables('webServerLogsContainerName'))]"
                    ],
                    "properties": {
                        "httpLogs": {
                            "azureBlobStorage": {
                                "sasUrl": "[concat('https://',parameters('storageName'),'.blob.core.windows.net/',variables('webServerLogsContainerName'),'?',listServiceSas(parameters('storageName'), '2018-11-01', variables('webServerLogsSasProperties')).serviceSasToken)]",
                                "retentionInDays": "[parameters('diagnosticsLogsRetentionInDays')]",
                                "enabled": true
                            }
                        },
                        "failedRequestsTracing": {
                            "enabled": true
                        },
                        "detailedErrorMessages": {
                            "enabled": true
                        }
                    }
                },
                {
                    "type": "siteextensions",
                    "name": "Microsoft.ApplicationInsights.AzureWebSites",
                    "apiVersion": "[variables('appServiceApiVersion')]",
                    "dependsOn": [
                        "[resourceId('Microsoft.Web/Sites', parameters('azureWebsiteName'))]"
                    ],
                    "properties": {}
                }
            ]
        }

The problem is when I deploy this, the logs config is set temporarily set then somehow gets un-set.
I believe it has something to do with multiple config objects(one for app-settings and one for logs) f I were to remove the app-settings config, the logs are correctly set and remain set.

Can someone help me understand what is happening?
Thanks!

Body:
Figured it out. I needed to add a dependency in logs on app settings.

"dependsOn": [
...
"[resourceId('Microsoft.Web/sites/config/', parameters('azureWebsiteName'), 'appsettings')]"
...
]

So the logs config will look like

        {
            "type": "config",
            "name": "logs",
            "apiVersion": "[variables('appServiceApiVersion')]",
            "dependsOn": [
                "[resourceId('Microsoft.Web/sites/', parameters('azureWebsiteName'))]",
                "[resourceId('Microsoft.Web/sites/config/', parameters('azureWebsiteName'), 'appsettings')]",
                "[resourceId('Microsoft.Storage/storageAccounts/', parameters('storageName'))]",
                "[concat('Microsoft.Storage/storageAccounts/', parameters('storageName'), '/blobServices/default/containers/', variables('appLogsContainerName'))]",
                "[concat('Microsoft.Storage/storageAccounts/', parameters('storageName'), '/blobServices/default/containers/', variables('webServerLogsContainerName'))]"
            ],
            "properties": {
                "applicationLogs": {
                    "azureBlobStorage": {
                        "level": "[parameters('diagnosticsLogsLevel')]",
                        "sasUrl": "[concat(reference(concat('Microsoft.Storage/storageAccounts/', parameters('storageName'))).primaryEndpoints.blob, variables('appLogsContainerName'), '?', listAccountSas(parameters('storageName'), variables('storageApiVersion'), variables('listAccountSasRequestContent')).accountSasToken)]",
                        "retentionInDays": "[parameters('diagnosticsLogsRetentionInDays')]"
                    }
                },
                "httpLogs": {
                    "azureBlobStorage": {
                        "sasUrl": "[concat(reference(concat('Microsoft.Storage/storageAccounts/', parameters('storageName'))).primaryEndpoints.blob, variables('webServerLogsContainerName'), '?', listAccountSas(parameters('storageName'), variables('storageApiVersion'), variables('listAccountSasRequestContent')).accountSasToken)]",
                        "retentionInDays": "[parameters('diagnosticsLogsRetentionInDays')]",
                        "enabled": true
                    }
                },
                "failedRequestsTracing": {
                    "enabled": true
                },
                "detailedErrorMessages": {
                    "enabled": true
                }
            }
        },


来源: stackexchange

问:
Is there a way to convert an array of bytes to a number in C++?
I have read 4 bytes as an array from a file from a SD-Card on an Arduino Mega. Now I want to convert this array in one number, so that I can work with the number as integer(The bytes are a length of the next File section). Is there any included function for my problem or must I code my own?

I read the File into the byte array with the file.read() function from SDFat:

byte array[4]; //creates the byte array
file.read(array,4); //reads 4 bytes from the file and stores it in the array
```

I hope, you can understand my Problem.

答:
It depends on the endianess of the stored bytes.
If the endianess matches the one of your target system (I believe the Atmegas are big endian) you can just do

```<code>int32_t number = *(int32_t*)array;
</code>```

to get a 32 bit integer.

If the endianess is not matching you have to shift the bytes around yourself, for a little endian encoded number:

```<code>int32_t number = uint32_t(array[3]) << 24 | uint32_t(array[2]) << 16 | uint32_t(array[1]) << 8 | uint32_t(array[0]);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have read 4 bytes as an array from a file from a SD-Card on an Arduino Mega. Now I want to convert this array in one number, so that I can work with the number as integer(The bytes are a length of the next File section). Is there any included function for my problem or must I code my own?

I read the File into the byte array with the file.read() function from SDFat:

byte array[4]; //creates the byte array
file.read(array,4); //reads 4 bytes from the file and stores it in the array

I hope, you can understand my Problem.

Body:
It depends on the endianess of the stored bytes.
If the endianess matches the one of your target system (I believe the Atmegas are big endian) you can just do

int32_t number = *(int32_t*)array;

to get a 32 bit integer.

If the endianess is not matching you have to shift the bytes around yourself, for a little endian encoded number:

int32_t number = uint32_t(array[3]) << 24 | uint32_t(array[2]) << 16 | uint32_t(array[1]) << 8 | uint32_t(array[0]);


问:
How to use gather() function for multiple value arguments in R
I am new in the tidyverse data manipulation and I am using gather() function from the tidyr package for changing from wide to long form on my data.

I have the following data dataframe:

```<code>id <- 1:10
stim_1_ACC <- 0.5:10
stim_2_ACC <- 10:19
stim_1_RT <- 0.4:10
stim_2_RT <- 15:24
data <- data.frame(id,stim_1_ACC,stim_2_ACC,stim_1_RT,stim_2_RT)
</code>```

I would have one column for stim in which I have stim1 and stim2 as values, and two columns ACC and RT as numeric variables.

With gather() function I can select only one value argument and so having doing what I want only for one variable.

```<code>data %>%
  gather(key = "Stimuli", value = "ACC", 2:5)
</code>```

I reach my goal with multiple steps, splitting and then binding dataframe columns, but I'm looking for a more tidy approach. Final results would be like this:

```<code>   id   stim  ACC  RT
1   1 stim_1  1.5 900
2   2 stim_1  2.5 901
3   3 stim_1  3.5 902
4   4 stim_1  4.5 903
5   5 stim_1  5.5 904
6   6 stim_2  6.5 905
7   7 stim_2  7.5 906
8   8 stim_2  8.5 907
9   9 stim_2  9.5 908
10 10 stim_2 10.5 909
</code>```

Thanks!

答:
Probably , after gathering you'll need to use extract/separate to separate "stim.." and "RT"/"ACC" component and then use spread

```<code>library(dplyr)
library(tidyr)

data %>%
  gather(key, value, -id) %>%
  extract(key, into = c("stim", "temp"), regex = "(stim_\\d+)_(.*)") %>%
  spread(temp, value)
</code>```

Body:
I am new in the tidyverse data manipulation and I am using gather() function from the tidyr package for changing from wide to long form on my data.

I have the following data dataframe:

id <- 1:10
stim_1_ACC <- 0.5:10
stim_2_ACC <- 10:19
stim_1_RT <- 0.4:10
stim_2_RT <- 15:24
data <- data.frame(id,stim_1_ACC,stim_2_ACC,stim_1_RT,stim_2_RT)

I would have one column for stim in which I have stim1 and stim2 as values, and two columns ACC and RT as numeric variables.

With gather() function I can select only one value argument and so having doing what I want only for one variable.

data %>%
  gather(key = "Stimuli", value = "ACC", 2:5)

I reach my goal with multiple steps, splitting and then binding dataframe columns, but I'm looking for a more tidy approach. Final results would be like this:

   id   stim  ACC  RT
1   1 stim_1  1.5 900
2   2 stim_1  2.5 901
3   3 stim_1  3.5 902
4   4 stim_1  4.5 903
5   5 stim_1  5.5 904
6   6 stim_2  6.5 905
7   7 stim_2  7.5 906
8   8 stim_2  8.5 907
9   9 stim_2  9.5 908
10 10 stim_2 10.5 909

Thanks!

Body:
Probably , after gathering you'll need to use extract/separate to separate "stim.." and "RT"/"ACC" component and then use spread

library(dplyr)
library(tidyr)

data %>%
  gather(key, value, -id) %>%
  extract(key, into = c("stim", "temp"), regex = "(stim_\\d+)_(.*)") %>%
  spread(temp, value)


问:
unable to update state using react useState
I am learning react hooks. In my code I have set the initial values  for plotting map as

```<code>//map state
const [mapData, setMapData] = useState(
    { lat: 40.712776, lng: -74.0059, zoom: 5 }
);
</code>```

In the useEffect() call back I am loading the map once

```<code>useEffect(() => {
    initMap();
}, []); // run once
</code>```

Inside the initMap() there is map.on() method to get the updated geo locations. The initMap() is

```<code>const initMap = () => {
    mapboxgl.accessToken = 'token';
    const map = new mapboxgl.Map({
        container: mapContainer,
        style: 'mapbox://styles/mapbox/streets-v11',
        center: [mapData.lng, mapData.lat],
        zoom: mapData.zoom
    }); // load the map with init values

    // update the `mapData` as map move
    map.on('moveend', () => {
        const { lng, lat } = map.getCenter(); // logs the updated lat and lon
        setMapData({ lat: lat.toFixed(4), lng: lng.toFixed(4), zoom: map.getZoom().toFixed(2) }); // suppose to set the updated value
        console.log(mapData); // not logging updated values!
    });
}
</code>```

The setMapData() is not setting the state. But the map.on is called and is logging the values.

答:
setState is asynchronous, updated state may or may not be available to statements following it.

Use an effect hook that runs on a mapData update to react to changes.

```<code>useEffect(() => console.log(mapData), [mapData])
</code>```

Body:
I am learning react hooks. In my code I have set the initial values  for plotting map as

//map state
const [mapData, setMapData] = useState(
    { lat: 40.712776, lng: -74.0059, zoom: 5 }
);

In the useEffect() call back I am loading the map once

useEffect(() => {
    initMap();
}, []); // run once

Inside the initMap() there is map.on() method to get the updated geo locations. The initMap() is

const initMap = () => {
    mapboxgl.accessToken = 'token';
    const map = new mapboxgl.Map({
        container: mapContainer,
        style: 'mapbox://styles/mapbox/streets-v11',
        center: [mapData.lng, mapData.lat],
        zoom: mapData.zoom
    }); // load the map with init values

    // update the `mapData` as map move
    map.on('moveend', () => {
        const { lng, lat } = map.getCenter(); // logs the updated lat and lon
        setMapData({ lat: lat.toFixed(4), lng: lng.toFixed(4), zoom: map.getZoom().toFixed(2) }); // suppose to set the updated value
        console.log(mapData); // not logging updated values!
    });
}

The setMapData() is not setting the state. But the map.on is called and is logging the values.

Body:
setState is asynchronous, updated state may or may not be available to statements following it.

Use an effect hook that runs on a mapData update to react to changes.

useEffect(() => console.log(mapData), [mapData])


问:
Using ternary for if else
I’m having this if-else condition..

```<code>if UIDevice.current.iPad {
    if APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc {
        theImage.contentMode = .scaleAspectFill
    } else {
        theImage.contentMode = .scaleToFill
    }
} else {
    theImage.contentMode = .scaleAspectFill
}
</code>```

How can I use a ternary operator instead of this if-else condition..

I referred this link..but it didn’t help

答:
You can break down it in to </p>

```<code>theImage.contentMode = APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc ? .scaleAspectFill : .scaleToFill
</code>```

Title: Using ternary for if else

Body:
I’m having this if-else condition..

if UIDevice.current.iPad {
    if APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc {
        theImage.contentMode = .scaleAspectFill
    } else {
        theImage.contentMode = .scaleToFill
    }
} else {
    theImage.contentMode = .scaleAspectFill
}

How can I use a ternary operator instead of this if-else condition..

I referred this link..but it didn’t help

Body:
You can break down it in to

theImage.contentMode = APIClient.shared.whiteLabel == .gld_default || APIClient.shared.whiteLabel == .abc ? .scaleAspectFill : .scaleToFill


问:
What are allowed characters for a submodule name in registerModule?
registerModule() expects a submodule key as a third parameter.

I think it should probably not contain a space and only alphabetic characters (or alphanumeric?) and underscore ('_'), but I'm not really sure.

I could not find specific information for this.

答:
I found this in the documentation just now:

```<code>Backend modules

1. The modkey is made up of alphanumeric characters only. It does not contain underscores and starts with a letter.
</code>```

https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ExtensionArchitecture/NamingConventions/Index.html

Body:
I found this in the documentation just now:

Backend modules

1. The modkey is made up of alphanumeric characters only. It does not contain underscores and starts with a letter.

https://docs.typo3.org/m/typo3/reference-coreapi/master/en-us/ExtensionArchitecture/NamingConventions/Index.html


问:
Sum up two columns using a trigger in mysql and Find the percentage
## HOW TO SUM UP AND FIND PERCENTAGE TWO COLUMNS IN MYSQL USING A TRIGGER  ##
I have tried creating a trigger to sum up two of my columns using the SUM function in mysql.Trigger is created successfully but upon data inserting i found out that the trigger is not working.Kindly help me out.

```<code>CREATE TRIGGER StudentPopulation
BEFORE INSERT ON studentable
FOR EACH ROW
   SET NEW.total = ((NEW.`NUMBER_OF_MALES`)/(SUM(NEW.`NUMBER_OF_MALES`)+ SUM(NEW.`NUMBER_OF_FEMALES`))) * 100;
</code>```

答:
Since MySQL 5.7.5 you don't need a trigger - you can use a generated column where you just provide the expression and leave all the heavy lifting to the database:</p>

```<code>CREATE TABLE mytable (
    col_a INT,
    col_b INT,
    sum_a_b INT AS (col_a + col_b)
);
</code>```

Body:
## HOW TO SUM UP AND FIND PERCENTAGE TWO COLUMNS IN MYSQL USING A TRIGGER  ##
I have tried creating a trigger to sum up two of my columns using the SUM function in mysql.Trigger is created successfully but upon data inserting i found out that the trigger is not working.Kindly help me out.

CREATE TRIGGER StudentPopulation
BEFORE INSERT ON studentable
FOR EACH ROW
   SET NEW.total = ((NEW.`NUMBER_OF_MALES`)/(SUM(NEW.`NUMBER_OF_MALES`)+ SUM(NEW.`NUMBER_OF_FEMALES`))) * 100;

Body:
Since MySQL 5.7.5 you don't need a trigger - you can use a generated column where you just provide the expression and leave all the heavy lifting to the database:

CREATE TABLE mytable (
    col_a INT,
    col_b INT,
    sum_a_b INT AS (col_a + col_b)
);


问:
Is there a way to include the react-select dropdown near the body tag
I have react-select included in my react application which is using react-bootstrap.

So I have a bootstrap modal, and the react select inside it, the problem is that the modal body is set to overflow auto, and the react select dropdown now instead of overlapping the modal, actually produces a scroll and is partially hidden.

Is there any way I can ask the options list to render outside the bootstrap modal (while the react-select input sits inside the modal)?

React select dropdown inside modal (Image)

答:
Doing this works:

For the style:

```<code>    menuPortal: (provided) => ({
        ...provided,
        zIndex: 9999,
    }),
</code>```

On the component:

```<code>    menuPortalTarget={document.body}
</code>```

Body:
Doing this works:

For the style:

    menuPortal: (provided) => ({
        ...provided,
        zIndex: 9999,
    }),

On the component:

    menuPortalTarget={document.body}


问:
How can I insert a new contact by using ContentProviderOperation
I have a form like below image and I want to add a new a contact by click on button add and using ContentProviderOperation for this

How can I do this ? Thanks you so much!!

And this is my onlick method

```<code>btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            edtName = (EditText) findViewById(R.id.edtName);
            edtPhone = (EditText) findViewById(R.id.edtPhone);
            edtEmail = (EditText) findViewById(R.id.edtEmail);

        }
    });
</code>```

答:
Before adding a contact you have to enable permission into the manifest file.

Android Manifest:

```<code> <uses-permission android:name="android.permission.WRITE_CONTACTS" />
</code>```

after adding permission.I have created one activity for adding contacts.

AddPhoneContactActivity.java file

```<code>import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.test.example.R;

public class AddPhoneContactActivity extends AppCompatActivity {

private EditText displayNameEditor;

private EditText phoneNumberEditor;

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

    setTitle("dev2qa.com - Android Add Phone Contact Example.");

    displayNameEditor = (EditText)findViewById(R.id.add_phone_contact_display_name);

    phoneNumberEditor = (EditText)findViewById(R.id.add_phone_contact_number);

    // Initialize phone type dropdown spinner.
    final Spinner phoneTypeSpinner = (Spinner)findViewById(R.id.add_phone_contact_type);
    String phoneTypeArr[] = {"Mobile", "Home", "Work"};
    ArrayAdapter<String> phoneTypeSpinnerAdaptor = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, phoneTypeArr);
    phoneTypeSpinner.setAdapter(phoneTypeSpinnerAdaptor);

    // Click this button to save user input phone contact info.
    Button savePhoneContactButton = (Button)findViewById(R.id.add_phone_contact_save_button);
    savePhoneContactButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Get android phone contact content provider uri.
            //Uri addContactsUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            // Below uri can avoid java.lang.UnsupportedOperationException: URI: content://com.android.contacts/data/phones error.
            Uri addContactsUri = ContactsContract.Data.CONTENT_URI;

            // Add an empty contact and get the generated id.
            long rowContactId = getRawContactId();

            // Add contact name data.
            String displayName = displayNameEditor.getText().toString();
            insertContactDisplayName(addContactsUri, rowContactId, displayName);

            // Add contact phone data.
            String phoneNumber = phoneNumberEditor.getText().toString();
            String phoneTypeStr = (String)phoneTypeSpinner.getSelectedItem();
            insertContactPhoneNumber(addContactsUri, rowContactId, phoneNumber, phoneTypeStr);

            Toast.makeText(getApplicationContext(),"New contact has been added, go back to previous page to see it in contacts list." , Toast.LENGTH_LONG).show();

            finish();
        }
    });
}

// This method will only insert an empty data to RawContacts.CONTENT_URI
// The purpose is to get a system generated raw contact id.
private long getRawContactId()
{
    // Inser an empty contact.
    ContentValues contentValues = new ContentValues();
    Uri rawContactUri = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, contentValues);
    // Get the newly created contact raw id.
    long ret = ContentUris.parseId(rawContactUri);
    return ret;
}

// Insert newly created contact display name.
private void insertContactDisplayName(Uri addContactsUri, long rawContactId, String displayName)
{
    ContentValues contentValues = new ContentValues();

    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);

    // Each contact must has an mime type to avoid java.lang.IllegalArgumentException: mimetype is required error.
    contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);

    // Put contact display name value.
    contentValues.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, displayName);

    getContentResolver().insert(addContactsUri, contentValues);

}

private void insertContactPhoneNumber(Uri addContactsUri, long rawContactId, String phoneNumber, String phoneTypeStr)
{
    // Create a ContentValues object.
    ContentValues contentValues = new ContentValues();

    // Each contact must has an id to avoid java.lang.IllegalArgumentException: raw_contact_id is required error.
    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);

    // Each contact must has an mime type to avoid java.lang.IllegalArgumentException: mimetype is required error.
    contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);

    // Put phone number value.
    contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber);

    // Calculate phone type by user selection.
    int phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;

    if("home".equalsIgnoreCase(phoneTypeStr))
    {
        phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
    }else if("mobile".equalsIgnoreCase(phoneTypeStr))
    {
        phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
    }else if("work".equalsIgnoreCase(phoneTypeStr))
    {
        phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_WORK;
    }
    // Put phone type value.
    contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, phoneContactType);

    // Insert new contact data into phone contact list.
    getContentResolver().insert(addContactsUri, contentValues);

}

// ListPhoneContactsActivity use this method to start this activity.
public static void start(Context context)
{
    Intent intent = new Intent(context, AddPhoneContactActivity.class);
    context.startActivity(intent);
}
</code>```

}

activity_addcontact.xml

```<code><LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="1dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:width="0dp"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Display Name : "
        android:gravity="right"/>

    <EditText
        android:id="@+id/add_phone_contact_display_name"
        android:layout_weight="2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:width="0dp"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Phone Number : "
        android:gravity="right" />

    <EditText
        android:id="@+id/add_phone_contact_number"
        android:layout_weight="2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:width="0dp"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Phone Type : "
        android:gravity="right" />

    <Spinner
        android:id="@+id/add_phone_contact_type"
        android:layout_weight="1.3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:spinnerMode="dropdown"/>

</LinearLayout>

<Button
    android:id="@+id/add_phone_contact_save_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Save Phone Contact"/>
</code>```

Body:
I have a form like below image and I want to add a new a contact by click on button add and using ContentProviderOperation for this

How can I do this ? Thanks you so much!!

And this is my onlick method

btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            edtName = (EditText) findViewById(R.id.edtName);
            edtPhone = (EditText) findViewById(R.id.edtPhone);
            edtEmail = (EditText) findViewById(R.id.edtEmail);

        }
    });

Body:
Before adding a contact you have to enable permission into the manifest file.

Android Manifest:

 <uses-permission android:name="android.permission.WRITE_CONTACTS" />

after adding permission.I have created one activity for adding contacts.

AddPhoneContactActivity.java file

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.test.example.R;

public class AddPhoneContactActivity extends AppCompatActivity {

private EditText displayNameEditor;

private EditText phoneNumberEditor;

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

    setTitle("dev2qa.com - Android Add Phone Contact Example.");

    displayNameEditor = (EditText)findViewById(R.id.add_phone_contact_display_name);

    phoneNumberEditor = (EditText)findViewById(R.id.add_phone_contact_number);

    // Initialize phone type dropdown spinner.
    final Spinner phoneTypeSpinner = (Spinner)findViewById(R.id.add_phone_contact_type);
    String phoneTypeArr[] = {"Mobile", "Home", "Work"};
    ArrayAdapter<String> phoneTypeSpinnerAdaptor = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, phoneTypeArr);
    phoneTypeSpinner.setAdapter(phoneTypeSpinnerAdaptor);

    // Click this button to save user input phone contact info.
    Button savePhoneContactButton = (Button)findViewById(R.id.add_phone_contact_save_button);
    savePhoneContactButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Get android phone contact content provider uri.
            //Uri addContactsUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            // Below uri can avoid java.lang.UnsupportedOperationException: URI: content://com.android.contacts/data/phones error.
            Uri addContactsUri = ContactsContract.Data.CONTENT_URI;

            // Add an empty contact and get the generated id.
            long rowContactId = getRawContactId();

            // Add contact name data.
            String displayName = displayNameEditor.getText().toString();
            insertContactDisplayName(addContactsUri, rowContactId, displayName);

            // Add contact phone data.
            String phoneNumber = phoneNumberEditor.getText().toString();
            String phoneTypeStr = (String)phoneTypeSpinner.getSelectedItem();
            insertContactPhoneNumber(addContactsUri, rowContactId, phoneNumber, phoneTypeStr);

            Toast.makeText(getApplicationContext(),"New contact has been added, go back to previous page to see it in contacts list." , Toast.LENGTH_LONG).show();

            finish();
        }
    });
}

// This method will only insert an empty data to RawContacts.CONTENT_URI
// The purpose is to get a system generated raw contact id.
private long getRawContactId()
{
    // Inser an empty contact.
    ContentValues contentValues = new ContentValues();
    Uri rawContactUri = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, contentValues);
    // Get the newly created contact raw id.
    long ret = ContentUris.parseId(rawContactUri);
    return ret;
}

// Insert newly created contact display name.
private void insertContactDisplayName(Uri addContactsUri, long rawContactId, String displayName)
{
    ContentValues contentValues = new ContentValues();

    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);

    // Each contact must has an mime type to avoid java.lang.IllegalArgumentException: mimetype is required error.
    contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);

    // Put contact display name value.
    contentValues.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, displayName);

    getContentResolver().insert(addContactsUri, contentValues);

}

private void insertContactPhoneNumber(Uri addContactsUri, long rawContactId, String phoneNumber, String phoneTypeStr)
{
    // Create a ContentValues object.
    ContentValues contentValues = new ContentValues();

    // Each contact must has an id to avoid java.lang.IllegalArgumentException: raw_contact_id is required error.
    contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);

    // Each contact must has an mime type to avoid java.lang.IllegalArgumentException: mimetype is required error.
    contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);

    // Put phone number value.
    contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber);

    // Calculate phone type by user selection.
    int phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;

    if("home".equalsIgnoreCase(phoneTypeStr))
    {
        phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_HOME;
    }else if("mobile".equalsIgnoreCase(phoneTypeStr))
    {
        phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE;
    }else if("work".equalsIgnoreCase(phoneTypeStr))
    {
        phoneContactType = ContactsContract.CommonDataKinds.Phone.TYPE_WORK;
    }
    // Put phone type value.
    contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, phoneContactType);

    // Insert new contact data into phone contact list.
    getContentResolver().insert(addContactsUri, contentValues);

}

// ListPhoneContactsActivity use this method to start this activity.
public static void start(Context context)
{
    Intent intent = new Intent(context, AddPhoneContactActivity.class);
    context.startActivity(intent);
}

}

activity_addcontact.xml

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="1dp">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:width="0dp"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Display Name : "
        android:gravity="right"/>

    <EditText
        android:id="@+id/add_phone_contact_display_name"
        android:layout_weight="2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:width="0dp"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Phone Number : "
        android:gravity="right" />

    <EditText
        android:id="@+id/add_phone_contact_number"
        android:layout_weight="2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:width="0dp"
        android:layout_weight="1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Phone Type : "
        android:gravity="right" />

    <Spinner
        android:id="@+id/add_phone_contact_type"
        android:layout_weight="1.3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:spinnerMode="dropdown"/>

</LinearLayout>

<Button
    android:id="@+id/add_phone_contact_save_button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Save Phone Contact"/>


问:
Python calculating Catalan Numbers
I have code which is calculating catalan numbers with method of Binominal Coefficients.

```<code>def BinominalCoefficient(n,k):
    res = 1;
    if (k > n - k):
        k = n - k
    for i in range(k):
        res *= (n - i)
        res /= (i + 1)
    return res
def CatalanNumbers(n):
   c = BinominalCoefficient(2*n, n)
   return (c//(n+1))
print (CatalanNumbers(510))
</code>```

I have a "nan" result when i try to calculate Catalan number which n is more than 510. Why this is happening? And how can i solve it?

答:
In addition to xnx's answer, note that starting Python 3.8, with the addition of math.comb (binomial coefficient) in the standard library, we can also calculate Catalan numbers as such:

```<code>import math

def catalan(n):
  return math.comb(2*n, n) / (n+1)

catalan(511) # 2.1902514917394773e+303
</code>```

ContentLicense: CC BY-SA 3.0

Title: Python calculating Catalan Numbers

Body:
I have code which is calculating catalan numbers with method of Binominal Coefficients.

def BinominalCoefficient(n,k):
    res = 1;
    if (k > n - k):
        k = n - k
    for i in range(k):
        res *= (n - i)
        res /= (i + 1)
    return res
def CatalanNumbers(n):
   c = BinominalCoefficient(2*n, n)
   return (c//(n+1))
print (CatalanNumbers(510))

I have a "nan" result when i try to calculate Catalan number which n is more than 510. Why this is happening? And how can i solve it?

Body:
In addition to xnx's answer, note that starting Python 3.8, with the addition of math.comb (binomial coefficient) in the standard library, we can also calculate Catalan numbers as such:

import math

def catalan(n):
  return math.comb(2*n, n) / (n+1)

catalan(511) # 2.1902514917394773e+303


问:
Old values get duplication in For each loop
I am getting values from Firebase. But the problem occur when i try to add values in array previous values get repeated. Can anyone tell me how can i put values in Array . i want to show those values in recyclerview.

Code :

```<code>    bookCollection
            .get().addOnSuccessListener {
                booksSnapshot->
                if (!booksSnapshot.isEmpty){
                    var booksArray = arrayListOf<Book>()
                    for (bookSnapshot in booksSnapshot.documents){
                        val hashmap = bookSnapshot.data
                        hashmap?.put("id", bookSnapshot.id)
                        bookCollection.document(bookSnapshot.id).collection("pages")
                                .get().addOnSuccessListener {
                                    pagesSnapshot->
                                    hashmap?.put("page_count", pagesSnapshot.documents.size)
                                    val bookData = Gson().toJson(hashmap)
                                    val book = Gson().fromJson<Book>(bookData, Book::class.java)
                                    booksArray.add(book)
                                }

                    }
                }
            }
</code>```

Log for array :

```<code>E/books: [co.myapp.myapplication.Book@d6f7f62]
E/books: [co.myapp.myapplication.Book@d6f7f62, co.syntags.myapplication.Book@93c49b0]
</code>```

Thanks in advance

答:
in main class (List add) :-

(Yourlistname).add(new yourpojoname(your value));

in PoJo class :-
create constructor :-

--> public constructorName(String s) { (Your value) = s; }

note :- yourpojoname == constructorName

Body:
I am getting values from Firebase. But the problem occur when i try to add values in array previous values get repeated. Can anyone tell me how can i put values in Array . i want to show those values in recyclerview.

Code :

    bookCollection
            .get().addOnSuccessListener {
                booksSnapshot->
                if (!booksSnapshot.isEmpty){
                    var booksArray = arrayListOf<Book>()
                    for (bookSnapshot in booksSnapshot.documents){
                        val hashmap = bookSnapshot.data
                        hashmap?.put("id", bookSnapshot.id)
                        bookCollection.document(bookSnapshot.id).collection("pages")
                                .get().addOnSuccessListener {
                                    pagesSnapshot->
                                    hashmap?.put("page_count", pagesSnapshot.documents.size)
                                    val bookData = Gson().toJson(hashmap)
                                    val book = Gson().fromJson<Book>(bookData, Book::class.java)
                                    booksArray.add(book)
                                }

                    }
                }
            }

Log for array :

E/books: [co.myapp.myapplication.Book@d6f7f62]
E/books: [co.myapp.myapplication.Book@d6f7f62, co.syntags.myapplication.Book@93c49b0]

Thanks in advance


问:
Set Background color for a selected item in a Select option (multiple)
I'm trying to change the background color of the selected items in a listbox (select multiple options).

I tried with css... I tried with  JavaScript... and with jquery... I really don't know what happen!! But I'm unable to find the answer :_(.

I read at least 10 questions in this forum.. and I tried all the proposed solutions but I only can change the background of the complete list... not the selected items. The only way I found is to use an unordered list with clickable list items instead if my select - option ... but I'm working with a form, and I want to send to the server the selected items in the traditional way.

答:
Doesn't look like it wants to play ball:

```<code><style>

::selection {
   background: #FF0000; /* Safari */
   }
::-moz-selection {
   background: #FF0000; /* Firefox */
}
</style>

<select multiple="true">
<option><span style="background:FF0000;">One</span></option>
<option>Two</option>
<option>Three</option>
</select>

<p>This is text.</p>
</code>```

This doesn't suprise me. In my experience widgets are generally resistant to such styling. Rolling your own, like in Hussein's approach, looks like your only way out.

Body:
Doesn't look like it wants to play ball:

<style>

::selection {
   background: #FF0000; /* Safari */
   }
::-moz-selection {
   background: #FF0000; /* Firefox */
}
</style>

<select multiple="true">
<option><span style="background:FF0000;">One</span></option>
<option>Two</option>
<option>Three</option>
</select>

<p>This is text.</p>

This doesn't suprise me. In my experience widgets are generally resistant to such styling. Rolling your own, like in Hussein's approach, looks like your only way out.


问:
If input not existing ( in dataset ) than display generic content
I'm working on a website with some kind of a JavaScript "input" tabs. Let say user type "running" in input and press submit than application display some quote about running, but when user type something that is not exist in predefined dataset (data-name) than application display  generic content.

Everything is working except generic content(class="generic").

How can I add generic content when input value is not existing in dataset values in the app section.

You can try in this fiddle: http://jsfiddle.net/e10nLbg2/1/

Here is my code:

```<code>.data, .generic {
    visibility: hidden;
    opacity: 0;
    background: blue;
    padding: 50px;
    color: white;
    transition: opacity 1s ease;
    position: absolute;
}

.active {
    visibility: visible;
    opacity: 1;
}

<input type="text" class="input">
<input type="submit" class="submit" value="SUBMIT">

<section class="app">

<div class="data" data-name="running">RUNNING - Lorem ipsum dolor sit...
</div>

<div class="data" data-name="walking">WALKING - Lorem ipsum dolor
sit...
</div>

<div class="generic">GENERIC - Lorem ipsum dolor sit...
</div>
</section>

var submit = document.querySelector('.submit');

submit.onclick = function(){
var input = document.querySelector('.input').value;
var e = input.toLowerCase();
var element = document.querySelector('[data-name="'+ e +'"]');

var generic = document.querySelector('.generic');
var active = document.querySelector('.active');

if(active){
  active.classList.remove('active');
  //generic.classList.add('active');
}else{
  //generic.classList.remove('active');
}

 element.classList.add('active');

}
</code>```

答:
On submit event you need to remove .active from active element and generic one as well, then set active the one that fits user input, else - set active generic:

var submit = document.querySelector('.submit');

 submit.onclick = function() {
     let e = document.querySelector('.input').value.toLowerCase();
     let element = document.querySelector('[data-name="'+ e +'"]');
     let generic = document.querySelector('.generic');
     let active = document.querySelector('.active');

     if (active) active.classList.remove('active');
     generic.classList.remove('active');

     if (element)
        element.classList.add('active');
     else
        generic.classList.add('active');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.data, .generic {
visibility: hidden;
opacity: 0;
background: blue;
padding: 50px;
color: white;
transition: opacity 1s ease;
position: absolute;
}

.active {
visibility: visible;
opacity: 1;
}

input {
height: 30px;
border-radius: 5px;
box-sizing: border-box;
outline: none;
}

input[type="text"] {
background: #e6e6e6;
color: grey;
outline: none;
padding: 15px;
border: 0;
}</code>```

<input type="text" class="input">
 <input type="submit" class="submit" value="SUBMIT">

RUNNING - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

PLAYING - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

DANCING - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

WALKING - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

GENERIC - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
```

Body:
I'm working on a website with some kind of a JavaScript "input" tabs. Let say user type "running" in input and press submit than application display some quote about running, but when user type something that is not exist in predefined dataset (data-name) than application display  generic content.

Everything is working except generic content(class="generic").

How can I add generic content when input value is not existing in dataset values in the app section.

You can try in this fiddle: http://jsfiddle.net/e10nLbg2/1/

Here is my code:

.data, .generic {
    visibility: hidden;
    opacity: 0;
    background: blue;
    padding: 50px;
    color: white;
    transition: opacity 1s ease;
    position: absolute;
}

.active {
    visibility: visible;
    opacity: 1;
}

<input type="text" class="input">
<input type="submit" class="submit" value="SUBMIT">

RUNNING - Lorem ipsum dolor sit...

WALKING - Lorem ipsum dolor
sit...

GENERIC - Lorem ipsum dolor sit...

var submit = document.querySelector('.submit');

submit.onclick = function(){
var input = document.querySelector('.input').value;
var e = input.toLowerCase();
var element = document.querySelector('[data-name="'+ e +'"]');

var generic = document.querySelector('.generic');
var active = document.querySelector('.active');

if(active){
  active.classList.remove('active');
  //generic.classList.add('active');
}else{
  //generic.classList.remove('active');
}

 element.classList.add('active');

}

Body:
On submit event you need to remove .active from active element and generic one as well, then set active the one that fits user input, else - set active generic:

var submit = document.querySelector('.submit');

 submit.onclick = function() {
     let e = document.querySelector('.input').value.toLowerCase();
     let element = document.querySelector('[data-name="'+ e +'"]');
     let generic = document.querySelector('.generic');
     let active = document.querySelector('.active');

     if (active) active.classList.remove('active');
     generic.classList.remove('active');

     if (element)
        element.classList.add('active');
     else
        generic.classList.add('active');
}

.data, .generic {
visibility: hidden;
opacity: 0;
background: blue;
padding: 50px;
color: white;
transition: opacity 1s ease;
position: absolute;
}

.active {
visibility: visible;
opacity: 1;
}

input {
height: 30px;
border-radius: 5px;
box-sizing: border-box;
outline: none;
}

input[type="text"] {
background: #e6e6e6;
color: grey;
outline: none;
padding: 15px;
border: 0;
}

<input type="text" class="input">
 <input type="submit" class="submit" value="SUBMIT">

 <div class="data" data-name="running">RUNNING - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>

 <div class="data" data-name="playing">PLAYING - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>

 <div class="data" data-name="dancing">DANCING - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>

 <div class="data" data-name="walking">WALKING - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>

 <div class="generic">GENERIC - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>


问:
How to evaluate the Database size requirements for OBIEE 12c
Experts,

We are considering OBIEE12c implementation. How to evaluate what should be the Database size requirement for OBIEE 12c metadata( MDS and BIPLATFORM items)? is there a rule which we follow?

Details:
App: OBIEE 12c
database: Oracle 12c

Oracle Official guidelines no mention any thing for Enterprise Edition however they 500MB DB size is sufficient for single user. However, nothing is mentioned about enterprise installation.

Any rule or calculation we follow for sizing the Database?

答:
As always: It depends.

It depends on how many users and how much they do. How many Agents, how many Scorecards, how many annotations,  etc etc.

I never saw this run into issues as  even 500GB are a glorified USB stick.


问:
How does Wikipedia make its search field?
I would like to know how Wikipedia does its search field.  What I mean by this is two things:  Its gradient and its button.

How does it make a gradient in the field?  This can be easily done with CSS cross browser at this point, but when you do the IE CSS code, it aliases the text.  Wikipedia has a gradient background, but the text is still anti-aliased!  How do they do that?

Also, how did they put a clickable search button INSIDE the text field?

Thanks.

答: It appears that the actual search input has no styling -- meaning no border and a transparent background.  The containing div is styled to look like an input field (border and gradient).  The clickable button is inside the div but not inside the actual input element.</p>


问:
How do I count the number of records that have one or more associated object?
I have a Property model that has_many :photos. I want to count the number of properties that have one or more photo.

How do I do that?

I have tried the simple:

```<code>> Property.where('properties.photos.count > ?', 0).count

   (3.1ms)  SELECT COUNT(*) FROM "properties" WHERE (properties.photos.count > 1)
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
                                                  ^
: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos.count > 0)
from /ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
</code>```

to:

```<code>> Property.joins(:photos).where('photos.count > ?', 0).count

   (3.7ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
: SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
</code>```

to the more advanced:

```<code>>Property.includes(:photos).group(['property.id', 'photos.id']).order('COUNT(photos.id) DESC').count

(0.6ms)  SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
                                                             ^
: SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
</code>```

and a few other variations, and they all produce similar errors.

What am I doing wrong?

Note: All I want is the count of properties that have photos.count > 0. I don't want a hash of all the properties and the count of photos. In other words, if there are 5000 properties in my db, I want to build a scope that returns just the properties that actually have photos.

答:
According to your requirement you can try this

1) A simple count of the number of properties that have 1 or more
  photo

To just get the number of properties which have one or more photo you can do this

```<code>Property.joins(:photos).distinct.count
</code>```

As we are not using group the distinct or uniq is necessary. distinct will return ActiveRecord_Relation and uniq will return Array.

2) I would like that set of properties returned so I can
  create a scope of just those properties. Also, I do have lots of
  properties with more than 1 photo.

To get all the property objects which have one or more than one photo you can use the same query:

```<code>Property.joins(:photos).distinct
</code>```

or you can use the group_by clause:

```<code>Property.joins(:photos).group('properties.id')
</code>```

The difference will be that when you will use size method on the group query it will return a hash with the property_id as key and number of photos on the property as value.

Performance Update:

If you always require the count of associated object and you want to fetch it efficiently you may use counter_cache like this:

```<code>class Photo < ApplicationRecord
  belongs_to :property, counter_cache: true
end

class Property < ApplicationRecord
  has_many :photos
end
</code>```

And then you will have to add a column in the properties table named photos_count and Rails will automatically update the column each time a new photo record is added or a exisisting photo record is removed. And then you can also query directly:

```<code>Property.where('photos_count > ?', 1)
</code>```

This is optional and you can do this if you are facing performance issues with the data fetch.

Body:
I have a Property model that has_many :photos. I want to count the number of properties that have one or more photo.

How do I do that?

I have tried the simple:

> Property.where('properties.photos.count > ?', 0).count

   (3.1ms)  SELECT COUNT(*) FROM "properties" WHERE (properties.photos.count > 1)
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....
                                                  ^
: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos.count > 0)
from /ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "photos"
LINE 1: SELECT COUNT(*) FROM "properties"  WHERE (properties.photos....

to:

> Property.joins(:photos).where('photos.count > ?', 0).count

   (3.7ms)  SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
ActiveRecord::StatementInvalid: PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...
                                                             ^
: SELECT COUNT(*) FROM "properties" INNER JOIN "photos" ON "photos"."property_id" = "properties"."id" WHERE (photos.count > 0)
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::GroupingError: ERROR:  aggregate functions are not allowed in WHERE
LINE 1: ..."photos"."property_id" = "properties"."id" WHERE (photos.cou...

to the more advanced:

>Property.includes(:photos).group(['property.id', 'photos.id']).order('COUNT(photos.id) DESC').count

(0.6ms)  SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...
                                                             ^
: SELECT COUNT(DISTINCT "properties"."id") AS count_id, property.id AS property_id, photos.id AS photos_id FROM "properties" LEFT OUTER JOIN "photos" ON "photos"."property_id" = "properties"."id" GROUP BY property.id, photos.id ORDER BY COUNT(photos.id) DESC
from ruby-2.3.0@myproject/gems/activerecord-3.2.22.5/lib/active_record/connection_adapters/postgresql_adapter.rb:1163:in `async_exec'
Caused by PG::UndefinedTable: ERROR:  missing FROM-clause entry for table "property"
LINE 1: ...CT COUNT(DISTINCT "properties"."id") AS count_id, property.i...

and a few other variations, and they all produce similar errors.

What am I doing wrong?

Note: All I want is the count of properties that have photos.count > 0. I don't want a hash of all the properties and the count of photos. In other words, if there are 5000 properties in my db, I want to build a scope that returns just the properties that actually have photos.

Body:
According to your requirement you can try this

1) A simple count of the number of properties that have 1 or more
  photo

To just get the number of properties which have one or more photo you can do this

Property.joins(:photos).distinct.count

As we are not using group the distinct or uniq is necessary. distinct will return ActiveRecord_Relation and uniq will return Array.

2) I would like that set of properties returned so I can
  create a scope of just those properties. Also, I do have lots of
  properties with more than 1 photo.

To get all the property objects which have one or more than one photo you can use the same query:

Property.joins(:photos).distinct

or you can use the group_by clause:

Property.joins(:photos).group('properties.id')

The difference will be that when you will use size method on the group query it will return a hash with the property_id as key and number of photos on the property as value.

Performance Update:

If you always require the count of associated object and you want to fetch it efficiently you may use counter_cache like this:

class Photo < ApplicationRecord
  belongs_to :property, counter_cache: true
end

class Property < ApplicationRecord
  has_many :photos
end

And then you will have to add a column in the properties table named photos_count and Rails will automatically update the column each time a new photo record is added or a exisisting photo record is removed. And then you can also query directly:

Property.where('photos_count > ?', 1)

This is optional and you can do this if you are facing performance issues with the data fetch.


问:
Is there any way in SQL or function in MYSQL that sums up all the increments in a column?
I want to find a way to sum up all the increments in the value of a column.

We provide delivery services to our customers. A customer can pay as he go, but if he pays an upfront fee, he gets a better deal. There is a table that has the balance of the customer across the time. So I want to sum all the increments to the balance. I can't change the way the payment is recorded.

I have alredy coded an stored procedure that works, but is kind slow, so I'm looking for alternatives. I think that, maybe, an sql statement that can do this task, can outperform my stored procedure that has loops.

My stored procedure makes a select of the customer in a given date range, and insert the result in a temp table X. After that, it starts to pop rows from X table, comparing the balance value in that row against the previous row, and detects if there is an increment. If there is not increment, pops another row and do the same routine, if there is an increment, it calculates the difference between that row and the previous, and the result is inserted in another temp table Y.

When there are no rows left, the stored procedure performs a SUM in the temp table Y, and thus, you can know how much the customer has "refilled" its balance.

This is an example of the table X, and the expected result:

```<code>DATE        BALANCE
----        -------
2019-02-01  200
2019-02-02  195    //from 200 to 195 there is a decrement, so it doesn't matter
2019-02-03  180
2019-02-04  150
2019-02-05  175    //there is an increment from 150 to 175, it's 25 that must be inserted in the temp table
2019-02-06  140
2019-02-07  180    //there is another increment, from 140 to 180, it's 40
</code>```

So the resulting temp table Y must be something like this:

```<code>REFILL
------
25
40
</code>```

The expected result is 65. My stored procedure returns this value, but as I said, is kind slow (it takes about 22 seconds to process 3900 rows, equivalent to 3 days, aprox), I think is because the loops. I would like to explore another alternatives. Because some details that I don't mention here, for a single costumer, I can have 1300 rows per day (the example is given in days, but I have rows by the minute). My tables are indexed, I think properly. I can't post my stored procedure, but it works as described (I know that "The devil is in the detail"). So any suggestion will be appreciated.

答:
Use lag() in MySQL 8+:

```<code>select sum(balance - prev_balance) as refills
from (select t.*, lag(balance) over (order by date) prev_balance
      from t
     ) t
where balance > prev_balance;
</code>```

In older versions of MySQL this is tricky.  If the values are continuous dates, then a simple JOIN works:

```<code>select sum(t.balance - tprev.balance) as refills
from t join
     t tprev
     on tprev.date = t.date - 1
where t.balance > tprev.balance;
</code>```

This may not be the case.  Then the next best method is variables.  But you have to be very careful.  MySQL does not declare the order of evaluation of expressions in a SELECT.  As the documentation explains:

The order of evaluation for expressions involving user variables is undefined. For example, there is no guarantee that SELECT @a, @a:=@a+1 evaluates @a first and then performs the assignment.

The variables need to be assigned and used in the same expression:

```<code>select sum(balance - prev_balance) as refills
from (select t.*,
             (case when (@temp_prevb := @prevb) = NULL  -- intentionally false
                   then -1
                   when (@prevb := balance)
                   then @temp_prevb
              end) as prev_balance
      from (select t.* from t order by date) t cross join
           (select @prevb := NULL) params
     ) t
where balance > prev_balance;
</code>```

And the final method is a correlated subquery:

```<code>select sum(balance - prev_balance) as refills
from (select t.*,
             (select t2.balance
              from t t2
              where t2.date < t.date
              order by t2.date desc
             ) as prev_balance
      from t
     ) t
where balance > prev_balance;
</code>```

Body:
I want to find a way to sum up all the increments in the value of a column.

We provide delivery services to our customers. A customer can pay as he go, but if he pays an upfront fee, he gets a better deal. There is a table that has the balance of the customer across the time. So I want to sum all the increments to the balance. I can't change the way the payment is recorded.

I have alredy coded an stored procedure that works, but is kind slow, so I'm looking for alternatives. I think that, maybe, an sql statement that can do this task, can outperform my stored procedure that has loops.

My stored procedure makes a select of the customer in a given date range, and insert the result in a temp table X. After that, it starts to pop rows from X table, comparing the balance value in that row against the previous row, and detects if there is an increment. If there is not increment, pops another row and do the same routine, if there is an increment, it calculates the difference between that row and the previous, and the result is inserted in another temp table Y.

When there are no rows left, the stored procedure performs a SUM in the temp table Y, and thus, you can know how much the customer has "refilled" its balance.

This is an example of the table X, and the expected result:

DATE        BALANCE
----        -------
2019-02-01  200
2019-02-02  195    //from 200 to 195 there is a decrement, so it doesn't matter
2019-02-03  180
2019-02-04  150
2019-02-05  175    //there is an increment from 150 to 175, it's 25 that must be inserted in the temp table
2019-02-06  140
2019-02-07  180    //there is another increment, from 140 to 180, it's 40

So the resulting temp table Y must be something like this:

REFILL
------
25
40

The expected result is 65. My stored procedure returns this value, but as I said, is kind slow (it takes about 22 seconds to process 3900 rows, equivalent to 3 days, aprox), I think is because the loops. I would like to explore another alternatives. Because some details that I don't mention here, for a single costumer, I can have 1300 rows per day (the example is given in days, but I have rows by the minute). My tables are indexed, I think properly. I can't post my stored procedure, but it works as described (I know that "The devil is in the detail"). So any suggestion will be appreciated.

Body:
Use lag() in MySQL 8+:

select sum(balance - prev_balance) as refills
from (select t.*, lag(balance) over (order by date) prev_balance
      from t
     ) t
where balance > prev_balance;

In older versions of MySQL this is tricky.  If the values are continuous dates, then a simple JOIN works:

select sum(t.balance - tprev.balance) as refills
from t join
     t tprev
     on tprev.date = t.date - 1
where t.balance > tprev.balance;

This may not be the case.  Then the next best method is variables.  But you have to be very careful.  MySQL does not declare the order of evaluation of expressions in a SELECT.  As the documentation explains:

The order of evaluation for expressions involving user variables is undefined. For example, there is no guarantee that SELECT @a, @a:=@a+1 evaluates @a first and then performs the assignment.

The variables need to be assigned and used in the same expression:

select sum(balance - prev_balance) as refills
from (select t.*,
             (case when (@temp_prevb := @prevb) = NULL  -- intentionally false
                   then -1
                   when (@prevb := balance)
                   then @temp_prevb
              end) as prev_balance
      from (select t.* from t order by date) t cross join
           (select @prevb := NULL) params
     ) t
where balance > prev_balance;

And the final method is a correlated subquery:

select sum(balance - prev_balance) as refills
from (select t.*,
             (select t2.balance
              from t t2
              where t2.date < t.date
              order by t2.date desc
             ) as prev_balance
      from t
     ) t
where balance > prev_balance;


问:
Arabic labels do not display correctly in Geoserver
I have geoserver installed with Tomcat and the text labeling do not display correctly . where can i set the Arabic encoding in geosever?
the labeling appear well in QGIS but when i publish it in geoserver i get this problem .

]1

The shape file
 Here Is the SLD :

```<code>   <?xml version="1.0" encoding="UTF-8"?>
<sld:StyledLayerDescriptor xmlns="http://www.opengis.net/sld" xmlns:sld="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml" version="1.0.0">
    <sld:UserLayer>
        <sld:LayerFeatureConstraints>
            <sld:FeatureTypeConstraint/>
        </sld:LayerFeatureConstraints>
        <sld:UserStyle>
            <sld:Name>sea</sld:Name>
            <sld:Title/>
            <sld:IsDefault>1</sld:IsDefault>
            <sld:FeatureTypeStyle>
                <sld:Name>group 0</sld:Name>
                <sld:FeatureTypeName>Feature</sld:FeatureTypeName>
                <sld:SemanticTypeIdentifier>generic:geometry</sld:SemanticTypeIdentifier>
                <sld:SemanticTypeIdentifier>simple</sld:SemanticTypeIdentifier>
                <sld:Rule>
                    <sld:Name>default rule</sld:Name>
                    <sld:PolygonSymbolizer>
                        <sld:Fill>
                            <sld:CssParameter name="fill">#1B9E77</sld:CssParameter>
                            <sld:CssParameter name="fill-opacity">0.5</sld:CssParameter>
                        </sld:Fill>
                        <sld:Stroke>
                            <sld:CssParameter name="stroke">#1B9E77</sld:CssParameter>
                        </sld:Stroke>
                    </sld:PolygonSymbolizer>
                    <sld:TextSymbolizer>
                        <sld:Label>
                            <ogc:PropertyName>ARABIC</ogc:PropertyName>
                        </sld:Label>
                        <sld:Font>
                            <sld:CssParameter name="font-family">Arial</sld:CssParameter>
                            <sld:CssParameter name="font-size">12.0</sld:CssParameter>
                            <sld:CssParameter name="font-style">normal</sld:CssParameter>
                            <sld:CssParameter name="font-weight">bold</sld:CssParameter>
                        </sld:Font>
                        <sld:LabelPlacement>
                            <sld:PointPlacement>
                                <sld:AnchorPoint>
                                    <sld:AnchorPointX>0.5</sld:AnchorPointX>
                                    <sld:AnchorPointY>0.5</sld:AnchorPointY>
                                </sld:AnchorPoint>
                            </sld:PointPlacement>
                        </sld:LabelPlacement>
                        <sld:Fill>
                            <sld:CssParameter name="fill">#000000</sld:CssParameter>
                        </sld:Fill>
                        <sld:VendorOption name="spaceAround">2</sld:VendorOption>
                    </sld:TextSymbolizer>
                </sld:Rule>
            </sld:FeatureTypeStyle>
        </sld:UserStyle>
    </sld:UserLayer>
</sld:StyledLayerDescriptor>
</code>```

答:
The most common problem is that you have miss set the character encoding, check the store page:

With my test data I get this with a setting of "windows-1250"

Switching to the (in my case) correct "UTF-8" gives this, which is better.

And finally using a "better" font than Arial (Trocchi) fills out the Chinese as well as the Arabic characters.

Update

So experimenting with your shapefile and SLD and googling "windows arabic character set" led me to setting the Shapefile datastore DBF character set to "Windows-1256" which seems to work.

Body:
I have geoserver installed with Tomcat and the text labeling do not display correctly . where can i set the Arabic encoding in geosever?
the labeling appear well in QGIS but when i publish it in geoserver i get this problem .

]1

The shape file
 Here Is the SLD :

   <?xml version="1.0" encoding="UTF-8"?>
<sld:StyledLayerDescriptor xmlns="http://www.opengis.net/sld" xmlns:sld="http://www.opengis.net/sld" xmlns:ogc="http://www.opengis.net/ogc" xmlns:gml="http://www.opengis.net/gml" version="1.0.0">
    <sld:UserLayer>
        <sld:LayerFeatureConstraints>
            <sld:FeatureTypeConstraint/>
        </sld:LayerFeatureConstraints>
        <sld:UserStyle>
            <sld:Name>sea</sld:Name>
            <sld:Title/>
            <sld:IsDefault>1</sld:IsDefault>
            <sld:FeatureTypeStyle>
                <sld:Name>group 0</sld:Name>
                <sld:FeatureTypeName>Feature</sld:FeatureTypeName>
                <sld:SemanticTypeIdentifier>generic:geometry</sld:SemanticTypeIdentifier>
                <sld:SemanticTypeIdentifier>simple</sld:SemanticTypeIdentifier>
                <sld:Rule>
                    <sld:Name>default rule</sld:Name>
                    <sld:PolygonSymbolizer>
                        <sld:Fill>
                            <sld:CssParameter name="fill">#1B9E77</sld:CssParameter>
                            <sld:CssParameter name="fill-opacity">0.5</sld:CssParameter>
                        </sld:Fill>
                        <sld:Stroke>
                            <sld:CssParameter name="stroke">#1B9E77</sld:CssParameter>
                        </sld:Stroke>
                    </sld:PolygonSymbolizer>
                    <sld:TextSymbolizer>
                        <sld:Label>
                            <ogc:PropertyName>ARABIC</ogc:PropertyName>
                        </sld:Label>
                        <sld:Font>
                            <sld:CssParameter name="font-family">Arial</sld:CssParameter>
                            <sld:CssParameter name="font-size">12.0</sld:CssParameter>
                            <sld:CssParameter name="font-style">normal</sld:CssParameter>
                            <sld:CssParameter name="font-weight">bold</sld:CssParameter>
                        </sld:Font>
                        <sld:LabelPlacement>
                            <sld:PointPlacement>
                                <sld:AnchorPoint>
                                    <sld:AnchorPointX>0.5</sld:AnchorPointX>
                                    <sld:AnchorPointY>0.5</sld:AnchorPointY>
                                </sld:AnchorPoint>
                            </sld:PointPlacement>
                        </sld:LabelPlacement>
                        <sld:Fill>
                            <sld:CssParameter name="fill">#000000</sld:CssParameter>
                        </sld:Fill>
                        <sld:VendorOption name="spaceAround">2</sld:VendorOption>
                    </sld:TextSymbolizer>
                </sld:Rule>
            </sld:FeatureTypeStyle>
        </sld:UserStyle>
    </sld:UserLayer>
</sld:StyledLayerDescriptor>


问:
Laravel - Reportico not working
I am using Reportico reporting module, and follow the installation instructions listed on official website, but somehow its not working.

Here are the steps I followed:

I have created a fresh laravel project mentioned on laravel docs:

```<code>composer create-project --prefer-dist laravel/laravel blog
</code>```

Then within the project root directory, I executed the following command by using composer:

```<code>composer require reportico/laravel-reportico "~5.2"
</code>```

And remaining steps are same as listed on Reportico website. It did not give me any error message in the steps, but finally when I go to the url:

```<code>http://localhost:8000/index.php/reportico
</code>```

It is showing error message that route not found.

Can anybody suggest how to fix this, or is there any free-open-source reporting tool which I can use with Laravel project.

答:
I had the same issue.
Changing the url to below worked for me

```<code>http://localhost:8000/index.php/reportico
</code>```

Hope it helps someone.

Title: Laravel - Reportico not working

Body:
I am using Reportico reporting module, and follow the installation instructions listed on official website, but somehow its not working.

Here are the steps I followed:

I have created a fresh laravel project mentioned on laravel docs:

composer create-project --prefer-dist laravel/laravel blog

Then within the project root directory, I executed the following command by using composer:

composer require reportico/laravel-reportico "~5.2"

And remaining steps are same as listed on Reportico website. It did not give me any error message in the steps, but finally when I go to the url:

http://localhost:8000/index.php/reportico

It is showing error message that route not found.

Can anybody suggest how to fix this, or is there any free-open-source reporting tool which I can use with Laravel project.

Body:
I had the same issue.
Changing the url to below worked for me

http://localhost:8000/index.php/reportico

Hope it helps someone.


问:
Is there correct Getting Started documentation?
I try to include Vuetify into an existing Vue project following step by step the guide:

Vuetify quick-start existing-applications

Vuetify styles are not visible. This is possible duplicate but is has no answer: Vuetify Styles not visible

How to make Vuetify styles work correctly?

Github Vuetify account has 500+ opened issues. Maybe this one is already reported somewhere?

答:
After an investigation I found the Vuetify is so buggy, I wondered why developers use it!

Finally I created new application following the official guide
which is also buggy. Then I move all my functionality to the new app.

Anyway I was able to set up empty Vuetify template.

Please avoid using Vuetify if you hasn't started yet. It will be pain in your brain!

Update:

Vuetify do not have possibility to contact support. That was a reason I created my question on Stackoverflow! Do not be offended please Vuetify is fit only for coding experts who use to survive without documentation and support. If you are beginner be aware.


问:
Catch and print full Python exception traceback without halting/exiting the program
I want to catch and log exceptions without exiting, e.g.,

```<code>try:
    do_stuff()
except Exception as err:
    print(Exception, err)
    # I want to print the entire traceback here,
    # not just the exception name and details
</code>```

I want to print the exact same output that is printed when the exception is raised without the try/except intercepting the exception, and I do not want it to exit my program.

答:
I don't see this mentioned in any of the other answers. If you're passing around an Exception object for whatever reason...

In Python 3.5+ you can get a trace from an Exception object using traceback.TracebackException.from_exception(). For example:

```<code>import traceback

def stack_lvl_3():
    raise Exception('a1', 'b2', 'c3')

def stack_lvl_2():
    try:
        stack_lvl_3()
    except Exception as e:
        # raise
        return e

def stack_lvl_1():
    e = stack_lvl_2()
    return e

e = stack_lvl_1()

tb1 = traceback.TracebackException.from_exception(e)
print(''.join(tb1.format()))
</code>```

However, the above code results in:

```<code>Traceback (most recent call last):
  File "exc.py", line 10, in stack_lvl_2
    stack_lvl_3()
  File "exc.py", line 5, in stack_lvl_3
    raise Exception('a1', 'b2', 'c3')
Exception: ('a1', 'b2', 'c3')
</code>```

This is just two levels of the stack, as opposed to what would have been printed on screen had the exception been raised in stack_lvl_2() and not intercepted (uncomment the # raise line).

As I understand it, that's because an exception records only the current level of the stack when it is raised, stack_lvl_3() in this case. As it's passed back up through the stack, more levels are being added to its __traceback__. But we intercepted it in stack_lvl_2(), meaning all it got to record was levels 3 and 2. To get the full trace as printed on stdout we'd have to catch it at the highest (lowest?) level:

```<code>import traceback

def stack_lvl_3():
    raise Exception('a1', 'b2', 'c3')

def stack_lvl_2():
    stack_lvl_3()

def stack_lvl_1():
    stack_lvl_2()

try:
    stack_lvl_1()
except Exception as exc:
    tb = traceback.TracebackException.from_exception(exc)

print('Handled at stack lvl 0')
print(''.join(tb.stack.format()))
</code>```

Which results in:

```<code>Handled at stack lvl 0
  File "exc.py", line 17, in <module>
    stack_lvl_1()
  File "exc.py", line 13, in stack_lvl_1
    stack_lvl_2()
  File "exc.py", line 9, in stack_lvl_2
    stack_lvl_3()
  File "exc.py", line 5, in stack_lvl_3
    raise Exception('a1', 'b2', 'c3')
</code>```

Notice that the stack print is different, the first and last lines are missing. Because it's a different format().

Intercepting the exception as far away from the point where it was raised as possible makes for simpler code while also giving more information.

Body:
I want to catch and log exceptions without exiting, e.g.,

try:
    do_stuff()
except Exception as err:
    print(Exception, err)
    # I want to print the entire traceback here,
    # not just the exception name and details

I want to print the exact same output that is printed when the exception is raised without the try/except intercepting the exception, and I do not want it to exit my program.

Body:
I don't see this mentioned in any of the other answers. If you're passing around an Exception object for whatever reason...

In Python 3.5+ you can get a trace from an Exception object using traceback.TracebackException.from_exception(). For example:

import traceback

def stack_lvl_3():
    raise Exception('a1', 'b2', 'c3')

def stack_lvl_2():
    try:
        stack_lvl_3()
    except Exception as e:
        # raise
        return e

def stack_lvl_1():
    e = stack_lvl_2()
    return e

e = stack_lvl_1()

tb1 = traceback.TracebackException.from_exception(e)
print(''.join(tb1.format()))

However, the above code results in:

Traceback (most recent call last):
  File "exc.py", line 10, in stack_lvl_2
    stack_lvl_3()
  File "exc.py", line 5, in stack_lvl_3
    raise Exception('a1', 'b2', 'c3')
Exception: ('a1', 'b2', 'c3')

This is just two levels of the stack, as opposed to what would have been printed on screen had the exception been raised in stack_lvl_2() and not intercepted (uncomment the # raise line).

As I understand it, that's because an exception records only the current level of the stack when it is raised, stack_lvl_3() in this case. As it's passed back up through the stack, more levels are being added to its __traceback__. But we intercepted it in stack_lvl_2(), meaning all it got to record was levels 3 and 2. To get the full trace as printed on stdout we'd have to catch it at the highest (lowest?) level:

import traceback

def stack_lvl_3():
    raise Exception('a1', 'b2', 'c3')

def stack_lvl_2():
    stack_lvl_3()

def stack_lvl_1():
    stack_lvl_2()

try:
    stack_lvl_1()
except Exception as exc:
    tb = traceback.TracebackException.from_exception(exc)

print('Handled at stack lvl 0')
print(''.join(tb.stack.format()))

Which results in:

Handled at stack lvl 0
  File "exc.py", line 17, in <module>
    stack_lvl_1()
  File "exc.py", line 13, in stack_lvl_1
    stack_lvl_2()
  File "exc.py", line 9, in stack_lvl_2
    stack_lvl_3()
  File "exc.py", line 5, in stack_lvl_3
    raise Exception('a1', 'b2', 'c3')

Notice that the stack print is different, the first and last lines are missing. Because it's a different format().

Intercepting the exception as far away from the point where it was raised as possible makes for simpler code while also giving more information.


问:
how to just print the statement without any loop condition in java?
I just want to print the "hello" 5 times without using for loop,while loop ?</p>

答:
```<code>public String repeat(String str, int times){
   return new String(new char[times]).replace("\0", str);
}
//...
String bob = "bob ";
System.out.println(repeat(bob, 5));
</code>```