问:
add labels to alluvia in ggalluvial
Is there any possibility to add labels to the alluvia in ggalluvial?

Example plot:

```<code>library(ggalluvial)
data(vaccinations)
levels(vaccinations$response) <- rev(levels(vaccinations$response))
ggplot(vaccinations,
       aes(x = survey, stratum = response, alluvium = subject,
           y = freq,
           fill = response, label = response)) +
  scale_x_discrete(expand = c(.1, .1)) +
  geom_flow() +
  geom_stratum(alpha = .5) +
  geom_text(stat = "stratum", size = 3) +
  theme(legend.position = "none") +
  ggtitle("vaccination survey responses at three points in time")
</code>```

Now I would like to add the subject id/nrs as labels to the alluvia (not to the boxes).
Is there any possibility to do so?
My original Data has much less subjects per alluvia (e.g. 2-5).

答:
I'd love to know a better way to accomplish this! Here's an illustration of the least bad trick i've come across. The key changes from your code are as follows:

The aesthetic mapping label = response is moved from the ggplot() call to the (first) geom_text() layer, so that it doesn't interfere with other text layers.

The additional geom_text() layer is paired with the flow stat in order to label each "flow" graphical element. Note that there are more such elements than are distinguishable visually.

The new text layer uses the new aesthetic mapping label = as.character(subject); the subject (actually cohort) IDs are numerical, so omitting the coercion to character would result in them being meaninglessly added together. (Maybe this behavior should be controllable by a new parameter?)

The new text layer uses the aesthetic mapping color = survey == "ms153_NSA" in order to separate the first time point from the latter two, and the manual color scale makes the one invisible (note: NA would be more appropriate than "00000000") and the other black. Though see the note below. (Setting data = subset(vaccinations, survey != "ms_153_NSA") would appear to have the same effect, but actually it can confuse the labels, since the flow stat partitions the flows differently when the first time point is removed.)

The labels are offset from the strata onto the flows by nudge_x = -.25.

Note: Something like this can produce the desired behavior with the alluvium stat, but the flow stat results in overlaid labels at the middle time point (or any axis other than the first and last), which don't always agree since the flows are arranged differently on the left and right sides. There are some toy examples of both in the vignette about stratum and lode ordering. I don't think there's any way around this currently.

library(ggalluvial)
#> Loading required package: ggplot2
data(vaccinations)
levels(vaccinations$response) <- rev(levels(vaccinations$response))
ggplot(vaccinations,
       aes(x = survey, stratum = response, alluvium = subject,
           y = freq,
           fill = response)) +
  scale_x_discrete(expand = c(.1, .1)) +
  geom_flow() +
  geom_stratum(alpha = .5) +
  geom_text(aes(label = response),
            stat = "stratum", size = 3) +
  geom_text(aes(label = as.character(subject), color = survey == "ms153_NSA"),
            stat = "flow", size = 3, nudge_x = -.25) +
  scale_colour_manual(values = c("#000000ff", "#00000000")) +
  theme(legend.position = "none") +
  ggtitle("vaccination survey responses at three points in time")
```

Created on 2020-02-19 by the reprex package (v0.3.0)

Title: add labels to alluvia in ggalluvial

Body:
Is there any possibility to add labels to the alluvia in ggalluvial?

Example plot:

library(ggalluvial)
data(vaccinations)
levels(vaccinations$response) <- rev(levels(vaccinations$response))
ggplot(vaccinations,
       aes(x = survey, stratum = response, alluvium = subject,
           y = freq,
           fill = response, label = response)) +
  scale_x_discrete(expand = c(.1, .1)) +
  geom_flow() +
  geom_stratum(alpha = .5) +
  geom_text(stat = "stratum", size = 3) +
  theme(legend.position = "none") +
  ggtitle("vaccination survey responses at three points in time")

Now I would like to add the subject id/nrs as labels to the alluvia (not to the boxes).
Is there any possibility to do so?
My original Data has much less subjects per alluvia (e.g. 2-5).

Body:
I'd love to know a better way to accomplish this! Here's an illustration of the least bad trick i've come across. The key changes from your code are as follows:

The aesthetic mapping label = response is moved from the ggplot() call to the (first) geom_text() layer, so that it doesn't interfere with other text layers.

The additional geom_text() layer is paired with the flow stat in order to label each "flow" graphical element. Note that there are more such elements than are distinguishable visually.

The new text layer uses the new aesthetic mapping label = as.character(subject); the subject (actually cohort) IDs are numerical, so omitting the coercion to character would result in them being meaninglessly added together. (Maybe this behavior should be controllable by a new parameter?)

The new text layer uses the aesthetic mapping color = survey == "ms153_NSA" in order to separate the first time point from the latter two, and the manual color scale makes the one invisible (note: NA would be more appropriate than "00000000") and the other black. Though see the note below. (Setting data = subset(vaccinations, survey != "ms_153_NSA") would appear to have the same effect, but actually it can confuse the labels, since the flow stat partitions the flows differently when the first time point is removed.)

The labels are offset from the strata onto the flows by nudge_x = -.25.

Note: Something like this can produce the desired behavior with the alluvium stat, but the flow stat results in overlaid labels at the middle time point (or any axis other than the first and last), which don't always agree since the flows are arranged differently on the left and right sides. There are some toy examples of both in the vignette about stratum and lode ordering. I don't think there's any way around this currently.

library(ggalluvial)
#> Loading required package: ggplot2
data(vaccinations)
levels(vaccinations$response) <- rev(levels(vaccinations$response))
ggplot(vaccinations,
       aes(x = survey, stratum = response, alluvium = subject,
           y = freq,
           fill = response)) +
  scale_x_discrete(expand = c(.1, .1)) +
  geom_flow() +
  geom_stratum(alpha = .5) +
  geom_text(aes(label = response),
            stat = "stratum", size = 3) +
  geom_text(aes(label = as.character(subject), color = survey == "ms153_NSA"),
            stat = "flow", size = 3, nudge_x = -.25) +
  scale_colour_manual(values = c("#000000ff", "#00000000")) +
  theme(legend.position = "none") +
  ggtitle("vaccination survey responses at three points in time")

Created on 2020-02-19 by the reprex package (v0.3.0)


来源: stackexchange

问:
Faulty If, Else Statement
I always get the the Error: unexpected 'else' in "     else" in my If, Else Statement. </p>

<p>Pls help I've been sitting with this Error since two days and need to finish my paper till tomorrow. </p>

```<code>Isflorida <- function(data) {
  data <- filter(data,is.na(State)== FALSE)
  data$Isflorida <- vector(mode = "logical", length = nrow(data))
  for (i in 1:nrow(data)) {
    if (data[i,]$State == "Florida") {
      data[i,]$Isflorida <- TRUE }
    else {data[i,]$Isflorida <- FALSE}}data}
</code>```

答:
Wouldn't that be enough?</p>

```<code>data$IsFlorida <- ifelse(data$State=="Florida", TRUE, FALSE)
</code>```

ContentLicense: CC BY-SA 4.0

Title: Faulty If, Else Statement

Body:
I always get the the Error: unexpected 'else' in "     else" in my If, Else Statement.

Pls help I've been sitting with this Error since two days and need to finish my paper till tomorrow.

Isflorida <- function(data) {
  data <- filter(data,is.na(State)== FALSE)
  data$Isflorida <- vector(mode = "logical", length = nrow(data))
  for (i in 1:nrow(data)) {
    if (data[i,]$State == "Florida") {
      data[i,]$Isflorida <- TRUE }
    else {data[i,]$Isflorida <- FALSE}}data}

Body:
Wouldn't that be enough?

data$IsFlorida <- ifelse(data$State=="Florida", TRUE, FALSE)


问:
Why in2csv not converting my XLSX file with non-ascii sheet title? [CentOS x64]
My problem is that I have an Excel XLSX file with non-ascii sheet name (Общий отчет) and I'm trying to convert it to CSV using in2csv tool. I run it from PHP using exec function.

On my local machine (Windows 10 x64) it's workong OK. I'm trying to run it on the CsntOS x64 VDS, and when I start my PHP script (which uses exec to call in2csv tool) from terminal - it works OK too. But when I run it from cron (php -f ./task.php) - it produces no error but the resulting CSV file is blank!

I did some tests, checking user and group running PHP script, python default encoding, but still have no clue. Please help!

Here is the command to convert the file:

```<code>in2csv --locale ru_RU --sheet "Общий отчет" --encoding windows-1251 "prices.xlsx" > "prices.csv"
</code>```

答:
Finally I figured it out.

The command in PHP's exec function should look like this:

```<code>exec('/usr/bin/in2csv --locale ru_RU --sheet "Общий отчет" --encoding windows-1251 "/home/admin/www/html/prices.xlsx" > "/home/admin/www/html/prices.csv"');
</code>```

And the cron command should look like this:

```<code>/usr/bin/php -f /home/admin/www/html/task.php
</code>```

That is, you need to provide full paths to all executables, and this will work both in terminal and in Cron!

Body:
My problem is that I have an Excel XLSX file with non-ascii sheet name (Общий отчет) and I'm trying to convert it to CSV using in2csv tool. I run it from PHP using exec function.

On my local machine (Windows 10 x64) it's workong OK. I'm trying to run it on the CsntOS x64 VDS, and when I start my PHP script (which uses exec to call in2csv tool) from terminal - it works OK too. But when I run it from cron (php -f ./task.php) - it produces no error but the resulting CSV file is blank!

I did some tests, checking user and group running PHP script, python default encoding, but still have no clue. Please help!

Here is the command to convert the file:

in2csv --locale ru_RU --sheet "Общий отчет" --encoding windows-1251 "prices.xlsx" > "prices.csv"

Body:
Finally I figured it out.

The command in PHP's exec function should look like this:

exec('/usr/bin/in2csv --locale ru_RU --sheet "Общий отчет" --encoding windows-1251 "/home/admin/www/html/prices.xlsx" > "/home/admin/www/html/prices.csv"');

And the cron command should look like this:

/usr/bin/php -f /home/admin/www/html/task.php

That is, you need to provide full paths to all executables, and this will work both in terminal and in Cron!


问:
Save button in table
I have an array of data that is taken from the site and output to the table, I want to add a button that will store a certain row from the table in the database how can I implement it?</p>

```<code>   let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
   cell.textLabel?.text = news[indexPath.row].tittle

   let tipDouble = NumberFormatter().number(from: news[indexPath.row].time!)!.doubleValue
   let date = Date(timeIntervalSince1970: tipDouble)

   let dateFormatter = DateFormatter()
   dateFormatter.timeZone = TimeZone(abbreviation: "GMT+2") //Set timezone that you want
   dateFormatter.locale = NSLocale.current
   dateFormatter.dateFormat = "MM-dd HH:mm" //Specify your format that you want

   let strDate = dateFormatter.string(from: date)

   cell.detailTextLabel?.text = strDate

   return cell
</code>```

答:
Use Tag.
set a tag to button. Give Tag value as index path.row value. Then on Button click you can access the corresponding data(if array) at index.

Ex:

```<code>var arrData = ["5","6","7","8"]

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

   cell.button.tag = IndexPath.row

}

func buttonAction(sender:UIButton){

   let data = arrData[sender.tag]

}
</code>```

Title: Save button in table

Body:
I have an array of data that is taken from the site and output to the table, I want to add a button that will store a certain row from the table in the database how can I implement it?

   let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)
   cell.textLabel?.text = news[indexPath.row].tittle

   let tipDouble = NumberFormatter().number(from: news[indexPath.row].time!)!.doubleValue
   let date = Date(timeIntervalSince1970: tipDouble)

   let dateFormatter = DateFormatter()
   dateFormatter.timeZone = TimeZone(abbreviation: "GMT+2") //Set timezone that you want
   dateFormatter.locale = NSLocale.current
   dateFormatter.dateFormat = "MM-dd HH:mm" //Specify your format that you want

   let strDate = dateFormatter.string(from: date)

   cell.detailTextLabel?.text = strDate

   return cell

Body:
Use Tag.
set a tag to button. Give Tag value as index path.row value. Then on Button click you can access the corresponding data(if array) at index.

Ex:

var arrData = ["5","6","7","8"]

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

   cell.button.tag = IndexPath.row

}

func buttonAction(sender:UIButton){

   let data = arrData[sender.tag]

}


问:
how to clear JavaScript variable value after few minutes / seconds / times
I have set a value in JavaScript local variable which is given below:

```<code>document.getElementById("class").value = getSavedValue("class");    // set the value to this input
document.getElementById("group").value = getSavedValue("group");   // set the value to this input
document.getElementById("section").value = getSavedValue("section");   // set the value to this input
document.getElementById("session").value = getSavedValue("session");   // set the value to this input
document.getElementById("shift").value = getSavedValue("shift");   // set the value to this input
document.getElementById("version").value = getSavedValue("version");   // set the value to this input
/* Here you can add more inputs to set value. if it's saved */

//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
    var id = e.id;  // get the sender's id to save it .
    var val = e.value; // get the value.
    localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}

//get the saved value function - return the value of "v" from localStorage.
function getSavedValue  (v){
    if (!localStorage.getItem(v)) {
        return "";// You can change this to your defualt value.
    }
    return localStorage.getItem(v);
}
</code>```

i want to when its value is saved then a certain amount of time it only that (specific) variable will be unset / clear automatically.

Thank you

答:
Set a timeout each time the variable is stored. And, depending on what you want, maybe sessionStorage is a better option.</p>

```<code>function saveValue(e){
  var id = e.id;
  var val = e.value;
  localStorage.setItem(id, val);

  clearTimeout(localStorage.getItem(id + '_timeout'));

  var timeoutId = setTimeout(function() { localStorage.removeItem(id); }, 1000);

  localStorage.setItem(id + '_timeout', timeoutId);
}
</code>```

Body:
I have set a value in JavaScript local variable which is given below:

document.getElementById("class").value = getSavedValue("class");    // set the value to this input
document.getElementById("group").value = getSavedValue("group");   // set the value to this input
document.getElementById("section").value = getSavedValue("section");   // set the value to this input
document.getElementById("session").value = getSavedValue("session");   // set the value to this input
document.getElementById("shift").value = getSavedValue("shift");   // set the value to this input
document.getElementById("version").value = getSavedValue("version");   // set the value to this input
/* Here you can add more inputs to set value. if it's saved */

//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
    var id = e.id;  // get the sender's id to save it .
    var val = e.value; // get the value.
    localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}

//get the saved value function - return the value of "v" from localStorage.
function getSavedValue  (v){
    if (!localStorage.getItem(v)) {
        return "";// You can change this to your defualt value.
    }
    return localStorage.getItem(v);
}

i want to when its value is saved then a certain amount of time it only that (specific) variable will be unset / clear automatically.

Thank you

Body:
Set a timeout each time the variable is stored. And, depending on what you want, maybe sessionStorage is a better option.

function saveValue(e){
  var id = e.id;
  var val = e.value;
  localStorage.setItem(id, val);

  clearTimeout(localStorage.getItem(id + '_timeout'));

  var timeoutId = setTimeout(function() { localStorage.removeItem(id); }, 1000);

  localStorage.setItem(id + '_timeout', timeoutId);
}


问:
Why do I need a default docker network to start a common docker network for two docker-compose projects?
I've got two projects (a and b) which both have a docker-compose.yml file. I now want one of the projects to be able to call a service of the other project and as far as I know I need to create a common docker network for that. So to create a minimal example I made two folders (a/ and b/) which both contain a docker-compose.yml file.

This is the one in folder a/:

```<code>version: '3'

services:
  common_server:
    image: ubuntu
    ports:
      - 4444:4444
    command: >
      bash -c '
      apt update && apt install netcat -y &&
      while true; do echo -e "HTTP/1.1 200 OK\n\npong" | nc -k -l -p 4444 -q 1; done'
#    networks:
#      - my_network

  project_a:
    image: ubuntu
    depends_on:
      - common_server
#    networks:
#      - my_network
    command: >
      bash -c '
      apt update && apt install curl -y &&
      while true; do echo "Calling the container";  echo "AAAAAAAA"; curl common_server:4444; sleep 10; done'

#networks:
#  my_network:
#    driver: bridge
</code>```

This sets up two things:

common_server: a simple ping/pong server which responds "pong" to every request it gets

project_a: a simple client which calls the common_server every 10 seconds

This works great like this. I quickly checked the docker networks using:

```<code>$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
5ac503033848        a_default           bridge              local  <== THIS NETWORK WAS CREATED
1f65f9c91441        bridge              bridge              local
72fcb38f2060        host                host                local
b76cd7ef1ac9        none                null                local
</code>```

I've got a second docker-compose.yml file in the folder b/ from which I also want to call the common_server defined in the file above. So I uncommented the lines with the network in the file above to enable my_network. Running that also works great.

When I check docker network ls again I also see the second network it created:

```<code>$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
5ac503033848        a_default           bridge              local  <== CREATED BY THE FIRST RUN
f0a42e17007b        a_my_network        bridge              local  <== CREATED BY THE SECOND RUN
1f65f9c91441        bridge              bridge              local
72fcb38f2060        host                host                local
b76cd7ef1ac9        none                null                local
</code>```

I then started the second docker-compose file:

```<code>version: '3'

services:
  project_b:
    image: ubuntu
    command: >
      bash -c '
      apt update && apt install curl -y &&
      while true; do echo "Calling the container";  echo "BBBBBBB"; curl common_server:4444; sleep 10; done'
    networks:
     - a_my_network
networks:
  a_my_network:
    external: true
</code>```

That also works. It can call the common_server from the first docker-compose file.

The first question I have: Although I define the network as my_network in the first file, it is called a_my_network by docker. Is there a way to define the network so that I can call it the same in both docker-compose files?

I then decided to remove those two networks using docker network prune, and start again. Unfortunately, when I now run the first file again I now get the following error:

```<code>$ docker-compose up
Creating network "a_my_network" with driver "bridge"
Starting a_common_server_1 ... error

ERROR: for a_common_server_1  Cannot start service common_server: network f0a42e17007bc0f352042f5394aef65be18bb12c7836e8864ecb734f83a421d7 not found

ERROR: for common_server  Cannot start service common_server: network f0a42e17007bc0f352042f5394aef65be18bb12c7836e8864ecb734f83a421d7 not found
ERROR: Encountered errors while bringing up the project.
</code>```

So my second question: Why can I only start the first docker-compose file if I first create the a_default network by not explicitly defining a network?

答:
You can alter the network name with the -p or --project-name flags or the COMPOSE_PROJECT_NAME environment variable.

And see here maybe: https://docs.docker.com/compose/networking/#use-a-pre-existing-network

Body:
I've got two projects (a and b) which both have a docker-compose.yml file. I now want one of the projects to be able to call a service of the other project and as far as I know I need to create a common docker network for that. So to create a minimal example I made two folders (a/ and b/) which both contain a docker-compose.yml file.

This is the one in folder a/:

version: '3'

services:
  common_server:
    image: ubuntu
    ports:
      - 4444:4444
    command: >
      bash -c '
      apt update && apt install netcat -y &&
      while true; do echo -e "HTTP/1.1 200 OK\n\npong" | nc -k -l -p 4444 -q 1; done'
#    networks:
#      - my_network

  project_a:
    image: ubuntu
    depends_on:
      - common_server
#    networks:
#      - my_network
    command: >
      bash -c '
      apt update && apt install curl -y &&
      while true; do echo "Calling the container";  echo "AAAAAAAA"; curl common_server:4444; sleep 10; done'

#networks:
#  my_network:
#    driver: bridge

This sets up two things:

common_server: a simple ping/pong server which responds "pong" to every request it gets

project_a: a simple client which calls the common_server every 10 seconds

This works great like this. I quickly checked the docker networks using:

$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
5ac503033848        a_default           bridge              local  <== THIS NETWORK WAS CREATED
1f65f9c91441        bridge              bridge              local
72fcb38f2060        host                host                local
b76cd7ef1ac9        none                null                local

I've got a second docker-compose.yml file in the folder b/ from which I also want to call the common_server defined in the file above. So I uncommented the lines with the network in the file above to enable my_network. Running that also works great.

When I check docker network ls again I also see the second network it created:

$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
5ac503033848        a_default           bridge              local  <== CREATED BY THE FIRST RUN
f0a42e17007b        a_my_network        bridge              local  <== CREATED BY THE SECOND RUN
1f65f9c91441        bridge              bridge              local
72fcb38f2060        host                host                local
b76cd7ef1ac9        none                null                local

I then started the second docker-compose file:

version: '3'

services:
  project_b:
    image: ubuntu
    command: >
      bash -c '
      apt update && apt install curl -y &&
      while true; do echo "Calling the container";  echo "BBBBBBB"; curl common_server:4444; sleep 10; done'
    networks:
     - a_my_network
networks:
  a_my_network:
    external: true

That also works. It can call the common_server from the first docker-compose file.

The first question I have: Although I define the network as my_network in the first file, it is called a_my_network by docker. Is there a way to define the network so that I can call it the same in both docker-compose files?

I then decided to remove those two networks using docker network prune, and start again. Unfortunately, when I now run the first file again I now get the following error:

$ docker-compose up
Creating network "a_my_network" with driver "bridge"
Starting a_common_server_1 ... error

ERROR: for a_common_server_1  Cannot start service common_server: network f0a42e17007bc0f352042f5394aef65be18bb12c7836e8864ecb734f83a421d7 not found

ERROR: for common_server  Cannot start service common_server: network f0a42e17007bc0f352042f5394aef65be18bb12c7836e8864ecb734f83a421d7 not found
ERROR: Encountered errors while bringing up the project.

So my second question: Why can I only start the first docker-compose file if I first create the a_default network by not explicitly defining a network?


问:
Oracle EBS R12.2 - Should I use the APPS synonym when selecting data from custom tables in Oracle Forms/Reports?
I have been analysing the changes that need to be performed in the customer custom code before upgrading from EBS 12.1 to 12.2 with focus on online patching compliance.

When running the ‘Online Patching Database Standards Checker ADZDDBCC.sql’, section SECTION-26 list a number of custom database objects to be amended. This section states that ‘Query/DML statements must access tables via the APPS table synonym.’.
Database objects residing in a registered custom schema (i.e. XXSCHEMA) will need to be amended to select data via the APPS table synonym. I understand that and we have a plan in place to sort out those violations.

Now, when running the GSCC checks for custom Oracle forms and reports the same violation is presented but they only point to standard EBS schemas i.e. INV.table_name which we will need to amend to APPS.table_name. The GSCC outputs do not display any violation against registered custom schemas in forms and reports i.e. accessing a table via our XXSCHEMA is not listed in the GSCC results.

We are in doubt if Oracle forms and reports could select data from the custom tables (registered schemas) directly i.e. XXSCHEMA.table_name without using the APPS synonym as this is not listed in the GSCC results.

Can anyone advise please?

Regards, Tiago

答:
EBS 12.2 is just a continuation of the standard that custom forms and reports should reference the APPS owned objects

It is just good practice to fix forms and reports that do not point at the APPS editioned view in lieu of pointing at the EBS table (e.g. apps.per_all_people_f in lieu of hr.per_all_people_f or apps.custom_table1 in lieu of xxschema.custom_table1).

Since forms and reports will be executed using APPS with the end user's context, it is advocated that one not qualify the editioned view (e.g. just use per_all_people_f).  References to registered schemas which are custom should also follow this practice.

Why?

-Oracle EBS security is all based on APPS.  When an end users logs in to EBS, a session context is set which defines the person's access.

Oracle has historically advocated that customizations should use APPS owned objects because the customization (e.g. Form or Report) will then leverage the user's context during execution to produce result sets that correspond with the end user's privileges.

-With EBS 12.2 pushing out online patching and its many components, Oracle steers us to continue to use this APPS centric approach (typically it is the editioned views owned by APPS). Not using the APPS editioned view could result in erroneous results.

One can query your editions:

```<code>SELECT level,
de.edition_name,
de.parent_edition_name,
de.usable
FROM dba_editions de
START WITH de.edition_name = 'ORA$BASE'
CONNECT BY PRIOR de.edition_name = de.parent_edition_name
ORDER BY de.edition_name
</code>```

Keep in mind that by not referencing the APPS editioned view of the seeded or custom table can result multiplying the number of records back (distorting the functioning of forms and reports).

Moving forward, one should just assume that Online patching will be the new patching methodology used (it is the supported one). With that assumption, referencing the APPS editioned view is a reasonable, defensive approach.

Body:
EBS 12.2 is just a continuation of the standard that custom forms and reports should reference the APPS owned objects

It is just good practice to fix forms and reports that do not point at the APPS editioned view in lieu of pointing at the EBS table (e.g. apps.per_all_people_f in lieu of hr.per_all_people_f or apps.custom_table1 in lieu of xxschema.custom_table1).

Since forms and reports will be executed using APPS with the end user's context, it is advocated that one not qualify the editioned view (e.g. just use per_all_people_f).  References to registered schemas which are custom should also follow this practice.

Why?

-Oracle EBS security is all based on APPS.  When an end users logs in to EBS, a session context is set which defines the person's access.

Oracle has historically advocated that customizations should use APPS owned objects because the customization (e.g. Form or Report) will then leverage the user's context during execution to produce result sets that correspond with the end user's privileges.

-With EBS 12.2 pushing out online patching and its many components, Oracle steers us to continue to use this APPS centric approach (typically it is the editioned views owned by APPS). Not using the APPS editioned view could result in erroneous results.

One can query your editions:

SELECT level,
de.edition_name,
de.parent_edition_name,
de.usable
FROM dba_editions de
START WITH de.edition_name = 'ORA$BASE'
CONNECT BY PRIOR de.edition_name = de.parent_edition_name
ORDER BY de.edition_name

Keep in mind that by not referencing the APPS editioned view of the seeded or custom table can result multiplying the number of records back (distorting the functioning of forms and reports).

Moving forward, one should just assume that Online patching will be the new patching methodology used (it is the supported one). With that assumption, referencing the APPS editioned view is a reasonable, defensive approach.


问:
Can a client connection in CLOSE_WAIT state be terminated from the command line (outside the server)?
I've an app running on the port 7496 (server), and there is an unknown process (unknown client) trying to connect to this port and it's not correctly closing the connection, so if I type

```<code>lsof -n -i4TCP:7496
COMMAND     PID  USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
JavaAppli 45628 Admin   61u  IPv6 0xb510809c2b4037f3      0t0  TCP *:7496 (LISTEN)
JavaAppli 45628 Admin   62u  IPv6 0xb510809c2b3ffab3      0t0  TCP 127.0.0.1:7496->127.0.0.1:58507 (CLOSE_WAIT)
</code>```

(this show that my server app (45628) but not shows the client PID)

the problem is that this process is blocking me for make new connections with the server: I'm trying to connect another processes to the server but the server is blocking these connections, I'd like close the client (not the server running on the port 7496)

would be possible close this connection? or force close that CLOSE_WAIT connection?, I'm on macOS

thank you so much

答:
Two suggestions:

If one client is blocking others, maybe you need a bigger listen queue?
https://docs.python.org/3/library/socket.html#socket.socket.listen

If you need timeouts, maybe use select and/or socket.settimeout() https://docs.python.org/3/library/socket.html#socket.socket.settimeout

HTH.

Body:
I've an app running on the port 7496 (server), and there is an unknown process (unknown client) trying to connect to this port and it's not correctly closing the connection, so if I type

lsof -n -i4TCP:7496
COMMAND     PID  USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
JavaAppli 45628 Admin   61u  IPv6 0xb510809c2b4037f3      0t0  TCP *:7496 (LISTEN)
JavaAppli 45628 Admin   62u  IPv6 0xb510809c2b3ffab3      0t0  TCP 127.0.0.1:7496->127.0.0.1:58507 (CLOSE_WAIT)

(this show that my server app (45628) but not shows the client PID)

the problem is that this process is blocking me for make new connections with the server: I'm trying to connect another processes to the server but the server is blocking these connections, I'd like close the client (not the server running on the port 7496)

would be possible close this connection? or force close that CLOSE_WAIT connection?, I'm on macOS

thank you so much


问:
How would i leave out the name jones but display people with the same deptno
```<code>SQL> select empno, ename, deptno
  2  from empcopy
  3  where deptno =
  4      (select deptno
  5       from empcopy
  6       where ename like 'JONES');

 EMPNO ENAME          DEPTNO
------ ---------- ----------
  7369 SMITH              20
  7566 JONES              20
  7788 SCOTT              20
  7876 ADAMS              20
  7902 FORD               20
</code>```

答:
You just add a predicate to your where clause to exclude Jones.</p>

```<code>SELECT
  empno,
  ename,
  deptno
  FROM
  empcopy
 WHERE
  deptno =(SELECT
             deptno
             FROM
             empcopy
            WHERE
             ename LIKE 'JONES'
          )
  AND ename != 'JONES';
</code>```

Body:
You just add a predicate to your where clause to exclude Jones.

SELECT
  empno,
  ename,
  deptno
  FROM
  empcopy
 WHERE
  deptno =(SELECT
             deptno
             FROM
             empcopy
            WHERE
             ename LIKE 'JONES'
          )
  AND ename != 'JONES';


问:
CASE query optimization
```<code>SELECT
  COUNT(CASE WHEN VALUE = 1 THEN 1 END) AS score_1,
  COUNT(CASE WHEN VALUE = 2 THEN 1 END) AS score_2,
  COUNT(CASE WHEN VALUE = 3 THEN 1 END) AS score_3,
  COUNT(CASE WHEN VALUE = 4 THEN 1 END) AS score_4,
  COUNT(CASE WHEN VALUE = 5 THEN 1 END) AS score_5,
  COUNT(CASE WHEN VALUE = 6 THEN 1 END) AS score_6,
  COUNT(CASE WHEN VALUE = 7 THEN 1 END) AS score_7,
  COUNT(CASE WHEN VALUE = 8 THEN 1 END) AS score_8,
  COUNT(CASE WHEN VALUE = 9 THEN 1 END) AS score_9,
  COUNT(CASE WHEN VALUE = 10 THEN 1 END) AS score_10
FROM
  `answers`
WHERE
`created_at` BETWEEN '2017-01-01 00:00:00' AND '2019-11-30 23:59:59'
</code>```

Is there a way to optimize this query, because I have 4 million answer records in my DB, and it runs very slowly?

答:
Want it to be 10 times as fast?  Use the Data Warehousing technique of buiding and maintaining a "Summary table".  In this example the summary table might be

```<code>CREATE TABLE subtotals (
    dy DATE NOT NULL,
    `value` ... NOT NULL,   -- TINYINT UNSIGNED ?
    ct SMALLINT UNSIGNED NOT NULL, -- this is 2 bytes, max 65K; change if might be bigger
    PRIMARY KEY(value, dy)  -- or perhaps the opposite order
) ENGINE=InnoDB
</code>```

Each night you summarize the day's data and build 10 new rows in subtotals.

Then the "report" query becomes

```<code>SELECT
  SUM(CASE WHEN VALUE = 1 THEN ct END) AS score_1,
  SUM(CASE WHEN VALUE = 2 THEN ct END) AS score_2,
  SUM(CASE WHEN VALUE = 3 THEN ct END) AS score_3,
  SUM(CASE WHEN VALUE = 4 THEN ct END) AS score_4,
  SUM(CASE WHEN VALUE = 5 THEN ct END) AS score_5,
  SUM(CASE WHEN VALUE = 6 THEN ct END) AS score_6,
  SUM(CASE WHEN VALUE = 7 THEN ct END) AS score_7,
  SUM(CASE WHEN VALUE = 8 THEN ct END) AS score_8,
  SUM(CASE WHEN VALUE = 9 THEN ct END) AS score_9,
  SUM(CASE WHEN VALUE = 10 THEN ct END) AS score_10
FROM
  `subtotals`
WHERE `created_at` >= '2017-01-01'
  AND `created_at`  < '2019-12-01'
</code>```

Based on what you have provided, there will be about 10K rows in subtotals; that's a lot less to wade through than 4M rows.  It might run more than 10 times as fast.

More discussion: http://mysql.rjweb.org/doc.php/summarytables

Title: CASE query optimization

Body:
SELECT
  COUNT(CASE WHEN VALUE = 1 THEN 1 END) AS score_1,
  COUNT(CASE WHEN VALUE = 2 THEN 1 END) AS score_2,
  COUNT(CASE WHEN VALUE = 3 THEN 1 END) AS score_3,
  COUNT(CASE WHEN VALUE = 4 THEN 1 END) AS score_4,
  COUNT(CASE WHEN VALUE = 5 THEN 1 END) AS score_5,
  COUNT(CASE WHEN VALUE = 6 THEN 1 END) AS score_6,
  COUNT(CASE WHEN VALUE = 7 THEN 1 END) AS score_7,
  COUNT(CASE WHEN VALUE = 8 THEN 1 END) AS score_8,
  COUNT(CASE WHEN VALUE = 9 THEN 1 END) AS score_9,
  COUNT(CASE WHEN VALUE = 10 THEN 1 END) AS score_10
FROM
  `answers`
WHERE
`created_at` BETWEEN '2017-01-01 00:00:00' AND '2019-11-30 23:59:59'

Is there a way to optimize this query, because I have 4 million answer records in my DB, and it runs very slowly?

Body:
Want it to be 10 times as fast?  Use the Data Warehousing technique of buiding and maintaining a "Summary table".  In this example the summary table might be

CREATE TABLE subtotals (
    dy DATE NOT NULL,
    `value` ... NOT NULL,   -- TINYINT UNSIGNED ?
    ct SMALLINT UNSIGNED NOT NULL, -- this is 2 bytes, max 65K; change if might be bigger
    PRIMARY KEY(value, dy)  -- or perhaps the opposite order
) ENGINE=InnoDB

Each night you summarize the day's data and build 10 new rows in subtotals.

Then the "report" query becomes

SELECT
  SUM(CASE WHEN VALUE = 1 THEN ct END) AS score_1,
  SUM(CASE WHEN VALUE = 2 THEN ct END) AS score_2,
  SUM(CASE WHEN VALUE = 3 THEN ct END) AS score_3,
  SUM(CASE WHEN VALUE = 4 THEN ct END) AS score_4,
  SUM(CASE WHEN VALUE = 5 THEN ct END) AS score_5,
  SUM(CASE WHEN VALUE = 6 THEN ct END) AS score_6,
  SUM(CASE WHEN VALUE = 7 THEN ct END) AS score_7,
  SUM(CASE WHEN VALUE = 8 THEN ct END) AS score_8,
  SUM(CASE WHEN VALUE = 9 THEN ct END) AS score_9,
  SUM(CASE WHEN VALUE = 10 THEN ct END) AS score_10
FROM
  `subtotals`
WHERE `created_at` >= '2017-01-01'
  AND `created_at`  < '2019-12-01'

Based on what you have provided, there will be about 10K rows in subtotals; that's a lot less to wade through than 4M rows.  It might run more than 10 times as fast.

More discussion: http://mysql.rjweb.org/doc.php/summarytables


问:
c++ SIGTERM not returning after caught
I am trying to catch SIGTERM in my program, this is the problem.

My program starts and sets ups the listener for the signal SIGTERM. The program then enters a loop which continuously checks a socket file descriptor using select so that it is non blocking.When I send the program TERM through kill the program acknowledges that it receives the signal but that's it no return back to the loop I describe earlier.

The signal handler sets a public variable inside the class so the loop knows to exit. I should mention that in gdb this works but outside of gdb it does not.

Thanks in advance.

```<code>class A
{
    public:
        bool volatile stop;

    void loop();
    {
        while(!stop)
            {
                //check socket
            }
    }
};

A *aptr;

void sigterm_handler(int i)
{
    aptr->stop = true;
}

int main()
{
    A a;
    aptr = &a;
    struct sigaction sa;
    sa.sa_handler = &sigterm_handler;
    sigaction(SIGTERM, &sa, NULL);
    a.stop = false;
    a.loop();
}
</code>```

EDIT: sorry did not finish the code off properly.

答: Maybe this is related with the other members of struct sigaction that are not initialized. gdb maybe initializes the memory to 0, whereas it is not initiazlized without gdb.

ContentLicense: CC BY-SA 3.0

Title: c++ SIGTERM not returning after caught

Body:
I am trying to catch SIGTERM in my program, this is the problem.

My program starts and sets ups the listener for the signal SIGTERM. The program then enters a loop which continuously checks a socket file descriptor using select so that it is non blocking.When I send the program TERM through kill the program acknowledges that it receives the signal but that's it no return back to the loop I describe earlier.

The signal handler sets a public variable inside the class so the loop knows to exit. I should mention that in gdb this works but outside of gdb it does not.

Thanks in advance.

class A
{
    public:
        bool volatile stop;

    void loop();
    {
        while(!stop)
            {
                //check socket
            }
    }
};

A *aptr;

void sigterm_handler(int i)
{
    aptr->stop = true;
}

int main()
{
    A a;
    aptr = &a;
    struct sigaction sa;
    sa.sa_handler = &sigterm_handler;
    sigaction(SIGTERM, &sa, NULL);
    a.stop = false;
    a.loop();
}

EDIT: sorry did not finish the code off properly.


问:
Disable Code Analysis output MSBuild
I am building projects using a build definition. When this executes, Code Analysis is also performed. Code Analysis outputs various files including:

```<code>ConsoleApplication2.exe.CodeAnalysisLog.xml
ConsoleApplication2.exe.lastcodeanalysissucceeded
</code>```

Is there any way to disable this output from happing in my build definition, say through parameters or something similar?

答:
I was unsuccessful with the two answers provided by Matthijs and Nicole Calinoiu, but after further investigation, I stumbled across this question on StackOverflow.

In short, it is not recommended one disable these files from being outputted in general. According to seva titov's answer in that question linked above:

First, removing .lastcodeanalysissucceededd will cause code analysis re-run even when nothing has changed. Second, removing .CodeAnalysisLog.xml will make it almost impossible to investigate details of analysis errors and warnings. So you might as well just turn off the code analysis for the project.

Therefore, it is best to just move these two files to the intermediate file location. This location is where all the *.obj files, *.log files, and other meta files exist. To do this, right click your project and click "Unload Project."

Then, right click the project and click Edit p͟r͟o͟j͟e͟c͟t͟.vcxproj. In the picture, I click Edit Test1.vcxproj, because my project for this demonstration is called Test1:

And then, at the end of the project tag </Project> you will see a bunch of <Import ...> statements. Put the property group described in the question after these import statements:

```<code><PropertyGroup>
    <CodeAnalysisLogFile>$(IntermediateOutputPath)$(TargetFileName).CodeAnalysisLog.xml</CodeAnalysisLogFile>
    <CodeAnalysisSucceededFile>$(IntermediateOutputPath)$(TargetFileName).lastcodeanalysissucceeded</CodeAnalysisSucceededFile>
</PropertyGroup>
</code>```

For example, it should look something like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

    <!--
        ...
        A lot of other stuff not shown
        ...
    -->

    <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
    <ImportGroup Label="ExtensionTargets">
    </ImportGroup>

    <!-- The following will move the code analysis output files and put them in the intermediate folder -->
    <PropertyGroup>
        <CodeAnalysisLogFile>$(IntermediateOutputPath)$(TargetFileName).CodeAnalysisLog.xml</CodeAnalysisLogFile>
        <CodeAnalysisSucceededFile>$(IntermediateOutputPath)$(TargetFileName).lastcodeanalysissucceeded</CodeAnalysisSucceededFile>
    </PropertyGroup>
</Project>
</code>```

(Note: Keep the contents of both <CodeAnalysisSucceededFile> and <CodeAnalysisLogFile> tags on a single line as shown above. Visual Studio 2019 throws an "Illegal Characters in Path" error, if you put the content across several lines.)

Title: Disable Code Analysis output MSBuild

Body:
I am building projects using a build definition. When this executes, Code Analysis is also performed. Code Analysis outputs various files including:

ConsoleApplication2.exe.CodeAnalysisLog.xml
ConsoleApplication2.exe.lastcodeanalysissucceeded

Is there any way to disable this output from happing in my build definition, say through parameters or something similar?

Body:
I was unsuccessful with the two answers provided by Matthijs and Nicole Calinoiu, but after further investigation, I stumbled across this question on StackOverflow.

In short, it is not recommended one disable these files from being outputted in general. According to seva titov's answer in that question linked above:

First, removing .lastcodeanalysissucceededd will cause code analysis re-run even when nothing has changed. Second, removing .CodeAnalysisLog.xml will make it almost impossible to investigate details of analysis errors and warnings. So you might as well just turn off the code analysis for the project.

Therefore, it is best to just move these two files to the intermediate file location. This location is where all the *.obj files, *.log files, and other meta files exist. To do this, right click your project and click "Unload Project."

Then, right click the project and click Edit p͟r͟o͟j͟e͟c͟t͟.vcxproj. In the picture, I click Edit Test1.vcxproj, because my project for this demonstration is called Test1:

And then, at the end of the project tag </Project> you will see a bunch of <Import ...> statements. Put the property group described in the question after these import statements:

<PropertyGroup>
    <CodeAnalysisLogFile>$(IntermediateOutputPath)$(TargetFileName).CodeAnalysisLog.xml</CodeAnalysisLogFile>
    <CodeAnalysisSucceededFile>$(IntermediateOutputPath)$(TargetFileName).lastcodeanalysissucceeded</CodeAnalysisSucceededFile>
</PropertyGroup>

For example, it should look something like this:

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

    <!--
        ...
        A lot of other stuff not shown
        ...
    -->

    <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
    <ImportGroup Label="ExtensionTargets">
    </ImportGroup>

    <!-- The following will move the code analysis output files and put them in the intermediate folder -->
    <PropertyGroup>
        <CodeAnalysisLogFile>$(IntermediateOutputPath)$(TargetFileName).CodeAnalysisLog.xml</CodeAnalysisLogFile>
        <CodeAnalysisSucceededFile>$(IntermediateOutputPath)$(TargetFileName).lastcodeanalysissucceeded</CodeAnalysisSucceededFile>
    </PropertyGroup>
</Project>

(Note: Keep the contents of both <CodeAnalysisSucceededFile> and <CodeAnalysisLogFile> tags on a single line as shown above. Visual Studio 2019 throws an "Illegal Characters in Path" error, if you put the content across several lines.)


问:
How the count the number of whitespaces between the first and second word in Java
I have a string that looks like the following:

```<code>Here    is a test
</code>```

I want to return the number of whitespaces (4) between the first and second word only but I'm not quite sure how to do that. For my current attempt it counts the number of whitespaces of the entire string but I just need it between the first and second words and to then stop:

```<code>int spaceCount = 0;
for (char c : line.toCharArray()) {
    if (c == ' ') {
         spaceCount++;
    }
}
</code>```

答:
Here is a solution using regular expression

```<code>    String text = "Here    is a test";

    Pattern pattern = Pattern.compile("(?<=\\w)(\\s+)");

    Matcher matcher = pattern.matcher(text);
    if (matcher.find()) {
        System.out.println("number of whitespaces = " + matcher.group().length());

    }
</code>```

The regular expression searches for a word (an arbitrary, consecutive number non-whitespace characters) followed by whitespaces, so it doesn't matter if the text starts with whitespaces or not. The whitespaces are captured by a group and the length of the found group is returned. The regexp pattern can be precompiled and the code for matching a text can be put in a method:

```<code>private static final Pattern pattern = Pattern.compile("(?<=\\w)(\\s+)");

public static void main(String[] args) {

  String text = "Here    is a test";

  System.out.println("countWhitespaces(text) = " + countWhitespaces(text));
}

private static int countWhitespaces(String text) {
    Matcher matcher = pattern.matcher(text);
    if (matcher.find()) {
        return matcher.group().length();
    }
    return 0;
}
</code>```

Body:
I have a string that looks like the following:

Here    is a test

I want to return the number of whitespaces (4) between the first and second word only but I'm not quite sure how to do that. For my current attempt it counts the number of whitespaces of the entire string but I just need it between the first and second words and to then stop:

int spaceCount = 0;
for (char c : line.toCharArray()) {
    if (c == ' ') {
         spaceCount++;
    }
}

Body:
Here is a solution using regular expression

    String text = "Here    is a test";

    Pattern pattern = Pattern.compile("(?<=\\w)(\\s+)");

    Matcher matcher = pattern.matcher(text);
    if (matcher.find()) {
        System.out.println("number of whitespaces = " + matcher.group().length());

    }

The regular expression searches for a word (an arbitrary, consecutive number non-whitespace characters) followed by whitespaces, so it doesn't matter if the text starts with whitespaces or not. The whitespaces are captured by a group and the length of the found group is returned. The regexp pattern can be precompiled and the code for matching a text can be put in a method:

private static final Pattern pattern = Pattern.compile("(?<=\\w)(\\s+)");

public static void main(String[] args) {

  String text = "Here    is a test";

  System.out.println("countWhitespaces(text) = " + countWhitespaces(text));
}

private static int countWhitespaces(String text) {
    Matcher matcher = pattern.matcher(text);
    if (matcher.find()) {
        return matcher.group().length();
    }
    return 0;
}


问:
Support for more devices for ARCore - Huawei Nova Plus
Exist the possibility to support more devices? For example, I have a Huawei Nova Plus, I think this phone fit with all the hardware and software capabilities to support applications developed with ARCore.</p>

答: Tbh I guess its possible, the Huawei Nova 2 Plus has a gyroscope, a accelerometer, and a camera, I even contacted google about this, because I wish my phone (a Huawei nova 2 Plus) can run ARcore :)</p>


问:
Python Data science beginner function question
I'm prepping for a Data science bootcamp and know nothing about coding. Im stuck on this lab im doing right now.

so I have this list:

```<code>travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']
</code>```

I need to write a function called number_of_destinations that returns the number of destinations in the list travel_destinations.

Here's my code:

```<code>def number_of_destinations(travel_destinations):
    x = len(travel_destinations)
    print (x)
</code>```

Which returns:

```<code><function __main__.number_of_destinations(travel_destinations)>
</code>```

Ive tried so many different approaches and python just keeps spitting out "yes this is a function" basically. Can anyone help me figure out what im doing wrong here?

答:
You can try:</p>

```<code>def number_of_destinations(destinations):
    return len(travel_destinations)

travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']

print(number_of_destinations(travel_destinations))
</code>```

Body:
I'm prepping for a Data science bootcamp and know nothing about coding. Im stuck on this lab im doing right now.

so I have this list:

travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']

I need to write a function called number_of_destinations that returns the number of destinations in the list travel_destinations.

Here's my code:

def number_of_destinations(travel_destinations):
    x = len(travel_destinations)
    print (x)

Which returns:

<function __main__.number_of_destinations(travel_destinations)>

Ive tried so many different approaches and python just keeps spitting out "yes this is a function" basically. Can anyone help me figure out what im doing wrong here?

Body:
You can try:

def number_of_destinations(destinations):
    return len(travel_destinations)

travel_destinations = ['argentina', 'mexico', 'italy', 'finland', 'canada', 'croatia']

print(number_of_destinations(travel_destinations))


问:
office-js add-in in offline mode
I'm trying to develop a new office add-in. Can i send the add-in (or the manifest itself) to the end user, without a server? To clarify, the contents of manifest.xml are:

```<code><DefaultSettings>
    <SourceLocation DefaultValue="https://localhost:3000/taskpane.html"/>
</DefaultSettings>
</code>```

It is looking for the taskpane on localhost. If i change it to a server (aws for examle), it works.

Could use the add-in without a server, so it works offline?

答: Sorry, but an Office Web Add-in cannot run offline currently. There has to be a server to host the HTML and JavaScript. We're working on supporting offline operation of add-ins, but we don't know when that will be available.</p>

Title: office-js add-in in offline mode

Body:
I'm trying to develop a new office add-in. Can i send the add-in (or the manifest itself) to the end user, without a server? To clarify, the contents of manifest.xml are:

<DefaultSettings>
    <SourceLocation DefaultValue="https://localhost:3000/taskpane.html"/>
</DefaultSettings>

It is looking for the taskpane on localhost. If i change it to a server (aws for examle), it works.

Could use the add-in without a server, so it works offline?


问:
Dereference Operator Before an Array Element?
What does the notation in something like int y = *x[0] do, i.e. when you have a dereference operator right before an array element?

答:
You forgot to specify an identifier:)

```<code>int = *x[0]
</code>```

Should be something like

```<code>int value = *x[0]
</code>```

Pay attention to that this expression *x[0] is equivalent to the expression *( x[0] ) because the postfix subscript operator has a higher precedence than the unary operator *.
It is evident that such a construction is used when x denotes an array of pointers or a pointer to an object of a pointer type.

That is when the type of the expression x[0] is a pointer type. So you may apply to such an expression the dereferncing operator.

Here is a demonstrative program.

```<code>#include <stdio.h>

long long int plus( int x, int y )
{
    return ( long long int )x + y;
}

long long int minus( int x, int y )
{
    return ( long long int )x - y;
}

int main(void)
{
    long long int ( *fp[] )( int, int ) = { plus, minus };
    int x = 10, y = 5;

    unsigned long long result = ( *fp[0] )( x, y );

    printf( "x + y = %lld\n", result );

    result = ( *fp[1] )( x, y );

    printf( "x - y = %lld\n", result );

    int a1[] = { 1, 2, 3 };
    int a2[]  = { 4, 5, 6 };

    int * a[] = { a1, a2 };

    int value = *a[1];

    printf( "value = %d\n", value );

    return 0;
}
</code>```

Its output is

```<code>x + y = 15
x - y = 5
value = 4
</code>```

Such a constriction like

```<code>int = *x[0]
</code>```

without an identifier you can meet in a C++ program. Such constructions are used to specify a default argument for a function parameter.

Here is a demonstrative program.

```<code>#include <iostream>

int a[][2] =
{
    { 10, 20 },
    { 30, 40 }
};

int ( *x )[2] = a;

void f( int = *x[0] );

void f( int value )
{
    std::cout << "value = " << value << '\n';
}

int main()
{
    f();

    return 0;
}
</code>```

The program output is

```<code>value = 10
</code>```

Body:
You forgot to specify an identifier:)

int = *x[0]

Should be something like

int value = *x[0]

Pay attention to that this expression *x[0] is equivalent to the expression *( x[0] ) because the postfix subscript operator has a higher precedence than the unary operator *.
It is evident that such a construction is used when x denotes an array of pointers or a pointer to an object of a pointer type.

That is when the type of the expression x[0] is a pointer type. So you may apply to such an expression the dereferncing operator.

Here is a demonstrative program.

#include <stdio.h>

long long int plus( int x, int y )
{
    return ( long long int )x + y;
}

long long int minus( int x, int y )
{
    return ( long long int )x - y;
}

int main(void)
{
    long long int ( *fp[] )( int, int ) = { plus, minus };
    int x = 10, y = 5;

    unsigned long long result = ( *fp[0] )( x, y );

    printf( "x + y = %lld\n", result );

    result = ( *fp[1] )( x, y );

    printf( "x - y = %lld\n", result );

    int a1[] = { 1, 2, 3 };
    int a2[]  = { 4, 5, 6 };

    int * a[] = { a1, a2 };

    int value = *a[1];

    printf( "value = %d\n", value );

    return 0;
}

Its output is

x + y = 15
x - y = 5
value = 4

Such a constriction like

int = *x[0]

without an identifier you can meet in a C++ program. Such constructions are used to specify a default argument for a function parameter.

Here is a demonstrative program.

#include <iostream>

int a[][2] =
{
    { 10, 20 },
    { 30, 40 }
};

int ( *x )[2] = a;

void f( int = *x[0] );

void f( int value )
{
    std::cout << "value = " << value << '\n';
}

int main()
{
    f();

    return 0;
}

The program output is

value = 10


问:
How to prevent tracking sensitive data in URLs?
Some URLs in my single-page-app (SPA) contain sensitive information like an access token, user information, etc.

Examples:

```<code>/callback#access_token=HBVYTU2Rugv3gUbvgIUY
/?email=username@example.com
</code>```

I see that hotjar allows suppressing DOM elements and images from tracked data. Is it possible to hide params in URL or at least disable tracking for some pages?

答:
It seems to me that it's reasonable to assume that tracking scripts will try to access window.location.href or similar to get the current url which they will store.

So a possible solution would be create a dynamic scope which has a different value for window.location.href (with all sensitive info filtered out)

This is how it might work:

// get the tracker script as a string, so you can eval it in a dynamic scope

let trackerScript = 'console.log("Tracked url:", window.location.href)';

// now lets lock it up
function trackerJail(){
  let window = {
    location: {
      // put your filtered url here
      href: "not so fast mr.bond"
    }
  }

  eval(String(trackerScript))
}

trackerJail()```

If the tracking snippet is wrapped in a function it might be possible to create a dynamic scope for it without running eval by overriding it's prototype instead. But I'm not sure you can count on tracker scripts being wrapped in a neat function you can modify.

Also, there are a couple more ways the script might try to access the URL, so make sure to cover all the exits

Body:
Some URLs in my single-page-app (SPA) contain sensitive information like an access token, user information, etc.

Examples:

/callback#access_token=HBVYTU2Rugv3gUbvgIUY
/?email=username@example.com

I see that hotjar allows suppressing DOM elements and images from tracked data. Is it possible to hide params in URL or at least disable tracking for some pages?

Body:
It seems to me that it's reasonable to assume that tracking scripts will try to access window.location.href or similar to get the current url which they will store.

So a possible solution would be create a dynamic scope which has a different value for window.location.href (with all sensitive info filtered out)

This is how it might work:

// get the tracker script as a string, so you can eval it in a dynamic scope

let trackerScript = 'console.log("Tracked url:", window.location.href)';

// now lets lock it up
function trackerJail(){
  let window = {
    location: {
      // put your filtered url here
      href: "not so fast mr.bond"
    }
  }

  eval(String(trackerScript))
}

trackerJail()

If the tracking snippet is wrapped in a function it might be possible to create a dynamic scope for it without running eval by overriding it's prototype instead. But I'm not sure you can count on tracker scripts being wrapped in a neat function you can modify.

Also, there are a couple more ways the script might try to access the URL, so make sure to cover all the exits


问:
SQL Server- How can I perform the same function as Excel index/match?
So I have the following code which works fine:

```<code>SELECT
    CODE,
    TRADEDATE,
    SETTLE,
    SUBSTRING(EXPIRY, 1, 1) AS CONTRACT_CODE,
    SUBSTRING(EXPIRY, 2, 4) AS CONTRACT_YEAR
FROM
    QUANDL.DBO.AR_MWCS$
INNER JOIN
    QUANDL.DBO.AR_MWCF$ ON QUANDL.DBO.AR_MWCS$.FULL_code = QUANDL.DBO.AR_MWCF$.FULL_CODE
 WHERE
    CODE IN ('CI', 'TC', 'PG', 'PW', 'NG', 'NL', 'PD', '8X', 'PH', 'PM', 'NJ', 'NX', 'TZ6', 'TR', 'NW', 'CL', 'CY', 'WJ')
    AND EXPIRY IN ('H2020')
ORDER BY
    CODE ASC, TRADEDATE DESC, EXPIRY ASC
</code>```

The output looks like this:

I have another table called "contract_key" which contains two columns. One is "contract_code" and the other is "contract_month". What I need is to join the tables so I can see the contract_month, March, instead of the contract_code, H.

In Excel it would be

```<code>=INDEX(A:A, MATCH(E2,B:B,0))
</code>```

where column A is the month and column B is the code,cell E2 is the code H and the formula returns "3".

The desired output would look like this instead:

I'm using AR_MWCS$ to pull in the settle price. The table looks like this:

Table AR_MWCF$ looks like this:

I'm using substring to split EXPIRY into "H" and "2020"

Table CONTRACT_KEY looks like this:

So I need to join the CONTRACT_CODE from table CONTRACT_KEY and the substring CONTRACT_CODE created from table AR_MWCF$ to find the contract month then combine the contract month with the contract year as a date.

I was able to get my desired output by modifying the code to:

```<code>SELECT
     CODE
    ,TRADEDATE
    ,SETTLE
    ,CONCAT(CONTRACT_MONTH,'-','01','-',CONTRACT_YEAR) AS EXPIRATION

FROM
     QUANDL.DBO.AR_MWCS$

INNER JOIN
    QUANDL.DBO.AR_MWCF$
 ON QUANDL.DBO.AR_MWCS$.FULL_code = QUANDL.DBO.AR_MWCF$.FULL_CODE

INNER JOIN
    QUANDL.DBO.CONTRACT_KEY
ON QUANDL.DBO.AR_MWCF$.CONTRACT_CODE = QUANDL.DBO.CONTRACT_KEY.CONTRACT_CODE

WHERE
    CODE IN ('CI','TC','PG','PW','NG','NL','PD','8X','PH','PM','NJ','NX','TZ6','TR','NW','CL','CY','WJ')

ORDER BY
    CODE ASC, TRADEDATE DESC, EXPIRY ASC
</code>```

Which returns the following:

答:
This code worked for what I needed:</p>

```<code>SELECT
     CODE
    ,TRADEDATE
    ,SETTLE
    ,CONCAT(CONTRACT_MONTH,'-','01','-',CONTRACT_YEAR) AS EXPIRATION

FROM
     QUANDL.DBO.AR_MWCS$

INNER JOIN
    QUANDL.DBO.AR_MWCF$
 ON QUANDL.DBO.AR_MWCS$.FULL_code = QUANDL.DBO.AR_MWCF$.FULL_CODE

INNER JOIN
    QUANDL.DBO.CONTRACT_KEY
ON QUANDL.DBO.AR_MWCF$.CONTRACT_CODE = QUANDL.DBO.CONTRACT_KEY.CONTRACT_CODE

WHERE
    CODE IN ('CI','TC','PG','PW','NG','NL','PD','8X','PH','PM','NJ','NX','TZ6','TR','NW','CL','CY','WJ')

ORDER BY
    CODE ASC, TRADEDATE DESC, EXPIRY ASC
</code>```

Body:
So I have the following code which works fine:

SELECT
    CODE,
    TRADEDATE,
    SETTLE,
    SUBSTRING(EXPIRY, 1, 1) AS CONTRACT_CODE,
    SUBSTRING(EXPIRY, 2, 4) AS CONTRACT_YEAR
FROM
    QUANDL.DBO.AR_MWCS$
INNER JOIN
    QUANDL.DBO.AR_MWCF$ ON QUANDL.DBO.AR_MWCS$.FULL_code = QUANDL.DBO.AR_MWCF$.FULL_CODE
 WHERE
    CODE IN ('CI', 'TC', 'PG', 'PW', 'NG', 'NL', 'PD', '8X', 'PH', 'PM', 'NJ', 'NX', 'TZ6', 'TR', 'NW', 'CL', 'CY', 'WJ')
    AND EXPIRY IN ('H2020')
ORDER BY
    CODE ASC, TRADEDATE DESC, EXPIRY ASC

The output looks like this:

I have another table called "contract_key" which contains two columns. One is "contract_code" and the other is "contract_month". What I need is to join the tables so I can see the contract_month, March, instead of the contract_code, H.

In Excel it would be

=INDEX(A:A, MATCH(E2,B:B,0))

where column A is the month and column B is the code,cell E2 is the code H and the formula returns "3".

The desired output would look like this instead:

I'm using AR_MWCS$ to pull in the settle price. The table looks like this:

Table AR_MWCF$ looks like this:

I'm using substring to split EXPIRY into "H" and "2020"

Table CONTRACT_KEY looks like this:

So I need to join the CONTRACT_CODE from table CONTRACT_KEY and the substring CONTRACT_CODE created from table AR_MWCF$ to find the contract month then combine the contract month with the contract year as a date.

I was able to get my desired output by modifying the code to:

SELECT
     CODE
    ,TRADEDATE
    ,SETTLE
    ,CONCAT(CONTRACT_MONTH,'-','01','-',CONTRACT_YEAR) AS EXPIRATION

FROM
     QUANDL.DBO.AR_MWCS$

INNER JOIN
    QUANDL.DBO.AR_MWCF$
 ON QUANDL.DBO.AR_MWCS$.FULL_code = QUANDL.DBO.AR_MWCF$.FULL_CODE

INNER JOIN
    QUANDL.DBO.CONTRACT_KEY
ON QUANDL.DBO.AR_MWCF$.CONTRACT_CODE = QUANDL.DBO.CONTRACT_KEY.CONTRACT_CODE

WHERE
    CODE IN ('CI','TC','PG','PW','NG','NL','PD','8X','PH','PM','NJ','NX','TZ6','TR','NW','CL','CY','WJ')

ORDER BY
    CODE ASC, TRADEDATE DESC, EXPIRY ASC

Which returns the following:

Body:
This code worked for what I needed:

SELECT
     CODE
    ,TRADEDATE
    ,SETTLE
    ,CONCAT(CONTRACT_MONTH,'-','01','-',CONTRACT_YEAR) AS EXPIRATION

FROM
     QUANDL.DBO.AR_MWCS$

INNER JOIN
    QUANDL.DBO.AR_MWCF$
 ON QUANDL.DBO.AR_MWCS$.FULL_code = QUANDL.DBO.AR_MWCF$.FULL_CODE

INNER JOIN
    QUANDL.DBO.CONTRACT_KEY
ON QUANDL.DBO.AR_MWCF$.CONTRACT_CODE = QUANDL.DBO.CONTRACT_KEY.CONTRACT_CODE

WHERE
    CODE IN ('CI','TC','PG','PW','NG','NL','PD','8X','PH','PM','NJ','NX','TZ6','TR','NW','CL','CY','WJ')

ORDER BY
    CODE ASC, TRADEDATE DESC, EXPIRY ASC


问:
Format string in python using sql.Literal
I am executing this SQL query in a python script,  in the config_study dictionary (got from json file), I have provided objects, like start_date, study_name etc. I want to enable that start_date or end_date are optional, so if not provided I want to use default values like '1900-01-01', '1900-01-01'. If they are provided I would like to use them as it is now.

How to set a default value in this query for start_date=sql.Literal(config_study['start_date'])?

```<code> import psycopg2
 from psycopg2 import sql

 def execute(conf, cur):
 config_study = conf['config_study']

    if 'start_date' not in config_study:
    config_study['start_date'] = '1900-01-01'

    if 'end_date' not in config_study:
    config_study['end_date'] = '1900-01-01'

    pre_query = sql.SQL("""

    INSERT INTO {{tmp_output_schema_name}}."config_set"
            ("study_id",
             "study_name",
             "study_type",
             "date_start",
             "date_end",
             "sales",
             "client")
        VALUES
            ({{study_id}},
             {study_name},
             {{study_type_shortname}},
             {start_date},
             {end_date},
             'edwin@gmail.co',
             'Persona client'); """).format(
                    study_name=sql.Literal(config_study['study_name']),
                    start_date=sql.Literal(config_study['start_date']),
                    end_date=sql.Literal(config_study['end_date']))
</code>```

答:
Probably most readable way of doing this is to leave your code untouched, but precede it with the following:

```<code>if 'start_date' not in config_study:
    config_study['start_date'] = '1900-01-01'
if 'end_date' not in config_study:
    config_study['end_date'] = '1900-01-01'
</code>```

so that missing values in config_study are filled with defaults.

Body:
I am executing this SQL query in a python script,  in the config_study dictionary (got from json file), I have provided objects, like start_date, study_name etc. I want to enable that start_date or end_date are optional, so if not provided I want to use default values like '1900-01-01', '1900-01-01'. If they are provided I would like to use them as it is now.

How to set a default value in this query for start_date=sql.Literal(config_study['start_date'])?

 import psycopg2
 from psycopg2 import sql

 def execute(conf, cur):
 config_study = conf['config_study']

    if 'start_date' not in config_study:
    config_study['start_date'] = '1900-01-01'

    if 'end_date' not in config_study:
    config_study['end_date'] = '1900-01-01'

    pre_query = sql.SQL("""

    INSERT INTO {{tmp_output_schema_name}}."config_set"
            ("study_id",
             "study_name",
             "study_type",
             "date_start",
             "date_end",
             "sales",
             "client")
        VALUES
            ({{study_id}},
             {study_name},
             {{study_type_shortname}},
             {start_date},
             {end_date},
             'edwin@gmail.co',
             'Persona client'); """).format(
                    study_name=sql.Literal(config_study['study_name']),
                    start_date=sql.Literal(config_study['start_date']),
                    end_date=sql.Literal(config_study['end_date']))

Body:
Probably most readable way of doing this is to leave your code untouched, but precede it with the following:

if 'start_date' not in config_study:
    config_study['start_date'] = '1900-01-01'
if 'end_date' not in config_study:
    config_study['end_date'] = '1900-01-01'

so that missing values in config_study are filled with defaults.


问:
How can codeBuild container run aws-cli commands without prior authentication?
Say I use aws-cli locally on my machine, I´d need to authenticate with credentials prior to any operation.

How do AWS services give permission to other services on my behalf? And more specifically, how does a container run aws-cli on my behalf without prior authentication?

I am asking this, after running my first pipeline successfully in codePipeline. My buildspec.yml does run aws s3 sync command flawlessly -which made me then wonder how do aws internally permissions work-.

答:
AWS CodeBuild uses an IAM Service Role to provide AWS permissions to the CodeBuild environment. You should have had to create a service role for your CodeBuild configuration.

When the AWS cli tool runs, and it hasn't been previously configured with API access keys, it will check if it is running in an AWS environment like EC2 or Lambda and if so, it will use the AWS IAM role assigned to that runtime environment.


问:
How to insert data from tableWidget into sqlite Database
I am trying to insert tableWidget data into SQLite db.

1) Total number of columns in a row are 9, If the table has less than 9 items data, for example: if table has items in date, name, location and item1, it shows an error like this:

item2 = [self.tableWidget.item(row, 4).text() for row in range(self.tableWidget.rowCount())]
  AttributeError: 'NoneType' object has no attribute 'text'

2) If table has 9 items, no error but data is not inserted into the db.

```<code>date = [self.tableWidget.item(row, 0).text() for row in range(self.tableWidget.rowCount())]
name = [self.tableWidget.item(row, 1).text() for row in range(self.tableWidget.rowCount())]

location = [self.tableWidget.item(row, 2).text() for row in range(self.tableWidget.rowCount())]
item1 = [self.tableWidget.item(row, 3).text() for row in range(self.tableWidget.rowCount())]
item2 = [self.tableWidget.item(row, 4).text() for row in range(self.tableWidget.rowCount())]
item3 = [self.tableWidget.item(row, 5).text() for row in range(self.tableWidget.rowCount())]
item4 = [self.tableWidget.item(row, 6).text() for row in range(self.tableWidget.rowCount())]
item5 = [self.tableWidget.item(row, 7).text() for row in range(self.tableWidget.rowCount())]
item6 = [self.tableWidget.item(row, 8).text() for row in range(self.tableWidget.rowCount())]
conn = sqlite3.connect('test.db')
conn.execute("INSERT INTO maintable(date,name,location,item1,item2,item3,item4,item5,item6) \
     VALUES ('%s', '%s','%s', '%s', '%s', '%s', '%s', '%s', '%s')" %(''.join(date),
                                                                     ''.join(name),
                                                                     ''.join(location),
                                                                     ''.join(item1),
                                                                     ''.join(item2),
                                                                     ''.join(item3),
                                                                     ''.join(item4),
                                                                     ''.join(item5),
                                                                     ''.join(item6)))
</code>```

qTableWidget

答:
If an item is empty, item() will return None; you can check if the item exists within the comprehension:

```<code>item2 = [self.tableWidget.item(row, 4).text() for row in range(self.tableWidget.rowCount()) if self.tableWidget.item(row,4)]
# ...
</code>```

But this is not very readable nor really optimized, as it will call item() twice for each row.

I'd suggest to use a function that returns the list based on the column:

```<code>def getColumn(self, column):
    data = []
    for row in range(self.tableWidget.rowCount()):
        item = self.tableWidget.item(row, column)
        if item:
            data.append(item.text())
    return ''.join(data)

def writeToDatabase(self):
    conn = sqlite3.connect('test.db')
    conn.execute("INSERT INTO \
        maintable(date,name,location,item1,item2,item3,item4,item5,item6) \
        VALUES ('{}', '{}','{}', '{}', '{}', '{}', '{}', '{}', '{}') \
        ".format(*[self.getColumn(c) for c in range(9)]))
    # if you don't call commit(), the data is not stored
    <b>conn.commit()</b>
</code>```

Body:
I am trying to insert tableWidget data into SQLite db.

1) Total number of columns in a row are 9, If the table has less than 9 items data, for example: if table has items in date, name, location and item1, it shows an error like this:

item2 = [self.tableWidget.item(row, 4).text() for row in range(self.tableWidget.rowCount())]
  AttributeError: 'NoneType' object has no attribute 'text'

2) If table has 9 items, no error but data is not inserted into the db.

date = [self.tableWidget.item(row, 0).text() for row in range(self.tableWidget.rowCount())]
name = [self.tableWidget.item(row, 1).text() for row in range(self.tableWidget.rowCount())]

location = [self.tableWidget.item(row, 2).text() for row in range(self.tableWidget.rowCount())]
item1 = [self.tableWidget.item(row, 3).text() for row in range(self.tableWidget.rowCount())]
item2 = [self.tableWidget.item(row, 4).text() for row in range(self.tableWidget.rowCount())]
item3 = [self.tableWidget.item(row, 5).text() for row in range(self.tableWidget.rowCount())]
item4 = [self.tableWidget.item(row, 6).text() for row in range(self.tableWidget.rowCount())]
item5 = [self.tableWidget.item(row, 7).text() for row in range(self.tableWidget.rowCount())]
item6 = [self.tableWidget.item(row, 8).text() for row in range(self.tableWidget.rowCount())]
conn = sqlite3.connect('test.db')
conn.execute("INSERT INTO maintable(date,name,location,item1,item2,item3,item4,item5,item6) \
     VALUES ('%s', '%s','%s', '%s', '%s', '%s', '%s', '%s', '%s')" %(''.join(date),
                                                                     ''.join(name),
                                                                     ''.join(location),
                                                                     ''.join(item1),
                                                                     ''.join(item2),
                                                                     ''.join(item3),
                                                                     ''.join(item4),
                                                                     ''.join(item5),
                                                                     ''.join(item6)))

qTableWidget

Body:
If an item is empty, item() will return None; you can check if the item exists within the comprehension:

item2 = [self.tableWidget.item(row, 4).text() for row in range(self.tableWidget.rowCount()) if self.tableWidget.item(row,4)]
# ...

But this is not very readable nor really optimized, as it will call item() twice for each row.

I'd suggest to use a function that returns the list based on the column:

def getColumn(self, column):
    data = []
    for row in range(self.tableWidget.rowCount()):
        item = self.tableWidget.item(row, column)
        if item:
            data.append(item.text())
    return ''.join(data)

def writeToDatabase(self):
    conn = sqlite3.connect('test.db')
    conn.execute("INSERT INTO \
        maintable(date,name,location,item1,item2,item3,item4,item5,item6) \
        VALUES ('{}', '{}','{}', '{}', '{}', '{}', '{}', '{}', '{}') \
        ".format(*[self.getColumn(c) for c in range(9)]))
    # if you don't call commit(), the data is not stored
    conn.commit()


问:
Resetting Modal Form When Closing C# Windows Forms App
I am writing a C# Windows Forms App Online Store GUI that interfaces with a database.  One of the things I have to do is handle customers that are already in the database.  From the main menu form they click the 'Returning Customer' button, and enter their email and password. The data entered is then checked against the customers stored in the database, and if it's verified, their user information is filled into text boxes (Name, Credit Card info, CVS, etc...) and the order form becomes visible. I have no issues there.  The issue I'm having is that if a returning customer successfully logs in, then cancels out back to the main menu, the next person to click the 'Returning Customer' button pulls up the form with the first user's information already filled in and visible, since both the this.Close() and the this.DialogResult = DialogResult.Cancel methods both only hide the form rather than actually close and free it.  But then if I use this.Dispose() on the Returning Customer Form to free it, it can't be reopened.

My question is: is there an easy way to handle this?  I'm self taught in C# so forgive my inexperience.  Thank you for any help you can give.

Per request see Form1 (Main Menu Form) code below:

```<code>using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Database_Interface_Project
{
    public partial class Form1 : Form
    {
        // Removed SqlConnectionString for security purposes.
        public SqlConnection cnn = new SqlConnection(connectionString);

        // Main Menu Form
        public Form1()
        {
            InitializeComponent();
        }

        // New Customer Form
        Form2 newCustomer = new Form2();

        private void newCusButt_Click(object sender, EventArgs e)
        {
            newCustomer.ShowDialog();
        }

        // Returning Customer Form
        ReturningCustomer returningCustomer = new ReturningCustomer();
        private void RetCusButt_Click(object sender, EventArgs e)
        {
            returningCustomer.ShowDialog();

        }

        private void exitButt_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        // Manager Menu Form
        Manager managerMenu = new Manager();
        private void managerButt_Click(object sender, EventArgs e)
        {
            managerMenu.ShowDialog();
        }
    }
}```
```

答:
You just need to re-instantiate returningCustomer form in order to reset its fields.

```<code>private void RetCusButt_Click(object sender, EventArgs e)
{
    using (var returningCustomer = new ReturningCustomer())
    {
        returningCustomer.ShowDialog();
    }
}
</code>```

Using statement calls Dispose() automatically after the using-block is left.

Note: In your case you need to dispose ShowDialog appropriately to avoid GDI leak, since it has side effect of keeping the GDI objects alive.

Body:
I am writing a C# Windows Forms App Online Store GUI that interfaces with a database.  One of the things I have to do is handle customers that are already in the database.  From the main menu form they click the 'Returning Customer' button, and enter their email and password. The data entered is then checked against the customers stored in the database, and if it's verified, their user information is filled into text boxes (Name, Credit Card info, CVS, etc...) and the order form becomes visible. I have no issues there.  The issue I'm having is that if a returning customer successfully logs in, then cancels out back to the main menu, the next person to click the 'Returning Customer' button pulls up the form with the first user's information already filled in and visible, since both the this.Close() and the this.DialogResult = DialogResult.Cancel methods both only hide the form rather than actually close and free it.  But then if I use this.Dispose() on the Returning Customer Form to free it, it can't be reopened.

My question is: is there an easy way to handle this?  I'm self taught in C# so forgive my inexperience.  Thank you for any help you can give.

Per request see Form1 (Main Menu Form) code below:

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Database_Interface_Project
{
    public partial class Form1 : Form
    {
        // Removed SqlConnectionString for security purposes.
        public SqlConnection cnn = new SqlConnection(connectionString);

        // Main Menu Form
        public Form1()
        {
            InitializeComponent();
        }

        // New Customer Form
        Form2 newCustomer = new Form2();

        private void newCusButt_Click(object sender, EventArgs e)
        {
            newCustomer.ShowDialog();
        }

        // Returning Customer Form
        ReturningCustomer returningCustomer = new ReturningCustomer();
        private void RetCusButt_Click(object sender, EventArgs e)
        {
            returningCustomer.ShowDialog();

        }

        private void exitButt_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        // Manager Menu Form
        Manager managerMenu = new Manager();
        private void managerButt_Click(object sender, EventArgs e)
        {
            managerMenu.ShowDialog();
        }
    }
}```

Body:
You just need to re-instantiate returningCustomer form in order to reset its fields.

private void RetCusButt_Click(object sender, EventArgs e)
{
    using (var returningCustomer = new ReturningCustomer())
    {
        returningCustomer.ShowDialog();
    }
}

Using statement calls Dispose() automatically after the using-block is left.

Note: In your case you need to dispose ShowDialog appropriately to avoid GDI leak, since it has side effect of keeping the GDI objects alive.


问:
How to use PyGObject module (gi) on Windows and PyCharm?
I have Python 3.8.1 installed and I've followed PyGObject tutorial to install the module.

I've installed MSYS2 64 bits and I certainly can import the gi module using MSYS2 terminal:

However, if I run Python from the cmd prompt or from PyCharm, it won't work:

I want to be able to run my project from PyCharm. What am I missing?

答:
Look at the first lines that both Pythons produce. They are different.

The command-line python is a 64-bit version compiled with GCC.

The Python inside pycharm is a 32-bit version compiled with MSC.

Bottom line: Pycharm is not using the Python that you installed PyGObject in.

Edit

If you're not using the second Python instance, and nothing else on your system is using it, then it is indeed useless.

Having said that, 32-bit programs on windows have a limited adress space (2.5 GiB, IIRC). For data-science projects that might be a significant limitation these days. So I would stick to 64-bit programs these days, unless your PC has less than 4 GiB of RAM. Then it makes sense to run 32-bit software.

Another point is that I've seen reports here on Stackoverflow that Pycharm can interact negatively with Python programs that run inside it. Especially if you are running multiprocessing. So you should always test your code from a standalone Python, not from within Pycharm.


问:
HTML/CSS Button Hover shifting everything else away?
If I hover over my buttons they shift(?) other elements.

as you can see I already tried to compensate the +4 pixels from the border by subtracting them from the height and the width but the problem remains.

I don't want this. I want it to change appearance without any shifting.

Here a video to visualize my problem

Thank you in advance :)

Here the CSS and HTML

HTML:

```<code><body>
  <nav>
    <img class="logo" src="images/logo-bookmark.svg" alt="Logo nav">
    <div class="navElements">
      <a href="#" class="nav-links">Features</a>
      <a href="#" class="nav-links">Pricing</a>
      <a href="#" class="nav-links">Contact</a>
      <a href="#" class="nav-logo-btn">Login</a>
    </div>
  </nav>

  <section class="header">
    <div class="header-left">
      <h1 class="header-heading">A Simple Bookmark Manager</h1>
      <p class="header-text"> A clean and simple interface to organize your favourite websites. Open a new
        browser tab and see your sites load instantly. Try it for free.</p>
      <a href="#" class="btn-1">Get it on Chrome</a>
      <a href="#" class="btn-2">Get it on Firefox</a>
    </div>
    <img class="header-img" src="images\illustration-hero.svg" alt="Hero image">
</code>```

Login Button:

```<code>.nav-logo-btn {
  text-decoration: none;
  color: white;
  background-color: var(--SoftRed);
  padding: 10px 32px;
  border-radius: 5px;
  text-transform: uppercase;
  font-weight: 500;
  font-family: "Rubik";
  font-size: 12px;
  letter-spacing: 2px;
}

.nav-logo-btn:hover {
  color: var(--SoftRed);
  background-color: white;
  border: solid 2px;
  padding: 8px 30px;
  transition: all 0.3s;
}
</code>```

Chrome/Firefox Buttons:

```<code>.btn-1, .btn-2 {
  display: inline-block;
  text-decoration: none;
  border-radius: 5px;
  text-align: center;
  line-height: 48px;
  height: 48px;
  width: 165px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
  position: relative;
}

.btn-1:hover, .btn-2:hover {
  background-color: white;
  border: solid 2px;
  height: 44px;
  width: 161px;
}

.btn-1 {
  background-color: var(--SoftBlue);
  color: white;

}

.btn-2 {
  background-color: #f7f7f7;
  color: #606068;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.1);
  left: 50px;
}

.btn-1:hover {
  color: var(--SoftBlue);
}

.btn-2:hover {
  color: #606068;
}

</code>```

答:
Instead of adding 2px border on hover, use box-shadow. It doesn't affect the physical size of elements.

.btn-1:hover, .btn-2:hover {
  background-color: white;
  box-shadow: 0px 0px 0px 2px var(--SoftBlue);
  height: 44px;
  width: 161px;
}
```

Body:
If I hover over my buttons they shift(?) other elements.

as you can see I already tried to compensate the +4 pixels from the border by subtracting them from the height and the width but the problem remains.

I don't want this. I want it to change appearance without any shifting.

Here a video to visualize my problem

Thank you in advance :)

Here the CSS and HTML

HTML:

      Features
      Pricing
      Contact
      Login

A Simple Bookmark Manager

 A clean and simple interface to organize your favourite websites. Open a new
        browser tab and see your sites load instantly. Try it for free.

      Get it on Chrome
      Get it on Firefox

Login Button:

.nav-logo-btn {
  text-decoration: none;
  color: white;
  background-color: var(--SoftRed);
  padding: 10px 32px;
  border-radius: 5px;
  text-transform: uppercase;
  font-weight: 500;
  font-family: "Rubik";
  font-size: 12px;
  letter-spacing: 2px;
}

.nav-logo-btn:hover {
  color: var(--SoftRed);
  background-color: white;
  border: solid 2px;
  padding: 8px 30px;
  transition: all 0.3s;
}

Chrome/Firefox Buttons:

.btn-1, .btn-2 {
  display: inline-block;
  text-decoration: none;
  border-radius: 5px;
  text-align: center;
  line-height: 48px;
  height: 48px;
  width: 165px;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.2s;
  position: relative;
}

.btn-1:hover, .btn-2:hover {
  background-color: white;
  border: solid 2px;
  height: 44px;
  width: 161px;
}

.btn-1 {
  background-color: var(--SoftBlue);
  color: white;

}

.btn-2 {
  background-color: #f7f7f7;
  color: #606068;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.1);
  left: 50px;
}

.btn-1:hover {
  color: var(--SoftBlue);
}

.btn-2:hover {
  color: #606068;
}


问:
How to test running http.server in Python?
I need to test availability of my server. I've written test:

```<code>class TestApp(unittest.TestCase):
    def setUp(self):
        self.child_pid = os.fork()
        if self.child_pid == 0:
            HTTPServer(('localhost', 8000), Handler).serve_forever()

    def test_app(self):
        try:
            urllib.request.urlopen('http://localhost:8000')
        except (URLError, HTTPError) as e:
            self.fail()
</code>```

But after tests pass there are several python processes that were adopted by init. How to kill subprocess after test is done?

答:
Found solution. Need to use threading module:

```<code>class TestApp(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.server = ...
        thread = threading.Thread(target=cls.server.serve_forever)
        thread.start()

    @classmethod
    def tearDownClass(cls):
        cls.server.shutdown()
</code>```

Body:
I need to test availability of my server. I've written test:

class TestApp(unittest.TestCase):
    def setUp(self):
        self.child_pid = os.fork()
        if self.child_pid == 0:
            HTTPServer(('localhost', 8000), Handler).serve_forever()

    def test_app(self):
        try:
            urllib.request.urlopen('http://localhost:8000')
        except (URLError, HTTPError) as e:
            self.fail()

But after tests pass there are several python processes that were adopted by init. How to kill subprocess after test is done?

Body:
Found solution. Need to use threading module:

class TestApp(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.server = ...
        thread = threading.Thread(target=cls.server.serve_forever)
        thread.start()

    @classmethod
    def tearDownClass(cls):
        cls.server.shutdown()


问:
Code to generate Crystal Reports report works fine in CLI, but "Data source name not found" when accessed from browser
I'm trying to generate a report from PHP, using Crystal Reports,
The code seems to be correct:

```<code><?php
set_time_limit(0);
if(isset($_GET['id']))
{
$id = $_GET['id'];
} else {
die('Please specify an ID');
}

$path = "c:\\wamp\\www\\billing\\reports";
$file = $chemin."\\bill_".$id.".pdf";
$app_obj = new COM("CrystalRuntime.Application") or Die ("Did not open");
$report= $path."\\bill.rpt";

$rpt_obj= $app_obj->OpenReport($report,1);
$app_obj->LogOnServer("p2ssql.dll","host","bdd","userbd","passwordbd");
$rpt_obj->EnableParameterPrompting = FALSE;
$rpt_obj->RecordSelectionFormula = "{F_DOCLIGNE.DO_Piece}='$id'";

$rpt_obj->ExportOptions->DiskFileName =  $file;
$rpt_obj->ExportOptions->PDFExportAllPages = true;
$rpt_obj->ExportOptions->DestinationType = 1;
$rpt_obj->ExportOptions->FormatType = 31;
$rpt_obj->Export(false);

header("Content-Type: application/pdf");
readfile($file);
?>
</code>```

If I run the script from command line, it works just fine, and I have the PDF exported and parsed in the console.

But from a browser's point of view, the story is different,
If you get the request through Apache, I get this exception :

```<code>com_exception: Source: Crystal Reports ActiveX Designer
Details : IM002:[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified in C:\wamp\www\facture\report.php on line 25
</code>```

On the report, the database connection is made through ODBC, I couldn't use that, as any other driver, marked with ODBC refused to work.

答:
I see you are using Wamp. This behaviour is very probably related to the user that the web server (Apache) runs under.

When you run PHP from CLI, PHP.exe inherits your user profile (in terms of database/network/filesystem access rights); on the other hand, usually Apache (and IIS,too) runs under different, unprivileged credentials, to prevent hackers from damaging and exploiting the server.

In Apache, you can change this behaviour modifying the httpd.conf Apache config file (in your case it could be located under C:\wamp\apache\conf), changing the User and/or Group config directives.

Body:
I'm trying to generate a report from PHP, using Crystal Reports,
The code seems to be correct:

<?php
set_time_limit(0);
if(isset($_GET['id']))
{
$id = $_GET['id'];
} else {
die('Please specify an ID');
}

$path = "c:\\wamp\\www\\billing\\reports";
$file = $chemin."\\bill_".$id.".pdf";
$app_obj = new COM("CrystalRuntime.Application") or Die ("Did not open");
$report= $path."\\bill.rpt";

$rpt_obj= $app_obj->OpenReport($report,1);
$app_obj->LogOnServer("p2ssql.dll","host","bdd","userbd","passwordbd");
$rpt_obj->EnableParameterPrompting = FALSE;
$rpt_obj->RecordSelectionFormula = "{F_DOCLIGNE.DO_Piece}='$id'";

$rpt_obj->ExportOptions->DiskFileName =  $file;
$rpt_obj->ExportOptions->PDFExportAllPages = true;
$rpt_obj->ExportOptions->DestinationType = 1;
$rpt_obj->ExportOptions->FormatType = 31;
$rpt_obj->Export(false);

header("Content-Type: application/pdf");
readfile($file);
?>

If I run the script from command line, it works just fine, and I have the PDF exported and parsed in the console.

But from a browser's point of view, the story is different,
If you get the request through Apache, I get this exception :

com_exception: Source: Crystal Reports ActiveX Designer
Details : IM002:[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified in C:\wamp\www\facture\report.php on line 25

On the report, the database connection is made through ODBC, I couldn't use that, as any other driver, marked with ODBC refused to work.