问:
Python Sorting through nested dictionary
From multiple tables I'm getting values of the form: (Sector, Stock, InvestedValue).

I'm using a Python dictionary object to insert these values and during insert if the combination (sector, stock) exists add the InvestedValue to the existing entry else add new entry to dictionary. After all data insert, let's say I end up with nested dictionary like:

```<code>stock_dict = {
    "Financial": {"HDFC Bank": 230.25, "Axis Bank": 70.15, "ICICI Bank": 110.45},
    "Automobile": {"Tata Motors": 135.67},
    "Consumer Goods": {"Avenue Supermarket": 190.45, "Godrej Industries": 120.32}
}
</code>```

How to print through this nested dictionary in sorted fashion:

Get combination of Sector,Company,InvestedValue sorted on the basis of InvestedValue

Get combination of Sector, sum(InvestedValue) ie. sum of InvestedValue of each company in that sector again sorted on the sum

My current approach to solve these problems is to flatten the nested dictionary to list of tuples and run sorted on it. For example:

To solve 1:

```<code>stock_list = []
for sector in stock_dict:
    for stock in stock_dict[sector]:
        stock_list.append((sector, stock, stock_dict[sector][stock]))
sorted_list = sorted(stock_list, key=lambda stock: stock[2], reverse=True)
</code>```

To solve 2:

```<code>sector_list = []
for sector in stock_dict:
    sector_list.append((sector,sum(stock_dict[sector].values())))
sorted_sector_list = sorted(sector_list, key=lambda sector: sector[1], reverse=True)
</code>```

IS there a better approach i.e. sort directly on the nested dictionary without having to flatten it into the list ?

答:
If you uses pandas, it can convert you dict to a dataframe.  You can then unstack the dataframe which will make it long form instead of wide.  Once it's in the long format, you will have null values for any sector which a company does not participate in, you can drop those with dropna(), reset the index and sort values by your desired column.  Once this is done rename your columns to the desired names, and select them in the order you want.  You can take that same df and groupby sector and sum the InvestedValue.

```<code>import pandas as pd
stock_dict = {
    "Financial": {"HDFC Bank": 230.25, "Axis Bank": 70.15, "ICICI Bank": 110.45},
    "Automobile": {"Tata Motors": 135.67},
    "Consumer Goods": {"Avenue Supermarket": 190.45, "Godrej Industries": 120.32}
}

df = pd.DataFrame.from_dict(stock_dict, orient='index')
df = df.unstack().dropna().reset_index(name='InvestedValue').sort_values(by='InvestedValue', ascending=False)

df.columns = ['Company','Sector','InvestedValue']
df[['Sector','Company','InvestedValue']]
</code>```

Output

```<code>           Sector             Company  InvestedValue
0       Financial           HDFC Bank         230.25
4  Consumer Goods  Avenue Supermarket         190.45
3      Automobile         Tata Motors         135.67
5  Consumer Goods   Godrej Industries         120.32
2       Financial          ICICI Bank         110.45
1       Financial           Axis Bank          70.15
</code>```

2nd Part

```<code>df.groupby('Sector')['InvestedValue'].sum().reset_index().sort_values(by='InvestedValue', ascending=False)
</code>```

Output

```<code>           Sector  InvestedValue
2       Financial         410.85
1  Consumer Goods         310.77
0      Automobile         135.67
</code>```

Body:
From multiple tables I'm getting values of the form: (Sector, Stock, InvestedValue).

I'm using a Python dictionary object to insert these values and during insert if the combination (sector, stock) exists add the InvestedValue to the existing entry else add new entry to dictionary. After all data insert, let's say I end up with nested dictionary like:

stock_dict = {
    "Financial": {"HDFC Bank": 230.25, "Axis Bank": 70.15, "ICICI Bank": 110.45},
    "Automobile": {"Tata Motors": 135.67},
    "Consumer Goods": {"Avenue Supermarket": 190.45, "Godrej Industries": 120.32}
}

How to print through this nested dictionary in sorted fashion:

Get combination of Sector,Company,InvestedValue sorted on the basis of InvestedValue

Get combination of Sector, sum(InvestedValue) ie. sum of InvestedValue of each company in that sector again sorted on the sum

My current approach to solve these problems is to flatten the nested dictionary to list of tuples and run sorted on it. For example:

To solve 1:

stock_list = []
for sector in stock_dict:
    for stock in stock_dict[sector]:
        stock_list.append((sector, stock, stock_dict[sector][stock]))
sorted_list = sorted(stock_list, key=lambda stock: stock[2], reverse=True)

To solve 2:

sector_list = []
for sector in stock_dict:
    sector_list.append((sector,sum(stock_dict[sector].values())))
sorted_sector_list = sorted(sector_list, key=lambda sector: sector[1], reverse=True)

IS there a better approach i.e. sort directly on the nested dictionary without having to flatten it into the list ?

Body:
If you uses pandas, it can convert you dict to a dataframe.  You can then unstack the dataframe which will make it long form instead of wide.  Once it's in the long format, you will have null values for any sector which a company does not participate in, you can drop those with dropna(), reset the index and sort values by your desired column.  Once this is done rename your columns to the desired names, and select them in the order you want.  You can take that same df and groupby sector and sum the InvestedValue.

import pandas as pd
stock_dict = {
    "Financial": {"HDFC Bank": 230.25, "Axis Bank": 70.15, "ICICI Bank": 110.45},
    "Automobile": {"Tata Motors": 135.67},
    "Consumer Goods": {"Avenue Supermarket": 190.45, "Godrej Industries": 120.32}
}

df = pd.DataFrame.from_dict(stock_dict, orient='index')
df = df.unstack().dropna().reset_index(name='InvestedValue').sort_values(by='InvestedValue', ascending=False)

df.columns = ['Company','Sector','InvestedValue']
df[['Sector','Company','InvestedValue']]

Output

           Sector             Company  InvestedValue
0       Financial           HDFC Bank         230.25
4  Consumer Goods  Avenue Supermarket         190.45
3      Automobile         Tata Motors         135.67
5  Consumer Goods   Godrej Industries         120.32
2       Financial          ICICI Bank         110.45
1       Financial           Axis Bank          70.15

2nd Part

df.groupby('Sector')['InvestedValue'].sum().reset_index().sort_values(by='InvestedValue', ascending=False)

Output

           Sector  InvestedValue
2       Financial         410.85
1  Consumer Goods         310.77
0      Automobile         135.67


来源: stackexchange

问:
X-axis minor gridlines still not showing even after trying all solutions
My x-axis minor gridlines are not showing, this is my code

```<code>ax = plt.gca()
ax.minorticks_on()
plt.semilogx(data_x1,data_y1,"red")
plt.semilogx(data_x2,data_y2,"blue")
ax.grid(b=True, which='major',axis="both", color='k', linestyle='-', linewidth=0.5)
ax.grid(b=True, which='minor',axis="both", color='k', linestyle='-', linewidth=0.2)
plt.xlabel("frequency(Hz)")
plt.ylabel("Iramp(dB)")
plt.show()
</code>```

enter image description here

答:
Either I'm not sure of what you want, or your code is actually working correctly. The minor grid lines are those between the powers of 10. I made a little example to show a comparison of your plot with the minor grid lines on and off.

```<code>import numpy as np
import matplotlib.pyplot as plt

data_x1  = np.linspace(0,2,10)
data_x2  = np.linspace(0,4,10)
data_y1  = np.random.rand(10)
data_y2  = np.random.rand(10)

fig, axall =plt.subplots(1,2, figsize=(10,5))

# your code with some changes
ax = axall[0]
ax.minorticks_on()
ax.semilogx(data_x1,data_y1,"red")
ax.semilogx(data_x2,data_y2,"blue")
ax.grid(b=True, which='major',axis="both", color='k', linestyle='-', linewidth=0.5)
ax.grid(b=True, which='minor',axis="both", color='k', linestyle='-', linewidth=0.2)
ax.set_xlabel("frequency(Hz)")
ax.set_ylabel("Iramp(dB)")

# code to make the plot on the right.
ax = axall[1]
ax.minorticks_on()
ax.semilogx(data_x1,data_y1,"red")
ax.semilogx(data_x2,data_y2,"blue")
ax.grid(b=True, which='major',axis="both", color='k', linestyle='-', linewidth=0.5)
# ax.grid(b=True, which='minor',axis="both", color='k', linestyle='-', linewidth=0.2)
ax.set_xlabel("frequency(Hz)")
ax.set_ylabel("Iramp(dB)")
plt.show()
</code>```

Note how I commented out your minor grid lines.

ContentLicense: CC BY-SA 4.0

Body:
My x-axis minor gridlines are not showing, this is my code

ax = plt.gca()
ax.minorticks_on()
plt.semilogx(data_x1,data_y1,"red")
plt.semilogx(data_x2,data_y2,"blue")
ax.grid(b=True, which='major',axis="both", color='k', linestyle='-', linewidth=0.5)
ax.grid(b=True, which='minor',axis="both", color='k', linestyle='-', linewidth=0.2)
plt.xlabel("frequency(Hz)")
plt.ylabel("Iramp(dB)")
plt.show()

enter image description here

Body:
Either I'm not sure of what you want, or your code is actually working correctly. The minor grid lines are those between the powers of 10. I made a little example to show a comparison of your plot with the minor grid lines on and off.

import numpy as np
import matplotlib.pyplot as plt

data_x1  = np.linspace(0,2,10)
data_x2  = np.linspace(0,4,10)
data_y1  = np.random.rand(10)
data_y2  = np.random.rand(10)

fig, axall =plt.subplots(1,2, figsize=(10,5))

# your code with some changes
ax = axall[0]
ax.minorticks_on()
ax.semilogx(data_x1,data_y1,"red")
ax.semilogx(data_x2,data_y2,"blue")
ax.grid(b=True, which='major',axis="both", color='k', linestyle='-', linewidth=0.5)
ax.grid(b=True, which='minor',axis="both", color='k', linestyle='-', linewidth=0.2)
ax.set_xlabel("frequency(Hz)")
ax.set_ylabel("Iramp(dB)")

# code to make the plot on the right.
ax = axall[1]
ax.minorticks_on()
ax.semilogx(data_x1,data_y1,"red")
ax.semilogx(data_x2,data_y2,"blue")
ax.grid(b=True, which='major',axis="both", color='k', linestyle='-', linewidth=0.5)
# ax.grid(b=True, which='minor',axis="both", color='k', linestyle='-', linewidth=0.2)
ax.set_xlabel("frequency(Hz)")
ax.set_ylabel("Iramp(dB)")
plt.show()

Note how I commented out your minor grid lines.


问:
'mc.cores' > 1 is not supported on Windows
I am new to programming and I am trying to use parallel processing for R in windows, using an existing code.

Following is the snippet of my code:

```<code>
if (length(grep("linux", R.version$os)) == 1){
    num_cores = detectCores()
    impact_list <- mclapply(len_a, impact_func, mc.cores = (num_cores - 1))
  }
  # else if(length(grep("mingw32", R.version$os)) == 1){
  #   num_cores = detectCores()
  #   impact_list <- mclapply(len_a, impact_func, mc.cores = (num_cores - 1))
  #
  # }
  else{
    impact_list <- lapply(len_a, impact_func)
  }
  return(sum(unlist(impact_list, use.names = F)))
</code>```

This works fine, I am using R on windows so the code enters in 'else' statement and it runs the code using lapply() and not by parallel processing.

I have added the 'else if' statement to make it work for windows. So when I un-comment 'else if' block of code and run it, I am getting an error "'mc.cores' > 1 is not supported on Windows".
Please suggest how can I use parallel processing in windows, so that less time is taken to run the code.
Any help will be appreciated.

答:
(disclaimer: I'm author of the future framework here)

The future.apply package provides parallel versions of R's built-in "apply" functions.  It's cross platform, i.e. it works on Linux, macOS, and Windows. The package allows you to often just replace an existing lapply() with a future_lapply() call, e.g.

library(future.apply)
plan(multisession)

your_fcn <- function(len_a) {
  impact_list <- future_lapply(len_a, impact_func)
  sum(unlist(impact_list, use.names = FALSE))
}
```

Regarding mclapply() per se: If you use parallel::mclapply() in your code, make sure that there is always an option not to use it.  The reason is that it is not guaranteed to work in all environment, that is, it might be unstable and crash R.  In R-devel thread 'mclapply returns NULLs on MacOS when running GAM' (https://stat.ethz.ch/pipermail/r-devel/2020-April/079384.html), the author of mclapply() wrote on 2020-04-28:

Do NOT use mcparallel() in packages except as a non-default option that user can set for the reasons Henrik explained. Multicore is intended for HPC applications that need to use many cores for computing-heavy jobs, but it does not play well with RStudio and more importantly you don't know the resource available so only the user can tell you when it's safe to use. Multi-core machines are often shared so using all detected cores is a very bad idea. The user should be able to explicitly enable it, but it should not be enabled by default.

Body:
I am new to programming and I am trying to use parallel processing for R in windows, using an existing code.

Following is the snippet of my code:

if (length(grep("linux", R.version$os)) == 1){
    num_cores = detectCores()
    impact_list <- mclapply(len_a, impact_func, mc.cores = (num_cores - 1))
  }
  # else if(length(grep("mingw32", R.version$os)) == 1){
  #   num_cores = detectCores()
  #   impact_list <- mclapply(len_a, impact_func, mc.cores = (num_cores - 1))
  #
  # }
  else{
    impact_list <- lapply(len_a, impact_func)
  }
  return(sum(unlist(impact_list, use.names = F)))

This works fine, I am using R on windows so the code enters in 'else' statement and it runs the code using lapply() and not by parallel processing.

I have added the 'else if' statement to make it work for windows. So when I un-comment 'else if' block of code and run it, I am getting an error "'mc.cores' > 1 is not supported on Windows".
Please suggest how can I use parallel processing in windows, so that less time is taken to run the code.
Any help will be appreciated.

Body:
(disclaimer: I'm author of the future framework here)

The future.apply package provides parallel versions of R's built-in "apply" functions.  It's cross platform, i.e. it works on Linux, macOS, and Windows. The package allows you to often just replace an existing lapply() with a future_lapply() call, e.g.

library(future.apply)
plan(multisession)

your_fcn <- function(len_a) {
  impact_list <- future_lapply(len_a, impact_func)
  sum(unlist(impact_list, use.names = FALSE))
}

Regarding mclapply() per se: If you use parallel::mclapply() in your code, make sure that there is always an option not to use it.  The reason is that it is not guaranteed to work in all environment, that is, it might be unstable and crash R.  In R-devel thread 'mclapply returns NULLs on MacOS when running GAM' (https://stat.ethz.ch/pipermail/r-devel/2020-April/079384.html), the author of mclapply() wrote on 2020-04-28:

Do NOT use mcparallel() in packages except as a non-default option that user can set for the reasons Henrik explained. Multicore is intended for HPC applications that need to use many cores for computing-heavy jobs, but it does not play well with RStudio and more importantly you don't know the resource available so only the user can tell you when it's safe to use. Multi-core machines are often shared so using all detected cores is a very bad idea. The user should be able to explicitly enable it, but it should not be enabled by default.


问:
GetHashCode() gives different results on different servers?
I declared a C# line of code like so

```<code>int hashcode = "apple".GetHashCode();
</code>```

On my computer, a computer at work, and a friend's computer, the result was 1657858284.   On a development server, the result was 1548091822.  Is there a way for me to tell the project to always make GetHashCode() yield 1657858284, regardless of which server it is on?

more notes
At first, i noticed there was a difference in versions...the 1657858284 results came from .NET 3.5 and .NET 4.0.  The 1548091822 came from .NET 2.0.

I then told visual studios 2010 to compile project as a .net 2.0 project, but it still gave me 1657858284.

答:
If you need to have a checksum that e.g. allows you to quickly verify data integrity in transport, simply run it through a (cryptographic) hash with appropriate number of bits, as

```<code>- MD5
- SHA256
- SHA1
- fletcher
</code>```

.Net's GetHashCode is not meant to identify anything (32 bits is going to result in collisions very soon anyway, which is why you can't use it to identify string anyway.)

Note that even the above four will allow collisions (but less soon); so be sure to only use it as a checksum, not identification.

ContentLicense: CC BY-SA 3.0

Body:
I declared a C# line of code like so

int hashcode = "apple".GetHashCode();

On my computer, a computer at work, and a friend's computer, the result was 1657858284.   On a development server, the result was 1548091822.  Is there a way for me to tell the project to always make GetHashCode() yield 1657858284, regardless of which server it is on?

more notes
At first, i noticed there was a difference in versions...the 1657858284 results came from .NET 3.5 and .NET 4.0.  The 1548091822 came from .NET 2.0.

I then told visual studios 2010 to compile project as a .net 2.0 project, but it still gave me 1657858284.

Body:
If you need to have a checksum that e.g. allows you to quickly verify data integrity in transport, simply run it through a (cryptographic) hash with appropriate number of bits, as

- MD5
- SHA256
- SHA1
- fletcher

.Net's GetHashCode is not meant to identify anything (32 bits is going to result in collisions very soon anyway, which is why you can't use it to identify string anyway.)

Note that even the above four will allow collisions (but less soon); so be sure to only use it as a checksum, not identification.


问:
suggestion for improving my long python code with a shorter and correct version
As a part of an online exercise, I want to Write a function, persistence, that takes in a positive parameter num and returns its
multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
For example:

persistence(39) => 3  # Because 3*9 = 27, 2*7 = 14, 1*4=4
                       # and 4 has only one digit.

persistence(999) => 4 # Because 9*9*9 = 729, 7*2*9 = 126,
                       # 1*2*6 = 12, and finally 1*2 = 2.

persistence(4) => 0   # Because 4 is already a one-digit number.

This is my code:

```<code>def persistence(n):
    count=0
    if n<10:
        return(count)
    else:
        count+=1
        a=([int(d) for d in str(n)])
        result = 1
        for i in a:
            result=result*i
        if result<10:
            return(count)
        else:
            count+=1
            a=([int(d) for d in str(result)])
            result1 = 1
            for i in a:
                result1=result1*i
                if result1<10:
                    return(count)
                else:
                    count+=1
                    a=([int(d) for d in str(result1)])
                    result2=1
                    for i in a:
                        result2=result2*i
                        if result2<10:
                            return(count)
                        else:
                            count+=1
                            a=([int(d) for d in str(result1)])
                            result3=1
                            for i in a:
                                result3=result3*i
                                if result3<10:
                                    return(count)
</code>```

but when I try n=999 it gives me 2 which is incorrect. Also it is limited to only 4 multiplicative persistence. How can I improve this code. Tnx in advance!

答:
Your code does not work because you don't know how many times you need to perform the operation to get a single digit number. What you can do in this situation is create a loop and let it run as long as the number is greater than 10. You can try something like this:

```<code>from functools import reduce
from operator import mul

def persistence(n):
    count = 0
    while n >= 10:
        n = reduce(mul, map(int, str(n)))
        count += 1
    return count
</code>```

And the reason why it does not work for 999 is because the if statement in the second for loop. You are checking if result1 is smaller than 10 inside the loop.

Body:
As a part of an online exercise, I want to Write a function, persistence, that takes in a positive parameter num and returns its
multiplicative persistence, which is the number of times you must multiply the digits in num until you reach a single digit.
For example:

persistence(39) => 3  # Because 3*9 = 27, 2*7 = 14, 1*4=4
                       # and 4 has only one digit.

persistence(999) => 4 # Because 9*9*9 = 729, 7*2*9 = 126,
                       # 1*2*6 = 12, and finally 1*2 = 2.

persistence(4) => 0   # Because 4 is already a one-digit number.

This is my code:

def persistence(n):
    count=0
    if n<10:
        return(count)
    else:
        count+=1
        a=([int(d) for d in str(n)])
        result = 1
        for i in a:
            result=result*i
        if result<10:
            return(count)
        else:
            count+=1
            a=([int(d) for d in str(result)])
            result1 = 1
            for i in a:
                result1=result1*i
                if result1<10:
                    return(count)
                else:
                    count+=1
                    a=([int(d) for d in str(result1)])
                    result2=1
                    for i in a:
                        result2=result2*i
                        if result2<10:
                            return(count)
                        else:
                            count+=1
                            a=([int(d) for d in str(result1)])
                            result3=1
                            for i in a:
                                result3=result3*i
                                if result3<10:
                                    return(count)

but when I try n=999 it gives me 2 which is incorrect. Also it is limited to only 4 multiplicative persistence. How can I improve this code. Tnx in advance!

Body:
Your code does not work because you don't know how many times you need to perform the operation to get a single digit number. What you can do in this situation is create a loop and let it run as long as the number is greater than 10. You can try something like this:

from functools import reduce
from operator import mul

def persistence(n):
    count = 0
    while n >= 10:
        n = reduce(mul, map(int, str(n)))
        count += 1
    return count

And the reason why it does not work for 999 is because the if statement in the second for loop. You are checking if result1 is smaller than 10 inside the loop.


问:
Apexcharts - Label colours do not match
I've assigned three different colours to the labels, but the colour dots always show up as Blue, Green and Yellow. I'm pretty sure I've done something wrong.

The code I've written is:

```<code>var pieSimpleChart = {
  chart: {
    height: 350,
    type: 'pie',
  },
  legend: {
    position: 'bottom'
  },
  labels: ["IT", "Product Development", "Sales"],
  series: [2, 2, 6],
  fill: {
    colors: ["#447b40", "#cc7870", "#e74ce4"]
  }
}

var chart = new ApexCharts(document.querySelector("#task-pie-chart"), pieSimpleChart);
chart.render();
</code>```

How can I match the labels to my selected colours?

答:
Use backgroundColor instead off fill: colors.

Also, you should use the dataset object for passing the values:

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'pie',
    data: {
        labels: ["IT", "Product Development", "Sales"],
        datasets: [{
            backgroundColor: [
                "#ff0000",
                "#00ff00",
                "#0000ff"
            ],
            data: [2, 2, 6]
        }]
    },
    options: {
        legend: {
            position: 'bottom'
        }
    }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<div class="container">
  <div>
    <canvas id="myChart"></canvas>
  </div>
</div></code>```

Title: Apexcharts - Label colours do not match

Body:
I've assigned three different colours to the labels, but the colour dots always show up as Blue, Green and Yellow. I'm pretty sure I've done something wrong.

The code I've written is:

var pieSimpleChart = {
  chart: {
    height: 350,
    type: 'pie',
  },
  legend: {
    position: 'bottom'
  },
  labels: ["IT", "Product Development", "Sales"],
  series: [2, 2, 6],
  fill: {
    colors: ["#447b40", "#cc7870", "#e74ce4"]
  }
}

var chart = new ApexCharts(document.querySelector("#task-pie-chart"), pieSimpleChart);
chart.render();

How can I match the labels to my selected colours?

Body:
Use backgroundColor instead off fill: colors.

Also, you should use the dataset object for passing the values:

var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
    type: 'pie',
    data: {
        labels: ["IT", "Product Development", "Sales"],
        datasets: [{
            backgroundColor: [
                "#ff0000",
                "#00ff00",
                "#0000ff"
            ],
            data: [2, 2, 6]
        }]
    },
    options: {
        legend: {
            position: 'bottom'
        }
    }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>
<div class="container">
  <div>
    <canvas id="myChart"></canvas>
  </div>
</div>


问:
Unable to link font awesome file in my working file
My working file is in this path: programming\neumorphic\neumorphic form\myfile.html
And my all.css file is in this path: programming\css\all.css

I'm trying to link the all.css file with my working file.But result is not showing.

The link path: programming\css\all.css

答:
To use font awesome icons offline download them here https://fontawesome.com/v4.7.0/get-started/ and follow the steps provided.

Move font awsome downlaod into direcotry.

Then in your css  tag add <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">

That's a basic explanation but more information can be found on the above provided link as well.

Body:
To use font awesome icons offline download them here https://fontawesome.com/v4.7.0/get-started/ and follow the steps provided.

Move font awsome downlaod into direcotry.

Then in your css <head> tag add <link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">

That's a basic explanation but more information can be found on the above provided link as well.


问:
Baidu web search engine API
The English version of baidu doesn't have meaningfull information about how to obtain or use their API. I've tried writing several emails, but no response so far.
Google translate tries to translate the Chinese version, but with no luck.
Has anyone yet found a way or someone to give more info about web/images search using Baudi API?</p>

答:
Disclaimer: I work at SerpApi.

Seems like baidu doesn't have an API to get search results.
You can use SerpApi in order to get scraped results for organic search.
You can check playgound and documentation to find out if this will cover your needs. There is also a .net client library.

Title: Baidu web search engine API


问:
Find all integers that multiplied gives X?
If I have a number, let's say 12, how can I calculate all integers that multiplied will give 12?

Example: If 12, then the solution would be 1x12, 2x6, 3x4.

How would that be done?

答: Check from 1 to sqrt(x) for divisors. Use those and their pairs. Watch out for squares.


问:
SessionStorage.getitem not working when loading page
I am having an issue trying to use storagesession.  I have gotten it to work, but as soon as I insert some ifthen logic, it breaks.  Below is the working code.  The bottom code is when I update the window.onload function that makes it break.  Does anybody know why its breaking and how I can fix this?  I am using only html/javascript and no server is being used. Thanks so much!</p>

```<code><!DOCTYPE html>
<!-- saved from url=(0014)about:internet -->
<html lang="en">
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="container">

<ul class="vertical-nav">

<li><a href="">Fruit</a>
<ul class="sub-menu">
<li><a href="test.html" onclick="ChangeToApple()">Apple</a></li>
<li><a href="test.html" onclick="ChangeToGrape()">Grape</a></li>
</ul>
</li>
</ul>

<div id="ShowDept">

</div>
</div>
</body>
</code>```

```<code><script>

  window.onload = function() {
  var x = sessionStorage.getItem("Dept");

document.getElementById("ShowDept").innerHTML = x;
 }

function ChangeToApple() {
sessionStorage.Dept = "Apple";
}

function ChangeToGrape() {
sessionStorage.Dept = "Grape";
}

 </script>
</code>```

```<code>  window.onload = function() {
  var x = sessionStorage.getItem("Dept");

      if (x = "Apple") {

} else if (x = "Grape") {

}
document.getElementById("ShowDept").innerHTML = x;
 }
</code>```

答:
```<code>var x = sessionStorage.getItem("Dept");

if (x = "Apple") {

} else if (x = "Grape") {

}
document.getElementById("ShowDept").innerHTML = x;
</code>```

x = "Apple" means "Assign the string 'Apple' to the variable x. It does not check if x equals "Apple"; use x === "Apple" for that. Because you're doing an assignment in your if statement, you're going to always see Apple in your HTML.

Body:
I am having an issue trying to use storagesession.  I have gotten it to work, but as soon as I insert some ifthen logic, it breaks.  Below is the working code.  The bottom code is when I update the window.onload function that makes it break.  Does anybody know why its breaking and how I can fix this?  I am using only html/javascript and no server is being used. Thanks so much!

<!DOCTYPE html>

<title>Test</title>

Fruit

Apple

Grape

  window.onload = function() {
  var x = sessionStorage.getItem("Dept");

      if (x = "Apple") {

} else if (x = "Grape") {

}
document.getElementById("ShowDept").innerHTML = x;
 }

Body:
var x = sessionStorage.getItem("Dept");

if (x = "Apple") {

} else if (x = "Grape") {

}
document.getElementById("ShowDept").innerHTML = x;

x = "Apple" means "Assign the string 'Apple' to the variable x. It does not check if x equals "Apple"; use x === "Apple" for that. Because you're doing an assignment in your if statement, you're going to always see Apple in your HTML.


问:
Get a line of space-separated integers from stdio without knowing how much they are (C++)
I'm dealing with a competitive programming challenge in which I have to take a line of space-separated integers from standard input, put them into an array, and treat them in a certain way. The problem is that I don't know how many integer I may get in each test case.
In case I know, my code would be like:

```<code>int n; // number of integers;
int arr[n];
for(int i = 0; i < n; i++)
    cin >> arr[i];
</code>```

In case I don't have 'n', how would I achieve the same thing?

答:
Use vectors beacuse vectors are dynamic in size. Keep pushing elements into vector until inputs are there.</p>

```<code>std::vector<int> v;
int temp;
while (std::cin >> temp) {
     v.push_back(temp);
}
</code>```

Body:
I'm dealing with a competitive programming challenge in which I have to take a line of space-separated integers from standard input, put them into an array, and treat them in a certain way. The problem is that I don't know how many integer I may get in each test case.
In case I know, my code would be like:

int n; // number of integers;
int arr[n];
for(int i = 0; i < n; i++)
    cin >> arr[i];

In case I don't have 'n', how would I achieve the same thing?

Body:
Use vectors beacuse vectors are dynamic in size. Keep pushing elements into vector until inputs are there.

std::vector<int> v;
int temp;
while (std::cin >> temp) {
     v.push_back(temp);
}


问:
Filter RDD's csv with JSON field using Spark/Scala
i'm studying spark/scala and i need want to filter a RDD by a specific field on a column, in this case, user.

I want to return a RDD with the users ["Joe","Plank","Willy"] but can't seem to figure out how

This is my RDD:

```<code>2020-03-01T00:00:05Z    my.local5.url   {"request_method":"GET","request_length":281,"user":"Joe"}
2020-03-01T00:00:05Z    my.local2.url   {"request_method":"GET","request_length":281,"user":"Plank"}
2020-03-01T00:00:05Z    my.local2.url   {"request_method":"GET","request_length":281,"user":"Willy"}
2020-03-01T00:00:05Z    my.local6.url   {"request_method":"GET","request_length":281,"user":"Plank"}
2020-03-01T00:00:05Z    my.local2.url   {"request_method":"GET","request_length":281,"user":"Plank"}
2020-03-01T00:00:05Z    my.local2.url   {"request_method":"GET","request_length":281,"user":"Tracy"}
2020-03-01T00:00:05Z    my.local6.url   {"request_method":"GET","request_length":281,"user":"Roger"}
</code>```

Expected output:

```<code>2020-03-01T00:00:05Z    my.local5.url   {"request_method":"GET","request_length":281,"user":"Joe"}
2020-03-01T00:00:05Z    my.local2.url   {"request_method":"GET","request_length":281,"user":"Plank"}
2020-03-01T00:00:05Z    my.local2.url   {"request_method":"GET","request_length":281,"user":"Willy"}
2020-03-01T00:00:05Z    my.local6.url   {"request_method":"GET","request_length":281,"user":"Plank"}
2020-03-01T00:00:05Z    my.local2.url   {"request_method":"GET","request_length":281,"user":"Plank"}
</code>```

I've extract the rdd using spark with something like this(pseudocode):

```<code>val sparkConf = new SparkConf().setAppName("MyApp")
master.foreach(sparkConf.setMaster)
val sc = new SparkContext(sparkConf)

val rdd = sc.textFile(inputDir)
rdd.filter(_.contains("\"user\":\"THE_ARRAY_OF_NAMES_"))
</code>```

答:
It's easier for you to use dataframes.

Using from_json function you can transform that json column into multiple columns

```<code>val jsonSchema = StructType(Array(
    StructField("request_method",StringType,true),
    StructField("request_length",IntegerType,true),
    StructField("user",StringType,true)
  ))

val myDf = spark.read.option("header", "true").csv(path)
val formatedDf = myDf.withColumn("formated_json", from_json($"column_name", jsonSchema)
.select($"formated_json.*")
.where($"user".isin("Joe","Plank","Willy")

formatedDf.show
</code>```

But if you want a RDD aproach, please let me know.

Edit with RDD version:
Remember this is one of manny approaches

```<code>//Define a regex pattern
val Pattern = """(?i)"user":"([a-zA-Z]+)"""".r
//Define a Set with your filtered values
val userSet = Set("Joe","Plank","Willy")
//Filter only the values you want
val filteredRdd = rdd.filter( x => {
    //Extract the user using the pattern we just declared
    val user = for(m <- Pattern.findFirstMatchIn(x)) yield m.group(1)
    //If the user variable is equal with one of your set values then this statement will return true and based on that the row will be kept
    userSet(user.getOrElse(""))
})
</code>```

To see if the result is right, you can use:

```<code>filteredRdd.collect().foreach(println)
</code>```

Body:
i'm studying spark/scala and i need want to filter a RDD by a specific field on a column, in this case, user.

I want to return a RDD with the users ["Joe","Plank","Willy"] but can't seem to figure out how

This is my RDD:

2020-03-01T00:00:05Z    my.local5.url   {"request_method":"GET","request_length":281,"user":"Joe"}
2020-03-01T00:00:05Z    my.local2.url   {"request_method":"GET","request_length":281,"user":"Plank"}
2020-03-01T00:00:05Z    my.local2.url   {"request_method":"GET","request_length":281,"user":"Willy"}
2020-03-01T00:00:05Z    my.local6.url   {"request_method":"GET","request_length":281,"user":"Plank"}
2020-03-01T00:00:05Z    my.local2.url   {"request_method":"GET","request_length":281,"user":"Plank"}
2020-03-01T00:00:05Z    my.local2.url   {"request_method":"GET","request_length":281,"user":"Tracy"}
2020-03-01T00:00:05Z    my.local6.url   {"request_method":"GET","request_length":281,"user":"Roger"}

Expected output:

2020-03-01T00:00:05Z    my.local5.url   {"request_method":"GET","request_length":281,"user":"Joe"}
2020-03-01T00:00:05Z    my.local2.url   {"request_method":"GET","request_length":281,"user":"Plank"}
2020-03-01T00:00:05Z    my.local2.url   {"request_method":"GET","request_length":281,"user":"Willy"}
2020-03-01T00:00:05Z    my.local6.url   {"request_method":"GET","request_length":281,"user":"Plank"}
2020-03-01T00:00:05Z    my.local2.url   {"request_method":"GET","request_length":281,"user":"Plank"}

I've extract the rdd using spark with something like this(pseudocode):

val sparkConf = new SparkConf().setAppName("MyApp")
master.foreach(sparkConf.setMaster)
val sc = new SparkContext(sparkConf)

val rdd = sc.textFile(inputDir)
rdd.filter(_.contains("\"user\":\"THE_ARRAY_OF_NAMES_"))

Body:
It's easier for you to use dataframes.

Using from_json function you can transform that json column into multiple columns

val jsonSchema = StructType(Array(
    StructField("request_method",StringType,true),
    StructField("request_length",IntegerType,true),
    StructField("user",StringType,true)
  ))

val myDf = spark.read.option("header", "true").csv(path)
val formatedDf = myDf.withColumn("formated_json", from_json($"column_name", jsonSchema)
.select($"formated_json.*")
.where($"user".isin("Joe","Plank","Willy")

formatedDf.show

But if you want a RDD aproach, please let me know.

Edit with RDD version:
Remember this is one of manny approaches

//Define a regex pattern
val Pattern = """(?i)"user":"([a-zA-Z]+)"""".r
//Define a Set with your filtered values
val userSet = Set("Joe","Plank","Willy")
//Filter only the values you want
val filteredRdd = rdd.filter( x => {
    //Extract the user using the pattern we just declared
    val user = for(m <- Pattern.findFirstMatchIn(x)) yield m.group(1)
    //If the user variable is equal with one of your set values then this statement will return true and based on that the row will be kept
    userSet(user.getOrElse(""))
})

To see if the result is right, you can use:

filteredRdd.collect().foreach(println)


问:
Deploying JavaFx Application jar
I am still learning !!!
I am using IDEA 2020.1 Community, Windows 10, Java 1.8, JavaFx 11.02 ans Gluon SceneBuilder 8.5.0

My application (rar file attached) uses two modules and was working fine, including as an exe file produced by launc4j.

Then to keep learning I added a second Stage with WebView to display a small User Guide as a single html file.
Both the primary stage and the secondary stage use the same Controller, where the help window gets initialized:

```<code>    // initializing help window
    @FXML
    public void initialize() throws IOException {
        webEngine = helpWebView.getEngine();
        File file = new File(String.valueOf(getClass().getResource("RateCalculatorHelp.html")));
        fpath = file.getPath();
        webEngine.load(fpath);
    }
</code>```

The secondary stage is made available to the Controller by Main.start:

```<code>        RateOfChangeController controller = loader.getController();
        controller.initHelpStage(anotherStage);
</code>```

The Controller uses the helpStage variable to show or close the Window:

```<code>    public void initHelpStage(Stage anotherStage) {
        helpStage =  anotherStage;
    }
    public void showUserGuide(ActionEvent actionEvent) {
        helpStage.show();
    }
    public void quitApp(ActionEvent actionEvent) {
        helpStage.close();
        System.exit(0);
    }
</code>```

It works file when running Main within IDEA. Then I produced a jar file. When running it from inside IDEA everything
works fine except for the help window, it shows up but is empty, the html file does not get loaded !  And the html file is
included in the jar.

Problem in configuring the artifact ?  Some advise or pointers to relevant examples would be most welcome.

答:
I found the following work-around: a method in the Controller will read the html file et return its content as a string:

```<code>    public String readFromFile(String filename) throws IOException {
        // borrowed from alvinalexander.com
        InputStream is = getClass().getResourceAsStream(filename);
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) { sb.append(line); }
        is.close();
        return sb.toString();
    }
</code>```

and then the initialize() method of the controller becomes:

```<code>    // initializing help window
    @FXML
    public void initialize() throws IOException {
        webEngine = helpWebView.getEngine();
        String html = readFromFile("RateCalculatorHelp.html");
        webEngine.loadContent(html);
    }
</code>```

And now it works from the jar file run from the IDEA, by double-clicking the jar file in Windows Explorer, or in the form of an exe file produced by launc4j.

I am still interested to hear from anyone who could explain why the first version did not work !

Title: Deploying JavaFx Application jar

Body:
I am still learning !!!
I am using IDEA 2020.1 Community, Windows 10, Java 1.8, JavaFx 11.02 ans Gluon SceneBuilder 8.5.0

My application (rar file attached) uses two modules and was working fine, including as an exe file produced by launc4j.

Then to keep learning I added a second Stage with WebView to display a small User Guide as a single html file.
Both the primary stage and the secondary stage use the same Controller, where the help window gets initialized:

    // initializing help window
    @FXML
    public void initialize() throws IOException {
        webEngine = helpWebView.getEngine();
        File file = new File(String.valueOf(getClass().getResource("RateCalculatorHelp.html")));
        fpath = file.getPath();
        webEngine.load(fpath);
    }

The secondary stage is made available to the Controller by Main.start:

        RateOfChangeController controller = loader.getController();
        controller.initHelpStage(anotherStage);

The Controller uses the helpStage variable to show or close the Window:

    public void initHelpStage(Stage anotherStage) {
        helpStage =  anotherStage;
    }
    public void showUserGuide(ActionEvent actionEvent) {
        helpStage.show();
    }
    public void quitApp(ActionEvent actionEvent) {
        helpStage.close();
        System.exit(0);
    }

It works file when running Main within IDEA. Then I produced a jar file. When running it from inside IDEA everything
works fine except for the help window, it shows up but is empty, the html file does not get loaded !  And the html file is
included in the jar.

Problem in configuring the artifact ?  Some advise or pointers to relevant examples would be most welcome.

Body:
I found the following work-around: a method in the Controller will read the html file et return its content as a string:

    public String readFromFile(String filename) throws IOException {
        // borrowed from alvinalexander.com
        InputStream is = getClass().getResourceAsStream(filename);
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) { sb.append(line); }
        is.close();
        return sb.toString();
    }

and then the initialize() method of the controller becomes:

    // initializing help window
    @FXML
    public void initialize() throws IOException {
        webEngine = helpWebView.getEngine();
        String html = readFromFile("RateCalculatorHelp.html");
        webEngine.loadContent(html);
    }

And now it works from the jar file run from the IDEA, by double-clicking the jar file in Windows Explorer, or in the form of an exe file produced by launc4j.

I am still interested to hear from anyone who could explain why the first version did not work !


问:
Org-mode cache does not work when using var
The Org-mode cache option, see https://orgmode.org/manual/cache.html, saves a lot of time when exporting to html. Unfortunately I cannot get it working when passing var parameters.

This is how it looks like in Org:

```<code>  #+tblname: howtocache
  | x | y |
  |---+---|
  | 1 | 5 |
  | 2 | 2 |
  | 3 | 1 |
  | 4 | 6 |
  | 5 | 3 |

  #+begin_src gnuplot :cache yes :var data=howtocache :exports code :file howtocache.png
  reset

  plot data u 1:2 w l
  #+end_src

  #+RESULTS[4a0d86e3196a769ad675be613318b8fb77d47f2e]:
  [[file:howtocache.png]]
</code>```

When I evaluate the gnuplot block I always get a new hash value.

In the gnuplot buffer I see the data is provided from a different temporary file.

One run:
data = "c:/Users/harald/AppData/Local/Temp/babel-14152bAf/gnuplot-141521-y"

Another run:
data = "c:/Users/harald/AppData/Local/Temp/babel-14152bAf/gnuplot-14152OnU"

Probably the hash is calculated based on the filename.

The main question is: How can I use cache together with var?

答:
Thanks to your infomration about the changing temp file, I've found a general solution for gnuplot caching that works for both regular execution and exporting.  Rather than passing data directly to the gnuplot src block and letting ob-gnuplot write a temp file, I write the temp file myself, cached it, and passed the file name to the gnuplot src block instead.  This works because ob-gnuplot only writes files for vectors in its input, and we're bypassing that by giving it a string instead.

Here's some code to illustrate, based on the example above:

```<code>  #+tblname: howtocache
  | x | y |
  |---+---|
  | 1 | 5 |
  | 2 | 2 |
  | 3 | 1 |
  | 4 | 6 |
  | 5 | 3 |

  #+name: data-file
  #+begin_src elisp :cache yes :var data=howtocache
  (org-babel-gnuplot-table-to-data data (org-babel-temp-file "gnuplot-") '())
  #+end_src

  #+RESULTS[25d02647c9b4a748ce6798d81e70d72c3ace0846]: data-file
  : /var/folders/n4/vg52wwmn02xbfx_4g2l53z1m0000gn/T/babel-eiHU75/gnuplot-8osPqw

  #+begin_src gnuplot :cache yes :var data=data-file :exports code :file howtocache.png
  reset

  plot data u 1:2 w l
  #+end_src

  #+RESULTS[af6331cf9eac29a503e86eb07dc76a1a0d808f85]:
  [[file:howtocache.png]]
</code>```

Hopefully this will be useful to future googlers of this thread, with the same use-case

Body:
The Org-mode cache option, see https://orgmode.org/manual/cache.html, saves a lot of time when exporting to html. Unfortunately I cannot get it working when passing var parameters.

This is how it looks like in Org:

  #+tblname: howtocache
  | x | y |
  |---+---|
  | 1 | 5 |
  | 2 | 2 |
  | 3 | 1 |
  | 4 | 6 |
  | 5 | 3 |

  #+begin_src gnuplot :cache yes :var data=howtocache :exports code :file howtocache.png
  reset

  plot data u 1:2 w l
  #+end_src

  #+RESULTS[4a0d86e3196a769ad675be613318b8fb77d47f2e]:
  [[file:howtocache.png]]

When I evaluate the gnuplot block I always get a new hash value.

In the gnuplot buffer I see the data is provided from a different temporary file.

One run:
data = "c:/Users/harald/AppData/Local/Temp/babel-14152bAf/gnuplot-141521-y"

Another run:
data = "c:/Users/harald/AppData/Local/Temp/babel-14152bAf/gnuplot-14152OnU"

Probably the hash is calculated based on the filename.

The main question is: How can I use cache together with var?

Body:
Thanks to your infomration about the changing temp file, I've found a general solution for gnuplot caching that works for both regular execution and exporting.  Rather than passing data directly to the gnuplot src block and letting ob-gnuplot write a temp file, I write the temp file myself, cached it, and passed the file name to the gnuplot src block instead.  This works because ob-gnuplot only writes files for vectors in its input, and we're bypassing that by giving it a string instead.

Here's some code to illustrate, based on the example above:

  #+tblname: howtocache
  | x | y |
  |---+---|
  | 1 | 5 |
  | 2 | 2 |
  | 3 | 1 |
  | 4 | 6 |
  | 5 | 3 |

  #+name: data-file
  #+begin_src elisp :cache yes :var data=howtocache
  (org-babel-gnuplot-table-to-data data (org-babel-temp-file "gnuplot-") '())
  #+end_src

  #+RESULTS[25d02647c9b4a748ce6798d81e70d72c3ace0846]: data-file
  : /var/folders/n4/vg52wwmn02xbfx_4g2l53z1m0000gn/T/babel-eiHU75/gnuplot-8osPqw

  #+begin_src gnuplot :cache yes :var data=data-file :exports code :file howtocache.png
  reset

  plot data u 1:2 w l
  #+end_src

  #+RESULTS[af6331cf9eac29a503e86eb07dc76a1a0d808f85]:
  [[file:howtocache.png]]

Hopefully this will be useful to future googlers of this thread, with the same use-case


问:
SVG: insert image in arc
So I have a "progress arc" written in SVG. The progress is drawn on the arc using this CSS rule:

```<code>--percent: 30;
stroke-dashoffset: calc(436 - (var(--percent) * 436 / 100));
</code>```

I want to put an indicator at the end of the progress arc (seen in red) but how can I determine the position to insert the image in?

Thanks

答:
In order to calculate the position for the indicator you can use the getPointAtLength() method like so:

Please read the comments in my code.

// the center of the progress arc
let c= {x:0,y:90}
// the radius of the progress arc
let r = 70;
// the starting and the ending angle for the progress arc
let a1 = -210 * Math.PI / 180;
let a2 = 30 * Math.PI / 180;
// the starting point for the progress arc
let p1 = {
  x: c.x+r*Math.cos(a1),
  y: c.y+r*Math.sin(a1)
}
// the ending point for the progress arc
let p2 = {
  x: c.x+r*Math.cos(a2),
  y: c.y+r*Math.sin(a2)
}
//the value of the d attribute for the base (silver) and the arc (red)
let d = `M${p1.x}, ${p1.y}A${r},${r},0 1 1 ${p2.x}, ${p2.y}`;
base.setAttributeNS(null,"d",d);
arc.setAttributeNS(null,"d",d);

let percent = 30;
//the total length of the arc and the base
//also the value used for the stroke-dasharray
let sda = arc.getTotalLength();
//the value for the stroke-dashoffset
let sdo = sda - (percent*sda/100);
//set the "stroke-dasharray" and the "stroke-dashoffset" for the arc
arc.setAttributeNS(null,"stroke-dasharray",sda);
arc.setAttributeNS(null,"stroke-dashoffset",sdo);

//calculate the position for the indicator: a golden point in this case
let p = arc.getPointAtLength(percent*sda/100)
img.setAttributeNS(null,"cx",p.x);
img.setAttributeNS(null,"cy",p.y);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>svg{border:solid;width:300px}</code>```

<svg viewBox="-100 0 200 150">
  <path id="base" fill="none" stroke="silver" stroke-width="8" stroke-linecap ="round" />
  <path id="arc" fill="none" stroke="red" stroke-width="8" stroke-linecap ="round" />

  <circle id="img" r="2" fill="gold"/>
</svg>```

Title: SVG: insert image in arc

Body:
So I have a "progress arc" written in SVG. The progress is drawn on the arc using this CSS rule:

--percent: 30;
stroke-dashoffset: calc(436 - (var(--percent) * 436 / 100));

I want to put an indicator at the end of the progress arc (seen in red) but how can I determine the position to insert the image in?

Thanks

Body:
In order to calculate the position for the indicator you can use the getPointAtLength() method like so:

Please read the comments in my code.

// the center of the progress arc
let c= {x:0,y:90}
// the radius of the progress arc
let r = 70;
// the starting and the ending angle for the progress arc
let a1 = -210 * Math.PI / 180;
let a2 = 30 * Math.PI / 180;
// the starting point for the progress arc
let p1 = {
  x: c.x+r*Math.cos(a1),
  y: c.y+r*Math.sin(a1)
}
// the ending point for the progress arc
let p2 = {
  x: c.x+r*Math.cos(a2),
  y: c.y+r*Math.sin(a2)
}
//the value of the d attribute for the base (silver) and the arc (red)
let d = `M${p1.x}, ${p1.y}A${r},${r},0 1 1 ${p2.x}, ${p2.y}`;
base.setAttributeNS(null,"d",d);
arc.setAttributeNS(null,"d",d);

let percent = 30;
//the total length of the arc and the base
//also the value used for the stroke-dasharray
let sda = arc.getTotalLength();
//the value for the stroke-dashoffset
let sdo = sda - (percent*sda/100);
//set the "stroke-dasharray" and the "stroke-dashoffset" for the arc
arc.setAttributeNS(null,"stroke-dasharray",sda);
arc.setAttributeNS(null,"stroke-dashoffset",sdo);

//calculate the position for the indicator: a golden point in this case
let p = arc.getPointAtLength(percent*sda/100)
img.setAttributeNS(null,"cx",p.x);
img.setAttributeNS(null,"cy",p.y);

svg{border:solid;width:300px}

<svg viewBox="-100 0 200 150">
  <path id="base" fill="none" stroke="silver" stroke-width="8" stroke-linecap ="round" />
  <path id="arc" fill="none" stroke="red" stroke-width="8" stroke-linecap ="round" />

  <circle id="img" r="2" fill="gold"/>
</svg>


问:
JSON to C# Classes - Unknown property names
let's say I have the following JSON payload;

```<code>  {
   "pagemap": {
    "metatags": [
     {
      "msapplication-task": "name\u003dAbout Tugberk Ugurlu;action-uri\u003d/about;icon-uri\u003d/content/App_Icons/icos/about.ico",
      "msapplication-task": "name\u003dContact;action-uri\u003d/contact;icon-uri\u003d/content/App_Icons/icos/contact.ico",
      "msapplication-task": "name\u003dBlog RSS Feed;action-uri\u003dhttp://feeds.feedburner.com/TugberkUgurlu;icon-uri\u003d/content/App_Icons/icos/rss.ico",
      "msapplication-task": "name\u003dTugberk on Twitter;action-uri\u003dhttp://twitter.com/tourismgeek;icon-uri\u003d/content/App_Icons/icos/twitter.ico",
      "msapplication-starturl": "./",
      "application-name": "Tugberk's Blog",
      "msapplication-tooltip": "bla bla bla..."
     }
    ]
   }
  }
</code>```

The property names under mettags are dynamic. I mean one of them is msapplication-starturl for this request but it might be msapplication-foo for another.

So what would be the best c# classes for this kind of JSON payload?

EDIT

this is the part of JSON format which google search API gives. Also I am using Json.NET. is There any other way than dynamic?

答:
You should look at JSON.NET and JObject for building dynamic loosely typed objects.  If you decide to use it, you should NuGet to download it.

Example:

```<code>var client = new WebClient();
client.Headers.Add("User-Agent", "your user agent here");
var response = client.DownloadString(new Uri("http://www.domain.com/source-page.html"));
JObject jo = JObject.Parse(response);
</code>```

Body:
let's say I have the following JSON payload;

  {
   "pagemap": {
    "metatags": [
     {
      "msapplication-task": "name\u003dAbout Tugberk Ugurlu;action-uri\u003d/about;icon-uri\u003d/content/App_Icons/icos/about.ico",
      "msapplication-task": "name\u003dContact;action-uri\u003d/contact;icon-uri\u003d/content/App_Icons/icos/contact.ico",
      "msapplication-task": "name\u003dBlog RSS Feed;action-uri\u003dhttp://feeds.feedburner.com/TugberkUgurlu;icon-uri\u003d/content/App_Icons/icos/rss.ico",
      "msapplication-task": "name\u003dTugberk on Twitter;action-uri\u003dhttp://twitter.com/tourismgeek;icon-uri\u003d/content/App_Icons/icos/twitter.ico",
      "msapplication-starturl": "./",
      "application-name": "Tugberk's Blog",
      "msapplication-tooltip": "bla bla bla..."
     }
    ]
   }
  }

The property names under mettags are dynamic. I mean one of them is msapplication-starturl for this request but it might be msapplication-foo for another.

So what would be the best c# classes for this kind of JSON payload?

EDIT

this is the part of JSON format which google search API gives. Also I am using Json.NET. is There any other way than dynamic?

Body:
You should look at JSON.NET and JObject for building dynamic loosely typed objects.  If you decide to use it, you should NuGet to download it.

Example:

var client = new WebClient();
client.Headers.Add("User-Agent", "your user agent here");
var response = client.DownloadString(new Uri("http://www.domain.com/source-page.html"));
JObject jo = JObject.Parse(response);


问:
Azure Data Factory Dataflows - dynamic sink paramterers
I'm working on dataflows that will handle my dimensions load.
I wanted it to be as parametrized as it can be so i created generic source and sink (both Azure Synapse).
In debug settings of dataflows i can put requested values (tableName and schema name).
It is working for source without issue however i have no idea why but sink is not reading values

I got
Connection failed
{ "Message": "No value provided for Parameter 'tableName'" } - RunId: 27be90a3-294a-48fa-93f0-d3fc2d6df3f5
but in debug parametes it's provided.
Anyone knows how to fix it?

Debug settings

答:
I tried to reproduce your issue:

Then i configured default value in the sink dataset parameter to solve the issue:


问:
Can Raspberry Pi host Node JS Applications
I am building a management system in node JS for a local business . The application will have a maximum of 10 concurrent users. Most of the tasks of application are basic CRUD operations on MongoDB with minimal processing . The application might generate PDFs but in most cases for one user at a time .I was thinking of hosting it on a local server. Rather than building a proper server , is it possible that I can use a raspberry PI 2/3/4 whichever is suitable to host MongoDB and node JS application and will the PI be able to handle the load so that the application is performing.</p>

答: Yes it can, the main problem will be the storage. How will you manage to store data in a microsd card. </p>


问:
Assembly binding problems when upgrading to .NET Framework 4.8
I need to upgrade my WebApi2 project from 4.7.1 to 4.8 so I did the following:

Changed the Target Framework to 4.8 in the Properties tab

Changed 'targetFramework="net471"' to '"targetFramework=net48"' in the packages.config

Deleted bin and obj folders, and then did a nuget restore

Checked that all referenced files under References\Assemblies point to the SDK v4.8 folder

Rebuilt the solution

Then I changed the following in web.config:

```<code><system.web>
  <compilation debug="true" targetFramework="4.8"/>
  <httpRuntime targetFramework="4.8"/>
</system.web>
</code>```

However I get an exception when running the project:

Could not load file or assembly 'System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

The corresponding section in web.config is:

```<code>  <dependentAssembly>
    <assemblyIdentity name="System.Net.Http" publicKeyToken="B03F5F7F11D50A3A" culture="neutral"/>
    <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0"/>
  </dependentAssembly>
</code>```

The project is part of a larger solution and it references projects which target netstandard2.0. This is however not the problem, because everything was working when still using 4.7.1

Where / what else do I need to check / change to make get the project going using v4.8?

答:
Following the steps as per @Igor 's comment reference the Could not load file or assembly “System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a” solves the problem.

Definitely the best solution.

Body:
I need to upgrade my WebApi2 project from 4.7.1 to 4.8 so I did the following:

Changed the Target Framework to 4.8 in the Properties tab

Changed 'targetFramework="net471"' to '"targetFramework=net48"' in the packages.config

Deleted bin and obj folders, and then did a nuget restore

Checked that all referenced files under References\Assemblies point to the SDK v4.8 folder

Rebuilt the solution

Then I changed the following in web.config:

<system.web>
  <compilation debug="true" targetFramework="4.8"/>
  <httpRuntime targetFramework="4.8"/>
</system.web>

However I get an exception when running the project:

Could not load file or assembly 'System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.IO.FileNotFoundException: Could not load file or assembly 'System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

The corresponding section in web.config is:

  <dependentAssembly>
    <assemblyIdentity name="System.Net.Http" publicKeyToken="B03F5F7F11D50A3A" culture="neutral"/>
    <bindingRedirect oldVersion="0.0.0.0-4.2.0.0" newVersion="4.2.0.0"/>
  </dependentAssembly>

The project is part of a larger solution and it references projects which target netstandard2.0. This is however not the problem, because everything was working when still using 4.7.1

Where / what else do I need to check / change to make get the project going using v4.8?


问:
Android, Multiple Views on screen but only one will respond to touch
I have a main FrameLayout and a collection of balls 5 by 7 (each a View) under it.  I added onTouchEvent() to switch colors.  But regardless which ball I click, only the bottom right ball responds to my touch event (it was the last one to be drawn).  Is there a way to get each ball recognize its own touch event?

A thought: I think this might be happening because I'm inserting each Ball (a View) into the main FrameLayout which is supposed to show only one thing at a time. I think it's like a stack of Views and only the top one is responding.  Any ideas?

in the Ball class

```<code>public class Ball extends View {
    private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    ...
}

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawCircle(x, y, r, mPaint);
}

public boolean onTouchEvent(MotionEvent event) {
    int eventAction = event.getAction();

    if(eventAction == MotionEvent.ACTION_DOWN) {
        switchcolor();
        this.postInvalidate();
        return true;
    } else {
        return false;
    }
}

private void switchcolor() {
    mPaint.setColor(touched ? 0xFFFFFFFF : 0xFFA606E2);
    touched = !touched;
}
</code>```

in main Activity

```<code>FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
...

some loop {
    main.addView(new Ball(this, x, y, radius - margin));
}
</code>```

答:
As you are creating custom builds, just create a field called last one or something like that... and change the color of the ball just if that is the last one:

```<code>some loop {
    Ball ball = new Ball(this, x, y, radius - margin);
    if(this is the last one)
        ball.setLast(true);
    else
        ball.setLast(false);
    main.addView(ball);
}
</code>```

Then, inside the Ball class in its onTouchEvent:

```<code>if(isLast()){
    // do it
}
</code>```

Body:
I have a main FrameLayout and a collection of balls 5 by 7 (each a View) under it.  I added onTouchEvent() to switch colors.  But regardless which ball I click, only the bottom right ball responds to my touch event (it was the last one to be drawn).  Is there a way to get each ball recognize its own touch event?

A thought: I think this might be happening because I'm inserting each Ball (a View) into the main FrameLayout which is supposed to show only one thing at a time. I think it's like a stack of Views and only the top one is responding.  Any ideas?

in the Ball class

public class Ball extends View {
    private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    ...
}

protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    canvas.drawCircle(x, y, r, mPaint);
}

public boolean onTouchEvent(MotionEvent event) {
    int eventAction = event.getAction();

    if(eventAction == MotionEvent.ACTION_DOWN) {
        switchcolor();
        this.postInvalidate();
        return true;
    } else {
        return false;
    }
}

private void switchcolor() {
    mPaint.setColor(touched ? 0xFFFFFFFF : 0xFFA606E2);
    touched = !touched;
}

in main Activity

FrameLayout main = (FrameLayout) findViewById(R.id.main_view);
...

some loop {
    main.addView(new Ball(this, x, y, radius - margin));
}

Body:
As you are creating custom builds, just create a field called last one or something like that... and change the color of the ball just if that is the last one:

some loop {
    Ball ball = new Ball(this, x, y, radius - margin);
    if(this is the last one)
        ball.setLast(true);
    else
        ball.setLast(false);
    main.addView(ball);
}

Then, inside the Ball class in its onTouchEvent:

if(isLast()){
    // do it
}


问:
Timeit.timeit error (name 'func' is not defined)
I tried doing timeit.timeit("func()") (func is a function defined by myself), however, I always get the error name 'func' is not defined. Using Jupyter Notebook (I know about the magic timeit of Jupyter, but I wonder why this doesn't work?).

答:
Most likely you are looking for (without quotes, just directly):

```<code>timeit.timeit(func, number=1000)
</code>```

instead of

```<code>timeit.timeit("func()", number=1000)
</code>```

To have parameters or other functions, use triple quotes, e.g.:

```<code>import timeit
import_module = "import whatever_module"
testcode = '''
def test():
    # some nasty operations here
    pass
'''
print(timeit.repeat(stmt=testcode, setup=import_module))
</code>```

The code must be self-contained, no external references are allowed.

Body:
Most likely you are looking for (without quotes, just directly):

timeit.timeit(func, number=1000)

instead of

timeit.timeit("func()", number=1000)

To have parameters or other functions, use triple quotes, e.g.:

import timeit
import_module = "import whatever_module"
testcode = '''
def test():
    # some nasty operations here
    pass
'''
print(timeit.repeat(stmt=testcode, setup=import_module))

The code must be self-contained, no external references are allowed.


问:
how to print column header every N rows in postgres?
I am aware that \t will print header, but I want it printed every N rows.
How do I set this please?

Thanks in advance

答: AFAIK this is not possible with psql.</p>

Body: AFAIK this is not possible with psql.


问:
how to disable header media in wordpress?
I am facing header media issues. I don't want that header area on my top of the website. I tried CSS code

```<code>.home #wp-custom-header {
    display: none;"
}
</code>```

but it's not working. please check my site for more details hindizone.in

答:
```<code>#site-header {
    display: none;
}
</code>```

<p>...should work for your site.</p>

Body:
I am facing header media issues. I don't want that header area on my top of the website. I tried CSS code

.home #wp-custom-header {
    display: none;"
}

but it's not working. please check my site for more details hindizone.in

Body:
#site-header {
    display: none;
}

...should work for your site.


问:
How to filter for multiple values within a long list of JSON data in JS?
I have a list of multiple items in JSON that looks like this:

```<code>[
  {
    IsValid: true,
    forSale: false,
    Color: red,
    value: 22
  },
  {
    IsValid: false,
    forSale: true,
    Color: blue,
    value: 123
  }
]
</code>```

A user will then select filters to search through the list such as:

```<code>[color: red, forSale: true, value over 10]
</code>```

What is the easiest way to filter through the JSON for multiple values?

I tried having the filtered options as an object like:

```<code>{forSale: true, color: blue}
</code>```

Then doing a forEach of the JSON, with a nested Object.map of the filtered options, but if there are two or more items the Object.mapping doesn't return the right results.

How would you filter through a long list of items in JSON, for multiple options?

答:
```<code>const filters = [{label: 'forSale', value: false}, {label: 'color', value: 'red'}];
const filteredArray = array.filter(item => filters.every(filter => item[filter.label] === filter.value))
</code>```

or

```<code>const filters = {forSale: true, color: 'blue'};
const filteredArray = array.filter(item => {
    let result = true;
    for(let key in filters) {
        if (item[key] !== filters[key]){
            result = false;
            break;
        }
    }
    return result;
})
</code>```

or

```<code>const filters = {forSale: true, color: 'blue'};
const filteredArray = array.filter(item => Object.keys(filters).every(key => item[key] === filters[key]))
</code>```

Body:
I have a list of multiple items in JSON that looks like this:

[
  {
    IsValid: true,
    forSale: false,
    Color: red,
    value: 22
  },
  {
    IsValid: false,
    forSale: true,
    Color: blue,
    value: 123
  }
]

A user will then select filters to search through the list such as:

[color: red, forSale: true, value over 10]

What is the easiest way to filter through the JSON for multiple values?

I tried having the filtered options as an object like:

{forSale: true, color: blue}

Then doing a forEach of the JSON, with a nested Object.map of the filtered options, but if there are two or more items the Object.mapping doesn't return the right results.

How would you filter through a long list of items in JSON, for multiple options?

Body:
const filters = [{label: 'forSale', value: false}, {label: 'color', value: 'red'}];
const filteredArray = array.filter(item => filters.every(filter => item[filter.label] === filter.value))

or

const filters = {forSale: true, color: 'blue'};
const filteredArray = array.filter(item => {
    let result = true;
    for(let key in filters) {
        if (item[key] !== filters[key]){
            result = false;
            break;
        }
    }
    return result;
})

or

const filters = {forSale: true, color: 'blue'};
const filteredArray = array.filter(item => Object.keys(filters).every(key => item[key] === filters[key]))


问:
how to provide multiprocessing.process unique variblables
I have a list containing ID Number's, I want to implement every unique ID Number in an API call for each Multiprocessor whilst running the same corresponding functions, implementing the same conditional statements to each processor etc. I have tried to make sense of it but there is not a lot online about this procedure.

I thought to use a for loop but I don't want every processor running this for loop picking up every item in a list. I just need each item to be associated to each processor.

I was thinking something like this:

```<code>from multiprocessing import process
import requests, json

ID_NUMBERS = ["ID 1", "ID 2", "ID 3".... ETC]
BASE_URL = "www.api.com"
KEY = {"KEY": "12345"}

a = 0

for x in ID_NUMBERS:
    def[a]():
        while Active_live_data == True:
            # continuously loops over, requesting data from the website
            unique_api_call = "{}/livedata[{}]".format(BASE_URL, x)
            request_it = requests.get(unique_api_call, headers=KEY)
            show_it = (json.loads(request_it.content))

            #some extra conditional code...

        a += 1

processes = []
b = 0

for _ in range(len(ID_NUMBERS))
    p = multiprocessing.Process(target = b)
    p.start()
    processes.append(p)
    b += 1

</code>```

Any help would be greatly appreciated!

Kindest regards,

Andrew

答:
Same approach as @AlessiaM but uses the high-level api in the concurrent.futures module.

```<code>import concurrent.futures as mp
import requests, json

BASE_URL = ''
KEY = {"KEY": "12345"}
ID_NUMBERS = ["ID 1", "ID 2", "ID 3"]

def job(id):
    unique_api_call = "{}/livedata[{}]".format(BASE_URL, id)
    request_it = requests.get(unique_api_call, headers=KEY)
    show_it = (json.loads(request_it.content))
    return show_it

# Default to as many workers as there are processors,
# But since your job is IO bound (vs CPU bound),
# you could increase this to an even bigger figure by giving the `max_workers` parameter
with mp.ProcessPoolExecutor() as pool:
    results = pool.map(job,ID_NUMBERS)

# Process results here
</code>```

Body:
I have a list containing ID Number's, I want to implement every unique ID Number in an API call for each Multiprocessor whilst running the same corresponding functions, implementing the same conditional statements to each processor etc. I have tried to make sense of it but there is not a lot online about this procedure.

I thought to use a for loop but I don't want every processor running this for loop picking up every item in a list. I just need each item to be associated to each processor.

I was thinking something like this:

from multiprocessing import process
import requests, json

ID_NUMBERS = ["ID 1", "ID 2", "ID 3".... ETC]
BASE_URL = "www.api.com"
KEY = {"KEY": "12345"}

a = 0

for x in ID_NUMBERS:
    def[a]():
        while Active_live_data == True:
            # continuously loops over, requesting data from the website
            unique_api_call = "{}/livedata[{}]".format(BASE_URL, x)
            request_it = requests.get(unique_api_call, headers=KEY)
            show_it = (json.loads(request_it.content))

            #some extra conditional code...

        a += 1

processes = []
b = 0

for _ in range(len(ID_NUMBERS))
    p = multiprocessing.Process(target = b)
    p.start()
    processes.append(p)
    b += 1

Any help would be greatly appreciated!

Kindest regards,

Andrew

Body:
Same approach as @AlessiaM but uses the high-level api in the concurrent.futures module.

import concurrent.futures as mp
import requests, json

BASE_URL = ''
KEY = {"KEY": "12345"}
ID_NUMBERS = ["ID 1", "ID 2", "ID 3"]

def job(id):
    unique_api_call = "{}/livedata[{}]".format(BASE_URL, id)
    request_it = requests.get(unique_api_call, headers=KEY)
    show_it = (json.loads(request_it.content))
    return show_it

# Default to as many workers as there are processors,
# But since your job is IO bound (vs CPU bound),
# you could increase this to an even bigger figure by giving the `max_workers` parameter
with mp.ProcessPoolExecutor() as pool:
    results = pool.map(job,ID_NUMBERS)

# Process results here


问:
Cluster vector get a zero one matrix in R
Let's say I have a cluster vector generated by any clustering method, like the following on the iris data:

```<code>data(iris)
kmeans_res <- kmeans(x = iris[,c(1:4)], centers = 3)
kmeans_res$cluster
</code>```

Is there an efficient way to create a matrix with zeros and ones based on this vector?

The rows and the columns of this matrix are the observations from the dataset from 1 to n. And the entries should be one, if e.g. observations 5 and 8 belong to the same cluster and zero otherwise.

The problem could be solved with a loop, but this doesn't seem very elegant. Can you think of another solution?

Body:
Let's say I have a cluster vector generated by any clustering method, like the following on the iris data:

data(iris)
kmeans_res <- kmeans(x = iris[,c(1:4)], centers = 3)
kmeans_res$cluster

Is there an efficient way to create a matrix with zeros and ones based on this vector?

The rows and the columns of this matrix are the observations from the dataset from 1 to n. And the entries should be one, if e.g. observations 5 and 8 belong to the same cluster and zero otherwise.

The problem could be solved with a loop, but this doesn't seem very elegant. Can you think of another solution?

Body:
You may use outer.

M <- +(outer(v, v, `==`))
M[50:60, 50:60]
#       [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
#  [1,]    1    0    0    0    0    0    0    0    0     0     0
#  [2,]    0    1    1    0    1    1    1    1    1     1     1
#  [3,]    0    1    1    0    1    1    1    1    1     1     1
#  [4,]    0    0    0    1    0    0    0    0    0     0     0
#  [5,]    0    1    1    0    1    1    1    1    1     1     1
#  [6,]    0    1    1    0    1    1    1    1    1     1     1
#  [7,]    0    1    1    0    1    1    1    1    1     1     1
#  [8,]    0    1    1    0    1    1    1    1    1     1     1
#  [9,]    0    1    1    0    1    1    1    1    1     1     1
# [10,]    0    1    1    0    1    1    1    1    1     1     1
# [11,]    0    1    1    0    1    1    1    1    1     1     1

v[50:60]
# [1] 1 2 2 3 2 2 2 2 2 2 2

Data:

v <- kmeans_res$cluster


问:
MS-Access run time error 2046
I am running MS-Access 2000 (not my choice - the company uses it).

I notice that if I have the startup settings set to open a form when the database is opened I get run time error 2046: The command or action 'Requery' isn't available at this time.

I cannot debug it though because when I click debug the database closes and the only time the error occurs is when I'm closing the database.

Does anyone know what triggers this and what I can do to rid of the error?

答: If you hold the shift key down as you open the database, it will bypass the startup settings and open directly to the database window. You can then look at the form to see what is causing the problem. There is either a macro or a VBA event procedure behind the form that is trying to Requery the form at the wrong time.</p>

Title: MS-Access run time error 2046


问:
How can we change aws instances region from US East (N. Virginia) us-east-1 to Asia Pacific (Mumbai) ap-south-1?
I deployed all my app on an Amazon EC2 instance in US East (N.Virginia). Now I want to move it to Asia Pacific (Mumbai) ap-south-1 region.

I don't want to change my IP (which one I got from US East (N.Virginia)). And I don't want to lose any activity from the EC2 Instance.

Even I tried Move an EC2 Instance to Another Subnet, Availability Zone, or VPC, but did not get anything.

How can we change this?

答:
You'll need to take an image (AMI) of the instance in US-East-1 and copy the image to the target region (ap-south-1) and then launch the AMI in the ap-south-1 region.

From AWS console, do the following:

Go to EC2 console.

Clock 'Running instances'.

Find the instance you want to move.  Click the check box for that instance.

If you want to move the instance, shut it down here, first, by clicking Actions->Instance State-Stop

Actions->Image->Create Image

Give a name, optionally a description.

If you didn't previously shutdown the instance, you have an option of whether to reboot the box when taking AMI.

Click 'Create Image'.

Wait for the image creation to complete, and you can see the new AMI in the the AMI page of the EC2 console.

In the left column of the EC2 console, go to 'AMIs'.

When you see the new AMI in the list, and it's available, click the checkbox to the left of the name.

Actions->Copy AMI

For Desination Region, selECT 'Asia Pacific (Mumbai)'.

Enter name, description, and whether you want the AMI in the destination region to be encrypted.

Click 'Copy AMI'.

Wait for copy to complete.

Switch to ap-south-1 region.

Find the AMI and select it.

click 'Launch Instance'.

Make your choices.

Wait for instance to launch.

Lots of little steps, but it's actually pretty easy.


问:
putting linq to objects query result into a typed dictionary
Still kinda new to LINQ.  Seems like there should be a more elegant way to do this using ToDictionary, but can't figure it out.  Here's my code I want to clean up:</p>

```<code> var EventOccurrencesMappedToPatientMeds = from pm in allPtMeds
      from e in thisUsersEventOccurrencesPlusEventData
      where e.EventContainer.Event.PatientMedId == pm.MedicationId
      select new ScheduleEventOccurrenceMedPair{
           PatientMedication = pm,
           ScheduledEventOccurrence = e.EventOccurrence
      };

 int evtOccCount = 1;
 foreach (var evtOcc in EventOccurrencesMappedToPatientMeds)
 {
      // EventOccurrenceChoices is a Dictionary of type <int, IScheduledEventOccurrenceMedPair>
      message.EventOccurrenceChoices.Add(evtOccCount,(ScheduleEventOccurrenceMedPair)evtOcc);
 }
</code>```

答:
Use ToDictionary extension method.

Something like this:

```<code>var i = 1;
var resultDictionary = (
    from pm in allPtMeds
    from e in thisUsersEventOccurrencesPlusEventData
    where e.EventContainer.Event.PatientMedId == pm.MedicationId
    select new ScheduleEventOccurrenceMedPair
    {
        PatientMedication = pm,
        ScheduledEventOccurrence = e.EventOccurrence
    })
    .ToDictionary(arg => i++, arg => arg);
</code>```

Body:
Still kinda new to LINQ.  Seems like there should be a more elegant way to do this using ToDictionary, but can't figure it out.  Here's my code I want to clean up:

 var EventOccurrencesMappedToPatientMeds = from pm in allPtMeds
      from e in thisUsersEventOccurrencesPlusEventData
      where e.EventContainer.Event.PatientMedId == pm.MedicationId
      select new ScheduleEventOccurrenceMedPair{
           PatientMedication = pm,
           ScheduledEventOccurrence = e.EventOccurrence
      };

 int evtOccCount = 1;
 foreach (var evtOcc in EventOccurrencesMappedToPatientMeds)
 {
      // EventOccurrenceChoices is a Dictionary of type <int, IScheduledEventOccurrenceMedPair>
      message.EventOccurrenceChoices.Add(evtOccCount,(ScheduleEventOccurrenceMedPair)evtOcc);
 }

Body:
Use ToDictionary extension method.

Something like this:

var i = 1;
var resultDictionary = (
    from pm in allPtMeds
    from e in thisUsersEventOccurrencesPlusEventData
    where e.EventContainer.Event.PatientMedId == pm.MedicationId
    select new ScheduleEventOccurrenceMedPair
    {
        PatientMedication = pm,
        ScheduledEventOccurrence = e.EventOccurrence
    })
    .ToDictionary(arg => i++, arg => arg);


问:
How to check if an element is clickable or not using Selenium WebDriver
I have a container, which contains number of elements.I am looping thru the elements.
My question is what is the syntax for checking if the element is NOT clickable. </p>

答:
One option is to do the following.</p>

```<code>from selenium.common.exceptions import WebDriverException
try:
  element.click()
  # add to list of clickable elements
except WebDriverException:
  print "Element is not clickable"
</code>```

Body:
One option is to do the following.

from selenium.common.exceptions import WebDriverException
try:
  element.click()
  # add to list of clickable elements
except WebDriverException:
  print "Element is not clickable"


问:
How do I get sum of two different columns from two diffrent tables and group them
I have two tables which I wanna perform join between two tables and group them by date

Table one is fb_data

```<code>id  name created_at           revenue
1   as   2020-05-29 19:30:54  5
2   as   2020-05-28 19:30:54  10
3   ad   2020-05-29 19:31:42  6
4  ad    2020-05-28 19:31:54 65
5  as    2020-05-29 19:32:10 7
6  ad    2020-05-28 19:31:54 5
</code>```

Table two is google_data

```<code>id name   created_at           sessions
1  as     2020-05-29 19:38:32    5
2  ad     2020-05-29 19:38:41    10
3  as      2020-05-29 19:38:49   7
4  as      2020-05-28 19:39:02   6
5  ad     2020-05-28 19:39:13   8
6  ad    2020-05-28 19:41:41   13
</code>```

Now what I want is to join two columns by name then group them by created_at . Something like this

```<code>Name , date(created_at) as date , sum(fb_data.revenue) , sum(google_data.revenue)
</code>```

I have one sql query but that doesn't gives result as I expected

```<code>select gd.name,fb.total_revenue,fb.created_at,gd.total_sessions
from (select date(fb_data.created_at) as created_at, sum(fb_data.revenue) as total_revenue, name
      from fb_data
      group by date(fb_data.created_at), name) fb,
     (select date(google_data.created_at) as created_at, sum(google_data.session) as total_sessions, name
      from google_data
      group by name, date(google_data.created_at)) as gd
      where fb.name = gd.name
      group by  gd.name,fb.name,fb.created_at,gd.total_sessions
</code>```

The result I get is

```<code>Name total_revenue   created_at     total_sessions
as   12              2020-05-29     12
as   12              2020-05-29     6
as   10              2020-05-28     12
as   10              2020-05-28     6
ad   6               2020-05-29     10
ad   6              2020-05-29      21
ad  70             2020-05-28       10
ad  70             2020-05-28      21
</code>```

The result that I am expecting is

```<code>name  total_revenue   created_at total_sessions
as    12              2020-05-29   12
as    10              2020-05-28   6
ad    6               2020-05-29   10
ad    70              2020-05-28   21
</code>```

答:
This problem is a little harder than it looks at first glance.

You'll need to join three subqueries, each with one row per name and date.

The first subquery gives you all the possible names and dates.  You need this one because one of your two detail file might be missing some name/date combinations the other one contains

```<code>        SELECT DISTINCT name, created_at
          FROM (
             SELECT name, DATE(created_at) created_at FROM fb
              UNION
             SELECT name, DATE(created_at) created_at  FROM gg
            ) a
</code>```

Your second subquery gets session counts for each name / date.

```<code>             SELECT name,
                    DATE(CREATED_AT) created_at,
                    SUM(sessions) sessions
               FROM gg
              GROUP BY name, DATE(created_at)
</code>```

The third one does the same for revenue.

```<code>             SELECT name,
                    DATE(CREATED_AT) created_at,
                    SUM(revenue) revenue
               FROM fb
              GROUP BY name, DATE(created_at)
</code>```

You then LEFT JOIN the second and third subqueries to the first subquery.

```<code>SELECT items.name, items.created_at, sess.sessions, rev.revenue
  FROM (first subquery) items
  LEFT JOIN (second subquery) sess ON items.name = sess.name
                                 AND items.created_at = sess.created_at
  LEFT JOIN (third subquery) rev ON items.name = rev.name
                                AND items.created_at = rev.created_at
</code>```

All together, you get this.

```<code>SELECT items.name, items.created_at, sess.sessions, rev.revenue
  FROM (SELECT DISTINCT name, created_at
          FROM (
             SELECT name, DATE(created_at) created_at FROM fb
              UNION
             SELECT name, DATE(created_at) created_at  FROM gg
            ) a
       ) items
  LEFT JOIN (SELECT name,
                    DATE(CREATED_AT) created_at,
                    SUM(sessions) sessions
               FROM gg
              GROUP BY name, DATE(created_at)
            ) sess ON items.name = sess.name
                  AND items.created_at = sess.created_at
  LEFT JOIN (SELECT name,
                    DATE(CREATED_AT) created_at,
                    SUM(revenue) revenue
               FROM fb
              GROUP BY name, DATE(created_at)
            ) rev ON items.name = rev.name
                  AND items.created_at = rev.created_at
</code>```

https://www.db-fiddle.com/f/hiAKaSDWn1FuUufF3oLbgZ/0

Body:
I have two tables which I wanna perform join between two tables and group them by date

Table one is fb_data

id  name created_at           revenue
1   as   2020-05-29 19:30:54  5
2   as   2020-05-28 19:30:54  10
3   ad   2020-05-29 19:31:42  6
4  ad    2020-05-28 19:31:54 65
5  as    2020-05-29 19:32:10 7
6  ad    2020-05-28 19:31:54 5

Table two is google_data

id name   created_at           sessions
1  as     2020-05-29 19:38:32    5
2  ad     2020-05-29 19:38:41    10
3  as      2020-05-29 19:38:49   7
4  as      2020-05-28 19:39:02   6
5  ad     2020-05-28 19:39:13   8
6  ad    2020-05-28 19:41:41   13

Now what I want is to join two columns by name then group them by created_at . Something like this

Name , date(created_at) as date , sum(fb_data.revenue) , sum(google_data.revenue)

I have one sql query but that doesn't gives result as I expected

select gd.name,fb.total_revenue,fb.created_at,gd.total_sessions
from (select date(fb_data.created_at) as created_at, sum(fb_data.revenue) as total_revenue, name
      from fb_data
      group by date(fb_data.created_at), name) fb,
     (select date(google_data.created_at) as created_at, sum(google_data.session) as total_sessions, name
      from google_data
      group by name, date(google_data.created_at)) as gd
      where fb.name = gd.name
      group by  gd.name,fb.name,fb.created_at,gd.total_sessions

The result I get is

Name total_revenue   created_at     total_sessions
as   12              2020-05-29     12
as   12              2020-05-29     6
as   10              2020-05-28     12
as   10              2020-05-28     6
ad   6               2020-05-29     10
ad   6              2020-05-29      21
ad  70             2020-05-28       10
ad  70             2020-05-28      21

The result that I am expecting is

name  total_revenue   created_at total_sessions
as    12              2020-05-29   12
as    10              2020-05-28   6
ad    6               2020-05-29   10
ad    70              2020-05-28   21

Body:
This problem is a little harder than it looks at first glance.

You'll need to join three subqueries, each with one row per name and date.

The first subquery gives you all the possible names and dates.  You need this one because one of your two detail file might be missing some name/date combinations the other one contains

        SELECT DISTINCT name, created_at
          FROM (
             SELECT name, DATE(created_at) created_at FROM fb
              UNION
             SELECT name, DATE(created_at) created_at  FROM gg
            ) a

Your second subquery gets session counts for each name / date.

             SELECT name,
                    DATE(CREATED_AT) created_at,
                    SUM(sessions) sessions
               FROM gg
              GROUP BY name, DATE(created_at)

The third one does the same for revenue.

             SELECT name,
                    DATE(CREATED_AT) created_at,
                    SUM(revenue) revenue
               FROM fb
              GROUP BY name, DATE(created_at)

You then LEFT JOIN the second and third subqueries to the first subquery.

SELECT items.name, items.created_at, sess.sessions, rev.revenue
  FROM (first subquery) items
  LEFT JOIN (second subquery) sess ON items.name = sess.name
                                 AND items.created_at = sess.created_at
  LEFT JOIN (third subquery) rev ON items.name = rev.name
                                AND items.created_at = rev.created_at

All together, you get this.

SELECT items.name, items.created_at, sess.sessions, rev.revenue
  FROM (SELECT DISTINCT name, created_at
          FROM (
             SELECT name, DATE(created_at) created_at FROM fb
              UNION
             SELECT name, DATE(created_at) created_at  FROM gg
            ) a
       ) items
  LEFT JOIN (SELECT name,
                    DATE(CREATED_AT) created_at,
                    SUM(sessions) sessions
               FROM gg
              GROUP BY name, DATE(created_at)
            ) sess ON items.name = sess.name
                  AND items.created_at = sess.created_at
  LEFT JOIN (SELECT name,
                    DATE(CREATED_AT) created_at,
                    SUM(revenue) revenue
               FROM fb
              GROUP BY name, DATE(created_at)
            ) rev ON items.name = rev.name
                  AND items.created_at = rev.created_at

https://www.db-fiddle.com/f/hiAKaSDWn1FuUufF3oLbgZ/0


问:
.htpasswd asking for authentication on the whole site
The screen shot from ChromeI use Vultr wordpress one click installation service . they have .htaccess file to protect me to login in wp-admin , but today after I changed the theme , it asks for authentication on all the pages of my site . I don't get any error after I click cancel the authentication window , similar problem as this guy https://wordpress.stackexchange.com/questions/103697/htpasswd-asking-for-authentication-on-home-page

I check the .htaccess file on my site , I found it is empty , there is no code there . What should I do to solve the problem .

You could see the popup window by visiting my site : www.hermoart.com

Sincerely looking for help ;(

答:
Vultr's documentation has been updated.

https://www.vultr.com/docs/one-click-wordpress#Vultr_Helper_Scripts

Remove wp-admin Security

One-Click WordPress has an extra security prompt for the /wp-admin/ page. To remove this feature, run the remove-htaccess.sh script.

```<code>$ /opt/vultr/remove-htaccess.sh
</code>```

Body:
Vultr's documentation has been updated.

https://www.vultr.com/docs/one-click-wordpress#Vultr_Helper_Scripts

Remove wp-admin Security

One-Click WordPress has an extra security prompt for the /wp-admin/ page. To remove this feature, run the remove-htaccess.sh script.

$ /opt/vultr/remove-htaccess.sh


问:
Send and consume message by one connection
Is there a way to do this? My case: there are connections "A", "B", and "C", that subscribed to the topic with name "Topic 1". "A" sends a message to the topic and it doesn't receive it. "B" and "C" receive this message. If "C" sends a message to topic then it's "A" and "B" who get the message.</p>

答:
Pass true for the noLocal parameter when you create your consumer.

For example, the javax.jms.MessageConsumer#createConsumer method has an overloaded version that takes a javax.jms.Destination, a String, and a boolean. If you specify true for the boolean (i.e. the noLocal parameter) then messages published using that same connection won't be consumed. The JavaDoc says this about the noLocal parameter:

The noLocal argument is for use when the destination is a topic and the session's connection is also being used to publish messages to that topic. If noLocal is set to true then the MessageConsumer will not receive messages published to the topic by its own connection. The default value of this argument is false. If the destination is a queue then the effect of setting noLocal to true is not specified.


问:
Flask doing calculations returns wrong values
I am trying to calculate 3 things, profit, total cost and the amount.

A user puts in the amount of coins he/she wants to spend. Each product has a buy price and a selling price, and I need to get, well profit, total cost, and amount.

I am doing that with this piece of code right here:

```<code>@app.route('/bflipper', methods=['POST', 'GET'])
def bFlipper():
    product_name = []
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=73ac0a44-4c41-4933-a9ee-b4095be2b6d2').json()
    for x in productNames:
        product_name.append(f["products"][x]["product_id"])
    if request.method == 'POST':
        userInput = request.form['coins'] # UserInput
        userInput = int(userInput)
        sell = [product['sell_summary'][0]['pricePerUnit']
                for product in f['products'].values() if product['sell_summary']]

        buy = [product['buy_summary'][0]['pricePerUnit']
               for product in f['products'].values() if product['buy_summary']]

        amount = []
        for x in range(len(buy)):
            amount.append(userInput * buy[x]) # This here calculates the amount user can buy

        total = []
        for x in range(len(buy)):
            total.append(amount[x] * buy[x])# This here calculates the total cost

        profit = []
        for x in range(len(buy)):
            sell_profit = amount[x] * sell[x]
            buy_profit = amount[x] * sell[x]
            total_profit = sell_profit - buy_profit
            profit.append(total_profit) # This here calculates the profit user will make
        return render_template("flipper.html", userInput=userInput, product_name=product_name, profit=profit, amount=amount, total=total, sell=sell, buy=buy)
    else:
        return render_template("flipper.html", product_name=product_name)
</code>```

The issue is that it returns the wrong values, for example:

User puts in '123321' coins. The program will then do:

```<code>123321 / buy = amount # how many of product x he/she can buy with 123321 coins.
amount * buy = total cost # the total cost
total cost(sell) - total cost(buy) # how much profit it will make
</code>```

Currently, it returns the wrong values. 123321 / 4.6 = 26808 (the amount) # 4.6 is an example of a product buy price

shows in the browser as: 727594. Which is a bit wrong! How do I fix this?

答: as roganjosh said, there is nothing to do with flask. The answer is just to debug the program and you will probably find your math mistake. Maybe open a test file and see if your math is correct there.</p>

Body:
I am trying to calculate 3 things, profit, total cost and the amount.

A user puts in the amount of coins he/she wants to spend. Each product has a buy price and a selling price, and I need to get, well profit, total cost, and amount.

I am doing that with this piece of code right here:

@app.route('/bflipper', methods=['POST', 'GET'])
def bFlipper():
    product_name = []
    f = requests.get(
        'https://api.hypixel.net/skyblock/bazaar?key=73ac0a44-4c41-4933-a9ee-b4095be2b6d2').json()
    for x in productNames:
        product_name.append(f["products"][x]["product_id"])
    if request.method == 'POST':
        userInput = request.form['coins'] # UserInput
        userInput = int(userInput)
        sell = [product['sell_summary'][0]['pricePerUnit']
                for product in f['products'].values() if product['sell_summary']]

        buy = [product['buy_summary'][0]['pricePerUnit']
               for product in f['products'].values() if product['buy_summary']]

        amount = []
        for x in range(len(buy)):
            amount.append(userInput * buy[x]) # This here calculates the amount user can buy

        total = []
        for x in range(len(buy)):
            total.append(amount[x] * buy[x])# This here calculates the total cost

        profit = []
        for x in range(len(buy)):
            sell_profit = amount[x] * sell[x]
            buy_profit = amount[x] * sell[x]
            total_profit = sell_profit - buy_profit
            profit.append(total_profit) # This here calculates the profit user will make
        return render_template("flipper.html", userInput=userInput, product_name=product_name, profit=profit, amount=amount, total=total, sell=sell, buy=buy)
    else:
        return render_template("flipper.html", product_name=product_name)

The issue is that it returns the wrong values, for example:

User puts in '123321' coins. The program will then do:

123321 / buy = amount # how many of product x he/she can buy with 123321 coins.
amount * buy = total cost # the total cost
total cost(sell) - total cost(buy) # how much profit it will make

Currently, it returns the wrong values. 123321 / 4.6 = 26808 (the amount) # 4.6 is an example of a product buy price

shows in the browser as: 727594. Which is a bit wrong! How do I fix this?