问:
How to export data from struts2 to Excel
I am expecting data to export in Excel format. I have a problem in writing data to Excel file and when I download that it is not in Excel format.

In the below first method I am getting data from a database and sending it as a list to a second method that expects a filename.  In the second method I am trying to write the database data to an Excel file.

I have done coding for exporting to PDF also.  It gets correctly downloaded, but in the URL bar downloadTeacherListINExcel.action. I have given a file path like this: String fileName = "f:\\teachersList.pdf". When it is downloaded in the browser the filename comes over like f-teachersList.

```<code>public String exportInExcel() {

        // getting data from data base
        listOfTeachers = reportService.getlistOfTeachers();
        for (TeacherDTO teacherDTO : listOfTeachers) {
            System.out.println(teacherDTO.getTeacherEmailID());
        }

        // sending a list data export in excel
        String excelFileName = reportService.exportInExcel(listOfTeachers);
        System.out.println(excelFileName);
        try {
            fileInputStream = new FileInputStream(excelFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Execl Download Method");
        return SUCCESS;
    }
</code>```

Code written for Excel

```<code>@Override
    public String exportInExcel(List<TeacherDTO> listOfTeachers) {
        String fileName = "f:\\test\\teachersList.xls";
        try {

            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("Products List");

            // create heading
            Row rowHeading = sheet.createRow(0);

            rowHeading.createCell(0).setCellValue("Id");
            rowHeading.createCell(1).setCellValue("Name");

            for (int i = 0; i < 6; i++) {

                CellStyle stylerowHeading = workbook.createCellStyle();

                Font font = workbook.createFont();
                font.setBoldweight(Font.BOLDWEIGHT_BOLD);
                font.setFontName(HSSFFont.FONT_ARIAL);
                font.setFontHeightInPoints((short) 11);

                stylerowHeading.setFont(font);
                stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER);

                rowHeading.getCell(i).setCellStyle(stylerowHeading);
            }

            int r = 1;
            for (TeacherDTO teacher : listOfTeachers) {
                Row row = sheet.createRow(r);

                // Id column
                Cell cellID = row.createCell(0);
                cellID.setCellValue(teacher.getTeacherFirstName());// (run after
                                                                    // this line
                                                                    // once)

                // name column
                Cell cellName = row.createCell(1);
                cellName.setCellValue(teacher.getTeacherEmailID());// (run after
                                                                    // this line
                                                                    // once)

                r++;
            }

            // Auto fit
            for (int i = 0; i < 6; i++) {
                sheet.autoSizeColumn(i);
            }

            FileOutputStream fout = new FileOutputStream(new File(fileName));
            workbook.write(fout);
            fout.close();

            System.out.println("Excel Written Success");

        } catch (Exception e) {
        System.out.println("%%%%%%%%%%%%%%%%%%"+e.getMessage());
        }
        return fileName;
    }
</code>```

Struts config

```<code><action name="downloadTeacherListINExcel" class="com.pradeep.sms.controller.report.StaffReportAction" method="exportInExcel">
            <result  name="success"  type="stream">

                <param name="contentType">application/vnd.ms-excel</param>
                <param name="inputName">fileInputStream</param>
                 <param name="contentDisposition">attachment;filename=${fileName}</param>
                <param name="bufferSize">1024</param>
        </result>
    </action>
</code>```

Error

```<code>Hibernate: select
pradeepkumarhe1989@gmail.com
%%%%%%%%%%%%%%%%%%null
f:\test\teachersList.xls
java.io.FileNotFoundException: f:\test\teachersList.xls (The system cannot find the file specified)
</code>```

答:
package com.download2excel;

import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import com.opensymphony.xwork2.ActionSupport;

public class Excelwritinginjava extends ActionSupport {     private InputStream fileInputStream;

```<code>public String createExcelFile() throws Exception {      HSSFWorkbook workbook = new HSSFWorkbook();         HSSFSheet sheet = workbook.createSheet("January");      HSSFRow rowhead = sheet.createRow((short) 0);       rowhead.createCell(0).setCellValue("S.No.");        rowhead.createCell(1).setCellValue("Customer Name");        rowhead.createCell(2).setCellValue("Account Number");       rowhead.createCell(3).setCellValue("e-mail");       rowhead.createCell(4).setCellValue("Balance");      HSSFRow row = sheet.createRow((short) 1);       row.createCell(0).setCellValue("1");        row.createCell(1).setCellValue("subodh");       row.createCell(2).setCellValue("7644864977");       row.createCell(3).setCellValue("subodh.orcl@gmail.com");        row.createCell(4).setCellValue("700000.00");        HSSFRow row1 = sheet.createRow((short) 2);      row1.createCell(0).setCellValue("2");       row1.createCell(1).setCellValue("subodh sharma");       row1.createCell(2).setCellValue("22222222");        row1.createCell(3).setCellValue("subodh.orcl@gmail.com");       row1.createCell(4).setCellValue("200000.00");       ByteArrayOutputStream baos = new ByteArrayOutputStream();       workbook.write(baos);       setFileInputStream(new ByteArrayInputStream(baos.toByteArray()));       return SUCCESS;     }

public InputStream getFileInputStream() {       return fileInputStream;     }

public void setFileInputStream(InputStream fileInputStream) {       this.fileInputStream = fileInputStream;     }
</code>```

}

======================struts.xml ====

       application/octet-stream      fileInputStream   attachment;filename="Download.xls"       1024

Body:
I am expecting data to export in Excel format. I have a problem in writing data to Excel file and when I download that it is not in Excel format.

In the below first method I am getting data from a database and sending it as a list to a second method that expects a filename.  In the second method I am trying to write the database data to an Excel file.

I have done coding for exporting to PDF also.  It gets correctly downloaded, but in the URL bar downloadTeacherListINExcel.action. I have given a file path like this: String fileName = "f:\\teachersList.pdf". When it is downloaded in the browser the filename comes over like f-teachersList.

public String exportInExcel() {

        // getting data from data base
        listOfTeachers = reportService.getlistOfTeachers();
        for (TeacherDTO teacherDTO : listOfTeachers) {
            System.out.println(teacherDTO.getTeacherEmailID());
        }

        // sending a list data export in excel
        String excelFileName = reportService.exportInExcel(listOfTeachers);
        System.out.println(excelFileName);
        try {
            fileInputStream = new FileInputStream(excelFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("Execl Download Method");
        return SUCCESS;
    }

Code written for Excel

@Override
    public String exportInExcel(List<TeacherDTO> listOfTeachers) {
        String fileName = "f:\\test\\teachersList.xls";
        try {

            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet("Products List");

            // create heading
            Row rowHeading = sheet.createRow(0);

            rowHeading.createCell(0).setCellValue("Id");
            rowHeading.createCell(1).setCellValue("Name");

            for (int i = 0; i < 6; i++) {

                CellStyle stylerowHeading = workbook.createCellStyle();

                Font font = workbook.createFont();
                font.setBoldweight(Font.BOLDWEIGHT_BOLD);
                font.setFontName(HSSFFont.FONT_ARIAL);
                font.setFontHeightInPoints((short) 11);

                stylerowHeading.setFont(font);
                stylerowHeading.setVerticalAlignment(CellStyle.ALIGN_CENTER);

                rowHeading.getCell(i).setCellStyle(stylerowHeading);
            }

            int r = 1;
            for (TeacherDTO teacher : listOfTeachers) {
                Row row = sheet.createRow(r);

                // Id column
                Cell cellID = row.createCell(0);
                cellID.setCellValue(teacher.getTeacherFirstName());// (run after
                                                                    // this line
                                                                    // once)

                // name column
                Cell cellName = row.createCell(1);
                cellName.setCellValue(teacher.getTeacherEmailID());// (run after
                                                                    // this line
                                                                    // once)

                r++;
            }

            // Auto fit
            for (int i = 0; i < 6; i++) {
                sheet.autoSizeColumn(i);
            }

            FileOutputStream fout = new FileOutputStream(new File(fileName));
            workbook.write(fout);
            fout.close();

            System.out.println("Excel Written Success");

        } catch (Exception e) {
        System.out.println("%%%%%%%%%%%%%%%%%%"+e.getMessage());
        }
        return fileName;
    }

Struts config

<action name="downloadTeacherListINExcel" class="com.pradeep.sms.controller.report.StaffReportAction" method="exportInExcel">
            <result  name="success"  type="stream">

                <param name="contentType">application/vnd.ms-excel</param>
                <param name="inputName">fileInputStream</param>
                 <param name="contentDisposition">attachment;filename=${fileName}</param>
                <param name="bufferSize">1024</param>
        </result>
    </action>

Error

Hibernate: select
pradeepkumarhe1989@gmail.com
%%%%%%%%%%%%%%%%%%null
f:\test\teachersList.xls
java.io.FileNotFoundException: f:\test\teachersList.xls (The system cannot find the file specified)

Body:
package com.download2excel;

import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import com.opensymphony.xwork2.ActionSupport;

public class Excelwritinginjava extends ActionSupport {     private InputStream fileInputStream;

public String createExcelFile() throws Exception {      HSSFWorkbook workbook = new HSSFWorkbook();         HSSFSheet sheet = workbook.createSheet("January");      HSSFRow rowhead = sheet.createRow((short) 0);       rowhead.createCell(0).setCellValue("S.No.");        rowhead.createCell(1).setCellValue("Customer Name");        rowhead.createCell(2).setCellValue("Account Number");       rowhead.createCell(3).setCellValue("e-mail");       rowhead.createCell(4).setCellValue("Balance");      HSSFRow row = sheet.createRow((short) 1);       row.createCell(0).setCellValue("1");        row.createCell(1).setCellValue("subodh");       row.createCell(2).setCellValue("7644864977");       row.createCell(3).setCellValue("subodh.orcl@gmail.com");        row.createCell(4).setCellValue("700000.00");        HSSFRow row1 = sheet.createRow((short) 2);      row1.createCell(0).setCellValue("2");       row1.createCell(1).setCellValue("subodh sharma");       row1.createCell(2).setCellValue("22222222");        row1.createCell(3).setCellValue("subodh.orcl@gmail.com");       row1.createCell(4).setCellValue("200000.00");       ByteArrayOutputStream baos = new ByteArrayOutputStream();       workbook.write(baos);       setFileInputStream(new ByteArrayInputStream(baos.toByteArray()));       return SUCCESS;     }

public InputStream getFileInputStream() {       return fileInputStream;     }

public void setFileInputStream(InputStream fileInputStream) {       this.fileInputStream = fileInputStream;     }

}

======================struts.xml ====

       application/octet-stream      fileInputStream   attachment;filename="Download.xls"       1024


来源: stackexchange

问:
Load image from url
I have an image URL. I want to display an image from this URL in an ImageView but I am unable to do that.

How can this be achieved?

答:
This is my working solution using Adrian's code example:

```<code>private void loadImage(String pUrl) {
    Thread imageDataThread = new Thread(() -> {
        try {
            URL tUrl = new URL(pUrl);
            Bitmap imageBitmap = BitmapFactory.decodeStream(tUrl.openConnection().getInputStream());
            runOnUiThread(() -> image_preview.setImageBitmap(imageBitmap));
        } catch(IOException pExc) {
            showToast("Error loading image for this question!");
            pExc.printStackTrace();
        }
    });
    imageDataThread.start();
}
</code>```

Note: You can use this pre-defined method to load image bitmap or you can use yours in case you need to resize image or some similar operation over image.

ContentLicense: CC BY-SA 3.0

Title: Load image from url

Body:
This is my working solution using Adrian's code example:

private void loadImage(String pUrl) {
    Thread imageDataThread = new Thread(() -> {
        try {
            URL tUrl = new URL(pUrl);
            Bitmap imageBitmap = BitmapFactory.decodeStream(tUrl.openConnection().getInputStream());
            runOnUiThread(() -> image_preview.setImageBitmap(imageBitmap));
        } catch(IOException pExc) {
            showToast("Error loading image for this question!");
            pExc.printStackTrace();
        }
    });
    imageDataThread.start();
}

Note: You can use this pre-defined method to load image bitmap or you can use yours in case you need to resize image or some similar operation over image.

ContentLicense: CC BY-SA 4.0


问:
How to activate and deactivate GameObjects with a delay in Untiy
I am working on a game, that has a keypad puzzle. A specific key combination lights up one by one, which the player must repeat to solve that puzzle. I am going to let the player know what the combination is by activating and deactivating some GameObjects systematically, one by one. As it suggests, there is some time delay between the deactivation of one GameObject and the activation of another. The problem is, in my code, all the GameObjects activate simultaneously instead of one by one, after a delay.

Here is the code:

```<code> public string Generate(int length, float delay)
    {
        // Variables for logic
        string combination = "";
        int prev = -1; int current = 0;
        int rnd = 0;

        for (int i = 0; i < length; i++)
        {
            rnd = Random.Range(0, BUTTONS);
            while (rnd == prev)
            {
                rnd = Random.Range(0, BUTTONS);
            }
            prev = current;
            current = rnd;

            combination += current.ToString();

            // Activation and Deactivation

            StartCoroutine(GenerateDelay(delay, current));
        }
        return combination;
    }

    IEnumerator GenerateDelay(float delay, int index)
    {
        ButtonClicks[index].SetActive(true);
        yield return new WaitForSeconds(delay);
        ButtonClicks[index].SetActive(false);
    }
</code>```

The loop counter specifies the length of the combination. I believe there is something wrong with the Coroutine I made? Since all the objects activate simultaneously.

Here is the result in the game as well:

We can see, only one button should turn green at a time, but all of them do in this case. Any solutions?

答:
You start all your Coroutines parallel so things happen at the same time.

StartCoroutine does not delay the method which calls it (unless it is yielded as well.

You would need to run the entire loop within a Coroutine in order to delay it as well.

You could simply split up the creation of the combination and while you already return it you start the visualization in the background in parallel

```<code>public string Generate(int length, float delay, Action<string> onCombination)
{
    // Variables for logic
    var combination = List<int>();
    var prev = -1;

    for (var i = 0; i < length; i++)
    {
        int rnd;
        do
        {
            rnd = Random.Range(0, BUTTONS);
        }
        while (rnd == prev);

        prev = rnd;

        combination.Add(rnd);
    }

    StartCorouine (ShowCombination(combination, delay));

    return string.Join("", combination);
}

private IEnumerator ShowCombination (IEnumerable<int> combination, float delay)
{
    foreach(var i in combination)
    {
        ButtonClicks[i].SetActive(true);
        yield return new WaitForSeconds(delay);
        ButtonClicks[i].SetActive(false);
    }
}
</code>```

Body:
I am working on a game, that has a keypad puzzle. A specific key combination lights up one by one, which the player must repeat to solve that puzzle. I am going to let the player know what the combination is by activating and deactivating some GameObjects systematically, one by one. As it suggests, there is some time delay between the deactivation of one GameObject and the activation of another. The problem is, in my code, all the GameObjects activate simultaneously instead of one by one, after a delay.

Here is the code:

 public string Generate(int length, float delay)
    {
        // Variables for logic
        string combination = "";
        int prev = -1; int current = 0;
        int rnd = 0;

        for (int i = 0; i < length; i++)
        {
            rnd = Random.Range(0, BUTTONS);
            while (rnd == prev)
            {
                rnd = Random.Range(0, BUTTONS);
            }
            prev = current;
            current = rnd;

            combination += current.ToString();

            // Activation and Deactivation

            StartCoroutine(GenerateDelay(delay, current));
        }
        return combination;
    }

    IEnumerator GenerateDelay(float delay, int index)
    {
        ButtonClicks[index].SetActive(true);
        yield return new WaitForSeconds(delay);
        ButtonClicks[index].SetActive(false);
    }

The loop counter specifies the length of the combination. I believe there is something wrong with the Coroutine I made? Since all the objects activate simultaneously.

Here is the result in the game as well:

We can see, only one button should turn green at a time, but all of them do in this case. Any solutions?

Body:
You start all your Coroutines parallel so things happen at the same time.

StartCoroutine does not delay the method which calls it (unless it is yielded as well.

You would need to run the entire loop within a Coroutine in order to delay it as well.

You could simply split up the creation of the combination and while you already return it you start the visualization in the background in parallel

public string Generate(int length, float delay, Action<string> onCombination)
{
    // Variables for logic
    var combination = List<int>();
    var prev = -1;

    for (var i = 0; i < length; i++)
    {
        int rnd;
        do
        {
            rnd = Random.Range(0, BUTTONS);
        }
        while (rnd == prev);

        prev = rnd;

        combination.Add(rnd);
    }

    StartCorouine (ShowCombination(combination, delay));

    return string.Join("", combination);
}

private IEnumerator ShowCombination (IEnumerable<int> combination, float delay)
{
    foreach(var i in combination)
    {
        ButtonClicks[i].SetActive(true);
        yield return new WaitForSeconds(delay);
        ButtonClicks[i].SetActive(false);
    }
}


问:
c++ std::accumulate with policy execution is not found
I want to use the new parallel facilities of C++17 but my computer don't.

This works :

```<code>finalOutline.push_back(std::accumulate(intermediateCoefs.begin(), intermediateCoefs.end(),origin,[](sf::Vector2f prev, sf::Vector2f current) {
            return sf::Vector2f(current.x + prev.x, current.y + prev.y);
        }));
</code>```

But this does not work :

```<code>finalOutline.push_back(std::accumulate(std::execution::seq, intermediateCoefs.begin(), intermediateCoefs.end(),origin,[](sf::Vector2f prev, sf::Vector2f current) {
            return sf::Vector2f(current.x + prev.x, current.y + prev.y);
        }));
</code>```

Here the error message :

```<code>/home/mbs/Bureau/cplusplusWorkspace/sauvegardeGit/compresse-moi-ces-cercles/src/Model.cpp: In member function ‘void Model::computeFinalOutline(int)’:
/home/mbs/Bureau/cplusplusWorkspace/sauvegardeGit/compresse-moi-ces-cercles/src/Model.cpp:246:47: error: no matching function for call to ‘accumulate(const __pstl::execution::v1::sequenced_policy&, std::vector<sf::Vector2<float> >::iterator, std::vector<sf::Vector2<float> >::iterator, sf::Vector2f&, Model::computeFinalOutline(int)::<lambda(sf::Vector2f, sf::Vector2f)>)’
  246 |         finalOutline.push_back(std::accumulate(std::execution::seq, intermediateCoefs.begin(), intermediateCoefs.end(),origin,[](sf::Vector2f prev, sf::Vector2f current) {
      |                                ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  247 |             return sf::Vector2f(current.x + prev.x, current.y + prev.y);
      |             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  248 |         }));
      |         ~~

</code>```

I do include what it is needed (i guess):

```<code>#include <numeric>
#include <execution>
</code>```

I always display the version of __cplusplus when I execute my programm and its value is : 202002

Here my CMAKE file (but i don't think it's usefull) :

```<code>cmake_minimum_required(VERSION 3.22) # way overkill

project(Taratari)

set (CMAKE_CXX_STANDARD 20)
set (CMAKE_CXX_STANDARD_REQUIRED ON)

set(CMAKE_CXX_FLAGS_DEBUG_INIT "-g -Wall -Wextra -pedantic -Werror")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++2a")

include_directories(
    $(PROJECT_SOURCE_DIR)/include
    $(PROJECT_SOURCE_DIR)/src
)

file(GLOB all_SRCS
    "${PROJECT_SOURCE_DIR}/include/*.h"
    "${PROJECT_SOURCE_DIR}/src/*.cpp"
)

add_compile_options(
       -mavx
)

#sfml
find_package(SFML REQUIRED system graphics network audio window) #too much flag no ?

add_executable(exe ${all_SRCS})

target_link_libraries(exe PRIVATE sfml-audio sfml-graphics sfml-network sfml-system sfml-window)

</code>```

And to be really sure, here is gcc -v :

```<code>Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.1.0-1ubuntu1~20.04' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --disable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-2V7zgg/gcc-11-11.1.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-11-2V7zgg/gcc-11-11.1.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 11.1.0 (Ubuntu 11.1.0-1ubuntu1~20.04)

</code>```

So, I do not understand what is happening. Do I need a compilation flag ? (But the doc do not mention it).

Thank you for your help and have a nice day :-)

答:
std::accumulate is meant to apply the binary operation in-order, so it doesn't make any sense to use an execution policy. It doesn't have any overload accepting one (see https://en.cppreference.com/w/cpp/algorithm/accumulate).

If you want to allow out-of-order evaluation with some execution policy, replace std::accumulate by std::reduce. std::reduce may assume commutativity and associativity of the operation to reorder it into any permutation and apply it in any grouping of the elements.

Body:
I want to use the new parallel facilities of C++17 but my computer don't.

This works :

finalOutline.push_back(std::accumulate(intermediateCoefs.begin(), intermediateCoefs.end(),origin,[](sf::Vector2f prev, sf::Vector2f current) {
            return sf::Vector2f(current.x + prev.x, current.y + prev.y);
        }));

But this does not work :

finalOutline.push_back(std::accumulate(std::execution::seq, intermediateCoefs.begin(), intermediateCoefs.end(),origin,[](sf::Vector2f prev, sf::Vector2f current) {
            return sf::Vector2f(current.x + prev.x, current.y + prev.y);
        }));

Here the error message :

/home/mbs/Bureau/cplusplusWorkspace/sauvegardeGit/compresse-moi-ces-cercles/src/Model.cpp: In member function ‘void Model::computeFinalOutline(int)’:
/home/mbs/Bureau/cplusplusWorkspace/sauvegardeGit/compresse-moi-ces-cercles/src/Model.cpp:246:47: error: no matching function for call to ‘accumulate(const __pstl::execution::v1::sequenced_policy&, std::vector<sf::Vector2<float> >::iterator, std::vector<sf::Vector2<float> >::iterator, sf::Vector2f&, Model::computeFinalOutline(int)::<lambda(sf::Vector2f, sf::Vector2f)>)’
  246 |         finalOutline.push_back(std::accumulate(std::execution::seq, intermediateCoefs.begin(), intermediateCoefs.end(),origin,[](sf::Vector2f prev, sf::Vector2f current) {
      |                                ~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  247 |             return sf::Vector2f(current.x + prev.x, current.y + prev.y);
      |             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  248 |         }));
      |         ~~

I do include what it is needed (i guess):

#include <numeric>
#include <execution>

I always display the version of __cplusplus when I execute my programm and its value is : 202002

Here my CMAKE file (but i don't think it's usefull) :

cmake_minimum_required(VERSION 3.22) # way overkill

project(Taratari)

set (CMAKE_CXX_STANDARD 20)
set (CMAKE_CXX_STANDARD_REQUIRED ON)

set(CMAKE_CXX_FLAGS_DEBUG_INIT "-g -Wall -Wextra -pedantic -Werror")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++2a")

include_directories(
    $(PROJECT_SOURCE_DIR)/include
    $(PROJECT_SOURCE_DIR)/src
)

file(GLOB all_SRCS
    "${PROJECT_SOURCE_DIR}/include/*.h"
    "${PROJECT_SOURCE_DIR}/src/*.cpp"
)

add_compile_options(
       -mavx
)

#sfml
find_package(SFML REQUIRED system graphics network audio window) #too much flag no ?

add_executable(exe ${all_SRCS})

target_link_libraries(exe PRIVATE sfml-audio sfml-graphics sfml-network sfml-system sfml-window)

And to be really sure, here is gcc -v :

Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/11/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:amdgcn-amdhsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 11.1.0-1ubuntu1~20.04' --with-bugurl=file:///usr/share/doc/gcc-11/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,m2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-11 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --enable-libphobos-checking=release --with-target-system-zlib=auto --enable-objc-gc=auto --enable-multiarch --disable-werror --disable-cet --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none=/build/gcc-11-2V7zgg/gcc-11-11.1.0/debian/tmp-nvptx/usr,amdgcn-amdhsa=/build/gcc-11-2V7zgg/gcc-11-11.1.0/debian/tmp-gcn/usr --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu --with-build-config=bootstrap-lto-lean --enable-link-serialization=2
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 11.1.0 (Ubuntu 11.1.0-1ubuntu1~20.04)

So, I do not understand what is happening. Do I need a compilation flag ? (But the doc do not mention it).

Thank you for your help and have a nice day :-)


问:
Youtube iframe is not working in Chrome browser on Mobile

Note: It also works fine in the incognito window of Chrome browser and other browsers (like Mozilla) on Mobile.

It loads the video data successfully but when I try to play the video it shows me an error.

Run this code using local environment like vs-code etc.

This snippet works on a computer browser properly, but when I open the same page using IP on my mobile Chrome browser, I got an error, but it works in the incognito mode and other browsers too.

I don't know why it is behaving like this, It would be really helpful if anyone can rid of this.

Computer Chrome Browser[Working fine]

Mobile Chrome Browser [Not Playing the video]

//YouTube embed with YouTube Iframe API
var tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// YouTube embed player details
var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player("player", {
    height: "390",
    width: "640",
    videoId: "668nUCeBHyY",

    //Features
    playerVars: {
      controls: 0,
      rel: 0,
      disablekb: 1,
    },
  });
}

//functions
function playYT() {
  player.playVideo();
}

function pauseYT() {
  player.pauseVideo();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div style="pointer-events:none" id="player"></div><br><br>
<button onclick="playYT()">Play</button>
<button onclick="pauseYT()">Pause</button></code>```

答:
Disable all of your browser extensions

I known is sounds like a simple answer but try it. This happens to me all the time. Probably one or more of you browser extensions is blocking the Youtube imbedded iframe from showing for more security or privacy. I know that Blocksi extension for Chrome blocks Youtube embeds.

Body:
Note: It also works fine in the incognito window of Chrome browser and other browsers (like Mozilla) on Mobile.

It loads the video data successfully but when I try to play the video it shows me an error.

Run this code using local environment like vs-code etc.

This snippet works on a computer browser properly, but when I open the same page using IP on my mobile Chrome browser, I got an error, but it works in the incognito mode and other browsers too.

I don't know why it is behaving like this, It would be really helpful if anyone can rid of this.

Computer Chrome Browser[Working fine]

Mobile Chrome Browser [Not Playing the video]

//YouTube embed with YouTube Iframe API
var tag = document.createElement("script");
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName("script")[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// YouTube embed player details
var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player("player", {
    height: "390",
    width: "640",
    videoId: "668nUCeBHyY",

    //Features
    playerVars: {
      controls: 0,
      rel: 0,
      disablekb: 1,
    },
  });
}

//functions
function playYT() {
  player.playVideo();
}

function pauseYT() {
  player.pauseVideo();
}

<button onclick="playYT()">Play</button>
<button onclick="pauseYT()">Pause</button>


问:
Why title, description goes off the screen and date not showing properly in constrainlayout
I am developing news app  and I have implemented constraint layout with  card view but title description not showing and title and description goes of the screen in real device  but in layout inspector in android studio it is showing fine

below my view

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="article"
            type="com.example.newsworldwide.model.Article" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView2"
        android:layout_width="0dp"
        android:layout_height="150dp"
        android:layout_marginHorizontal="16dp"
        android:layout_marginVertical="8dp"
        app:cardCornerRadius="12dp"
        app:cardElevation="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/articleImage"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_marginStart="4dp"
            android:elevation="16dp"
            android:src="@drawable/img"
            app:civ_border_width="2dp"
            app:imageUrl="@{article.urlToImage}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <TextView
            android:id="@+id/articleTitle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="10dp"
            android:layout_marginTop="24dp"
            android:ellipsize="end"
            android:maxLines="2"
            android:text="Mini olive pies by Vaggelio"
            android:textColor="#000"
            android:textSize="18sp"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.65"
            app:layout_constraintStart_toEndOf="@+id/articleImage"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/articleDescription"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="16dp"
            android:ellipsize="end"
            android:maxLines="6"
            android:text="This is the most information savory snack that I have ever seen!!!"
            android:textColor="#000"
            android:textSize="12sp"
            android:textStyle="italic"
            app:layout_constraintStart_toStartOf="@+id/articleTitle"
            app:layout_constraintTop_toBottomOf="@+id/articleTitle" />

        <TextView
            android:id="@+id/articleDate"
            android:layout_width="wrap_content"
            android:layout_height="16dp"
            android:layout_marginEnd="48dp"
            android:layout_marginBottom="8dp"
            android:text="01.02.2022"
            android:textColor="#FF9935"
            android:textSize="12sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.cardview.widget.CardView>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
</code>```

below my  recyclerview layout

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="491dp"
        android:layout_height="826dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        tools:listitem="@layout/news_item" />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_marginBottom="260dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

following screenshot from layout inspector in android studio

following screenshot of the app  from real device

I want to know where exactly I am making mistake what I have to do in order to show title description and date so that it can fit screen perfectly

答: I think the tour item not the problem.  Check the size of the RecyclerView.

Body:
I am developing news app  and I have implemented constraint layout with  card view but title description not showing and title and description goes of the screen in real device  but in layout inspector in android studio it is showing fine

below my view

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <variable
            name="article"
            type="com.example.newsworldwide.model.Article" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView2"
        android:layout_width="0dp"
        android:layout_height="150dp"
        android:layout_marginHorizontal="16dp"
        android:layout_marginVertical="8dp"
        app:cardCornerRadius="12dp"
        app:cardElevation="10dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <de.hdodenhof.circleimageview.CircleImageView
            android:id="@+id/articleImage"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_marginStart="4dp"
            android:elevation="16dp"
            android:src="@drawable/img"
            app:civ_border_width="2dp"
            app:imageUrl="@{article.urlToImage}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

        <TextView
            android:id="@+id/articleTitle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginHorizontal="10dp"
            android:layout_marginTop="24dp"
            android:ellipsize="end"
            android:maxLines="2"
            android:text="Mini olive pies by Vaggelio"
            android:textColor="#000"
            android:textSize="18sp"
            android:textStyle="bold"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.65"
            app:layout_constraintStart_toEndOf="@+id/articleImage"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/articleDescription"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="8dp"
            android:layout_marginTop="16dp"
            android:ellipsize="end"
            android:maxLines="6"
            android:text="This is the most information savory snack that I have ever seen!!!"
            android:textColor="#000"
            android:textSize="12sp"
            android:textStyle="italic"
            app:layout_constraintStart_toStartOf="@+id/articleTitle"
            app:layout_constraintTop_toBottomOf="@+id/articleTitle" />

        <TextView
            android:id="@+id/articleDate"
            android:layout_width="wrap_content"
            android:layout_height="16dp"
            android:layout_marginEnd="48dp"
            android:layout_marginBottom="8dp"
            android:text="01.02.2022"
            android:textColor="#FF9935"
            android:textSize="12sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.cardview.widget.CardView>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

below my  recyclerview layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="491dp"
        android:layout_height="826dp"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.506"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        tools:listitem="@layout/news_item" />

    <ProgressBar
        android:id="@+id/progressBar"
        android:layout_width="0dp"
        android:layout_height="48dp"
        android:layout_marginBottom="260dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

following screenshot from layout inspector in android studio

following screenshot of the app  from real device

I want to know where exactly I am making mistake what I have to do in order to show title description and date so that it can fit screen perfectly


问:
jQuery addClass() not working in IE (8, 9 and probably the other one too)
Simple html:

```<code><div class="stuff-choice">
  <div class="item a">
    <label class="signup-checkbox">
      <input type="checkbox" value="a" name="stuff[a][]" id="stuff_choice_" class="things">
      <strong>A</strong>
    </label>
  </div>
</div>
</code>```

Basically I detect when someone click on the checkbox with the css class .things, and then I updated the parent
 with a css class .selected.

The JS: (with a $(document).ready(function(){ ...

```<code>$('.things').click(function() {
    item = $(this).closest("div");
    if ($(this).attr('checked') != null)
        $(item).addClass('selected');
    else
        $(item).removeClass('selected');
});
</code>```

This works like a charm under:
- Safari (mac & win)
- Firefox (mac & win)

But not under IE !?!?

I have no clue why...

Thanks,

Alex

答:
Try this, closest already gives a jQuery object you dont have to wrap it in $() and also is() method can be used to check is checked or not.

```<code>$('.things').click(function() {
    $item = $(this).closest("div");
    if ($(this).is(':checked'))
        $item.addClass('selected');
    else
        $item.removeClass('selected');
});
</code>```

Body:
Simple html:

      <input type="checkbox" value="a" name="stuff[a][]" id="stuff_choice_" class="things">
      A

Basically I detect when someone click on the checkbox with the css class .things, and then I updated the parent
 with a css class .selected.

The JS: (with a $(document).ready(function(){ ...

$('.things').click(function() {
    item = $(this).closest("div");
    if ($(this).attr('checked') != null)
        $(item).addClass('selected');
    else
        $(item).removeClass('selected');
});

This works like a charm under:
- Safari (mac & win)
- Firefox (mac & win)

But not under IE !?!?

I have no clue why...

Thanks,

Alex

Body:
Try this, closest already gives a jQuery object you dont have to wrap it in $() and also is() method can be used to check is checked or not.

$('.things').click(function() {
    $item = $(this).closest("div");
    if ($(this).is(':checked'))
        $item.addClass('selected');
    else
        $item.removeClass('selected');
});


问:
OCaml function definition
Can somebody tell me the difference between these two definitions ?

```<code>let f x y = x + y;;
</code>```

which yields val f : int -> int -> int = <fun>

and  this definition

```<code>let f = fun x y -> x + y;;
</code>```

which also yields val f : int -> int -> int = <fun> ?

答:
All functions in OCaml take a single argument, and return a single value.

Here's a function that demonstrates this.

```<code>fun x -> x + 1
</code>```

We can apply this function to a value.

```<code>(fun x -> x + 1) 2
</code>```

But this is inconvenient, so we bind a name to this function.

```<code>let inc = fun x -> x + 1
</code>```

Functions are values in OCaml, so a function can return a function.

```<code>let add = fun x -> fun y -> x + y
</code>```

We can now apply this:

```<code>(add 1) 1
</code>```

Or because of how this is processed:

```<code>add 1 1
</code>```

All of this is very inconvenient in practice, there is shorthand syntax so we can just write:

```<code>let add x y = x + y
</code>```

But consider again:

```<code>let add = fun x -> fun y -> x + y
</code>```

This if a function that takes an argument and spits out a function that takes an argument. What if we stop at providing that first argument? Well, then we get a function back that takes the second argument and produces a sum.

```<code>let inc = add 1
</code>```

In this case, we've partially applied the add function. This lets us take bits of code like:

```<code>let some_list = [2; 3; 4] in
List.map (fun x -> add 1 x) some_list
</code>```

And express it as:

```<code>let some_list = [2; 3; 4] in
List.map (add 1) some_list
</code>```

Title: OCaml function definition

Body:
Can somebody tell me the difference between these two definitions ?

let f x y = x + y;;

which yields val f : int -> int -> int = <fun>

and  this definition

let f = fun x y -> x + y;;

which also yields val f : int -> int -> int = <fun> ?

Body:
All functions in OCaml take a single argument, and return a single value.

Here's a function that demonstrates this.

fun x -> x + 1

We can apply this function to a value.

(fun x -> x + 1) 2

But this is inconvenient, so we bind a name to this function.

let inc = fun x -> x + 1

Functions are values in OCaml, so a function can return a function.

let add = fun x -> fun y -> x + y

We can now apply this:

(add 1) 1

Or because of how this is processed:

add 1 1

All of this is very inconvenient in practice, there is shorthand syntax so we can just write:

let add x y = x + y

But consider again:

let add = fun x -> fun y -> x + y

This if a function that takes an argument and spits out a function that takes an argument. What if we stop at providing that first argument? Well, then we get a function back that takes the second argument and produces a sum.

let inc = add 1

In this case, we've partially applied the add function. This lets us take bits of code like:

let some_list = [2; 3; 4] in
List.map (fun x -> add 1 x) some_list

And express it as:

let some_list = [2; 3; 4] in
List.map (add 1) some_list


问:
How to pass struct array arguments to a function the right way?
Source Code:

```<code>#include <iostream>

using namespace std;

struct Employee {

   string name;
   int age;
   float salary;

};

void displayData(Employee);

int main() {

   Employee employee[3];
   int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);

   for(int i = 0; i < sizeOfEmployee; i++) {
       cout << "Enter name for employee " << i + 1 << ": ";
       cin >> employee->name;
       cout << "Enter age for employee " << i + 1 << ": ";
       cin >> employee->age;
       cout << "Enter salary for employee " << i + 1 << ": ";
       cin >> employee->salary;
}

   for(int i = 0; i < sizeOfEmployee; i++) {
       displayData(employee[i]);
}

}

void displayData(Employee employee) {

   cout << "DISPLAYING INFORMATION" << endl;
   cout << "Name: " << employee.name << endl;
   cout << "Age: " << employee.age << endl;
   cout << "Salary: " << employee.salary << endl;

}
</code>```

My code doesn't display all the data i've stored into the array, it only reads and display the last data i've inputted.

CODE OUTPUT:

In what way could i possibly get all the data i've stored into the array and display it?

答:
I simply fixed my problem by using loop counter:

```<code>#include <iostream>

using namespace std;

struct Employee {

   string name;
   int age;
   float salary;

};

void displayData(Employee[], int);

int main() {

   Employee employee[3];
   int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);

   for(int i = 0; i < sizeOfEmployee; i++) {
       cout << "Enter name for employee " << i + 1 << ": ";
       getline(cin, employee[i].name);
       cout << "Enter age for employee " << i + 1 << ": ";
       cin >> employee[i].age;
       cout << "Enter salary for employee " << i + 1 << ": ";
       cin >> employee[i].salary;
       cin.ignore();
   }

   displayData(employee, sizeOfEmployee);

}

void displayData(Employee employee[], int sizeOfEmployee) {

   cout << "DISPLAYING INFORMATION" << endl;

   for(int i = 0; i < sizeOfEmployee; i++) {
       cout << "Name: " << employee[i].name << endl;
       cout << "Age: " << employee[i].age << endl;
       cout << "Salary: " << employee[i].salary << endl;
   }

}
</code>```

Thanks to all the people who helped me and provided me with answers. Very much appreciated as I'm still learning :))

Body:
Source Code:

#include <iostream>

using namespace std;

struct Employee {

   string name;
   int age;
   float salary;

};

void displayData(Employee);

int main() {

   Employee employee[3];
   int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);

   for(int i = 0; i < sizeOfEmployee; i++) {
       cout << "Enter name for employee " << i + 1 << ": ";
       cin >> employee->name;
       cout << "Enter age for employee " << i + 1 << ": ";
       cin >> employee->age;
       cout << "Enter salary for employee " << i + 1 << ": ";
       cin >> employee->salary;
}

   for(int i = 0; i < sizeOfEmployee; i++) {
       displayData(employee[i]);
}

}

void displayData(Employee employee) {

   cout << "DISPLAYING INFORMATION" << endl;
   cout << "Name: " << employee.name << endl;
   cout << "Age: " << employee.age << endl;
   cout << "Salary: " << employee.salary << endl;

}

My code doesn't display all the data i've stored into the array, it only reads and display the last data i've inputted.

CODE OUTPUT:

In what way could i possibly get all the data i've stored into the array and display it?

Body:
I simply fixed my problem by using loop counter:

#include <iostream>

using namespace std;

struct Employee {

   string name;
   int age;
   float salary;

};

void displayData(Employee[], int);

int main() {

   Employee employee[3];
   int sizeOfEmployee = sizeof(employee) / sizeof(employee[0]);

   for(int i = 0; i < sizeOfEmployee; i++) {
       cout << "Enter name for employee " << i + 1 << ": ";
       getline(cin, employee[i].name);
       cout << "Enter age for employee " << i + 1 << ": ";
       cin >> employee[i].age;
       cout << "Enter salary for employee " << i + 1 << ": ";
       cin >> employee[i].salary;
       cin.ignore();
   }

   displayData(employee, sizeOfEmployee);

}

void displayData(Employee employee[], int sizeOfEmployee) {

   cout << "DISPLAYING INFORMATION" << endl;

   for(int i = 0; i < sizeOfEmployee; i++) {
       cout << "Name: " << employee[i].name << endl;
       cout << "Age: " << employee[i].age << endl;
       cout << "Salary: " << employee[i].salary << endl;
   }

}

Thanks to all the people who helped me and provided me with answers. Very much appreciated as I'm still learning :))


问:
Blank page after running build on the react app and errors on the console
I am a beginner in React JS. I was deploying my React App that I created using create-react-app on netlify. The build was successful but on checking the link https://schotrix.netlify.app/, it was showing a blank page and errors on the console. So i decided to check again on my localhost by running npm run build I realized it's the same problem.

What could these errors mean and how can I solve them?
picture to the error on the console

react-dom.production.min.js:216
Error
at i (index.tsx:19:20)
at index.tsx:776:5
at react.production.min.js:19:66
at react.production.min.js:17:388
at S (react.production.min.js:16:230)
at C (react.production.min.js:17:355)
at Object.forEach (react.production.min.js:19:49)
at j (index.tsx:760:3)
at index.tsx:791:24
at react.production.min.js:19:66
su @ react-dom.production.min.js:216
n.callback @ react-dom.production.min.js:216
ho @ react-dom.production.min.js:131
yu @ react-dom.production.min.js:220
Ac @ react-dom.production.min.js:259
t.unstable_runWithPriority @ scheduler.production.min.js:18
qa @ react-dom.production.min.js:122
Nc @ react-dom.production.min.js:252
gc @ react-dom.production.min.js:243
vc @ react-dom.production.min.js:237
el @ react-dom.production.min.js:285
(anonymous) @ react-dom.production.min.js:289
jc @ react-dom.production.min.js:244
il @ react-dom.production.min.js:289
t.render @ react-dom.production.min.js:296
287 @ index.js:6
i @ (index):1
t @ (index):1
r @ (index):1
(anonymous) @ main.b32d759b.chunk.js:1
index.tsx:19
Uncaught Error
at i (index.tsx:19:20)
at index.tsx:776:5
at react.production.min.js:19:66
at react.production.min.js:17:388
at S (react.production.min.js:16:230)
at C (react.production.min.js:17:355)
at Object.forEach (react.production.min.js:19:49)
at j (index.tsx:760:3)
at index.tsx:791:24
at react.production.min.js:19:66

答:
Actually i had to run npm start inorder to find out what exactly the error is and for my case the error was

Error: [Users] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>```
</div>
</div>
</p>
<p>because i was accessing the component like this</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><Route path="/users" ><Users/></Route></code>```

instead of this

<Route path="/users" element={<Users/>}/>```

Body:
Actually i had to run npm start inorder to find out what exactly the error is and for my case the error was

Error: [Users] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment>

because i was accessing the component like this

<Route path="/users" ><Users/></Route>

instead of this

<Route path="/users" element={<Users/>}/>


问:
Lazy mode of recursive function
I'm going to find a solution to this problem:

Splitting given list to sublist with given sub-list length and skip length, for example:

groupEvery 3 1 [1..6] = [[1,2,3], [2,3,4], [3,4,5], [4,5,6]]
groupEvery 3 2 "abcdefghij" = [ "abc", "cde", "efg", "ghi", "ij"]
```
<p>The <code>groupEvery n p l</code> args details are:</p>
<ul>
<li>n is length of sub-list: Int</li>
<li>f is length of skip: Int</li>
<li>xs is input list: [a]</li>
</ul>
<p>Here is my solution:</p>
<pre class="lang-haskell prettyprint-override"><code>groupEvery :: Int -> Int -> [a] -> [[a]] -> [[a]]
groupEvery n p xs acc
    | length xs <= n = acc ++ [xs]
    | otherwise = groupEvery n p dropped (acc++[segment])
        where
            dropped = drop p xs
            segment = take n xs
</code>```

But this solution is not lazy, for example take 3 Lib2.groupEvery 3 1 [1..] [] never finished.
My question is about

Better solutions for the groupEvery function ?

How we can write recursive lazy function that accumulate some data ? In other words is there any structure for this kind of recursive functions that accumulate results and are lazy ?

答:
Your use of "accumulator" here is vague.

The useful nomenclature is "state passing and building up", "output list creation", "tail recursion", and "guarded recursion" otherwise known as "tail recursion modulo cons" in the strict setting.

Yes, we can create the output list gradually through guarded recursion while simultaneously arranging for passing and accumulating / building up the state from one invocation to the next:

```<code>makeList elt next state = go state
  where
  go state = elt state : go (next state)
  --- which is just
  -- go = map elt . iterate next
</code>```

("guarded" recursion, guarded by a lazy data constructor, here :).

Specifically, your example is

```<code>groupEvery n p  =  makeList (take n) (drop p)
</code>```

up to a termination condition:

```<code>> takeWhile (not . null) $ groupEvery 3 2 [1..20]
[[1,2,3],[3,4,5],[5,6,7],[7,8,9],[9,10,11],[11,12,13],
 [13,14,15],[15,16,17],[17,18,19],[19,20]]
</code>```

Title: Lazy mode of recursive function

Body:
I'm going to find a solution to this problem:

Splitting given list to sublist with given sub-list length and skip length, for example:

groupEvery 3 1 [1..6] = [[1,2,3], [2,3,4], [3,4,5], [4,5,6]]
groupEvery 3 2 "abcdefghij" = [ "abc", "cde", "efg", "ghi", "ij"]

The groupEvery n p l args details are:

n is length of sub-list: Int

f is length of skip: Int

xs is input list: [a]

Here is my solution:

groupEvery :: Int -> Int -> [a] -> [[a]] -> [[a]]
groupEvery n p xs acc
    | length xs <= n = acc ++ [xs]
    | otherwise = groupEvery n p dropped (acc++[segment])
        where
            dropped = drop p xs
            segment = take n xs

But this solution is not lazy, for example take 3 Lib2.groupEvery 3 1 [1..] [] never finished.
My question is about

Better solutions for the groupEvery function ?

How we can write recursive lazy function that accumulate some data ? In other words is there any structure for this kind of recursive functions that accumulate results and are lazy ?

Body:
Your use of "accumulator" here is vague.

The useful nomenclature is "state passing and building up", "output list creation", "tail recursion", and "guarded recursion" otherwise known as "tail recursion modulo cons" in the strict setting.

Yes, we can create the output list gradually through guarded recursion while simultaneously arranging for passing and accumulating / building up the state from one invocation to the next:

makeList elt next state = go state
  where
  go state = elt state : go (next state)
  --- which is just
  -- go = map elt . iterate next

("guarded" recursion, guarded by a lazy data constructor, here :).

Specifically, your example is

groupEvery n p  =  makeList (take n) (drop p)

up to a termination condition:

> takeWhile (not . null) $ groupEvery 3 2 [1..20]
[[1,2,3],[3,4,5],[5,6,7],[7,8,9],[9,10,11],[11,12,13],
 [13,14,15],[15,16,17],[17,18,19],[19,20]]


问:
Given a latitude, longitude and altitude - calculate pitch/yaw to face object from the ground at given latitude/longitude
I have two locations.

Object in sky: latitude, longitude, altitude

Object on the ground: latitude, longitude, compass heading

I would like to make something that will point my object on the ground to face the object in the sky (i.e move it clockwise/anticlockwise on a circular axis and then tilt it up and down)

I have looked at different astronomy libraries available which can provide the direction to face to see the moon and so on, but none seem to provide any option for a given location

Ideally I'd like to do this calculation in either NodeJS or PHP but can also work with Java.

答:
Python solution from

cRadiusOfEarth = 6371;
cFeetToKm = 0.0003048
cHomeLat1=-33.123
cHomeLon1=151.456

f1 = math.radians(cHomeLat1);
f2 = math.radians(lat2);
delta_f = math.radians(lat2-cHomeLat1);
delta_g = math.radians(lon2-cHomeLon1);
a = math.sin(delta_f/2) * math.sin(delta_f/2) + math.cos(f1) * math.cos(f2) * math.sin(delta_g/2) * math.sin(delta_g/2);
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1-a));
dist_km = cRadiusOfEarth * c;
brng_r=math.atan2(
math.sin(lon2-cHomeLon1) * math.cos(lat2)
, math.cos(cHomeLat1)*math.sin(lat2)-math.sin(cHomeLat1)*math.cos(lat2)*math.cos(lon2-cHomeLon1)
)

brng_d=(360.0 - math.degrees(brng_r))%360.0
azmth=math.degrees(math.atan(pFeet*cFeetToKm / dist_km))
```


问:
PHP 8.1: strftime() is deprecated
When upgrading to PHP 8.1, I got an error regarding "strftime".
How do I correct the code to correctly display the full month name in any language?</p>
```<code> $date = strftime("%e %B %Y", strtotime('2010-01-08'))
</code>```

答:
The strftime is obsolete and DateTime::format() provide a quick replacement and IntlDateFormatter::format() provied a more sophisticated slution.

this links will be help you:

https://github.com/modxcms/revolution/issues/15864

https://github.com/php/php-src/blob/1cf4fb739f7a4fa8404a4c0958f13d04eae519d4/UPGRADING#L379-L381

https://www.php.net/manual/en/datetime.format.php

Title: PHP 8.1: strftime() is deprecated

Body:
When upgrading to PHP 8.1, I got an error regarding "strftime".
How do I correct the code to correctly display the full month name in any language?

 $date = strftime("%e %B %Y", strtotime('2010-01-08'))


问:
Why are my GKAgent2D's position and velocity nan?
Using GameplayKit, I'm trying to make an enemy character pursue the player while avoiding obstacles in a SpriteKit game.

However, the agent in agentDidUpdate(_:) has a position and velocity of nan.

Here's what I'm doing now:

Configure the obstacles:

```<code>//node is defined here
let obstacle = GKCircleObstacle(radius: Float(node.size.width*0.5))
obstacle.position = vector_float2(x: Float(node.position.x), y: Float(node.position.y))
levelObstacles.append(obstacle)
</code>```

Configure a GKEntity (etc.) for the player SKSpriteNode, saving a reference to the component and agent for use in #3:

```<code>//node is defined here
let entity1 = GKEntity()
heroAgent = GKAgent2D()
heroComponent = GKSKNodeComponent(node: node)
heroAgent.delegate = self // <-- self is a GKAgentDelegate
node.entity = entity1
heroEntity = entity1
if let comp = heroComponent {
    entity1.addComponent(comp)
    entity1.addComponent(heroAgent)
}
</code>```

Configure a GKEntity (etc.) for the enemy SKSpriteNode, using the saved hero component and agent to set up the necessary behaviors:

```<code>//node is defined here
let entity = GKEntity()
let agent = GKAgent2D()
let avoid = GKGoal(toAvoid: levelObstacles, maxPredictionTime: 5.0)
let pursue = GKGoal(toInterceptAgent: heroAgent, maxPredictionTime: 5.0)
nodeComponent = GKSKNodeComponent(node: node)
agent.behavior = GKBehavior(goals: [avoid, pursue], andWeights: [100.0, 50.0])
agent.delegate = self // <-- self is a GKAgentDelegate
node.entity = entity
if let comp = nodeComponent {
    entity.addComponent(comp)
    entity.addComponent(agent)
}
nodeEntity = entity
</code>```

In the SKScene's update(_:) method, call the enemy entity's update(deltaTime:) method:

```<code>nodeEntity?.update(deltaTime: currentTime-lastFrameTime)
</code>```

Print the agent's position and velocity in agentDidUpdate(_:):

```<code>func agentDidUpdate(_ agent: GKAgent) {
   if let a = agent as? GKAgent2D {
      print("agent position: \(a.position), agent velocity: \(a.velocity)") //Prints a position and velocity of "-nan"
   }
}
</code>```

Question: Why are the agent's position and velocity nan inside agentDidUpdate(_:), and how do I solve the problem?

Update: The problem is apparently related to GKGoal(toInterceptAgent:maxPredictionTime:). If I use a different goal, like GKGoal(toFleeAgent:) for example, there are actual values available in agentDidUpdate(_:).

答:
I was able to get this working by setting the player agent's position to the actual SpriteKit node's position inside the SKScene's update(_:) method, like this:

```<code>heroAgent.position = vector_float2(x: Float(mainCharacter?.position.x ?? 0.0), y: Float(mainCharacter?.position.y ?? 0.0))
</code>```

I'm not really sure why that worked, but it did.

Body:
Using GameplayKit, I'm trying to make an enemy character pursue the player while avoiding obstacles in a SpriteKit game.

However, the agent in agentDidUpdate(_:) has a position and velocity of nan.

Here's what I'm doing now:

Configure the obstacles:

//node is defined here
let obstacle = GKCircleObstacle(radius: Float(node.size.width*0.5))
obstacle.position = vector_float2(x: Float(node.position.x), y: Float(node.position.y))
levelObstacles.append(obstacle)

Configure a GKEntity (etc.) for the player SKSpriteNode, saving a reference to the component and agent for use in #3:

//node is defined here
let entity1 = GKEntity()
heroAgent = GKAgent2D()
heroComponent = GKSKNodeComponent(node: node)
heroAgent.delegate = self // <-- self is a GKAgentDelegate
node.entity = entity1
heroEntity = entity1
if let comp = heroComponent {
    entity1.addComponent(comp)
    entity1.addComponent(heroAgent)
}

Configure a GKEntity (etc.) for the enemy SKSpriteNode, using the saved hero component and agent to set up the necessary behaviors:

//node is defined here
let entity = GKEntity()
let agent = GKAgent2D()
let avoid = GKGoal(toAvoid: levelObstacles, maxPredictionTime: 5.0)
let pursue = GKGoal(toInterceptAgent: heroAgent, maxPredictionTime: 5.0)
nodeComponent = GKSKNodeComponent(node: node)
agent.behavior = GKBehavior(goals: [avoid, pursue], andWeights: [100.0, 50.0])
agent.delegate = self // <-- self is a GKAgentDelegate
node.entity = entity
if let comp = nodeComponent {
    entity.addComponent(comp)
    entity.addComponent(agent)
}
nodeEntity = entity

In the SKScene's update(_:) method, call the enemy entity's update(deltaTime:) method:

nodeEntity?.update(deltaTime: currentTime-lastFrameTime)

Print the agent's position and velocity in agentDidUpdate(_:):

func agentDidUpdate(_ agent: GKAgent) {
   if let a = agent as? GKAgent2D {
      print("agent position: \(a.position), agent velocity: \(a.velocity)") //Prints a position and velocity of "-nan"
   }
}

Question: Why are the agent's position and velocity nan inside agentDidUpdate(_:), and how do I solve the problem?

Update: The problem is apparently related to GKGoal(toInterceptAgent:maxPredictionTime:). If I use a different goal, like GKGoal(toFleeAgent:) for example, there are actual values available in agentDidUpdate(_:).

Body:
I was able to get this working by setting the player agent's position to the actual SpriteKit node's position inside the SKScene's update(_:) method, like this:

heroAgent.position = vector_float2(x: Float(mainCharacter?.position.x ?? 0.0), y: Float(mainCharacter?.position.y ?? 0.0))

I'm not really sure why that worked, but it did.


问:
Distinguish between HTTP error code generated by Traefik itself or by service
We are using Traefik v2.4.7 on Docker Swarm provider. We are also using custom error middleware which routes the request to nginx server (error-pages@docker service). We have the following code in traefik.yml:

http:
  middlewares:
    error-pages:
      errors:
        status:
          - "400-599"
        service: error-pages@docker
        query: "/{status}.html"

entrypoints:
  web-secure:
    address: ":443"
    http:
      middlewares:
        - error-pages@file
```

Our application, which is deployed behind Traefik, has some IPs whitelisted with ipwhitelist.sourcerange=... label. If it is accessed from an IP which is not allowed, error-pages middleware routes the request to /403.html in nginx service. This is expected behavior.

However, we have some cases where our application purposely returns 403 HTTP status code and displays its own "forbidden" page with support contact form, debug information and other useful info. We don't want Traefik middleware to route the request to nginx.

Is it possible to distinguish between HTTP error codes generated by Traefik and services themselves? If the error code is generated by Traefik, then it should go through error-pages middleware. If the error code is generated by service, the page should be returned as-is, without going through middleware. How can we achieve this?

答:
Hmm I don't think that is possible (using the built in errorpages middleware) ...

The only solution I can think of is to have the client application send back a 200 (Status Code) to every request but show the 403 (Html) page.

Use a custom plugin (middleware) eg. https://github.com/pierre-verhaeghe/traefik-replace-response-code to change the status code eg return 493 from your application and change it to 403 before it goes to the client.

Both solutions don't look good to me as the application behavior needs to be changed ... but maybe its good enough for your needs.

Body:
We are using Traefik v2.4.7 on Docker Swarm provider. We are also using custom error middleware which routes the request to nginx server (error-pages@docker service). We have the following code in traefik.yml:

http:
  middlewares:
    error-pages:
      errors:
        status:
          - "400-599"
        service: error-pages@docker
        query: "/{status}.html"

entrypoints:
  web-secure:
    address: ":443"
    http:
      middlewares:
        - error-pages@file

Our application, which is deployed behind Traefik, has some IPs whitelisted with ipwhitelist.sourcerange=... label. If it is accessed from an IP which is not allowed, error-pages middleware routes the request to /403.html in nginx service. This is expected behavior.

However, we have some cases where our application purposely returns 403 HTTP status code and displays its own "forbidden" page with support contact form, debug information and other useful info. We don't want Traefik middleware to route the request to nginx.

Is it possible to distinguish between HTTP error codes generated by Traefik and services themselves? If the error code is generated by Traefik, then it should go through error-pages middleware. If the error code is generated by service, the page should be returned as-is, without going through middleware. How can we achieve this?


问:
How to assign Redis key names to Flask app users?
I have a Flask app which stores user sessions in Redis on localhost.

User sessions are managed by Flask-Session module:

```<code>import flask
import redis
import flask_session

app = flask.Flask(__name__)

app.secret_key = b'Test123'

app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_KEY_PREFIX'] = 'flask_session_'
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_REDIS'] = redis.from_url('redis://localhost:6379', password='Test123')

server_session = flask_session.Session(app)
</code>```

I'd like to know which Redis session key name belongs to which user or device.

For example I'd like to add client's IP addresses to Redis key names.

Is it possible?

When I try to get client's IP address and set it as a key prefix like this:

```<code>ip = flask.request.environ.get('REMOTE_ADDR')

app.config['SESSION_KEY_PREFIX'] = 'flask_session_' + ip
</code>```

I get this message in Apache error.log:

RuntimeError: Working outside of request context.

[Fri Feb 11 22:19:14.371919 2022] [wsgi:error] [pid 264638:tid 264787] [remote 1.2.3.4:35695] This typically means that you attempted to use functionality that needed

[Fri Feb 11 22:19:14.371930 2022] [wsgi:error] [pid 264638:tid 264787] [remote 1.2.3.4:35695] an active HTTP request.  Consult the documentation on testing for

[Fri Feb 11 22:19:14.371941 2022] [wsgi:error] [pid 264638:tid 264787] [remote 1.2.3.4:35695] information about how to avoid this problem.

答:
I've figured it out.

Obviously you can't run  flask.request.environ.get('REMOTE_ADDR') before the request, even with @app.before_request.

So, to identify sessions (Redis key names) and assign them to app users (so I know which session/key belongs to which user) my app now writes Flask-Session SID along with the logged in username to the Apache error.log:

```<code>app.logger.warning('User ' + login + ' logged in. Flask-Session SID: ' + str(flask.session.sid) + '. Flask-Login session ID: ' + str(flask.session['_id']) + '.')
</code>```

Flask-Session SID is the Redis key name.

Another way would be storing the username or IP address in flask.session after the request (after the users login), SCAN-ning the Redis KEYS for values (usernames or IP address) and RENAME-ing the keys by pattern.

Body:
I have a Flask app which stores user sessions in Redis on localhost.

User sessions are managed by Flask-Session module:

import flask
import redis
import flask_session

app = flask.Flask(__name__)

app.secret_key = b'Test123'

app.config['SESSION_TYPE'] = 'redis'
app.config['SESSION_KEY_PREFIX'] = 'flask_session_'
app.config['SESSION_PERMANENT'] = False
app.config['SESSION_USE_SIGNER'] = True
app.config['SESSION_REDIS'] = redis.from_url('redis://localhost:6379', password='Test123')

server_session = flask_session.Session(app)

I'd like to know which Redis session key name belongs to which user or device.

For example I'd like to add client's IP addresses to Redis key names.

Is it possible?

When I try to get client's IP address and set it as a key prefix like this:

ip = flask.request.environ.get('REMOTE_ADDR')

app.config['SESSION_KEY_PREFIX'] = 'flask_session_' + ip

I get this message in Apache error.log:

RuntimeError: Working outside of request context.

[Fri Feb 11 22:19:14.371919 2022] [wsgi:error] [pid 264638:tid 264787] [remote 1.2.3.4:35695] This typically means that you attempted to use functionality that needed

[Fri Feb 11 22:19:14.371930 2022] [wsgi:error] [pid 264638:tid 264787] [remote 1.2.3.4:35695] an active HTTP request.  Consult the documentation on testing for

[Fri Feb 11 22:19:14.371941 2022] [wsgi:error] [pid 264638:tid 264787] [remote 1.2.3.4:35695] information about how to avoid this problem.

Body:
I've figured it out.

Obviously you can't run  flask.request.environ.get('REMOTE_ADDR') before the request, even with @app.before_request.

So, to identify sessions (Redis key names) and assign them to app users (so I know which session/key belongs to which user) my app now writes Flask-Session SID along with the logged in username to the Apache error.log:

app.logger.warning('User ' + login + ' logged in. Flask-Session SID: ' + str(flask.session.sid) + '. Flask-Login session ID: ' + str(flask.session['_id']) + '.')

Flask-Session SID is the Redis key name.

Another way would be storing the username or IP address in flask.session after the request (after the users login), SCAN-ning the Redis KEYS for values (usernames or IP address) and RENAME-ing the keys by pattern.


问:
Is faster code also more power efficient?
Assume I have a CPU running at a constant rate, pulling an equal amount of energy per instruction. I also have two functionally identical programs, which result in the same output, except one has been optimized to execute only 100 instructions, while the other program executes 200 instructions. Is the 100 instruction program necessarily faster than the 200 instruction program? Does a program with fewer instructions draw less power than a program with more instructions?</p>

答: I found a paper from 2017 comparing the energy usage, speed, and memory consumption of various programming languages. There is an obvious positive correlation between faster languages also using less energy.


问:
How to parse Json with 2 different keys?
I'm trying to parse this API

that is basically an order book with "asks" and "bids".
How can I parse them splitting the asks from the bids?
for example the api start with asks property
So if Json is  {"asks":[["0.00001555","3264400"],["0.00001556","3662200"],["0.00001573","3264400"]

I'm expecting an output like:

[asks]

Price- Quantity

0.00001555 - 3264400

0.00001556 - 3662200

0.00001573 - 3264400

ecc

and After there is "bids":[["0.00001325","300"],["0.00001313","100"],["0.00001312","1051400"],["0.00001311","1300000"],["0.0000131","9336700"]
so I'm expecting

[bids]

Price- Quantity

0.00001325- 300

0.00001313 - 100

0.00001312 - 1051400

0.00001311 - 1300000

0.0000131 - 9336700

ecc

I know how to parse each single value with the code:

```<code> Dim streamData As Stream = Nothing
      Using http As HttpClient = New HttpClient
          Dim url As String = "https://api.hotbit.io/api/v1/order.depth?market=KIBA/USDT&limit=100&interval=1e-8"

          Dim t As Task(Of Stream) = http.GetStreamAsync(url)
          streamData = t.Result
      End Using

      Dim jsonResponse As JsonNode = JsonNode.Parse(streamData)
      Dim result As JsonObject = jsonResponse("result").AsObject

  For Each kvp In result.AsEnumerable
      c &= kvp.Value("key?!?!?!?").ToString & ", "
  Next
</code>```

but in this case there is no Key that I can "parse" and also the values are in the format ["Price", "Quantity"]
and also I don't know how to split the results between asks and bids maybe splitting them in two different richtextboxes multiline..
Any help would be appreciated
Thanks

答:
Use JsonUtils which will create the classes for you and then you can copy these into your project.

In this instance it will create:

```<code>Public Class Result
    Public Property asks As String()()
    Public Property bids As String()()
    Public Property seqNum As Integer
    Public Property prevSeqNum As Integer
    Public Property lastTs As Double
End Class

Public Class Root
    Public Property [error] As Object
    Public Property result As Result
    Public Property id As Integer
End Class
</code>```

Please note having error as a property name will throw a compiler error and so you'll need to wrap it in square brackets like [error].

You can also simplify your code considerably:

```<code>Private Async Sub MyMethod()
    Dim root As Root = Await GetJsonFromApi()

    For each ask In root.result.asks
        Console.WriteLine(ask(0))
    Next
End Sub

Private Async Function GetJsonFromApi() As Task(Of Root)
    Using http As New HttpClient()
        Dim url As String = "https://api.hotbit.io/api/v1/order.depth?market=KIBA/USDT&limit=100&interval=1e-8"
        Return Await http.GetFromJsonAsync(Of Root)(url)
    End Using
End Function
</code>```

Or if you prefer, and want to handle exceptions, something like:

```<code>Private Async Sub MyMethod()
    Dim root As Root = Await GetJsonFromApi()

    For each ask In root.result.asks

    Next
End Sub

Private Async Function GetJsonFromApi() As Task(Of Root)
    Using http As New HttpClient()
        Dim url As String = "https://api.hotbit.io/api/v1/order.depth?market=KIBA/USDT&limit=100&interval=1e-8"
        Dim response As HttpResponseMessage = Await http.GetAsync(url)

        If response.IsSuccessStatusCode
            Return Await response.Content.ReadFromJsonAsync(Of Root)
        End If
    End Using

    Return New Result
End Function
</code>```

As a side note, I'm awaiting the response as you can see with the keyword Await. I prefer to do this rather than call .Result on the end.

Lastly, I would consider making the url variable a constant:

```<code>Private Const URI As String = "https://api.hotbit.io/api/v1/order.depth?market=KIBA/USDT&limit=100&interval=1e-8"

...
Dim response As HttpResponseMessage = Await http.GetAsync(URI)
</code>```

There is also Newtonsoft.Json which can be used to deserialise JSON to a class:

```<code>Private Async Function GetJsonFromApi() As Task(Of Root)
    Using http As New HttpClient(),
          response As HttpResponseMessage = await http.GetAsync(URI)
            Return JsonConvert.DeserializeObject(Of Root)(Await response.Content.ReadAsStringAsync())
    End Using
End Function
</code>```

Note you will have to add this as a Nuget package to your application. Also I've assumed the URI is now a constant and I've nested the Using statements.

To output these you will have to use String.Join and to ensure the UI doesn't freeze you can call Control.BeginInvoke:

```<code>Private Sub OutputAsks(asks As String()())
    Dim contents As New StringBuilder

    contents.AppendLine("[asks]")
    contents.AppendLine("Price - Quantity")

    For Each ask In asks
        contents.AppendLine(String.Join(" - ", ask))
    Next

    RichTextBox1.BeginInvoke(Sub()
                                 RichTextBox1.Text = contents.ToString()
                             End Sub)
End Sub

Private Sub OutputBids(bids As String()())
    Dim contents As New StringBuilder

    contents.AppendLine("[bids]")
    contents.AppendLine("Price - Quantity")

    For Each bid In bids
        contents.AppendLine(String.Join(" - ", bid))
    Next

    RichTextBox2.BeginInvoke(Sub()
                                 RichTextBox2.Text = contents.ToString()
                             End Sub)
End Sub
</code>```

Note, as part of the Control.BeginInvoke you don't have to strictly call Control.EndInvoke as noted in the docs:

You can call EndInvoke to retrieve the return value from the delegate, if neccesary, but this is not required. EndInvoke will block until the return value can be retrieved.

The full solution - taking into account your Button, Timer, and RichTextbox controls - would look something like :

```<code>Private Const URI As String = "https://api.hotbit.io/api/v1/order.depth?market=KIBA/USDT&limit=10&interval=1e-8"

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    UpdateContents()
End Sub

Private Async Sub UpdateContents()
    Dim jsonContents As String = Await GetJsonFromApi()
    Dim root As Root = DeserialiseJsonToRoot(jsonContents)

    OutputAsks(root.result.asks)
    OutputBids(root.result.bids)
End Sub

Private Async Function GetJsonFromApi() As Task(Of String)
    Using http As New HttpClient(),
        response As HttpResponseMessage = Await http.GetAsync(URI)
        Return Await response.Content.ReadAsStringAsync()
    End Using
End Function

Private Function DeserialiseJsonToRoot(json As String) As Root
    Return JsonConvert.DeserializeObject(Of Root)(json)
End Function

Private Sub OutputAsks(asks As String()())
    Dim contents As New StringBuilder

    contents.AppendLine("[asks]")
    contents.AppendLine("Price - Quantity")

    For Each ask In asks
        contents.AppendLine(String.Join(" - ", ask))
    Next

    RichTextBox1.BeginInvoke(Sub()
                                 RichTextBox1.Text = contents.ToString()
                             End Sub)
End Sub

Private Sub OutputBids(bids As String()())
    Dim contents As New StringBuilder

    contents.AppendLine("[bids]")
    contents.AppendLine("Price - Quantity")

    For Each bid In bids
        contents.AppendLine(String.Join(" - ", bid))
    Next

    RichTextBox2.BeginInvoke(Sub()
                                 RichTextBox2.Text = contents.ToString()
                             End Sub)
End Sub
</code>```

Body:
I'm trying to parse this API

that is basically an order book with "asks" and "bids".
How can I parse them splitting the asks from the bids?
for example the api start with asks property
So if Json is  {"asks":[["0.00001555","3264400"],["0.00001556","3662200"],["0.00001573","3264400"]

I'm expecting an output like:

[asks]

Price- Quantity

0.00001555 - 3264400

0.00001556 - 3662200

0.00001573 - 3264400

ecc

and After there is "bids":[["0.00001325","300"],["0.00001313","100"],["0.00001312","1051400"],["0.00001311","1300000"],["0.0000131","9336700"]
so I'm expecting

[bids]

Price- Quantity

0.00001325- 300

0.00001313 - 100

0.00001312 - 1051400

0.00001311 - 1300000

0.0000131 - 9336700

ecc

I know how to parse each single value with the code:

 Dim streamData As Stream = Nothing
      Using http As HttpClient = New HttpClient
          Dim url As String = "https://api.hotbit.io/api/v1/order.depth?market=KIBA/USDT&limit=100&interval=1e-8"

          Dim t As Task(Of Stream) = http.GetStreamAsync(url)
          streamData = t.Result
      End Using

      Dim jsonResponse As JsonNode = JsonNode.Parse(streamData)
      Dim result As JsonObject = jsonResponse("result").AsObject

  For Each kvp In result.AsEnumerable
      c &= kvp.Value("key?!?!?!?").ToString & ", "
  Next

but in this case there is no Key that I can "parse" and also the values are in the format ["Price", "Quantity"]
and also I don't know how to split the results between asks and bids maybe splitting them in two different richtextboxes multiline..
Any help would be appreciated
Thanks

Body:
Use JsonUtils which will create the classes for you and then you can copy these into your project.

In this instance it will create:

Public Class Result
    Public Property asks As String()()
    Public Property bids As String()()
    Public Property seqNum As Integer
    Public Property prevSeqNum As Integer
    Public Property lastTs As Double
End Class

Public Class Root
    Public Property [error] As Object
    Public Property result As Result
    Public Property id As Integer
End Class

Please note having error as a property name will throw a compiler error and so you'll need to wrap it in square brackets like [error].

You can also simplify your code considerably:

Private Async Sub MyMethod()
    Dim root As Root = Await GetJsonFromApi()

    For each ask In root.result.asks
        Console.WriteLine(ask(0))
    Next
End Sub

Private Async Function GetJsonFromApi() As Task(Of Root)
    Using http As New HttpClient()
        Dim url As String = "https://api.hotbit.io/api/v1/order.depth?market=KIBA/USDT&limit=100&interval=1e-8"
        Return Await http.GetFromJsonAsync(Of Root)(url)
    End Using
End Function

Or if you prefer, and want to handle exceptions, something like:

Private Async Sub MyMethod()
    Dim root As Root = Await GetJsonFromApi()

    For each ask In root.result.asks

    Next
End Sub

Private Async Function GetJsonFromApi() As Task(Of Root)
    Using http As New HttpClient()
        Dim url As String = "https://api.hotbit.io/api/v1/order.depth?market=KIBA/USDT&limit=100&interval=1e-8"
        Dim response As HttpResponseMessage = Await http.GetAsync(url)

        If response.IsSuccessStatusCode
            Return Await response.Content.ReadFromJsonAsync(Of Root)
        End If
    End Using

    Return New Result
End Function

As a side note, I'm awaiting the response as you can see with the keyword Await. I prefer to do this rather than call .Result on the end.

Lastly, I would consider making the url variable a constant:

Private Const URI As String = "https://api.hotbit.io/api/v1/order.depth?market=KIBA/USDT&limit=100&interval=1e-8"

...
Dim response As HttpResponseMessage = Await http.GetAsync(URI)

There is also Newtonsoft.Json which can be used to deserialise JSON to a class:

Private Async Function GetJsonFromApi() As Task(Of Root)
    Using http As New HttpClient(),
          response As HttpResponseMessage = await http.GetAsync(URI)
            Return JsonConvert.DeserializeObject(Of Root)(Await response.Content.ReadAsStringAsync())
    End Using
End Function

Note you will have to add this as a Nuget package to your application. Also I've assumed the URI is now a constant and I've nested the Using statements.

To output these you will have to use String.Join and to ensure the UI doesn't freeze you can call Control.BeginInvoke:

Private Sub OutputAsks(asks As String()())
    Dim contents As New StringBuilder

    contents.AppendLine("[asks]")
    contents.AppendLine("Price - Quantity")

    For Each ask In asks
        contents.AppendLine(String.Join(" - ", ask))
    Next

    RichTextBox1.BeginInvoke(Sub()
                                 RichTextBox1.Text = contents.ToString()
                             End Sub)
End Sub

Private Sub OutputBids(bids As String()())
    Dim contents As New StringBuilder

    contents.AppendLine("[bids]")
    contents.AppendLine("Price - Quantity")

    For Each bid In bids
        contents.AppendLine(String.Join(" - ", bid))
    Next

    RichTextBox2.BeginInvoke(Sub()
                                 RichTextBox2.Text = contents.ToString()
                             End Sub)
End Sub

Note, as part of the Control.BeginInvoke you don't have to strictly call Control.EndInvoke as noted in the docs:

You can call EndInvoke to retrieve the return value from the delegate, if neccesary, but this is not required. EndInvoke will block until the return value can be retrieved.

The full solution - taking into account your Button, Timer, and RichTextbox controls - would look something like :

Private Const URI As String = "https://api.hotbit.io/api/v1/order.depth?market=KIBA/USDT&limit=10&interval=1e-8"

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Timer1.Start()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    UpdateContents()
End Sub

Private Async Sub UpdateContents()
    Dim jsonContents As String = Await GetJsonFromApi()
    Dim root As Root = DeserialiseJsonToRoot(jsonContents)

    OutputAsks(root.result.asks)
    OutputBids(root.result.bids)
End Sub

Private Async Function GetJsonFromApi() As Task(Of String)
    Using http As New HttpClient(),
        response As HttpResponseMessage = Await http.GetAsync(URI)
        Return Await response.Content.ReadAsStringAsync()
    End Using
End Function

Private Function DeserialiseJsonToRoot(json As String) As Root
    Return JsonConvert.DeserializeObject(Of Root)(json)
End Function

Private Sub OutputAsks(asks As String()())
    Dim contents As New StringBuilder

    contents.AppendLine("[asks]")
    contents.AppendLine("Price - Quantity")

    For Each ask In asks
        contents.AppendLine(String.Join(" - ", ask))
    Next

    RichTextBox1.BeginInvoke(Sub()
                                 RichTextBox1.Text = contents.ToString()
                             End Sub)
End Sub

Private Sub OutputBids(bids As String()())
    Dim contents As New StringBuilder

    contents.AppendLine("[bids]")
    contents.AppendLine("Price - Quantity")

    For Each bid In bids
        contents.AppendLine(String.Join(" - ", bid))
    Next

    RichTextBox2.BeginInvoke(Sub()
                                 RichTextBox2.Text = contents.ToString()
                             End Sub)
End Sub


问:
Razor Pay integration with android (java)error: "android:exported needs to be explicitly specified for <activity>"
I am trying to integrate payment method using "Razor Pay" payment gateway in android(Java), but each time error persists. The app itself, has nothing in it, I am just running the app after adding the razor pay dependency. I have tried several similar questions but they all say that explicitly add the 'android:exported="true" but then my app is running fine when I remove the  "implementation 'com.razorpay:checkout:1.6.12'" from the build.gradle(app) file.  '

I followed the steps exactly from the razor pay documentation, this is the LINK

This the error shown in the "Merged Manifest":

"Merging Errors:

Error: android:exported needs to be explicitly specified for . Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details. My_Application_razor_pay.app main manifest (this file)"

This the "AndroidManifest.xml" file:

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.MyApplicationRazorPay">

    <activity
        android:name=".MainActivity"
        android:exported="true"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

Any help would be great, thank you for your time.

答:
Upgrade to implementation 'com.razorpay:checkout:1.6.17'

They have fix this problem:

Body:
I am trying to integrate payment method using "Razor Pay" payment gateway in android(Java), but each time error persists. The app itself, has nothing in it, I am just running the app after adding the razor pay dependency. I have tried several similar questions but they all say that explicitly add the 'android:exported="true" but then my app is running fine when I remove the  "implementation 'com.razorpay:checkout:1.6.12'" from the build.gradle(app) file.  '

I followed the steps exactly from the razor pay documentation, this is the LINK

This the error shown in the "Merged Manifest":

"Merging Errors:

Error: android:exported needs to be explicitly specified for . Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. See https://developer.android.com/guide/topics/manifest/activity-element#exported for details. My_Application_razor_pay.app main manifest (this file)"

This the "AndroidManifest.xml" file:

<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.MyApplicationRazorPay">

    <activity
        android:name=".MainActivity"
        android:exported="true"
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
        >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Any help would be great, thank you for your time.