问:
Adding tooltip to folium.features.GeoJson from a geopandas dataframe
I am having issues adding tooltips to my folium.features.GeoJson. I can't get columns to display from the dataframe when I select them.

```<code>feature = folium.features.GeoJson(df.geometry,
  name='Location',
  style_function=style_function,
  tooltip=folium.GeoJsonTooltip(fields= [df.acquired],aliases=["Time"],labels=True))
  ax.add_child(feature)

</code>```

For some reason when I run the code above it responds with
Name: acquired, Length: 100, dtype: object is not available in the data. Choose from: ().
I can't seem to link the data to my tooltip.

Body:
I am having issues adding tooltips to my folium.features.GeoJson. I can't get columns to display from the dataframe when I select them.

feature = folium.features.GeoJson(df.geometry,
  name='Location',
  style_function=style_function,
  tooltip=folium.GeoJsonTooltip(fields= [df.acquired],aliases=["Time"],labels=True))
  ax.add_child(feature)

For some reason when I run the code above it responds with
Name: acquired, Length: 100, dtype: object is not available in the data. Choose from: ().
I can't seem to link the data to my tooltip.

Body:
have made your code a MWE by including some data

two key issues with your code

need to pass properties not just geometry to folium.features.GeoJson() Hence passed df instead of df.geometry

folium.GeoJsonTooltip() takes a list of properties (columns) not an array of values.  Hence passed ["acquired"] instead of array of values from a dataframe column

implied issue with your code.  All dataframe columns need to contain values that can be serialised to JSON.  Hence conversion of acquired to string and drop()

import geopandas as gpd
import pandas as pd
import shapely.wkt
import io
import folium

df = pd.read_csv(io.StringIO("""ref;lanes;highway;maxspeed;length;name;geometry
A3015;2;primary;40 mph;40.68;Rydon Lane;MULTILINESTRING ((-3.4851169 50.70864409999999, -3.4849879 50.7090007), (-3.4857269 50.70693379999999, -3.4853034 50.7081574), (-3.488620899999999 50.70365289999999, -3.4857269 50.70693379999999), (-3.4853034 50.7081574, -3.4851434 50.70856839999999), (-3.4851434 50.70856839999999, -3.4851169 50.70864409999999))
A379;3;primary;50 mph;177.963;Rydon Lane;MULTILINESTRING ((-3.4763853 50.70886769999999, -3.4786112 50.70811229999999), (-3.4746017 50.70944449999999, -3.4763853 50.70886769999999), (-3.470350900000001 50.71041779999999, -3.471219399999999 50.71028909999998), (-3.465049699999999 50.712158, -3.470350900000001 50.71041779999999), (-3.481215600000001 50.70762499999999, -3.4813909 50.70760109999999), (-3.4934747 50.70059599999998, -3.4930204 50.7007898), (-3.4930204 50.7007898, -3.4930048 50.7008015), (-3.4930048 50.7008015, -3.4919513 50.70168349999999), (-3.4919513 50.70168349999999, -3.49137 50.70213669999998), (-3.49137 50.70213669999998, -3.4911565 50.7023015), (-3.4911565 50.7023015, -3.4909108 50.70246919999999), (-3.4909108 50.70246919999999, -3.4902349 50.70291189999999), (-3.4902349 50.70291189999999, -3.4897693 50.70314579999999), (-3.4805021 50.7077218, -3.4806265 50.70770150000001), (-3.488620899999999 50.70365289999999, -3.4888806 50.70353719999999), (-3.4897693 50.70314579999999, -3.489176800000001 50.70340539999999), (-3.489176800000001 50.70340539999999, -3.4888806 50.70353719999999), (-3.4865751 50.70487679999999, -3.4882604 50.70375799999999), (-3.479841700000001 50.70784459999999, -3.4805021 50.7077218), (-3.4882604 50.70375799999999, -3.488620899999999 50.70365289999999), (-3.4806265 50.70770150000001, -3.481215600000001 50.70762499999999), (-3.4717096 50.71021009999998, -3.4746017 50.70944449999999), (-3.4786112 50.70811229999999, -3.479841700000001 50.70784459999999), (-3.471219399999999 50.71028909999998, -3.4717096 50.71021009999998))"""),
           sep=";")

df = gpd.GeoDataFrame(df, geometry=df["geometry"].apply(shapely.wkt.loads), crs="epsg:4326")
df["acquired"] = pd.date_range("8-feb-2022", freq="1H", periods=len(df))

def style_function(x):
    return {"color":"blue", "weight":3}

ax = folium.Map(
    location=[sum(df.total_bounds[[1, 3]]) / 2, sum(df.total_bounds[[0, 2]]) / 2],
    zoom_start=12,
)

# data time is not JSON serializable...
df["tt"] = df["acquired"].dt.strftime("%Y-%b-%d %H:%M")

feature = folium.features.GeoJson(df.drop(columns="acquired"),
  name='Location',
  style_function=style_function,
  tooltip=folium.GeoJsonTooltip(fields= ["tt"],aliases=["Time"],labels=True))
ax.add_child(feature)


来源: stackexchange

问:
Vue Jest Framework | Uncovered lines are show as invalid
I am using jest framework for vue.js unit test cases. My issue is my file lines of code is 31. But showing uncovered line is 39, 40. Is there any issue in config related things.

What is the issue here. I am facing this issue in all my .vue files. How to rectify this

答:
```<code>"mapCoverage": true
</code>```

Add this link in your jest.config.json file, then try it will work.

ContentLicense: CC BY-SA 4.0

Body:
"mapCoverage": true

Add this link in your jest.config.json file, then try it will work.


问:
Can we get data type of a field value from Firestore DB using Java?
I am fetching a JSON document from Firestore DB using java. I need to know the data type of the fields(values of json keys) in the JSON. Is there any way to know if a field value in Json is a String/Boolean/Number?</p>

答:
```<code>System.out.println(document.get("fieldname").getClass().getSimpleName());
</code>```

prints something like:

field name : geo

field type : GeoPoint

field name : number

field type : Long

field name : field1

field type : String

field name : array

field type : ArrayList

field name : time

field type : Timestamp

Body:
System.out.println(document.get("fieldname").getClass().getSimpleName());

prints something like:

field name : geo

field type : GeoPoint

field name : number

field type : Long

field name : field1

field type : String

field name : array

field type : ArrayList

field name : time

field type : Timestamp


问:
How to Convert 2022-02-08T09:34:35.000Z this date and time into dd/mm/yyyy hh:mm;ss in javascript?
I am getting 2022-02-08T09:34:35.000Z this response from an API.

I am trying to convert it into a simple format like- 08-02-2022 09:34:35

答:
You can use the Date.prototype.toLocaleString()</p>
```<code>let date = new Date();
date = date.toLocaleString()
</code>```

Body:
You can use the Date.prototype.toLocaleString()

let date = new Date();
date = date.toLocaleString()


问:
VS Code Remote - Can't run 'code' command in WSL Ubuntu 18 or WSL 2 Ubuntu 20 - wrong path
I'm having an issue when I try to run the code command from Visual Studio Code in WSL Ubuntu. I get the following error:

```<code>$ code .

/mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: 63: /mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: /home/barry/.vscode/bin/899d46d82c4c95423fb7e10e68eba52050e30ba3/bin/remote-cli/code: not found
</code>```

When I run the following, it installs the VS Code Server and the command works as expected:

```<code>$ /mnt/c/Users/Name/AppData/Local/Programs/Microsoft\ VS\ Code/bin/code .
</code>```

When I run which -a code, I can see I have two paths related to this command and I believe the correct one is /mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code, but I don't know how to remove the first one or how it even related two paths to this command in the first place?

```<code>barry@RandomName:~$ which -a code
/mnt/c/Program Files/Microsoft VS Code/bin/code
/mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code
</code>```

Can anyone help please?

答: A simple sudo apt update -y and then rerunning code . fixed this for me.

Body:
I'm having an issue when I try to run the code command from Visual Studio Code in WSL Ubuntu. I get the following error:

$ code .

/mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: 63: /mnt/c/Users/Name/.vscode/extensions/ms-vscode-remote.remote-wsl-0.64.2/scripts/wslCode.sh: /home/barry/.vscode/bin/899d46d82c4c95423fb7e10e68eba52050e30ba3/bin/remote-cli/code: not found

When I run the following, it installs the VS Code Server and the command works as expected:

$ /mnt/c/Users/Name/AppData/Local/Programs/Microsoft\ VS\ Code/bin/code .

When I run which -a code, I can see I have two paths related to this command and I believe the correct one is /mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code, but I don't know how to remove the first one or how it even related two paths to this command in the first place?

barry@RandomName:~$ which -a code
/mnt/c/Program Files/Microsoft VS Code/bin/code
/mnt/c/Users/Name/AppData/Local/Programs/Microsoft VS Code/bin/code

Can anyone help please?


问:
How can I efficiently connect a web frontend to my server application?
Our server product is currently in desktop form and we're trying to move it over to a service while providing a web-based frontend to make it easier to monitor and administrate.  Not having a ton of web experience I'm struggling with figuring out the best way to do this.

For a first pass, our requirements are pretty basic.  We want to be able to view the status of the various components of our system and real-time monitor the logs that it spits out.

My thought is to add some sort of TCP-based interface to our server application that can be used by a separate web framework running on a different server somewhere.  For basic status messages this seems straightforward: the user connects to the web interface, it queries the server application for the current status, then displays that status to the user.  It gets a bit more complicated when it comes to the log streaming.  I'm concerned that constantly requesting the latest logs from the server application, especially if there is a separate connection for each user, will put more stress on the server application than we would like.

It seems that ideally the web server will open a single persistent connection to the server application, and the server application will push data to the web server anytime the status changes or a new message is logged.  The web server will then cache this data and "forward" it to all connected users.  This way the amount of work that the server application is doing is largely fixed and is not dependent on the number of users currently connected to the server.

My questions are:

Does this fundamentally make sense?

How should I go about doing this?  Is it something that a web framework should be able to handle (I'm leaning towards lift, but not tied to anything right now) or will I need to write my own intermediate caching layer that keeps a persistent connection to the server application, but serves the data to the web server as needed?  Is my best bet to do this from scratch or are there already well tested solutions for this type of thing?

As I mentioned I'm a pretty big noob when it comes to any sort of web development so anything that even just points me in the right direction will help.

答:
Is your product a hardware device that puts out info to something like a syslog, or a software app that monitors the info, and has a real-time log display and stores that info in text log files? You didn't mention anything about pulling the data from a database, so I'm assuming it's not storing it in one?

I'm not sure I understand completely the pieces of the puzzle, but with that in mind, a couple thoughts come to mind...

Have your server app store that log data in a db somewhere that the web server can access, then use an AJAX-enabled web frontend to refresh the 'log view' section of the web page every x seconds looking for just new entries to the log to append to the view

XMPP/Jabber might also be able to play a part in what you're doing - the protocol is used in some IM clients for real-time messaging. It sounds a bit like you're wanting this to work in a 'push messaging' kind of way. So, possibly it could make sense to setup a jabber server alongside the web server (could probably be the same server, depending on load), and then in your server app send the messages to the jabber server via XMPP, which will relay them out to the listeners, which would be XMPP/Jabber clients - I know googletalk can act as a client, and iChat can, and I believe some others. Or you can possibly write a Java client to run in the browser (I'm not a Java person, though...)
And then write a minimal web app to handle the administration side of things for the app.
You could probably also handle the administration side of things over XMPP - send it a message to 'change x setting to y' and possibly do it all on just the one server without a need for a separate web/jabber server.

But these are things I'd look at.

www.jivesoftware.org still has their jabber server available free I believe, and I have no association with them - just something I experimented with at one time and thought it was very interesting.

Greg

ContentLicense: CC BY-SA 3.0


问:
Filtering for email address with a dot
I am trying to filter only the email with dot (Sam.Smith@forfun.com). But all email would be displayed to me. Is this somehow possible to get only "Sam.Smith@forfun.com" this?

```<code>PS C:\Users\Rayman>  Get-AzureADUser -SearchString "Sam".AlternateEmailAddresses
PS C:\Users\Rayman>  (Get-AzureADUser -SearchString "Sam Smith").UserPrincipalName
PS C:\Users\Rayman> Get-AzureADUser -SearchString "Sam Smith" | Select Mail
Sam.Smith@forfun.com
samsmith@forfun.com
</code>```

I have tried many variants without success.

答:
Thank You Abraham Zinala for your suggestion posting this as solution to help other community member if they encounter for same requirement.

Note : Use PowerShell Version 7+ Version.

PowerShell Script :

```<code>(Get-AzureADUser -SearchString "Sam Smith"| Select Mail)[0]
</code>```

Title: Filtering for email address with a dot

Body:
I am trying to filter only the email with dot (Sam.Smith@forfun.com). But all email would be displayed to me. Is this somehow possible to get only "Sam.Smith@forfun.com" this?

PS C:\Users\Rayman>  Get-AzureADUser -SearchString "Sam".AlternateEmailAddresses
PS C:\Users\Rayman>  (Get-AzureADUser -SearchString "Sam Smith").UserPrincipalName
PS C:\Users\Rayman> Get-AzureADUser -SearchString "Sam Smith" | Select Mail
Sam.Smith@forfun.com
samsmith@forfun.com

I have tried many variants without success.

Body:
Thank You Abraham Zinala for your suggestion posting this as solution to help other community member if they encounter for same requirement.

Note : Use PowerShell Version 7+ Version.

PowerShell Script :

(Get-AzureADUser -SearchString "Sam Smith"| Select Mail)[0]


问:
How to detect if left mousebutton is being held down with SDL2
I know how to use events to detect when the mouse button is pressed, however, how do detect if a mouse button is currently held down? Note I am not asking how to get it from an event.

I have not tried anything apart from SDL_GetMouseState(&x, &y); however it seems to only return the X and Y position of the mouse.

答:
From my understanding a state machine should do the trick.
If you detect a MB Down event (SDL_PRESSED), set a variable to hold that information for you, if you detect a MB Up event (SDL_RELEASED), reset the variable.
So reading the content of this variable would return the "held down" information.

Side info: Depending on the mouse you are using the button state may bounce between high and low state. If that is the case, add a samll (~1ms) delay.

Because i do not have SDL2 currently on my machine, i can not provide code.
Sorry for that.

In case you have trouble finding the SDL2 docu for this because they reworked their wiki, here is a link: https://wiki.libsdl.org/SDL_MouseButtonEvent

But let me know if this was helpful.


问:
Why can't I use <Class>.this in anonymous class?
I recently use this code, and realize that in anonymous class, I can't access the instance by .this, like this:

```<code>Sprite sprFace = new Sprite() {

    @Override
    protected void onManagedUpdate(float pSecondElapsed) {
        runOnUpdateThread(new Runnable() {

        @Override
        protected void run() {
            Sprite.this.getParent().detach(Sprite.this); // Here
        }});
    }

};
</code>```

I know how to solve it (just declare a "me" variable), but I need to know why I can't use <Class>.this?

答:
The type of the outer object is not Sprite, but rather an anonymous subclass of Sprite and you have no way of naming this anonymous subclass in your code.

In this case you need a name to refer to and therefore an anonymous class will not do the job. You can use a local class instead (which behaves as an anonymous class with a name). In the code block, you can write:

```<code>class MySprite extends Sprite {

    @Override
    protected void onManagedUpdate(float pSecondElapsed) {
        runOnUpdateThread(new Runnable() {
            MySprite.this.getParent().detach(MySprite.this); // Here
        });
    }

};

Sprite sprFace = new MySprite();
</code>```

Body:
I recently use this code, and realize that in anonymous class, I can't access the instance by .this, like this:

Sprite sprFace = new Sprite() {

    @Override
    protected void onManagedUpdate(float pSecondElapsed) {
        runOnUpdateThread(new Runnable() {

        @Override
        protected void run() {
            Sprite.this.getParent().detach(Sprite.this); // Here
        }});
    }

};

I know how to solve it (just declare a "me" variable), but I need to know why I can't use <Class>.this?

Body:
The type of the outer object is not Sprite, but rather an anonymous subclass of Sprite and you have no way of naming this anonymous subclass in your code.

In this case you need a name to refer to and therefore an anonymous class will not do the job. You can use a local class instead (which behaves as an anonymous class with a name). In the code block, you can write:

class MySprite extends Sprite {

    @Override
    protected void onManagedUpdate(float pSecondElapsed) {
        runOnUpdateThread(new Runnable() {
            MySprite.this.getParent().detach(MySprite.this); // Here
        });
    }

};

Sprite sprFace = new MySprite();


问:
How to get template class template parameter?
I have a template class and want to know, how to get template class variable type when it is used as a template parameter of function.
I tried to do the following

#include <iostream>
#include <type_traits>

using namespace std;

template <typename T>
class foo
{
};

template <typename templateClass>
void f()
{
    if (is_same<typename templateClass::T, int>::value)
        cout << "int";
    else if (is_same<typename templateClass::T, double>::value)
        cout << "double";
    else
        cout << "Unknown type";
}

int main()
{
    f<foo<double>>();

    return 0;
}
```
<p>This code does not compile, because <code>no type named 'T' in 'foo<double>'</code>.
Then I changed it a little bit:</p>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
#include <type_traits>

using namespace std;

template <typename T>
class foo
{
public:
    using Type = T; //can't write : using T = T;
};

template <typename templateClass>
void f()
{
    if (is_same<typename templateClass::Type, int>::value)
        cout << "int";
    else if (is_same<typename templateClass::Type, double>::value)
        cout << "double";
    else
        cout << "Unknown type";
}

int main()
{
    f<foo<double>>();

    return 0;
}
</code>```

Now it works fine, but I had to rename template parameter. Can I get template parameter value without renaming it with using?

答:
You can create traits to extract that information without changing originel types.

```<code>template <typename T>
struct template_parameter;

template <template <typename ...> class C, typename T>
struct template_parameter<C<T>>
{
    using type = T;
};

template <typename T>
using template_parameter_t = typename template_parameter<T>::type;
</code>```

and then

```<code>template <typename templateClass>
void f()
{
    if constexpr (std::is_same_v<template_parameter_t<templateClass>, int>)
        std::cout << "int";
    else if constexpr (std::is_same_v<template_parameter_t<templateClass>, double>)
        std::cout << "double";
    else
        std::cout << "Unknown type";
}
</code>```

Demo

Body:
I have a template class and want to know, how to get template class variable type when it is used as a template parameter of function.
I tried to do the following

#include <iostream>
#include <type_traits>

using namespace std;

template <typename T>
class foo
{
};

template <typename templateClass>
void f()
{
    if (is_same<typename templateClass::T, int>::value)
        cout << "int";
    else if (is_same<typename templateClass::T, double>::value)
        cout << "double";
    else
        cout << "Unknown type";
}

int main()
{
    f<foo<double>>();

    return 0;
}

This code does not compile, because no type named 'T' in 'foo<double>'.
Then I changed it a little bit:

#include <iostream>
#include <type_traits>

using namespace std;

template <typename T>
class foo
{
public:
    using Type = T; //can't write : using T = T;
};

template <typename templateClass>
void f()
{
    if (is_same<typename templateClass::Type, int>::value)
        cout << "int";
    else if (is_same<typename templateClass::Type, double>::value)
        cout << "double";
    else
        cout << "Unknown type";
}

int main()
{
    f<foo<double>>();

    return 0;
}

Now it works fine, but I had to rename template parameter. Can I get template parameter value without renaming it with using?

Body:
You can create traits to extract that information without changing originel types.

template <typename T>
struct template_parameter;

template <template <typename ...> class C, typename T>
struct template_parameter<C<T>>
{
    using type = T;
};

template <typename T>
using template_parameter_t = typename template_parameter<T>::type;

and then

template <typename templateClass>
void f()
{
    if constexpr (std::is_same_v<template_parameter_t<templateClass>, int>)
        std::cout << "int";
    else if constexpr (std::is_same_v<template_parameter_t<templateClass>, double>)
        std::cout << "double";
    else
        std::cout << "Unknown type";
}

Demo


问:
Want to make standalone program with cmake
My program uses giblib and Imlib2 library and it is built with cmake.

It works perfectly in my computer but not in other's.

I guess the reason is I installed every library what my program needs but other's doesn't.

My goal is making standalone program. (don't need to install any other library addtionally)

What should I add in cmake file?

projectDef.cmake source code

```<code>file (GLOB PLATFORM RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
    X11/[^.]*.cpp
    X11/[^.]*.h
    X11/[^.]*.cmake
    )

SOURCE_GROUP(X11 FILES ${PLATFORM})

add_definitions(
)

set (SOURCES
    ${SOURCES}
    ${PLATFORM}
    )

add_x11_plugin(${PROJECT_NAME} SOURCES)

target_link_libraries(${PROJECT_NAME}
    ${PLUGIN_INTERNAL_DEPS}
    )

include_directories(/usr/include/giblib)
include_directories(/usr/include/X11)

target_link_libraries(MyProject X11)
target_link_libraries(MyProject Imlib2)
target_link_libraries(MyProject giblib)
</code>```

CMakeList.txt source code

```<code>cmake_minimum_required (VERSION 2.6)
set (CMAKE_BACKWARDS_COMPATIBILITY 2.6)
set(BUILD_SHARED_LIBS OFF)
set(CMAKE_EXE_LINKER_FLAGS "-static")

Project(${PLUGIN_NAME})

file (GLOB GENERAL RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
    [^.]*.cpp
    [^.]*.h
    [^.]*.cmake
    )

include_directories(${PLUGIN_INCLUDE_DIRS})

SET_SOURCE_FILES_PROPERTIES(
    ${GENERATED}
    PROPERTIES
        GENERATED 1
    )

SOURCE_GROUP(Generated FILES
    ${GENERATED}
    )

SET( SOURCES
    ${GENERAL}
    ${GENERATED}
    )

include_platform()
</code>```

答:
Try starting with this options in your root CMakeLists.txt:

```<code>set(BUILD_SHARED_LIBS OFF)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static")
</code>```

BUILD_SHARED_LIBS is only needed if your project has its own libraries (add_library).

With the -static linker flag, you need static libs for ALL your additional libraries too! One common problem when static linking is to avoid circular dependencies.

Body:
My program uses giblib and Imlib2 library and it is built with cmake.

It works perfectly in my computer but not in other's.

I guess the reason is I installed every library what my program needs but other's doesn't.

My goal is making standalone program. (don't need to install any other library addtionally)

What should I add in cmake file?

projectDef.cmake source code

file (GLOB PLATFORM RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
    X11/[^.]*.cpp
    X11/[^.]*.h
    X11/[^.]*.cmake
    )

SOURCE_GROUP(X11 FILES ${PLATFORM})

add_definitions(
)

set (SOURCES
    ${SOURCES}
    ${PLATFORM}
    )

add_x11_plugin(${PROJECT_NAME} SOURCES)

target_link_libraries(${PROJECT_NAME}
    ${PLUGIN_INTERNAL_DEPS}
    )

include_directories(/usr/include/giblib)
include_directories(/usr/include/X11)

target_link_libraries(MyProject X11)
target_link_libraries(MyProject Imlib2)
target_link_libraries(MyProject giblib)

CMakeList.txt source code

cmake_minimum_required (VERSION 2.6)
set (CMAKE_BACKWARDS_COMPATIBILITY 2.6)
set(BUILD_SHARED_LIBS OFF)
set(CMAKE_EXE_LINKER_FLAGS "-static")

Project(${PLUGIN_NAME})

file (GLOB GENERAL RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
    [^.]*.cpp
    [^.]*.h
    [^.]*.cmake
    )

include_directories(${PLUGIN_INCLUDE_DIRS})

SET_SOURCE_FILES_PROPERTIES(
    ${GENERATED}
    PROPERTIES
        GENERATED 1
    )

SOURCE_GROUP(Generated FILES
    ${GENERATED}
    )

SET( SOURCES
    ${GENERAL}
    ${GENERATED}
    )

include_platform()

Body:
Try starting with this options in your root CMakeLists.txt:

set(BUILD_SHARED_LIBS OFF)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static")

BUILD_SHARED_LIBS is only needed if your project has its own libraries (add_library).

With the -static linker flag, you need static libs for ALL your additional libraries too! One common problem when static linking is to avoid circular dependencies.


问:
Excel VBA, a good way to avoid conflict when a same text file is possible to be opened by two different computer at the same time?
Within Computer-A there is a shared folder

Main folder ---> csv folder ---> tmp folder

Inside Main folder : wb-A.xlsm and wb-B.xlsm

Inside csv folder : transaction.csv, customer.csv, supplier.csv and item.csv

Inside tmp folder : nothing

User-A in computer-A always use/open wb-A.xlsm to input data, either if there is a new transaction, new cust/sup, or new item where each will be put in the csv file respectively.

User-B in computer-B (connected to the network) always use/open the wb-B.xlsm (which in that shared folder) and move the data (if any) in those csv files to the tables within wb-B.xlsm. Each table is a named range : transaction, customer, supplier, and item.

The code for writing to the csv files (done by user-A, wb-A.xlsm, computer-A) , I use open the csv for append as #1. The code for getting the data from the csv file (done by user-B, wb-B.xlsm, computer-B), I use QueryTables.Add(Connection:="TEXT;" ....).

Because I'm worried there will be a conflict when user-A is writing data to the csv file and user-B  is moving data from the same csv file at the same time, what I've tried so far is writing a same code in both wb to check if the tmpFolder is empty. If it's empty, then create a dummy file inside the tmpFolder, do things to the csv file then delete the dummy file. If it's not empty, it will do a checking-loop until the tmpFolder empty is true. If the checking loop is more than 10 seconds, then it exit the sub, meaning the writing/moving data to/from the csv file failed.

So the dummy file in the tmp folder is just for a sign something like "someone is using the files in the csv folder, don't do anything to the files in the csv folder".

The code for a new customer/supplier/item in wb-A.xlsm (simplified) :

```<code>Sub WriteToCsv()

csvData = "Mr. John Smith": x = "supplier"
p = ActiveWorkbook.Path & "\csv\"
pTmp = p & "tmp\": pfTmp = pTmp & "Z.txt"

'if pTmp empty create Z.txt file,
'if pTmp not empty loop until pTmp empty
oStart = Timer
Do
    If Dir(pTmp) = "" Then
        Open pfTmp For Output As #1: Close #1
        cek = "True"
    Else
        cek = "False"
        If Timer - oStart > 10 Then _
            MsgBox "Writing to csv file failed": Exit Sub
    End If
Loop Until cek = "True"

'do things to the csv file
    'If cek = "True" Then
        CSVFile = p & x & ".csv"
        Open CSVFile For Append As #1
        Print #1, csvData: Close #1
        Kill pfTmp 'delete the dummy file in tmp folder
    'End If

End Sub
</code>```

The code in wb-B.xlsm :

```<code>Sub AddNewDataIfAny()
p = ThisWorkbook.Path & "\csv"
pTmp = p & "\tmp\": pfTmp = pTmp & "Z.txt"

'if pTmp empty create Z.txt file,
'if pTmp not empty loop until pTmp empty
oStart = Timer
Do
    If Dir(pTmp) = "" Then
        Open pfTmp For Output As #1: Close #1
        cek = "True"
    Else
        cek = "False"
        If Timer - oStart > 10 Then _
            MsgBox "Getting data from csv file to this wb failed": Exit Sub
    End If
Loop Until cek = "True"

'do things to the csv file
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(p)
    For Each oFile In oFolder.Files
        pf = p + "\" + oFile.Name
            If FileLen(pf) <> 0 Then
                fn = Split(oFile.Name, ".")(0)
                If fn = "Data" Then _
                      Set ws = Sheets("DATA") Else Set ws = Sheets("TABEL")
                Set rg = ws.Range(fn)
                Set rg = rg.Resize(1, 1).Offset(rg.Rows.Count, 0)
                    With ws.QueryTables.Add(Connection:="TEXT;" & pf, _
                                    Destination:=ws.Range(rg.Address))
                        .TextFileParseType = xlDelimited
                        .TextFileCommaDelimiter = True
                        .Refresh
                        .Delete
                    End With
                Open pf For Output As #1: Close #1 'emptying the csv file
            End If
    Next oFile
Kill pfTmp 'emptying the tmpFolder

End Sub
</code>```

Although it seems the code work OK, but I'm not so sure if the code will be error-free all the time. So my question : is there a better way to write the code in this kind of situation ?

Any kind of help would be much appreciated.

Thank you in advanced.

答:
One way for synchronization is to make use of a Mutex object. There is a Mutex object  sample in VBA here

As far as I know, Mutex guaranties access to only one thread at a time in AddNewDataIfAny(). So:

```<code>    Private Const ERROR_ALREADY_EXISTS = 183&
Private Const MUTEX_ALL_ACCESS = &H1F0001

Private Declare PtrSafe Function CreateMutex Lib "kernel32" Alias "CreateMutexA" (ByVal lpMutexAttributes As Long, ByVal bInitialOwner As Long, ByVal lpName As String) As Long
Private Declare PtrSafe Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare PtrSafe Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare PtrSafe Function OpenMutex Lib "kernel32" Alias "OpenMutexA" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal lpName As String) As Long
Private Declare PtrSafe Function ReleaseMutex Lib "kernel32" (ByVal hMutex As Long) As Long

Private Sub Workbook_Open()
    myMutex = CreateMutex(0, 1, "myMutex")
    Dim er As Long: er = Err.LastDllError
    If er = 0 Then
        MsgBox "myMutex Created"
    ElseIf er = ERROR_ALREADY_EXISTS Then
        MsgBox "mutex previously created"
        myMutex = OpenMutex(MUTEX_ALL_ACCESS, 0, "myMutex")
    Else
        MsgBox "mutex creation failed"
    End If
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    CloseHandle myMutex
End Sub

Private Sub doSomeCriticalTask()
    WaitForSingleObject myMutex, 20000 ' say we can wait for 20 seconds
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' do critical section code, access shared data safely
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''
    AddNewDataIfAny()
    ReleaseMutex myMutex
End Sub
</code>```

Body:
Within Computer-A there is a shared folder

Main folder ---> csv folder ---> tmp folder

Inside Main folder : wb-A.xlsm and wb-B.xlsm

Inside csv folder : transaction.csv, customer.csv, supplier.csv and item.csv

Inside tmp folder : nothing

User-A in computer-A always use/open wb-A.xlsm to input data, either if there is a new transaction, new cust/sup, or new item where each will be put in the csv file respectively.

User-B in computer-B (connected to the network) always use/open the wb-B.xlsm (which in that shared folder) and move the data (if any) in those csv files to the tables within wb-B.xlsm. Each table is a named range : transaction, customer, supplier, and item.

The code for writing to the csv files (done by user-A, wb-A.xlsm, computer-A) , I use open the csv for append as #1. The code for getting the data from the csv file (done by user-B, wb-B.xlsm, computer-B), I use QueryTables.Add(Connection:="TEXT;" ....).

Because I'm worried there will be a conflict when user-A is writing data to the csv file and user-B  is moving data from the same csv file at the same time, what I've tried so far is writing a same code in both wb to check if the tmpFolder is empty. If it's empty, then create a dummy file inside the tmpFolder, do things to the csv file then delete the dummy file. If it's not empty, it will do a checking-loop until the tmpFolder empty is true. If the checking loop is more than 10 seconds, then it exit the sub, meaning the writing/moving data to/from the csv file failed.

So the dummy file in the tmp folder is just for a sign something like "someone is using the files in the csv folder, don't do anything to the files in the csv folder".

The code for a new customer/supplier/item in wb-A.xlsm (simplified) :

Sub WriteToCsv()

csvData = "Mr. John Smith": x = "supplier"
p = ActiveWorkbook.Path & "\csv\"
pTmp = p & "tmp\": pfTmp = pTmp & "Z.txt"

'if pTmp empty create Z.txt file,
'if pTmp not empty loop until pTmp empty
oStart = Timer
Do
    If Dir(pTmp) = "" Then
        Open pfTmp For Output As #1: Close #1
        cek = "True"
    Else
        cek = "False"
        If Timer - oStart > 10 Then _
            MsgBox "Writing to csv file failed": Exit Sub
    End If
Loop Until cek = "True"

'do things to the csv file
    'If cek = "True" Then
        CSVFile = p & x & ".csv"
        Open CSVFile For Append As #1
        Print #1, csvData: Close #1
        Kill pfTmp 'delete the dummy file in tmp folder
    'End If

End Sub

The code in wb-B.xlsm :

Sub AddNewDataIfAny()
p = ThisWorkbook.Path & "\csv"
pTmp = p & "\tmp\": pfTmp = pTmp & "Z.txt"

'if pTmp empty create Z.txt file,
'if pTmp not empty loop until pTmp empty
oStart = Timer
Do
    If Dir(pTmp) = "" Then
        Open pfTmp For Output As #1: Close #1
        cek = "True"
    Else
        cek = "False"
        If Timer - oStart > 10 Then _
            MsgBox "Getting data from csv file to this wb failed": Exit Sub
    End If
Loop Until cek = "True"

'do things to the csv file
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFolder = oFSO.GetFolder(p)
    For Each oFile In oFolder.Files
        pf = p + "\" + oFile.Name
            If FileLen(pf) <> 0 Then
                fn = Split(oFile.Name, ".")(0)
                If fn = "Data" Then _
                      Set ws = Sheets("DATA") Else Set ws = Sheets("TABEL")
                Set rg = ws.Range(fn)
                Set rg = rg.Resize(1, 1).Offset(rg.Rows.Count, 0)
                    With ws.QueryTables.Add(Connection:="TEXT;" & pf, _
                                    Destination:=ws.Range(rg.Address))
                        .TextFileParseType = xlDelimited
                        .TextFileCommaDelimiter = True
                        .Refresh
                        .Delete
                    End With
                Open pf For Output As #1: Close #1 'emptying the csv file
            End If
    Next oFile
Kill pfTmp 'emptying the tmpFolder

End Sub

Although it seems the code work OK, but I'm not so sure if the code will be error-free all the time. So my question : is there a better way to write the code in this kind of situation ?

Any kind of help would be much appreciated.

Thank you in advanced.

Body:
One way for synchronization is to make use of a Mutex object. There is a Mutex object  sample in VBA here

As far as I know, Mutex guaranties access to only one thread at a time in AddNewDataIfAny(). So:

    Private Const ERROR_ALREADY_EXISTS = 183&
Private Const MUTEX_ALL_ACCESS = &H1F0001

Private Declare PtrSafe Function CreateMutex Lib "kernel32" Alias "CreateMutexA" (ByVal lpMutexAttributes As Long, ByVal bInitialOwner As Long, ByVal lpName As String) As Long
Private Declare PtrSafe Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long
Private Declare PtrSafe Function WaitForSingleObject Lib "kernel32" (ByVal hHandle As Long, ByVal dwMilliseconds As Long) As Long
Private Declare PtrSafe Function OpenMutex Lib "kernel32" Alias "OpenMutexA" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal lpName As String) As Long
Private Declare PtrSafe Function ReleaseMutex Lib "kernel32" (ByVal hMutex As Long) As Long

Private Sub Workbook_Open()
    myMutex = CreateMutex(0, 1, "myMutex")
    Dim er As Long: er = Err.LastDllError
    If er = 0 Then
        MsgBox "myMutex Created"
    ElseIf er = ERROR_ALREADY_EXISTS Then
        MsgBox "mutex previously created"
        myMutex = OpenMutex(MUTEX_ALL_ACCESS, 0, "myMutex")
    Else
        MsgBox "mutex creation failed"
    End If
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    CloseHandle myMutex
End Sub

Private Sub doSomeCriticalTask()
    WaitForSingleObject myMutex, 20000 ' say we can wait for 20 seconds
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''
    ' do critical section code, access shared data safely
    ''''''''''''''''''''''''''''''''''''''''''''''''''''''
    AddNewDataIfAny()
    ReleaseMutex myMutex
End Sub


问:
How to validate Hangouts Chat webhook token in C#
I am working on a pretty simple chat bot with an ASP.NET webhook to process responses. I am not having any issues sending or receiving messages, but I am a little bit stuck on validating the Bearer token in the Authorization header in order to validate that the incoming request has come from Google.

I have included the Google.Apis.Auth API version 1.55. It has the functionality that should do this validation. Of course the documentation does not give a .NET example, but from what I can gather, it should look like this:

```<code>try
{
    string token = "token here";
    SignedTokenVerificationOptions stvo = new SignedTokenVerificationOptions()
    {
        TrustedAudiences = { "my project id" },
        TrustedIssuers = { "chat@system.gserviceaccount.com" },
        CertificatesUrl = "https://www.googleapis.com/service_accounts/v1/metadata/x509/chat@system.gserviceaccount.com"
    };
    JsonWebSignature.Payload r = await JsonWebSignature.VerifySignedTokenAsync(token, stvo);
    return true;
}
catch (InvalidJwtException)
{
    return false;
}
</code>```

My issue is that I am getting an exception from deep inside the API where it looks like it is processing the certificates from Google. I don't think I have much influence over this bit!

```<code>System.ArgumentNullException: Value cannot be null.
Parameter name: source
   at System.Linq.Enumerable.Select[TSource,TResult](IEnumerable`1 source, Func`2 selector)
   at Google.Apis.Auth.SignedTokenVerification.CertificateCacheBase.<GetCertificatesAsync>d__5.MoveNext() in C:\Apiary\2021-09-08.15-52-39\Src\Support\Google.Apis.Auth\SignedTokenVerification.cs:line 246
   at Google.Apis.Auth.SignedTokenVerification.<GetCertificatesAsync>d__6.MoveNext() in C:\Apiary\2021-09-08.15-52-39\Src\Support\Google.Apis.Auth\SignedTokenVerification.cs:line 203
   at Google.Apis.Auth.SignedTokenVerification.<VerifyRS256TokenAsync>d__4`2.MoveNext() in C:\Apiary\2021-09-08.15-52-39\Src\Support\Google.Apis.Auth\SignedTokenVerification.cs:line 110
   at Google.Apis.Auth.SignedTokenVerification.<VerifySignedTokenAsync>d__3`2.MoveNext() in C:\Apiary\2021-09-08.15-52-39\Src\Support\Google.Apis.Auth\SignedTokenVerification.cs:line 102
   at Google.Apis.Auth.JsonWebSignature.<VerifySignedTokenAsync>d__1`1.MoveNext() in C:\Apiary\2021-09-08.15-52-39\Src\Support\Google.Apis.Auth\JsonWebSignature.cs:line 61
   at GroupHandler.<>c__DisplayClass0_0.<<ProcessRequest>b__0>d.MoveNext() in D:\IIS\Sites\Test\Google\BotVerify.ashx:line 31
</code>```

Is this the right approach? Or am I missing something totally obvious? :)
Joel

答:
It should be the standard service account authorization.

You need Google.Apis.Auth and Google.Apis.HangoutsChat.v1 packages.

```<code>public class HangoutsAuth
    {
        public static string[] scopes =  { "https://www.googleapis.com/auth/chat.bot" };

            private static GoogleCredential GetCredential(string pathToServiceAccountKeyFile, string[] scopes)
            {
                // Load the Service account credentials and define the scope of its access.
                return GoogleCredential.FromFile(pathToServiceAccountKeyFile)
                    .CreateScoped(scopes);
            }

        }
</code>```

Just call it with

```<code>var service = HangoutsAuth.GetService(PathToKeyFile,  { "https://www.googleapis.com/auth/chat.bot" });

var response = await service.Spaces.Messages.Create(body, "spaces/AAAA2CiqVDM").ExecuteAsync();
</code>```

Body:
I am working on a pretty simple chat bot with an ASP.NET webhook to process responses. I am not having any issues sending or receiving messages, but I am a little bit stuck on validating the Bearer token in the Authorization header in order to validate that the incoming request has come from Google.

I have included the Google.Apis.Auth API version 1.55. It has the functionality that should do this validation. Of course the documentation does not give a .NET example, but from what I can gather, it should look like this:

try
{
    string token = "token here";
    SignedTokenVerificationOptions stvo = new SignedTokenVerificationOptions()
    {
        TrustedAudiences = { "my project id" },
        TrustedIssuers = { "chat@system.gserviceaccount.com" },
        CertificatesUrl = "https://www.googleapis.com/service_accounts/v1/metadata/x509/chat@system.gserviceaccount.com"
    };
    JsonWebSignature.Payload r = await JsonWebSignature.VerifySignedTokenAsync(token, stvo);
    return true;
}
catch (InvalidJwtException)
{
    return false;
}

My issue is that I am getting an exception from deep inside the API where it looks like it is processing the certificates from Google. I don't think I have much influence over this bit!

System.ArgumentNullException: Value cannot be null.
Parameter name: source
   at System.Linq.Enumerable.Select[TSource,TResult](IEnumerable`1 source, Func`2 selector)
   at Google.Apis.Auth.SignedTokenVerification.CertificateCacheBase.<GetCertificatesAsync>d__5.MoveNext() in C:\Apiary\2021-09-08.15-52-39\Src\Support\Google.Apis.Auth\SignedTokenVerification.cs:line 246
   at Google.Apis.Auth.SignedTokenVerification.<GetCertificatesAsync>d__6.MoveNext() in C:\Apiary\2021-09-08.15-52-39\Src\Support\Google.Apis.Auth\SignedTokenVerification.cs:line 203
   at Google.Apis.Auth.SignedTokenVerification.<VerifyRS256TokenAsync>d__4`2.MoveNext() in C:\Apiary\2021-09-08.15-52-39\Src\Support\Google.Apis.Auth\SignedTokenVerification.cs:line 110
   at Google.Apis.Auth.SignedTokenVerification.<VerifySignedTokenAsync>d__3`2.MoveNext() in C:\Apiary\2021-09-08.15-52-39\Src\Support\Google.Apis.Auth\SignedTokenVerification.cs:line 102
   at Google.Apis.Auth.JsonWebSignature.<VerifySignedTokenAsync>d__1`1.MoveNext() in C:\Apiary\2021-09-08.15-52-39\Src\Support\Google.Apis.Auth\JsonWebSignature.cs:line 61
   at GroupHandler.<>c__DisplayClass0_0.<<ProcessRequest>b__0>d.MoveNext() in D:\IIS\Sites\Test\Google\BotVerify.ashx:line 31

Is this the right approach? Or am I missing something totally obvious? :)
Joel

Body:
It should be the standard service account authorization.

You need Google.Apis.Auth and Google.Apis.HangoutsChat.v1 packages.

public class HangoutsAuth
    {
        public static string[] scopes =  { "https://www.googleapis.com/auth/chat.bot" };

            private static GoogleCredential GetCredential(string pathToServiceAccountKeyFile, string[] scopes)
            {
                // Load the Service account credentials and define the scope of its access.
                return GoogleCredential.FromFile(pathToServiceAccountKeyFile)
                    .CreateScoped(scopes);
            }

        }

Just call it with

var service = HangoutsAuth.GetService(PathToKeyFile,  { "https://www.googleapis.com/auth/chat.bot" });

var response = await service.Spaces.Messages.Create(body, "spaces/AAAA2CiqVDM").ExecuteAsync();


问:
Mapping of Host System Memory to PCI domain Address

My understanding of PCI

The Host CPU is responsible for assigning the PCI domain address to all other devices on PCI bus by setting  the devices BAR register in PCI configuration space

The Host CPU can map the PCI address domain to its domain(i.e System domain), so that Host initiated  "PCI Memory transactions" with  devices on PCI bus can be achieved using simple load/ store instructions of the host CPU

Question ->
Is it possible that even the system memory i.e. the main memory of the host(actual ram) be mapped to PCI domain address, so that when Host system is a target device of the "PCI memory transaction" initiated by a device on PCI bus, the main memory is read/ written without the intervention of the Host CPU?

Additional Information: I am working of embedded system with 3 SH4 processors communicating using PCI bus

答: Yes it is very much possible. You can also use DMA functionality of PCIE to 'bypass' the CPU.</p>


问:
How to create a new text file on button click
Here is my problem:

I am developing a windows application

I am converting an image into text format, and saving it into a system location.

This is my code:

```<code>if (!System.IO.Directory.Exists("D:\\SaveImageOutPutFolder"))
{
    System.IO.Directory.CreateDirectory("D:\\SaveImageOutPutFolder");
    doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] +@"\\MytxtFile.txt", Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
    MessageBox.Show("folder created and image output saved");
}
else
{
    doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] + @"\\MytxtFile.txt", Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
    MessageBox.Show("ImageFolder is available  images are  Saved into folder Now");
}
</code>```

The problem is that it is not creating a new text file every time the button is clicked. It is writing to the same file. I want to create to a new txt file for every click.

Can anyboy help in this, and give me some sample code?

答:
You can use System.IO.Path.GetRandomFileName method, here is a method I develop sometime ago:

```<code>public static string GetUniqueFileName(string rootDirectory, string extension)
{
    if (rootDirectory == null)
    {
        throw new ArgumentNullException("rootDirectory");
    }

    if (!Directory.Exists(rootDirectory))
    {
        throw new DirectoryNotFoundException();
    }

    string fileName = null;
    do
    {
        fileName = System.IO.Path.Combine(rootDirectory, System.IO.Path.GetRandomFileName().Replace(".", ""));

        fileName = System.IO.Path.ChangeExtension(fileName, extension);

    } while (System.IO.File.Exists(fileName) || System.IO.Directory.Exists(fileName));

    return fileName;
}
</code>```

Edit: How to use it and re-factoring your method:

```<code>string root = ConfigurationSettings.AppSettings["SaveImagefolderPath"];
string extension = ".txt";
bool newlyFolderCreated = false;

if (!System.IO.Directory.Exists(root))
{
    System.IO.Directory.CreateDirectory(root);
    newlyFolderCreated = true;
}

doc.Save(GetUniqueFileName(root, extension),
    Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);

if (newlyFolderCreated)
{
    MessageBox.Show("folder created and image output saved");
}
else
{
    MessageBox.Show("ImageFolder is available  images are  Saved into folder Now");
}
</code>```

Also I don't know why youare using "D:\\SaveImageOutPutFolder" and ConfigurationSettings.AppSettings["SaveImagefolderPath"] at the same time, maybe it is a typo?

Body:
Here is my problem:

I am developing a windows application

I am converting an image into text format, and saving it into a system location.

This is my code:

if (!System.IO.Directory.Exists("D:\\SaveImageOutPutFolder"))
{
    System.IO.Directory.CreateDirectory("D:\\SaveImageOutPutFolder");
    doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] +@"\\MytxtFile.txt", Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
    MessageBox.Show("folder created and image output saved");
}
else
{
    doc.Save(ConfigurationSettings.AppSettings["SaveImagefolderPath"] + @"\\MytxtFile.txt", Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);
    MessageBox.Show("ImageFolder is available  images are  Saved into folder Now");
}

The problem is that it is not creating a new text file every time the button is clicked. It is writing to the same file. I want to create to a new txt file for every click.

Can anyboy help in this, and give me some sample code?

Body:
You can use System.IO.Path.GetRandomFileName method, here is a method I develop sometime ago:

public static string GetUniqueFileName(string rootDirectory, string extension)
{
    if (rootDirectory == null)
    {
        throw new ArgumentNullException("rootDirectory");
    }

    if (!Directory.Exists(rootDirectory))
    {
        throw new DirectoryNotFoundException();
    }

    string fileName = null;
    do
    {
        fileName = System.IO.Path.Combine(rootDirectory, System.IO.Path.GetRandomFileName().Replace(".", ""));

        fileName = System.IO.Path.ChangeExtension(fileName, extension);

    } while (System.IO.File.Exists(fileName) || System.IO.Directory.Exists(fileName));

    return fileName;
}

Edit: How to use it and re-factoring your method:

string root = ConfigurationSettings.AppSettings["SaveImagefolderPath"];
string extension = ".txt";
bool newlyFolderCreated = false;

if (!System.IO.Directory.Exists(root))
{
    System.IO.Directory.CreateDirectory(root);
    newlyFolderCreated = true;
}

doc.Save(GetUniqueFileName(root, extension),
    Leadtools.Forms.DocumentWriters.DocumentFormat.Text, null);

if (newlyFolderCreated)
{
    MessageBox.Show("folder created and image output saved");
}
else
{
    MessageBox.Show("ImageFolder is available  images are  Saved into folder Now");
}

Also I don't know why youare using "D:\\SaveImageOutPutFolder" and ConfigurationSettings.AppSettings["SaveImagefolderPath"] at the same time, maybe it is a typo?


问:
Separate mesh by loose parts in threejs
I’ve created a some basic model in Blender. It’s 4 times subdivided cube (I need faces to look like squares), then faces was split by edges (in Blender too). Then I need to separate final mesh by loose parts in threejs (if I do that in Blender the exported file is too big, like a few MB big). So each face become separate one.

How should I do that?

Step 1 (blender)

Step 2 (blender)

After step 2 each face is a separate mesh. I need to replicate step 2 in ThreeJS.

As a result I need to explode faces of a sphere

Here's what I have so far

I'll need much more faces to achieve the desired result. One possible solution would be to place 2 spheres one inside another and then "explode" them simultaneosly. But I need faces to be much smaller too.

My "explosion" code is heavily based on this: https://github.com/akella/ExplodingObjects/blob/0ed8d2668e3fe9913133382bb139c73b9d554494/src/egg.js#L178

And here's demo:
https://tympanus.net/Development/ExplodingObjects/index-heart.html

答:
In your case I would use bufferGeometry.

According to this showcase: https://threejs.org/examples/#webgl_buffergeometry

16000 triangles are generated with normal orientations.

I think you should use BufferGeometry.

Build on top of your codePen,
Here you'll find a solution to have quad faces (instead of your triangles) oriented along a sphere surface.

The core to get the quad faces laying along the surface of a sphere:

for (let down = 0; down < segmentsDown; ++down) {
      const v0 = down / segmentsDown;
      const v1 = (down + 1) / segmentsDown;
      const lat0 = (v0 - 0.5) * Math.PI;
      const lat1 = (v1 - 0.5) * Math.PI;

      for (let across = 0; across < segmentsAround; ++across) {
        //for each quad we randomize the radius
        const radius = radiusOfSphere + Math.random()*1.5*radiusOfSphere;
        const u0 = across / segmentsAround;
        const u1 = (across + 1) / segmentsAround;
        const long0 = u0 * Math.PI * 2;
        const long1 = u1 * Math.PI * 2;
        //for each quad you have 2 triangles
        //first triangle of the quad
        //getPoint() returns xyz coord in vector3  array with (latitude longitude radius) input
        positions.push(...getPoint(lat0, long0, radius));
        positions.push(...getPoint(lat1, long0, radius));
        positions.push(...getPoint(lat0, long1, radius));
        //second triangle of the quad. Order matter for UV mapping,
        positions.push(...getPoint(lat1, long0, radius));
        positions.push(...getPoint(lat1, long1, radius));
        positions.push(...getPoint(lat0, long1, radius));
      }
    }
```

https://codepen.io/mquantin/pen/mdqmwMa

I hope this will do the job for you.

Title: Separate mesh by loose parts in threejs

Body:
In your case I would use bufferGeometry.

According to this showcase: https://threejs.org/examples/#webgl_buffergeometry

16000 triangles are generated with normal orientations.

I think you should use BufferGeometry.

Build on top of your codePen,
Here you'll find a solution to have quad faces (instead of your triangles) oriented along a sphere surface.

The core to get the quad faces laying along the surface of a sphere:

for (let down = 0; down < segmentsDown; ++down) {
      const v0 = down / segmentsDown;
      const v1 = (down + 1) / segmentsDown;
      const lat0 = (v0 - 0.5) * Math.PI;
      const lat1 = (v1 - 0.5) * Math.PI;

      for (let across = 0; across < segmentsAround; ++across) {
        //for each quad we randomize the radius
        const radius = radiusOfSphere + Math.random()*1.5*radiusOfSphere;
        const u0 = across / segmentsAround;
        const u1 = (across + 1) / segmentsAround;
        const long0 = u0 * Math.PI * 2;
        const long1 = u1 * Math.PI * 2;
        //for each quad you have 2 triangles
        //first triangle of the quad
        //getPoint() returns xyz coord in vector3  array with (latitude longitude radius) input
        positions.push(...getPoint(lat0, long0, radius));
        positions.push(...getPoint(lat1, long0, radius));
        positions.push(...getPoint(lat0, long1, radius));
        //second triangle of the quad. Order matter for UV mapping,
        positions.push(...getPoint(lat1, long0, radius));
        positions.push(...getPoint(lat1, long1, radius));
        positions.push(...getPoint(lat0, long1, radius));
      }
    }

https://codepen.io/mquantin/pen/mdqmwMa

I hope this will do the job for you.


问:
How to implement a function that takes an array and some other arguments then removes the other arguments from that array
Please guys, this is an exercise (exercise 04) from Odin Project. I don't know if there is anything wrong with the code below, it keeps failing the 'npm test' (a test in the terminal) but then i checked it with console.log and it worked.</p>
```<code>const removeFromArray= function(...args) {
    const array = args[0];
        const newArray = [];
             array.forEach((item) => {
                 if(!args.includes(item)) {
                      newArray.push(item);
        }
        });
        return newArray;
    };
</code>```

答:
I'd suggest using Array.filter() in combination with Array.includes() to achieve the required result.

We filter any element from the input array if it is present in the itemsToRemove array.

function removeFromArray(array, itemsToRemove) {
    return array.filter(element => !itemsToRemove.includes(element));
}

let array = [1,2,3,4,5,6];
let itemsToRemove = [2,4,6];

console.log(removeFromArray(array, itemsToRemove))```
</div>
</div>
</p>
<p>We can do this in a more efficient manner if <code>itemsToRemove</code> is very large, using a <code>Set</code>:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function removeFromArray(array, itemsToRemove) {
    const itemsToRemoveSet = new Set(itemsToRemove);
    return array.filter(element => !itemsToRemoveSet.has(element));
}

let array = [1,2,3,4,5,6];
let itemsToRemove = [2,4,6];

console.log(removeFromArray(array, itemsToRemove))</code>```

Body:
Please guys, this is an exercise (exercise 04) from Odin Project. I don't know if there is anything wrong with the code below, it keeps failing the 'npm test' (a test in the terminal) but then i checked it with console.log and it worked.

const removeFromArray= function(...args) {
    const array = args[0];
        const newArray = [];
             array.forEach((item) => {
                 if(!args.includes(item)) {
                      newArray.push(item);
        }
        });
        return newArray;
    };

Body:
I'd suggest using Array.filter() in combination with Array.includes() to achieve the required result.

We filter any element from the input array if it is present in the itemsToRemove array.

function removeFromArray(array, itemsToRemove) {
    return array.filter(element => !itemsToRemove.includes(element));
}

let array = [1,2,3,4,5,6];
let itemsToRemove = [2,4,6];

console.log(removeFromArray(array, itemsToRemove))

We can do this in a more efficient manner if itemsToRemove is very large, using a Set:

function removeFromArray(array, itemsToRemove) {
    const itemsToRemoveSet = new Set(itemsToRemove);
    return array.filter(element => !itemsToRemoveSet.has(element));
}

let array = [1,2,3,4,5,6];
let itemsToRemove = [2,4,6];

console.log(removeFromArray(array, itemsToRemove))


问:
How to use a custom analyser on specific elasticsearch documents
Suppose I have a custom analyser that I want to use on only specific documents that have the table entity_type, how would I go about that?

Document I want to match:

```<code>{
  ... other keys

  "_source": {
    "entity_type": "table"  // <-- I want to match this and use the custom analyser on this entire document
  }
}
</code>```

Custom analyser (currently just set to the default but I want it to only affect tables)

elasticsearch.indices.create(
  index="myIndex",
  body={
    "settings": {
      "analysis": {
        "char_filter": {
          "underscore_to_dash": {
            "type": "mapping",
            "mappings": ["_ => -"],
          }
        },
        "analyzer": {
          "default": {
            "type": "custom",
            "tokenizer": "standard",
            "filter": ["lowercase"],
            "char_filter": ["underscore_to_dash"],
          }
        },
      },
    }
  })
```

答: Analyzer can only be applied to a specific field. So in your case it might make sense to have 2 fields and use one for "entity_type": "table" and another for other docs.

Body:
Suppose I have a custom analyser that I want to use on only specific documents that have the table entity_type, how would I go about that?

Document I want to match:

{
  ... other keys

  "_source": {
    "entity_type": "table"  // <-- I want to match this and use the custom analyser on this entire document
  }
}

Custom analyser (currently just set to the default but I want it to only affect tables)

elasticsearch.indices.create(
  index="myIndex",
  body={
    "settings": {
      "analysis": {
        "char_filter": {
          "underscore_to_dash": {
            "type": "mapping",
            "mappings": ["_ => -"],
          }
        },
        "analyzer": {
          "default": {
            "type": "custom",
            "tokenizer": "standard",
            "filter": ["lowercase"],
            "char_filter": ["underscore_to_dash"],
          }
        },
      },
    }
  })


问:
How to select cells behind the shapes in spreadsheet?
I have a spreadsheet which have Dotted lines as a shapes.When i try to select the cells behind those shapes (highlighted in attached picture), these shapes come in the way.Is there a way to put those shapes behind the cells or select the cells without obstruction from shapes so that i can put data on the cells behind the shape ?

Some of the ideas that i have come up with are:

Hiding the shapes using macro then putting data on required cells then unhiding shapes.

Increasing the column width so the cells can be easily selected.

答:
SelectUnderShape macro provided by John Simmons worked. Thanks a lot for the post.

It took a while to get it running, but it works.

For the novice, find the name of the object in your worksheet and substitute it in the VBA code, in both places. Use Shift Arrow keys to select a Range from the first cell clicked.


问:
What's the difference between is and inherits?
If I want to check whether a variable inherits from some class, I can either use is or inherits.

```<code>class(letters)
## [1] "character"
is(letters, "character")
## [1] TRUE
inherits(letters, "character")
## [1] TRUE
</code>```

Is there a preference for which one I should use, and do they ever return different values?

答:
Besides is() and inherits() we can also test objects with is.*() for a certain type. Those three function can return different results. Based on this answer I did the following

Created numerous R objects of different types

Extracted the type of those objects using storage.mode(), mode(), typeof() and class().

Tested the objects whether they are of the returned types using is(), inherits() and is.*().

Here is a small example of the three steps above:

```<code># Get object classes withs torage.mode(), mode(), typeof() and class().
obj <- logical()
(types <- c(storage.mode= storage.mode(obj),
            mode= mode(obj),
            type= typeof(obj),
            class= class(obj)))
storage.mode         mode         type        class
    "double"    "numeric"     "double"    "numeric"

# Test returned types with is, inhertis and is.*.
> is(obj, "double"); is(obj, "numeric")
[1] FALSE
[1] TRUE
> inherits(obj, "double"); inherits(obj, "numeric")
[1] FALSE
[1] TRUE
> is.double(obj); is.numeric(obj)
[1] TRUE
[1] TRUE
</code>```

Now we do this for a bunch of object types with the following code:

```<code># Generate objects of different types.
library(xml2)
setClass("dummy", representation(x="numeric", y="numeric"))
obj <- list(
  "logical vector" = logical(),
  "integer vector" = integer(),
  "numeric vector" = numeric(),
  "complex vector" = complex(),
  "character vector" = character(),
  "raw vector" = raw(),
  "factor" = factor(),
  "logical matrix" = matrix(logical()),
  "numeric matrix" = matrix(numeric()),
  "logical array" = array(logical(8), c(2, 2, 2)),
  "numeric array" = array(numeric(8), c(2, 2, 2)),
  "list" = list(),
  "pairlist" = .Options,
  "data frame" = data.frame(),
  "closure function" = identity,
  "builtin function" = `+`,
  "special function" = `if`,
  "environment" = new.env(),
  "null" = NULL,
  "formula" = y ~ x,
  "expression" = expression(),
  "call" = call("identity"),
  "name" = as.name("x"),
  #"paren in expression" = expression((1))[[1]], # Code fails with this
  #"brace in expression" = expression({1})[[1]], # Code fails with this
  "S3 lm object" = lm(dist ~ speed, cars),
  "S4 dummy object" = new("dummy", x = 1:10, y = rnorm(10)),
  "external pointer" = read_xml("<foo><bar /></foo>")$node
  )

# Extract types and test them.
res <- do.call("rbind.data.frame", Map(function(x, name){
  types <- c(storage.mode= storage.mode(x),
                mode= mode(x),
                type= typeof(x),
                class= class(x))
  data.frame("object"= name,
             "extract_method"= names(types),
             "extract_result"= types,
             "inherits"= sapply(types, function(i) inherits(x, i)),
             "is"= sapply(types, function(i) is(x, i)),
             "is.type"= sapply(types, function(i) eval(parse(text= paste0("tryCatch({is.", i, "(x)}, error= function(e){'is.", i, "() does not exist'})"))))
  )}, obj, names(obj)))
rownames(res) <- 1:nrow(res)
res <- res[order(res$extract_method), ]
</code>```

We can get a few insights from the results res. For example, we can loow were is.() does not return same as inherits():

```<code>> res[res$inherits != res$is, ]
           object extract_method extract_result inherits   is is.type
6  integer vector           mode        numeric    FALSE TRUE TRUE
87           call   storage.mode       language    FALSE TRUE TRUE
89           call           type       language    FALSE TRUE TRUE
</code>```

Of course the results show much more, e.g. we can see where inherits() returns FALSE on types that where returned of one of the three extraction methods and so on. I left this out here. In fact, I think my answer is much broader since it takes into account both, differences in extraction and test of object type. After reading quite some time about object types I arrived at the code above and wanted to share it. However, using res[res$inherits != res$is, ] soly answers the question.

Body:
If I want to check whether a variable inherits from some class, I can either use is or inherits.

class(letters)
## [1] "character"
is(letters, "character")
## [1] TRUE
inherits(letters, "character")
## [1] TRUE

Is there a preference for which one I should use, and do they ever return different values?

Body:
Besides is() and inherits() we can also test objects with is.*() for a certain type. Those three function can return different results. Based on this answer I did the following

Created numerous R objects of different types

Extracted the type of those objects using storage.mode(), mode(), typeof() and class().

Tested the objects whether they are of the returned types using is(), inherits() and is.*().

Here is a small example of the three steps above:

# Get object classes withs torage.mode(), mode(), typeof() and class().
obj <- logical()
(types <- c(storage.mode= storage.mode(obj),
            mode= mode(obj),
            type= typeof(obj),
            class= class(obj)))
storage.mode         mode         type        class
    "double"    "numeric"     "double"    "numeric"

# Test returned types with is, inhertis and is.*.
> is(obj, "double"); is(obj, "numeric")
[1] FALSE
[1] TRUE
> inherits(obj, "double"); inherits(obj, "numeric")
[1] FALSE
[1] TRUE
> is.double(obj); is.numeric(obj)
[1] TRUE
[1] TRUE

Now we do this for a bunch of object types with the following code:

# Generate objects of different types.
library(xml2)
setClass("dummy", representation(x="numeric", y="numeric"))
obj <- list(
  "logical vector" = logical(),
  "integer vector" = integer(),
  "numeric vector" = numeric(),
  "complex vector" = complex(),
  "character vector" = character(),
  "raw vector" = raw(),
  "factor" = factor(),
  "logical matrix" = matrix(logical()),
  "numeric matrix" = matrix(numeric()),
  "logical array" = array(logical(8), c(2, 2, 2)),
  "numeric array" = array(numeric(8), c(2, 2, 2)),
  "list" = list(),
  "pairlist" = .Options,
  "data frame" = data.frame(),
  "closure function" = identity,
  "builtin function" = `+`,
  "special function" = `if`,
  "environment" = new.env(),
  "null" = NULL,
  "formula" = y ~ x,
  "expression" = expression(),
  "call" = call("identity"),
  "name" = as.name("x"),
  #"paren in expression" = expression((1))[[1]], # Code fails with this
  #"brace in expression" = expression({1})[[1]], # Code fails with this
  "S3 lm object" = lm(dist ~ speed, cars),
  "S4 dummy object" = new("dummy", x = 1:10, y = rnorm(10)),
  "external pointer" = read_xml("<foo><bar /></foo>")$node
  )

# Extract types and test them.
res <- do.call("rbind.data.frame", Map(function(x, name){
  types <- c(storage.mode= storage.mode(x),
                mode= mode(x),
                type= typeof(x),
                class= class(x))
  data.frame("object"= name,
             "extract_method"= names(types),
             "extract_result"= types,
             "inherits"= sapply(types, function(i) inherits(x, i)),
             "is"= sapply(types, function(i) is(x, i)),
             "is.type"= sapply(types, function(i) eval(parse(text= paste0("tryCatch({is.", i, "(x)}, error= function(e){'is.", i, "() does not exist'})"))))
  )}, obj, names(obj)))
rownames(res) <- 1:nrow(res)
res <- res[order(res$extract_method), ]

We can get a few insights from the results res. For example, we can loow were is.() does not return same as inherits():

> res[res$inherits != res$is, ]
           object extract_method extract_result inherits   is is.type
6  integer vector           mode        numeric    FALSE TRUE TRUE
87           call   storage.mode       language    FALSE TRUE TRUE
89           call           type       language    FALSE TRUE TRUE

Of course the results show much more, e.g. we can see where inherits() returns FALSE on types that where returned of one of the three extraction methods and so on. I left this out here. In fact, I think my answer is much broader since it takes into account both, differences in extraction and test of object type. After reading quite some time about object types I arrived at the code above and wanted to share it. However, using res[res$inherits != res$is, ] soly answers the question.


问:
ReactJS, SocketIO & Redux - What is the right design
What is the best pattern for a large multi-component ReactJS app to integrate with a socket io back-end server?

Here are some of the requirements

The React application must connect to the backend (a server using a Flask-based socket.io implementation) upon login. The connection must be torn down on logout

The connection should be managed from a central place (as in I don't want every component to connect/disconnect to socket-io). This should also be a place to manage life-cycle of the socketio connection (disconnect, reconnect, etc).

Back-end will send async updates (a.k.a statistics for various components). These stats must be handled by the common socketio handling instance and pushed into redux store. The message body will have enough information to demux the messages.

The components themselves, should (preferably) not know about socket-io, they operate on the redux state.

Components can dispatch actions, that could potentially result in sending out a socketio message (to back-end).

[I don't have a use-case where a client needs to talk to another client.]

Few questions:

What is the right way to design this? At what point should I connect to socket-io?

I have a basic-layout component which is used by all pages. Is this the right place to hook up socket-io call? However, I see that this component is unloaded/loaded for each page. Somehow, this doesn't feel like the right place

I have seen some examples where every page opens a socketio connection. I am not sure if this is the right model?

答:
I think you should probably store your socket on a Context, so that you can create your socket on your index.js file, like I did here :

```<code>import React from "react";
import App from "./App";
import socketIOClient from "socket.io-client";
import { MainProvider } from "./context/MainContext.js";

const ENDPOINT = "http://127.0.0.1:1234"; //Your backend endpoint

ReactDOM.render(
  <React.StrictMode>
    <MainProvider value={{socket: socketIOClient(ENDPOINT)}}>
      <App />
    </MainProvider>
  </React.StrictMode>,
  document.getElementById("root")
);
</code>```

Then as it is on the context, you can access it in any component, like that :

```<code>import React, { useContext } from 'react';
import PropTypes from 'prop-types';

import MainContext from "./context/MainContext"; //import your context here

const myComponent = props => {

    const myContext = useContext(MainContext); //your context is stored in a prop

    return (
        <div></div>
    );
};

myComponent.propTypes = {

};

export default myComponent;
</code>```

Finally you can access your socket in the component by calling myContext.socket

Body:
I think you should probably store your socket on a Context, so that you can create your socket on your index.js file, like I did here :

import React from "react";
import App from "./App";
import socketIOClient from "socket.io-client";
import { MainProvider } from "./context/MainContext.js";

const ENDPOINT = "http://127.0.0.1:1234"; //Your backend endpoint

ReactDOM.render(
  <React.StrictMode>
    <MainProvider value={{socket: socketIOClient(ENDPOINT)}}>
      <App />
    </MainProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

Then as it is on the context, you can access it in any component, like that :

import React, { useContext } from 'react';
import PropTypes from 'prop-types';

import MainContext from "./context/MainContext"; //import your context here

const myComponent = props => {

    const myContext = useContext(MainContext); //your context is stored in a prop

    return (
        <div></div>
    );
};

myComponent.propTypes = {

};

export default myComponent;

Finally you can access your socket in the component by calling myContext.socket


问:
Daemon Threads shutting down main thread
I was looking through online sites about anything about daeomon threads, but the best I could find was on the python documentation here. It only says that a thread that is flagged as a "daemon thread" will automatically kill itself when the main thread has shut down. It doesn't mention what would happen if these child processes died on their own, possibly due to an error.

To connect this with a project I'm currently working on, I'm working on an error checking process, where whenever a child thread that is running in the background finds an error, it shuts itself down and automatically restarts the entire IDE. I was wondering if daemon threads could automatically shut down the main thread, by simply shutting down their own.

…and if they cannot, are there any alternatives to this problem?

答:
You shouldn't kill a thread in Python, but you can ask it to stop what it is doing :

import time
import threading

MAIN_THREAD_SHOULD_STOP = False

def wait_5_seconds_then_ask_the_main_thread_to_stop():
    for i in range(5, 0, -1):
        print(i)
        time.sleep(1)
    print("asking to stop")
    global MAIN_THREAD_SHOULD_STOP
    MAIN_THREAD_SHOULD_STOP = True
    if not threading.currentThread().daemon:
        return

def doing_busy_work_until_asked_to_stop():
    while not MAIN_THREAD_SHOULD_STOP:
        print("busy busy busy")
        time.sleep(0.6)
    print("stopped")

if __name__ == "__main__":
    annex = threading.Thread(target=wait_5_seconds_then_ask_the_main_thread_to_stop, args=(), daemon=True)
    annex.start()
    doing_busy_work_until_asked_to_stop()
```
```5
busy busy busy
busy busy busy
4
busy busy busy
busy busy busy
3
busy busy busy
2
busy busy busy
busy busy busy
1
busy busy busy
busy busy busy
asking to stop
stopped
```

Body:
You shouldn't kill a thread in Python, but you can ask it to stop what it is doing :

import time
import threading

MAIN_THREAD_SHOULD_STOP = False

def wait_5_seconds_then_ask_the_main_thread_to_stop():
    for i in range(5, 0, -1):
        print(i)
        time.sleep(1)
    print("asking to stop")
    global MAIN_THREAD_SHOULD_STOP
    MAIN_THREAD_SHOULD_STOP = True
    if not threading.currentThread().daemon:
        return

def doing_busy_work_until_asked_to_stop():
    while not MAIN_THREAD_SHOULD_STOP:
        print("busy busy busy")
        time.sleep(0.6)
    print("stopped")

if __name__ == "__main__":
    annex = threading.Thread(target=wait_5_seconds_then_ask_the_main_thread_to_stop, args=(), daemon=True)
    annex.start()
    doing_busy_work_until_asked_to_stop()

5
busy busy busy
busy busy busy
4
busy busy busy
busy busy busy
3
busy busy busy
2
busy busy busy
busy busy busy
1
busy busy busy
busy busy busy
asking to stop
stopped


问:
How to setup DVWA on localhost - windows 11

Error

```<code>Fatal error:
Uncaught mysqli_sql_exception:
Unknown database 'dvwa' in C:\xampp\htdocs\dvwa\dvwa\includes\dvwaPage.inc.php:499
Stack trace:
#0 C:\xampp\htdocs\dvwa\dvwa\includes\dvwaPage.inc.php(499): mysqli_query(Object(mysqli), 'USE dvwa')
#1 C:\xampp\htdocs\dvwa\login.php(8): dvwaDatabaseConnect()
#2 {main} thrown in C:\xampp\htdocs\dvwa\dvwa\includes\dvwaPage.inc.php on line 499
</code>```

答:
Change this in config.inc.php

```<code>$_DVWA[ 'db_database' ] = 'dvwa';
$_DVWA[ 'db_user' ]     = 'dvwa';
</code>```

Go to phpmyadmin page: http://localhost/phpmyadmin/index.php

Create a new user dvwa with all privileges. (see steps below)

Go to http://127.0.0.1/login.php

Enter username dvwa and press login.

To create a new user:

click on User accounts

click on Add new user

set username to dvwa and password to no password

check Create database with same name and grant all privileges

check all global privileges

press Go

Body:
Error

Fatal error:
Uncaught mysqli_sql_exception:
Unknown database 'dvwa' in C:\xampp\htdocs\dvwa\dvwa\includes\dvwaPage.inc.php:499
Stack trace:
#0 C:\xampp\htdocs\dvwa\dvwa\includes\dvwaPage.inc.php(499): mysqli_query(Object(mysqli), 'USE dvwa')
#1 C:\xampp\htdocs\dvwa\login.php(8): dvwaDatabaseConnect()
#2 {main} thrown in C:\xampp\htdocs\dvwa\dvwa\includes\dvwaPage.inc.php on line 499

Body:
Change this in config.inc.php

$_DVWA[ 'db_database' ] = 'dvwa';
$_DVWA[ 'db_user' ]     = 'dvwa';

Go to phpmyadmin page: http://localhost/phpmyadmin/index.php

Create a new user dvwa with all privileges. (see steps below)

Go to http://127.0.0.1/login.php

Enter username dvwa and press login.

To create a new user:

click on User accounts

click on Add new user

set username to dvwa and password to no password

check Create database with same name and grant all privileges

check all global privileges

press Go


问:
Subprocess.Popen() hanging even with shell=False and p.communicate()
I am desperate as I am battling since weeks now with subprocess.Popen() hanging. I read a lot of forums with sometime contradictory information and tried as many of them but still without any mean to resolve the issue.

Basically what I simply need is to execute X subprocesses that will run a command and I even do not need their stdout or stderr. They are all writing to sub xml files dedicate to each one of them and I collect them all once they have all finished. The command to be executed is running a python script where I can see it is arriving at the end line in the script logs. I even added a sys.exit() at the end of the called script to make sure it exists properly.

Simplified code looks like:

```<code>for cmd in commands:
    p = subprocess.Popen(cmd[0], shell=False)
    processes.append(p)

# We now pause execution on the main process by 'joining' all of our started sub processes.
# This ensures that each has finished processing their own batch.
for index, process in enumerate(processes):
    logging.info(f"Waiting for process #{index}")
    try:
        (out, err) = process.communicate(timeout=3600)
        outputs.append(out) # not even required
        errors.append(err) # not even required
        process.wait()
        logging.info(f"Process #{index} finished")
    except TimeoutExpired as timeout_err:
        logging.exception(f"Timeout Exception from process #{index}", timeout_err)
        process.kill()
        (out, err) = process.communicate()
    # Reading sub xml
    # reading generated xml for the sub process here
</code>```

Not sure what can be deadlocking here ! even the timeout scenario is not raising properly. And it is unpredictable when it is going to actually hang ...

Any help or support is much appreciated.

Thanks.

EDIT
As pointed ou from @MauriceMeyer, the current given timeout is happening sequentially but  I have no means to make it start at the time I call subprocess.Popen(). Also this is a very painful workaround as I can't predict exactly the timeout value and it is killing performance while the whole subprocess story was aimed for having better execution performance.

答:
You could manually check if a process needs to get killed:

```<code>import time
import subprocess

TIMEOUT = 5

processes = []
for x in range(1, 10):
    cmd = [f'sleep {x}']
    p = subprocess.Popen(cmd, shell=True) # shell=True for simplicity!

    # add start time, so we can manually kill the process
    processes.append({'handle': p, 'start': time.time(), 'returncode': None})

_allFinished = False
while not all([p['returncode'] is not None for p in processes]):
    for i, process in enumerate(processes):
        # poll() checks if child process has terminated, returns None if it is running
        rtc = process["handle"].poll()

        if rtc is None:
            # Process is still running, check if it needs to get killed
            if time.time() - process['start'] > TIMEOUT:
                # kills the process!
                process["handle"].terminate()
                process["handle"].wait()
                processes[i]['returncode'] = 'timeout'
        else:
            processes[i]['returncode'] = rtc

    time.sleep(0.1)

for p in processes:
    print(p)
</code>```

Out:

```<code>{'handle': <subprocess.Popen object at 0x10d4d3040>, 'start': 1644318572.923203, 'returncode': 0}
{'handle': <subprocess.Popen object at 0x10d4ee7c0>, 'start': 1644318572.9256551, 'returncode': 0}
{'handle': <subprocess.Popen object at 0x10d550d30>, 'start': 1644318572.928237, 'returncode': 0}
{'handle': <subprocess.Popen object at 0x10d550d90>, 'start': 1644318572.930966, 'returncode': 0}
{'handle': <subprocess.Popen object at 0x10d50fa60>, 'start': 1644318572.934939, 'returncode': 0}
{'handle': <subprocess.Popen object at 0x10d805250>, 'start': 1644318572.937738, 'returncode': 'timeout'}
{'handle': <subprocess.Popen object at 0x10d82f250>, 'start': 1644318572.940351, 'returncode': 'timeout'}
{'handle': <subprocess.Popen object at 0x10d82f370>, 'start': 1644318572.943875, 'returncode': 'timeout'}
{'handle': <subprocess.Popen object at 0x10d82f490>, 'start': 1644318572.946584, 'returncode': 'timeout'}
</code>```

Body:
I am desperate as I am battling since weeks now with subprocess.Popen() hanging. I read a lot of forums with sometime contradictory information and tried as many of them but still without any mean to resolve the issue.

Basically what I simply need is to execute X subprocesses that will run a command and I even do not need their stdout or stderr. They are all writing to sub xml files dedicate to each one of them and I collect them all once they have all finished. The command to be executed is running a python script where I can see it is arriving at the end line in the script logs. I even added a sys.exit() at the end of the called script to make sure it exists properly.

Simplified code looks like:

for cmd in commands:
    p = subprocess.Popen(cmd[0], shell=False)
    processes.append(p)

# We now pause execution on the main process by 'joining' all of our started sub processes.
# This ensures that each has finished processing their own batch.
for index, process in enumerate(processes):
    logging.info(f"Waiting for process #{index}")
    try:
        (out, err) = process.communicate(timeout=3600)
        outputs.append(out) # not even required
        errors.append(err) # not even required
        process.wait()
        logging.info(f"Process #{index} finished")
    except TimeoutExpired as timeout_err:
        logging.exception(f"Timeout Exception from process #{index}", timeout_err)
        process.kill()
        (out, err) = process.communicate()
    # Reading sub xml
    # reading generated xml for the sub process here

Not sure what can be deadlocking here ! even the timeout scenario is not raising properly. And it is unpredictable when it is going to actually hang ...

Any help or support is much appreciated.

Thanks.

EDIT
As pointed ou from @MauriceMeyer, the current given timeout is happening sequentially but  I have no means to make it start at the time I call subprocess.Popen(). Also this is a very painful workaround as I can't predict exactly the timeout value and it is killing performance while the whole subprocess story was aimed for having better execution performance.

Body:
You could manually check if a process needs to get killed:

import time
import subprocess

TIMEOUT = 5

processes = []
for x in range(1, 10):
    cmd = [f'sleep {x}']
    p = subprocess.Popen(cmd, shell=True) # shell=True for simplicity!

    # add start time, so we can manually kill the process
    processes.append({'handle': p, 'start': time.time(), 'returncode': None})

_allFinished = False
while not all([p['returncode'] is not None for p in processes]):
    for i, process in enumerate(processes):
        # poll() checks if child process has terminated, returns None if it is running
        rtc = process["handle"].poll()

        if rtc is None:
            # Process is still running, check if it needs to get killed
            if time.time() - process['start'] > TIMEOUT:
                # kills the process!
                process["handle"].terminate()
                process["handle"].wait()
                processes[i]['returncode'] = 'timeout'
        else:
            processes[i]['returncode'] = rtc

    time.sleep(0.1)

for p in processes:
    print(p)

Out:

{'handle': <subprocess.Popen object at 0x10d4d3040>, 'start': 1644318572.923203, 'returncode': 0}
{'handle': <subprocess.Popen object at 0x10d4ee7c0>, 'start': 1644318572.9256551, 'returncode': 0}
{'handle': <subprocess.Popen object at 0x10d550d30>, 'start': 1644318572.928237, 'returncode': 0}
{'handle': <subprocess.Popen object at 0x10d550d90>, 'start': 1644318572.930966, 'returncode': 0}
{'handle': <subprocess.Popen object at 0x10d50fa60>, 'start': 1644318572.934939, 'returncode': 0}
{'handle': <subprocess.Popen object at 0x10d805250>, 'start': 1644318572.937738, 'returncode': 'timeout'}
{'handle': <subprocess.Popen object at 0x10d82f250>, 'start': 1644318572.940351, 'returncode': 'timeout'}
{'handle': <subprocess.Popen object at 0x10d82f370>, 'start': 1644318572.943875, 'returncode': 'timeout'}
{'handle': <subprocess.Popen object at 0x10d82f490>, 'start': 1644318572.946584, 'returncode': 'timeout'}


问:
run prepared statement in fat-free framework
I need to run a following prepared statement query in fat-free framework.

I am trying to run the query as normal query.

```<code>public function weeklyLunchReport($date1=null, $date2=null)
{
    $user = AclHelper::getCurrentUser();
    $default_userID = intval($user['user_id']);
    $defDate = new DateTime();
    $default_date = $defDate->format('Y-m-d');

    $date1 = (isset($date1) && $date1 != '') ? $date1 : $default_date;
    $date2 = (isset($date2) && $date2 != '') ? $date2 : $default_date;

    $sql =
    "
    SET @SQL = NULL;

    SELECT
    GROUP_CONCAT(DISTINCT
        CONCAT(
        'SUM(CASE WHEN date = "',dt,'" THEN lunchStatus ELSE 0 END) AS "',dt,'"',
        )
    ) INTO @SQL
    FROM
    (
        SELECT DATE(issuedDateTime) as dt
        FROM `lunch_status`
        WHERE DATE(issuedDateTime) BETWEEN '$date1' AND '$date2'
    ) d;

    SET @SQL
    = CONCAT('SELECT userId, ', @SQL, '
    FROM
    (
        SELECT userId, lunchStatus, DATE(issuedDateTime) as date
        FROM `lunch_status`
        WHERE DATE(issuedDateTime) BETWEEN '$date1' AND '$date2'
    ) as a
    GROUP BY userId;');

    PREPARE stmt FROM @SQL;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    ";
    return $this->db->exec($sql);
}
</code>```

But I know this isn't the right way.

Do I run it as stored procedure?

答:
Put code in stored procedure and call it from F3, something like this:</p>
```<code>$rows = $f3->get('DB')->exec("call my_stored_procedure($var1,$var2,...)");
</code>```

Body:
I need to run a following prepared statement query in fat-free framework.

I am trying to run the query as normal query.

public function weeklyLunchReport($date1=null, $date2=null)
{
    $user = AclHelper::getCurrentUser();
    $default_userID = intval($user['user_id']);
    $defDate = new DateTime();
    $default_date = $defDate->format('Y-m-d');

    $date1 = (isset($date1) && $date1 != '') ? $date1 : $default_date;
    $date2 = (isset($date2) && $date2 != '') ? $date2 : $default_date;

    $sql =
    "
    SET @SQL = NULL;

    SELECT
    GROUP_CONCAT(DISTINCT
        CONCAT(
        'SUM(CASE WHEN date = "',dt,'" THEN lunchStatus ELSE 0 END) AS "',dt,'"',
        )
    ) INTO @SQL
    FROM
    (
        SELECT DATE(issuedDateTime) as dt
        FROM `lunch_status`
        WHERE DATE(issuedDateTime) BETWEEN '$date1' AND '$date2'
    ) d;

    SET @SQL
    = CONCAT('SELECT userId, ', @SQL, '
    FROM
    (
        SELECT userId, lunchStatus, DATE(issuedDateTime) as date
        FROM `lunch_status`
        WHERE DATE(issuedDateTime) BETWEEN '$date1' AND '$date2'
    ) as a
    GROUP BY userId;');

    PREPARE stmt FROM @SQL;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    ";
    return $this->db->exec($sql);
}

But I know this isn't the right way.

Do I run it as stored procedure?

Body:
Put code in stored procedure and call it from F3, something like this:

$rows = $f3->get('DB')->exec("call my_stored_procedure($var1,$var2,...)");


问:
ReactJS not rendering on Laravel
I am trying to render reactJS a component on my laravel (5.7) but it does not seem to show up. This is what my files look like:

welcome.blade.php

```<code><!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}" />
    <title>React JS</title>

    <!-- Fonts -->
    <link href="https://fonts.googleapis.com/css?family=Varela+Round" rel="stylesheet" type="text/css">

    <!-- Styles -->
    <link href="{{asset('css/app.css')}}" rel="stylesheet">

</head>
<body>
    <div id="root"></div>
    <script src="{{asset('js/app.js')}}"></script>
</body>
</html>
</code>```

Example.js

```<code>import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import App from "./App.js";
ReactDOM.render(<App />, document.getElementById("root"));
</code>```

App.js

```<code>import React from 'react';

class App extends React.Component() {
    render(){
        return (
            <div>
                <h1>Hello</h1>
                <p>What a REAVELation</p>
            </div>
        );
    }

}
export default App;
</code>```

npm run watch is running and shows no errors.

Please what might I be doing wrong here?

答:
Add this inside the

```<code><script src="{{ asset('js/manifest.js') }}"></script>
<script src="{{ asset('js/vendor.js') }}"></script>
<script src="{{ asset('js/app.js') }}"></script>
</code>```

One way to solve this issue is by extracting the vendor library code in a separate file. To do so, open the webpack.mix.js file and update its code as follows:

// webpack.mix.js

```<code>const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
    .react()
    .extract(['react'])
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]);

</code>```

Title: ReactJS not rendering on Laravel

Body:
I am trying to render reactJS a component on my laravel (5.7) but it does not seem to show up. This is what my files look like:

welcome.blade.php

<!DOCTYPE html>
getLocale() }}">

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}" />
    <title>React JS</title>

    <link href="https://fonts.googleapis.com/css?family=Varela+Round" rel="stylesheet" type="text/css">

    <link href="{{asset('css/app.css')}}" rel="stylesheet">

Example.js

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import App from "./App.js";
ReactDOM.render(<App />, document.getElementById("root"));

App.js

import React from 'react';

class App extends React.Component() {
    render(){
        return (

Hello

What a REAVELation

        );
    }

}
export default App;

npm run watch is running and shows no errors.

Please what might I be doing wrong here?

Body:
Add this inside the <head> </head>

<script src="{{ asset('js/manifest.js') }}"></script>
<script src="{{ asset('js/vendor.js') }}"></script>
<script src="{{ asset('js/app.js') }}"></script>

One way to solve this issue is by extracting the vendor library code in a separate file. To do so, open the webpack.mix.js file and update its code as follows:

// webpack.mix.js

const mix = require('laravel-mix');

mix.js('resources/js/app.js', 'public/js')
    .react()
    .extract(['react'])
    .postCss('resources/css/app.css', 'public/css', [
        //
    ]);


问:
Elegant way to correctly index a Dataframe after Subsetting
I have the following dummy dataframe with two columns:

```<code>set.seed(666)
df = data.frame(group = rep(c(-1,1), times = 5, each = 1),
                values = runif(10))

   group     values
1     -1 0.77436849
2      1 0.19722419
3     -1 0.97801384
4      1 0.20132735
5     -1 0.36124443
6      1 0.74261194
7     -1 0.97872844
8      1 0.49811371
9     -1 0.01331584
10     1 0.25994613
</code>```

I want to find the row index of the maximum value from group "1" in the original dataframe. Applying which.max() after subsetting the dataframe will return the wrong row:

```<code>which.max(df[df[,1]==1,2]) #returns '3'
</code>```

As a workaround I did the following:

```<code>sdf = df[df[,1] == 1,] # subset of dataframe that keeps row names
rownames(sdf[which.max(sdf[,2]),]) # returns '6'
</code>```

Which does return the correct row index from the original dataframe. However I feel there must be an easier, more elegant solution but can't think of anything else myself. Any ideas?

I feel really stupid for asking this question but it seems I'm overlooking something very simple.

答:
Use match() to create a logical vector with 1 being the group of interest, and NA for all other groups. Use it as a filter on values,

```<code>which.max(match(df$group, 1) * df$values)
</code>```

match(df$group, 1) (for any value, not just 1) returns a vector of NA or 1. Multiplying df$values returns either NA or the original value. which.max() select the maximum of the original values, ignoring (in the calculation of the maximum) the NA values.

Body:
I have the following dummy dataframe with two columns:

set.seed(666)
df = data.frame(group = rep(c(-1,1), times = 5, each = 1),
                values = runif(10))

   group     values
1     -1 0.77436849
2      1 0.19722419
3     -1 0.97801384
4      1 0.20132735
5     -1 0.36124443
6      1 0.74261194
7     -1 0.97872844
8      1 0.49811371
9     -1 0.01331584
10     1 0.25994613

I want to find the row index of the maximum value from group "1" in the original dataframe. Applying which.max() after subsetting the dataframe will return the wrong row:

which.max(df[df[,1]==1,2]) #returns '3'

As a workaround I did the following:

sdf = df[df[,1] == 1,] # subset of dataframe that keeps row names
rownames(sdf[which.max(sdf[,2]),]) # returns '6'

Which does return the correct row index from the original dataframe. However I feel there must be an easier, more elegant solution but can't think of anything else myself. Any ideas?

I feel really stupid for asking this question but it seems I'm overlooking something very simple.

Body:
Use match() to create a logical vector with 1 being the group of interest, and NA for all other groups. Use it as a filter on values,

which.max(match(df$group, 1) * df$values)

match(df$group, 1) (for any value, not just 1) returns a vector of NA or 1. Multiplying df$values returns either NA or the original value. which.max() select the maximum of the original values, ignoring (in the calculation of the maximum) the NA values.


问:
Precedence of function application
In order to illustrate function application has the highest precedence in Haskell the following example was provided (by schoolofhaskell):

```<code>sq b = b * b
main = print $
-- show
    sq 3+1
-- /show
</code>```

The result here is 10.

What puzzles me is that the argument constitutes a function application too. Consider the operator + being a short-cut of a function. So when the argument is taken, I would expect that its function application now takes precedence over the original one.

Written that way it delivers the expected result:

```<code>sq b = b * b
main = print $
    sq ((+) 3 1 )
</code>```

Any explanation?

答:
So when the argument is taken, would expect that its function application now takes precedence over the original one.

The Haskell grammar [Haskell report] specifies:

```exp<sup><strong>10</strong></sup>
  → …
  | …
  | fexp
fexp
  →  [fexp] aexp   (function application)```

This means that function application syntax has precedence 10 (the superscript on the exp10 part).

This means that, when your expression is parsed, the empty space in sq 3 takes precedence over the + in 3+1, and thus sq 3+1 is interpreted as (sq 3) + 1 which semantically means that it squares 3 first, and then adds 1 to the result, and will thus  produce 10.

If you write it as sq (3 + 1) or in canonical form as sq ((+) 3 1) it will first sum up 3 and 1 and then determine the square which will produce 16.

Title: Precedence of function application

Body:
In order to illustrate function application has the highest precedence in Haskell the following example was provided (by schoolofhaskell):

sq b = b * b
main = print $
-- show
    sq 3+1
-- /show

The result here is 10.

What puzzles me is that the argument constitutes a function application too. Consider the operator + being a short-cut of a function. So when the argument is taken, I would expect that its function application now takes precedence over the original one.

Written that way it delivers the expected result:

sq b = b * b
main = print $
    sq ((+) 3 1 )

Any explanation?

Body:
So when the argument is taken, would expect that its function application now takes precedence over the original one.

The Haskell grammar [Haskell report] specifies:

exp10
  → …
  | …
  | fexp
fexp
  →  [fexp] aexp   (function application)

This means that function application syntax has precedence 10 (the superscript on the exp10 part).

This means that, when your expression is parsed, the empty space in sq 3 takes precedence over the + in 3+1, and thus sq 3+1 is interpreted as (sq 3) + 1 which semantically means that it squares 3 first, and then adds 1 to the result, and will thus  produce 10.

If you write it as sq (3 + 1) or in canonical form as sq ((+) 3 1) it will first sum up 3 and 1 and then determine the square which will produce 16.