问:
How can I save the headers and values in Html

```

<p>My purpose is to extract this output into a table and save it as a csv file. How can i extract this script as i want?</p>

<p>all dates should be on top, all names should be on the far right, all values should be between the two.</p>

```Hisse      2012.12             2013.3             2013.4 ...
ANA      1,114,919,783.60   1,142,792,778.19     1,091,028,645.38  ...
DEN      55,200,000.00      55,920,000.00        45,960,000.00  ....
.
.
.
```

答:
Solution

The custom-function process_scripts() will produce what you are looking for. I am using the dummy data given below (at the end). First we check that the code does what it is expected and so we create a pandas dataframe to see the output.

You could also open this Colab Jupyter Notebook and run it on Cloud for free. This will allow you to not worry about any installation or setup and simply focus on examining the solution itself.

1. Processing A Single Script

## Define CSV file-output folder-path
OUTPUT_PATH = './output'
## Process scripts
dfs = process_scripts(scripts = [s],
                        output_path = OUTPUT_PATH,
                        save_to_csv = False,
                        verbose = 0)

print(dfs[0].reset_index(drop=True))
```

<p><strong>Output</strong>:  </p>

<pre class="lang-sh prettyprint-override"><code>  Name           2012.12  ...            2019.12           2020.03
0  ANA  1,114,919,783.60  ...   3,270,000,000.87  2,347,500,000.63
1  DEN     55,200,000.00  ...     125,100,000.00     85,350,000.00
2  SIS  4,425,000,000.00  ...  11,857,500,000.00  9,315,000,000.00
3  TRK  1,692,579,200.00  ...   4,375,000,000.00  3,587,500,000.00

[4 rows x 31 columns]
</code>```

2. Processing All the Scripts

You can process all your scripts using the custom-define function process_scripts(). The code is given below.

## Define CSV file-output folder-path
OUTPUT_PATH = './output'
## Process scripts
dfs = process_scripts(scripts,
                        output_path = OUTPUT_PATH,
                        save_to_csv = True,
                        verbose = 0)

## To clear the output dir-contents
#!rm -f $OUTPUT_PATH/*
```

<p>I did this on Google Colab and it worked as expected. </p>

<p><img src="https://i.stack.imgur.com/v0mzt.png" alt="enter image description here"></p>

<h2>3. Making Paths in OS-agnostic Manner</h2>

<p>Making paths for windows or unix based systems could be very different. The following shows you a method to achieve that without having to worry about which OS you will run the code. I have used the <code>os</code> library here. However, I would suggest you to look at the <code>Pathlib</code> library as well.</p>

<pre class="lang-py prettyprint-override"><code># Define relative path for output-folder
OUTPUT_PATH = './output'

# Dynamically define absolute path
pwd = os.getcwd() # present-working-directory
OUTPUT_PATH = os.path.join(pwd, os.path.abspath(OUTPUT_PATH))
</code>```

4. Code: custom function process_scripts()

Here we use the regex (regular expression) library, along with pandas for organizing the data in a tabular format and then writing to csv file. The tqdm library is used to give you a nice progressbar while processing multiple scripts. Please see the comments in the code to know what to do if you are running it not from a jupyter notebook. The os library is used for path manipulation and creation of output-directory.

#pip install -U pandas
#pip install tqdm
import pandas as pd
import re # regex
import os
from tqdm.notebook import tqdm
# Use the following line if not using a jupyter notebook
# from tqdm import tqdm

def process_scripts(scripts,
                    output_path='./output',
                    save_to_csv: bool=False,
                    verbose: int=0):
    """Process all scripts and return a list of dataframes and
    optionally write each dataframe to a CSV file.

    Parameters
    ----------
        scripts: list of scripts
        output_path (str): output-folder-path for csv files
        save_to_csv (bool):  default is False
        verbose (int): prints output for verbose>0

    Example
    -------
    OUTPUT_PATH = './output'
    dfs = process_scripts(scripts,
                          output_path = OUTPUT_PATH,
                          save_to_csv = True,
                          verbose = 0)

    ## To clear the output dir-contents
    #!rm -f $OUTPUT_PATH/*
    """
    ## Define regex patterns and compile for speed
    pat_header = re.compile(r"theCols\[\d+\] = new Array\s*\([\'](\d{4}\.\d{1,2})[\'],\d+,\d+\)")
    pat_line = re.compile(r"theRows\[\d+\] = new Array\s*\((.*)\).*")
    pat_code = re.compile("([A-Z]{3})")

    # Calculate zfill-digits
    zfill_digits = len(str(len(scripts)))
    print(f'Total scripts: {len(scripts)}')

    # Create output_path
    if not os.path.exists(output_path):
        os.makedirs(output_path)

    # Define a list of dataframes:
    #   An accumulator of all scripts
    dfs = []

    ## If you do not have tqdm installed, uncomment the
    #  next line and comment out the following line.
    #for script_num, script in enumerate(scripts):
    for script_num, script in enumerate(tqdm(scripts, desc='Scripts Processed')):
        ## Extract: Headers, Rows
        #    Rows : code (Name: single column), line-data (multi-column)
        headers = script.strip().split('\n', 0)[0]
        headers = ['Name'] + re.findall(pat_header, headers)
        lines = re.findall(pat_line, script)
        codes = [re.findall(pat_code, line)[0] for line in lines]
        # Clean data for each row
        lines_data = dict()
        for line, code in zip(lines, codes):
            line_data = line.replace("','", "|").split('|')
            line_data[-1] = line_data[-1].replace("'", "")
            line_data[0] = code
            lines_data.update({code: line_data.copy()})
        if verbose>0:
            print('{}: {}'.format(script_num, codes))
        ## Load data into a pandas-dataframe
        #  and write to csv.
        df = pd.DataFrame(lines_data).T
        df.columns = headers
        dfs.append(df.copy()) # update list
        # Write to CSV
        if save_to_csv:
            num_label = str(script_num).zfill(zfill_digits)
            script_file_csv = f'Script_{num_label}.csv'
            script_path = os.path.join(output_path, script_file_csv)
            df.to_csv(script_path, index=False)
    return dfs
```

<hr>

<h2>5. Dummy Data</h2>

<pre class="lang-py prettyprint-override"><code>## Dummy Data
s = """
<script language="JavaScript"> var theHlp='/yardim/matris.asp';var theTitle = 'Piyasa Değeri';var theCaption='Cam (TL)';var lastmod = '';var h='<font face=symbol size=1 color=#FF0000><b>ß</b></font></center>';var u='<center><font face=symbol size=1 color=#008000><b>İ</b></font></center>';var n='<center><font face=symbol size=1 color=#00A000><b>=</b></font></center>';var fr='<font color=#FF0000>';var fg='<font color=#008000>';var theFooter=new Array();var theCols = new Array();theCols[0] = new Array('Hisse',4,50);theCols[1] = new Array('2012.12',1,60);theCols[2] = new Array('2013.03',1,60);theCols[3] = new Array('2013.06',1,60);theCols[4] = new Array('2013.09',1,60);theCols[5] = new Array('2013.12',1,60);theCols[6] = new Array('2014.03',1,60);theCols[7] = new Array('2014.06',1,60);theCols[8] = new Array('2014.09',1,60);theCols[9] = new Array('2014.12',1,60);theCols[10] = new Array('2015.03',1,60);theCols[11] = new Array('2015.06',1,60);theCols[12] = new Array('2015.09',1,60);theCols[13] = new Array('2015.12',1,60);theCols[14] = new Array('2016.03',1,60);theCols[15] = new Array('2016.06',1,60);theCols[16] = new Array('2016.09',1,60);theCols[17] = new Array('2016.12',1,60);theCols[18] = new Array('2017.03',1,60);theCols[19] = new Array('2017.06',1,60);theCols[20] = new Array('2017.09',1,60);theCols[21] = new Array('2017.12',1,60);theCols[22] = new Array('2018.03',1,60);theCols[23] = new Array('2018.06',1,60);theCols[24] = new Array('2018.09',1,60);theCols[25] = new Array('2018.12',1,60);theCols[26] = new Array('2019.03',1,60);theCols[27] = new Array('2019.06',1,60);theCols[28] = new Array('2019.09',1,60);theCols[29] = new Array('2019.12',1,60);theCols[30] = new Array('2020.03',1,60);var theRows = new Array();
theRows[0] = new Array ('<b>'+h+'30>ANA</B>','1,114,919,783.60','1,142,792,778.19','1,091,028,645.38','991,850,000.48','796,800,000.38','697,200,000.34','751,150,000.36','723,720,000.33','888,000,000.40','790,320,000.36','883,560,000.40','927,960,000.42','737,040,000.33','879,120,000.40','914,640,000.41','927,960,000.42','1,172,160,000.53','1,416,360,000.64','1,589,520,000.72','1,552,500,000.41','1,972,500,000.53','2,520,000,000.67','2,160,000,000.58','2,475,000,000.66','2,010,000,000.54','2,250,000,000.60','2,077,500,000.55','2,332,500,000.62','3,270,000,000.87','2,347,500,000.63');
theRows[1] = new Array ('<b>'+h+'89>DEN</B></a>','55,200,000.00','55,920,000.00','45,960,000.00','42,600,000.00','35,760,000.00','39,600,000.00','40,200,000.00','47,700,000.00','50,460,000.00','45,300,000.00','41,760,000.00','59,340,000.00','66,600,000.00','97,020,000.00','81,060,000.00','69,300,000.00','79,800,000.00','68,400,000.00','66,900,000.00','66,960,000.00','71,220,000.00','71,520,000.00','71,880,000.00','60,600,000.00','69,120,000.00','62,640,000.00','57,180,000.00','89,850,000.00','125,100,000.00','85,350,000.00');
theRows[2] = new Array ('<b>'+h+'269>SIS</B></a>','4,425,000,000.00','4,695,000,000.00','4,050,000,000.00','4,367,380,000.00','4,273,120,000.00','3,644,720,000.00','4,681,580,000.00','4,913,000,000.00','6,188,000,000.00','5,457,000,000.00','6,137,000,000.00','5,453,000,000.00','6,061,000,000.00','6,954,000,000.00','6,745,000,000.00','6,519,000,000.00','7,851,500,000.00','8,548,500,000.00','9,430,000,000.00','9,225,000,000.00','10,575,000,000.00','11,610,000,000.00','9,517,500,000.00','13,140,000,000.00','12,757,500,000.00','13,117,500,000.00','11,677,500,000.00','10,507,500,000.00','11,857,500,000.00','9,315,000,000.00');
theRows[3] = new Array ('<b>'+h+'297>TRK</B></a>','1,692,579,200.00','1,983,924,800.00','1,831,315,200.00','1,704,000,000.00','1,803,400,000.00','1,498,100,000.00','1,803,400,000.00','1,884,450,000.00','2,542,160,000.00','2,180,050,000.00','2,069,200,000.00','1,682,600,000.00','1,619,950,000.00','1,852,650,000.00','2,040,600,000.00','2,315,700,000.00','2,641,200,000.00','2,938,800,000.00','3,599,100,000.00','4,101,900,000.00','5,220,600,000.00','5,808,200,000.00','4,689,500,000.00','5,375,000,000.00','3,787,500,000.00','4,150,000,000.00','3,662,500,000.00','3,712,500,000.00','4,375,000,000.00','3,587,500,000.00');
var thetable=new mytable();thetable.tableWidth=650;thetable.shownum=false;thetable.controlaccess=true;thetable.visCols=new Array(true,true,true,true,true);thetable.initsort=new Array(0,-1);thetable.inittable();thetable.refreshTable();</script>
"""

## Make a dummy list of scripts
scripts = [s for _ in range(10)]
</code>```

Title: How can I save the headers and values in Html <script> as a table in the csv file?

Body:
I'm new to writing code. Using slenium and beautifulsoup, I managed to reach the script I want among dozens of scripts on the web page. I am looking for script [17]. When these codes are executed, the script [17] gives a result as follows.

the last part of my codes

html=driver.page_source
soup=BeautifulSoup(html, "html.parser")
scripts=soup.find_all("script")
x=scripts[17]
print(x)

result, output
note: The list of dates is ahead of the script [17]. slide the bar. Dummy Data

Dummy Data

My purpose is to extract this output into a table and save it as a csv file. How can i extract this script as i want?

all dates should be on top, all names should be on the far right, all values should be between the two.

Hisse      2012.12             2013.3             2013.4 ...
ANA      1,114,919,783.60   1,142,792,778.19     1,091,028,645.38  ...
DEN      55,200,000.00      55,920,000.00        45,960,000.00  ....
.
.
.

Body:
Solution

The custom-function process_scripts() will produce what you are looking for. I am using the dummy data given below (at the end). First we check that the code does what it is expected and so we create a pandas dataframe to see the output.

You could also open this Colab Jupyter Notebook and run it on Cloud for free. This will allow you to not worry about any installation or setup and simply focus on examining the solution itself.

1. Processing A Single Script

## Define CSV file-output folder-path
OUTPUT_PATH = './output'
## Process scripts
dfs = process_scripts(scripts = [s],
                        output_path = OUTPUT_PATH,
                        save_to_csv = False,
                        verbose = 0)

print(dfs[0].reset_index(drop=True))

Output:

  Name           2012.12  ...            2019.12           2020.03
0  ANA  1,114,919,783.60  ...   3,270,000,000.87  2,347,500,000.63
1  DEN     55,200,000.00  ...     125,100,000.00     85,350,000.00
2  SIS  4,425,000,000.00  ...  11,857,500,000.00  9,315,000,000.00
3  TRK  1,692,579,200.00  ...   4,375,000,000.00  3,587,500,000.00

[4 rows x 31 columns]

2. Processing All the Scripts

You can process all your scripts using the custom-define function process_scripts(). The code is given below.

## Define CSV file-output folder-path
OUTPUT_PATH = './output'
## Process scripts
dfs = process_scripts(scripts,
                        output_path = OUTPUT_PATH,
                        save_to_csv = True,
                        verbose = 0)

## To clear the output dir-contents
#!rm -f $OUTPUT_PATH/*

I did this on Google Colab and it worked as expected.

3. Making Paths in OS-agnostic Manner

Making paths for windows or unix based systems could be very different. The following shows you a method to achieve that without having to worry about which OS you will run the code. I have used the os library here. However, I would suggest you to look at the Pathlib library as well.

# Define relative path for output-folder
OUTPUT_PATH = './output'

# Dynamically define absolute path
pwd = os.getcwd() # present-working-directory
OUTPUT_PATH = os.path.join(pwd, os.path.abspath(OUTPUT_PATH))

4. Code: custom function process_scripts()

Here we use the regex (regular expression) library, along with pandas for organizing the data in a tabular format and then writing to csv file. The tqdm library is used to give you a nice progressbar while processing multiple scripts. Please see the comments in the code to know what to do if you are running it not from a jupyter notebook. The os library is used for path manipulation and creation of output-directory.

#pip install -U pandas
#pip install tqdm
import pandas as pd
import re # regex
import os
from tqdm.notebook import tqdm
# Use the following line if not using a jupyter notebook
# from tqdm import tqdm

def process_scripts(scripts,
                    output_path='./output',
                    save_to_csv: bool=False,
                    verbose: int=0):
    """Process all scripts and return a list of dataframes and
    optionally write each dataframe to a CSV file.

    Parameters
    ----------
        scripts: list of scripts
        output_path (str): output-folder-path for csv files
        save_to_csv (bool):  default is False
        verbose (int): prints output for verbose>0

    Example
    -------
    OUTPUT_PATH = './output'
    dfs = process_scripts(scripts,
                          output_path = OUTPUT_PATH,
                          save_to_csv = True,
                          verbose = 0)

    ## To clear the output dir-contents
    #!rm -f $OUTPUT_PATH/*
    """
    ## Define regex patterns and compile for speed
    pat_header = re.compile(r"theCols\[\d+\] = new Array\s*\([\'](\d{4}\.\d{1,2})[\'],\d+,\d+\)")
    pat_line = re.compile(r"theRows\[\d+\] = new Array\s*\((.*)\).*")
    pat_code = re.compile("([A-Z]{3})")

    # Calculate zfill-digits
    zfill_digits = len(str(len(scripts)))
    print(f'Total scripts: {len(scripts)}')

    # Create output_path
    if not os.path.exists(output_path):
        os.makedirs(output_path)

    # Define a list of dataframes:
    #   An accumulator of all scripts
    dfs = []

    ## If you do not have tqdm installed, uncomment the
    #  next line and comment out the following line.
    #for script_num, script in enumerate(scripts):
    for script_num, script in enumerate(tqdm(scripts, desc='Scripts Processed')):
        ## Extract: Headers, Rows
        #    Rows : code (Name: single column), line-data (multi-column)
        headers = script.strip().split('\n', 0)[0]
        headers = ['Name'] + re.findall(pat_header, headers)
        lines = re.findall(pat_line, script)
        codes = [re.findall(pat_code, line)[0] for line in lines]
        # Clean data for each row
        lines_data = dict()
        for line, code in zip(lines, codes):
            line_data = line.replace("','", "|").split('|')
            line_data[-1] = line_data[-1].replace("'", "")
            line_data[0] = code
            lines_data.update({code: line_data.copy()})
        if verbose>0:
            print('{}: {}'.format(script_num, codes))
        ## Load data into a pandas-dataframe
        #  and write to csv.
        df = pd.DataFrame(lines_data).T
        df.columns = headers
        dfs.append(df.copy()) # update list
        # Write to CSV
        if save_to_csv:
            num_label = str(script_num).zfill(zfill_digits)
            script_file_csv = f'Script_{num_label}.csv'
            script_path = os.path.join(output_path, script_file_csv)
            df.to_csv(script_path, index=False)
    return dfs

5. Dummy Data

## Dummy Data
s = """
<script language="JavaScript"> var theHlp='/yardim/matris.asp';var theTitle = 'Piyasa Değeri';var theCaption='Cam (TL)';var lastmod = '';var h='<a class=hisselink href=../Hisse/HisseAnaliz.aspx?HNO=';var e='<a class=hisselink href=../endeks/endeksAnaliz.aspx?HNO=';var d='<center><font face=symbol size=1 color=#FF0000><b>ß</b></font></center>';var u='<center><font face=symbol size=1 color=#008000><b>İ</b></font></center>';var n='<center><font face=symbol size=1 color=#00A000><b>=</b></font></center>';var fr='<font color=#FF0000>';var fg='<font color=#008000>';var theFooter=new Array();var theCols = new Array();theCols[0] = new Array('Hisse',4,50);theCols[1] = new Array('2012.12',1,60);theCols[2] = new Array('2013.03',1,60);theCols[3] = new Array('2013.06',1,60);theCols[4] = new Array('2013.09',1,60);theCols[5] = new Array('2013.12',1,60);theCols[6] = new Array('2014.03',1,60);theCols[7] = new Array('2014.06',1,60);theCols[8] = new Array('2014.09',1,60);theCols[9] = new Array('2014.12',1,60);theCols[10] = new Array('2015.03',1,60);theCols[11] = new Array('2015.06',1,60);theCols[12] = new Array('2015.09',1,60);theCols[13] = new Array('2015.12',1,60);theCols[14] = new Array('2016.03',1,60);theCols[15] = new Array('2016.06',1,60);theCols[16] = new Array('2016.09',1,60);theCols[17] = new Array('2016.12',1,60);theCols[18] = new Array('2017.03',1,60);theCols[19] = new Array('2017.06',1,60);theCols[20] = new Array('2017.09',1,60);theCols[21] = new Array('2017.12',1,60);theCols[22] = new Array('2018.03',1,60);theCols[23] = new Array('2018.06',1,60);theCols[24] = new Array('2018.09',1,60);theCols[25] = new Array('2018.12',1,60);theCols[26] = new Array('2019.03',1,60);theCols[27] = new Array('2019.06',1,60);theCols[28] = new Array('2019.09',1,60);theCols[29] = new Array('2019.12',1,60);theCols[30] = new Array('2020.03',1,60);var theRows = new Array();
theRows[0] = new Array ('<b>'+h+'30>ANA</B></a>','1,114,919,783.60','1,142,792,778.19','1,091,028,645.38','991,850,000.48','796,800,000.38','697,200,000.34','751,150,000.36','723,720,000.33','888,000,000.40','790,320,000.36','883,560,000.40','927,960,000.42','737,040,000.33','879,120,000.40','914,640,000.41','927,960,000.42','1,172,160,000.53','1,416,360,000.64','1,589,520,000.72','1,552,500,000.41','1,972,500,000.53','2,520,000,000.67','2,160,000,000.58','2,475,000,000.66','2,010,000,000.54','2,250,000,000.60','2,077,500,000.55','2,332,500,000.62','3,270,000,000.87','2,347,500,000.63');
theRows[1] = new Array ('<b>'+h+'89>DEN</B></a>','55,200,000.00','55,920,000.00','45,960,000.00','42,600,000.00','35,760,000.00','39,600,000.00','40,200,000.00','47,700,000.00','50,460,000.00','45,300,000.00','41,760,000.00','59,340,000.00','66,600,000.00','97,020,000.00','81,060,000.00','69,300,000.00','79,800,000.00','68,400,000.00','66,900,000.00','66,960,000.00','71,220,000.00','71,520,000.00','71,880,000.00','60,600,000.00','69,120,000.00','62,640,000.00','57,180,000.00','89,850,000.00','125,100,000.00','85,350,000.00');
theRows[2] = new Array ('<b>'+h+'269>SIS</B></a>','4,425,000,000.00','4,695,000,000.00','4,050,000,000.00','4,367,380,000.00','4,273,120,000.00','3,644,720,000.00','4,681,580,000.00','4,913,000,000.00','6,188,000,000.00','5,457,000,000.00','6,137,000,000.00','5,453,000,000.00','6,061,000,000.00','6,954,000,000.00','6,745,000,000.00','6,519,000,000.00','7,851,500,000.00','8,548,500,000.00','9,430,000,000.00','9,225,000,000.00','10,575,000,000.00','11,610,000,000.00','9,517,500,000.00','13,140,000,000.00','12,757,500,000.00','13,117,500,000.00','11,677,500,000.00','10,507,500,000.00','11,857,500,000.00','9,315,000,000.00');
theRows[3] = new Array ('<b>'+h+'297>TRK</B></a>','1,692,579,200.00','1,983,924,800.00','1,831,315,200.00','1,704,000,000.00','1,803,400,000.00','1,498,100,000.00','1,803,400,000.00','1,884,450,000.00','2,542,160,000.00','2,180,050,000.00','2,069,200,000.00','1,682,600,000.00','1,619,950,000.00','1,852,650,000.00','2,040,600,000.00','2,315,700,000.00','2,641,200,000.00','2,938,800,000.00','3,599,100,000.00','4,101,900,000.00','5,220,600,000.00','5,808,200,000.00','4,689,500,000.00','5,375,000,000.00','3,787,500,000.00','4,150,000,000.00','3,662,500,000.00','3,712,500,000.00','4,375,000,000.00','3,587,500,000.00');
var thetable=new mytable();thetable.tableWidth=650;thetable.shownum=false;thetable.controlaccess=true;thetable.visCols=new Array(true,true,true,true,true);thetable.initsort=new Array(0,-1);thetable.inittable();thetable.refreshTable();</script>
"""

## Make a dummy list of scripts
scripts = [s for _ in range(10)]


来源: stackexchange

问:
Can't I call function in function in python?
Below is a part of my code.

```<code>class Financial_Statements:
    def __init__(self,API_KEY,company_code,year,report_sort):
        self.API_KEY = API_KEY
        self.company_code = company_code
        self.year = year
        self.report_sort =report_sort

    def get_request(self):
        request= Request('https://opendart.fss.or.kr/api/fnlttSinglAcnt.json?crtfc_key='+self.API_KEY+'&corp_code='+self.company_code+'&bsns_year='+self.year+'&reprt_code='+self.report_sort)

        response = urlopen(request)
        elevations = response.read()
        data = json.loads(elevations)
        data = json_normalize(data['list']) ##--- json to dataframe
        data = data.loc[:,['fs_nm','sj_nm','account_nm','thstrm_dt','thstrm_amount','frmtrm_nm','frmtrm_amount','bfefrmtrm_nm','bfefrmtrm_amount']]
        return data

    def get_financial_stock_price(self,reo = 0):
        data = get_request(self)
</code>```

I define def get_request to get data and use it in other functions, but when I run the code it returns 'get_request' is not defined.

Can't I use a function inside another function?

答: If you want to call the function inside the class, you have to call it with self. The appropriate code should be self.get_request()

ContentLicense: CC BY-SA 4.0

Body:
Below is a part of my code.

class Financial_Statements:
    def __init__(self,API_KEY,company_code,year,report_sort):
        self.API_KEY = API_KEY
        self.company_code = company_code
        self.year = year
        self.report_sort =report_sort

    def get_request(self):
        request= Request('https://opendart.fss.or.kr/api/fnlttSinglAcnt.json?crtfc_key='+self.API_KEY+'&corp_code='+self.company_code+'&bsns_year='+self.year+'&reprt_code='+self.report_sort)

        response = urlopen(request)
        elevations = response.read()
        data = json.loads(elevations)
        data = json_normalize(data['list']) ##--- json to dataframe
        data = data.loc[:,['fs_nm','sj_nm','account_nm','thstrm_dt','thstrm_amount','frmtrm_nm','frmtrm_amount','bfefrmtrm_nm','bfefrmtrm_amount']]
        return data

    def get_financial_stock_price(self,reo = 0):
        data = get_request(self)

I define def get_request to get data and use it in other functions, but when I run the code it returns 'get_request' is not defined.

Can't I use a function inside another function?


问:
Convert static query from column to row results
I want convert a query that generated column results to row results.

I simplified production query with more 1000 columns and different numbers but same logic.

My example:
convert the following query:

SELECT 1,2,3

actual results:

```<code>-------------------
|  1  |  2  |  3  |
-------------------
|  1  |  2  |  3  |
-------------------
</code>```

expected results:

```<code>-----------
|  title  |
-----------
|    1    |
-----------
|    2    |
-----------
|    3    |
-----------
</code>```

答:
You can use pivot pattern: </p>

```<code>SELECT 1 as `title`
UNION
SELECT 2 as `title`
UNION
SELECT 3 as `title`;
</code>```

Body:
I want convert a query that generated column results to row results.

I simplified production query with more 1000 columns and different numbers but same logic.

My example:
convert the following query:

SELECT 1,2,3

actual results:

-------------------
|  1  |  2  |  3  |
-------------------
|  1  |  2  |  3  |
-------------------

expected results:

-----------
|  title  |
-----------
|    1    |
-----------
|    2    |
-----------
|    3    |
-----------

Body:
You can use pivot pattern:

SELECT 1 as `title`
UNION
SELECT 2 as `title`
UNION
SELECT 3 as `title`;


问:
Redis / Rejson nested document hierarchy performance
I'm storing records as json documents, organized into a hierarchy based on record type. The traditional way to store these in Redis is to have something like:

```<code>customer:walmart   = {...}
customer:target    = {...}
order:po123        = {...}
person:bob         = {...]
person:tom         = {...}
</code>```

However, Rejson (aka RedisJSON) lets us query subdocuments from a path efficiently, as it stores the json as actual hashtables of hashtables. So I could instead organize my records in an actual hierarchy, which would also help accomodate the distinct key limits in Redis at the root.

```<code>["customer"]    = {"walmart": {...}, "target": {...}, "amazon": {...}}
["order"]       = {"po1": {...}, "po2": {...}, "po3": {...}}
["transaction"] = {"uuid1": {...}, "uuid2": {...}, "uuid3": {...}}
["person"]      = {"bob": {...}, "tom": {...}, "dave": {...}}
["widget"]      = {"this": {...}, "that": {...}, "other": {...}}
</code>```

I regularly retrieve one or more records of the same type. For example, I may want to retrieve target (a customer) or both bob and tom (persons). I rarely retrieve all records from a single type.

What is the performance difference between these two different approaches? Does Rejson make retrieving a subdocument based on a json path ('record' above) roughly as efficient as retrieving the document from the root Redis store?

Rejson doesn't appear to have a way to retrieve bob and tom above in a single command/fetch. mget fetches a common path across multiple root Redis keys. That's the opposite of what I want, and is a sign I'm abusing Redis.

Even with Rejson, should deliberate data hierarchies used in this way be considered bad practice due to performance penalties?

答:
What is the performance difference between these two different approaches? Does Rejson make retrieving a subdocument based on a json path ('record' above) roughly as efficient as retrieving the document from the root Redis store?

RedisJSON is retrieving subdocument parts based on JsonPath so obviously the more complex he JsonPath is the more overhead it will add. But simple paths like you mentioned above shouldn't impose big overhead.

Rejson doesn't appear to have a way to retrieve bob and tom above in a single command/fetch.

RedisJSON json.get supports multi paths so you can call JSON.GET customer .bob .tom.
Also the upcoming RedisJSON 2.0 includes full support for JsonPath, so you should be able to run  JSON.GET customer .["bob"|"tom"]

Even with Rejson, should deliberate data hierarchies used in this way be considered bad practice due to performance penalties?

The thing you should consider here is, do you need all "parts" sit at the same shard in case you're using Redis Cluster, would you need to atomically/transaction update those part?

Body:
I'm storing records as json documents, organized into a hierarchy based on record type. The traditional way to store these in Redis is to have something like:

customer:walmart   = {...}
customer:target    = {...}
order:po123        = {...}
person:bob         = {...]
person:tom         = {...}

However, Rejson (aka RedisJSON) lets us query subdocuments from a path efficiently, as it stores the json as actual hashtables of hashtables. So I could instead organize my records in an actual hierarchy, which would also help accomodate the distinct key limits in Redis at the root.

["customer"]    = {"walmart": {...}, "target": {...}, "amazon": {...}}
["order"]       = {"po1": {...}, "po2": {...}, "po3": {...}}
["transaction"] = {"uuid1": {...}, "uuid2": {...}, "uuid3": {...}}
["person"]      = {"bob": {...}, "tom": {...}, "dave": {...}}
["widget"]      = {"this": {...}, "that": {...}, "other": {...}}

I regularly retrieve one or more records of the same type. For example, I may want to retrieve target (a customer) or both bob and tom (persons). I rarely retrieve all records from a single type.

What is the performance difference between these two different approaches? Does Rejson make retrieving a subdocument based on a json path ('record' above) roughly as efficient as retrieving the document from the root Redis store?

Rejson doesn't appear to have a way to retrieve bob and tom above in a single command/fetch. mget fetches a common path across multiple root Redis keys. That's the opposite of what I want, and is a sign I'm abusing Redis.

Even with Rejson, should deliberate data hierarchies used in this way be considered bad practice due to performance penalties?


问:
vue js reusing component twice in same page
i  have a components  with axios call. i declare two of then with a props that give the uri to axios call

```<code>export default {
name: "CardData",

props :['uri','suffixe' ,'label'],

data : function (){
    return  {

        lab : this.label,
        suff: this.suffixe,
        data :0,
    }
},

methods :{
    init(){

        self = this;
        this.$http.get(this.$ApiUri+this.uri)

            .then(function (response) {
                self.loading = true;
                // handle success
                if (response.data){
                    if (response.data.nb){
                      console.log('we have nb :' + response.data.nb );
                      self.data = response.data.nb;
                    }

                    self.loading = false;
                }
            })
            .catch(function (error) {console.log(error);});
    },
},

mounted(){

     this.init();
},
</code>```

i have a container that call this components twice

```<code> <CardData uri="getNbNews" suffixe=" "  label="News" :key="100" ></CardData>
 <CardData uri="getNbSources" suffixe=" "  label="Sources" :key="101"></CardData>
</code>```

i can see the result on console.log  to response.data.nb
but only one is updated on front ... other contain 0
i can't figure it out

答:
Being the same component you need to distinguish them using a key property.</p>

```<code> <CardData key="news" uri="getNbNews" suffixe=" "  label="News" ></CardData>
 <CardData key="sources" uri="getNbSources" suffixe=" "  label="Sources"></CardData>
</code>```

Body:
i  have a components  with axios call. i declare two of then with a props that give the uri to axios call

export default {
name: "CardData",

props :['uri','suffixe' ,'label'],

data : function (){
    return  {

        lab : this.label,
        suff: this.suffixe,
        data :0,
    }
},

methods :{
    init(){

        self = this;
        this.$http.get(this.$ApiUri+this.uri)

            .then(function (response) {
                self.loading = true;
                // handle success
                if (response.data){
                    if (response.data.nb){
                      console.log('we have nb :' + response.data.nb );
                      self.data = response.data.nb;
                    }

                    self.loading = false;
                }
            })
            .catch(function (error) {console.log(error);});
    },
},

mounted(){

     this.init();
},

i have a container that call this components twice

 <CardData uri="getNbNews" suffixe=" "  label="News" :key="100" ></CardData>
 <CardData uri="getNbSources" suffixe=" "  label="Sources" :key="101"></CardData>

i can see the result on console.log  to response.data.nb
but only one is updated on front ... other contain 0
i can't figure it out

Body:
Being the same component you need to distinguish them using a key property.

 <CardData key="news" uri="getNbNews" suffixe=" "  label="News" ></CardData>
 <CardData key="sources" uri="getNbSources" suffixe=" "  label="Sources"></CardData>


问:
Using rsync to delete a single file
File foo.txt exists on the remote machine at: /home/user/foo.txt

It doesn't exist on the local machine.

I want to delete foo.txt using rsync.

I do not know (and assume for the purposes of this question that I cannot find out) what other files are in /home/user on either the local or remote machines, so I can't just sync the whole directory.

What rsync command can I use to delete foo.txt on the remote machine?

答:
Just came across the same problem, needed to use rsync to delete a remote file, as only rsync and no other SSH commands were allowed. The --remove-source-files option (formerly known as --remove-sender-files) did exactly that:

```<code>rsync -avPn --remove-source-files remote:/home/user/foo.txt .
rm foo.txt
</code>```

As always, remove the -n option to really execute this.

OwnerDisplayName: dirtside

ContentLicense: CC BY-SA 2.5

Title: Using rsync to delete a single file

Body:
Just came across the same problem, needed to use rsync to delete a remote file, as only rsync and no other SSH commands were allowed. The --remove-source-files option (formerly known as --remove-sender-files) did exactly that:

rsync -avPn --remove-source-files remote:/home/user/foo.txt .
rm foo.txt

As always, remove the -n option to really execute this.


问:
ERRORS in NetBeans " Class.forName("com.mysql.jdbc.Driver");"
i am using netbeans 8.2 and mysql 8.0 and inport mysql connector 8.0.11 to the library file as well for my following java codes,

```<code>package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class JDBC {

    public static void main(String[] args) {
        String SQL="Insert into Customer Values('C111','Somadasa','Matugama',34000)";
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3308/ThogaKade", "root", "ftwxy");
        Statement stm=connection.createStatement();
        stm.executeUpdate(SQL);
    }

}
</code>```

but following lines have been highlighted
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3308/ThogaKade", "root", "mysql");

with the message 'unreported exception ClassNotFoundException; must be caught or declared to be thrown
----'
how could fix this problem?

答:
You can specify that main throws the Exception(s). Like,

```<code>public static void main(String[] args) throws SQLException, ClassNotFoundException {
    String SQL = "Insert into Customer Values('C111','Somadasa','Matugama',34000)";
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager
            .getConnection("jdbc:mysql://localhost:3308/ThogaKade", "root", "ftwxy");
    Statement stm = connection.createStatement();
    stm.executeUpdate(SQL);
}
</code>```

Or, you can use a try-catch (preferably with a try-with-Resources) like,

```<code>public static void main(String[] args) {
    String SQL = "Insert into Customer Values('C111','Somadasa','Matugama',34000)";
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }
    try (Connection connection = DriverManager
            .getConnection("jdbc:mysql://localhost:3308/ThogaKade", "root",
            "ftwxy"); Statement stm = connection.createStatement()) {
        stm.executeUpdate(SQL);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}
</code>```

The advantage of a try-with-Resources is it will close() your Connection and Statement(s) correctly. Finally, you haven't actually needed to explicitly load a JDBC driver with Class.forName(String) since Java 6.

Body:
i am using netbeans 8.2 and mysql 8.0 and inport mysql connector 8.0.11 to the library file as well for my following java codes,

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class JDBC {

    public static void main(String[] args) {
        String SQL="Insert into Customer Values('C111','Somadasa','Matugama',34000)";
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3308/ThogaKade", "root", "ftwxy");
        Statement stm=connection.createStatement();
        stm.executeUpdate(SQL);
    }

}

but following lines have been highlighted
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3308/ThogaKade", "root", "mysql");

with the message 'unreported exception ClassNotFoundException; must be caught or declared to be thrown
----'
how could fix this problem?

Body:
You can specify that main throws the Exception(s). Like,

public static void main(String[] args) throws SQLException, ClassNotFoundException {
    String SQL = "Insert into Customer Values('C111','Somadasa','Matugama',34000)";
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager
            .getConnection("jdbc:mysql://localhost:3308/ThogaKade", "root", "ftwxy");
    Statement stm = connection.createStatement();
    stm.executeUpdate(SQL);
}

Or, you can use a try-catch (preferably with a try-with-Resources) like,

public static void main(String[] args) {
    String SQL = "Insert into Customer Values('C111','Somadasa','Matugama',34000)";
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e1) {
        e1.printStackTrace();
    }
    try (Connection connection = DriverManager
            .getConnection("jdbc:mysql://localhost:3308/ThogaKade", "root",
            "ftwxy"); Statement stm = connection.createStatement()) {
        stm.executeUpdate(SQL);
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

The advantage of a try-with-Resources is it will close() your Connection and Statement(s) correctly. Finally, you haven't actually needed to explicitly load a JDBC driver with Class.forName(String) since Java 6.


问:
Type Error : destroy is not a function in Reactjs while call api async function in useEffect hook
```<code>
const [dailyData, setDailyData] = useState([]);
 useEffect(async () => {
    const fetchData =  await fetchDailyData();  // fetchDailyData() is calling Api
    setDailyData(fetchData);

    console.log(fetchData); //fetchData print the value but dailyData not updating

  },[]);
</code>```

showing destroy is not a function and func.apply is not a function

答:
Effect hook callbacks can't be async. Instead, declare a callback function scoped async function and then invoke it. Also, as pointed out by @StéphaneVeyret your "async" effect hook callback implicitly returns a Promise which gets interpreted as an effect hook clean up function. It isn't one though and causes error.

```<code>useEffect(() => {
  const asyncFetchDailyData = async () => {
    const fetchData = await fetchDailyData(); // fetchDailyData() is calling Api
    setDailyData(fetchData);
    console.log(fetchData);
  }

  asyncFetchDailyData();
}, []);
</code>```

Body:
const [dailyData, setDailyData] = useState([]);
 useEffect(async () => {
    const fetchData =  await fetchDailyData();  // fetchDailyData() is calling Api
    setDailyData(fetchData);

    console.log(fetchData); //fetchData print the value but dailyData not updating

  },[]);

showing destroy is not a function and func.apply is not a function

Body:
Effect hook callbacks can't be async. Instead, declare a callback function scoped async function and then invoke it. Also, as pointed out by @StéphaneVeyret your "async" effect hook callback implicitly returns a Promise which gets interpreted as an effect hook clean up function. It isn't one though and causes error.

useEffect(() => {
  const asyncFetchDailyData = async () => {
    const fetchData = await fetchDailyData(); // fetchDailyData() is calling Api
    setDailyData(fetchData);
    console.log(fetchData);
  }

  asyncFetchDailyData();
}, []);


答:
this is because Class.forName and DriverManager.getConnection throws Exception that needs to be handled.

The simplest approach to fix this error is to make your main method throw Exception.

Something like this:

```<code>public static void main(String[] args) throws Exception {
    // your code here
}
</code>```

Another approach would be to enclose your code inside a try-catch block.

Something like this:

```<code>public static void main(String[] args) {
    String SQL="Insert into Customer Values('C111','Somadasa','Matugama',34000)";
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3308/ThogaKade", "root", "ftwxy");
        Statement stm=connection.createStatement();
        stm.executeUpdate(SQL);
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }
}
</code>```

Hope this helps

Title: ERRORS in NetBeans " Class.forName("com.mysql.jdbc.Driver");"

Body:
this is because Class.forName and DriverManager.getConnection throws Exception that needs to be handled.

The simplest approach to fix this error is to make your main method throw Exception.

Something like this:

public static void main(String[] args) throws Exception {
    // your code here
}

Another approach would be to enclose your code inside a try-catch block.

Something like this:

public static void main(String[] args) {
    String SQL="Insert into Customer Values('C111','Somadasa','Matugama',34000)";
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3308/ThogaKade", "root", "ftwxy");
        Statement stm=connection.createStatement();
        stm.executeUpdate(SQL);
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }
}

Hope this helps


问:
integer constant long long int?
```<code>long long int
</code>```

It seems to be valid in C. but is this valid in c++?

答:
It's not portable in C++. What is normally done in programs is to have a single .h file that defines all the numeric types you are going to need depending on compiler/hw. For example you may find code like

```<code>#if defined(__THISCOMPILER__)
typedef long long int64;
typedef unsigned long long uint64;
typedef short int16;
typedef unsigned short uint16;
...
#elseif defined(__THATCOMPILER__)
typedef __int64 int64;
...
#endif
</code>```

then in the rest of the code only types like int64 are used instead of the specific compiler-dependent declarations to keep most of the source portable.

C99 defined standard names for types of a specific size (or of a minimum guaranteed size) but not every compiler out there is fully C99 compliant so this kind of typedef include is still quite common. Note also that currrent standard C++ doesn't include C99.

ContentLicense: CC BY-SA 3.0

Title: integer constant long long int?

Body:
long long int

It seems to be valid in C. but is this valid in c++?

Body:
It's not portable in C++. What is normally done in programs is to have a single .h file that defines all the numeric types you are going to need depending on compiler/hw. For example you may find code like

#if defined(__THISCOMPILER__)
typedef long long int64;
typedef unsigned long long uint64;
typedef short int16;
typedef unsigned short uint16;
...
#elseif defined(__THATCOMPILER__)
typedef __int64 int64;
...
#endif

then in the rest of the code only types like int64 are used instead of the specific compiler-dependent declarations to keep most of the source portable.

C99 defined standard names for types of a specific size (or of a minimum guaranteed size) but not every compiler out there is fully C99 compliant so this kind of typedef include is still quite common. Note also that currrent standard C++ doesn't include C99.


问:
Dialogflow response with parameters
I'm trying to set up Dialogflow interaction with my Go service. Is there any way to use 'formatting' in response?
The perfect solution for me is if I could get some data from my service, let's say the manager's name, and then substitute it as if it was an input parameter.
And use it like this
I know there is a way to process it and compile the answer on my own at webhook but it's not possible with multiple responses where I can substitute the calculated answer.
Is there any way to do it?
Thanks</p>

答:
This is unfortunately not possible. Dialogflow should really only be used for detecting intents, parameters etc. Whenever something needs to be calculated or formatted you will need to use your webhook to do that. You can use multiple responses in your webhook, it will just not show up in the Dialogflow console which only shows 1 reply.

I would suggest you to link your bot to the messaging channel where you will deploy it to. Personally I link it to Telegram or Crisp.chat (an omnichannel platform).

Title: Dialogflow response with parameters


问:
Inheritance guideline for a child class
Since in C#, we can only inherit from a single base class and implement multiple interfaces.

I see this normal pattern everywhere:-

DerivedClass : BaseClass, IInterface1, IInterface2

How should one decide what goes inside BaseClass and what things inside the interfaces?

Are there any guidelines for it?

答:
I use to follow these rules:

Base classes contain common methods or properties that will be used by its children, this is mainly to avoid having duplicated code in each child class.

Interfaces contain the methods or properties that need to be used outside the context of those classes. And depending on the case they will be implemented by the base class or by the child classes.

So it can happen that you want to have a method or property in the base class AND in the interface, and sometimes you will want it to be only in the base class because it's only a utility for its children.

But like everything in design, there're no 100% correct answers, it really depends on the context and the meaning of each object.

Title: Inheritance guideline for a child class


问:
Linq with inner join and grouping
Sorry, this is the kind of question that will annoy the experts, but I've been searching for similar cases and I'm sure they exist, but I'm simply not good enough to recognize what applies to my scenario.

I have two tables, where there's a 1-n relation between MeasuresSet and Measure :

```<code>MeasuresSet {
   Id : Guid
   Date : DateTime
}

Measure {
   Id : Guid
   MeasuresSetId : Guid
   MeasureCategory : string
   Value : double
   VehicleName: string
}
</code>```

MeasuresSet is a group of measures that were performed on the same day, hence the date.

Each row in table Measure represents a specific measure that was performed on the vehicle. For example it could be have MeasureCategory "tyre pressure" and have a corresponding value in psi.

In other words : Each vehicle has many measures, of same or different categories, performed on the same day or on different days.

I want to be able to write a query that means "Give me all the measures that were performed for Vehicle 'Mike's car', but group on MeasureCategory so that I get only the most recent value of each MeasureCategory."
The issue is that the date is stored in MeasuresSet, not Measure. Unfortunately I get lost in the join and the grouping.

I would have imagined that this would be the correct query, but the syntax is incorrect :

```<code>from MeasuresSet
join Measure
on MeasuresSet.Id equals Measure.MeasuresSetId  //your typical inner join
where VehicleName == "Mike's car"
group Measure by Measure.MeasureCategory into g
select new ResultType {
   MeasureCategory : g.Key,
   Date: g.OrderByDescending(data => data.Date).First().Date,
   Value: g.OrderByDescending(data => data.Date).First().Value,
};
</code>```

答:
```<code>public class MeasuresSet
{
    public string Id { get; set; } //: Guid
    public DateTime Day { get; set; } //: DateTime
}

public class Measure
{
    public string Id { get; set; }//: Guid
    public string MeasuresSetId { get; set; }//: Guid
    public string MeasureCategory { get; set; } //: string
    public double Value { get; set; } //: double
    public string VehicleName { get; set; }//: string
}

var measureSets = new List<MeasuresSet>() {
new MeasuresSet() { Daisy = DateTime.Today, Id = "GUID-0" },
new MeasuresSet() { Daisy = DateTime.Today.AddDays(1), Id = "GUID-1" },
new MeasuresSet() { Daisy = DateTime.Today.AddDays(2), Id = "GUID-2" },
new MeasuresSet() { Daisy = DateTime.Today.AddDays(3), Id = "GUID-3" },
new MeasuresSet() { Daisy = DateTime.Today.AddDays(4), Id = "GUID-4" }};

var measures = new List<Measure>() {
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-0", Value = 10 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-0", Value = 11 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-0", Value = 12 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-1", Value = 20 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-1", Value = 21 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-1", Value = 22 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-2", Value = 30 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-2", Value = 31 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-2", Value = 32 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-3", Value = 40 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-3", Value = 41 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-3", Value = 42 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-4", Value = 50 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-4", Value = 51 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-4", Value = 52 },

new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-0", Value = 110 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-0", Value = 111 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-0", Value = 112 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-1", Value = 220 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-1", Value = 221 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-1", Value = 222 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-2", Value = 330 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-2", Value = 331 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-2", Value = 332 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-3", Value = 440 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-3", Value = 441 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-3", Value = 442 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-4", Value = 550 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-4", Value = 551 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-4", Value = 552 }};

  var result = from set in (from measureSet in measureSets
                                  join measure in measures
                                       on measureSet.Id equals measure.MeasuresSetId
                                  select new
                                  {
                                      Day = measureSet.Day,
                                      ParentId = measureSet.Id,
                                      MeasureCategory = measure.MeasureCategory,
                                      Id = measure.Id,
                                      Value = measure.Value,
                                      VehicleName = measure.VehicleName
                                  })
                     where set.VehicleName == "Mike's car"
                     group set by set.MeasureCategory into g
                     select new
                     {
                         MeasureCategory = g.Key,
                         Day = g.Max(x => x.Day),
                         Value = g.First(x => x.Day == g.Max(y => y.Day)).Value
                     };
</code>```

RESULTS :

```<code>Mike's car
tyre pressure | 04/06/2020 00:00:00 | 50
engine | 04/06/2020 00:00:00 | 51
air conditioner | 04/06/2020 00:00:00 | 52

NOT Mike's car
tyre pressure | 02/06/2020 00:00:00 | 330
engine | 03/06/2020 00:00:00 | 441
air conditioner | 04/06/2020 00:00:00 | 552
</code>```

Title: Linq with inner join and grouping

Body:
Sorry, this is the kind of question that will annoy the experts, but I've been searching for similar cases and I'm sure they exist, but I'm simply not good enough to recognize what applies to my scenario.

I have two tables, where there's a 1-n relation between MeasuresSet and Measure :

MeasuresSet {
   Id : Guid
   Date : DateTime
}

Measure {
   Id : Guid
   MeasuresSetId : Guid
   MeasureCategory : string
   Value : double
   VehicleName: string
}

MeasuresSet is a group of measures that were performed on the same day, hence the date.

Each row in table Measure represents a specific measure that was performed on the vehicle. For example it could be have MeasureCategory "tyre pressure" and have a corresponding value in psi.

In other words : Each vehicle has many measures, of same or different categories, performed on the same day or on different days.

I want to be able to write a query that means "Give me all the measures that were performed for Vehicle 'Mike's car', but group on MeasureCategory so that I get only the most recent value of each MeasureCategory."
The issue is that the date is stored in MeasuresSet, not Measure. Unfortunately I get lost in the join and the grouping.

I would have imagined that this would be the correct query, but the syntax is incorrect :

from MeasuresSet
join Measure
on MeasuresSet.Id equals Measure.MeasuresSetId  //your typical inner join
where VehicleName == "Mike's car"
group Measure by Measure.MeasureCategory into g
select new ResultType {
   MeasureCategory : g.Key,
   Date: g.OrderByDescending(data => data.Date).First().Date,
   Value: g.OrderByDescending(data => data.Date).First().Value,
};

Body:
public class MeasuresSet
{
    public string Id { get; set; } //: Guid
    public DateTime Day { get; set; } //: DateTime
}

public class Measure
{
    public string Id { get; set; }//: Guid
    public string MeasuresSetId { get; set; }//: Guid
    public string MeasureCategory { get; set; } //: string
    public double Value { get; set; } //: double
    public string VehicleName { get; set; }//: string
}

var measureSets = new List<MeasuresSet>() {
new MeasuresSet() { Daisy = DateTime.Today, Id = "GUID-0" },
new MeasuresSet() { Daisy = DateTime.Today.AddDays(1), Id = "GUID-1" },
new MeasuresSet() { Daisy = DateTime.Today.AddDays(2), Id = "GUID-2" },
new MeasuresSet() { Daisy = DateTime.Today.AddDays(3), Id = "GUID-3" },
new MeasuresSet() { Daisy = DateTime.Today.AddDays(4), Id = "GUID-4" }};

var measures = new List<Measure>() {
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-0", Value = 10 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-0", Value = 11 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-0", Value = 12 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-1", Value = 20 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-1", Value = 21 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-1", Value = 22 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-2", Value = 30 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-2", Value = 31 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-2", Value = 32 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-3", Value = 40 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-3", Value = 41 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-3", Value = 42 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-4", Value = 50 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-4", Value = 51 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-4", Value = 52 },

new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-0", Value = 110 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-0", Value = 111 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-0", Value = 112 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-1", Value = 220 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-1", Value = 221 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-1", Value = 222 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-2", Value = 330 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-2", Value = 331 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-2", Value = 332 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-3", Value = 440 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-3", Value = 441 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-3", Value = 442 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "tyre pressure", MeasuresSetId = "GUID-4", Value = 550 },
//new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "engine", MeasuresSetId = "GUID-4", Value = 551 },
new Measure() { Id = Guid.NewGuid().ToString(), VehicleName = "NOT Mike's car", MeasureCategory = "air conditioner", MeasuresSetId = "GUID-4", Value = 552 }};

  var result = from set in (from measureSet in measureSets
                                  join measure in measures
                                       on measureSet.Id equals measure.MeasuresSetId
                                  select new
                                  {
                                      Day = measureSet.Day,
                                      ParentId = measureSet.Id,
                                      MeasureCategory = measure.MeasureCategory,
                                      Id = measure.Id,
                                      Value = measure.Value,
                                      VehicleName = measure.VehicleName
                                  })
                     where set.VehicleName == "Mike's car"
                     group set by set.MeasureCategory into g
                     select new
                     {
                         MeasureCategory = g.Key,
                         Day = g.Max(x => x.Day),
                         Value = g.First(x => x.Day == g.Max(y => y.Day)).Value
                     };

RESULTS :

Mike's car
tyre pressure | 04/06/2020 00:00:00 | 50
engine | 04/06/2020 00:00:00 | 51
air conditioner | 04/06/2020 00:00:00 | 52

NOT Mike's car
tyre pressure | 02/06/2020 00:00:00 | 330
engine | 03/06/2020 00:00:00 | 441
air conditioner | 04/06/2020 00:00:00 | 552


问:
Qsort() comparing the sum of struct ints
I have a program meant to take in a number n structs of students composed of their name and 3 tests scores, and must use qsort() to output them in descending order based on their total score. While I have been able to sort them, they are only being sorted by their first value.

Is there a way to sum each students values then use qsort? I have tried editing the values of number of elements as well as the pointers of the comparison function but nothing is working

```<code>#include <cstdlib>
#include <iostream>

using namespace std;

typedef struct {
    char name[16];
    int chineseScore;
    int mathScore;
    int englishScore;
    int totalScore;
} student;

int compare(const void* p1, const void* p2) {
    student *a = (student *)p1;
    student *b = (student *)p2;
    return (a - b);
}

int main() {
    //gets input
    int n;
    do{
        cin >> n;
    }while (n < 1 || n > 10);
    student stud[n];
    for (int i = 0; i < n; i++){
        cin >> stud[i].name >> stud[i].chineseScore >> stud[i].mathScore >> stud[i].englishScore;
        stud[i].totalScore = stud[i].chineseScore + stud[i].mathScore + stud[i].englishScore;
    }
    //sorts array with qsort()
    qsort(stud, n, sizeof(student), compare);
    //prints result
    for (int i = 0; i < n; i++){
        cout << stud[i].name << ' '<< stud[i].chineseScore <<' '<< stud[i].mathScore <<' '<< stud[i].englishScore<< endl;
     }

    return 0;
}
</code>```

答:
```<code>int n;
...
student stud[n];
</code>```

Is invalid in C++. It is using a compiler extension that enables the use of a C feature variable length arrays in C++. VLAs are not part of C++. Use std::vector<student> in C++.

You function:

```<code>int compare(const void* p1, const void* p2) {
    student *a = (student *)p1;
    student *b = (student *)p2;
    return (a - b);
}
</code>```

is invalid - a - b is substracting pointers to students and then returning that value - that value has nothing to do with the values students actually have. Dereference the pointers and compare the values inside. Also, do not remove const-ness.

```<code>int compare(const void* p1, const void* p2) {
    const student *a = (const student*)p1;
    const student *b = (const student*)p2;
    return a->chineseScore - b->chineseScore;
}
</code>```

Is there a way to sum each students values then use qsort?

Declare a variable that will hold the sum and initialize it to zero. Then iterate over the array of students and add the value of something in the student to the sum variable you declared earlier.

Body:
I have a program meant to take in a number n structs of students composed of their name and 3 tests scores, and must use qsort() to output them in descending order based on their total score. While I have been able to sort them, they are only being sorted by their first value.

Is there a way to sum each students values then use qsort? I have tried editing the values of number of elements as well as the pointers of the comparison function but nothing is working

#include <cstdlib>
#include <iostream>

using namespace std;

typedef struct {
    char name[16];
    int chineseScore;
    int mathScore;
    int englishScore;
    int totalScore;
} student;

int compare(const void* p1, const void* p2) {
    student *a = (student *)p1;
    student *b = (student *)p2;
    return (a - b);
}

int main() {
    //gets input
    int n;
    do{
        cin >> n;
    }while (n < 1 || n > 10);
    student stud[n];
    for (int i = 0; i < n; i++){
        cin >> stud[i].name >> stud[i].chineseScore >> stud[i].mathScore >> stud[i].englishScore;
        stud[i].totalScore = stud[i].chineseScore + stud[i].mathScore + stud[i].englishScore;
    }
    //sorts array with qsort()
    qsort(stud, n, sizeof(student), compare);
    //prints result
    for (int i = 0; i < n; i++){
        cout << stud[i].name << ' '<< stud[i].chineseScore <<' '<< stud[i].mathScore <<' '<< stud[i].englishScore<< endl;
     }

    return 0;
}

Body:
int n;
...
student stud[n];

Is invalid in C++. It is using a compiler extension that enables the use of a C feature variable length arrays in C++. VLAs are not part of C++. Use std::vector<student> in C++.

You function:

int compare(const void* p1, const void* p2) {
    student *a = (student *)p1;
    student *b = (student *)p2;
    return (a - b);
}

is invalid - a - b is substracting pointers to students and then returning that value - that value has nothing to do with the values students actually have. Dereference the pointers and compare the values inside. Also, do not remove const-ness.

int compare(const void* p1, const void* p2) {
    const student *a = (const student*)p1;
    const student *b = (const student*)p2;
    return a->chineseScore - b->chineseScore;
}

Is there a way to sum each students values then use qsort?

Declare a variable that will hold the sum and initialize it to zero. Then iterate over the array of students and add the value of something in the student to the sum variable you declared earlier.


问:
What is a .dbml.layout file for?
What is a .dbml.layout file for? Is it important? Or, maybe, it just stores the placing of blocks in the designer and can be deleted?

I've got this question because I want to edit the .dbml file manually and need to know if I must edit .dbml.layout accordingly or can just delete it to get it recreated automatically. Luckily it seems for me that it is indeed autogenerated.

答: The layout file is just to show you how your model classes are laid out in the designer. I don't believe it has any information about the actual schema etc. If your experimentation shows that it's being regenerated for you and you don't mind losing any custom layouts you've created to make the diagram simpler to understand, it should be fine to delete it.

Title: What is a .dbml.layout file for?


问:
how to enable zooming in Microsoft chart control by using Mouse wheel
I am using Microsoft Chart control in my project and I want to enable zooming feature in Chart Control by using Mouse Wheel, how can I achieve this?

but user don't have to click on chart, It should be like if mouse position is on my Chart than from that point onward  by mouse wheel rolling it can zoom in / out

答:
I modificated code from above and added a reverse zooming using Stack.

```<code>private class ZoomFrame
{
    public double XStart { get; set; }
    public double XFinish { get; set; }
    public double YStart { get; set; }
    public double YFinish { get; set; }
}

private readonly Stack<ZoomFrame> _zoomFrames = new Stack<ZoomFrame>();
private void chart1_MouseWheel(object sender, MouseEventArgs e)
{
    var chart = (Chart)sender;
    var xAxis = chart.ChartAreas[0].AxisX;
    var yAxis = chart.ChartAreas[0].AxisY;

    try
    {
        if (e.Delta < 0)
        {
            if (0 < _zoomFrames.Count)
            {
                var frame = _zoomFrames.Pop();
                if (_zoomFrames.Count == 0)
                {
                    xAxis.ScaleView.ZoomReset();
                    yAxis.ScaleView.ZoomReset();
                }
                else
                {
                    xAxis.ScaleView.Zoom(frame.XStart, frame.XFinish);
                    yAxis.ScaleView.Zoom(frame.YStart, frame.YFinish);
                }
            }
        }
        else if (e.Delta > 0)
        {
            var xMin = xAxis.ScaleView.ViewMinimum;
            var xMax = xAxis.ScaleView.ViewMaximum;
            var yMin = yAxis.ScaleView.ViewMinimum;
            var yMax = yAxis.ScaleView.ViewMaximum;

            _zoomFrames.Push(new ZoomFrame { XStart = xMin, XFinish = xMax, YStart = yMin, YFinish = yMax });

            var posXStart = xAxis.PixelPositionToValue(e.Location.X) - (xMax - xMin) / 4;
            var posXFinish = xAxis.PixelPositionToValue(e.Location.X) + (xMax - xMin) / 4;
            var posYStart = yAxis.PixelPositionToValue(e.Location.Y) - (yMax - yMin) / 4;
            var posYFinish = yAxis.PixelPositionToValue(e.Location.Y) + (yMax - yMin) / 4;

            xAxis.ScaleView.Zoom(posXStart, posXFinish);
            yAxis.ScaleView.Zoom(posYStart, posYFinish);
        }
    }
    catch { }
}
</code>```

Hope this helps!

Body:
I modificated code from above and added a reverse zooming using Stack.

private class ZoomFrame
{
    public double XStart { get; set; }
    public double XFinish { get; set; }
    public double YStart { get; set; }
    public double YFinish { get; set; }
}

private readonly Stack<ZoomFrame> _zoomFrames = new Stack<ZoomFrame>();
private void chart1_MouseWheel(object sender, MouseEventArgs e)
{
    var chart = (Chart)sender;
    var xAxis = chart.ChartAreas[0].AxisX;
    var yAxis = chart.ChartAreas[0].AxisY;

    try
    {
        if (e.Delta < 0)
        {
            if (0 < _zoomFrames.Count)
            {
                var frame = _zoomFrames.Pop();
                if (_zoomFrames.Count == 0)
                {
                    xAxis.ScaleView.ZoomReset();
                    yAxis.ScaleView.ZoomReset();
                }
                else
                {
                    xAxis.ScaleView.Zoom(frame.XStart, frame.XFinish);
                    yAxis.ScaleView.Zoom(frame.YStart, frame.YFinish);
                }
            }
        }
        else if (e.Delta > 0)
        {
            var xMin = xAxis.ScaleView.ViewMinimum;
            var xMax = xAxis.ScaleView.ViewMaximum;
            var yMin = yAxis.ScaleView.ViewMinimum;
            var yMax = yAxis.ScaleView.ViewMaximum;

            _zoomFrames.Push(new ZoomFrame { XStart = xMin, XFinish = xMax, YStart = yMin, YFinish = yMax });

            var posXStart = xAxis.PixelPositionToValue(e.Location.X) - (xMax - xMin) / 4;
            var posXFinish = xAxis.PixelPositionToValue(e.Location.X) + (xMax - xMin) / 4;
            var posYStart = yAxis.PixelPositionToValue(e.Location.Y) - (yMax - yMin) / 4;
            var posYFinish = yAxis.PixelPositionToValue(e.Location.Y) + (yMax - yMin) / 4;

            xAxis.ScaleView.Zoom(posXStart, posXFinish);
            yAxis.ScaleView.Zoom(posYStart, posYFinish);
        }
    }
    catch { }
}

Hope this helps!


问:
ViewPager2, get current page viewholder
When a page is selected, I want to display an image with a description in the current page.

Specifically, in the activity

viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
    @Override
    public void onPageSelected(int position) {
        super.onPageSelected(position);
        viewPagerAdapter.showImage(position);
    }
});
```

<p>In adapter</p>

<pre class="lang-java prettyprint-override"><code>public void showImage(int position) {
    ViewHolder holer = getHolder(position);
    holer.imageview.setVisibility(View.VISIBLE);
}
</code>```

I want the same function as above...

Is there a good solution?

答:
You can do something like this

```<code>(viewPager2.get(0) as RecyclerView).findViewHolderForAdapterPosition(position)
</code>```

or

```<code>(viewPager2.get(0) as RecyclerView).layoutManager.findViewByPosition(position)
</code>```

Title: ViewPager2, get current page viewholder

Body:
When a page is selected, I want to display an image with a description in the current page.

Specifically, in the activity

viewPager2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
    @Override
    public void onPageSelected(int position) {
        super.onPageSelected(position);
        viewPagerAdapter.showImage(position);
    }
});

In adapter

public void showImage(int position) {
    ViewHolder holer = getHolder(position);
    holer.imageview.setVisibility(View.VISIBLE);
}

I want the same function as above...

Is there a good solution?

Body:
You can do something like this

(viewPager2.get(0) as RecyclerView).findViewHolderForAdapterPosition(position)

or

(viewPager2.get(0) as RecyclerView).layoutManager.findViewByPosition(position)


问:
Configuring USB token for a standalone JavaFX application
This question may be off-topic but anyway I could not find any appropriate solution on Google so I have coded a standalone JavaFX application using JDK 14 & OpenJFX 15-ea+3 and I want to make this application work only when a USB token is connected to the computer. Actually I have three questions:

Q1: How to put a key on a USB Flash Memory & make it unreadable?

Q2: Which kind of key should be placed on USB Flash Memory? It should be a specific file or something?

Q3: How to read the key from USB Flash Memory when JavaFX application is up?

答: I've made a small library to detect USB storage devices on Java. It works on Windows, OSX and Linux. Take a look at: https://github.com/samuelcampos/usbdrivedetector</p>


问:
how to import library and use it in all store files nuxtjs
im using nuxtjs and i want import library one time and access it on any store file like

import Swal from 'sweetalert2'

thank you

答:
Try to assign that library to the store instance.

Then you can access it with "this" keyword from actions and - if not mistaken - mutations as well


问:
Redirect a specific url that is not found with javascript in header
I moved my website and I have a QR code (which is printed in public and can't be easily replaced) that points to a specific file on my old website that has now been moved. Currently, the URL just points to a "Not found" page on my new website. I try to use javascript in the header to catch the URL and forward it to the right URL as following:

```<code><script type="text/javascript">
    if(window.location.href === "https://www.website.com/multimedia/hoerproben/1.mp3")
    {
        window.location.href = "https://www.webseite.com/app/download/10079133850/1.mp3";
    }
</script>
</code>```

But it doesn't work. Any hints what I am doing wrong?

答:
when you open an url, the browser makes an http request to your server for that particular resource (in your example, an mp3 file).
JavaScript is not involved at all (actually, there are so called "service workers", but they are not what you're looking for, they are meant to do caching, not redirecting). The browser does not know that your JavaScript code exists and would not execute it.

What you should do is route redirecting from server, so when the browser asks from /oldlocation/file.mp3, instead the server answers with /newlocation/file.mp3

This could be in some different way according to your server. If you have no control on how your server works, what you're asking is simply not possibile.

Body:
I moved my website and I have a QR code (which is printed in public and can't be easily replaced) that points to a specific file on my old website that has now been moved. Currently, the URL just points to a "Not found" page on my new website. I try to use javascript in the header to catch the URL and forward it to the right URL as following:

But it doesn't work. Any hints what I am doing wrong?


答:
It won't work unless you place that code in the "Not found" page that gets served. If your URL pointed to an HTML file, you could have just placed one to do the redirect. For media files you would have to configure your server to serve an HTML file instead. Don't worry about the extension, it's the Content-Type header that determines the type of the file served. Doing this, however, is not good practice because your server would still be returning a 200 response code.

It's good practice to return 301 Moved Permanently as 101arrowz pointed out in the comments. How that can be accomplished will depend on what server you're using.

Here's how that would have been accomplished with express.js:

```<code>app.get('/multimedia/hoerproben/1.mp3', function(req, res) {
  res.redirect('/app/download/10079133850/1.mp3');
});
</code>```

Title: Redirect a specific url that is not found with javascript in header

Body:
It won't work unless you place that code in the "Not found" page that gets served. If your URL pointed to an HTML file, you could have just placed one to do the redirect. For media files you would have to configure your server to serve an HTML file instead. Don't worry about the extension, it's the Content-Type header that determines the type of the file served. Doing this, however, is not good practice because your server would still be returning a 200 response code.

It's good practice to return 301 Moved Permanently as 101arrowz pointed out in the comments. How that can be accomplished will depend on what server you're using.

Here's how that would have been accomplished with express.js:

app.get('/multimedia/hoerproben/1.mp3', function(req, res) {
  res.redirect('/app/download/10079133850/1.mp3');
});


问:
(Django) Trying to figure out how I can get the right product using query parameters on Postman (url.py and views.py)
I have been building a sandwich shop app and I succeesfully build models.py and inserted all the product data. However, when I try to call specific products using Postman and the Django server, it keeps showing 404. What I typed on postman is like so:
http://10.58.1.157:8000/product/sandwich?product_id=1

Below are my codes for urls.py and views.py

So far, I have tried:
urls.py

```<code>from django.urls import path
from .views import ProductView

urlpatterns = [
    path('sandwich/int:<product_id>/', ProductView.as_view()),
]
</code>```

and:
urls.py

```<code>path('sandwich/(?P<product_id>[\w.-]+)/', ProductView.as_view())
</code>```

views.py

```<code>import json
import bcrypt
import jwt

from django.views               import View
from django.shortcuts           import render
from django.http                import HttpResponse, JsonResponse
from django.db.models           import Q

from .models                    import Product, Category, SubCategory

class ProductView(View):
    def get(self, request):

        product_id = request.GET.get('product_id', None)

        return JsonResponse({'product_name':Product.objects.get(id=product_id).values()})
</code>```

To clarify the GET request, I will add the screenshot of Postman below:

答:
I finally solved the issue!

I looked at this page and improvised accordingly...
https://docs.djangoproject.com/en/3.0/topics/http/urls/#nested-arguments

the final version of request is:
http://127.0.0.1:8000/product/?product_id=1

and the urls.py is:

```<code>from django.urls        import path, re_path
from .views             import ProductView

urlpatterns = [
    re_path(r'^(?:\?product_id=(?P<product_id>\d+)/)?$', ProductView.as_view()),
]
</code>```

Body:
I have been building a sandwich shop app and I succeesfully build models.py and inserted all the product data. However, when I try to call specific products using Postman and the Django server, it keeps showing 404. What I typed on postman is like so:
http://10.58.1.157:8000/product/sandwich?product_id=1

Below are my codes for urls.py and views.py

So far, I have tried:
urls.py

from django.urls import path
from .views import ProductView

urlpatterns = [
    path('sandwich/int:<product_id>/', ProductView.as_view()),
]

and:
urls.py

path('sandwich/(?P<product_id>[\w.-]+)/', ProductView.as_view())

views.py

import json
import bcrypt
import jwt

from django.views               import View
from django.shortcuts           import render
from django.http                import HttpResponse, JsonResponse
from django.db.models           import Q

from .models                    import Product, Category, SubCategory

class ProductView(View):
    def get(self, request):

        product_id = request.GET.get('product_id', None)

        return JsonResponse({'product_name':Product.objects.get(id=product_id).values()})

To clarify the GET request, I will add the screenshot of Postman below:

Body:
I finally solved the issue!

I looked at this page and improvised accordingly...
https://docs.djangoproject.com/en/3.0/topics/http/urls/#nested-arguments

the final version of request is:
http://127.0.0.1:8000/product/?product_id=1

and the urls.py is:

from django.urls        import path, re_path
from .views             import ProductView

urlpatterns = [
    re_path(r'^(?:\?product_id=(?P<product_id>\d+)/)?$', ProductView.as_view()),
]


问:
How to prevent column total Count from display on component.html?
I have field total count I need to prevent total Count from display on component.html

I already do it but not working if you can tell me how to do that ?

I display data dynamically on header column and body data with angular 7

I try using filter function below but not working

```<code>this._displayreport.GetReportDetailsPaging(this.searchData).subscribe((data: any[]) => {

        this.reportdetailslist = data;
  this.headerCols = Object.keys(data[0]);
  this.contentBody=data.filter(item =>item != data[0].totalCount);

      });

    }

  }

<thead>
                  <tr>
                    <th >
                      <ng-container *ngIf="coln != 'totalCount'">

                        {{coln}}
                      </ng-container>
                    </th>

                  </tr>
                </thead>
                <tbody>

                    <tr *ngFor="let rep of contentBody">

                      <td *ngFor="let coln of headerCols">

                        <span>

                        {{rep[coln]}}
                        </span>
                       </td>
                       </tr>
                      <tbody>
</code>```

data object represent following data as any[]

```<code>companyName: "Innovasic, Inc."
done: "0"
notImpacted: "0"
notificationDate: "2009-11-12"
offilneURL: "https://source.z2data.com/2019/1/13/8/55/47/351/662203977/21527_SPCN.PDF"
onlineURL: "N/A"
pending: "3"
reportDate: "2020-05-07"
revisionID: "272299243"
teamName: "MFG"
totalCount: 79
</code>```

答:
it solved by change my code above to</p>

```<code>this.headerCols = Object.keys(data[0]).filter(x => x !== 'totalCount');
</code>```

Body:
I have field total count I need to prevent total Count from display on component.html

I already do it but not working if you can tell me how to do that ?

I display data dynamically on header column and body data with angular 7

I try using filter function below but not working

this._displayreport.GetReportDetailsPaging(this.searchData).subscribe((data: any[]) => {

        this.reportdetailslist = data;
  this.headerCols = Object.keys(data[0]);
  this.contentBody=data.filter(item =>item != data[0].totalCount);

      });

    }

  }

                      <ng-container *ngIf="coln != 'totalCount'">

                        {{coln}}
                      </ng-container>

                        {{rep[coln]}}

data object represent following data as any[]

companyName: "Innovasic, Inc."
done: "0"
notImpacted: "0"
notificationDate: "2009-11-12"
offilneURL: "https://source.z2data.com/2019/1/13/8/55/47/351/662203977/21527_SPCN.PDF"
onlineURL: "N/A"
pending: "3"
reportDate: "2020-05-07"
revisionID: "272299243"
teamName: "MFG"
totalCount: 79

Body:
it solved by change my code above to

this.headerCols = Object.keys(data[0]).filter(x => x !== 'totalCount');


问:
Joining the same table twice in MYSQL
I am trying to create a MYSQL query that pulls in data from a range of tables. I have a master bookings table and an invoice table where I am recording invoice id's etc from Stripe.

I am storing two invoices per booking; one a deposit, the second the final balance.

In my admin backend I then display to the admin info on whether the invoice is paid etc so need to pull in data from SQL to show this.

I'm following some previous guidance here What's the best way to join on the same table twice?.

My query is returning data, however when the invoices table is included twice (to give me the deposit and balance invoices) however the column names are identical.

Could someone point me in the right direction? I think I need to somehow rename the columns on the second returned invoice??? Sorry new to anything but basic SQL queries.

This is my SQL

```<code>SELECT * FROM bookings
INNER JOIN voyages ON bookings.booking_voyageID = voyages.voyage_id
LEFT JOIN emailautomations ON bookings.booking_reference = emailautomations.automation_bookingRef AND emailautomations.automation_sent != 1
LEFT JOIN invoices ON bookings.booking_stripeDepositInvoice = invoices.invoice_id
LEFT JOIN invoices inv2 ON bookings.booking_stripeBalanceInvoice = inv2.invoice_id
</code>```

Thanks to @Algef Almocera's answer I have amended my SQL (and stopped being lazy by using SELECT *, was able to trim loads of columns down to not many!)

```<code>SELECT
        bookings.booking_status,
        bookings.booking_reference,
        bookings.booking_stripeCustomerReference,
        bookings.booking_stripeDepositInvoice,
        bookings.booking_stripeBalanceInvoice,
        bookings.booking_totalPaid,
        bookings.booking_voyageID,
        bookings.booking_firstName,
        bookings.booking_lastName,
        bookings.booking_contractName,
        bookings.booking_contractEmail,
        voyages.voyage_id,
        voyages.voyage_name,
        voyages.voyage_startDate,
        depositInvoice.invoice_id AS depositInvoice_id,
        depositInvoice.invoice_status AS depositInvoice_status,
        balanceInvoice.invoice_id AS balanceInvoice_id,
        balanceInvoice.invoice_status AS balanceInvoice_status
      FROM bookings
      INNER JOIN voyages ON bookings.booking_voyageID = voyages.voyage_id
      LEFT JOIN emailautomations ON bookings.booking_reference = emailautomations.automation_bookingRef AND emailautomations.automation_sent != 1
      LEFT JOIN invoices depositInvoice ON bookings.booking_stripeDepositInvoice = depositInvoice.invoice_id
      LEFT JOIN invoices balanceInvoice ON bookings.booking_stripeBalanceInvoice = balanceInvoice.invoice_id
</code>```

答:
This, sometimes, couldn't be avoided as keywords might actually often be the same but of different purpose per table. To help with that, you can use aliases. for example:

```<code>SELECT
invoices.column_name AS invoices_column_name,
transactions.column_name AS transactions_column_name
FROM invoices ...
LEFT JOIN transactions ...
</code>```

Title: Joining the same table twice in MYSQL

Body:
I am trying to create a MYSQL query that pulls in data from a range of tables. I have a master bookings table and an invoice table where I am recording invoice id's etc from Stripe.

I am storing two invoices per booking; one a deposit, the second the final balance.

In my admin backend I then display to the admin info on whether the invoice is paid etc so need to pull in data from SQL to show this.

I'm following some previous guidance here What's the best way to join on the same table twice?.

My query is returning data, however when the invoices table is included twice (to give me the deposit and balance invoices) however the column names are identical.

Could someone point me in the right direction? I think I need to somehow rename the columns on the second returned invoice??? Sorry new to anything but basic SQL queries.

This is my SQL

SELECT * FROM bookings
INNER JOIN voyages ON bookings.booking_voyageID = voyages.voyage_id
LEFT JOIN emailautomations ON bookings.booking_reference = emailautomations.automation_bookingRef AND emailautomations.automation_sent != 1
LEFT JOIN invoices ON bookings.booking_stripeDepositInvoice = invoices.invoice_id
LEFT JOIN invoices inv2 ON bookings.booking_stripeBalanceInvoice = inv2.invoice_id

Thanks to @Algef Almocera's answer I have amended my SQL (and stopped being lazy by using SELECT *, was able to trim loads of columns down to not many!)

SELECT
        bookings.booking_status,
        bookings.booking_reference,
        bookings.booking_stripeCustomerReference,
        bookings.booking_stripeDepositInvoice,
        bookings.booking_stripeBalanceInvoice,
        bookings.booking_totalPaid,
        bookings.booking_voyageID,
        bookings.booking_firstName,
        bookings.booking_lastName,
        bookings.booking_contractName,
        bookings.booking_contractEmail,
        voyages.voyage_id,
        voyages.voyage_name,
        voyages.voyage_startDate,
        depositInvoice.invoice_id AS depositInvoice_id,
        depositInvoice.invoice_status AS depositInvoice_status,
        balanceInvoice.invoice_id AS balanceInvoice_id,
        balanceInvoice.invoice_status AS balanceInvoice_status
      FROM bookings
      INNER JOIN voyages ON bookings.booking_voyageID = voyages.voyage_id
      LEFT JOIN emailautomations ON bookings.booking_reference = emailautomations.automation_bookingRef AND emailautomations.automation_sent != 1
      LEFT JOIN invoices depositInvoice ON bookings.booking_stripeDepositInvoice = depositInvoice.invoice_id
      LEFT JOIN invoices balanceInvoice ON bookings.booking_stripeBalanceInvoice = balanceInvoice.invoice_id

Body:
This, sometimes, couldn't be avoided as keywords might actually often be the same but of different purpose per table. To help with that, you can use aliases. for example:

SELECT
invoices.column_name AS invoices_column_name,
transactions.column_name AS transactions_column_name
FROM invoices ...
LEFT JOIN transactions ...


问:
query database for results within a certain time using the user's timezone
How can I query a set of results that belong to a specific time period according to the user's time.

For example: "select * from table where datestamp like ".date("Y-m-d",strtotime("-1 day"))."%"

would give me results within the past 24 hours based on the server time. How can I do this query to be based on the user's time rather than the server's time?

答:
Ask your user which timezone he's in, then subtract/add the offset to your server's time.

"The last 24 hours" are the same all over the world though, so I'd rather change the query to encompass the last 24 hours, not the same day:

```<code>SELECT * FROM `table`
WHERE `datestamp` BETWEEN DATE_SUB(NOW(), INTERVAL 1 DAY) AND NOW()
</code>```

Body:
Ask your user which timezone he's in, then subtract/add the offset to your server's time.

"The last 24 hours" are the same all over the world though, so I'd rather change the query to encompass the last 24 hours, not the same day:

SELECT * FROM `table`
WHERE `datestamp` BETWEEN DATE_SUB(NOW(), INTERVAL 1 DAY) AND NOW()


问:
Why this Syntax Error on Python 3.8 for Mac
Check out the screenshot and help this newb with why i'm getting this syntax error with the for loop even though im following the right syntax.

The code :

```<code>elif choice == 'AVERAGE':
import statistics
lst = []
n = int(input('Enter number of values to calculate mean of: ')
for i in range(0,n):
        ele=int(input())
        lst.append(ele)
</code>```

The Error : Invalid Syntax for the ':' after 'range(0,n)'

答:
You are spacing the items inside the for loop with double Tab, the indentation should be either 4 spaces or a single tab.

And you are missing a parenthesis closing in the n input line

See the modified code below.

```<code>elif choice == 'AVERAGE':
    import statistics
    lst = []
    n = int(input('Enter number of values to calculate mean of: '))
    for i in range(0,n):
        ele=int(input())
        lst.append(ele)
</code>```

Body:
Check out the screenshot and help this newb with why i'm getting this syntax error with the for loop even though im following the right syntax.

The code :

elif choice == 'AVERAGE':
import statistics
lst = []
n = int(input('Enter number of values to calculate mean of: ')
for i in range(0,n):
        ele=int(input())
        lst.append(ele)

The Error : Invalid Syntax for the ':' after 'range(0,n)'

Body:
You are spacing the items inside the for loop with double Tab, the indentation should be either 4 spaces or a single tab.

And you are missing a parenthesis closing in the n input line

See the modified code below.

elif choice == 'AVERAGE':
    import statistics
    lst = []
    n = int(input('Enter number of values to calculate mean of: '))
    for i in range(0,n):
        ele=int(input())
        lst.append(ele)


问:
categoryChoiceTree in prestashop module configuration page
I'm developing a prestashop module and I'm trying to show a category tree in my backoffice configuration page.

I'm trying to follow this instructions below but  I don't know exactly where to add this code.

It should be inside main module's php? or inside a separate .php file and call it from the main one (don't know how to do it either).

As much time I'm spending trying to figure out, how to implement the code in the link above, the more I think I'm losing my time.
I see that "use" files, and this JS, " /admin-dev/themes/new-theme/js/components/form/choice-tree.js " are not in any prestashop folders.

答:
Well, you should invest some time and learn Symfony since this is what you need to build backend modules for Prestashop 1.7.

As a pointer, you need to create a form class extending the CommonAbstractType, add a build form method. e.g. :

```<code>public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->context = Context::getContext();
        $parents = [
          ['id_category' => 2, 'name' => 'Home', 'children' => $this->getSubCategories(1, true, 2)]
        ];

        $builder->add('category', CategoryChoiceTreeType::class, [
            'choices_tree' => $parents,
            'choice_value' => 'id_category',
            'choice_children' => 'children',
            'choice_label' => 'name',
            'disabled_values' => $disabledCategories,
            'label' => 'Choose a category'
        ])
</code>```

then add methods for retrieving the data to populate the form fields.

Then use this class in your controller and display the form:

```<code>$form = $this->createForm(YourFormForm::class);
</code>```

Also add a processForm to process data.

As mentioned, this is not a copy/paste situation you need to understand the Symfony workflow.

Body:
Well, you should invest some time and learn Symfony since this is what you need to build backend modules for Prestashop 1.7.

As a pointer, you need to create a form class extending the CommonAbstractType, add a build form method. e.g. :

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->context = Context::getContext();
        $parents = [
          ['id_category' => 2, 'name' => 'Home', 'children' => $this->getSubCategories(1, true, 2)]
        ];

        $builder->add('category', CategoryChoiceTreeType::class, [
            'choices_tree' => $parents,
            'choice_value' => 'id_category',
            'choice_children' => 'children',
            'choice_label' => 'name',
            'disabled_values' => $disabledCategories,
            'label' => 'Choose a category'
        ])

then add methods for retrieving the data to populate the form fields.

Then use this class in your controller and display the form:

$form = $this->createForm(YourFormForm::class);

Also add a processForm to process data.

As mentioned, this is not a copy/paste situation you need to understand the Symfony workflow.