问:
Visual studio 2022 not showing any project after upgrade to windows 11

VS 2022 and VS 2019 both do not show any project (after "add new" > project ) added even when the files (including csproj file) are present in the file system . I tried following

restarting system

deleting temp files

different project types


来源: stackexchange

问:
NXOpen, How to get first and last point3d of a dimension?
I'm trying to get the first and second point of a given dimension in NX draft.
Actually I tried this code:

```<code>var firstPoint3D = dimension.GetFirstAssociativity().FirstDefinitionPoint;
var SecondPoint3D = dimension.GetSecondAssociativity().FirstDefinitionPoint;
</code>```

but the result always is 0,0,0 for both.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to get the first and second point of a given dimension in NX draft.
Actually I tried this code:

var firstPoint3D = dimension.GetFirstAssociativity().FirstDefinitionPoint;
var SecondPoint3D = dimension.GetSecondAssociativity().FirstDefinitionPoint;

but the result always is 0,0,0 for both.


问:
How selenium closes browser pop-ups?
After I set up Google Forward Email, a browser pop-up window appeared, and I couldn't use self.driver.switch_to.alert to identify this pop-up window and close it.
This pop-up window does not belong to another window, how do I close it with selenium?

```<code>self.driver.switch_to.alert   //can't
all_windows = self.driver.window_handles   //can't

</code>```

I expect to close this pop-up

enter image description here

Title: How selenium closes browser pop-ups?

Body:
After I set up Google Forward Email, a browser pop-up window appeared, and I couldn't use self.driver.switch_to.alert to identify this pop-up window and close it.
This pop-up window does not belong to another window, how do I close it with selenium?

self.driver.switch_to.alert   //can't
all_windows = self.driver.window_handles   //can't

I expect to close this pop-up

enter image description here


问:
CSS grid of square div elements that fills width but not height
My goal is to create a grid of square "pixels" (div elements) that automatically scales the pixels to match the width of the page (up to max-width: 800px).

I want to implement this using CSS in a way that is "agnostic" to the number of rows and columns in the grid. This rules out using CSS display: grid, for example.

Here is my attempt:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pixel grid</title>
    <style>
        #container {
            max-width: 800px;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            gap: 8px;
        }

        .pixel-row {
            display: flex;
            gap: 8px;
            justify-content: space-between;
        }

        .pixel {
            flex: 1;
            border: 1px solid gray;
        }
    </style>
</head>

<body>
    <div id="container"></div>

    <!-- Script to generate row and column elements-->
    <script>
        // These numbers could change
        const rows = 10;
        const columns = 14;

        for (let i = 0; i < rows; i++) {
            newRow = document.createElement("div");
            newRow.classList.add("pixel-row");
            for (let j = 0; j < columns; j++) {
                newPixel = document.createElement("div");
                newPixel.classList.add("pixel");
                newRow.appendChild(newPixel);
            }
            document.getElementById("container").appendChild(newRow);
        }
    </script>
</body>
</html>
</code>```

As you can see in the following screenshot, this achieves the desired distribution of columns. But I cannot figure out how to make the height of the pixel divs match their width.

How do I style the .pixels and .pixel-rows so that the pixels have height matching their width?

Disclaimers

I have seen various tutorials online for making these kinds of equally spaced pixel grids, but all of them were one step away from my specific problem, e.g. because they used a static number of rows/columns (meaning they could use display: grid or display: flexbox with flex-wrap), or used a static pixel size (.pixel { width: 10px; height: 10px; })

For example, my question is distinct from this one because I only want the width of the grid to fit in the browser. If there are many rows, then the user should have to scroll vertically to see them.

And my question is distinct from this one because that solution depends on there being exactly two columns.

Body:
My goal is to create a grid of square "pixels" (div elements) that automatically scales the pixels to match the width of the page (up to max-width: 800px).

I want to implement this using CSS in a way that is "agnostic" to the number of rows and columns in the grid. This rules out using CSS display: grid, for example.

Here is my attempt:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Pixel grid</title>

As you can see in the following screenshot, this achieves the desired distribution of columns. But I cannot figure out how to make the height of the pixel divs match their width.

How do I style the .pixels and .pixel-rows so that the pixels have height matching their width?

Disclaimers

I have seen various tutorials online for making these kinds of equally spaced pixel grids, but all of them were one step away from my specific problem, e.g. because they used a static number of rows/columns (meaning they could use display: grid or display: flexbox with flex-wrap), or used a static pixel size (.pixel { width: 10px; height: 10px; })

For example, my question is distinct from this one because I only want the width of the grid to fit in the browser. If there are many rows, then the user should have to scroll vertically to see them.

And my question is distinct from this one because that solution depends on there being exactly two columns.


问:
Spring or Hibernate reutilizes the result of a previous consult
I have a problem with Spring or Hibernate.

Lets say i have a class call Dad with a list of Child.

```<code>public class Dad {
    private Long id;

    @OneToMany(mappedBy="dad", cascade = CascadeType.ALL)
    @Where(clause = "exclude_date is null")
    private List<Child> childs
}

public class Child{
    private Long id;

    @ManyToOne
    @JoinColumn(name = "dad_id")
    private Dad dad;

    private Calendar excludeDate;

}

controller:

  @PutMapping
  @Transactional
  public ResponseEntity<JSONObject> update(@RequestBody Dad dad){

try{
   service.saveOrUpdate(dad);
}catch (Exception e){
   return sucess;
}

try {
   D newDto = service.findById(dad.getId());
   return sucess;
} catch (Exception e) {
   return error;
}
  }
</code>```

In my controller i have a PUT method that a when i receive a object Dad whith a child with excludeDate set i updated the objects. But because of my @Where condition the return of dad should be without the excluded childs. But is not working.

When i debug the code i find out that Spring or Hibernate identify the list of childs on the save as @123 and when i do the findById i get the same list @123 so probably the list is not being reloaded from the database.

Body:
I have a problem with Spring or Hibernate.

Lets say i have a class call Dad with a list of Child.

public class Dad {
    private Long id;

    @OneToMany(mappedBy="dad", cascade = CascadeType.ALL)
    @Where(clause = "exclude_date is null")
    private List<Child> childs
}

public class Child{
    private Long id;

    @ManyToOne
    @JoinColumn(name = "dad_id")
    private Dad dad;

    private Calendar excludeDate;

}

controller:

  @PutMapping
  @Transactional
  public ResponseEntity<JSONObject> update(@RequestBody Dad dad){

try{
   service.saveOrUpdate(dad);
}catch (Exception e){
   return sucess;
}

try {
   D newDto = service.findById(dad.getId());
   return sucess;
} catch (Exception e) {
   return error;
}
  }

In my controller i have a PUT method that a when i receive a object Dad whith a child with excludeDate set i updated the objects. But because of my @Where condition the return of dad should be without the excluded childs. But is not working.

When i debug the code i find out that Spring or Hibernate identify the list of childs on the save as @123 and when i do the findById i get the same list @123 so probably the list is not being reloaded from the database.


问:
How to show arrows using input type="number" in Vue 3?
When I try to add input type="number" in my Vue 3 project, arrows doesn't show up like this:

Does anyone ever had this problem?

I tried to replicate what I'm doing on CodeSandbox in order to show here because I thought I was missing something in my code, but on CodeSandbox it works just normally. This happens in all my Vue projects.

I can solve this by making my own arrows, but I was just wondering why this is not working.

Edit

I'm also not able to edit the arrows. I was trying to maybe force them to appear but I couldn't do it

But maybe that's a hint, idk


问:
How to position and label objects on a map created with /map
Currently, while using cartographer to generate a map, yolact can be used for object recognition to obtain the point cloud location and class name of the object from the camera.
My goal is to navigate to the front of a given object using a map with the object's location and class name

My thought is that it could be done with a method like semantic map.
But I am not familiar with semantic map.
Could you please elaborate on this?
Also, are there any other simple methods?
At this stage, I just need to be able to create a position diagram that shows the location of the object and the class name.
Could someone please tell me what it is?


问:
Debugger goes to return statement first
I experience a strange behavior in X64 (debug mode) application during debugging with functions returning std::string, std::stack, std::vector:

```<code>std::stack<std::string> fooNoOk()
{
    std::stack<std::string> s;
    int r = 0;
    return s;
}

std::vector<int> barNook()
{
    std::vector<int> s;
    int r = 0;
    return s;
}

std::string bar2NoOk()
{
    std::string s;
    int r = 0;
    return s;
}

int foOk()
{
    int s{};
    int r = 0;
    return s;
}

int main()
{
    fooNoOk();
    barNook();
    bar2NoOk();
    foOk();
}
</code>```

for fooNoOk, barNook and bar2NoOk debugger as it enters function first jumps to the corresponding return statement, then goes through function and again to the return statement.
Here's disassembly listing of the application where it is clear that return statement is included twice (for example for fooNoOk function):

```<code>std::stack<std::string> fooNoOk()
{
00007FF63B544D30  mov         qword ptr [rsp+8],rcx
00007FF63B544D35  push        rbp
00007FF63B544D36  push        rdi
00007FF63B544D37  sub         rsp,188h
00007FF63B544D3E  lea         rbp,[rsp+20h]
00007FF63B544D43  lea         rdi,[rsp+20h]
00007FF63B544D48  mov         ecx,2Ah
00007FF63B544D4D  mov         eax,0CCCCCCCCh
00007FF63B544D52  rep stos    dword ptr [rdi]
00007FF63B544D54  mov         rcx,qword ptr [rsp+1A8h]
00007FF63B544D5C  mov         dword ptr [rbp+144h],0
00007FF63B544D66  lea         rcx,[__F9076511_TestReturn@cpp (07FF63B55906Ah)]
00007FF63B544D6D  call        __CheckForDebuggerJustMyCode (07FF63B54161Dh)
    std::stack<std::string> s;
00007FF63B544D72  mov         edx,28h
00007FF63B544D77  mov         rcx,qword ptr [rbp+180h]
00007FF63B544D7E  call        std::stack<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::deque<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > > >::__autoclassinit2 (07FF63B541280h)
00007FF63B544D83  mov         rcx,qword ptr [rbp+180h]
00007FF63B544D8A  call        std::stack<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::deque<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > > >::stack<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::deque<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > > > (07FF63B541532h)
00007FF63B544D8F  mov         qword ptr [rbp+158h],rax
    return s;
00007FF63B544D96  mov         eax,dword ptr [rbp+144h]
00007FF63B544D9C  or          eax,1
00007FF63B544D9F  mov         dword ptr [rbp+144h],eax
    int r = 0;
00007FF63B544DA5  mov         dword ptr [r],0
    return s;
00007FF63B544DAC  mov         rax,qword ptr [rbp+180h]
}
</code>```

the same is for barNoOk and bar2NoOk.
for foOk everything is Ok:

```<code>int foOk()
{
00007FF63B545500  push        rbp
00007FF63B545502  push        rdi
00007FF63B545503  sub         rsp,128h
00007FF63B54550A  lea         rbp,[rsp+20h]
00007FF63B54550F  lea         rcx,[__F9076511_TestReturn@cpp (07FF63B55906Ah)]
00007FF63B545516  call        __CheckForDebuggerJustMyCode (07FF63B54161Dh)
    int s{};
00007FF63B54551B  mov         dword ptr [s],0
    int r = 0;
00007FF63B545522  mov         dword ptr [r],0
    return s;
00007FF63B545529  mov         eax,dword ptr [s]
}
</code>```

godbolt.org

Title: Debugger goes to return statement first

Body:
I experience a strange behavior in X64 (debug mode) application during debugging with functions returning std::string, std::stack, std::vector:

std::stack<std::string> fooNoOk()
{
    std::stack<std::string> s;
    int r = 0;
    return s;
}

std::vector<int> barNook()
{
    std::vector<int> s;
    int r = 0;
    return s;
}

std::string bar2NoOk()
{
    std::string s;
    int r = 0;
    return s;
}

int foOk()
{
    int s{};
    int r = 0;
    return s;
}

int main()
{
    fooNoOk();
    barNook();
    bar2NoOk();
    foOk();
}

for fooNoOk, barNook and bar2NoOk debugger as it enters function first jumps to the corresponding return statement, then goes through function and again to the return statement.
Here's disassembly listing of the application where it is clear that return statement is included twice (for example for fooNoOk function):

std::stack<std::string> fooNoOk()
{
00007FF63B544D30  mov         qword ptr [rsp+8],rcx
00007FF63B544D35  push        rbp
00007FF63B544D36  push        rdi
00007FF63B544D37  sub         rsp,188h
00007FF63B544D3E  lea         rbp,[rsp+20h]
00007FF63B544D43  lea         rdi,[rsp+20h]
00007FF63B544D48  mov         ecx,2Ah
00007FF63B544D4D  mov         eax,0CCCCCCCCh
00007FF63B544D52  rep stos    dword ptr [rdi]
00007FF63B544D54  mov         rcx,qword ptr [rsp+1A8h]
00007FF63B544D5C  mov         dword ptr [rbp+144h],0
00007FF63B544D66  lea         rcx,[__F9076511_TestReturn@cpp (07FF63B55906Ah)]
00007FF63B544D6D  call        __CheckForDebuggerJustMyCode (07FF63B54161Dh)
    std::stack<std::string> s;
00007FF63B544D72  mov         edx,28h
00007FF63B544D77  mov         rcx,qword ptr [rbp+180h]
00007FF63B544D7E  call        std::stack<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::deque<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > > >::__autoclassinit2 (07FF63B541280h)
00007FF63B544D83  mov         rcx,qword ptr [rbp+180h]
00007FF63B544D8A  call        std::stack<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::deque<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > > >::stack<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::deque<std::basic_string<char,std::char_traits<char>,std::allocator<char> >,std::allocator<std::basic_string<char,std::char_traits<char>,std::allocator<char> > > > > (07FF63B541532h)
00007FF63B544D8F  mov         qword ptr [rbp+158h],rax
    return s;
00007FF63B544D96  mov         eax,dword ptr [rbp+144h]
00007FF63B544D9C  or          eax,1
00007FF63B544D9F  mov         dword ptr [rbp+144h],eax
    int r = 0;
00007FF63B544DA5  mov         dword ptr [r],0
    return s;
00007FF63B544DAC  mov         rax,qword ptr [rbp+180h]
}

the same is for barNoOk and bar2NoOk.
for foOk everything is Ok:

int foOk()
{
00007FF63B545500  push        rbp
00007FF63B545502  push        rdi
00007FF63B545503  sub         rsp,128h
00007FF63B54550A  lea         rbp,[rsp+20h]
00007FF63B54550F  lea         rcx,[__F9076511_TestReturn@cpp (07FF63B55906Ah)]
00007FF63B545516  call        __CheckForDebuggerJustMyCode (07FF63B54161Dh)
    int s{};
00007FF63B54551B  mov         dword ptr [s],0
    int r = 0;
00007FF63B545522  mov         dword ptr [r],0
    return s;
00007FF63B545529  mov         eax,dword ptr [s]
}

godbolt.org


问:
Python: sum dataframe rows with same datetime year
I have a dataframe with two datetime columns and a third column with a numeric value. Here is an example:

```<code>2019-01-01 00:00:00 2019-12-31 00:00:00 118433.0
2020-01-01 00:00:00 2020-12-31 00:00:00 120087.0
2021-01-01 00:00:00 2021-06-30 00:00:00 63831.0
2021-07-01 00:00:00 2021-12-31 00:00:00 63089.0
2022-01-01 00:00:00 2022-06-30 00:00:00 60753.0
2022-07-08 00:00:00 2022-11-30 00:00:00 9067.17
</code>```

As you can see while 2019 and 2020 are full years, the other rows describe different time spans.

I need to sum all the numeric values pertaining to the same year to get something like:

```<code>2019 118422.0
2020 120087.0
2021 123842.0
2022 9067.0
</code>```

The from-to dates on every row always fall in the same year.

Any given year does not have to be a full year.

I'd love to avoid simple iterations and learn a properly pythonic way of achieving this (list comprehension / vectorization).

Thank you

Body:
I have a dataframe with two datetime columns and a third column with a numeric value. Here is an example:

2019-01-01 00:00:00 2019-12-31 00:00:00 118433.0
2020-01-01 00:00:00 2020-12-31 00:00:00 120087.0
2021-01-01 00:00:00 2021-06-30 00:00:00 63831.0
2021-07-01 00:00:00 2021-12-31 00:00:00 63089.0
2022-01-01 00:00:00 2022-06-30 00:00:00 60753.0
2022-07-08 00:00:00 2022-11-30 00:00:00 9067.17

As you can see while 2019 and 2020 are full years, the other rows describe different time spans.

I need to sum all the numeric values pertaining to the same year to get something like:

2019 118422.0
2020 120087.0
2021 123842.0
2022 9067.0

The from-to dates on every row always fall in the same year.

Any given year does not have to be a full year.

I'd love to avoid simple iterations and learn a properly pythonic way of achieving this (list comprehension / vectorization).

Thank you


问:
OPC UA-Certificate Based Login
How can I configure OPC UA Server to use Username & Password?

How can I configure OPC UA Server to use Certificate? I need some sample code to Login with certificate In C#

Anonymous Login for OPC UA Server is working and able to create a session but can  have alternative Login using certification authorization In C#

Title: OPC UA-Certificate Based Login


问:
Jenkins gradle task configuration for multi module project
I have a multi module gradle project and trying to configure build in Jenkins web interface.
Also I need possibility to choose module or build the whole project, then create docker image and upload it to the repository.

I've created Choice parameter with variable $PROJECT and module enumeration, like this:

```<code>module1
module2
module3
</code>```

Then I added stage Invoke gradle script.

If I add gradle task $PROJECT:clean $PROJECT:build $PROJECT:jib, it will work fine for the selected module. But if I don't select module, it won't build the whole project, because of

```<code>$ /var/lib/jenkins/tools/hudson.plugins.gradle.GradleInstallation/gradle7.1.1/bin/gradle -DGRADLE_TASK= -PGRADLE_TASK= :clean :build :jib
Task 'clean' not found in root project 'name_of_project'.
</code>```

Tasks have unnecessary : symbol if module was not selected.

If I add gradle task clean build jib it will do these tasks for the whole project always no matter which module is selected.

Also I tried to create stage Run shell command before Invoke Gradle script with this code:

```<code>GRADLE_TASK="clean build jib"
if [ -z $PROJECT ]
then
  GRADLE_TASK="$PROJECT:clean $PROJECT:build $PROJECT:jib"
fi
</code>```

And use it in gradle task field like this:

```<code>$GRADLE_TASK
</code>```

But it doesn't take effect, because of:

```<code>/var/lib/jenkins/tools/hudson.plugins.gradle.GradleInstallation/gradle7.1.1/bin/gradle -DGRADLE_TASK= -PGRADLE_TASK= $GRADLE_TASK
Task '$GRADLE_TASK' not found in root project 'name_of_project'
</code>```

I tried some variants of this variable, but it doesn't work too:

```<code>- $GRADLE_TASK
- ${GRADLE_TASK}
- "${GRADLE_TASK}"
- GRADLE_TASK
</code>```

Can anybody help with this problem?

Body:
I have a multi module gradle project and trying to configure build in Jenkins web interface.
Also I need possibility to choose module or build the whole project, then create docker image and upload it to the repository.

I've created Choice parameter with variable $PROJECT and module enumeration, like this:

module1
module2
module3

Then I added stage Invoke gradle script.

If I add gradle task $PROJECT:clean $PROJECT:build $PROJECT:jib, it will work fine for the selected module. But if I don't select module, it won't build the whole project, because of

$ /var/lib/jenkins/tools/hudson.plugins.gradle.GradleInstallation/gradle7.1.1/bin/gradle -DGRADLE_TASK= -PGRADLE_TASK= :clean :build :jib
Task 'clean' not found in root project 'name_of_project'.

Tasks have unnecessary : symbol if module was not selected.

If I add gradle task clean build jib it will do these tasks for the whole project always no matter which module is selected.

Also I tried to create stage Run shell command before Invoke Gradle script with this code:

GRADLE_TASK="clean build jib"
if [ -z $PROJECT ]
then
  GRADLE_TASK="$PROJECT:clean $PROJECT:build $PROJECT:jib"
fi

And use it in gradle task field like this:

$GRADLE_TASK

But it doesn't take effect, because of:

/var/lib/jenkins/tools/hudson.plugins.gradle.GradleInstallation/gradle7.1.1/bin/gradle -DGRADLE_TASK= -PGRADLE_TASK= $GRADLE_TASK
Task '$GRADLE_TASK' not found in root project 'name_of_project'

I tried some variants of this variable, but it doesn't work too:

- $GRADLE_TASK
- ${GRADLE_TASK}
- "${GRADLE_TASK}"
- GRADLE_TASK

Can anybody help with this problem?


问:
openstack swift unauthorzed 401 while using swift stat in ubuntu 22.04 terminal
I have install openstack using ubuntu microstack
https://ubuntu.com/openstack/install

and then followed the steps to install swift
https://docs.openstack.org/swift/rocky/install/index.html

After the finalize steps for verfication , trying to give swift stat .
getting the error unauthorized error 401.

Please suggest

how to resolve the unauthorzed error 401 for swift


问:
Split pdf pages in two based on the content
I have to split multilingual PDFs to two different pdfs. I do have a function to split them but some of the files need to be split while others don't. How can identify based on their content does a pdf document needs to be split or not? It has to be done in python

samples:
https://drive.google.com/file/d/1AJ7ci6bQbRyRszIDIG_xqisKC2YsUzfO/view?usp=sharing this one needs to be split vertically so i can have Dutch and French separately

https://drive.google.com/file/d/1tU2kGnUARKSa39-R78aGcaBZZInLH0xu/view?usp=sharing This one does not need to be split

samples:
https://drive.google.com/file/d/1AJ7ci6bQbRyRszIDIG_xqisKC2YsUzfO/view?usp=sharing this one needs to be split vertically so i can have Dutch and French separately

https://drive.google.com/file/d/1tU2kGnUARKSa39-R78aGcaBZZInLH0xu/view?usp=sharing This one does not need to be split


问:
Get metrics that are exposed using REST API's into Prometheus
For instance am trying to get the connected user count from this API

The return json looks like,

If I want to grab the user_count and send it to data visualization platform like datadog or prometheus, is writing a custom exporter that polls at a certain interval and grabs the value, converts it to a metric(like gauge or counter) the only option to accomplish this?

Or is there a better way to do this integration that I might be missing?


问:
shm_open failing on read only file system
I'm trying to define a shared memory for IPC across two processes on an embedded device where the root is readonly.

It appears that this condition does not allow the creation.

How can I create a shared memory on RO filesystem?

This is the incriminated code:

```<code>//...
auto m_fmap = shm_open("/common_memory", O_CREAT | O_RDWR | O_EXCL, (S_IRUSR | S_IWUSR));
    if (m_fmap  == SHARED_INVALID) {
        printf("error opening sh. mem!\n");
        Close();
        return false;
    }

</code>```

Body:
I'm trying to define a shared memory for IPC across two processes on an embedded device where the root is readonly.

It appears that this condition does not allow the creation.

How can I create a shared memory on RO filesystem?

This is the incriminated code:

//...
auto m_fmap = shm_open("/common_memory", O_CREAT | O_RDWR | O_EXCL, (S_IRUSR | S_IWUSR));
    if (m_fmap  == SHARED_INVALID) {
        printf("error opening sh. mem!\n");
        Close();
        return false;
    }


问:
How to construct keyline in opencv if only the end points of the line are available?
Opencv provides a structure called keyline, which is detected by line segment detectors. The structure has various public members such as angle, length etc.

The following class members are not clearly explained such as class_id, endPointX, endPointY, ePointInOctaveX, ePointInOctaveY, octave, startPointX, startPointY etc.

My questions is if I have the end points of the line, can the structure members of keyline be constructed?

```<code>cv::Point P1 (0,0);
cv::Point P2 (10,10);

cv::line_descriptor::KeyLine L; // How to construct L from P1 and P2?
L.octave = ??;
L.endPointX = ??;
L.endPointY = ??;
L.ePointInOctaveX = ??;
L.ePointInOctaveY = ??;
L.startPointX = ??;
L.startPointY = ??
</code>```

Body:
Opencv provides a structure called keyline, which is detected by line segment detectors. The structure has various public members such as angle, length etc.

The following class members are not clearly explained such as class_id, endPointX, endPointY, ePointInOctaveX, ePointInOctaveY, octave, startPointX, startPointY etc.

My questions is if I have the end points of the line, can the structure members of keyline be constructed?

cv::Point P1 (0,0);
cv::Point P2 (10,10);

cv::line_descriptor::KeyLine L; // How to construct L from P1 and P2?
L.octave = ??;
L.endPointX = ??;
L.endPointY = ??;
L.ePointInOctaveX = ??;
L.ePointInOctaveY = ??;
L.startPointX = ??;
L.startPointY = ??


问:
How add in request header in code generate wsdl
I have test.wsdl, and generate Java code for this test.wsdl.
After generate code, i have many classes and interface:

```<code>@XmlSeeAlso({ObjectFactory.class, comTest.cxf.test.hdr.ObjectFactory.class})
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface Test{

@WebMethod(operationName = "GetData", action = "GET_DATA")
@WebResult(name = "GET_DATA_RESPONSE", targetNamespace = "", partName = "part1")
public GETDATARESPONSE getData(

    @WebParam(partName = "part1", name = "GET_DATA_REQUEST", targetNamespace = "")
    GETDATAREQUEST part1
);

}
</code>```

And when i call this method getData with params GETDATAREQUEST, service create request with body in my  GETDATAREQUEST params, but without header. And header which i need contains in class comTest.cxf.test.hdr.ObjectFactory.class. I think important annotation @XmlSeeAlso, but don't know how realise this...and binding ObjectFactory with GETDATAREQUEST

i implements interface Test in TestImpl and add in this class fields comTest.cxf.test.hdr.ObjectFactory.class, but when i want get ServicesHttpPort which created wsdl, this service return interface type Test//

I think important annotation @XmlSeeAlso, but don't know how realise this...and binding ObjectFactory with GETDATAREQUEST

Body:
I have test.wsdl, and generate Java code for this test.wsdl.
After generate code, i have many classes and interface:

@XmlSeeAlso({ObjectFactory.class, comTest.cxf.test.hdr.ObjectFactory.class})
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface Test{

@WebMethod(operationName = "GetData", action = "GET_DATA")
@WebResult(name = "GET_DATA_RESPONSE", targetNamespace = "", partName = "part1")
public GETDATARESPONSE getData(

    @WebParam(partName = "part1", name = "GET_DATA_REQUEST", targetNamespace = "")
    GETDATAREQUEST part1
);

}

And when i call this method getData with params GETDATAREQUEST, service create request with body in my  GETDATAREQUEST params, but without header. And header which i need contains in class comTest.cxf.test.hdr.ObjectFactory.class. I think important annotation @XmlSeeAlso, but don't know how realise this...and binding ObjectFactory with GETDATAREQUEST

i implements interface Test in TestImpl and add in this class fields comTest.cxf.test.hdr.ObjectFactory.class, but when i want get ServicesHttpPort which created wsdl, this service return interface type Test//

I think important annotation @XmlSeeAlso, but don't know how realise this...and binding ObjectFactory with GETDATAREQUEST


问:
Log scale circlize barplot
Is it possible to add a log scale to a circlize barplot axis?

I would like add a y-axis with a scale of 0.1, 1, 10, 100 to a circular barplot created using the package circlize.

I have not been successful yet finding a way using circos.yaxis.

Is it possible to do this?

Any help would be greatly appreciated.

Title: Log scale circlize barplot


问:
How to set absolute path to $schema in deeply nested jsons
I have a project where we keep recorded HTML responses as jsons, and they live in directory structure resembling the api paths. I'd like to add $schema property to each json to let IDEs provide some coding assistance / validation.

Because the jsons are nested in many directories, I can't use just one universal relative path to the schema definition. The definition comes from one of the packages in node_modules dir.

I tried ~node_modules or ~/ but this doesn't work. I expect this will be IDE dependent but maybe someone already stumbled upon such issue and has a solution.


问:
Confused about python dictionary behavior
I have a python class that I am developing that has a dict attribute with a list field. The list is then populated with additional dicts that default to empty dicts. What I am confused about is that somehow the previously generated dictionary is getting passed as input (I think) without explicitly being called.

A minimum example:

```<code>class Test:
    def __init__(self):
        self.c = {'test':[]}
    def populate(self):
        self.add_point()
        self.add_point()
    def add_point(self, d={}):
        print(d)
        self.c['test'].append(self.get_random(d))
    def get_random(self, d={}):
        d['field'] = random.uniform(0,1)
        return d
t = Test()
t.populate()
t.add_point()
print(t.c)
</code>```

What I expected to see is something like:

```<code>{}
{}
{}
{'test': [{'field': 0.6357007816254333}, {'field': 0.41279078670743063}, {'field': 0.822863149552643}]}
</code>```

What I actually see:

```<code>{}
{'field': 0.6357007816254333}
{'field': 0.822863149552643}
{'test': [{'field': 0.41279078670743063}, {'field': 0.41279078670743063}, {'field': 0.41279078670743063}]}
</code>```

I think I understand what is happening is somehow the dictionary is being persisted within the class. What I don't understand is why and how I can fix it.

```<code></code>```

Body:
I have a python class that I am developing that has a dict attribute with a list field. The list is then populated with additional dicts that default to empty dicts. What I am confused about is that somehow the previously generated dictionary is getting passed as input (I think) without explicitly being called.

A minimum example:

class Test:
    def __init__(self):
        self.c = {'test':[]}
    def populate(self):
        self.add_point()
        self.add_point()
    def add_point(self, d={}):
        print(d)
        self.c['test'].append(self.get_random(d))
    def get_random(self, d={}):
        d['field'] = random.uniform(0,1)
        return d
t = Test()
t.populate()
t.add_point()
print(t.c)

What I expected to see is something like:

{}
{}
{}
{'test': [{'field': 0.6357007816254333}, {'field': 0.41279078670743063}, {'field': 0.822863149552643}]}

What I actually see:

{}
{'field': 0.6357007816254333}
{'field': 0.822863149552643}
{'test': [{'field': 0.41279078670743063}, {'field': 0.41279078670743063}, {'field': 0.41279078670743063}]}

I think I understand what is happening is somehow the dictionary is being persisted within the class. What I don't understand is why and how I can fix it.


问:
Kiymd - Python app crashes on mobile phone
Good morning,

i'm very new on kivymd and Python, too. I made a code for a mobile app. Below the main.py code used to build the application. When i create the APK file using Colab - Buildozer (below the buildozer.spec file) and after installing the app on the phone, it correctly open in its main window but when i click to go in the second window where some actions could be done, it crashes.. The same app works perfectly on the pc, using PyCharm.

If i have to provide some other informations, please ask.

Thank you.

MAIN.PY

```<code>from kivy.core.window import Window
from kivy.lang import Builder
from kivy.properties import ObjectProperty, Clock
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.app import MDApp
from kivymd.icon_definitions import md_icons
from kivymd.uix.button import MDRaisedButton, MDFlatButton
from kivymd.uix.dialog import MDDialog
from kivymd.uix.list import OneLineListItem

class MainWindow(Screen):

    #Window.size = (480, 700)
    start_application=ObjectProperty(None)

class ShoppingWindow(Screen):
    #Window.size = (480, 700)
    fruit_vegetables_value=ObjectProperty(None)
    fruit_vegetables_Okbutton=ObjectProperty(None)
    bread_value=ObjectProperty(None)
    bread_OKButton=ObjectProperty(None)
    pasta_value=ObjectProperty(None)
    pasta_OKButton=ObjectProperty(None)
    delete_cart=ObjectProperty(None)
    delete_veg_value=ObjectProperty(None)
    delete_bread_value=ObjectProperty(None)
    delete_pasta_value=ObjectProperty(None)
    cleanser_Okbutton=ObjectProperty(None)
    delete_cleanser_value = ObjectProperty(None)
    fish_Okbutton=ObjectProperty(None)
    delete_fish_value=ObjectProperty(None)
    fish_value=ObjectProperty(None)
    meat_Okbutton=ObjectProperty(None)
    meat_value=ObjectProperty(None)
    delete_meat_value=ObjectProperty(None)
    freezer_value=ObjectProperty(None)
    freezer_Okbutton=ObjectProperty(None)
    delete_freezer_value=ObjectProperty(None)
    cheese_value=ObjectProperty(None)
    cheese_Okbutton=ObjectProperty(None)
    delete_cheese_value=ObjectProperty(None)
    cookies_value = ObjectProperty(None)
    cookies_Okbutton = ObjectProperty(None)
    delete_cookies_value = ObjectProperty(None)

    def fruit_vegetables(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.fruit_vegetables_value.text+'\n')
    def bread(self):
        global entry
        entry=1
        data_file = open("data_file.txt", "a+")
        data_file.write(self.bread_value.text + '\n')
    def pasta(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.pasta_value.text + '\n')
    def cleanser(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.cleanser_value.text + '\n')
    def fish(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.fish_value.text + '\n')
    def meat(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.meat_value.text + '\n')
    def freezer(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.freezer_value.text + '\n')
    def cheese(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.cheese_value.text + '\n')
    def cookies(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.cookies_value.text + '\n')
    def delete_veg_value_func(self):
        self.fruit_vegetables_value.text=""
    def delete_cookies_value_func(self):
        self.fruit_vegetables_value.text=""
    def delete_bread_value_func(self):
        self.bread_value.text=""
    def delete_pasta_value_func(self):
        self.pasta_value.text=""
    def delete_cleanser_value_func(self):
        self.cleanser_value.text=""
    def delete_fish_value_func(self):
        self.fish_value.text=""
    def delete_meat_value_func(self):
        self.meat_value.text=""
    def delete_freezer_value_func(self):
        self.freezer_value.text=""
    def delete_cheese_value_func(self):
        self.cheese_value.text=""

class WindowManager(ScreenManager):
    pass

sm=ScreenManager()
sm.add_widget(MainWindow(name="MainWindow"))
sm.add_widget(ShoppingWindow(name="ShoppingWindow"))

class CartShow(OneLineListItem):
    pass

class CartWindow(Screen):
    scroll=ObjectProperty(None)
    refresh=ObjectProperty(None)
    back_to_home=ObjectProperty(None)
    refresh_cart=ObjectProperty(None)

    def on_enter(self):
        global x
        self.dialog = MDDialog(
            text="Click on an item to remove it from list and confirm with refresh!",
            buttons=[
                MDFlatButton(
                    text="OK",
                    theme_text_color="Custom",
                    text_color="black",
                    on_release=lambda _: self.dialog.dismiss())
            ]
        )

        self.dialog.open()
        with open("data_file.txt", 'r') as fp:
            x = len(fp.readlines())

    def refresh(self):

        with open("data_file.txt", 'r') as fp:
            q = len(fp.readlines())

            self.ids.scroll.clear_widgets()

            file= open("data_file.txt" , "r")
            i=0
            for line in file:
                i=i+1
                icons = list(md_icons.keys())
                self.ids.scroll.add_widget(
                    CartShow(text=f"{line}",on_release=self.erase_list_item))

    def erase_list_item(self,OneLineListItem):

        with open("data_file.txt", "r+") as f:
            d = f.readlines()
            f.seek(0)
            for k in d:
                if k != OneLineListItem.text:
                    f.write(k)
            f.truncate()

        self.ids.scroll.clear_widgets()

        file = open("data_file.txt", "r")
        i = 0
        for line in file:
            i = i + 1
            self.ids.scroll.add_widget(
                CartShow(text=f"{line}",on_release=self.erase_list_item))

class MainApp(MDApp):

    def build(self):
        self.theme_cls.theme_style = "Light"
        self.theme_cls.primary_palette = "Blue"
        ww = Builder.load_file("Layout.kv")
        return ww
        return sm

MainApp().run()
</code>```

buildozer.spec - the part where i did some modifications

```<code>[app]

# (str) Title of your application
title = My Application

# (str) Package name
package.name = myapp

# (str) Package domain (needed for android/ios packaging)
package.domain = org.test

# (str) Source code where the main.py live
source.dir = .

# (list) Source files to include (let empty to include all the files)
source.include_exts = py,png,jpg,kv,atlas,txt,gif

# (list) List of inclusions using pattern matching
#source.include_patterns = assets/*,images/*.png

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin, venv

# (list) List of exclusions using pattern matching
# Do not prefix with './'
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
version = 0.1

# (str) Application versioning (method 2)
# version.regex = __version__ = ['"](.*)['"]
# version.filename = %(source.dir)s/main.py

# (list) Application requirements
# comma separated e.g. requirements = sqlite3,kivy
requirements = python3,kivy==2.1.0,kivymd,pillow

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy

# (str) Presplash of the application
#presplash.filename = %(source.dir)s/data/presplash.png

# (str) Icon of the application
#icon.filename = %(source.dir)s/data/icon.png

# (str) Supported orientation (one of landscape, sensorLandscape, portrait or all)
orientation = portrait

# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY

#
# OSX Specific
#

#
# author = © Copyright Info

# change the major version of python used by the app
osx.python_version = 3

# Kivy version to use
osx.kivy_version = 2.1.0

</code>```

I tried to:

Modify specifications in buildozer file but no improvement was obtained

Make a debugging of the application but no improvement was obtained

Reading everywhere on the internet but no answer was found.

Body:
Good morning,

i'm very new on kivymd and Python, too. I made a code for a mobile app. Below the main.py code used to build the application. When i create the APK file using Colab - Buildozer (below the buildozer.spec file) and after installing the app on the phone, it correctly open in its main window but when i click to go in the second window where some actions could be done, it crashes.. The same app works perfectly on the pc, using PyCharm.

If i have to provide some other informations, please ask.

Thank you.

MAIN.PY

from kivy.core.window import Window
from kivy.lang import Builder
from kivy.properties import ObjectProperty, Clock
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.app import MDApp
from kivymd.icon_definitions import md_icons
from kivymd.uix.button import MDRaisedButton, MDFlatButton
from kivymd.uix.dialog import MDDialog
from kivymd.uix.list import OneLineListItem

class MainWindow(Screen):

    #Window.size = (480, 700)
    start_application=ObjectProperty(None)

class ShoppingWindow(Screen):
    #Window.size = (480, 700)
    fruit_vegetables_value=ObjectProperty(None)
    fruit_vegetables_Okbutton=ObjectProperty(None)
    bread_value=ObjectProperty(None)
    bread_OKButton=ObjectProperty(None)
    pasta_value=ObjectProperty(None)
    pasta_OKButton=ObjectProperty(None)
    delete_cart=ObjectProperty(None)
    delete_veg_value=ObjectProperty(None)
    delete_bread_value=ObjectProperty(None)
    delete_pasta_value=ObjectProperty(None)
    cleanser_Okbutton=ObjectProperty(None)
    delete_cleanser_value = ObjectProperty(None)
    fish_Okbutton=ObjectProperty(None)
    delete_fish_value=ObjectProperty(None)
    fish_value=ObjectProperty(None)
    meat_Okbutton=ObjectProperty(None)
    meat_value=ObjectProperty(None)
    delete_meat_value=ObjectProperty(None)
    freezer_value=ObjectProperty(None)
    freezer_Okbutton=ObjectProperty(None)
    delete_freezer_value=ObjectProperty(None)
    cheese_value=ObjectProperty(None)
    cheese_Okbutton=ObjectProperty(None)
    delete_cheese_value=ObjectProperty(None)
    cookies_value = ObjectProperty(None)
    cookies_Okbutton = ObjectProperty(None)
    delete_cookies_value = ObjectProperty(None)

    def fruit_vegetables(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.fruit_vegetables_value.text+'\n')
    def bread(self):
        global entry
        entry=1
        data_file = open("data_file.txt", "a+")
        data_file.write(self.bread_value.text + '\n')
    def pasta(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.pasta_value.text + '\n')
    def cleanser(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.cleanser_value.text + '\n')
    def fish(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.fish_value.text + '\n')
    def meat(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.meat_value.text + '\n')
    def freezer(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.freezer_value.text + '\n')
    def cheese(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.cheese_value.text + '\n')
    def cookies(self):
        data_file = open("data_file.txt", "a+")
        data_file.write(self.cookies_value.text + '\n')
    def delete_veg_value_func(self):
        self.fruit_vegetables_value.text=""
    def delete_cookies_value_func(self):
        self.fruit_vegetables_value.text=""
    def delete_bread_value_func(self):
        self.bread_value.text=""
    def delete_pasta_value_func(self):
        self.pasta_value.text=""
    def delete_cleanser_value_func(self):
        self.cleanser_value.text=""
    def delete_fish_value_func(self):
        self.fish_value.text=""
    def delete_meat_value_func(self):
        self.meat_value.text=""
    def delete_freezer_value_func(self):
        self.freezer_value.text=""
    def delete_cheese_value_func(self):
        self.cheese_value.text=""

class WindowManager(ScreenManager):
    pass

sm=ScreenManager()
sm.add_widget(MainWindow(name="MainWindow"))
sm.add_widget(ShoppingWindow(name="ShoppingWindow"))

class CartShow(OneLineListItem):
    pass

class CartWindow(Screen):
    scroll=ObjectProperty(None)
    refresh=ObjectProperty(None)
    back_to_home=ObjectProperty(None)
    refresh_cart=ObjectProperty(None)

    def on_enter(self):
        global x
        self.dialog = MDDialog(
            text="Click on an item to remove it from list and confirm with refresh!",
            buttons=[
                MDFlatButton(
                    text="OK",
                    theme_text_color="Custom",
                    text_color="black",
                    on_release=lambda _: self.dialog.dismiss())
            ]
        )

        self.dialog.open()
        with open("data_file.txt", 'r') as fp:
            x = len(fp.readlines())

    def refresh(self):

        with open("data_file.txt", 'r') as fp:
            q = len(fp.readlines())

            self.ids.scroll.clear_widgets()

            file= open("data_file.txt" , "r")
            i=0
            for line in file:
                i=i+1
                icons = list(md_icons.keys())
                self.ids.scroll.add_widget(
                    CartShow(text=f"{line}",on_release=self.erase_list_item))

    def erase_list_item(self,OneLineListItem):

        with open("data_file.txt", "r+") as f:
            d = f.readlines()
            f.seek(0)
            for k in d:
                if k != OneLineListItem.text:
                    f.write(k)
            f.truncate()

        self.ids.scroll.clear_widgets()

        file = open("data_file.txt", "r")
        i = 0
        for line in file:
            i = i + 1
            self.ids.scroll.add_widget(
                CartShow(text=f"{line}",on_release=self.erase_list_item))

class MainApp(MDApp):

    def build(self):
        self.theme_cls.theme_style = "Light"
        self.theme_cls.primary_palette = "Blue"
        ww = Builder.load_file("Layout.kv")
        return ww
        return sm

MainApp().run()

buildozer.spec - the part where i did some modifications

[app]

# (str) Title of your application
title = My Application

# (str) Package name
package.name = myapp

# (str) Package domain (needed for android/ios packaging)
package.domain = org.test

# (str) Source code where the main.py live
source.dir = .

# (list) Source files to include (let empty to include all the files)
source.include_exts = py,png,jpg,kv,atlas,txt,gif

# (list) List of inclusions using pattern matching
#source.include_patterns = assets/*,images/*.png

# (list) Source files to exclude (let empty to not exclude anything)
#source.exclude_exts = spec

# (list) List of directory to exclude (let empty to not exclude anything)
#source.exclude_dirs = tests, bin, venv

# (list) List of exclusions using pattern matching
# Do not prefix with './'
#source.exclude_patterns = license,images/*/*.jpg

# (str) Application versioning (method 1)
version = 0.1

# (str) Application versioning (method 2)
# version.regex = __version__ = ['"](.*)['"]
# version.filename = %(source.dir)s/main.py

# (list) Application requirements
# comma separated e.g. requirements = sqlite3,kivy
requirements = python3,kivy==2.1.0,kivymd,pillow

# (str) Custom source folders for requirements
# Sets custom source for any requirements with recipes
# requirements.source.kivy = ../../kivy

# (str) Presplash of the application
#presplash.filename = %(source.dir)s/data/presplash.png

# (str) Icon of the application
#icon.filename = %(source.dir)s/data/icon.png

# (str) Supported orientation (one of landscape, sensorLandscape, portrait or all)
orientation = portrait

# (list) List of service to declare
#services = NAME:ENTRYPOINT_TO_PY,NAME2:ENTRYPOINT2_TO_PY

#
# OSX Specific
#

#
# author = © Copyright Info

# change the major version of python used by the app
osx.python_version = 3

# Kivy version to use
osx.kivy_version = 2.1.0

I tried to:

Modify specifications in buildozer file but no improvement was obtained

Make a debugging of the application but no improvement was obtained

Reading everywhere on the internet but no answer was found.


问:
How to store data from nested loop in React&

There's an array of weeks and for each week I have an array of data from database. I need to find a way to store all data in redux store. How can I do this? I would appreciate any help or suggestions

I tried to initialize results variable in the upper useEffect scope, but it didn't work as expected. Any ideas?


问:
Cannot import file with types from custom library into CRA with typescript
I'm working in mono-repo environment so I created package which i can share between my frontend and backend services.

I have generated react app through CRA with typescript template, I can import typescript files with typescript syntax totally fine when files are located in my frontend app.
But when I try to import typescript file from custom library I created, I get the following error

```<code>Module parse failed: Unexpected token (16:10)
File was processed with these loaders:
 * ../../node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
 * ../../node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
|
> const test: number = 0
</code>```

When I remove typescript syntax from file the import works.

I tried using tsc to transpile typescript into javascript. Importing javascript files also works

Body:
I'm working in mono-repo environment so I created package which i can share between my frontend and backend services.

I have generated react app through CRA with typescript template, I can import typescript files with typescript syntax totally fine when files are located in my frontend app.
But when I try to import typescript file from custom library I created, I get the following error

Module parse failed: Unexpected token (16:10)
File was processed with these loaders:
 * ../../node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
 * ../../node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
|
> const test: number = 0

When I remove typescript syntax from file the import works.

I tried using tsc to transpile typescript into javascript. Importing javascript files also works


问:
download and upload files or image using react native
how can I download files (pdf,word,etc...) or image using react native, I want to download files from json api.

I want to download files from json api


问:
Having a problem with IMAGE datatype and duplicated records which make query run for minutes
I know the IMAGE datatype is deprecated, but that is how the database I am working in is set-up, and I cannot change it.

I have an Invoice table, which records every order that is made.

That Invoice table is joined to Invoice_Details, which has information about the line items in the invoice.

Then we further join tables based on the Style table which is the item master table and has all information about that item specifically, like color, category, size, etc.

Here is the initial query.

```<code>SELECT
    I.[Company_Code]
    ,I.[Division_Code]
    ,s.Item_Number
    ,s.Color_Code
    ,s.License_Code
    ,s.Master_Item
    ,i.Date_Invoiced
    ,id.Quantity * id.Price total
    ,Year(i.Date_Invoiced) Year
    ,DATEPART(Quarter, (i.Date_Invoiced)) Quarter
    ,ss.upc_number
    ,ss.size_description
INTO
    #SELLINS
FROM
    [AMTPLUS].[dbo].[Invoices] i
LEFT JOIN
    invoices_detail id ON i.Company_Code = id.Company_Code
                       AND i.Division_Code = id.Division_Code
                       AND i.Invoice_Number = id.Invoice_Number
JOIN
    style s ON id.Item_Number = s.Item_Number
            AND id.Color_Code = s.Color_Code
JOIN
    License ON s.License_Code = License.License_Code
JOIN
    Style_Size ss ON s.Item_Number = ss.Item_Number
                  AND s.Color_Code = ss.Color_Code
WHERE
    i.Date_Invoiced BETWEEN '01/01/2022' AND '12/30/2022'

SELECT * FROM #SELLINS
</code>```

This line:

```<code>SELECT * FROM #SELLINS
</code>```

returns 500,000 rows and it does so within 45 seconds, which is reasonable enough.

Now the problem comes in when I want to join the Style_Image table, which has an IMAGE datatype for each item.

I have been playing around and altering this query a lot, but I cannot make any progress.

One thing I tried to do is separate the image part by itself. So in my stored procedure, the next lines after the above are:

```<code>SELECT
    s.Item_Number
    ,s.Color_Code
    ,sp.Item_Image
INTO
    #Sellins2
FROM
    Style S
LEFT JOIN
    Style_Pictures sp ON s.Item_Number = sp.Item_Number
                      AND s.Color_Code = sp.Color_Code
                      AND s.Company_Code = sp.Company_Code
                      AND s.Division_Code = sp.Division_Code
WHERE
    s.Item_Number IN (SELECT DISTINCT Item_Number FROM #SELLINS)

SELECT * FROM #Sellins2
</code>```

I used to have everything on one main query with all the table joins, but to improve performance, I'm trying to split things up.

The

```<code>Select * from #Sellins2
</code>```

line runs in about 30 seconds, and returns 5,000 lines.

Because while there might be 500,000 records about invoices and the items on each invoice, those are spread out over about 5,000 total items, which get repeated a lot on different invoices.

For example, lots of different people can buy Style A, spread over different invoices, but Style A only has one record on the Image table, since it only has one image.

The problem comes when I try to combine these 2 temporary tables.

The last part of my stored procedure looks like this

```<code>select
    s.*
    ,s2.Item_Image
from
    #Sellins s
    left join #Sellins2 s2 on s.Item_Number=s2.Item_Number and s.Color_Code=s2.Color_Code
</code>```

It takes the image from the #Sellins2 table, and has to attach it to each invoice record, so each of the 500,000 lines shows what is the image that is associated to that line.

That final query, it starts displaying the results instantly, but the lines load in very slowly. And the query only finishes running after 5-10 minutes. Which causes the report to time out when showing it in the SSRS report viewer.

I think the reason this is happening is because even though there are only 5,000 image records, they are getting duplicated each time that item appears. So if a particular item was bought 500 times over the year, in the invoice table there will be 500 lines for that item, and each line will have 500 image records, even though that image is exactly the same for all 500 records.

Is there any way to make SQL Server know that we only need 1 cached image for each item, and to just use the same thing when duplicates are found?

Thanks a lot, any help would be appreciated.

Body:
I know the IMAGE datatype is deprecated, but that is how the database I am working in is set-up, and I cannot change it.

I have an Invoice table, which records every order that is made.

That Invoice table is joined to Invoice_Details, which has information about the line items in the invoice.

Then we further join tables based on the Style table which is the item master table and has all information about that item specifically, like color, category, size, etc.

Here is the initial query.

SELECT
    I.[Company_Code]
    ,I.[Division_Code]
    ,s.Item_Number
    ,s.Color_Code
    ,s.License_Code
    ,s.Master_Item
    ,i.Date_Invoiced
    ,id.Quantity * id.Price total
    ,Year(i.Date_Invoiced) Year
    ,DATEPART(Quarter, (i.Date_Invoiced)) Quarter
    ,ss.upc_number
    ,ss.size_description
INTO
    #SELLINS
FROM
    [AMTPLUS].[dbo].[Invoices] i
LEFT JOIN
    invoices_detail id ON i.Company_Code = id.Company_Code
                       AND i.Division_Code = id.Division_Code
                       AND i.Invoice_Number = id.Invoice_Number
JOIN
    style s ON id.Item_Number = s.Item_Number
            AND id.Color_Code = s.Color_Code
JOIN
    License ON s.License_Code = License.License_Code
JOIN
    Style_Size ss ON s.Item_Number = ss.Item_Number
                  AND s.Color_Code = ss.Color_Code
WHERE
    i.Date_Invoiced BETWEEN '01/01/2022' AND '12/30/2022'

SELECT * FROM #SELLINS

This line:

SELECT * FROM #SELLINS

returns 500,000 rows and it does so within 45 seconds, which is reasonable enough.

Now the problem comes in when I want to join the Style_Image table, which has an IMAGE datatype for each item.

I have been playing around and altering this query a lot, but I cannot make any progress.

One thing I tried to do is separate the image part by itself. So in my stored procedure, the next lines after the above are:

SELECT
    s.Item_Number
    ,s.Color_Code
    ,sp.Item_Image
INTO
    #Sellins2
FROM
    Style S
LEFT JOIN
    Style_Pictures sp ON s.Item_Number = sp.Item_Number
                      AND s.Color_Code = sp.Color_Code
                      AND s.Company_Code = sp.Company_Code
                      AND s.Division_Code = sp.Division_Code
WHERE
    s.Item_Number IN (SELECT DISTINCT Item_Number FROM #SELLINS)

SELECT * FROM #Sellins2

I used to have everything on one main query with all the table joins, but to improve performance, I'm trying to split things up.

The

Select * from #Sellins2

line runs in about 30 seconds, and returns 5,000 lines.

Because while there might be 500,000 records about invoices and the items on each invoice, those are spread out over about 5,000 total items, which get repeated a lot on different invoices.

For example, lots of different people can buy Style A, spread over different invoices, but Style A only has one record on the Image table, since it only has one image.

The problem comes when I try to combine these 2 temporary tables.

The last part of my stored procedure looks like this

select
    s.*
    ,s2.Item_Image
from
    #Sellins s
    left join #Sellins2 s2 on s.Item_Number=s2.Item_Number and s.Color_Code=s2.Color_Code

It takes the image from the #Sellins2 table, and has to attach it to each invoice record, so each of the 500,000 lines shows what is the image that is associated to that line.

That final query, it starts displaying the results instantly, but the lines load in very slowly. And the query only finishes running after 5-10 minutes. Which causes the report to time out when showing it in the SSRS report viewer.

I think the reason this is happening is because even though there are only 5,000 image records, they are getting duplicated each time that item appears. So if a particular item was bought 500 times over the year, in the invoice table there will be 500 lines for that item, and each line will have 500 image records, even though that image is exactly the same for all 500 records.

Is there any way to make SQL Server know that we only need 1 cached image for each item, and to just use the same thing when duplicates are found?

Thanks a lot, any help would be appreciated.


问:
Show multiple file thumbnail on custom dropzone
I created custom dropzone in order to upload my files as the following example

function readFile(input) {

  debugger;
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    for (let i = 0; i < input.files.length; i++) {
      reader.onload = function(e) {
        var htmlPreview =
          '' +
          "
" +
          input.files[i].name +
          "
";
        var wrapperZone = $(input).parent();
        var previewZone = $(input)
          .parent()
          .parent()
          .find(".preview-zone");
        var boxZone = $(input)
          .parent()
          .parent()
          .find(".preview-zone")
          .find(".box")
          .find(".box-body");

        wrapperZone.removeClass("dragover");
        previewZone.removeClass("hidden");
        // boxZone.empty();
        boxZone.append(htmlPreview);
      };
    }

    reader.readAsDataURL(input.files[0]);
  }
}

function reset(e) {
  e.wrap("<form>")
    .closest("form")
    .get(0)
    .reset();
  e.unwrap();
}

$(".dropzone").change(function() {
  readFile(this);
});

$(".dropzone-wrapper").on("dragover", function(e) {
  e.preventDefault();
  e.stopPropagation();
  $(this).addClass("dragover");
});

$(".dropzone-wrapper").on("dragleave", function(e) {
  e.preventDefault();
  e.stopPropagation();
  $(this).removeClass("dragover");
});

$(".remove-preview").on("click", function() {
  var boxZone = $(this)
    .parents(".preview-zone")
    .find(".box-body");
  var previewZone = $(this).parents(".preview-zone");
  var dropzone = $(this)
    .parents(".form-group")
    .find(".dropzone");
  boxZone.empty();
  previewZone.addClass("hidden");
  reset(dropzone);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  padding: 50px 100px;
}

.box {
  position: relative;
  background: #ffffff;
  width: 100%;
}

.box-header {
  color: #444;
  display: block;
  padding: 10px;
  position: relative;
  margin-bottom: 10px;
}

.box-tools {
  position: absolute;
  right: 10px;
  top: 5px;
}

.dropzone-wrapper {
  border: 2px dashed #91b0b3;
  color: #92b0b3;
  position: relative;
  height: 150px;
}

.dropzone-desc {
  position: absolute;
  margin: 0 auto;
  left: 0;
  right: 0;
  text-align: center;
  width: 40%;
  top: 60px;
  font-size: 16px;
}

.dropzone,
.dropzone:focus {
  outline: none !important;
  width: 100%;
  cursor: pointer;
}

.input-file {
  position: absolute;
  width: 100%;
  height: 150px;
  opacity: 0;
}

.dropzone-wrapper:hover,
.dropzone-wrapper.dragover {
  background: #ecf0f5;
}

.preview-zone {
  text-align: center;
}

.preview-zone .box {
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

10sec

Preview

                        <button type="button" class="btn btn-danger btn-xs remove-preview">
                                              Reset
                                           </button>

Choose an image file or drag it here.

                  <input type="file" class="dropzone input-file" multiple asp-for="@Model.Files10" />

```

As you can see it is a multiple-input file, so you can upload multiple files in the same dropzone.

as you can see in the readFile javascript function, I create the thumbnail, the problem is when selecting more than one file, it only shows one thumbnail, how can I display each of them each next to the other as:

Regards

Body:
I created custom dropzone in order to upload my files as the following example

function readFile(input) {

  debugger;
  if (input.files && input.files[0]) {
    var reader = new FileReader();

    for (let i = 0; i < input.files.length; i++) {
      reader.onload = function(e) {
        var htmlPreview =
          '' +
          "
" +
          input.files[i].name +
          "
";
        var wrapperZone = $(input).parent();
        var previewZone = $(input)
          .parent()
          .parent()
          .find(".preview-zone");
        var boxZone = $(input)
          .parent()
          .parent()
          .find(".preview-zone")
          .find(".box")
          .find(".box-body");

        wrapperZone.removeClass("dragover");
        previewZone.removeClass("hidden");
        // boxZone.empty();
        boxZone.append(htmlPreview);
      };
    }

    reader.readAsDataURL(input.files[0]);
  }
}

function reset(e) {
  e.wrap("<form>")
    .closest("form")
    .get(0)
    .reset();
  e.unwrap();
}

$(".dropzone").change(function() {
  readFile(this);
});

$(".dropzone-wrapper").on("dragover", function(e) {
  e.preventDefault();
  e.stopPropagation();
  $(this).addClass("dragover");
});

$(".dropzone-wrapper").on("dragleave", function(e) {
  e.preventDefault();
  e.stopPropagation();
  $(this).removeClass("dragover");
});

$(".remove-preview").on("click", function() {
  var boxZone = $(this)
    .parents(".preview-zone")
    .find(".box-body");
  var previewZone = $(this).parents(".preview-zone");
  var dropzone = $(this)
    .parents(".form-group")
    .find(".dropzone");
  boxZone.empty();
  previewZone.addClass("hidden");
  reset(dropzone);
});

.container {
  padding: 50px 100px;
}

.box {
  position: relative;
  background: #ffffff;
  width: 100%;
}

.box-header {
  color: #444;
  display: block;
  padding: 10px;
  position: relative;
  margin-bottom: 10px;
}

.box-tools {
  position: absolute;
  right: 10px;
  top: 5px;
}

.dropzone-wrapper {
  border: 2px dashed #91b0b3;
  color: #92b0b3;
  position: relative;
  height: 150px;
}

.dropzone-desc {
  position: absolute;
  margin: 0 auto;
  left: 0;
  right: 0;
  text-align: center;
  width: 40%;
  top: 60px;
  font-size: 16px;
}

.dropzone,
.dropzone:focus {
  outline: none !important;
  width: 100%;
  cursor: pointer;
}

.input-file {
  position: absolute;
  width: 100%;
  height: 150px;
  opacity: 0;
}

.dropzone-wrapper:hover,
.dropzone-wrapper.dragover {
  background: #ecf0f5;
}

.preview-zone {
  text-align: center;
}

.preview-zone .box {
  box-shadow: none;
  border-radius: 0;
  margin-bottom: 0;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

10sec

Preview

                        <button type="button" class="btn btn-danger btn-xs remove-preview">
                                              Reset
                                           </button>

Choose an image file or drag it here.

                  <input type="file" class="dropzone input-file" multiple asp-for="@Model.Files10" />

As you can see it is a multiple-input file, so you can upload multiple files in the same dropzone.

as you can see in the readFile javascript function, I create the thumbnail, the problem is when selecting more than one file, it only shows one thumbnail, how can I display each of them each next to the other as:

Regards


问:
Fill a plot with color from a y upwards to infinity
I am trying to indicate a "dangerous" zone in my sns boxplot.

So far this is what i came up with:

plt.fill_between([0, 6], [danger, danger], danger * 1.2, color='salmon', alpha=0.5)
```

But since I use sns boxplot, the x values are totally messed up and i had to play with it to get the following result:

I cant really increase the polygon size as the plot grows with it (understandingly).
Ideally i would have wanted to simply paint everything above this threshold as red like so:

Body:
I am trying to indicate a "dangerous" zone in my sns boxplot.

So far this is what i came up with:

plt.fill_between([0, 6], [danger, danger], danger * 1.2, color='salmon', alpha=0.5)

But since I use sns boxplot, the x values are totally messed up and i had to play with it to get the following result:

I cant really increase the polygon size as the plot grows with it (understandingly).
Ideally i would have wanted to simply paint everything above this threshold as red like so:


问:
I Can't connect postgresql in local env after deploy via Render.com
Most important thing, I'm sorry, but I'm not native English speaker.

What I can't

After I deployed my app via "Render.com" (Luckily, it has been a success!), I thought keep developing in local env, but I can't connect my DB.

Error Description

I wanted to test with Rspec, but I got an error so I tried "rails db:reset" to see if it would work.

```<code>rails aborted!
ActiveRecord::ConnectionNotEstablished: could not translate host name "xxxxxxxxxxxx" to address: Name or service not known
</code>```

What I want to do

I would like to eliminate this error so that I can continue to develop properly and locally.

Worry

I am concerned that it may have some effect on the deployed apps. If anyone knows, please advise.

Environment

Ruby 3.1.2

Rails 7.0.4

Addendum

database.yml

```<code># PostgreSQL. Versions 9.3 and up are supported.
#
# Install the pg driver:
#   gem install pg
# On macOS with Homebrew:
#   gem install pg -- --with-pg-config=/usr/local/bin/pg_config
# On macOS with MacPorts:
#   gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
# On Windows:
#   gem install pg
#       Choose the win32 build.
#       Install PostgreSQL and put its /bin directory on your path.
#
# Configure Using Gemfile
# gem "pg"
#
default: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see Rails configuration guide
  # https://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: k_development

  # The specified database role being used to connect to postgres.
  # To create additional roles in postgres see `$ createuser --help`.
  # When left blank, postgres will use the default role. This is
  # the same name as the operating system user running Rails.
  #username: k

  # The password associated with the postgres role (username).
  #password:

  # Connect on a TCP socket. Omitted by default since the client uses a
  # domain socket that doesn't need configuration. Windows does not have
  # domain sockets, so uncomment these lines.
  #host: localhost

  # The TCP port the server listens on. Defaults to 5432.
  # If your server runs on a different port number, change accordingly.
  #port: 5432

  # Schema search path. The server defaults to $user,public
  #schema_search_path: myapp,sharedapp,public

  # Minimum log levels, in increasing order:
  #   debug5, debug4, debug3, debug2, debug1,
  #   log, notice, warning, error, fatal, and panic
  # Defaults to warning.
  #min_messages: notice

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: k_test

# As with config/credentials.yml, you never want to store sensitive information,
# like your database password, in your source code. If your source code is
# ever seen by anyone, they now have access to your database.
#
# Instead, provide the password or a full connection URL as an environment
# variable when you boot the app. For example:
#
#   DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase"
#
# If the connection URL is provided in the special DATABASE_URL environment
# variable, Rails will automatically merge its configuration values on top of
# the values provided in this file. Alternatively, you can specify a connection
# URL environment variable explicitly:
#
#   production:
#     url: <%= ENV["MY_APP_DATABASE_URL"] %>
#
# Read https://guides.rubyonrails.org/configuring.html#configuring-a-database
# for a full overview on how database connection configuration can be specified.
#
production:
  <<: *default
  database: k_production
  username: <%= ENV["K_DATABASE_USERNAME"] %>
  password: <%= ENV["K_DATABASE_PASSWORD"] %>
</code>```

Body:
Most important thing, I'm sorry, but I'm not native English speaker.

What I can't

After I deployed my app via "Render.com" (Luckily, it has been a success!), I thought keep developing in local env, but I can't connect my DB.

Error Description

I wanted to test with Rspec, but I got an error so I tried "rails db:reset" to see if it would work.

rails aborted!
ActiveRecord::ConnectionNotEstablished: could not translate host name "xxxxxxxxxxxx" to address: Name or service not known

What I want to do

I would like to eliminate this error so that I can continue to develop properly and locally.

Worry

I am concerned that it may have some effect on the deployed apps. If anyone knows, please advise.

Environment

Ruby 3.1.2

Rails 7.0.4

Addendum

database.yml

# PostgreSQL. Versions 9.3 and up are supported.
#
# Install the pg driver:
#   gem install pg
# On macOS with Homebrew:
#   gem install pg -- --with-pg-config=/usr/local/bin/pg_config
# On macOS with MacPorts:
#   gem install pg -- --with-pg-config=/opt/local/lib/postgresql84/bin/pg_config
# On Windows:
#   gem install pg
#       Choose the win32 build.
#       Install PostgreSQL and put its /bin directory on your path.
#
# Configure Using Gemfile
# gem "pg"
#
default: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see Rails configuration guide
  # https://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
  <<: *default
  database: k_development

  # The specified database role being used to connect to postgres.
  # To create additional roles in postgres see `$ createuser --help`.
  # When left blank, postgres will use the default role. This is
  # the same name as the operating system user running Rails.
  #username: k

  # The password associated with the postgres role (username).
  #password:

  # Connect on a TCP socket. Omitted by default since the client uses a
  # domain socket that doesn't need configuration. Windows does not have
  # domain sockets, so uncomment these lines.
  #host: localhost

  # The TCP port the server listens on. Defaults to 5432.
  # If your server runs on a different port number, change accordingly.
  #port: 5432

  # Schema search path. The server defaults to $user,public
  #schema_search_path: myapp,sharedapp,public

  # Minimum log levels, in increasing order:
  #   debug5, debug4, debug3, debug2, debug1,
  #   log, notice, warning, error, fatal, and panic
  # Defaults to warning.
  #min_messages: notice

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: k_test

# As with config/credentials.yml, you never want to store sensitive information,
# like your database password, in your source code. If your source code is
# ever seen by anyone, they now have access to your database.
#
# Instead, provide the password or a full connection URL as an environment
# variable when you boot the app. For example:
#
#   DATABASE_URL="postgres://myuser:mypass@localhost/somedatabase"
#
# If the connection URL is provided in the special DATABASE_URL environment
# variable, Rails will automatically merge its configuration values on top of
# the values provided in this file. Alternatively, you can specify a connection
# URL environment variable explicitly:
#
#   production:
#     url: <%= ENV["MY_APP_DATABASE_URL"] %>
#
# Read https://guides.rubyonrails.org/configuring.html#configuring-a-database
# for a full overview on how database connection configuration can be specified.
#
production:
  <<: *default
  database: k_production
  username: <%= ENV["K_DATABASE_USERNAME"] %>
  password: <%= ENV["K_DATABASE_PASSWORD"] %>


问:
pdf.getDocument does not throw a PasswordException
Using react web app

package.json

```<code>    "react": "^16.10.2",
    "react-pdf": "^5.7.2",
</code>```

imports:

```<code>import {pdfjs} from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;
</code>```

When loading encrypted (protected) pdf file, promise does not throw a PasswordException as it should

code

```<code>const data = convertDataURIToBinary(base64PdfData); //implementation not important
pdfjs.getDocument({data, password: ''}).promise.then(doc => {
   console.warn('ends up here even with wrong password!')
}).catch(e => {
   console.error('never executed, why?')
})
</code>```

imported pdfjs dependency is version 2.12.313 so API should match

Body:
Using react web app

package.json

    "react": "^16.10.2",
    "react-pdf": "^5.7.2",

imports:

import {pdfjs} from "react-pdf";
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;

When loading encrypted (protected) pdf file, promise does not throw a PasswordException as it should

code

const data = convertDataURIToBinary(base64PdfData); //implementation not important
pdfjs.getDocument({data, password: ''}).promise.then(doc => {
   console.warn('ends up here even with wrong password!')
}).catch(e => {
   console.error('never executed, why?')
})

imported pdfjs dependency is version 2.12.313 so API should match


问:
Soap WebAPI with duplicate element C#
I have created a WebMethod to handle the soap api. I am facing some challenges to while creating soap api.

How to read action attribute from order root element?

WSDL has duplicate keys(CustomElement) in the root of xml document. How to map CustomElement element to C# model object?

This order WebMethod (code added here) insert empty order element in the xml?

```<code><Body>
<Order xmlns="http://tempuri.org/">
  <order> // Empty key
  ...
  ...

</Order>
</Body>
</code>```

WSDL Doc:

```<code><Body>
      <Order action="NEW_ORDER" transactionID="ABC12300000000-0000-4000-8000-000000000000">
         <ProductID>123</ProductID>
         <ProductName>End To End Title</ProductName>
         <CustomElement id="11" name="">
            <Value>String</Value>
         </CustomElement>
         <CustomElement id="22" name="">
            <Value>String</Value>
         </CustomElement>
         <CustomElement id="33" name="">
            <Value>String</Value>
         </CustomElement>
      </Order>    </Body>

[WebMethod]
public string Order(Models.OrderSoap order)
{
            return "Hello World";
}

public class OrderSoap
{

    public int ProductID { get; set;}
    public string ProductName { get; set; }
    ...

}
</code>```

Title: Soap WebAPI with duplicate element C#

Body:
I have created a WebMethod to handle the soap api. I am facing some challenges to while creating soap api.

How to read action attribute from order root element?

WSDL has duplicate keys(CustomElement) in the root of xml document. How to map CustomElement element to C# model object?

This order WebMethod (code added here) insert empty order element in the xml?

<Order xmlns="http://tempuri.org/">
  <order> // Empty key
  ...
  ...

</Order>

WSDL Doc:

      <Order action="NEW_ORDER" transactionID="ABC12300000000-0000-4000-8000-000000000000">
         <ProductID>123</ProductID>
         <ProductName>End To End Title</ProductName>
         <CustomElement id="11" name="">
            <Value>String</Value>
         </CustomElement>
         <CustomElement id="22" name="">
            <Value>String</Value>
         </CustomElement>
         <CustomElement id="33" name="">
            <Value>String</Value>
         </CustomElement>
      </Order>

[WebMethod]
public string Order(Models.OrderSoap order)
{
            return "Hello World";
}

public class OrderSoap
{

    public int ProductID { get; set;}
    public string ProductName { get; set; }
    ...

}


问:
SignalR Disconnect method is not invoked on Internet Disconnection
I have a ASP.NET CORE Web API .net 6.0 application with SignalR WebSocket hub and JS Client for SignalR. And when I am disconecting from internet SignalR disconnect method is not calling. I tried to config timeouts but still not working

Disconnect signalR when there is no internet


问:
ImportError: No module named site running Gdb from a Python script
I am using a Python script to connect to a launched Gdb server. In my code I have used

```<code>os.system('./debug.sh')
</code>```

where debug.sh content is

```<code>gdb main.x < debug >& debug.log
</code>```

when I check debug.log I find the output as follows

```<code>Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
ImportError: No module named site
</code>```

Although when I run the script directly from the terminal the command gets executed and Gdb client connects with no issues. I'm not sure if the issue is tied to Gdb command but when I tried executing other commands instead like echo I faced no issues. I tried doing as the error says and according to the answers to "ImportError: No module named site" on Windows and Python/IPython ImportError: no module named site I prepended those line to debug.sh

```<code>export PYTHONHOME=/usr/bin
export PYTHONPATH=/usr/lib/python2.7
export PATH=$PYTHONHOME:$PATH
</code>```

But I still got

```<code>ImportError: No module named site
</code>```

I also tried unsetting PYTHONHOME as the second link suggests but that didn't work. If I run a Python shell from the terminal and run

```<code>import site
</code>```

I face no issues, So I am not really sure what's the issue here. I am working on a Redhat7 machine. Thanks in advance.

Body:
I am using a Python script to connect to a launched Gdb server. In my code I have used

os.system('./debug.sh')

where debug.sh content is

gdb main.x < debug >& debug.log

when I check debug.log I find the output as follows

Could not find platform independent libraries <prefix>
Could not find platform dependent libraries <exec_prefix>
Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>]
ImportError: No module named site

Although when I run the script directly from the terminal the command gets executed and Gdb client connects with no issues. I'm not sure if the issue is tied to Gdb command but when I tried executing other commands instead like echo I faced no issues. I tried doing as the error says and according to the answers to "ImportError: No module named site" on Windows and Python/IPython ImportError: no module named site I prepended those line to debug.sh

export PYTHONHOME=/usr/bin
export PYTHONPATH=/usr/lib/python2.7
export PATH=$PYTHONHOME:$PATH

But I still got

ImportError: No module named site

I also tried unsetting PYTHONHOME as the second link suggests but that didn't work. If I run a Python shell from the terminal and run

import site

I face no issues, So I am not really sure what's the issue here. I am working on a Redhat7 machine. Thanks in advance.


问:
Confusion in Regular expression in SpringBoot
Yesterday I was going through a question that goes like:

Write the regexp for "Id can have  words containing alphabets and numbers, and each word should be separated by a single space"
I wrote

[A-Za-z0-9/s]
```
<p>Now, when thinking about it, can the answer be</p>
<pre class="lang-none prettyprint-override"><code>[A-Za-z0-9 ]//{1}
</code>```

or was I right?

Body:
Yesterday I was going through a question that goes like:

Write the regexp for "Id can have  words containing alphabets and numbers, and each word should be separated by a single space"
I wrote

[A-Za-z0-9/s]

Now, when thinking about it, can the answer be

[A-Za-z0-9 ]//{1}

or was I right?


问:
React Context does not trigger component re-rendering
I am using context to store a gallery of products for a web store. I will be cropping out some code that is not relevant to the issue.

The gallery context provider looks like this.

```<code>
    export const GalleryProvider = (props) => {

    const [galleryItems, setGalleryItems] = useState()

    const uploadItemHandler = (data) => {
        setGalleryItems(prevState => [...prevState], data)
    }

    const galleryContext = {
        items: galleryItems,
        uploadItem: uploadItemHandler
    }

    return <GalleryContext.Provider value={galleryContext}>
        {props.children}
    </GalleryContext.Provider>

    }

</code>```

In the main component after my initial request to the db I am setting the fetched products in the context and I add the galleryCtx as a dependency in the useEffect hook.

```<code>
    export const FetchAllProducts = (props) => {
    const dbUrl = '*****'
    const [itemsInfo, setItemsInfo] = useState([])
    const loadedProducts= []

    const galleryCtx = useContext(GalleryContext)

    const setInitialGallery = () => {
        galleryCtx.items = itemsInfo
    }

        useEffect(() => {
            const fetchProducts = async () => {
               .
               . // loadedProducts is here
               .
                }
                setItemsInfo(loadedProducts)
                setInitialGallery()
            }
            fetchProducts().catch((error) => {
                console.log(error);
            })
        }, [galleryCtx])
    .
    .
    .

    }

</code>```

I also have a component that allows an admin to upload new products to the db and firebase storage. The successful uploads are also set and the change is visible in the provider's items array, however it does not trigger a rerender in the main component to reload the gallery. They are successfully rendered after a manual refresh of the page.

```<code>
    export const Upload = () => {
    const galleryCtx = useContext(GalleryContext)
    const authCtx = useContext(AuthContext)
    const dbUrl = '*****'
    .
    .
    .
    const currentProductInfo = {
        name,
        price,
        quantity,
        description,
    }
       const onUpload = () => {
        galleryCtx.items = galleryCtx.items.push(currentProductInfo)

    }

    .
    .
    .
    const uploadImage = (event) => {
        event.preventDefault()
        if (imageUpload === null) {
            alert("Please choose a file first!")
        }

        const imageRef = ref(storage, `images/${imageUpload.name}`)

        if (authCtx.isAdmin) {
            uploadBytes(imageRef, imageUpload).then((result) => {
                alert('Image uploaded')
                return getDownloadURL(result.ref)
            }).then((downloadUrl) => {
                currentImageInfo.imageUrl = downloadUrl
                fetch(dbUrl, {
                    method: 'POST',
                    headers: {
                        'content-type': 'application/json'
                    },
                    body: JSON.stringify(currentProductInfo)
                })
                onUpload()
                clearInputHandler()
            })
        }
    }
    }

</code>```

I tried setting galleryCtx.items as the dependency in the main component's useEffect but that triggers endless re-renders. Also tried useMemo to store the state of the gallery on the initial render but could not make it work.
I feel like I might be setting the items in the context the wrong way but can not figure out where my mistake is.

Body:
I am using context to store a gallery of products for a web store. I will be cropping out some code that is not relevant to the issue.

The gallery context provider looks like this.

    export const GalleryProvider = (props) => {

    const [galleryItems, setGalleryItems] = useState()

    const uploadItemHandler = (data) => {
        setGalleryItems(prevState => [...prevState], data)
    }

    const galleryContext = {
        items: galleryItems,
        uploadItem: uploadItemHandler
    }

    return <GalleryContext.Provider value={galleryContext}>
        {props.children}
    </GalleryContext.Provider>

    }

In the main component after my initial request to the db I am setting the fetched products in the context and I add the galleryCtx as a dependency in the useEffect hook.

    export const FetchAllProducts = (props) => {
    const dbUrl = '*****'
    const [itemsInfo, setItemsInfo] = useState([])
    const loadedProducts= []

    const galleryCtx = useContext(GalleryContext)

    const setInitialGallery = () => {
        galleryCtx.items = itemsInfo
    }

        useEffect(() => {
            const fetchProducts = async () => {
               .
               . // loadedProducts is here
               .
                }
                setItemsInfo(loadedProducts)
                setInitialGallery()
            }
            fetchProducts().catch((error) => {
                console.log(error);
            })
        }, [galleryCtx])
    .
    .
    .

    }

I also have a component that allows an admin to upload new products to the db and firebase storage. The successful uploads are also set and the change is visible in the provider's items array, however it does not trigger a rerender in the main component to reload the gallery. They are successfully rendered after a manual refresh of the page.

    export const Upload = () => {
    const galleryCtx = useContext(GalleryContext)
    const authCtx = useContext(AuthContext)
    const dbUrl = '*****'
    .
    .
    .
    const currentProductInfo = {
        name,
        price,
        quantity,
        description,
    }
       const onUpload = () => {
        galleryCtx.items = galleryCtx.items.push(currentProductInfo)

    }

    .
    .
    .
    const uploadImage = (event) => {
        event.preventDefault()
        if (imageUpload === null) {
            alert("Please choose a file first!")
        }

        const imageRef = ref(storage, `images/${imageUpload.name}`)

        if (authCtx.isAdmin) {
            uploadBytes(imageRef, imageUpload).then((result) => {
                alert('Image uploaded')
                return getDownloadURL(result.ref)
            }).then((downloadUrl) => {
                currentImageInfo.imageUrl = downloadUrl
                fetch(dbUrl, {
                    method: 'POST',
                    headers: {
                        'content-type': 'application/json'
                    },
                    body: JSON.stringify(currentProductInfo)
                })
                onUpload()
                clearInputHandler()
            })
        }
    }
    }

I tried setting galleryCtx.items as the dependency in the main component's useEffect but that triggers endless re-renders. Also tried useMemo to store the state of the gallery on the initial render but could not make it work.
I feel like I might be setting the items in the context the wrong way but can not figure out where my mistake is.


问:
How to display Link from a comment in DraftJs editor?
I am pretty new to draft Js.
I have tried using many ways to display link in draft js editor from a string where the string may be like:
Here is the story [HyperLink](https://exampleHyperLink.com) which I am working on. This is a demo test comment. Adding one more link for [Google](https://www.google.com).

Output would be like:
Here is the story HyperLink which I am working on. This is a demo test comment. Adding one more link for Google.

But in vain the result doesn't come with the links within the string, it comes as a plain text: Here is the story [HyperLink](https://exampleHyperLink.com) which I am working on. This is a demo test comment. Adding one more link for [Google](https://www.google.com)..

Please have a look and let me know what can be done to solve this. Thank you in advance.

Adding code snippet:

```<code>import React from 'react'
import { convertMarkdownToDraftjs } from '../functions/draftjsUtils'
import { Editor, CompositeDecorator, Entity, EditorState, ContentState } from 'draft-js'

/**
 * Readonly view which converts comment from markdown format and display in rich text format
 */
const RichTextView = ({ comment }) => {
  const decorators = [
    { strategy: findLinkEntities, component: Link }
  ]

  const commentValue = convertMarkdownToDraftjs(comment)
  const content = Content
State.createFromText(comment)
  const editorStateValue = EditorState.createWithContent(content, new CompositeDecorator(decorators))
  // console.log('comment', comment)
  // console.log('commentValue', commentValue)
  // console.log('content', content)
  // console.log('editorStateValue', editorStateValue)
  return (
    <Editor
      editorState={editorStateValue}
      readOnly
      data-test="draftjs-comment"
      decorators={decorators}
    />
  )
}

function findLinkEntities (contentBlock, callback) {
  contentBlock.findEntityRanges(
    (character) => {
      const entityKey = character.getEntity()
      return (
        entityKey !== null &&
        Entity.get(entityKey).getType() === 'LINK'
      )
    },
    callback
  )
}

const Link = (props) => {
  const { url } = Entity.get(props.entityKey).getData()
  return (
    <a href={url}>{props.children}</a>
  )
}

export default RichTextView
</code>```

Body:
I am pretty new to draft Js.
I have tried using many ways to display link in draft js editor from a string where the string may be like:
Here is the story [HyperLink](https://exampleHyperLink.com) which I am working on. This is a demo test comment. Adding one more link for [Google](https://www.google.com).

Output would be like:
Here is the story HyperLink which I am working on. This is a demo test comment. Adding one more link for Google.

But in vain the result doesn't come with the links within the string, it comes as a plain text: Here is the story [HyperLink](https://exampleHyperLink.com) which I am working on. This is a demo test comment. Adding one more link for [Google](https://www.google.com)..

Please have a look and let me know what can be done to solve this. Thank you in advance.

Adding code snippet:

import React from 'react'
import { convertMarkdownToDraftjs } from '../functions/draftjsUtils'
import { Editor, CompositeDecorator, Entity, EditorState, ContentState } from 'draft-js'

/**
 * Readonly view which converts comment from markdown format and display in rich text format
 */
const RichTextView = ({ comment }) => {
  const decorators = [
    { strategy: findLinkEntities, component: Link }
  ]

  const commentValue = convertMarkdownToDraftjs(comment)
  const content = Content
State.createFromText(comment)
  const editorStateValue = EditorState.createWithContent(content, new CompositeDecorator(decorators))
  // console.log('comment', comment)
  // console.log('commentValue', commentValue)
  // console.log('content', content)
  // console.log('editorStateValue', editorStateValue)
  return (
    <Editor
      editorState={editorStateValue}
      readOnly
      data-test="draftjs-comment"
      decorators={decorators}
    />
  )
}

function findLinkEntities (contentBlock, callback) {
  contentBlock.findEntityRanges(
    (character) => {
      const entityKey = character.getEntity()
      return (
        entityKey !== null &&
        Entity.get(entityKey).getType() === 'LINK'
      )
    },
    callback
  )
}

const Link = (props) => {
  const { url } = Entity.get(props.entityKey).getData()
  return (
    {props.children}
  )
}

export default RichTextView


问:
Math operation with values from userform's textbox
I'm looking for a solution to do math operations from six values entered from the left column. (photo)

I have tried both solutions that I found on web :
the 1st one is Application.Evaluate("TextBox2.Value - TextBox4.Value")
the 2nd one is CStr(CDbl(TextBox2.Text) - CDbl(TextBox3.Text))
but they returned either 0 or the excel doesn’t recognize my formula...

Any ideas? Thanks in advance

My code was as below

```<code>Dim ajout As Long
Dim NiveauTN As Long
ajout = Range("A" & Rows.Count).End(xlUp).Row + 1
Rows(ajout).Insert 'insertion d'une ligne juste en dessous du tableau
Range("A" & ajout).Value = TextBox1.Value
Range("A" & ajout).Offset(0, 1).Value = TextBox2.Value
Range("A" & ajout).Offset(0, 2).Value = Application.Evaluate("TextBox2.Value-TextBox3.Value")
'Range("A" & ajout).Offset(0, 2).Value = CStr(CDbl(TextBox2.Text) - CDbl(TextBox3.Text))
'Range("A" & ajout).Offset(0, 3).Value = Application.Evaluate("TextBox2.Value - TextBox4.Value")
'Range("A" & ajout).Offset(0, 4).Value = Application.Evaluate("TextBox2.Value - TextBox5.Value")
'Range("A" & ajout).Offset(0, 5).Value = TextBox2.Value - TextBox6.Value
'Range("A" & ajout).Offset(0, 6).Value = TextBox2.Value - TextBox7.Value
'Range("A" & ajout).Offset(0, 7).Value = TextBox2.Value - TextBox8.Value
</code>```

Body:
I'm looking for a solution to do math operations from six values entered from the left column. (photo)

I have tried both solutions that I found on web :
the 1st one is Application.Evaluate("TextBox2.Value - TextBox4.Value")
the 2nd one is CStr(CDbl(TextBox2.Text) - CDbl(TextBox3.Text))
but they returned either 0 or the excel doesn’t recognize my formula...

Any ideas? Thanks in advance

My code was as below

Dim ajout As Long
Dim NiveauTN As Long
ajout = Range("A" & Rows.Count).End(xlUp).Row + 1
Rows(ajout).Insert 'insertion d'une ligne juste en dessous du tableau
Range("A" & ajout).Value = TextBox1.Value
Range("A" & ajout).Offset(0, 1).Value = TextBox2.Value
Range("A" & ajout).Offset(0, 2).Value = Application.Evaluate("TextBox2.Value-TextBox3.Value")
'Range("A" & ajout).Offset(0, 2).Value = CStr(CDbl(TextBox2.Text) - CDbl(TextBox3.Text))
'Range("A" & ajout).Offset(0, 3).Value = Application.Evaluate("TextBox2.Value - TextBox4.Value")
'Range("A" & ajout).Offset(0, 4).Value = Application.Evaluate("TextBox2.Value - TextBox5.Value")
'Range("A" & ajout).Offset(0, 5).Value = TextBox2.Value - TextBox6.Value
'Range("A" & ajout).Offset(0, 6).Value = TextBox2.Value - TextBox7.Value
'Range("A" & ajout).Offset(0, 7).Value = TextBox2.Value - TextBox8.Value


问:
How to maintain the sequence of events while forwarding it to external system
Suppose I have 3 different type of services:
Service A ( distributed )
Service B ( distributed )
Service C ( distributed )

Now that each of them is producing events to my kafka. [ please decide whether a single topic or multiple topic for the solution ]

Each of events have the timestamp in their header [assuming all are unique, somehow, but even if 2 messages can have same timestamp due to highly distributed nature of the system]

Now,
I want to forward these events, IN ORDER of their sequence to some third party, how can I do that ?

I understand that all the events can map to a single partition which will lead to a single consumer which will ensure ordering, and then I can send / forward it to my third party.
But a single consumer means, a single threaded program.

But is there any scalable solution possible for this ?
Be it kafka or any other solution , but scalable, events are at 1000 events / second