问:
SemaphoreSlim vs Parallel Processing for API post calls in .NET
I have a chron job which calls a database table and gets about half a million records returned. I need to loop through all of that data, and send API post's to a third party API. In general, this works fine, but the processing time is forever (10 hours). I need a way to speed it up. I've been trying to use a list of Task with SemaphoreSlim, but running into issues (it doesn't like that my api call returns a Task). I'm wondering if anyone has a solution to this that won't destroy the VM's memory?

Current code looks something like:

```<code>foreach(var data in dataList)
{
  try
  {
    var response = await _apiService.PostData(data);
    _logger.Trace(response.Message);
  } catch//
}
</code>```

But I'm trying to do this and getting the syntax wrong:

```<code>var tasks = new List<Task<DataObj>>();
var throttler = new SemaphoreSlim(10);
foreach(var data in dataList)
{
  await throttler.WaitAsync();
  tasks.Add(Task.Run(async () => {
    try
    {
      var response = await _apiService.PostData(data);
        _logger.Trace(response.Message);
    }
    finally
    {
      throttler.Release();
    }
  }));
}
</code>```

答:
Your list is of type Task<DataObj>, but your async lambda doesn't return anything, so its return type is Task. To fix the syntax, just return the value:

```<code>var response = await _apiService.PostData(data);
_logger.Trace(response.Message);
return response;
</code>```

As others have noted in the comments, I also recommend not using Task.Run here. A local async method would work fine:

```<code>var tasks = new List<Task<DataObj>>();
var throttler = new SemaphoreSlim(10);
foreach(var data in dataList)
{
  tasks.Add(ThrottledPostData(data));
}
var results = await Task.WhenAll(tasks);

async Task<DataObj> ThrottledPostData(Data data)
{
  await throttler.WaitAsync();
  try
  {
    var response = await _apiService.PostData(data);
    _logger.Trace(response.Message);
    return response;
  }
  finally
  {
    throttler.Release();
  }
}
</code>```

Body:
I have a chron job which calls a database table and gets about half a million records returned. I need to loop through all of that data, and send API post's to a third party API. In general, this works fine, but the processing time is forever (10 hours). I need a way to speed it up. I've been trying to use a list of Task with SemaphoreSlim, but running into issues (it doesn't like that my api call returns a Task). I'm wondering if anyone has a solution to this that won't destroy the VM's memory?

Current code looks something like:

foreach(var data in dataList)
{
  try
  {
    var response = await _apiService.PostData(data);
    _logger.Trace(response.Message);
  } catch//
}

But I'm trying to do this and getting the syntax wrong:

var tasks = new List<Task<DataObj>>();
var throttler = new SemaphoreSlim(10);
foreach(var data in dataList)
{
  await throttler.WaitAsync();
  tasks.Add(Task.Run(async () => {
    try
    {
      var response = await _apiService.PostData(data);
        _logger.Trace(response.Message);
    }
    finally
    {
      throttler.Release();
    }
  }));
}

Body:
Your list is of type Task<DataObj>, but your async lambda doesn't return anything, so its return type is Task. To fix the syntax, just return the value:

var response = await _apiService.PostData(data);
_logger.Trace(response.Message);
return response;

As others have noted in the comments, I also recommend not using Task.Run here. A local async method would work fine:

var tasks = new List<Task<DataObj>>();
var throttler = new SemaphoreSlim(10);
foreach(var data in dataList)
{
  tasks.Add(ThrottledPostData(data));
}
var results = await Task.WhenAll(tasks);

async Task<DataObj> ThrottledPostData(Data data)
{
  await throttler.WaitAsync();
  try
  {
    var response = await _apiService.PostData(data);
    _logger.Trace(response.Message);
    return response;
  }
  finally
  {
    throttler.Release();
  }
}


来源: stackexchange

问:
Preventing duplicate accounts from being made, infinite amount of messages
I have been writing code for my Computer Science Internal assessment, I am close to finishing it but keep finding this error, I am unsure how to solve it.

Here is my code for that section:

```<code>JButton createbutton = new JButton("Create");
createbutton.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        String[] characters = { "!", "#", "$", "%", "^", "&", "*" };
        boolean passcontains = false;
        for (int i = 0; i < characters.length; i++) {
            if (new String(passwordfield.getPassword()).contains(new String(characters[i]))) {
                passcontains = true;
            }
        }
        boolean emcontains = false;
        for (int i = 0; i < characters.length; i++) {
            if (new String(emailfield.getText()).contains(new String(characters[i]))) {
                emcontains = true;
            }
        }
        loop: if (passwordfield.getPassword().length == 0
                || passwordfield.getPassword().length < 8
                || passcontains == false) {
            message("INCORRECT PASSWORD\ncheck README");
        } else {
            if (emailfield.getText().length() == 0 || emcontains
                    || emailfield.getText().contains("@") == false
                    || emailfield.getText().contains(".") == false) {
                message("INCORRECT EMAIL\ncheck README");
            } else {
                boolean pass = true;
                for (int i = 0; i < database.size(); i++) {
                    if (database.get(i).getEmail() == emailfield.getText()) {
                        pass = false;
                    }
                }
                if (pass == true) {
                    database.add(
                            create(emailfield.getText(), new String(passwordfield.getPassword())));
                    write();
                    frame.setVisible(false);
                    message("SUCCESSFULLY MADE ACCOUNT");
                    frame.dispose();
                } else {
                    message("AN ACCOUNT WITH THAT EMAIL ALREADY EXISTS\n GO TO LOGIN");
                    emailfield.setText("");
                    passwordfield.setText("");
                    break loop;
                }
            }
        }
    }
});
</code>```

EDIT:
I have resolved the issue myself, I had a function which went to 'create(input1, input2)' but due to my previous version of the code the checking algorithm was included in there, therefore it completed the checking twice and entered a while loop.
Thank you for the response(s).

答:
Don't do that!

Follow Separation of Concerns and Single Responsibility Principle.

Don't put such logic to the code that is responsible for showing things to the user. Keep the business logic of your application away from GUI code. Create some classes and put the code with logic there. Then in your GUI you will call this code in a simple way and everything will be better. The fact this is a school project, does not mean that you deliver the code that "just works".

Check my approach:

```<code>public class Account {

    private final Email email;
    private final Password password;

    public Account(Email email, Password password) {
        Objects.requireNonNull(email, "An account cannot have null email");
        Objects.requireNonNull(email, "An account cannot have null password");
        this.email = email;
        this.password = password;
    }

    public Email getEmail() {
        return email;
    }

    public Password getPassword() {
        return password;
    }

    public static class InvalidAccountInformationException extends RuntimeException {

        public InvalidAccountInformationException(String message) {
            super(message);
        }
    }
}
</code>```

.

```<code>public class Email {
    private final String value;

    private Email(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }

    // Eclipse generated
    @Override
    public int hashCode() {
        return Objects.hash(value);
    }

    // Eclipse generated
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Email other = (Email) obj;
        return Objects.equals(value, other.value);
    }

    public static Email of(final String email) {
        if (email == null)
            throw new InvalidAccountInformationException("Email cannot be empty.");

        String trimmedEmail = email.trim();

        if (trimmedEmail.isEmpty())
            throw new InvalidAccountInformationException("Email cannot be empty.");

        if (!isValidEmailAddress(trimmedEmail))
            throw new InvalidAccountInformationException("Email is not a valid email address.");

        return new Email(trimmedEmail);
    }

    /*
     * Shamelessly copy-pasta from https://stackoverflow.com/a/16058059/6579265
     */
    private static boolean isValidEmailAddress(String email) {
        String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}"
                + "\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
        java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
        java.util.regex.Matcher m = p.matcher(email);
        return m.matches();
    }
}
</code>```

.

```<code>public class Password {
    private static final String[] MANDATORY_CHARACTERS = { "!", "#", "$", "%", "^", "&", "*" };
    private final String value;

    private Password(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }

    public static Password of(final String pass) {
        if (pass == null || pass.trim().isEmpty())
            throw new InvalidAccountInformationException("Password cannot be empty.");

        if (!containsAtLeastOneMandatoryCharacter(pass))
            throw new InvalidAccountInformationException("Password is too weak.");

        return new Password(pass);
    }

    private static boolean containsAtLeastOneMandatoryCharacter(String pass) {
        return Stream.of(MANDATORY_CHARACTERS).anyMatch(pass::contains);
    }

    // Eclipse generated
    @Override
    public int hashCode() {
        return Objects.hash(value);
    }

    // Eclipse generated
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Password other = (Password) obj;
        return Objects.equals(value, other.value);
    }

}
</code>```

.

```<code>public class AccountDatabase {

    private final List<Account> accounts = new ArrayList<>();

    public void save(Account account) {
        Objects.requireNonNull(account, "Account should not be null");

        if (emailIsAlreadyTaken(account))
            throw new InvalidAccountInformationException("Email is already taken by another user.");

        accounts.add(account);
    }

    private boolean emailIsAlreadyTaken(Account account) {
        return accounts.stream().map(Account::getEmail).anyMatch(account::equals);
    }
}
</code>```

And then, in the GUI (ActionListener) the code looks like:

```<code>AccountDatabase database = ...

try {
    Email email = Email.of(emailField.getText());
    Password pass = Password.of(passwordField.getText());

    Account account = new Account(email, pass);

    database.save(account);
} catch (InvalidAccountInformationException ex) {
    showToUser(ex.getMessage());
    resetTextFieldsToEmptyTextSoUserCanFillThemAgain();
}
</code>```

What did you achieve? To always be in a consistent state! Your application will never allow a non-valid password. You want to add or remove password validations, like length and etc? You edit the Password class. Not some weird, full of noise class. Your GUI does simple calls to this classes that contain the actual logic.

In addition, you achieve testability. How would you test in an automated-way your GUI code? This is a complex topic and for sure it is not the best way to test application logic through the UI. Extracting logic and rules to other classes, you can "just test them":

```<code>public class PasswordShould {

    @Test
    void not_be_valid_when_is_empty() {
        assertThrows(RuntimeException.class, () -> Password.of(null));
        assertThrows(RuntimeException.class, () -> Password.of(""));
        assertThrows(RuntimeException.class, () -> Password.of("  "));
    }

    @Test
    void not_be_valid_when_is_weak() {
        assertThrows(RuntimeException.class, () -> Password.of("1234"));
        assertThrows(RuntimeException.class, () -> Password.of("GGfdsfds12312"));
    }

    @Test
    void be_valid_when_is_strong() {
        assertDoesNotThrow(() -> Password.of("GGf##dsfds12312"));
    }
}
</code>```

My code might be a lot to digest, but I suggest to give it a try to understand it. First of all, take a look at the readability. You came here, because you can't debug your own code. Well...Neither can we.

ContentLicense: CC BY-SA 4.0

Body:
I have been writing code for my Computer Science Internal assessment, I am close to finishing it but keep finding this error, I am unsure how to solve it.

Here is my code for that section:

JButton createbutton = new JButton("Create");
createbutton.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        String[] characters = { "!", "#", "$", "%", "^", "&", "*" };
        boolean passcontains = false;
        for (int i = 0; i < characters.length; i++) {
            if (new String(passwordfield.getPassword()).contains(new String(characters[i]))) {
                passcontains = true;
            }
        }
        boolean emcontains = false;
        for (int i = 0; i < characters.length; i++) {
            if (new String(emailfield.getText()).contains(new String(characters[i]))) {
                emcontains = true;
            }
        }
        loop: if (passwordfield.getPassword().length == 0
                || passwordfield.getPassword().length < 8
                || passcontains == false) {
            message("INCORRECT PASSWORD\ncheck README");
        } else {
            if (emailfield.getText().length() == 0 || emcontains
                    || emailfield.getText().contains("@") == false
                    || emailfield.getText().contains(".") == false) {
                message("INCORRECT EMAIL\ncheck README");
            } else {
                boolean pass = true;
                for (int i = 0; i < database.size(); i++) {
                    if (database.get(i).getEmail() == emailfield.getText()) {
                        pass = false;
                    }
                }
                if (pass == true) {
                    database.add(
                            create(emailfield.getText(), new String(passwordfield.getPassword())));
                    write();
                    frame.setVisible(false);
                    message("SUCCESSFULLY MADE ACCOUNT");
                    frame.dispose();
                } else {
                    message("AN ACCOUNT WITH THAT EMAIL ALREADY EXISTS\n GO TO LOGIN");
                    emailfield.setText("");
                    passwordfield.setText("");
                    break loop;
                }
            }
        }
    }
});

EDIT:
I have resolved the issue myself, I had a function which went to 'create(input1, input2)' but due to my previous version of the code the checking algorithm was included in there, therefore it completed the checking twice and entered a while loop.
Thank you for the response(s).

Body:
Don't do that!

Follow Separation of Concerns and Single Responsibility Principle.

Don't put such logic to the code that is responsible for showing things to the user. Keep the business logic of your application away from GUI code. Create some classes and put the code with logic there. Then in your GUI you will call this code in a simple way and everything will be better. The fact this is a school project, does not mean that you deliver the code that "just works".

Check my approach:

public class Account {

    private final Email email;
    private final Password password;

    public Account(Email email, Password password) {
        Objects.requireNonNull(email, "An account cannot have null email");
        Objects.requireNonNull(email, "An account cannot have null password");
        this.email = email;
        this.password = password;
    }

    public Email getEmail() {
        return email;
    }

    public Password getPassword() {
        return password;
    }

    public static class InvalidAccountInformationException extends RuntimeException {

        public InvalidAccountInformationException(String message) {
            super(message);
        }
    }
}

.

public class Email {
    private final String value;

    private Email(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }

    // Eclipse generated
    @Override
    public int hashCode() {
        return Objects.hash(value);
    }

    // Eclipse generated
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Email other = (Email) obj;
        return Objects.equals(value, other.value);
    }

    public static Email of(final String email) {
        if (email == null)
            throw new InvalidAccountInformationException("Email cannot be empty.");

        String trimmedEmail = email.trim();

        if (trimmedEmail.isEmpty())
            throw new InvalidAccountInformationException("Email cannot be empty.");

        if (!isValidEmailAddress(trimmedEmail))
            throw new InvalidAccountInformationException("Email is not a valid email address.");

        return new Email(trimmedEmail);
    }

    /*
     * Shamelessly copy-pasta from https://stackoverflow.com/a/16058059/6579265
     */
    private static boolean isValidEmailAddress(String email) {
        String ePattern = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@((\\[[0-9]{1,3}\\.[0-9]{1,3}"
                + "\\.[0-9]{1,3}\\.[0-9]{1,3}\\])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$";
        java.util.regex.Pattern p = java.util.regex.Pattern.compile(ePattern);
        java.util.regex.Matcher m = p.matcher(email);
        return m.matches();
    }
}

.

public class Password {
    private static final String[] MANDATORY_CHARACTERS = { "!", "#", "$", "%", "^", "&", "*" };
    private final String value;

    private Password(String value) {
        this.value = value;
    }

    public String value() {
        return value;
    }

    public static Password of(final String pass) {
        if (pass == null || pass.trim().isEmpty())
            throw new InvalidAccountInformationException("Password cannot be empty.");

        if (!containsAtLeastOneMandatoryCharacter(pass))
            throw new InvalidAccountInformationException("Password is too weak.");

        return new Password(pass);
    }

    private static boolean containsAtLeastOneMandatoryCharacter(String pass) {
        return Stream.of(MANDATORY_CHARACTERS).anyMatch(pass::contains);
    }

    // Eclipse generated
    @Override
    public int hashCode() {
        return Objects.hash(value);
    }

    // Eclipse generated
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Password other = (Password) obj;
        return Objects.equals(value, other.value);
    }

}

.

public class AccountDatabase {

    private final List<Account> accounts = new ArrayList<>();

    public void save(Account account) {
        Objects.requireNonNull(account, "Account should not be null");

        if (emailIsAlreadyTaken(account))
            throw new InvalidAccountInformationException("Email is already taken by another user.");

        accounts.add(account);
    }

    private boolean emailIsAlreadyTaken(Account account) {
        return accounts.stream().map(Account::getEmail).anyMatch(account::equals);
    }
}

And then, in the GUI (ActionListener) the code looks like:

AccountDatabase database = ...

try {
    Email email = Email.of(emailField.getText());
    Password pass = Password.of(passwordField.getText());

    Account account = new Account(email, pass);

    database.save(account);
} catch (InvalidAccountInformationException ex) {
    showToUser(ex.getMessage());
    resetTextFieldsToEmptyTextSoUserCanFillThemAgain();
}

What did you achieve? To always be in a consistent state! Your application will never allow a non-valid password. You want to add or remove password validations, like length and etc? You edit the Password class. Not some weird, full of noise class. Your GUI does simple calls to this classes that contain the actual logic.

In addition, you achieve testability. How would you test in an automated-way your GUI code? This is a complex topic and for sure it is not the best way to test application logic through the UI. Extracting logic and rules to other classes, you can "just test them":

public class PasswordShould {

    @Test
    void not_be_valid_when_is_empty() {
        assertThrows(RuntimeException.class, () -> Password.of(null));
        assertThrows(RuntimeException.class, () -> Password.of(""));
        assertThrows(RuntimeException.class, () -> Password.of("  "));
    }

    @Test
    void not_be_valid_when_is_weak() {
        assertThrows(RuntimeException.class, () -> Password.of("1234"));
        assertThrows(RuntimeException.class, () -> Password.of("GGfdsfds12312"));
    }

    @Test
    void be_valid_when_is_strong() {
        assertDoesNotThrow(() -> Password.of("GGf##dsfds12312"));
    }
}

My code might be a lot to digest, but I suggest to give it a try to understand it. First of all, take a look at the readability. You came here, because you can't debug your own code. Well...Neither can we.


问:
SQLAlchemy distinct() filter on one column
I´m trying to get distinct rows of a certain column (and some other columns as well) filtering by a value in that same column. As the other columns in the query have unique values, I´m getting all the rows.

This is the subquery and query. I´m using this method because the join() -which is done on c_id column) is much more efficient than including it in the main query. My table has more than 2M rows and growing.

```<code>search_string = <some_str_value>
per_page = <some_int_value>

eventsQ1d = db.session.query(Events.p_id, Events.timestamp_event, Events.c_id).distinct(Events.p_id)\
                                    .filter(Events.p_id.contains(search_string))\
                                    .order_by(Events.timestamp_event.desc())\
                                    .limit(per_page).subquery()

eventsQd = db.session.query(eventsQ1d, Devices.name).join(Devices).all()
</code>```

Given this Events table:

```<code>p_id   timestamp_event  c_id
------ ---------------  -----
ABC    2022-01-15 12:34 001
ABA    2022-02-03 11:21 002
ABC    2022-02-01 10:01 002
XYZ    2022-01-22 09:02 001
</code>```

when I search by "AB" I would like to get 2 rows (ABC and ABA, plus the other columns in Events and Devices tables) but instead I´m getting the 3 rows that contain the search string.

Basically I don´t know how to make the distinct() clause work only on p_id column.

答:
This gets the job done, and with great performance (less than 2 seconds in the +2M rows table):

```<code>eventsQ1d = db.session.query(Events.p_id, Events.timestamp_event, Events.c_id)\
                                    .filter(Events.p_id.contains(search_string))\
                                    .order_by(Events.timestamp_event.desc())\
                                    .limit(per_page).subquery()

eventsQd = db.session.query(eventsQ1d, Devices.name).group_by(eventsQ1.c.p_id).join(Devices).all()
</code>```

The grouping is done at the join operation. No distinct() required.

Body:
I´m trying to get distinct rows of a certain column (and some other columns as well) filtering by a value in that same column. As the other columns in the query have unique values, I´m getting all the rows.

This is the subquery and query. I´m using this method because the join() -which is done on c_id column) is much more efficient than including it in the main query. My table has more than 2M rows and growing.

search_string = <some_str_value>
per_page = <some_int_value>

eventsQ1d = db.session.query(Events.p_id, Events.timestamp_event, Events.c_id).distinct(Events.p_id)\
                                    .filter(Events.p_id.contains(search_string))\
                                    .order_by(Events.timestamp_event.desc())\
                                    .limit(per_page).subquery()

eventsQd = db.session.query(eventsQ1d, Devices.name).join(Devices).all()

Given this Events table:

p_id   timestamp_event  c_id
------ ---------------  -----
ABC    2022-01-15 12:34 001
ABA    2022-02-03 11:21 002
ABC    2022-02-01 10:01 002
XYZ    2022-01-22 09:02 001

when I search by "AB" I would like to get 2 rows (ABC and ABA, plus the other columns in Events and Devices tables) but instead I´m getting the 3 rows that contain the search string.

Basically I don´t know how to make the distinct() clause work only on p_id column.

Body:
This gets the job done, and with great performance (less than 2 seconds in the +2M rows table):

eventsQ1d = db.session.query(Events.p_id, Events.timestamp_event, Events.c_id)\
                                    .filter(Events.p_id.contains(search_string))\
                                    .order_by(Events.timestamp_event.desc())\
                                    .limit(per_page).subquery()

eventsQd = db.session.query(eventsQ1d, Devices.name).group_by(eventsQ1.c.p_id).join(Devices).all()

The grouping is done at the join operation. No distinct() required.


问:
Problems installing Repast HPC 2.3.1 on MacOS
Updated:
I am trying to install repast hpc 2.3.1 on my MacBook Pro with M1 processor, however I run into the following issue. I am following the Install.txt instructions included in the package. The issue now occurs when I try to use ./install rhpc I get the following errors, which seem to stem from the GridComponents.o file failing to find the DBL_MAX variable and marking it as undeclared:

```<code>checking for mpicc... mpicc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether mpicc accepts -g... yes
checking for mpicc option to accept ISO C89... none needed
checking whether we are using the GNU C++ compiler... yes
checking whether /Users/alxndr/sfw/MPICH/bin//mpicxx accepts -g... yes
checking for ar... ar
checking for ranlib... ranlib
detected Mac.
checking for cp that supports -u... no
checking for grep that handles long lines and -e... /usr/bin/grep
checking how to run the C preprocessor... mpicc -E
checking for a sed that does not truncate output... /usr/bin/sed
checking for Boost headers version >= 0... yes
checking for Boost's header version... 1_78
checking build system type... arm-apple-darwin20.6.0
checking host system type... arm-apple-darwin20.6.0
checking for the toolset name used by Boost for /Users/alxndr/sfw/MPICH/bin//mpicxx... xgcc42 -xgcc
checking how to run the C++ preprocessor... /Users/alxndr/sfw/MPICH/bin//mpicxx -E
checking for egrep... /usr/bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking boost/archive/text_oarchive.hpp usability... yes
checking boost/archive/text_oarchive.hpp presence... yes
checking for boost/archive/text_oarchive.hpp... yes
checking for the Boost serialization library... yes
checking boost/mpi.hpp usability... yes
checking boost/mpi.hpp presence... yes
checking for boost/mpi.hpp... yes
checking for the Boost mpi library... yes
checking boost/system/error_code.hpp usability... yes
checking boost/system/error_code.hpp presence... yes
checking for boost/system/error_code.hpp... yes
checking for the Boost system library... yes
checking boost/filesystem/path.hpp usability... yes
checking boost/filesystem/path.hpp presence... yes
checking for boost/filesystem/path.hpp... yes
checking for the Boost filesystem library... yes
checking for boost/system/error_code.hpp... (cached) yes
checking for the Boost system library... (cached) yes
checking for curl_version in -lcurl... yes
checking for nc_open in -lnetcdf... yes
checking netcdfcpp.h usability... yes
checking netcdfcpp.h presence... yes
checking for netcdfcpp.h... yes
checking for stdbool.h that conforms to C99... yes
checking for _Bool... yes
checking for an ANSI C-conforming const... yes
checking for inline... inline
checking for size_t... yes
checking whether struct tm is in sys/time.h or time.h... time.h
checking for uint32_t... yes
checking for ptrdiff_t... yes
checking for error_at_line... no
checking for ANSI C header files... (cached) yes
checking for floor... yes
checking for rint... yes
checking for sqrt... yes
configure: creating ./config.status
config.status: creating Makefile
config.status: creating config.h
  CC        src/repast_hpc/AgentId.o
  CC        src/repast_hpc/AgentImporterExporter.o
  CC        src/repast_hpc/AgentRequest.o
  CC        src/repast_hpc/AgentStatus.o
  CC        src/repast_hpc/CartesianTopology.o
  CC        src/repast_hpc/Graph.o
  CC        src/repast_hpc/GridComponents.o
src/repast_hpc/GridComponents.cpp:165:64: error: use of undeclared identifier 'DBL_MAX'
      if(out[i] >= maxs[i])       out[i] = nextafter(maxs[i], -DBL_MAX);
                                                               ^
src/repast_hpc/GridComponents.cpp:166:64: error: use of undeclared identifier 'DBL_MAX'
      else if(out[i] < mins[i])   out[i] = nextafter(mins[i],  DBL_MAX);
                                                               ^
2 errors generated.
make: *** [src/repast_hpc/GridComponents.o] Error 1
</code>```

答:
I've outlined all the required fixes (including the DBL_MAX fix) here: https://github.com/Repast/repast.hpc/issues/7. With those in place, the zombies and rumor demo models work on macOS on an M1 Max laptop.

All that said, and as an aside, we typically do our repast hpc and repast4py development work on a Linux VM running under Parallels or VMWare Fusion on a Mac. This is because that more closely matches the cluster or HPC environments we ultimately run the models on.

Body:
Updated:
I am trying to install repast hpc 2.3.1 on my MacBook Pro with M1 processor, however I run into the following issue. I am following the Install.txt instructions included in the package. The issue now occurs when I try to use ./install rhpc I get the following errors, which seem to stem from the GridComponents.o file failing to find the DBL_MAX variable and marking it as undeclared:

checking for mpicc... mpicc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether mpicc accepts -g... yes
checking for mpicc option to accept ISO C89... none needed
checking whether we are using the GNU C++ compiler... yes
checking whether /Users/alxndr/sfw/MPICH/bin//mpicxx accepts -g... yes
checking for ar... ar
checking for ranlib... ranlib
detected Mac.
checking for cp that supports -u... no
checking for grep that handles long lines and -e... /usr/bin/grep
checking how to run the C preprocessor... mpicc -E
checking for a sed that does not truncate output... /usr/bin/sed
checking for Boost headers version >= 0... yes
checking for Boost's header version... 1_78
checking build system type... arm-apple-darwin20.6.0
checking host system type... arm-apple-darwin20.6.0
checking for the toolset name used by Boost for /Users/alxndr/sfw/MPICH/bin//mpicxx... xgcc42 -xgcc
checking how to run the C++ preprocessor... /Users/alxndr/sfw/MPICH/bin//mpicxx -E
checking for egrep... /usr/bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking boost/archive/text_oarchive.hpp usability... yes
checking boost/archive/text_oarchive.hpp presence... yes
checking for boost/archive/text_oarchive.hpp... yes
checking for the Boost serialization library... yes
checking boost/mpi.hpp usability... yes
checking boost/mpi.hpp presence... yes
checking for boost/mpi.hpp... yes
checking for the Boost mpi library... yes
checking boost/system/error_code.hpp usability... yes
checking boost/system/error_code.hpp presence... yes
checking for boost/system/error_code.hpp... yes
checking for the Boost system library... yes
checking boost/filesystem/path.hpp usability... yes
checking boost/filesystem/path.hpp presence... yes
checking for boost/filesystem/path.hpp... yes
checking for the Boost filesystem library... yes
checking for boost/system/error_code.hpp... (cached) yes
checking for the Boost system library... (cached) yes
checking for curl_version in -lcurl... yes
checking for nc_open in -lnetcdf... yes
checking netcdfcpp.h usability... yes
checking netcdfcpp.h presence... yes
checking for netcdfcpp.h... yes
checking for stdbool.h that conforms to C99... yes
checking for _Bool... yes
checking for an ANSI C-conforming const... yes
checking for inline... inline
checking for size_t... yes
checking whether struct tm is in sys/time.h or time.h... time.h
checking for uint32_t... yes
checking for ptrdiff_t... yes
checking for error_at_line... no
checking for ANSI C header files... (cached) yes
checking for floor... yes
checking for rint... yes
checking for sqrt... yes
configure: creating ./config.status
config.status: creating Makefile
config.status: creating config.h
  CC        src/repast_hpc/AgentId.o
  CC        src/repast_hpc/AgentImporterExporter.o
  CC        src/repast_hpc/AgentRequest.o
  CC        src/repast_hpc/AgentStatus.o
  CC        src/repast_hpc/CartesianTopology.o
  CC        src/repast_hpc/Graph.o
  CC        src/repast_hpc/GridComponents.o
src/repast_hpc/GridComponents.cpp:165:64: error: use of undeclared identifier 'DBL_MAX'
      if(out[i] >= maxs[i])       out[i] = nextafter(maxs[i], -DBL_MAX);
                                                               ^
src/repast_hpc/GridComponents.cpp:166:64: error: use of undeclared identifier 'DBL_MAX'
      else if(out[i] < mins[i])   out[i] = nextafter(mins[i],  DBL_MAX);
                                                               ^
2 errors generated.
make: *** [src/repast_hpc/GridComponents.o] Error 1


问:
How to convert Datetime from (ddmmyyyy hh:mm:ss) to (ddmmmyyyy:00:00:00) [SAS]
I need to convert hour, minutes and seconds to 00:00:00

I´ve tried a lot but i got nothing but the real time.

data pr; dat=put(date()-1,yymmddn.); datsas=PUT(datetime(), datetime.); run;

Thank You!

答:
Do you have a datetime value already?  If you want to remove the timepart from that datetime value you can just use subtraction.

```<code>midnight = datetime - timepart(datetime);
</code>```

Or you could take the datepart and recreate a datetime value from it.

```<code>midnight = dhms(datepart(datetime),0,0,0);
</code>```

Or you could use INTNX() function to transform to the start of the current DTDAY interval

```<code>midnight = intnx('dtday',datetime,0,'b');
</code>```

Body:
Do you have a datetime value already?  If you want to remove the timepart from that datetime value you can just use subtraction.

midnight = datetime - timepart(datetime);

Or you could take the datepart and recreate a datetime value from it.

midnight = dhms(datepart(datetime),0,0,0);

Or you could use INTNX() function to transform to the start of the current DTDAY interval

midnight = intnx('dtday',datetime,0,'b');


问:
Make Image Clickable on Slide Show
I'm using this code for slide show. I can't seem to get the image clickable without losing the name in the 'name' div.

What I'm after is to be able to click on a picture on the slide show and be able to go to the details page. Whenever I get the image clickable, the name does not display in the 'name' div; and if I remove the link, then the name will display.

I don't know how to solve this problem.

Here's the code I'm using.

```<code><!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>JQuery Cycle Plugin - Pager Demo with Prev/Next Controls</title>
<link rel="stylesheet" type="text/css" media="screen" href="../jq.css" />
<link rel="stylesheet" type="text/css" media="screen" href="cycle.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="http://malsup.github.com/chili-1.7.pack.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.cycle.all.js"></script>

<style type="text/css">
#main { margin: 20px }
#nav { margin: 10px; position: relative }
#nav li { float: left; list-style: none}
#nav a { margin: 5px; padding: 3px 5px; border: 1px solid #ccc; background: #fc0; text-decoration: none }
#nav li.activeSlide a { background: #faa; color: black }
#nav a:focus { outline: none; }

</style>

<script type="text/javascript">
$(document).ready(function() {
     $('#slideshow').cycle({
          prev:    '.prev', // Setup prev links
          next:    '.next', // Setup next links
          pager:   '.nav',       // Setup pager navs
          before: function () {
          $("#name").text(this.alt);     }
     });
});
</script>

<style type="text/css">
#left, #slideshow, #right { float: left; width: 200px; }
</style>
</head>
<body>

<!-- left nav bar -->
<div id="left">
    <a href="#"><span class="prev">Prev</span></a>
    <a href="#"><span class="next">Next</span></a>

    <ul class="nav"></ul>
</div>

<!-- slideshow -->
<div id="slideshow">

 <?php
                 mysql_connect("localhost", "root", "")or die("cannot connect");
                 mysql_select_db($db_name)or die("cannot select DB");

                 $data = mysql_query("SELECT * FROM people") or die(mysql_error());
                 while($info = mysql_fetch_array( $data )){
    <!--HERE ON THIS LINE---- > echo "<a href=\"show.php?id=".$info['id']."\"><img src=\"http://localhost:8080/about/images/".$info['photo'] . "\" alt=\"".$info['name'] ."\"/>";
  }
?>

</div>

 <div id="name">

 </div>
 <!-- right nav bar -->
 <div id="right">
     <a href="#"><span class="prev">Prev</span></a>
     <a href="#"><span class="next">Next</span></a>
     <ul class="nav"></ul>
 </div>

 </div>

</body>
</html>
</code>```

Thanks for your assistance

答:
Never used cycle plugin personally, but I think you are not attaching click callback to the image at all. Instead, you  attaching it on before, which makes name be displayed in your div when images start swapping. See cycle plugin reference for details

To display image name on click use the following code:

```<code>$('.clickable_image').click(function(){
    $('#name').html($(this).attr('alt'));
});
</code>```

Don't forget to add class clickable_image to your images.

Also, if you plan add images dynamically, live function may be helpful.

ContentLicense: CC BY-SA 3.0

Title: Make Image Clickable on Slide Show

Body:
I'm using this code for slide show. I can't seem to get the image clickable without losing the name in the 'name' div.

What I'm after is to be able to click on a picture on the slide show and be able to go to the details page. Whenever I get the image clickable, the name does not display in the 'name' div; and if I remove the link, then the name will display.

I don't know how to solve this problem.

Here's the code I'm using.

<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>JQuery Cycle Plugin - Pager Demo with Prev/Next Controls</title>
<link rel="stylesheet" type="text/css" media="screen" href="../jq.css" />
<link rel="stylesheet" type="text/css" media="screen" href="cycle.css" />

    Prev
    Next

 <?php
                 mysql_connect("localhost", "root", "")or die("cannot connect");
                 mysql_select_db($db_name)or die("cannot select DB");

                 $data = mysql_query("SELECT * FROM people") or die(mysql_error());
                 while($info = mysql_fetch_array( $data )){

     Prev
     Next

Thanks for your assistance

Body:
Never used cycle plugin personally, but I think you are not attaching click callback to the image at all. Instead, you  attaching it on before, which makes name be displayed in your div when images start swapping. See cycle plugin reference for details

To display image name on click use the following code:

$('.clickable_image').click(function(){
    $('#name').html($(this).attr('alt'));
});

Don't forget to add class clickable_image to your images.

Also, if you plan add images dynamically, live function may be helpful.


问:
How to find valid FQDN value for my ambari agent
I am using this project : https://github.com/adoroszlai/ambari-runtime-compose.git to run ambari on my local system

The docker compose includes one server and one agent.

After running the containers, there are few installation steps :

I am struggling with what could be the valid FQDN name

I tried hostname, hostname -f, hostname --fqdn inside my agent container.
All these 3 values are returing the container id.
So, I tried container id as well but no luck.

Should I add a new entry in the ambari agent's /etc/hosts, not sure what is the correct approach.

Thanks in advance !

答: Yes, add your hosts in /etc/hosts as fqdn (Fully Qualified Domain Name) such as "node1.domain.com" and put the full list of all node fqdn's on every node.</p>


问:
Screen Space Ambient Occlusion (SSAO) being rendered for clipped meshes
I am working on a small game where I only want to draw the objects (mesh) when it is inside an invicible box. I have gotten the clipping to work so that the mesh is only rendered inside the box (using the solution mentioned here: https://answers.unity.com/questions/1875660/urp-render-only-whats-inside-a-cube.html

The only annoyance now is that even when the mesh is clipped, the SSAO is still being rendered as you can see in the following image (in the red box):

I assume it is because the object is still contributing to the depth normals - but I am unable to find more information about this - or even if this is the actual issue.

Do any of you have a suggestion for how to prevent this from happening?

I am using Unity 2021.2.8f and URP v12.1.3 btw

答:
The Postprocessing effect SSAO is applied to all layers seen (not culled) by your main camera. Try to put the object on a different layer and ignore it on your main camera.
You could also integrate an additional forward renderer (+ new camera) to your project, which does not use the SSAO effect and takes care of your object.</p>


问:
Material-UI: Grid items with same height
I want to bring these grid items to the same height, but not to stretch them.

This is what it looks like:

This is how I want it:

But I can only do that by manually setting the image width therefore it's not responsive. The users are able to replace this image so setting fixed dimensions is not an option. Any help is appreciated. Here is the minimum code needed to reproduce (I have removed the content within the card to keep the code minimal):

Note: I have used material-ui v4

```<code><Grid container spacing={3}>
   <Grid item lg={12} md={12} sm={12} xs={12}>
      <Grid container spacing={3} className="mb-3">
         <Grid item xs={12} md={3}>
            <Card
               className="justify-between items-center p-sm-24 bg-paper dashboard-card"
               elevation={6}
               >
            </Card>
         </Grid>
         <Grid item xs={12} md={3}>
            <Card
               className="justify-between items-center p-sm-24 bg-paper dashboard-card"
               elevation={6}
               >
            </Card>
         </Grid>
         <Grid item xs={12} md={6}>
            <Card className="bg-paper" elevation={6}>
               <CardContent className="flex justify-center">
                  <img
                  src={this.state.logo}
                  alt="logo"
                  style={{ width: "100%" }}
                  />
               </CardContent>
            </Card>
         </Grid>
      </Grid>
   </Grid>
</Grid>
</code>```

答:
I'm not sure if this is the best way but it worked for me. So I'm answering my own question.

Instead of using an image tag, I used the CardMedia component which allows to set the height to match the other cards and it is also responsive.

you might want to display a video or a responsive image. Use the component prop for these use cases

```<code><CardMedia
  component="img"
  alt="green iguana"
  height="140"
  image="/static/images/cards/contemplative-reptile.jpg"
  />
</code>```

More info: https://mui.com/components/cards/#media

Body:
I want to bring these grid items to the same height, but not to stretch them.

This is what it looks like:

This is how I want it:

But I can only do that by manually setting the image width therefore it's not responsive. The users are able to replace this image so setting fixed dimensions is not an option. Any help is appreciated. Here is the minimum code needed to reproduce (I have removed the content within the card to keep the code minimal):

Note: I have used material-ui v4

<Grid container spacing={3}>
   <Grid item lg={12} md={12} sm={12} xs={12}>
      <Grid container spacing={3} className="mb-3">
         <Grid item xs={12} md={3}>
            <Card
               className="justify-between items-center p-sm-24 bg-paper dashboard-card"
               elevation={6}
               >
            </Card>
         </Grid>
         <Grid item xs={12} md={3}>
            <Card
               className="justify-between items-center p-sm-24 bg-paper dashboard-card"
               elevation={6}
               >
            </Card>
         </Grid>
         <Grid item xs={12} md={6}>
            <Card className="bg-paper" elevation={6}>
               <CardContent className="flex justify-center">

               </CardContent>
            </Card>
         </Grid>
      </Grid>
   </Grid>
</Grid>

Body:
I'm not sure if this is the best way but it worked for me. So I'm answering my own question.

Instead of using an image tag, I used the CardMedia component which allows to set the height to match the other cards and it is also responsive.

you might want to display a video or a responsive image. Use the component prop for these use cases

<CardMedia
  component="img"
  alt="green iguana"
  height="140"
  image="/static/images/cards/contemplative-reptile.jpg"
  />

More info: https://mui.com/components/cards/#media


问:
i want to add "list_a" to "list_b"
```<code>temp_list = [2,2,9]
var_a = 2

list_a = []
print("first temp_list : ",temp_list)
print()

while temp_list[-1] >= var_a:
    before_end_value = temp_list[-1]
    temp_list[-1] = var_a
    temp_list.append(before_end_value - var_a)
    list_a.append(temp_list)
    print("temp_list", temp_list)
    print("list_a : ", list_a)
    print()
</code>```

-----output-----

```<code>first temp_list :  [2, 2, 9]

temp_list [2, 2, 2, 7]
list_a :  [[2, 2, 2, 7]]

temp_list [2, 2, 2, 2, 5]
list_a :  [[2, 2, 2, 2, 5], [2, 2, 2, 2, 5]]

temp_list [2, 2, 2, 2, 2, 3]
list_a :  [[2, 2, 2, 2, 2, 3], [2, 2, 2, 2, 2, 3], [2, 2, 2, 2, 2, 3]]

temp_list [2, 2, 2, 2, 2, 2, 1]
list_a :  [[2, 2, 2, 2, 2, 2, 1], [2, 2, 2, 2, 2, 2, 1], [2, 2, 2, 2, 2, 2, 1], [2, 2, 2, 2, 2, 2, 1]]
</code>```

i want to make list_a [[2,2,2,7],[2,2,2,2,5],[2,2,2,2,2,3],[2,2,2,2,2,2,1]]
(to solve this problem i used list_a.append(temp_list) but list_a have wrong values)

can you advise for this problem?

答:
thanks for your latest edit, Here is the solution:

temp_list = [2,2,9]
var_a = 2

list_a = []
print("first temp_list : ",temp_list)
print()

while temp_list[-1] >= var_a:
    before_end_value = temp_list[-1]
    temp_list[-1] = var_a
    temp_list.append(before_end_value - temp_list[-1])
    list_a.append(temp_list.copy())
    print("temp_list", temp_list)
    print("list_a : ", list_a)
    print()
```
<p>just need to replace <code>list_a.append(temp_list)</code> with <code>list_a.append(temp_list.copy())</code></p>
<p>Output:</p>
```first temp_list :  [2, 2, 9]

temp_list [2, 2, 2, 7]
list_a :  [[2, 2, 2, 7]]

temp_list [2, 2, 2, 2, 5]
list_a :  [[2, 2, 2, 7], [2, 2, 2, 2, 5]]

temp_list [2, 2, 2, 2, 2, 3]
list_a :  [[2, 2, 2, 7], [2, 2, 2, 2, 5], [2, 2, 2, 2, 2, 3]]

temp_list [2, 2, 2, 2, 2, 2, 1]
list_a :  [[2, 2, 2, 7], [2, 2, 2, 2, 5], [2, 2, 2, 2, 2, 3], [2, 2, 2, 2, 2, 2, 1]]
```

Title: i want to add "list_a" to "list_b"

Body:
temp_list = [2,2,9]
var_a = 2

list_a = []
print("first temp_list : ",temp_list)
print()

while temp_list[-1] >= var_a:
    before_end_value = temp_list[-1]
    temp_list[-1] = var_a
    temp_list.append(before_end_value - var_a)
    list_a.append(temp_list)
    print("temp_list", temp_list)
    print("list_a : ", list_a)
    print()

-----output-----

first temp_list :  [2, 2, 9]

temp_list [2, 2, 2, 7]
list_a :  [[2, 2, 2, 7]]

temp_list [2, 2, 2, 2, 5]
list_a :  [[2, 2, 2, 2, 5], [2, 2, 2, 2, 5]]

temp_list [2, 2, 2, 2, 2, 3]
list_a :  [[2, 2, 2, 2, 2, 3], [2, 2, 2, 2, 2, 3], [2, 2, 2, 2, 2, 3]]

temp_list [2, 2, 2, 2, 2, 2, 1]
list_a :  [[2, 2, 2, 2, 2, 2, 1], [2, 2, 2, 2, 2, 2, 1], [2, 2, 2, 2, 2, 2, 1], [2, 2, 2, 2, 2, 2, 1]]

i want to make list_a [[2,2,2,7],[2,2,2,2,5],[2,2,2,2,2,3],[2,2,2,2,2,2,1]]
(to solve this problem i used list_a.append(temp_list) but list_a have wrong values)

can you advise for this problem?

Body:
thanks for your latest edit, Here is the solution:

temp_list = [2,2,9]
var_a = 2

list_a = []
print("first temp_list : ",temp_list)
print()

while temp_list[-1] >= var_a:
    before_end_value = temp_list[-1]
    temp_list[-1] = var_a
    temp_list.append(before_end_value - temp_list[-1])
    list_a.append(temp_list.copy())
    print("temp_list", temp_list)
    print("list_a : ", list_a)
    print()

just need to replace list_a.append(temp_list) with list_a.append(temp_list.copy())

Output:

first temp_list :  [2, 2, 9]

temp_list [2, 2, 2, 7]
list_a :  [[2, 2, 2, 7]]

temp_list [2, 2, 2, 2, 5]
list_a :  [[2, 2, 2, 7], [2, 2, 2, 2, 5]]

temp_list [2, 2, 2, 2, 2, 3]
list_a :  [[2, 2, 2, 7], [2, 2, 2, 2, 5], [2, 2, 2, 2, 2, 3]]

temp_list [2, 2, 2, 2, 2, 2, 1]
list_a :  [[2, 2, 2, 7], [2, 2, 2, 2, 5], [2, 2, 2, 2, 2, 3], [2, 2, 2, 2, 2, 2, 1]]


问:
Iterate range of addresses between two IPV6 addresses
I need some way to iterate over the range of addresses between two IPv6 addresses. i.e. if the first IP is 2a03:6300:1:103:219:5bff:fe31:13e1 and the second one is 2a03:6300:1:103:219:5bff:fe31:13f4, I would like to visit the 19 addresses in that range.

With IPv4 I just do inet_aton for string representation and get htonl of s_addr in the resulting struct, but how can I do that for IPv6?

For simplify:

```<code>struct in6_addr sn,en;
long i;

s="2a03:6300:1:103:219:5bff:fe31:13e1";
e="2a03:6300:1:103:219:5bff:fe31:13f4";

inet_pton(AF_INET6,s,&sn);
inet_pton(AF_INET6,e,&en);
</code>```

[..]

```<code>for (i = _first_ipv6_representation; i<=_second_ipv6_representation; i++){
    /* stuck here */
}
</code>```

答:
Python3:</p>
```<code>import ipaddress
st_add=int(ips.ip_address(st_add).packed.hex(),16)
end_add=int(ips.ip_address(end_add).packed.hex(),16)
Ips=set(ips.ip_address(ip).compressed for ip in range(st_add,end_add))
</code>```

Body:
I need some way to iterate over the range of addresses between two IPv6 addresses. i.e. if the first IP is 2a03:6300:1:103:219:5bff:fe31:13e1 and the second one is 2a03:6300:1:103:219:5bff:fe31:13f4, I would like to visit the 19 addresses in that range.

With IPv4 I just do inet_aton for string representation and get htonl of s_addr in the resulting struct, but how can I do that for IPv6?

For simplify:

struct in6_addr sn,en;
long i;

s="2a03:6300:1:103:219:5bff:fe31:13e1";
e="2a03:6300:1:103:219:5bff:fe31:13f4";

inet_pton(AF_INET6,s,&sn);
inet_pton(AF_INET6,e,&en);

[..]

for (i = _first_ipv6_representation; i<=_second_ipv6_representation; i++){
    /* stuck here */
}

Body:
Python3:

import ipaddress
st_add=int(ips.ip_address(st_add).packed.hex(),16)
end_add=int(ips.ip_address(end_add).packed.hex(),16)
Ips=set(ips.ip_address(ip).compressed for ip in range(st_add,end_add))


问:
JTable wait indicator
I have java applet with JTable. Due to lots of data and poor network bandwidth it takes lots of time to perform any operation like load the table or change it.
I'm thinking about adding sort of activity indicator to let user know that his request is processing.
Before i use JProgressBar, I'd like to know whether there are other options like ajax activity flower.

答:
The easiest way would be setting a (not animated) WAIT_CURSOR

```<code>// Setting cursor for any Component:
  component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
  doProcessing();
  component.setCursor(Cursor.getDefaultCursor());
</code>```

see http://www.catalysoft.com/articles/busyCursor.html

For an animated cursor see:

http://book.javanb.com/swing-hacks/swinghacks-chp-12-sect-2.html

Title: JTable wait indicator

Body:
The easiest way would be setting a (not animated) WAIT_CURSOR

// Setting cursor for any Component:
  component.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
  doProcessing();
  component.setCursor(Cursor.getDefaultCursor());

see http://www.catalysoft.com/articles/busyCursor.html

For an animated cursor see:

http://book.javanb.com/swing-hacks/swinghacks-chp-12-sect-2.html


问:
How to write AuthGuard in Ionic/Angular with AngularFire7 that works on iOS?
I'm running into an odd problem with my Ionic/angular app.
I'm using

"@angular/core": "~13.2.2"

"@capacitor/core": "3.4.0"

"@capacitor/ios": "3.4.0"

"@angular/fire": "^7.2.0"

"firebase": "^9.6.6",

It works well on the web-version and Android, but when I compile to iOS, I only get a blank screen. I've narrowed the problem down to the auth-guard

I have tried using

the @angular/fire/compat/authguard - blank screen

not using any guard - works fine

writing my own guard and always returning true - works fine

writing my own guard, code below - blank screen

Here are the app-routing.module.ts:

```<code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from '../guards/auth.guard';
import { AutoLoginGuard } from '../guards/auto-login.guard';
import { TabsPage } from './tabs.page';
const routes: Routes = [
  {
    path: '',
    component: TabsPage,
    children: [
      {
        path: '',
        redirectTo: 'dashboard',
        pathMatch: 'full',
      },
      {
        path: 'dashboard',
        loadChildren: () =>
          import('../pages/dashboard/dashboard.module').then(
            (m) => m.DashboardPageModule
          ),
        canActivate: [AuthGuard],
      },
      {
        path: 'welcome',
        loadChildren: () =>
          import('../pages/welcome/welcome.module').then(
            (m) => m.WelcomePageModule
          ),
        canActivate: [AutoLoginGuard],
      },
      {
        path: 'login',
        loadChildren: () =>
          import('../pages/login/login.module').then((m) => m.LoginPageModule),
        canActivate: [AutoLoginGuard],
      },
    ],
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
})
export class TabsPageRoutingModule {}
</code>```

and the auth.guard.ts

```<code>import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Auth, onAuthStateChanged } from '@angular/fire/auth';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  constructor(private auth: Auth, private router: Router) {}

  canActivate(): Promise<boolean> {
    return new Promise(async (resolve, reject) => {
      onAuthStateChanged(this.auth, async (user) => {
        if (user) {
          console.log('User authenticated');
          resolve(true);
        } else {
          console.log('User redirected to login');
          this.router.navigateByUrl('/', { replaceUrl: true });
          reject(false);
        }
      });
    });
  }
}
</code>```

Any idea what might be causing this issue?

答:
Found the answer (or rather Simon Grimm did): it's a bug in the capacitor SDK.
When initializing the auth module you have to adjust for Capacitor:

app.module.ts:

```<code>import { Capacitor } from '@capacitor/core';
import { indexedDBLocalPersistence, initializeAuth } from 'firebase/auth';
import { getApp } from 'firebase/app';

...
imports: [ ...

provideAuth(() => {
      if (Capacitor.isNativePlatform()) {
        return initializeAuth(getApp(), {
          persistence: indexedDBLocalPersistence,
        });
      } else {
        return getAuth();
      }
    }),
...
]
</code>```

Body:
I'm running into an odd problem with my Ionic/angular app.
I'm using

"@angular/core": "~13.2.2"

"@capacitor/core": "3.4.0"

"@capacitor/ios": "3.4.0"

"@angular/fire": "^7.2.0"

"firebase": "^9.6.6",

It works well on the web-version and Android, but when I compile to iOS, I only get a blank screen. I've narrowed the problem down to the auth-guard

I have tried using

the @angular/fire/compat/authguard - blank screen

not using any guard - works fine

writing my own guard and always returning true - works fine

writing my own guard, code below - blank screen

Here are the app-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { AuthGuard } from '../guards/auth.guard';
import { AutoLoginGuard } from '../guards/auto-login.guard';
import { TabsPage } from './tabs.page';
const routes: Routes = [
  {
    path: '',
    component: TabsPage,
    children: [
      {
        path: '',
        redirectTo: 'dashboard',
        pathMatch: 'full',
      },
      {
        path: 'dashboard',
        loadChildren: () =>
          import('../pages/dashboard/dashboard.module').then(
            (m) => m.DashboardPageModule
          ),
        canActivate: [AuthGuard],
      },
      {
        path: 'welcome',
        loadChildren: () =>
          import('../pages/welcome/welcome.module').then(
            (m) => m.WelcomePageModule
          ),
        canActivate: [AutoLoginGuard],
      },
      {
        path: 'login',
        loadChildren: () =>
          import('../pages/login/login.module').then((m) => m.LoginPageModule),
        canActivate: [AutoLoginGuard],
      },
    ],
  },
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
})
export class TabsPageRoutingModule {}

and the auth.guard.ts

import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { Auth, onAuthStateChanged } from '@angular/fire/auth';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {
  constructor(private auth: Auth, private router: Router) {}

  canActivate(): Promise<boolean> {
    return new Promise(async (resolve, reject) => {
      onAuthStateChanged(this.auth, async (user) => {
        if (user) {
          console.log('User authenticated');
          resolve(true);
        } else {
          console.log('User redirected to login');
          this.router.navigateByUrl('/', { replaceUrl: true });
          reject(false);
        }
      });
    });
  }
}

Any idea what might be causing this issue?

Body:
Found the answer (or rather Simon Grimm did): it's a bug in the capacitor SDK.
When initializing the auth module you have to adjust for Capacitor:

app.module.ts:

import { Capacitor } from '@capacitor/core';
import { indexedDBLocalPersistence, initializeAuth } from 'firebase/auth';
import { getApp } from 'firebase/app';

...
imports: [ ...

provideAuth(() => {
      if (Capacitor.isNativePlatform()) {
        return initializeAuth(getApp(), {
          persistence: indexedDBLocalPersistence,
        });
      } else {
        return getAuth();
      }
    }),
...
]


问:
componentWillUnmount with React useEffect hook
How can the useEffect hook (or any other hook for that matter) be used to replicate componentWillUnmount?

In a traditional class component I would do something like this:

```<code>class Effect extends React.PureComponent {
    componentDidMount() { console.log("MOUNT", this.props); }
    componentWillUnmount() { console.log("UNMOUNT", this.props); }
    render() { return null; }
}
</code>```

With the useEffect hook:

```<code>function Effect(props) {
  React.useEffect(() => {
    console.log("MOUNT", props);

    return () => console.log("UNMOUNT", props)
  }, []);

  return null;
}
</code>```

(Full example: https://codesandbox.io/s/2oo7zqzx1n)

This does not work, since the "cleanup" function returned in useEffect captures the props as they were during mount and not state of the props during unmount.

How could I get the latest version of the props in useEffect clean up without running the function body (or cleanup) on every prop change?

A similar question does not address the part of having access to the latest props.

The react docs state:

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.

In this case however I depend on the props... but only for the cleanup part...

答:
useLayoutEffect is great for cleaning eventListeners on DOM nodes.

Otherwise, with regular useEffect ref.current will be null on time hook triggered

More on react docs https://reactjs.org/docs/hooks-reference.html#uselayouteffect

```<code>  import React, { useLayoutEffect, useRef } from 'react';

  const audioRef = useRef(null);

  useLayoutEffect(() => {
    if (!audioRef.current) return;

    const progressEvent = (e) => {
      setProgress(audioRef.current.currentTime);
    };

    audioRef.current.addEventListener('timeupdate', progressEvent);

    return () => {
      try {
        audioRef.current.removeEventListener('timeupdate', progressEvent);
      } catch (e) {
        console.warn('could not removeEventListener on timeupdate');
      }
    };
  }, [audioRef.current]);

</code>```

Attach ref to component DOM node

<audio ref={audioRef} />

Body:
How can the useEffect hook (or any other hook for that matter) be used to replicate componentWillUnmount?

In a traditional class component I would do something like this:

class Effect extends React.PureComponent {
    componentDidMount() { console.log("MOUNT", this.props); }
    componentWillUnmount() { console.log("UNMOUNT", this.props); }
    render() { return null; }
}

With the useEffect hook:

function Effect(props) {
  React.useEffect(() => {
    console.log("MOUNT", props);

    return () => console.log("UNMOUNT", props)
  }, []);

  return null;
}

(Full example: https://codesandbox.io/s/2oo7zqzx1n)

This does not work, since the "cleanup" function returned in useEffect captures the props as they were during mount and not state of the props during unmount.

How could I get the latest version of the props in useEffect clean up without running the function body (or cleanup) on every prop change?

A similar question does not address the part of having access to the latest props.

The react docs state:

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.

In this case however I depend on the props... but only for the cleanup part...

Body:
useLayoutEffect is great for cleaning eventListeners on DOM nodes.

Otherwise, with regular useEffect ref.current will be null on time hook triggered

More on react docs https://reactjs.org/docs/hooks-reference.html#uselayouteffect

  import React, { useLayoutEffect, useRef } from 'react';

  const audioRef = useRef(null);

  useLayoutEffect(() => {
    if (!audioRef.current) return;

    const progressEvent = (e) => {
      setProgress(audioRef.current.currentTime);
    };

    audioRef.current.addEventListener('timeupdate', progressEvent);

    return () => {
      try {
        audioRef.current.removeEventListener('timeupdate', progressEvent);
      } catch (e) {
        console.warn('could not removeEventListener on timeupdate');
      }
    };
  }, [audioRef.current]);

Attach ref to component DOM node

<audio ref={audioRef} />


问:
correctly reading or writing serial port Windows API
I have read alot of issues with serial port reading and writing. None so far have helped me figure out what my code is missing. The msdn example for c++ has undefined variables and missing brackets so although i can add brackets it still does not function. Here's what I've got at this point. It appears I can open the port and do the configuration but I cannot read a byte/char of data. I really just want a simple asyncronous serial read/write for aprogram to read from an Arduino.

```<code>class MY_SERIAL
{

HANDLE serialinstance;

DWORD      dwStoredFlags;
DWORD      dwRes;
DWORD      dwCommEvent;
OVERLAPPED osStatus = {0};
BOOL       fWaitingOnStat;
//dwStoredFlags = EV_BREAK | EV_CTS   | EV_DSR | EV_ERR | EV_RING | EV_RLSD | EV_RXCHAR |      EV_RXFLAG | EV_TXEMPTY ;

DCB dcb;
COMMTIMEOUTS timeouts;

COMMCONFIG serialconfig;

public:
char inBuffer[1000];
char outBuffer[100];

PDWORD noBytes;

void close_serial()
{
    CloseHandle(serialinstance);
}
//----------------------------------------------------
bool open_serial(LPCSTR portNumber)   // serial port name use this format  "\\\\.\\COM10"
{

    serialinstance = CreateFile(portNumber, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
    if(serialinstance == INVALID_HANDLE_VALUE)
    {
        int error = GetLastError();
        printf("ERROR opening serial port  %s\r\n", portNumber);
        if(error == 0x2){printf("ERROR_FILE_NOT_FOUND\r\n");}
        if(error == 0x5){printf("ERROR_ACCESS_DENIED\r\n");}
        if(error == 0xC){printf("ERROR_INVALID_ACCESS\r\n");}
        if(error == 0x6){printf("ERROR_INVALID_HANDLE\r\n");}
        printf("error code %d\r\n", error);
        return false;
    }
    if(GetCommState(serialinstance, &dcb)!= true)
    {
        printf("ERROR getting current state of COM   %d \r\n", GetLastError());
        return false;
    }
    else{printf("debug   read current comstate\r\n");}

    FillMemory(&dcb, sizeof(dcb), 0); //zero initialize the structure
    dcb.DCBlength = sizeof(dcb);      //fill in length

    dcb.BaudRate = CBR_115200;     //  baud rate
    dcb.ByteSize = 8;             //  data size, xmit and rcv
    dcb.Parity   = NOPARITY;      //  parity bit
    dcb.StopBits = ONESTOPBIT;

    if(SetCommState(serialinstance, &dcb) != true)
    {
        printf("ERROR setting new state of COM   %d \r\n", GetLastError());
        return false;
    }
    else{printf("debug   set new comstate\r\n");}
    /*
    if (!BuildCommDCB("115200,n,8,1", &dcb)) //fills in basic async details
    {
        printf("ERROR getting port comstate\r\n");
        return FALSE;
    }
    */
    if (!SetCommMask(serialinstance, EV_RXCHAR))
    {
        printf("ERROR setting new COM MASK   %d \r\n", GetLastError());
        return false;
    }
    else{printf("debug   commmask set\r\n");}
    timeouts.ReadIntervalTimeout = MAXDWORD;
    timeouts.ReadTotalTimeoutMultiplier = 20;
    timeouts.ReadTotalTimeoutConstant = 0;
    timeouts.WriteTotalTimeoutMultiplier = 0;
    timeouts.WriteTotalTimeoutConstant = 0;

    if (!SetCommTimeouts(serialinstance, &timeouts))
    {
        printf("ERROR setting timeout parameters\r\n");
        return false;
    }
    else{printf("debug   timeouts set\r\n");}
    osStatus.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (osStatus.hEvent == NULL)
    {// error creating event; abort
        printf("ERROR creating Serial EVENT\r\n");
        return false;
    }
    else{printf("debug   event created set\r\n");}
    osStatus.Internal = 0;
    osStatus.InternalHigh = 0;
    osStatus.Offset = 0;
    osStatus.OffsetHigh = 0;
    assert(osStatus.hEvent);
    printf("debug   com port setting complete\r\n");

    return true;
}
//---------------------------------------------------------

bool read_serial_simple()
{
    char m[1000];
    LPDWORD bytesRead;

    if (WaitCommEvent(serialinstance, &dwCommEvent, &osStatus))
    {
        if(dwCommEvent & EV_RXCHAR)
        {
            ReadFile(serialinstance, &m, 1, bytesRead, &osStatus);
            printf("data read =   %d,       number bytes read =     %d  \r\n", m, bytesRead);
            return true;
        }
        else
        {
            int error = GetLastError();
            if(error == ERROR_IO_PENDING){printf(" waiting on incomplete IO\r\n");}
            else{printf("ERROR %d\r\n", error);}
            return false;
        }
    }
    return false;
}

};
</code>```

So I stripped the read function down. I now get a char and it reports reading 1 byte but the value of the char is incorrect. I get a series of 48, 13, 10, and occasionally a 50 value for the byte. However the Arduino is sending a series a 0's then a 128 as verified with TerraTerm. What else do I need here?

```<code>bool read_serial_simple()
{
    unsigned char m = 0;
    DWORD bytesRead;
    if(ReadFile(serialinstance, &m, 1, &bytesRead, &osStatus) == true)
    {
        printf("data read =   %d,       number bytes read =     %d  \r\n", m, bytesRead);
        return true;
    }
    else{
        int error = GetLastError();
        if(error == ERROR_IO_PENDING){printf(" waiting on incomplete IO\r\n");}
        else{printf("ERROR %d\r\n", error);}
        return false;
    }

}
</code>```

So now I can read a byte of data but I cannot write a byte or more to the port. I just get ERROR_IO_PENDING. Can someone help out with this as well. Write function of my class below.

```<code>bool write(DWORD noBytesToWrite)
{
    if(WriteFile(serialinstance, outBuffer, noBytesToWrite, NULL, &osStatus) == true)
    {
        printf("message sent\r\n");
        return true;
    }
    else
    {
        int error = GetLastError();
        if(error != ERROR_IO_PENDING){LastError();}
        return false;
    }
}
</code>```

I'm calling both functions from main as follows

```<code>myserial.open_serial(COM12);
myserial.outBuffer[0] = 'H';
myserial.outBuffer[1] = 'e';
myserial.outBuffer[2] = 'L';
myserial.outBuffer[3] = 'l';
myserial.outBuffer[4] = 'O';
for(int n=0; n<5; n++){printf("%c", myserial.outBuffer[n]);}
printf("\r\n");

while(1)
{
    myserial.read();
    myserial.write(5);
    //system("PAUSE");
}
</code>```

Currently the arduino is set up to read bytes in and repeat them back to the pc. It is doing this fine on the arduino IDE serial monitor so now I just need to get this pc program to write out.

答:
Sorry my answer is a bit late, but as I was checking up on another serial port detail I found this.

There is a bit flaw in the original code.  You are calling CreateFile with the FILE_FLAG_OVERLAPPED flag.  This means you want to use non-blocking calls.  You either need to remove this flag, or change your ReadFile and WriteFile calls so that they include a pointer to an OVERLAPPED structure WriteFile.

Your code works with ReadFile as it will complete syncrhronously as there is a character already waiting.  The WriteFile will return IO_PENDING result to indicate that the write has been queued.

Body:
I have read alot of issues with serial port reading and writing. None so far have helped me figure out what my code is missing. The msdn example for c++ has undefined variables and missing brackets so although i can add brackets it still does not function. Here's what I've got at this point. It appears I can open the port and do the configuration but I cannot read a byte/char of data. I really just want a simple asyncronous serial read/write for aprogram to read from an Arduino.

class MY_SERIAL
{

HANDLE serialinstance;

DWORD      dwStoredFlags;
DWORD      dwRes;
DWORD      dwCommEvent;
OVERLAPPED osStatus = {0};
BOOL       fWaitingOnStat;
//dwStoredFlags = EV_BREAK | EV_CTS   | EV_DSR | EV_ERR | EV_RING | EV_RLSD | EV_RXCHAR |      EV_RXFLAG | EV_TXEMPTY ;

DCB dcb;
COMMTIMEOUTS timeouts;

COMMCONFIG serialconfig;

public:
char inBuffer[1000];
char outBuffer[100];

PDWORD noBytes;

void close_serial()
{
    CloseHandle(serialinstance);
}
//----------------------------------------------------
bool open_serial(LPCSTR portNumber)   // serial port name use this format  "\\\\.\\COM10"
{

    serialinstance = CreateFile(portNumber, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL);
    if(serialinstance == INVALID_HANDLE_VALUE)
    {
        int error = GetLastError();
        printf("ERROR opening serial port  %s\r\n", portNumber);
        if(error == 0x2){printf("ERROR_FILE_NOT_FOUND\r\n");}
        if(error == 0x5){printf("ERROR_ACCESS_DENIED\r\n");}
        if(error == 0xC){printf("ERROR_INVALID_ACCESS\r\n");}
        if(error == 0x6){printf("ERROR_INVALID_HANDLE\r\n");}
        printf("error code %d\r\n", error);
        return false;
    }
    if(GetCommState(serialinstance, &dcb)!= true)
    {
        printf("ERROR getting current state of COM   %d \r\n", GetLastError());
        return false;
    }
    else{printf("debug   read current comstate\r\n");}

    FillMemory(&dcb, sizeof(dcb), 0); //zero initialize the structure
    dcb.DCBlength = sizeof(dcb);      //fill in length

    dcb.BaudRate = CBR_115200;     //  baud rate
    dcb.ByteSize = 8;             //  data size, xmit and rcv
    dcb.Parity   = NOPARITY;      //  parity bit
    dcb.StopBits = ONESTOPBIT;

    if(SetCommState(serialinstance, &dcb) != true)
    {
        printf("ERROR setting new state of COM   %d \r\n", GetLastError());
        return false;
    }
    else{printf("debug   set new comstate\r\n");}
    /*
    if (!BuildCommDCB("115200,n,8,1", &dcb)) //fills in basic async details
    {
        printf("ERROR getting port comstate\r\n");
        return FALSE;
    }
    */
    if (!SetCommMask(serialinstance, EV_RXCHAR))
    {
        printf("ERROR setting new COM MASK   %d \r\n", GetLastError());
        return false;
    }
    else{printf("debug   commmask set\r\n");}
    timeouts.ReadIntervalTimeout = MAXDWORD;
    timeouts.ReadTotalTimeoutMultiplier = 20;
    timeouts.ReadTotalTimeoutConstant = 0;
    timeouts.WriteTotalTimeoutMultiplier = 0;
    timeouts.WriteTotalTimeoutConstant = 0;

    if (!SetCommTimeouts(serialinstance, &timeouts))
    {
        printf("ERROR setting timeout parameters\r\n");
        return false;
    }
    else{printf("debug   timeouts set\r\n");}
    osStatus.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
    if (osStatus.hEvent == NULL)
    {// error creating event; abort
        printf("ERROR creating Serial EVENT\r\n");
        return false;
    }
    else{printf("debug   event created set\r\n");}
    osStatus.Internal = 0;
    osStatus.InternalHigh = 0;
    osStatus.Offset = 0;
    osStatus.OffsetHigh = 0;
    assert(osStatus.hEvent);
    printf("debug   com port setting complete\r\n");

    return true;
}
//---------------------------------------------------------

bool read_serial_simple()
{
    char m[1000];
    LPDWORD bytesRead;

    if (WaitCommEvent(serialinstance, &dwCommEvent, &osStatus))
    {
        if(dwCommEvent & EV_RXCHAR)
        {
            ReadFile(serialinstance, &m, 1, bytesRead, &osStatus);
            printf("data read =   %d,       number bytes read =     %d  \r\n", m, bytesRead);
            return true;
        }
        else
        {
            int error = GetLastError();
            if(error == ERROR_IO_PENDING){printf(" waiting on incomplete IO\r\n");}
            else{printf("ERROR %d\r\n", error);}
            return false;
        }
    }
    return false;
}

};

So I stripped the read function down. I now get a char and it reports reading 1 byte but the value of the char is incorrect. I get a series of 48, 13, 10, and occasionally a 50 value for the byte. However the Arduino is sending a series a 0's then a 128 as verified with TerraTerm. What else do I need here?

bool read_serial_simple()
{
    unsigned char m = 0;
    DWORD bytesRead;
    if(ReadFile(serialinstance, &m, 1, &bytesRead, &osStatus) == true)
    {
        printf("data read =   %d,       number bytes read =     %d  \r\n", m, bytesRead);
        return true;
    }
    else{
        int error = GetLastError();
        if(error == ERROR_IO_PENDING){printf(" waiting on incomplete IO\r\n");}
        else{printf("ERROR %d\r\n", error);}
        return false;
    }

}

So now I can read a byte of data but I cannot write a byte or more to the port. I just get ERROR_IO_PENDING. Can someone help out with this as well. Write function of my class below.

bool write(DWORD noBytesToWrite)
{
    if(WriteFile(serialinstance, outBuffer, noBytesToWrite, NULL, &osStatus) == true)
    {
        printf("message sent\r\n");
        return true;
    }
    else
    {
        int error = GetLastError();
        if(error != ERROR_IO_PENDING){LastError();}
        return false;
    }
}

I'm calling both functions from main as follows

myserial.open_serial(COM12);
myserial.outBuffer[0] = 'H';
myserial.outBuffer[1] = 'e';
myserial.outBuffer[2] = 'L';
myserial.outBuffer[3] = 'l';
myserial.outBuffer[4] = 'O';
for(int n=0; n<5; n++){printf("%c", myserial.outBuffer[n]);}
printf("\r\n");

while(1)
{
    myserial.read();
    myserial.write(5);
    //system("PAUSE");
}

Currently the arduino is set up to read bytes in and repeat them back to the pc. It is doing this fine on the arduino IDE serial monitor so now I just need to get this pc program to write out.


问:
no warning for missing ctor initializer list?
This code is missing a constructor initializer list:

```<code>#include <cstdio>

struct s {
    s() {}  // should be s(): m() {}
    int m;
};

int main() {
    struct s *px = new s();
    if (px->m) {
        printf("true\n");
    } else {
        printf("false\n");
    }
    delete px;
    return 0;
}
</code>```

gcc compiles clean with no warnings:

```<code>$ g++ -Wall -Wextra -g -O2 test.cpp
</code>```

However, valgrind knows that the class member m wasn't initialized:

```<code>$ valgrind ./a.out
==10953== Conditional jump or move depends on uninitialised value(s)
==10953==    at 0x400512: main (test.cpp:10)
==10953==
</code>```

Why didn't gcc warn about the missing initialization (-Wmissing-field-initializers or -Wuninitialized or -Wmaybe-uninitialized)?

Is there a flag I can pass that will catch this case?

答:
GCC also has the -fanalyzer flag which does some deeper static analysis than the warning flags do and can catch this specific case on current trunk (but not in GCC 11.2 or earlier):

```<code><source>:10:13: warning: use of uninitialized value '*px.s::m' [CWE-457] [-Wanalyzer-use-of-uninitialized-value]
   10 |     if (px->m) {
      |         ~~~~^
  'int main()': events 1-2
    |
    |    9 |     struct s *px = new s();
    |      |                          ^
    |      |                          |
    |      |                          (1) region created on heap here
    |   10 |     if (px->m) {
    |      |         ~~~~~
    |      |             |
    |      |             (2) use of uninitialized value '*px.s::m' here
    |
</code>```

But I often seem to have problems with the flag for generating false positives. For example in this case it complains about operator new potentially returning a null pointer, which cannot ever happen (bug).

See docs for details.

Body:
This code is missing a constructor initializer list:

#include <cstdio>

struct s {
    s() {}  // should be s(): m() {}
    int m;
};

int main() {
    struct s *px = new s();
    if (px->m) {
        printf("true\n");
    } else {
        printf("false\n");
    }
    delete px;
    return 0;
}

gcc compiles clean with no warnings:

$ g++ -Wall -Wextra -g -O2 test.cpp

However, valgrind knows that the class member m wasn't initialized:

$ valgrind ./a.out
==10953== Conditional jump or move depends on uninitialised value(s)
==10953==    at 0x400512: main (test.cpp:10)
==10953==

Why didn't gcc warn about the missing initialization (-Wmissing-field-initializers or -Wuninitialized or -Wmaybe-uninitialized)?

Is there a flag I can pass that will catch this case?

Body:
GCC also has the -fanalyzer flag which does some deeper static analysis than the warning flags do and can catch this specific case on current trunk (but not in GCC 11.2 or earlier):

<source>:10:13: warning: use of uninitialized value '*px.s::m' [CWE-457] [-Wanalyzer-use-of-uninitialized-value]
   10 |     if (px->m) {
      |         ~~~~^
  'int main()': events 1-2
    |
    |    9 |     struct s *px = new s();
    |      |                          ^
    |      |                          |
    |      |                          (1) region created on heap here
    |   10 |     if (px->m) {
    |      |         ~~~~~
    |      |             |
    |      |             (2) use of uninitialized value '*px.s::m' here
    |

But I often seem to have problems with the flag for generating false positives. For example in this case it complains about operator new potentially returning a null pointer, which cannot ever happen (bug).

See docs for details.


问:
reusable UI in android app
I am working on android app where I am thinking to develop reusable UI interface. How it can be developed and included in my .xml's

Here I want to develop a progress bar with my image and it will be display on some .xml's.
Please provide any code help.

I am a new in this field.

答:
You can either build custom (compound) views, look at Building Custom Components.
Or you can use Fragments. Fragments are new in Honeycomb (Android 3.0), but there is a compatibility library that adds fragment support to lower android versions (can be found in your ANDROID_SDK/extras/android folder). Or you can mix both of course.

Title: reusable UI in android app


问:
How to download Carbon monoxide concentration daily data from Google Earth Engine, without gaps?
I need to download Carbon monoxide concentrations daily data provided by sentinel 5p but the data consists of gaps for my region of interest

```<code>var dataset1 = ee.ImageCollection("COPERNICUS/S5P/NRTI/L3_CO")
             .filterDate('2021-03-01', '2021-03-31')
             .filterBounds(roi)
             .select("CO_column_number_density")
print (dataset1)
var img = dataset1.filterMetadata('TIME_REFERENCE_DAYS_SINCE_1950', 'equals',25992 )
     .mean();
Map.addLayer(img)
</code>```

Google Earth Engine

This is the code used. I am trying to average the data available for a single day but there are gaps. if the data has to be averaged over more than one day, how to do it? how to create a loop that iterates over the dates and computes the average?

答:
Try This Code</p>
```<code>var batch = require('users/fitoprincipe/geetools:batch')
print("batch.help", batch.help)

var Sentinel_CO_Dataset = ee.ImageCollection("COPERNICUS/S5P/NRTI/L3_CO")
                          .filterDate('2021-03-01', '2021-03-10')
                          .filterBounds(roi)
                          .select("CO_column_number_density")
print (Sentinel_CO_Dataset)

var count = Sentinel_CO_Dataset.size()
print("Collection count", count)

var all_Sentinel_CO_tiles = Sentinel_CO_Dataset.map(function(image) { return image.clip(roi).reproject('EPSG:4326', null, 1113.2); });

var check = ee.Image(all_Sentinel_CO_tiles.first());
var Sentinel_CO_Palette = ['FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718',
               '74A901', '66A000', '529400', '3E8601', '207401', '056201',
               '004C00', '023B01', '012E01', '011D01', '011301'];

Map.addLayer(check, {min:0.02, max: 0.05, palette: Sentinel_CO_Palette}, 'Sentinel_CO_Palette_Check');

var colList = all_Sentinel_CO_tiles.toList(all_Sentinel_CO_tiles.size());
var n = colList.size().getInfo();
for (var i = 0; i < n; i++) {
      var img = ee.Image(colList.get(i));
      var id = img.id().getInfo();
      var listOfImages = all_Sentinel_CO_tiles.toList(all_Sentinel_CO_tiles.size());
      var Tile = listOfImages.get(i);
      var allRasters = ee.ImageCollection.fromImages([Tile]);
      batch.Download.ImageCollection.toDrive(allRasters, "Sentinel_CO",
      {name: 'MONOXIDE_'+id,
      scale: 1113.2,
      region: roi
      })
}
</code>```

Body:
I need to download Carbon monoxide concentrations daily data provided by sentinel 5p but the data consists of gaps for my region of interest

var dataset1 = ee.ImageCollection("COPERNICUS/S5P/NRTI/L3_CO")
             .filterDate('2021-03-01', '2021-03-31')
             .filterBounds(roi)
             .select("CO_column_number_density")
print (dataset1)
var img = dataset1.filterMetadata('TIME_REFERENCE_DAYS_SINCE_1950', 'equals',25992 )
     .mean();
Map.addLayer(img)

Google Earth Engine

This is the code used. I am trying to average the data available for a single day but there are gaps. if the data has to be averaged over more than one day, how to do it? how to create a loop that iterates over the dates and computes the average?

Body:
Try This Code

var batch = require('users/fitoprincipe/geetools:batch')
print("batch.help", batch.help)

var Sentinel_CO_Dataset = ee.ImageCollection("COPERNICUS/S5P/NRTI/L3_CO")
                          .filterDate('2021-03-01', '2021-03-10')
                          .filterBounds(roi)
                          .select("CO_column_number_density")
print (Sentinel_CO_Dataset)

var count = Sentinel_CO_Dataset.size()
print("Collection count", count)

var all_Sentinel_CO_tiles = Sentinel_CO_Dataset.map(function(image) { return image.clip(roi).reproject('EPSG:4326', null, 1113.2); });

var check = ee.Image(all_Sentinel_CO_tiles.first());
var Sentinel_CO_Palette = ['FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718',
               '74A901', '66A000', '529400', '3E8601', '207401', '056201',
               '004C00', '023B01', '012E01', '011D01', '011301'];

Map.addLayer(check, {min:0.02, max: 0.05, palette: Sentinel_CO_Palette}, 'Sentinel_CO_Palette_Check');

var colList = all_Sentinel_CO_tiles.toList(all_Sentinel_CO_tiles.size());
var n = colList.size().getInfo();
for (var i = 0; i < n; i++) {
      var img = ee.Image(colList.get(i));
      var id = img.id().getInfo();
      var listOfImages = all_Sentinel_CO_tiles.toList(all_Sentinel_CO_tiles.size());
      var Tile = listOfImages.get(i);
      var allRasters = ee.ImageCollection.fromImages([Tile]);
      batch.Download.ImageCollection.toDrive(allRasters, "Sentinel_CO",
      {name: 'MONOXIDE_'+id,
      scale: 1113.2,
      region: roi
      })
}


问:
Why does Python follow symlinks? How do I work around that?
This is my directory layout:

```<code>projects/
   +-projectA/
     |---moduleA.py
     |---script.py -> ../projectB/script.py
   +-projectB/
     |---script.py
</code>```

This is what script.py contains:

```<code>import moduleA
print "hello there"
</code>```

Here's what I'm doing:

```<code>$ pwd
[...]/projects/projectA

$ python2 script.py
Traceback (most recent call last):
  File "script.py", line 1, in <module>
    import moduleA
ImportError: No module named moduleA
</code>```

The reason for this layout is that project A and project B are both from git repositories and get updated every once in a while. However, I write projectB and want to edit and push it, while not having to copy files over (it relies on stuff in project A).

Having it as a submodule/part of projectA is not an option, since the script has dependencies the maintainer of project A doesn't want.

The reverse is also not an option, since it's also so small in relation that it doesn't warrant adding project A (which is large and actually many different modules) as a submodule in project B, which would also create unnecessary extra files. Additionally, users are mainly be in project A's directory so a submodule would not make sense anyway.

I also don't want to use hard links for obvious reasons. I also can't do something like

```<code>sys.path.append("../projectA")
</code>```

in script.py, because other users of script.py probably don't have the same directory layout as me, and some will download it straight to projectA (without cloning).

So first of all, why does the python interpreter follow that symlink, and not execute the code as if it was in projectA's directory?

And secondly, how can I solve this problem with the caveats stated above?

(Feel free to also just answer a single of the two above questions.)

答:
I just run into the same "surprise" today with python3.9 -- so at least python ecosystem seems to be stable and upward compatible. ;)

For another surprise, using PYTHONPATH=. "fixes" that behaviour!
I would have guessed that only PYTHONPATH=$PWD would do the job, no idea why PYTHONPATH=. is fine too. ;)

```<code>$ python3.9 symlink.py  #  this breaks with "import local_module" -- ModuleNotFoundError: No module named 'local_module'
$ PYTHONPATH=.    python3.9 symlink.py # works
$ PYTHONPATH=$PWD python3.9 symlink.py # works
</code>```

I still do not like that "solution" (not yet?), so right now that work/test directory now doesn't use any symlinks anymore -- all stuff now gets copied/rsynced into the test dir. :-(

Body:
This is my directory layout:

projects/
   +-projectA/
     |---moduleA.py
     |---script.py -> ../projectB/script.py
   +-projectB/
     |---script.py

This is what script.py contains:

import moduleA
print "hello there"

Here's what I'm doing:

$ pwd
[...]/projects/projectA

$ python2 script.py
Traceback (most recent call last):
  File "script.py", line 1, in <module>
    import moduleA
ImportError: No module named moduleA

The reason for this layout is that project A and project B are both from git repositories and get updated every once in a while. However, I write projectB and want to edit and push it, while not having to copy files over (it relies on stuff in project A).

Having it as a submodule/part of projectA is not an option, since the script has dependencies the maintainer of project A doesn't want.

The reverse is also not an option, since it's also so small in relation that it doesn't warrant adding project A (which is large and actually many different modules) as a submodule in project B, which would also create unnecessary extra files. Additionally, users are mainly be in project A's directory so a submodule would not make sense anyway.

I also don't want to use hard links for obvious reasons. I also can't do something like

sys.path.append("../projectA")

in script.py, because other users of script.py probably don't have the same directory layout as me, and some will download it straight to projectA (without cloning).

So first of all, why does the python interpreter follow that symlink, and not execute the code as if it was in projectA's directory?

And secondly, how can I solve this problem with the caveats stated above?

(Feel free to also just answer a single of the two above questions.)

Body:
I just run into the same "surprise" today with python3.9 -- so at least python ecosystem seems to be stable and upward compatible. ;)

For another surprise, using PYTHONPATH=. "fixes" that behaviour!
I would have guessed that only PYTHONPATH=$PWD would do the job, no idea why PYTHONPATH=. is fine too. ;)

$ python3.9 symlink.py  #  this breaks with "import local_module" -- ModuleNotFoundError: No module named 'local_module'
$ PYTHONPATH=.    python3.9 symlink.py # works
$ PYTHONPATH=$PWD python3.9 symlink.py # works

I still do not like that "solution" (not yet?), so right now that work/test directory now doesn't use any symlinks anymore -- all stuff now gets copied/rsynced into the test dir. :-(


问:
Csv to Json with nodeJS
I would like to convert a csv file to json with the csv-parser library.

That's my file csv :

```<code>account/firstname,account/lastname,account/location/countryName,account/location/town,account/location/address,Id
Babouche,Dorian,US,Washington,***,1
</code>```

That's the code i have for the csv to json :

```<code>const csv = require('csv-parser');
const fs = require('fs');
let results = [];
let data;
fs.createReadStream('simple.csv')
    .pipe(csv())
    .on('data', (data) => results.push(data))
    .on('end', () => {
        data = JSON.stringify(results, null, 2)

        fs.writeFile('user.json', data, (err) => {
            if (err) {
                throw err;
            }
            console.log("JSON data is saved.");
        });
})
</code>```

Desired JSON:

```<code>[{
    account: {
        firstname: "Babouche",
        lastname: "Dorian",
        location: {
            countryName: "US",
            town: "Washington",
            address: "***"
        }
    },
    Id: "1",
}
]
</code>```

The result i have:

```<code>[
  {
    "account/firstname": "Babouche",
    "account/lastname": "Dorian",
    "account/location/countryName": "US",
    "account/location/town": "Washington",
    "account/location/address": "***",
    "Id": " 1"
  }
]
</code>```

I would like a recommendation on how to easily accomplish this, please.

答:
I recommend using 'json-2-csv'

First, install the package

```<code>npm install json-2-csv
</code>```

Import:

```<code>let converter = require('json-2-csv');
</code>```

Function with Callback

```<code>let csv2jsonCallback = function (err, json) {
    if (err) throw err;
        console.log(typeof json);
        console.log(json.length);
        console.log(json);
}

converter.csv2json(csv, csv2jsonCallback);
</code>```

Function with Promise

```<code>converter.csv2jsonAsync(csv)
.then(console.log)
.catch((err) => console.log('ERROR: ' + err.message));
</code>```

Title: Csv to Json with nodeJS

Body:
I would like to convert a csv file to json with the csv-parser library.

That's my file csv :

account/firstname,account/lastname,account/location/countryName,account/location/town,account/location/address,Id
Babouche,Dorian,US,Washington,***,1

That's the code i have for the csv to json :

const csv = require('csv-parser');
const fs = require('fs');
let results = [];
let data;
fs.createReadStream('simple.csv')
    .pipe(csv())
    .on('data', (data) => results.push(data))
    .on('end', () => {
        data = JSON.stringify(results, null, 2)

        fs.writeFile('user.json', data, (err) => {
            if (err) {
                throw err;
            }
            console.log("JSON data is saved.");
        });
})

Desired JSON:

[{
    account: {
        firstname: "Babouche",
        lastname: "Dorian",
        location: {
            countryName: "US",
            town: "Washington",
            address: "***"
        }
    },
    Id: "1",
}
]

The result i have:

[
  {
    "account/firstname": "Babouche",
    "account/lastname": "Dorian",
    "account/location/countryName": "US",
    "account/location/town": "Washington",
    "account/location/address": "***",
    "Id": " 1"
  }
]

I would like a recommendation on how to easily accomplish this, please.

Body:
I recommend using 'json-2-csv'

First, install the package

npm install json-2-csv

Import:

let converter = require('json-2-csv');

Function with Callback

let csv2jsonCallback = function (err, json) {
    if (err) throw err;
        console.log(typeof json);
        console.log(json.length);
        console.log(json);
}

converter.csv2json(csv, csv2jsonCallback);

Function with Promise

converter.csv2jsonAsync(csv)
.then(console.log)
.catch((err) => console.log('ERROR: ' + err.message));