问:
Problem in converting pytorch model to CoreML
System info
・torch 1.12.1
・coremltools 6.1
・python 3.8.15

I tried to convert model of votenet to the Core ML format.
I am referring to the following.
https://coremltools.readme.io/docs/pytorch-conversion

After defining the model I get an error like below when converting to 'torchscript'

```<code>
[/usr/local/lib/python3.8/dist-packages/torch/jit/_trace.py](https://localhost:8080/#) in trace_module(mod, inputs, optimize, check_trace, check_inputs, check_tolerance, strict, _force_outplace, _module_class, _compilation_unit)
    965             example_inputs = make_tuple(example_inputs)
    966
--> 967             module._c._create_method_from_trace(
    968                 method_name,
    969                 func,

RuntimeError: Encountering a dict at the output of the tracer might cause the trace to be incorrect, this is only valid if the container structure does not change based on the module's inputs. Consider using a constant container instead (e.g. for `list`, use a `tuple` instead. for `dict`, use a `NamedTuple` instead). If you absolutely need this and know the side effects, pass strict=False to trace() to allow this behavior.
</code>```

This is my code

```<code>model = VoteNet(10,12,10,np.random.random((10,3))).to('cuda')
model.eval()
model.load_state_dict(torch.load('checkpoint.tar'), strict=False)
dummy_input = {'point_clouds': torch.rand((20000,3)).unsqueeze(0).cuda()}
trace = torch.jit.trace(model, dummy_input)
</code>```

I searched problem,then I found this https://github.com/huggingface/transformers/issues/9095

I changed code like this based on comments in the issue

```<code>model = VoteNet(10,12,10,np.random.random((10,3))).to('cuda')
model.eval()
model.load_state_dict(torch.load('checkpoint.tar'), return_dict=False)
dummy_input = {'point_clouds': torch.rand((20000,3)).unsqueeze(0).cuda()}
trace = torch.jit.trace(model, dummy_input)
</code>```

But this time I got the following error

```<code>TypeError                                 Traceback (most recent call last)
[<ipython-input-31-0811dab20119>](https://localhost:8080/#) in <module>
----> 1 model.load_state_dict(torch.load('checkpoint.tar'), return_dict= False)

TypeError: load_state_dict() got an unexpected keyword argument 'return_dict'
</code>```

I'm a beginner, so maybe I'm stumbling on a rudimentary part
Could you help me?

Body:
System info
・torch 1.12.1
・coremltools 6.1
・python 3.8.15

I tried to convert model of votenet to the Core ML format.
I am referring to the following.
https://coremltools.readme.io/docs/pytorch-conversion

After defining the model I get an error like below when converting to 'torchscript'

[/usr/local/lib/python3.8/dist-packages/torch/jit/_trace.py](https://localhost:8080/#) in trace_module(mod, inputs, optimize, check_trace, check_inputs, check_tolerance, strict, _force_outplace, _module_class, _compilation_unit)
    965             example_inputs = make_tuple(example_inputs)
    966
--> 967             module._c._create_method_from_trace(
    968                 method_name,
    969                 func,

RuntimeError: Encountering a dict at the output of the tracer might cause the trace to be incorrect, this is only valid if the container structure does not change based on the module's inputs. Consider using a constant container instead (e.g. for `list`, use a `tuple` instead. for `dict`, use a `NamedTuple` instead). If you absolutely need this and know the side effects, pass strict=False to trace() to allow this behavior.

This is my code

model = VoteNet(10,12,10,np.random.random((10,3))).to('cuda')
model.eval()
model.load_state_dict(torch.load('checkpoint.tar'), strict=False)
dummy_input = {'point_clouds': torch.rand((20000,3)).unsqueeze(0).cuda()}
trace = torch.jit.trace(model, dummy_input)

I searched problem,then I found this https://github.com/huggingface/transformers/issues/9095

I changed code like this based on comments in the issue

model = VoteNet(10,12,10,np.random.random((10,3))).to('cuda')
model.eval()
model.load_state_dict(torch.load('checkpoint.tar'), return_dict=False)
dummy_input = {'point_clouds': torch.rand((20000,3)).unsqueeze(0).cuda()}
trace = torch.jit.trace(model, dummy_input)

But this time I got the following error

TypeError                                 Traceback (most recent call last)
[<ipython-input-31-0811dab20119>](https://localhost:8080/#) in <module>
----> 1 model.load_state_dict(torch.load('checkpoint.tar'), return_dict= False)

TypeError: load_state_dict() got an unexpected keyword argument 'return_dict'

I'm a beginner, so maybe I'm stumbling on a rudimentary part
Could you help me?


来源: stackexchange

问:
Invalid Caputre Filter
I have a Problem with my IP Telefon and the Partner want me to monitor the Network with Wireshark. I created a batch to start Wireshark on Startup with the following cmd line:

C:\Programme\wireshark>wireshark -i \Device\NPF_{23EA96D6-BEE6-405B-B124-B6E0D919C34F}  -f "net 66.81.246.0/20" -b filesize:10000 -w "C:\Users\EIBL\OneDrive\wiresharklogs\wireshark.pcap" -k --no-promiscuous-mode

The Problem is the /20 on -f "net 66.81.246.0/20" if i do /24 it works but on /22 or less i get an error. Can anybody help me?

did also try "net XXX.XXX.XXX.XXX mask XXX.XXX.XXX.XXX" but i wont work below /22

ContentLicense: CC BY-SA 4.0

Title: Invalid Caputre Filter


问:
What shall be the right structure/format for changelog file
I am trying to get my project automated using CI/CD pipelines and I am getting this error:

```<code>$ dpkg-buildpackage -us -uc
dpkg-buildpackage: source package 142CPACKAGE
dpkg-buildpackage: source version 1.1.1
dpkg-buildpackage: source changed by root <root@localhost>
dpkg-buildpackage: warning: debian/rules is not executable; fixing that
 dpkg-source --before-build edge_release_management
dpkg-buildpackage: host architecture amd64
dpkg-source: error: cannot read edge_release_management/debian/control: No such file or directory
dpkg-buildpackage: error: dpkg-source --before-build edge_release_management gave error exit status 2
Cleaning up project directory and file based variables
00:00
ERROR: Job failed: exit code 1
</code>```

Here is my changelog file:

```<code>142CPACKAGE (1.1.1) UNRELEASED; urgency=low
  * Initial releaseeeee. (Closes: #XXXXXX)
 -- root <root@localhost>  Wed, 07 Dec 2022 07:32:17 +0000
</code>```

Why my changelog file look like this because i used dch --create command in gitlab-ci.yml file and it gave me this output:

```<code>$ dch --create
Vim: Warning: Output is not to a terminal
Vim: Warning: Input is not from a terminal
="debian/changelog.dch" 5L, 142CPACKAGE (VERSION) UNRELEASED; urgency=low
  * Initial release. (Closes: #XXXXXX)
 -- root <root@localhost>  Wed, 07 Dec 2022 07:32:17 +0000
~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               1,1All
</code>```

So I copied this output and pasted it in debian/changefile and pushed changelog file on my git project so that pipelines picks it up from there.

here is my gitlab-ci.yml

```<code># Is performed before the scripts in the stages step
before_script:
  - source /etc/profile
  - echo "Hello, $GITLAB_USER_LOGIN!"
  - echo "Hello, $GITLAB_USER_PASSWORD"
#  - sudo rm /var/cache/apt/archives/lock
#  - sudo rm /var/lib/dpkg/lock
#  - sudo su
#  - sudo -S su < $password_secret

# Defines stages which are to be executed
stages:
  - build

# Stage "build"
run-build:
  stage: build
  script:
#    - apt-get install --force-yes libncurses5-dev libglib2.0-dev libgeoip-dev libtokyocabinet-dev zlib1g-dev libncursesw5-dev libbz2-dev
#    - autoreconf -fvi
#    - mkdir debian
    - ls
    - mkdir -p debian/usr/local/bin/
    - cp COPYING debian/copyright
    - cp ermbuild debian/usr/local/bin/ermbuild
#    - cp changelog debian
#    - cd ..
    - ls
#    - cd debian
    - pwd
    - ls
    - echo $EDITOR
#    - export EDITOR="/usr/bin/vim"
    - echo $EDITOR
#    - dch --create
    - dpkg-buildpackage -us -uc
    - mkdir build
    - mv ../ermbuild.deb build/

  # This stage is only executed for new tags
  only:
    - tags

  # The files which are to be made available in GitLab
  artifacts:
    paths:
      - build/*
</code>```

Body:
I am trying to get my project automated using CI/CD pipelines and I am getting this error:

$ dpkg-buildpackage -us -uc
dpkg-buildpackage: source package 142CPACKAGE
dpkg-buildpackage: source version 1.1.1
dpkg-buildpackage: source changed by root <root@localhost>
dpkg-buildpackage: warning: debian/rules is not executable; fixing that
 dpkg-source --before-build edge_release_management
dpkg-buildpackage: host architecture amd64
dpkg-source: error: cannot read edge_release_management/debian/control: No such file or directory
dpkg-buildpackage: error: dpkg-source --before-build edge_release_management gave error exit status 2
Cleaning up project directory and file based variables
00:00
ERROR: Job failed: exit code 1

Here is my changelog file:

142CPACKAGE (1.1.1) UNRELEASED; urgency=low
  * Initial releaseeeee. (Closes: #XXXXXX)
 -- root <root@localhost>  Wed, 07 Dec 2022 07:32:17 +0000

Why my changelog file look like this because i used dch --create command in gitlab-ci.yml file and it gave me this output:

$ dch --create
Vim: Warning: Output is not to a terminal
Vim: Warning: Input is not from a terminal
="debian/changelog.dch" 5L, 142CPACKAGE (VERSION) UNRELEASED; urgency=low
  * Initial release. (Closes: #XXXXXX)
 -- root <root@localhost>  Wed, 07 Dec 2022 07:32:17 +0000
~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               ~                                                                               1,1All

So I copied this output and pasted it in debian/changefile and pushed changelog file on my git project so that pipelines picks it up from there.

here is my gitlab-ci.yml

# Is performed before the scripts in the stages step
before_script:
  - source /etc/profile
  - echo "Hello, $GITLAB_USER_LOGIN!"
  - echo "Hello, $GITLAB_USER_PASSWORD"
#  - sudo rm /var/cache/apt/archives/lock
#  - sudo rm /var/lib/dpkg/lock
#  - sudo su
#  - sudo -S su < $password_secret

# Defines stages which are to be executed
stages:
  - build

# Stage "build"
run-build:
  stage: build
  script:
#    - apt-get install --force-yes libncurses5-dev libglib2.0-dev libgeoip-dev libtokyocabinet-dev zlib1g-dev libncursesw5-dev libbz2-dev
#    - autoreconf -fvi
#    - mkdir debian
    - ls
    - mkdir -p debian/usr/local/bin/
    - cp COPYING debian/copyright
    - cp ermbuild debian/usr/local/bin/ermbuild
#    - cp changelog debian
#    - cd ..
    - ls
#    - cd debian
    - pwd
    - ls
    - echo $EDITOR
#    - export EDITOR="/usr/bin/vim"
    - echo $EDITOR
#    - dch --create
    - dpkg-buildpackage -us -uc
    - mkdir build
    - mv ../ermbuild.deb build/

  # This stage is only executed for new tags
  only:
    - tags

  # The files which are to be made available in GitLab
  artifacts:
    paths:
      - build/*


问:
Cant log in from manually entered credentials for admin ASP.NET Core 6
I was following this tutorial (https://codewithmukesh.com/blog/user-management-in-aspnet-core-mvc/). I followed the tutorial till adding a default user (for admin purposes). I can view the added user in the database but cannot log in. On the other hand, if I register a user on the website (using the registration form), I can log in to that account. Can someone please help me?

https://drive.google.com/file/d/1CoWh74vwjstVIfJztwRoEuQmWGsceiR7/view?usp=sharing This is the link to my project file. Kindly take a look.

Thanks in advance.


问:
Why does an explicit interface implementation with varying case prevent a class from being CLS compliant?
Consider the following example:

```<code>[assembly:CLSCompliant(true)]

public interface I
{
    void FrobnicateSQL();
}

public class C : I
{
    public void FrobnicateSql() { }  // *
    void I.FrobnicateSQL() { }
}
</code>```

The line marked with * yields the following compiler warning:

CS3005: Identifier 'C.FrobnicateSql()' differing only in case is not CLS-compliant

Now, I understand that members visible to other assemblies should not differ only in case, because, for example, case-insensitive languages such as VB.NET would not be able to decide which method to call.

And technically, yes, both members are visible and only differ in case, but they are not visible at the same time: Since FrobnicateSQL is an explicit interface implementation, it's only visible if the static type of the variable is I. The following VB code using the library above compiles correctly and is completely unambiguous:

```<code>Dim c As New C()
Dim i As I = c

c.FrobnicateSql()
i.FrobnicateSQL()
</code>```

Still, the C# compiler treats this as a CLS violation. My question is: Why? Was it a deliberate design decision to include this rare edge case because it makes the specification and/or the algorithm for detecting CLS violations easier? Or did I miss something and the example above can actually cause problems in case-insensitive .NET languages?

Body:
Consider the following example:

[assembly:CLSCompliant(true)]

public interface I
{
    void FrobnicateSQL();
}

public class C : I
{
    public void FrobnicateSql() { }  // *
    void I.FrobnicateSQL() { }
}

The line marked with * yields the following compiler warning:

CS3005: Identifier 'C.FrobnicateSql()' differing only in case is not CLS-compliant

Now, I understand that members visible to other assemblies should not differ only in case, because, for example, case-insensitive languages such as VB.NET would not be able to decide which method to call.

And technically, yes, both members are visible and only differ in case, but they are not visible at the same time: Since FrobnicateSQL is an explicit interface implementation, it's only visible if the static type of the variable is I. The following VB code using the library above compiles correctly and is completely unambiguous:

Dim c As New C()
Dim i As I = c

c.FrobnicateSql()
i.FrobnicateSQL()

Still, the C# compiler treats this as a CLS violation. My question is: Why? Was it a deliberate design decision to include this rare edge case because it makes the specification and/or the algorithm for detecting CLS violations easier? Or did I miss something and the example above can actually cause problems in case-insensitive .NET languages?


问:
How can I add backend to Vite
I'm using Vite React App with Socket.io and I have a server.js inside the directory but outside Vite folder. How can I connect Back-End file (server.js) to Vite?

I tried to add a proxy inside package.json in Vite folder but it didn't work.

Title: How can I add backend to Vite


问:
SonarQube with Ant on multi module project having more submodules
I have a project with multiple modules where one module again has submodules

```<code>root
|
|--mod1
|--mod2
   |
   |--mod2.1
   |--mod2.2
|--mod3
</code>```

I am able to set up SonarQube and run analysis, except for mod2 as the configured Sonar src, binaries and report paths are not present in mod2, but in mod2.x

The relevant section from the build file:

```<code><property name="sonar.sources" value="src/main/java" />
<property name="sonar.java.binaries" value="target/tmp/classes" />
<property name="sonar.coverage.jacoco.xmlReportPaths" value="target/test-junit/coverage/report.xml" />
</code>```

I tried adding the properties under the root as well as in the build.xml in mod2 but getting the same issue.

What should be the correct way to configure this?

Body:
I have a project with multiple modules where one module again has submodules

root
|
|--mod1
|--mod2
   |
   |--mod2.1
   |--mod2.2
|--mod3

I am able to set up SonarQube and run analysis, except for mod2 as the configured Sonar src, binaries and report paths are not present in mod2, but in mod2.x

The relevant section from the build file:

<property name="sonar.sources" value="src/main/java" />
<property name="sonar.java.binaries" value="target/tmp/classes" />
<property name="sonar.coverage.jacoco.xmlReportPaths" value="target/test-junit/coverage/report.xml" />

I tried adding the properties under the root as well as in the build.xml in mod2 but getting the same issue.

What should be the correct way to configure this?


问:
Installing and using python3-adios on ubuntu 22.04
I just installed python3-adios by using apt-get python3-adios. Then when I try to use the attribute ad.file, python raised an error : "module 'adios' has no attribute 'file'" .
I don't understand why because I already get to used this attribute before on another computer..
How can I solve this problem ?</p>


问:
How to correctly access to remote Jupyter Lab server (Gitpod) and how to provide security
I'm working on a project, and one of the steps is to allow contributors to be able to use Jupyter Lab on the Gitpod. Also in our project, we assume that users can use Jupyter Lab on a compute cluster and connect to it from home. So basically our problem is related to accessing a remote Jupyter Lab server.

When I started testing this functionality, I noticed that we had a kernel connection problem (none of the used kernels can connect properly).

I started looking for information and found here and here that we need to change config options in jupyter_notebook_config.py. So I changed default option which is

```<code>c.ServerApp.allow_origin = ' '
</code>```

to

```<code>c.ServerApp.allow_origin = '*'
</code>```

After that change all kernels are connected properly.
But I started to wonder about security.

Is it safe to do it this way? I know that Jupyter Lab requires a token to be able to connect to the server and maybe that's enough, but I'm not sure.

Body:
I'm working on a project, and one of the steps is to allow contributors to be able to use Jupyter Lab on the Gitpod. Also in our project, we assume that users can use Jupyter Lab on a compute cluster and connect to it from home. So basically our problem is related to accessing a remote Jupyter Lab server.

When I started testing this functionality, I noticed that we had a kernel connection problem (none of the used kernels can connect properly).

I started looking for information and found here and here that we need to change config options in jupyter_notebook_config.py. So I changed default option which is

c.ServerApp.allow_origin = ' '

to

c.ServerApp.allow_origin = '*'

After that change all kernels are connected properly.
But I started to wonder about security.

Is it safe to do it this way? I know that Jupyter Lab requires a token to be able to connect to the server and maybe that's enough, but I'm not sure.


问:
Applying CryptoJS.AES.encrypt(inputText, password) in kotlin
I have this project wherein I have to convert nodeJs into Kotlin. The nodeJs project uses CryptoJS.AES.encrypt(text, password) which produces a encrypted value with 256 bytes. I. have been doing this in kotlin but the encrypted value returned is not the same from the nodeJs version and it only has 236 bytes. Can someone help me why it is not producing the same result? and how can i do it? Below is my sample code in kotlin</p>
```<code>fun encryptAesTry(text: String, password: String): String {

    val md = MessageDigest.getInstance("SHA-256")
    val bytes = password.toByteArray(StandardCharsets.UTF_8)
    md.update(bytes, 0, bytes.size)
    val key = md.digest()
    val secretKeySpec = SecretKeySpec(key, "AES")
    val c = Cipher.getInstance("AES")
    c.init(Cipher.ENCRYPT_MODE, secretKeySpec)
    val encVal = c.doFinal(text.toByteArray())

    return Base64.getEncoder().encodeToString(encVal)

}
</code>```

Body:
I have this project wherein I have to convert nodeJs into Kotlin. The nodeJs project uses CryptoJS.AES.encrypt(text, password) which produces a encrypted value with 256 bytes. I. have been doing this in kotlin but the encrypted value returned is not the same from the nodeJs version and it only has 236 bytes. Can someone help me why it is not producing the same result? and how can i do it? Below is my sample code in kotlin

fun encryptAesTry(text: String, password: String): String {

    val md = MessageDigest.getInstance("SHA-256")
    val bytes = password.toByteArray(StandardCharsets.UTF_8)
    md.update(bytes, 0, bytes.size)
    val key = md.digest()
    val secretKeySpec = SecretKeySpec(key, "AES")
    val c = Cipher.getInstance("AES")
    c.init(Cipher.ENCRYPT_MODE, secretKeySpec)
    val encVal = c.doFinal(text.toByteArray())

    return Base64.getEncoder().encodeToString(encVal)

}


问:
Sonarqube: service start but die after some second and not active on 9000 port
I'm trying, for testing, to install Sonarqube on a CentOS7 virtual machine created on Oracle Virtual Bx (8 Gbyte RAM, 2 CPU), with PostgreSQL 12 and Nginx following these steps https://blog.yasithab.com/centos/install-sonarqube-on-centos-7/

PostgreSQL installation is ok, service is up and running on port 5432

Also Nginx is  installed and up and running

When I check for the status of sonar service I obtain this

If I try

```<code>sudo netstat -tulpn | grep 9000
</code>```

nothing happens so no other services are on this port.

Checking the logs I've found a nohup.log file that says

```<code>2022.12.07 12:24:12 INFO  app[][o.s.a.AppFileSystem] Cleaning or creating temp directory /opt/sonarqube/temp
2022.12.07 12:24:12 INFO  app[][o.s.a.es.EsSettings] Elasticsearch listening on [HTTP: 127.0.0.1:9001, TCP: 127.0.0.1:44843]
2022.12.07 12:24:12 INFO  app[][o.s.a.ProcessLauncherImpl] Launch process[ELASTICSEARCH] from [/opt/sonarqube/elasticsearch]: /opt/sonarqube/elasticsearch/bin/elasticsearch
2022.12.07 12:24:12 INFO  app[][o.s.a.SchedulerImpl] Waiting for Elasticsearch to be up and running
uncaught exception in thread [main]
java.lang.RuntimeException: can not run elasticsearch as root
        at org.elasticsearch.bootstrap.Bootstrap.initializeNatives(Bootstrap.java:107)
        at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:183)
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:434)
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:169)
        at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:160)
        at org.elasticsearch.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:77)
        at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:112)
        at org.elasticsearch.cli.Command.main(Command.java:77)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:125)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:80)
For complete error details, refer to the log at /opt/sonarqube/logs/sonarqube.log
2022.12.07 12:24:16 WARN  app[][o.s.a.p.AbstractManagedProcess] Process exited with exit value [ElasticSearch]: 1
2022.12.07 12:24:16 INFO  app[][o.s.a.SchedulerImpl] Process[ElasticSearch] is stopped
2022.12.07 12:24:16 INFO  app[][o.s.a.SchedulerImpl] SonarQube is stopped
</code>```

This is my sonarqube installation directory

```<code>[vagrant@lgqrk-local sonarqube]$ pwd
/opt/sonarqube
[vagrant@lgqrk-local sonarqube]$ ls -la
total 92
drwxr-xr-x. 11 sonar sonar   172 Oct 28 06:31 .
drwxr-xr-x.  5 root  root     68 Dec  7 08:21 ..
drwxr-xr-x.  6 sonar sonar    96 Oct 28 06:26 bin
drwxr-xr-x.  2 sonar sonar    30 Dec  7 12:21 conf
-rw-r--r--.  1 sonar sonar  7651 Oct 28 06:26 COPYING
drwxr-xr-x.  4 sonar sonar    46 Dec  7 09:33 data
-rw-r--r--.  1 sonar sonar 78958 Oct 28 06:29 dependency-license.json
drwxr-xr-x.  7 sonar sonar   132 Oct 28 06:31 elasticsearch
drwxr-xr-x.  4 sonar sonar    40 Oct 28 06:26 extensions
drwxr-xr-x.  5 sonar sonar   132 Oct 28 06:32 lib
drwxr-xr-x.  2 sonar sonar   105 Dec  7 09:33 logs
drwxr-xr-x.  3 sonar sonar    38 Dec  7 12:55 temp
drwxr-xr-x.  5 sonar sonar  4096 Oct 28 06:32 web
</code>```

so the owner is sonar / sonar

What is happening?

Any suggestion will be appreciated and thank you in advance!

Body:
I'm trying, for testing, to install Sonarqube on a CentOS7 virtual machine created on Oracle Virtual Bx (8 Gbyte RAM, 2 CPU), with PostgreSQL 12 and Nginx following these steps https://blog.yasithab.com/centos/install-sonarqube-on-centos-7/

PostgreSQL installation is ok, service is up and running on port 5432

Also Nginx is  installed and up and running

When I check for the status of sonar service I obtain this

If I try

sudo netstat -tulpn | grep 9000

nothing happens so no other services are on this port.

Checking the logs I've found a nohup.log file that says

2022.12.07 12:24:12 INFO  app[][o.s.a.AppFileSystem] Cleaning or creating temp directory /opt/sonarqube/temp
2022.12.07 12:24:12 INFO  app[][o.s.a.es.EsSettings] Elasticsearch listening on [HTTP: 127.0.0.1:9001, TCP: 127.0.0.1:44843]
2022.12.07 12:24:12 INFO  app[][o.s.a.ProcessLauncherImpl] Launch process[ELASTICSEARCH] from [/opt/sonarqube/elasticsearch]: /opt/sonarqube/elasticsearch/bin/elasticsearch
2022.12.07 12:24:12 INFO  app[][o.s.a.SchedulerImpl] Waiting for Elasticsearch to be up and running
uncaught exception in thread [main]
java.lang.RuntimeException: can not run elasticsearch as root
        at org.elasticsearch.bootstrap.Bootstrap.initializeNatives(Bootstrap.java:107)
        at org.elasticsearch.bootstrap.Bootstrap.setup(Bootstrap.java:183)
        at org.elasticsearch.bootstrap.Bootstrap.init(Bootstrap.java:434)
        at org.elasticsearch.bootstrap.Elasticsearch.init(Elasticsearch.java:169)
        at org.elasticsearch.bootstrap.Elasticsearch.execute(Elasticsearch.java:160)
        at org.elasticsearch.cli.EnvironmentAwareCommand.execute(EnvironmentAwareCommand.java:77)
        at org.elasticsearch.cli.Command.mainWithoutErrorHandling(Command.java:112)
        at org.elasticsearch.cli.Command.main(Command.java:77)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:125)
        at org.elasticsearch.bootstrap.Elasticsearch.main(Elasticsearch.java:80)
For complete error details, refer to the log at /opt/sonarqube/logs/sonarqube.log
2022.12.07 12:24:16 WARN  app[][o.s.a.p.AbstractManagedProcess] Process exited with exit value [ElasticSearch]: 1
2022.12.07 12:24:16 INFO  app[][o.s.a.SchedulerImpl] Process[ElasticSearch] is stopped
2022.12.07 12:24:16 INFO  app[][o.s.a.SchedulerImpl] SonarQube is stopped

This is my sonarqube installation directory

[vagrant@lgqrk-local sonarqube]$ pwd
/opt/sonarqube
[vagrant@lgqrk-local sonarqube]$ ls -la
total 92
drwxr-xr-x. 11 sonar sonar   172 Oct 28 06:31 .
drwxr-xr-x.  5 root  root     68 Dec  7 08:21 ..
drwxr-xr-x.  6 sonar sonar    96 Oct 28 06:26 bin
drwxr-xr-x.  2 sonar sonar    30 Dec  7 12:21 conf
-rw-r--r--.  1 sonar sonar  7651 Oct 28 06:26 COPYING
drwxr-xr-x.  4 sonar sonar    46 Dec  7 09:33 data
-rw-r--r--.  1 sonar sonar 78958 Oct 28 06:29 dependency-license.json
drwxr-xr-x.  7 sonar sonar   132 Oct 28 06:31 elasticsearch
drwxr-xr-x.  4 sonar sonar    40 Oct 28 06:26 extensions
drwxr-xr-x.  5 sonar sonar   132 Oct 28 06:32 lib
drwxr-xr-x.  2 sonar sonar   105 Dec  7 09:33 logs
drwxr-xr-x.  3 sonar sonar    38 Dec  7 12:55 temp
drwxr-xr-x.  5 sonar sonar  4096 Oct 28 06:32 web

so the owner is sonar / sonar

What is happening?

Any suggestion will be appreciated and thank you in advance!


问:
Array formula for separating cell entries with delimiters
I was trying to use Split and Arrayformula to have separate entries for combination of items with multiple modifiers.

Input and Output is as illustrated below:
Sample Input & Output Desired

So far, I have used arrayformula-split combinations but none can provide the output I am looking for.


问:
Printing in Linux using Python
Good day,

I'm working on a Raspberry Pi project and one of the features is to print a .docx hard copy. Unfortunately, the os.startfile(filename, "print") method does not work on Linux. Is there a good workaround for this? I'm using Python 3.7 for this project.

Thank you.

Title: Printing in Linux using Python


问:
Streaming Jobs and tables consistency
I have been assigned the task to create a data streaming pipeline to move data from mysql to a datalake.

To achieve this task, I have created a pipeline using Debezium, Kafka and Spark Structured Streaming.

Debezium writes all the events to a single kafka topic.

The Spark job uses the forEachBatch function, it reads events, divides them by table, and makes sure to upsert events in each corresponding table using Delta.

One tough requirement to implement is that this data should be directly queried by data consumers, it is a tough requirement because due to grouping upserts by table I am changing the events order (performing upserts in an ordered way for each individual transaction would be extremely inefficient). This could lead to potential data inconsistencies because during the batch processing time some tables are more updated than others.

One way to mitigate this issue I came up with is to let users access these tables only through athena/snowflake, this way I can decouple what data I am showing from what data is actually inside the table by using the symlink manifest files. This is a workaround and not a definitive solution, because it minimizes the time tables are inconsistent to the time it takes to refresh all the manifests.

Is there any better way to achieve consistency between tables in a streaming system?

I am also tempted to reduce inconsistency by minimizing latency , creating append-only tables, but I am afraid these tables will start growing exponentially.

Title: Streaming Jobs and tables consistency


问:
OPENPYXL - Exception has occurred: ParseError - mismatched tag: line 19, column 8
I am creating a Django application to be run on an IIS server.

I need to update an Excel file (with macros - extension xlsm) automatically on the server. Given that the interactive update using COM (pywin32.com) is not supported by Microsoft (https://support.microsoft.com/en-us/topic/considerations-for-server-side-automation-of-office-48bcfe93-8a89-47f1-0bce-017433ad79e2), I am using OpenPYXL (version 3.0.7) to manipulate the Excel file.

Before moving on to the actual Django application, I am testing it in a standard Python environment (version 3.9.1).

IMPORTANT NOTE: This .xlsm Excel file format needs to be preserved after writing values to it, i.e., all formulae and macros need be maintained.

Here is a snippet of the relevant code:

The function is called, invoking as argument, the Excel .xlsm file:

Code snippet 1

Here is the relevant function code together with the error message:

Code snippet 2

The error occurs when the Excel file is saved. I have tested the loading of the file - openpyxl.load_workbook(uploaded_excel_file, keep_vba=True) - with and without the keep_vba=True argument.

I don't find anything special with Line 19 Column 8 in the Excel file. I am sorry, but due to confidentiality reasons, I cannot share the file.

The error only occurs when the keep_vba=True .

Any help is much appreciated.


问:
Inconsistency in MIME types for .py files
I am currently working on a file selector in js which should accept certain file types. Everything is working fine, except when it comes to Python files.

The way i'm handling accepting different types is by using MIME types. So for example, to accept excel files i'm setting "application/vnd.ms-excel", which is working correctly.
Though, when I want to accept .py files, setting "text/x-python" does not suffice. I am aware that I can set accept to ".py", but in my case I want to specifically set the MIME tipe and not the file suffix. Furthermore, some python files seems to get the type "text/plain" which is another problem I am completely baffled of.

So, my question is: Why is it that python files seem to be handled somewhat differently from others? The MIME type should be consistent and enough to get the OS browser to show .py files.


问:
Including other projects in the Java Build Path using Eclipse and Maven
I have been using Eclipse and Maven quite happily (in a largely non-understanding way) for some time to build Java/Selenium/TestNG projects.
I have one project representing a set of utilities that I use in all of the other website-based projects.
To include the utility classes I have simply added the utilities Project to the Classpath via the Java Build Path dialog.  This worked well and any changes made to the utilities project were immediately reflected in the projects that used it.
However, when adding Logging capability (slf4j + logback) I started hitting issues with multiple versions being included.  I eventually tracked down the issues but in order to solve them I ran "clean install" on both the utilities project and the projects using the utilities.
As a result I am now unable to build the website-based projects without adding the utilities jar as a dependency in pom.xml.

The previous method of simply adding as a Project is still sufficient to remove the errors from displaying on the source files, but now Maven (maven-compiler-plugin:3.7.0) reports a Compilation Failure as it says the utilities packages do not exist.

Looking at the impact of adding a Project to the build path, I see that a line is added to the project's .classpath file:
<classpathentry combineaccessrules="false" kind="src" path="/myutils"/>
but Maven debug shows no indication that this has had any impact on the classpath that it uses to compile.

What did I break when I did "clean install" and how do I restore it?
What mechanism does the Java Build Path Projects tab use to include content (source files or compiled classes?) from other projects in the Workspace?

Alternatively is this just a feature of Maven, that it wants to control everything (but why did it work before?) and is the dependency solution just as good?  When including via dependencies (in pom.xml) are changes made to utilities immediately reflected without the need for a complete rebuild?


问:
FFMPEG Pipeline
I created an FFMPEG pipeline so that I can stream video frames to an RTSP server. I created a synthetic video for testing where each frame is a green number on a black background. The video plays on my screen but it does not stream to the server because I get the error  "Unable to find a suitable output format for 'rtsp://10.0.0.6:8554/mystream"
My code is below.  The source code is taken from the answer: How to stream frames from OpenCV C++ code to Video4Linux or ffmpeg?

```<code>int main() {
    int width = 720;
    int height = 1280;
    int fps = 30;

    FILE* pipeout = _popen("ffmpeg -f rawvideo -r 30 -video_size 720x1280 -pixel_format bgr24 -i pipe: -vcodec libx264 -crf 24 -pix_fmt yuv420p rtsp://10.0.0.6:8554/mystream", "w");

    for (int i = 0; i < 100; i++)
    {
        Mat frame = Mat(height, width, CV_8UC3);
        frame = Scalar(60, 60, 60); //Fill background with dark gray
        putText(frame, to_string(i + 1), Point(width / 2 - 50 * (int)(to_string(i + 1).length()), height / 2 + 50), FONT_HERSHEY_DUPLEX, 5, Scalar(30, 255, 30), 10);  // Draw a green number

        imshow("frame", frame);
waitKey(1);

        fwrite(frame.data, 1, width * height * 3, pipeout);
    }
    // Flush and close input and output pipes
    fflush(pipeout);

    _pclose(pipeout);   //Windows
    return 0;
}
</code>```

When I change -f rawvideo to -f rtsp in the FFMPEG command, I no longer get the error but the program just displays the first frame on the screen and seems to get stuck. Is there a wrong parameter in the pipeline. When I change the RTSP url to a file name such as output.mkv, it works perfectly and saves the video to the file.

Title: FFMPEG Pipeline

Body:
I created an FFMPEG pipeline so that I can stream video frames to an RTSP server. I created a synthetic video for testing where each frame is a green number on a black background. The video plays on my screen but it does not stream to the server because I get the error  "Unable to find a suitable output format for 'rtsp://10.0.0.6:8554/mystream"
My code is below.  The source code is taken from the answer: How to stream frames from OpenCV C++ code to Video4Linux or ffmpeg?

int main() {
    int width = 720;
    int height = 1280;
    int fps = 30;

    FILE* pipeout = _popen("ffmpeg -f rawvideo -r 30 -video_size 720x1280 -pixel_format bgr24 -i pipe: -vcodec libx264 -crf 24 -pix_fmt yuv420p rtsp://10.0.0.6:8554/mystream", "w");

    for (int i = 0; i < 100; i++)
    {
        Mat frame = Mat(height, width, CV_8UC3);
        frame = Scalar(60, 60, 60); //Fill background with dark gray
        putText(frame, to_string(i + 1), Point(width / 2 - 50 * (int)(to_string(i + 1).length()), height / 2 + 50), FONT_HERSHEY_DUPLEX, 5, Scalar(30, 255, 30), 10);  // Draw a green number

        imshow("frame", frame);
waitKey(1);

        fwrite(frame.data, 1, width * height * 3, pipeout);
    }
    // Flush and close input and output pipes
    fflush(pipeout);

    _pclose(pipeout);   //Windows
    return 0;
}

When I change -f rawvideo to -f rtsp in the FFMPEG command, I no longer get the error but the program just displays the first frame on the screen and seems to get stuck. Is there a wrong parameter in the pipeline. When I change the RTSP url to a file name such as output.mkv, it works perfectly and saves the video to the file.


问:
Distorted lines in Travel Tracking in Flutter
I am trying to implement a functionality, that if a user travels, then his/her live location will be captured in every interval of 10 sec. I am saving the captured lat-longs in local database and then run a API after every 10 mins to save data on server.

In every 10 secs I am calculating the distance between last last lat-long captured and updated lat-long captured.

When I tested it, I travelled around 35 KM, but total distance calculate was around 400 KM.
On again testing, I travelled around 15 KM, but total distance calculate was around 150 KM.

Please anyone suggest what am I doing wrong. Or is there any alternative solution to track my path on which I travelled and total distance I covered.

For this I am using the below code to run the timer in every 10 secs

```<code>Timer.periodic(const Duration(seconds: 10), (timer) async {
  await CommonMethods.getCurrentLocationDateTime();
});
</code>```

In every 10 secs, I run the below code:

```<code>static Future getCurrentLocationDateTime() async {
  _result = await Geolocator.getCurrentPosition(
    desiredAccuracy: LocationAccuracy.bestForNavigation,
  );
  if (_updatedLatitude == null && _updatedLongitude == null) {
    _previousLatitude = _result!.latitude;
    _previousLongitude = _result!.longitude;
  } else {
    _previousLatitude = _updatedLatitude;
    _previousLongitude = _updatedLongitude;
  }
  _updatedLatitude = _result!.latitude;
  _updatedLongitude = _result!.longitude;

  // Save data in a local variable
  Map<String, String> _currentLatLong = {
    "lat": _result!.latitude.toStringAsFixed(8),
    "long": _result!.longitude.toStringAsFixed(8),
  };
  CommonEntities.travelHistoryLatLng.add(_currentLatLong);

  // Update previous and current location names
  await placemarkFromCoordinates(_updatedLatitude!, _updatedLongitude!)
      .then((List<Placemark> placemarks) {
    _previousLocationName = (_currentLocationName == "")
        ? placemarks[0].name!
        : _currentLocationName;
    _currentLocationName = placemarks[0].subLocality!;
  }).catchError((e) {
    debugPrint(e.toString());
  });

  // Check if device is not moved for more than 2 hours
  // if not moved then stop the timer
  if (CommonEntities.travelHistoryLatLng.toSet().length == 1) {
    CommonEntities.idealStateTravelTimeSpent += 10;
    if (CommonEntities.idealStateTravelTimeSpent >= 7200) {
      CommonEntities.idealStateTravelTimeSpent = 0;
      // BackgroundLocation.stopLocationService();
      if (CommonEntities.travelTimer != null) {
        CommonEntities.travelTimer!.cancel();
      }
      CommonEntities.isTravelTimerActive = false;
      CommonEntities.workEndTime =
          CommonEntities.travelTrackingDetails["current_date_time"];
    }
  } else {
    CommonEntities.idealStateTravelTimeSpent = 0;
  }

  // Get Current date time of captured lat-longs
  _currentDateTime = DateTime.now();
  _currentDateTimeString = _currentDateTime.year.toString() +
      "-" +
      _currentDateTime.month.toString() +
      "-" +
      _currentDateTime.day.toString() +
      " " +
      _currentDateTime.hour.toString() +
      ":" +
      _currentDateTime.minute.toString();

  if (CommonEntities.workStartTime == "00:00") {
    CommonEntities.workStartTime = _currentDateTime.hour.toString() +
        ":" +
        _currentDateTime.minute.toString();
    // LocalSharedPreferences().setWorkStartTime();
  }

  // Update the total distance covered in 10 min
  updateDistanceTraveled();
  print("Total Distance Covered: " + CommonEntities.travelTrackingDetails["total_distance_covered"]);
  // Call API to save travel data in every 10 minutes.
  if (CommonEntities.totalTravelsecondsCount == 600) {
    // Calculate the time before 10 min and for time interval in post params
    String _currentTime = _currentDateTime.hour.toString() +
        ':' +
        _currentDateTime.minute.toString();
    DateTime _dateTimeBeforeTenMin =
        _currentDateTime.subtract(const Duration(minutes: 10));
    String _timeBeforeTenMin = _dateTimeBeforeTenMin.hour.toString() +
        ':' +
        _dateTimeBeforeTenMin.minute.toString();

    String _tempDistanceTravelled =
        CommonEntities.travelTrackingDetails["total_distance_covered"];
    CommonEntities.travelTrackingDetails["total_distance_covered"] = "";
    _distanceTravelled = 0.0;
    // Create post params value
    Map<String, dynamic> params = {
      'lat_long': jsonEncode(CommonEntities.travelHistoryLatLng),
      'date': _currentDateTime.day.toString() +
          '-' +
          _currentDateTime.month.toString() +
          '-' +
          _currentDateTime.year.toString() +
          ' ' +
          _currentDateTime.hour.toString() +
          ':' +
          _currentDateTime.minute.toString() +
          ':' +
          _currentDateTime.second.toString(),
      'distance_covered': _tempDistanceTravelled,
      'userID': await LocalSharedPreferences().getUserId(),
      'time_interval': _timeBeforeTenMin + '-' + _currentTime,
      'location_name': _currentLocationName,
      'status': 'progress',
    };

    // Call the API to save travel history of 10 min of server
    HomeProvider().saveTravelDetails(params);
    // await LocalSharedPreferences().saveTravelHistoryLatLng();

    // Reset the timer of 10 min, clear lat-long history of 10 min
    CommonEntities.totalTravelsecondsCount = 0;
    CommonEntities.travelHistoryLatLng = [];
  }
  CommonEntities.totalTravelsecondsCount += 10;

  // Save latlong and date time
  // BOC: commented logging of lat-long as the same is not required in final app
  // by shubham.bansal2
  AppLogs().logToFile(
      _result!.latitude.toString() + "-" + _result!.longitude.toString(),
      _currentDateTimeString);

  CommonEntities.travelTrackingDetails["updated_latitude"] =
      _updatedLatitude!.toStringAsFixed(8);
  CommonEntities.travelTrackingDetails["updated_longitude"] =
      _updatedLongitude!.toStringAsFixed(8);
  CommonEntities.travelTrackingDetails["updated_location_name"] =
      _currentLocationName;
  CommonEntities.travelTrackingDetails["previous_latitude"] =
      _previousLatitude!.toStringAsFixed(8);
  CommonEntities.travelTrackingDetails["previous_longitude"] =
      _previousLongitude!.toStringAsFixed(8);
  CommonEntities.travelTrackingDetails["previous_location_name"] =
      _previousLocationName;
  CommonEntities.travelTrackingDetails["total_distance_covered"] =
      _distanceTravelled.toStringAsFixed(8);
  CommonEntities.travelTrackingDetails["current_date_time"] =
      _currentDateTimeString;
}
</code>```

Also for Distance, I am using the below code:

```<code>static updateDistanceTraveled() {
  var p = 0.017453292519943295;
  var c = cos;
  var a = 0.5 -
      c((_updatedLatitude! - _previousLatitude!) * p) / 2 +
      c(_previousLatitude! * p) *
          c(_updatedLatitude! * p) *
          (1 - c((_updatedLongitude! - _previousLongitude!) * p)) /
          2;
  _distanceTravelled = double.parse(CommonEntities.travelTrackingDetails["total_distance_covered"]);
  _distanceTravelled += (12742 * asin(sqrt(a))).toDouble();
  CommonEntities.travelTrackingDetails["total_distance_covered"] =
      _distanceTravelled.toStringAsFixed(5);
}
</code>```
```<code></code>```

Body:
I am trying to implement a functionality, that if a user travels, then his/her live location will be captured in every interval of 10 sec. I am saving the captured lat-longs in local database and then run a API after every 10 mins to save data on server.

In every 10 secs I am calculating the distance between last last lat-long captured and updated lat-long captured.

When I tested it, I travelled around 35 KM, but total distance calculate was around 400 KM.
On again testing, I travelled around 15 KM, but total distance calculate was around 150 KM.

Please anyone suggest what am I doing wrong. Or is there any alternative solution to track my path on which I travelled and total distance I covered.

For this I am using the below code to run the timer in every 10 secs

Timer.periodic(const Duration(seconds: 10), (timer) async {
  await CommonMethods.getCurrentLocationDateTime();
});

In every 10 secs, I run the below code:

static Future getCurrentLocationDateTime() async {
  _result = await Geolocator.getCurrentPosition(
    desiredAccuracy: LocationAccuracy.bestForNavigation,
  );
  if (_updatedLatitude == null && _updatedLongitude == null) {
    _previousLatitude = _result!.latitude;
    _previousLongitude = _result!.longitude;
  } else {
    _previousLatitude = _updatedLatitude;
    _previousLongitude = _updatedLongitude;
  }
  _updatedLatitude = _result!.latitude;
  _updatedLongitude = _result!.longitude;

  // Save data in a local variable
  Map<String, String> _currentLatLong = {
    "lat": _result!.latitude.toStringAsFixed(8),
    "long": _result!.longitude.toStringAsFixed(8),
  };
  CommonEntities.travelHistoryLatLng.add(_currentLatLong);

  // Update previous and current location names
  await placemarkFromCoordinates(_updatedLatitude!, _updatedLongitude!)
      .then((List<Placemark> placemarks) {
    _previousLocationName = (_currentLocationName == "")
        ? placemarks[0].name!
        : _currentLocationName;
    _currentLocationName = placemarks[0].subLocality!;
  }).catchError((e) {
    debugPrint(e.toString());
  });

  // Check if device is not moved for more than 2 hours
  // if not moved then stop the timer
  if (CommonEntities.travelHistoryLatLng.toSet().length == 1) {
    CommonEntities.idealStateTravelTimeSpent += 10;
    if (CommonEntities.idealStateTravelTimeSpent >= 7200) {
      CommonEntities.idealStateTravelTimeSpent = 0;
      // BackgroundLocation.stopLocationService();
      if (CommonEntities.travelTimer != null) {
        CommonEntities.travelTimer!.cancel();
      }
      CommonEntities.isTravelTimerActive = false;
      CommonEntities.workEndTime =
          CommonEntities.travelTrackingDetails["current_date_time"];
    }
  } else {
    CommonEntities.idealStateTravelTimeSpent = 0;
  }

  // Get Current date time of captured lat-longs
  _currentDateTime = DateTime.now();
  _currentDateTimeString = _currentDateTime.year.toString() +
      "-" +
      _currentDateTime.month.toString() +
      "-" +
      _currentDateTime.day.toString() +
      " " +
      _currentDateTime.hour.toString() +
      ":" +
      _currentDateTime.minute.toString();

  if (CommonEntities.workStartTime == "00:00") {
    CommonEntities.workStartTime = _currentDateTime.hour.toString() +
        ":" +
        _currentDateTime.minute.toString();
    // LocalSharedPreferences().setWorkStartTime();
  }

  // Update the total distance covered in 10 min
  updateDistanceTraveled();
  print("Total Distance Covered: " + CommonEntities.travelTrackingDetails["total_distance_covered"]);
  // Call API to save travel data in every 10 minutes.
  if (CommonEntities.totalTravelsecondsCount == 600) {
    // Calculate the time before 10 min and for time interval in post params
    String _currentTime = _currentDateTime.hour.toString() +
        ':' +
        _currentDateTime.minute.toString();
    DateTime _dateTimeBeforeTenMin =
        _currentDateTime.subtract(const Duration(minutes: 10));
    String _timeBeforeTenMin = _dateTimeBeforeTenMin.hour.toString() +
        ':' +
        _dateTimeBeforeTenMin.minute.toString();

    String _tempDistanceTravelled =
        CommonEntities.travelTrackingDetails["total_distance_covered"];
    CommonEntities.travelTrackingDetails["total_distance_covered"] = "";
    _distanceTravelled = 0.0;
    // Create post params value
    Map<String, dynamic> params = {
      'lat_long': jsonEncode(CommonEntities.travelHistoryLatLng),
      'date': _currentDateTime.day.toString() +
          '-' +
          _currentDateTime.month.toString() +
          '-' +
          _currentDateTime.year.toString() +
          ' ' +
          _currentDateTime.hour.toString() +
          ':' +
          _currentDateTime.minute.toString() +
          ':' +
          _currentDateTime.second.toString(),
      'distance_covered': _tempDistanceTravelled,
      'userID': await LocalSharedPreferences().getUserId(),
      'time_interval': _timeBeforeTenMin + '-' + _currentTime,
      'location_name': _currentLocationName,
      'status': 'progress',
    };

    // Call the API to save travel history of 10 min of server
    HomeProvider().saveTravelDetails(params);
    // await LocalSharedPreferences().saveTravelHistoryLatLng();

    // Reset the timer of 10 min, clear lat-long history of 10 min
    CommonEntities.totalTravelsecondsCount = 0;
    CommonEntities.travelHistoryLatLng = [];
  }
  CommonEntities.totalTravelsecondsCount += 10;

  // Save latlong and date time
  // BOC: commented logging of lat-long as the same is not required in final app
  // by shubham.bansal2
  AppLogs().logToFile(
      _result!.latitude.toString() + "-" + _result!.longitude.toString(),
      _currentDateTimeString);

  CommonEntities.travelTrackingDetails["updated_latitude"] =
      _updatedLatitude!.toStringAsFixed(8);
  CommonEntities.travelTrackingDetails["updated_longitude"] =
      _updatedLongitude!.toStringAsFixed(8);
  CommonEntities.travelTrackingDetails["updated_location_name"] =
      _currentLocationName;
  CommonEntities.travelTrackingDetails["previous_latitude"] =
      _previousLatitude!.toStringAsFixed(8);
  CommonEntities.travelTrackingDetails["previous_longitude"] =
      _previousLongitude!.toStringAsFixed(8);
  CommonEntities.travelTrackingDetails["previous_location_name"] =
      _previousLocationName;
  CommonEntities.travelTrackingDetails["total_distance_covered"] =
      _distanceTravelled.toStringAsFixed(8);
  CommonEntities.travelTrackingDetails["current_date_time"] =
      _currentDateTimeString;
}

Also for Distance, I am using the below code:

static updateDistanceTraveled() {
  var p = 0.017453292519943295;
  var c = cos;
  var a = 0.5 -
      c((_updatedLatitude! - _previousLatitude!) * p) / 2 +
      c(_previousLatitude! * p) *
          c(_updatedLatitude! * p) *
          (1 - c((_updatedLongitude! - _previousLongitude!) * p)) /
          2;
  _distanceTravelled = double.parse(CommonEntities.travelTrackingDetails["total_distance_covered"]);
  _distanceTravelled += (12742 * asin(sqrt(a))).toDouble();
  CommonEntities.travelTrackingDetails["total_distance_covered"] =
      _distanceTravelled.toStringAsFixed(5);
}


问:
Performance issues processing & updating huge dataset in JS
I have a Python Tkinter app that loads a dataset with 10 million data points into a plot using Matplotlib. In addition, it allows the user to constantly apply various signal processing filters on runtime that manipulate the data and update the plot.

I'm re-building this app in a web platform using React and microservices architecture, The data files are saved in S3 and loaded by the client side.

The data filters that should be applied are:

Butterworth

Trace normalize

Standard deviation

The python libraries used currently are:

scipy

NumPy

matplotlib

The problems I'm facing are as followed:

There are no apparent libraries in JS that suits my needs for complex signal processing like Pyhton does

Doing the processing anywhere else than the client side will result in unnecessary network trafficking.

What is the right approach for applying live complex mathematical calculations for a huge dataset in JS?

My initial thinking was to send an HTTP request to a Python microservice with the chosen filters that he will apply to the file and send the data back to the client. The biggest problem with that approach is the huge network trafficking used just to make a small change. For compression in the desktop app, it takes less than half a second to process such a change.

My web app is written in ReactJS and the plot library I'm using is Poltly.js which is working just fine, but the real-time data manipulation is the big challenge.


问:
react-google-maps/api polyline weird lines issue
i am trying to draw directions with a dynamic latitude and longitude array of objects coming from a realtime database, its working properly but there is a extra weird lines like the image below

what i want

if anyone can help thats will be great, thanks

here is my code snippets:

```<code>const [tripsState, setTripsState] = useState([]);
useEffect(() => {
    const unsubscribe = onSnapshot(collection(db, "LiveTrips"), (snapshot) => {
      setTripsState(
        snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() }))
      );
      // setStopNames(
      //   snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() }))
      // );
    });
    return () => {
      unsubscribe();
    };
  }, []);
</code>```
```<code>const handleDisplayMapById = (id) => {
    setTripID(id);
    tripsState.map((item) => {
      if (id === item.id) {
        setCurrentTrip(item);
        setStops(item.data.Stops);
      } else {
        console.log("not working");
      }
    });
  };
</code>```
```<code>const getCurrentTripData = () => {
    for (var key in currentTrip) {
      if (currentTrip.hasOwnProperty(key)) {
        SiteLocation = currentTrip[key].SiteLocation;
      }
    }
  };
  getCurrentTripData();
</code>```
```<code>const handlePolylineDraw = () => {
    var PathLatLong = [];
    var polylinePath = [];
    if (tripID > 0) {
      PathLatLong.length = 0;
      polylinePath.length = 0;
      PathLatLong = currentTrip.data.Polyline.map((line) => {
        return decode(line);
      });
      // console.log(PathLatLong);
      for (let x of PathLatLong) {
        x.map((i) => {
          polylinePath.push({ lat: i[0], lng: i[1] });
        });
      }
    }
    return { polylinePath };
  };
</code>```
```<code><Polyline
  path={handlePolylineDraw().polylinePath}
   options={{
                        strokeColor: "#42A9E7",
                        strokeOpacity: 1,
                        strokeWeight: 3,
                        fillOpacity: 0,
                        clickable: false,
                        draggable: true,
                        editable: false,
                        visible: true,
                        radius: 30000,
                        path: handlePolylineDraw().polylinePath,
                        zIndex: 1,
                      }}
                    />
</code>```
```<code></code>```

Body:
i am trying to draw directions with a dynamic latitude and longitude array of objects coming from a realtime database, its working properly but there is a extra weird lines like the image below

what i want

if anyone can help thats will be great, thanks

here is my code snippets:

const [tripsState, setTripsState] = useState([]);
useEffect(() => {
    const unsubscribe = onSnapshot(collection(db, "LiveTrips"), (snapshot) => {
      setTripsState(
        snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() }))
      );
      // setStopNames(
      //   snapshot.docs.map((doc) => ({ id: doc.id, data: doc.data() }))
      // );
    });
    return () => {
      unsubscribe();
    };
  }, []);

const handleDisplayMapById = (id) => {
    setTripID(id);
    tripsState.map((item) => {
      if (id === item.id) {
        setCurrentTrip(item);
        setStops(item.data.Stops);
      } else {
        console.log("not working");
      }
    });
  };

const getCurrentTripData = () => {
    for (var key in currentTrip) {
      if (currentTrip.hasOwnProperty(key)) {
        SiteLocation = currentTrip[key].SiteLocation;
      }
    }
  };
  getCurrentTripData();

const handlePolylineDraw = () => {
    var PathLatLong = [];
    var polylinePath = [];
    if (tripID > 0) {
      PathLatLong.length = 0;
      polylinePath.length = 0;
      PathLatLong = currentTrip.data.Polyline.map((line) => {
        return decode(line);
      });
      // console.log(PathLatLong);
      for (let x of PathLatLong) {
        x.map((i) => {
          polylinePath.push({ lat: i[0], lng: i[1] });
        });
      }
    }
    return { polylinePath };
  };

<Polyline
  path={handlePolylineDraw().polylinePath}
   options={{
                        strokeColor: "#42A9E7",
                        strokeOpacity: 1,
                        strokeWeight: 3,
                        fillOpacity: 0,
                        clickable: false,
                        draggable: true,
                        editable: false,
                        visible: true,
                        radius: 30000,
                        path: handlePolylineDraw().polylinePath,
                        zIndex: 1,
                      }}
                    />


问:
Changer l'ID Google Tag Manager (GTM) dynamiquement
Context:
We have launched the beta of our event-based in-app messaging SaaS. We want to make a sandbox to allow users to test the tool and validate if it fits their needs.

For this we want to allow our testers to add their GTM ID to be able to play with the product on a fake application.

Do you know a way to send a gtm ID dynamically so that with a single web-app they can each send their own in-app messages from their GTM?

Currently we are looking for solutions and will try to change the GTM ID to a param URL, but have very little hope.

Open to all possibilities


问:
mvc 2 passing a parameter as a QueryString
If I have for example a controller home with a ActionResult videoInfo Home/VideoInfo that pop up a form where put id and after clicking button getinfo it will redirect me to a page where info about a video are displayed. VideoInfo is an ActionResult.
The url look like: Home/VideoInfo/21222 where 21222 is the id and this url display some infos about a video. For the Id I have created a model : class Video with the property public int id {get; set}.

How can I make the url home/VideoInfo?id=21222 and redirect me to a page where info's are dispayed? make it like a querystring i guess..., no?

Need help pls. Thx

ContentLicense: CC BY-SA 3.0


问:
Google Play Store Notification to remove the app || SSL Error Handler Security Vulnerability
I am recently getting security vulnerabilities regarding the SSL Error Handler.
I have checked many stackoverflow question but couldnt come to a conclusion to how to fix it. Some recent answers are saying to not override the onReceivedSslError but am not sure what will be the consequence of it.

Please suggest a fix for the below:

```<code> @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        if (SslError.SSL_UNTRUSTED == error.getPrimaryError() &&
                (error.getUrl().startsWith("https://localhost:" + Constants.TEST_SERVER_PORT) ||
                        error.getUrl().startsWith("wss://localhost:" + Constants.TEST_SERVER_PORT))) {
            handler.proceed();
        } else {
            handler.cancel();
        }
    }
</code>```

The method overided from SystemWebViewClient.

Please let me know how to fix this error as the google notified that the app will be removed from play store.

Body:
I am recently getting security vulnerabilities regarding the SSL Error Handler.
I have checked many stackoverflow question but couldnt come to a conclusion to how to fix it. Some recent answers are saying to not override the onReceivedSslError but am not sure what will be the consequence of it.

Please suggest a fix for the below:

 @Override
    public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
        if (SslError.SSL_UNTRUSTED == error.getPrimaryError() &&
                (error.getUrl().startsWith("https://localhost:" + Constants.TEST_SERVER_PORT) ||
                        error.getUrl().startsWith("wss://localhost:" + Constants.TEST_SERVER_PORT))) {
            handler.proceed();
        } else {
            handler.cancel();
        }
    }

The method overided from SystemWebViewClient.

Please let me know how to fix this error as the google notified that the app will be removed from play store.


问:
Appium Webview for windows application not working
Appium Webview for windows application not working,
once i click on webview/Hybrid app icon on top of appium inspector , not able to fetch all the webview HTML DOM elements.

I tried adding capabilities for windows

```<code>{
  "platformName": "windows",
  "appium:platformVersion": "10",
  "appium:deviceName": "WindowsPC",
  "appium:app": "xxxxx",
  "appium:allowInvisibleElements": true,
  "appium:autoWebview": true,
}

can you help me out with any other capabilities thats need to be added or any other work around how to get the DOM element once i click on appium inspector from windows app.

You can see webview HTML DOM elements for IOS. But not in windows
</code>```

Windows - https://i.stack.imgur.com/y503o.png
IOS - https://i.stack.imgur.com/nd3oD.png

Body:
Appium Webview for windows application not working,
once i click on webview/Hybrid app icon on top of appium inspector , not able to fetch all the webview HTML DOM elements.

I tried adding capabilities for windows

{
  "platformName": "windows",
  "appium:platformVersion": "10",
  "appium:deviceName": "WindowsPC",
  "appium:app": "xxxxx",
  "appium:allowInvisibleElements": true,
  "appium:autoWebview": true,
}

can you help me out with any other capabilities thats need to be added or any other work around how to get the DOM element once i click on appium inspector from windows app.

You can see webview HTML DOM elements for IOS. But not in windows

Windows - https://i.stack.imgur.com/y503o.png
IOS - https://i.stack.imgur.com/nd3oD.png


问:
Presenting Modal UINavigationController Changes Background of presented UIViewController
I have a current controller within a UITabBarController

I present a UINavigationController on this UITabBarController with a modal style of .overFullScreen

I then want to present modally another controller on top of this however, the background color of the second modally presented controller is grey. Even if it's set to another color it will revert to a grey color.

How do I remove this color issue?

CODE

```<code>// MARK: - WITHIN TABBARCONTROLLER
fileprivate func presentCreatePostController() {
    let controller = CreatePostController()
    let navigationController = UINavigationController(rootViewController: controller)
    navigationController.navigationBar.configureAppearance()
    navigationController.modalPresentationStyle = .overFullScreen
    navigationController.navigationBar.isTranslucent = true
    selectedViewController?.present(navigationController, animated: true)
}

// MARK: - WITHIN CREATEPOSTCONTROLLER
func uploadMedia() {
    print("UPLOAD IMAGE BUTTON TAPPED")
    PermissionManager.shared.requestPhotoLibraryPermission()
    let navigationController = UINavigationController(rootViewController: ControllerProvider.mediaPickerController)
    navigationController.modalPresentationStyle = .popover
    navigationController.definesPresentationContext = true
    let rootViewController: UIViewController = (UIApplication.shared.windows.last?.rootViewController)!
    self.view.endEditing(true)
    rootViewController.present(navigationController, animated: true, completion: nil)
}
</code>```

Body:
I have a current controller within a UITabBarController

I present a UINavigationController on this UITabBarController with a modal style of .overFullScreen

I then want to present modally another controller on top of this however, the background color of the second modally presented controller is grey. Even if it's set to another color it will revert to a grey color.

How do I remove this color issue?

CODE

// MARK: - WITHIN TABBARCONTROLLER
fileprivate func presentCreatePostController() {
    let controller = CreatePostController()
    let navigationController = UINavigationController(rootViewController: controller)
    navigationController.navigationBar.configureAppearance()
    navigationController.modalPresentationStyle = .overFullScreen
    navigationController.navigationBar.isTranslucent = true
    selectedViewController?.present(navigationController, animated: true)
}

// MARK: - WITHIN CREATEPOSTCONTROLLER
func uploadMedia() {
    print("UPLOAD IMAGE BUTTON TAPPED")
    PermissionManager.shared.requestPhotoLibraryPermission()
    let navigationController = UINavigationController(rootViewController: ControllerProvider.mediaPickerController)
    navigationController.modalPresentationStyle = .popover
    navigationController.definesPresentationContext = true
    let rootViewController: UIViewController = (UIApplication.shared.windows.last?.rootViewController)!
    self.view.endEditing(true)
    rootViewController.present(navigationController, animated: true, completion: nil)
}


问:
How to disable HTTP Multiplexing in a Netty Client
I have a Netty HttpClient that is created using the code mentioned below. I wish to disable HTTP2.0 connection multiplexing for this client. How can this be achieved ?</p>
```<code>public HttpClient getHttpClient(Configuration config,
                                               ConnectionProvider connectionProvider) {

    HttpClient httpClient = HttpClient
            .create(connectionProvider)
            .responseTimeout(Duration.ofMillis(config.getGlobalResponseTimeout()))
            .tcpConfiguration(tcpClient -> {
              /**
               * Create a simple LoopResources to provide automatically for EventLoopGroup and Channel factories
               * Params:
               * prefix – the event loop thread name prefix selectCount – number of selector threads workerCount – number of worker threads daemon – should the thread be released on jvm shutdown
               * Returns:
               * a new LoopResources to provide automatically for EventLoopGroup and Channel factories
               */
              LoopResources loopResources = LoopResources.create("webClient-event-loop",
                      config.getSelectorThreadCount(), config.getWorkerThreadCount(), Boolean.TRUE);
              tcpClient.runOn(loopResources);
              tcpClient.doOnConnected(conn -> conn
                      .addHandler(new ReadTimeoutHandler(config.getGlobalReadTimeout(), TimeUnit.MILLISECONDS))
                      .addHandler(new WriteTimeoutHandler(config.getGlobalWriteTimeout(), TimeUnit.MILLISECONDS)));
              tcpClient
                      .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getGlobalConnectionTimeout())
                      .option(ChannelOption.TCP_NODELAY, true);

              return tcpClient;
            });
    return httpClient;
</code>```

Body:
I have a Netty HttpClient that is created using the code mentioned below. I wish to disable HTTP2.0 connection multiplexing for this client. How can this be achieved ?

public HttpClient getHttpClient(Configuration config,
                                               ConnectionProvider connectionProvider) {

    HttpClient httpClient = HttpClient
            .create(connectionProvider)
            .responseTimeout(Duration.ofMillis(config.getGlobalResponseTimeout()))
            .tcpConfiguration(tcpClient -> {
              /**
               * Create a simple LoopResources to provide automatically for EventLoopGroup and Channel factories
               * Params:
               * prefix – the event loop thread name prefix selectCount – number of selector threads workerCount – number of worker threads daemon – should the thread be released on jvm shutdown
               * Returns:
               * a new LoopResources to provide automatically for EventLoopGroup and Channel factories
               */
              LoopResources loopResources = LoopResources.create("webClient-event-loop",
                      config.getSelectorThreadCount(), config.getWorkerThreadCount(), Boolean.TRUE);
              tcpClient.runOn(loopResources);
              tcpClient.doOnConnected(conn -> conn
                      .addHandler(new ReadTimeoutHandler(config.getGlobalReadTimeout(), TimeUnit.MILLISECONDS))
                      .addHandler(new WriteTimeoutHandler(config.getGlobalWriteTimeout(), TimeUnit.MILLISECONDS)));
              tcpClient
                      .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getGlobalConnectionTimeout())
                      .option(ChannelOption.TCP_NODELAY, true);

              return tcpClient;
            });
    return httpClient;


问:
SQL Server service virtual accounts permissions
SQL Server service accounts are virtual accounts as MSSQL$InstanceName. When a SQL Server instance uses a directory to write data it is necessary that the virtual account has permissions to write in the directory.

Nevertheless, I have a server in which an instance is using a directory without, apparently, having the required permissions on it, altough there are two groups with full permissions: Administrators and System.

How is it possible that the virtual service account writes in the directory? Is a virtual account able to write in any directory in the server?


问:
How many IAP can an app apply in AppStore, Google Play and Amazon Store?
We've apply about 900+ IAP for our app.
I wonder is there a limit for the amount of IAP?</p>


问:
Change text color with a chosen one if the Text Widget is covered by another Widget (BlendMode, Flutter)
I would like to make the text grey (it is the default color of the text widget) when the Waves DO NOT covers it. When the Waves covers it then i want the text to be black.

The better result i can achieve is this one, shown in the image. It isn't what i want though, since the color is purple when the waves are covering the text, i want it to be black. Can someone explain me what i am missing?

This is basically a stack where at the bottom i have the Waves (CustomPainter and Canvas) and at the top i have the Text widget. Note that the Waves are moving, it's an animation.

```<code>BlendMask(
          blendMode: BlendMode.difference,
           child: Text(
               'Obiettivo già raggiunto'
                   textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.grey[600],
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      )
</code>```

I got the BlendMask widget from here.

Body:
I would like to make the text grey (it is the default color of the text widget) when the Waves DO NOT covers it. When the Waves covers it then i want the text to be black.

The better result i can achieve is this one, shown in the image. It isn't what i want though, since the color is purple when the waves are covering the text, i want it to be black. Can someone explain me what i am missing?

This is basically a stack where at the bottom i have the Waves (CustomPainter and Canvas) and at the top i have the Text widget. Note that the Waves are moving, it's an animation.

BlendMask(
          blendMode: BlendMode.difference,
           child: Text(
               'Obiettivo già raggiunto'
                   textAlign: TextAlign.center,
                          style: TextStyle(
                            fontSize: 16,
                            color: Colors.grey[600],
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      )

I got the BlendMask widget from here.


问:
Management of PHP/Composer for all SSH User on Plesk ( Ubuntu Server )
I had this situation:

Root User with SSH key for login

One user for each domain with SSH enable (/bin/bash) with different groups ( one for each domain )

What i want to do:

Have different PHP version (CLI) for each user

Use globally installed packages (such as Composer) with each Plesk SSH user

Understand, if I should add plesk users to the "sudoers" group so that I can run su- and have access to everything ( now, I can't, because Root haven't a password )

The problems are:

I don't know how ( and if I can ) create a global .bashrc for store for example the alias for Composer, NVM etc...

if I change the PHP version with which the session starts (for example 8.0), pointing directly to the Plesk bin (for example 8.1), Composer continues to use the old one (8.0)

Composer give me an error when i start it ( file_put_contents ... Permission denied )

I think I'm having problems (and a lot od confusion) regarding Plesk SSH user management in Ubuntu.


问:
Hotchocolate GraphQl schema does not support record struct
I have the schema definition below. Which while the server runs without error, the Chilicream IDE reports schema unavailable. The same code works fine if I change record struct to either record or class

Does Hotchocolate not support record struct?

```<code>    public record struct Money(long Cents);
    public class DemoQuery
    {
        public Money GetMoney() => new Money(1);
    }
</code>```

Edit: the workaround without changing the Money type is to map it explicitly like below. But I still like to know why HotChocolate does not support record struct and struct

```<code> services.AddGraphQLServer()
     .BindRuntimeType<Money, LongType>()
     .AddTypeConverter<Money, long>(money => money.Cents)
  ...
</code>```

Body:
I have the schema definition below. Which while the server runs without error, the Chilicream IDE reports schema unavailable. The same code works fine if I change record struct to either record or class

Does Hotchocolate not support record struct?

    public record struct Money(long Cents);
    public class DemoQuery
    {
        public Money GetMoney() => new Money(1);
    }

Edit: the workaround without changing the Money type is to map it explicitly like below. But I still like to know why HotChocolate does not support record struct and struct

 services.AddGraphQLServer()
     .BindRuntimeType<Money, LongType>()
     .AddTypeConverter<Money, long>(money => money.Cents)
  ...


问:
amCharts 5 unable to test demo graphics, error Property 'strokes' does not exist on type 'XYSeries'
enter image description here Good afternoon, I tried to test charts from amcharts 5 in an angular application.

After installing all the libraries, an error is generated Property 'strokes' does not exist on type 'XYSeries' Here is a link to a demo https://www.amcharts.com/demos/highlighting-line-chart-series-on-legend-hover/, I tried to find property descriptions on the Internet, but nothing was said about strokes, maybe someone encountered this problem?


问:
PDF File Not Launching on WKWEbView in iOS Swift
I have downloaded pdf file from the Webservices and downloaded into Document Directory as shown below

file:///Users/iOS/Library/Developer/CoreSimulator/Devices/C4003255-3946-4AD1-FEFG-8B4D6EE70F65/data/Containers/Data/Application/S61AZ-051B-40AB-B7A1-B7FD37A2D3C3/Documents/Sample.pdf

While launching this path on WKWebView in iOS Simulator then it is working like pdf file showing all pages but
While Launching this path in iOS Devices then im facing the issue is: "The operation couldn’t be completed. Operation not permitted".

How to fix this issue in iOS devices ?

is there any permission have to provide to devices ?

please fix this issue


问:
Accessing folder on external drive via apache 2 symlink returns 403 error
I have read many posts on the subject but can not figure how to solve error 403 following apache 2 symlink.

I am working with Laradock on Mac with Laravel.

So for this test, I simply have a folder on an external drive containing an image:

```<code>/Volumes/TravelMate/video/logo_UC.png
</code>```

In the paulgodard project in Laravel, the blade php page is supposed to display the logo but instead returns error 403 "forbidden".

```<code><img src="/video/logo_UC.png" alt="logo" style="max-width: 240px;">
</code>```

In the apache conf file for the paulgodard project, I have the defined the alias as follow:

```<code><VirtualHost *:80>

  ServerName paulgodard.test
  DocumentRoot /var/www/paulgodard
  Options Indexes FollowSymLinks

  <Directory "/var/www/paulgodard">
    AllowOverride All
    <IfVersion < 2.4>
      Allow from all
    </IfVersion>
    <IfVersion >= 2.4>
      Require all granted
    </IfVersion>
  </Directory>

  Alias "/video" "/Volumes/TravelMate/video"
  <Directory "/Volumes/TravelMate/video">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
  </Directory>

</VirtualHost>
</code>```

Please note that if I do not have the alias defined, the error is 404 "not found"... so I presume the alias correctly creates the symlink.

What should I do in terminal to allow Apache 2 to read the logo?

Body:
I have read many posts on the subject but can not figure how to solve error 403 following apache 2 symlink.

I am working with Laradock on Mac with Laravel.

So for this test, I simply have a folder on an external drive containing an image:

/Volumes/TravelMate/video/logo_UC.png

In the paulgodard project in Laravel, the blade php page is supposed to display the logo but instead returns error 403 "forbidden".

In the apache conf file for the paulgodard project, I have the defined the alias as follow:

<VirtualHost *:80>

  ServerName paulgodard.test
  DocumentRoot /var/www/paulgodard
  Options Indexes FollowSymLinks

  <Directory "/var/www/paulgodard">
    AllowOverride All
    <IfVersion < 2.4>
      Allow from all
    </IfVersion>
    <IfVersion >= 2.4>
      Require all granted
    </IfVersion>
  </Directory>

  Alias "/video" "/Volumes/TravelMate/video"
  <Directory "/Volumes/TravelMate/video">
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
  </Directory>

</VirtualHost>

Please note that if I do not have the alias defined, the error is 404 "not found"... so I presume the alias correctly creates the symlink.

What should I do in terminal to allow Apache 2 to read the logo?


问:
Modify each string property in flat object, complex object, list, etc
I need to write a generic method that will take any object, loop over its values, and, for each string, modify it (HtmlEncode it in this case).
(this need to execute on all objects submitted to my.net 4.7 API controllers)

So I created an ActionFilterAttribute, and added it to my global filters, and it works fine on "flat" objects.

However, the object can be something like an object with an IList member (each of which will need to be modified) or a nested object/s with its own string properties.

Anyone done anything like this?  Got like 10 commented out failed experiments.  lol

```<code>public override void OnActionExecuting(HttpActionContext actionContext)
{
    // Decode strings from PUT or POST requests
    if (actionContext.Request.Method.ToString() == WebRequestMethods.Http.Post
        || actionContext.Request.Method.ToString() == WebRequestMethods.Http.Put)
    {
        // For each of the items in the PUT/POST
        foreach (var item in actionContext.ActionArguments.Values)
        {
            try
            {
                var type = item.GetType();

                // For each property of this object, html decode it if it is of type string
                foreach (PropertyInfo propertyInfo in type.GetProperties())
                {
                    var prop = propertyInfo.GetValue(item);
                    if (prop is string str)
                    {
                        propertyInfo.SetValue(item, WebUtility.HtmlEncode(str));
                    }
                }
            }
            catch (Exception)
            {
                // ignored
            }
        }
    }
    base.OnActionExecuting(actionContext);
}
</code>```

UPDATE:

Currently testing this:
update: no good...an Int will be identified as Object

```<code> public class HttpStringDecodeFilter : ActionFilterAttribute
    {
        private void HtmlEncodeAllStringsInObject(Object obj)
        {
            var type = obj.GetType();
            var properties = type.GetProperties();
            foreach (var property in properties)
            {
                var propValue = property.GetValue(obj);
                if (property.PropertyType.IsAssignableFrom(typeof(string)))
                {
                    property.SetValue(obj, WebUtility.HtmlEncode(propValue?.ToString()));
                }
                else if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(IList<>))
                {
                    if (propValue is not List<string> list) continue;
                    for (var i = 0; i < list.Count; i++)
                    {
                        list[i] = WebUtility.HtmlEncode(list[i]);
                    }
                    property.SetValue(obj, list);
                } else
                {
                    var typeCode = Type.GetTypeCode(property.PropertyType);
                    if (typeCode.Equals(TypeCode.Object))
                    {
                        HtmlEncodeAllStringsInObject(property);
                    }
                }
            }
        }
</code>```

Body:
I need to write a generic method that will take any object, loop over its values, and, for each string, modify it (HtmlEncode it in this case).
(this need to execute on all objects submitted to my.net 4.7 API controllers)

So I created an ActionFilterAttribute, and added it to my global filters, and it works fine on "flat" objects.

However, the object can be something like an object with an IList member (each of which will need to be modified) or a nested object/s with its own string properties.

Anyone done anything like this?  Got like 10 commented out failed experiments.  lol

public override void OnActionExecuting(HttpActionContext actionContext)
{
    // Decode strings from PUT or POST requests
    if (actionContext.Request.Method.ToString() == WebRequestMethods.Http.Post
        || actionContext.Request.Method.ToString() == WebRequestMethods.Http.Put)
    {
        // For each of the items in the PUT/POST
        foreach (var item in actionContext.ActionArguments.Values)
        {
            try
            {
                var type = item.GetType();

                // For each property of this object, html decode it if it is of type string
                foreach (PropertyInfo propertyInfo in type.GetProperties())
                {
                    var prop = propertyInfo.GetValue(item);
                    if (prop is string str)
                    {
                        propertyInfo.SetValue(item, WebUtility.HtmlEncode(str));
                    }
                }
            }
            catch (Exception)
            {
                // ignored
            }
        }
    }
    base.OnActionExecuting(actionContext);
}

UPDATE:

Currently testing this:
update: no good...an Int will be identified as Object

 public class HttpStringDecodeFilter : ActionFilterAttribute
    {
        private void HtmlEncodeAllStringsInObject(Object obj)
        {
            var type = obj.GetType();
            var properties = type.GetProperties();
            foreach (var property in properties)
            {
                var propValue = property.GetValue(obj);
                if (property.PropertyType.IsAssignableFrom(typeof(string)))
                {
                    property.SetValue(obj, WebUtility.HtmlEncode(propValue?.ToString()));
                }
                else if (property.PropertyType.IsGenericType && property.PropertyType.GetGenericTypeDefinition() == typeof(IList<>))
                {
                    if (propValue is not List<string> list) continue;
                    for (var i = 0; i < list.Count; i++)
                    {
                        list[i] = WebUtility.HtmlEncode(list[i]);
                    }
                    property.SetValue(obj, list);
                } else
                {
                    var typeCode = Type.GetTypeCode(property.PropertyType);
                    if (typeCode.Equals(TypeCode.Object))
                    {
                        HtmlEncodeAllStringsInObject(property);
                    }
                }
            }
        }


问:
how do I track total revenue and revenue by category through universal analytics?
I want to track total revenue of products ordered if product is of X category.

I tried adding extra parameter to action field

'actionField': {
'id': '${fn:escapeXml(orderData.code)}', // Document number
'revenue': '${orderData.totalPrice.value}', // Total transaction value (excl. tax)
'tax': '${orderData.totalTax.value}',
'xcategoryproductrevenue': '${orderData.totalTax.value}',
}


问:
In flutter app,how do I fetch setting values from Android system settings?Such as currently default sms app's name or value
As title,in flutter app,how do I read/fetch setting values from Android system settings?Such as currently default sms app's name or value,is there any Flutter plugins can do this?Till now,I couldn't find any similar solutions....please help,many thanks.

As below I want to fetch the name of default sms app via dart code,how do I finish it?

enter image description here

I hope my flutter app can fetch the name of default sms app.


问:
Can't add Categories to Listings for Jobs in .Net 6
So i'm trying to add a Listing for Job, but cannot add Categories, the other things are ok (Id,Name,Description and Date of Creation) but i can't figure out how to make Category if not exists and i need help

ListingController.cs

```<code>           [HttpPost]
            [Authorize(Roles = "Company")]
            public async Task<ActionResult> List(ListingDto ldt)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest();
                }
                var user = await _userManager.GetUserAsync(User);
                var listingToAdd = new Listing()
                {
                        Name = ldt.Name,
                        Description = ldt.Description,
                        CreatedDate = DateTime.Now,
                        Author = user
                };
                var flag = 0;

                // Not working
                //foreach (string categoryToAdd in ldt.Categories)
                //{
                //  foreach(Category existingCategories in _dbContext.Categories)
                //    {
                //        if(existingCategories.Name == categoryToAdd)
                //        {
                //           existingCategories.Listings.Add(listingToAdd);
                //            flag = 1;
                //        }
                //    }
                //}
                // Not working

                _dbContext.Listings.Add(listingToAdd);

                _dbContext.SaveChanges();
                return Ok(listingToAdd);
</code>```

ListingModel.cs

```<code>public class Listing
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime CreatedDate { get; set; }
        public string? Description   { get; set; }
        // I don't know if here the IList<String> needs to be IList<Category>
        public IList<String> Categories { get; set; }
        public User Author { get; set; }

    }
</code>```

CategoryModel.cs

```<code>    public class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Listing> Listings { get; set;}
    }
</code>```

The logic i want to implement is: if i don't have a Category.Name , to create a new category with the last category id + 1 , the name , and add the listing, if the category exists i want just to add the Listing to the colection of the existing category

Body:
So i'm trying to add a Listing for Job, but cannot add Categories, the other things are ok (Id,Name,Description and Date of Creation) but i can't figure out how to make Category if not exists and i need help

ListingController.cs

           [HttpPost]
            [Authorize(Roles = "Company")]
            public async Task<ActionResult> List(ListingDto ldt)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest();
                }
                var user = await _userManager.GetUserAsync(User);
                var listingToAdd = new Listing()
                {
                        Name = ldt.Name,
                        Description = ldt.Description,
                        CreatedDate = DateTime.Now,
                        Author = user
                };
                var flag = 0;

                // Not working
                //foreach (string categoryToAdd in ldt.Categories)
                //{
                //  foreach(Category existingCategories in _dbContext.Categories)
                //    {
                //        if(existingCategories.Name == categoryToAdd)
                //        {
                //           existingCategories.Listings.Add(listingToAdd);
                //            flag = 1;
                //        }
                //    }
                //}
                // Not working

                _dbContext.Listings.Add(listingToAdd);

                _dbContext.SaveChanges();
                return Ok(listingToAdd);

ListingModel.cs

public class Listing
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public DateTime CreatedDate { get; set; }
        public string? Description   { get; set; }
        // I don't know if here the IList<String> needs to be IList<Category>
        public IList<String> Categories { get; set; }
        public User Author { get; set; }

    }

CategoryModel.cs

    public class Category
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Listing> Listings { get; set;}
    }

The logic i want to implement is: if i don't have a Category.Name , to create a new category with the last category id + 1 , the name , and add the listing, if the category exists i want just to add the Listing to the colection of the existing category


问:
Get predictions made when training the model
I would like to know if it's possible to get the predictions made when training the dataset (using .fit from sklearn). I've already use predict in order to get the predictions for the test dataset.

I except to get te predictions for the whole dataset not just the test set.


问:
How to import node module into a custom script in react public folder
In my React project, I must create a script in the public folder,
But when I try to import a node module in this script:

```<code>import someVariable from '@module/someVariable';
</code>```

I'm having this error:

```<code>Cannot use import statement outside a module
</code>```

Body:
In my React project, I must create a script in the public folder,
But when I try to import a node module in this script:

import someVariable from '@module/someVariable';

I'm having this error:

Cannot use import statement outside a module


问:
Send static image when video is muted in pjSIP Android
I am developing an application using pjSIP JNI APIs. In this application, I need to cater a use case when video is muted (don't use Camera2), but need to send some still image to peer.
I did not find any pjSIP JNI interface through which I can do it.
Any help is greatly appreciated.

pjSIP android JNI APIs & stack overflow


问:
Panda how to overwrite new value on previous value?
I have the following code :

```<code># Append columns to an empty DataFrame.
    self.df = pd.DataFrame(columns = ["ID", "Features"],index=['index1'])
</code>```
```<code>
tracking_id = output[4]
print(tracking_id in set(self.df['ID']))
if tracking_id in self.df['ID'] :

      df2 = pd.DataFrame([[tracking_id], features])
      self.df.update(df2)
      print(self.df)

else :
     self.df = self.df.append({'ID' : tracking_id, 'Features' : features}, ignore_index = True)
</code>```

In this code, first I check whether an element with the same İD is available or not. Is it is available, previous feature value should be updated with the new one. Actually it works but not correctly.

My output is :

```<code>    ID                                           Features
0  NaN                                                NaN
1  1.0  [[1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 50.0...
2  4.0  [[0.0, 0.0, 0.0, 1.0, 89.0, 15.0, 0.0, 0.0, 10...
3  4.0  [[70.0, 41.0, 17.0, 41.0, 4.0, 0.0, 0.0, 0.0, ...
4  4.0  [[42.0, 18.0, 16.0, 14.0, 2.0, 0.0, 0.0, 0.0, ...
5  6.0  [[3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 8.0, 59.0...
6  6.0  [[0.0, 6.0, 7.0, 9.0, 12.0, 3.0, 0.0, 0.0, 51....
</code>```

As you can see, the same value is appended like absent İD on the list. However sometimes it is not added to the list just is overwrited to previous ones. How can I solve this problem ?

Body:
I have the following code :

# Append columns to an empty DataFrame.
    self.df = pd.DataFrame(columns = ["ID", "Features"],index=['index1'])

tracking_id = output[4]
print(tracking_id in set(self.df['ID']))
if tracking_id in self.df['ID'] :

      df2 = pd.DataFrame([[tracking_id], features])
      self.df.update(df2)
      print(self.df)

else :
     self.df = self.df.append({'ID' : tracking_id, 'Features' : features}, ignore_index = True)

In this code, first I check whether an element with the same İD is available or not. Is it is available, previous feature value should be updated with the new one. Actually it works but not correctly.

My output is :

    ID                                           Features
0  NaN                                                NaN
1  1.0  [[1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 50.0...
2  4.0  [[0.0, 0.0, 0.0, 1.0, 89.0, 15.0, 0.0, 0.0, 10...
3  4.0  [[70.0, 41.0, 17.0, 41.0, 4.0, 0.0, 0.0, 0.0, ...
4  4.0  [[42.0, 18.0, 16.0, 14.0, 2.0, 0.0, 0.0, 0.0, ...
5  6.0  [[3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 8.0, 59.0...
6  6.0  [[0.0, 6.0, 7.0, 9.0, 12.0, 3.0, 0.0, 0.0, 51....

As you can see, the same value is appended like absent İD on the list. However sometimes it is not added to the list just is overwrited to previous ones. How can I solve this problem ?