问:
Create a linearly decreasing value depending on time (in a function)
I have a stochastic SIR model that has the variables time T, contact rate beta, recovery rate gamma, and a number of susceptible n plus a number of infectious m. And I would like to find a way to get a time-varying beta value that linearly decreases depending on time over some period.

I previously got help from one of you here on how to change my beta value to two different values depending on the time, which worked perfectly. But now I also want to linearly decrease my beta between some time period [t1,t2] via reducing the beta with 1% for each step. This is my code:

```<code>rSIR <- function(T, beta, gamma, n, m) {
  t <- 0
  x <- n # Susceptibles
  y <- m # Infectious

  # Possible events
  eventLevels <- c("S->I","I->R")
  # Initialize result
  events <- data.frame(t=t,x=x,y=y,event=NA)
  # Loop
  while (t < T & (y>0)) {
    beta <- if(t <= 10) {b} else if(t <= 11) {b*0.99} else if(t <= 12) {b*0.98} else if(t <= 13) {b*0.97} else if(t <= 14) {b*0.96} else if(t > 14){b*0.8}
    print(beta)
    # Draw
    wait <- rexp(2,c("S->I"=beta*x*y,"I->R"=gamma*y))
    # Which event occurs first
    i <- which.min(wait)
    # Advance time
    t <- t+wait[i]
    # Update population
    if (eventLevels[i] == "S->I") {x <- x-1; y <- y+1}
    if (eventLevels[i] == "I->R") {y <- y-1}
    # Store results
    events <- rbind(events,c(t,x,y,i))
  }
  events$event<- factor(eventLevels[events$event], levels=eventLevels)
  return(events)
}
</code>```

As you can see I have made my beta decrease linearly with 1% for each time step between the times t1=11 and t2=14 by multiplying the beta value with 0.99,0.98,0.97,0.96 for each step respectively (row 11 counting from the top). However, this becomes quite extensive if I want it to decrease linearly for a longer period. And hence I wonder if you can somehow get a function for this instead of having to write it step by step?

I wrote a simple loop that decreased my beta value for each step, see below, but couldn't find a way to get this into my rSIR function. Maybe someone here knows if it is possible to do so? Thanks in advance!

```<code>beta_value <- function(beta,t) {
  for (i in 1:t) {
    beta = beta*0.99
    print(beta)
  }
}
</code>```

Body:
I have a stochastic SIR model that has the variables time T, contact rate beta, recovery rate gamma, and a number of susceptible n plus a number of infectious m. And I would like to find a way to get a time-varying beta value that linearly decreases depending on time over some period.

I previously got help from one of you here on how to change my beta value to two different values depending on the time, which worked perfectly. But now I also want to linearly decrease my beta between some time period [t1,t2] via reducing the beta with 1% for each step. This is my code:

rSIR <- function(T, beta, gamma, n, m) {
  t <- 0
  x <- n # Susceptibles
  y <- m # Infectious

  # Possible events
  eventLevels <- c("S->I","I->R")
  # Initialize result
  events <- data.frame(t=t,x=x,y=y,event=NA)
  # Loop
  while (t < T & (y>0)) {
    beta <- if(t <= 10) {b} else if(t <= 11) {b*0.99} else if(t <= 12) {b*0.98} else if(t <= 13) {b*0.97} else if(t <= 14) {b*0.96} else if(t > 14){b*0.8}
    print(beta)
    # Draw
    wait <- rexp(2,c("S->I"=beta*x*y,"I->R"=gamma*y))
    # Which event occurs first
    i <- which.min(wait)
    # Advance time
    t <- t+wait[i]
    # Update population
    if (eventLevels[i] == "S->I") {x <- x-1; y <- y+1}
    if (eventLevels[i] == "I->R") {y <- y-1}
    # Store results
    events <- rbind(events,c(t,x,y,i))
  }
  events$event<- factor(eventLevels[events$event], levels=eventLevels)
  return(events)
}

As you can see I have made my beta decrease linearly with 1% for each time step between the times t1=11 and t2=14 by multiplying the beta value with 0.99,0.98,0.97,0.96 for each step respectively (row 11 counting from the top). However, this becomes quite extensive if I want it to decrease linearly for a longer period. And hence I wonder if you can somehow get a function for this instead of having to write it step by step?

I wrote a simple loop that decreased my beta value for each step, see below, but couldn't find a way to get this into my rSIR function. Maybe someone here knows if it is possible to do so? Thanks in advance!

beta_value <- function(beta,t) {
  for (i in 1:t) {
    beta = beta*0.99
    print(beta)
  }
}


来源: stackexchange

问:
Firebase Dynamic Links pending data on receiving is null
As the title describes when my open through dynamic link the pendingDynamicLink Data is null in onsuccesslistener. The intent does have the link but the pendingdynamicLinkdata is always null.
Posting the code stub for reference here:

```<code>Firebase.dynamicLinks
            .getDynamicLink(intent)
            .addOnSuccessListener(this) { pendingDynamicLinkData: PendingDynamicLinkData? ->
                // Get deep link from result (may be null if no link is found)
                var deepLink: Uri? = null
                if (pendingDynamicLinkData != null) {
                    deepLink = pendingDynamicLinkData.link
                }

            }
            .addOnFailureListener(this) { e -> Log.w("TAG", "getDynamicLink:onFailure", e) }
</code>```

the manifest intent filter for my activity.

```<code><intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data
                    android:host="myapp.page.link"
                    android:scheme="https"/>
            </intent-filter>
</code>```

For info my activity is indeed the MainActivity which is launched on app startup.

Browsing through the internet i've seen that short link usually doesn't work on android. I am using the short link since I am receiving short link on iOS.

For some reason whatever i try onSuccessListener always returns null in lambda expression.

ContentLicense: CC BY-SA 4.0

Body:
As the title describes when my open through dynamic link the pendingDynamicLink Data is null in onsuccesslistener. The intent does have the link but the pendingdynamicLinkdata is always null.
Posting the code stub for reference here:

Firebase.dynamicLinks
            .getDynamicLink(intent)
            .addOnSuccessListener(this) { pendingDynamicLinkData: PendingDynamicLinkData? ->
                // Get deep link from result (may be null if no link is found)
                var deepLink: Uri? = null
                if (pendingDynamicLinkData != null) {
                    deepLink = pendingDynamicLinkData.link
                }

            }
            .addOnFailureListener(this) { e -> Log.w("TAG", "getDynamicLink:onFailure", e) }

the manifest intent filter for my activity.

<intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data
                    android:host="myapp.page.link"
                    android:scheme="https"/>
            </intent-filter>

For info my activity is indeed the MainActivity which is launched on app startup.

Browsing through the internet i've seen that short link usually doesn't work on android. I am using the short link since I am receiving short link on iOS.

For some reason whatever i try onSuccessListener always returns null in lambda expression.


问:
How to plot multiple time series using the Dataset component from Echarts taking data from a relational sql query
I'm looking for your support in order to know how to plot multiple time-series in a line-chart from Echarts. I read the documentation but i couldn't find a proper way to do it. Let me explain it:

I have this simple SQL query (Postgres)

SELECT DAY, CATEGORY, INDEX FROM schema.table t WHERE DATE >= 'start_time' and DATE < 'end_time' ORDER BY 1,2

The field CATEGORY has 5 unique values:

```<code>`category_1
category_2
category_3
category_4
category_5
`
</code>```

DAY is a date field who takes dates from 'start_time" to "end_time" for each Category.
INDEX is a numeric value.

Here is an example how the table looks like for three days (end_time - start_time):

(https://i.stack.imgur.com/ICkQZ.png)

So, as you can see it has 5 time-series. Here is a unique time-series for instance

(https://i.stack.imgur.com/KcOQH.png)

So, i would like to plot these 5 time-series in a line-chart from Echarts library. Here is an example how should it looks like (it's done with another tool)

(https://i.stack.imgur.com/KvTOw.png)

The Echart documentation recommend to use the Dataset component but I've been doing a lot of  tests with no success! :(

'''

```<code>dataset: {
        dimensions:   // How should i define dimension?
        source:       // How should i define the source for the 5 categories?
}

series: [
{
          type: 'line',
          encode: { x: 'day', y: 'index' } //How should i split index for each category?
}
]
</code>```

'''

Could you please help with these items?:

How should i define the Dataset component for the 5 categories (time-series)?

How should i define "series" and "encode" for the 5 categories?

Thanks in advance!!

Body:
I'm looking for your support in order to know how to plot multiple time-series in a line-chart from Echarts. I read the documentation but i couldn't find a proper way to do it. Let me explain it:

I have this simple SQL query (Postgres)

SELECT DAY, CATEGORY, INDEX FROM schema.table t WHERE DATE >= 'start_time' and DATE < 'end_time' ORDER BY 1,2

The field CATEGORY has 5 unique values:

`category_1
category_2
category_3
category_4
category_5
`

DAY is a date field who takes dates from 'start_time" to "end_time" for each Category.
INDEX is a numeric value.

Here is an example how the table looks like for three days (end_time - start_time):

(https://i.stack.imgur.com/ICkQZ.png)

So, as you can see it has 5 time-series. Here is a unique time-series for instance

(https://i.stack.imgur.com/KcOQH.png)

So, i would like to plot these 5 time-series in a line-chart from Echarts library. Here is an example how should it looks like (it's done with another tool)

(https://i.stack.imgur.com/KvTOw.png)

The Echart documentation recommend to use the Dataset component but I've been doing a lot of  tests with no success! :(

'''

dataset: {
        dimensions:   // How should i define dimension?
        source:       // How should i define the source for the 5 categories?
}

series: [
{
          type: 'line',
          encode: { x: 'day', y: 'index' } //How should i split index for each category?
}
]

'''

Could you please help with these items?:

How should i define the Dataset component for the 5 categories (time-series)?

How should i define "series" and "encode" for the 5 categories?

Thanks in advance!!


问:
Javascript OOP : Difference between this 2 objects
I'm trying to understand better OOP. Anyone can explain what is the difference between this two object below? How javascript can display the both are varible of type object, if both seems completely different.</p>
```<code>class Dog {
  constructor(name) {
    this.name = name;
  }

  bark() {
    console.log(`Woof! My name is ${this.name}`);
  }
}

const fido = new Dog('Fido');
fido.bark();

console.log(typeof fido)

let dog = { name : "Baby"};
console.log(typeof dog)
</code>```

Body:
I'm trying to understand better OOP. Anyone can explain what is the difference between this two object below? How javascript can display the both are varible of type object, if both seems completely different.

class Dog {
  constructor(name) {
    this.name = name;
  }

  bark() {
    console.log(`Woof! My name is ${this.name}`);
  }
}

const fido = new Dog('Fido');
fido.bark();

console.log(typeof fido)

let dog = { name : "Baby"};
console.log(typeof dog)


问:
How to make sure text inside a column is fully visible using Playwright?
I have a table in my web page. Let us assume that one of the columns has a very long text, and the column is at its default width.

```<code>expect(self.page.locator('text=ABCDEFGHIJKLMNOPQRSTUVWXYZ')).\
to_be_visible(timeout=20 *1000)
</code>```

The code passes, as Playwright can find the text in the HTML.

How can I make sure that a human can see all the letters and that nothing is hidden?

Body:
I have a table in my web page. Let us assume that one of the columns has a very long text, and the column is at its default width.

expect(self.page.locator('text=ABCDEFGHIJKLMNOPQRSTUVWXYZ')).\
to_be_visible(timeout=20 *1000)

The code passes, as Playwright can find the text in the HTML.

How can I make sure that a human can see all the letters and that nothing is hidden?


问:
How can i solve this sql error to delete duplicate data
```<code>with CTE as
(select s.*,row_number() over(partition by store_id order by store_id ) as rank from stores s)
DELETE FROM cte where cte.rank>1;
</code>```

i am trying to delete row with multiple store_id by the error : missing select keyword is the output

delete duplicate data

Body:
with CTE as
(select s.*,row_number() over(partition by store_id order by store_id ) as rank from stores s)
DELETE FROM cte where cte.rank>1;

i am trying to delete row with multiple store_id by the error : missing select keyword is the output

delete duplicate data


问:
How to ensure that the codes of the same plugin are called in the same thread gracefully in a plugin system?

Background

I'm designing a plugin system, in which plugins can register event listeners and commands in their onEnable() method. We inevitably encounter the question of whether the thread of the callback onEnable() method is the same thread as the thread of the listener or command method registered by the callback plugin.

Question

Because plugin developers may not write thread-safe codes, which may cause unexpected results, we can design a mechanism so that all codes of the same plugin will be called in the same thread called its main thread. Every time the plugin system want to call a plugin code, it can invoke a method like this:

application.getTaskManager().submit(
    Task.builder()
        .plugin(plugin)
        .action(context -> {
             // ...
             plugin.onEnable();
             // ...
         })
        .build()
);
```

How to implement it gracefully?

Thinkings

Consider 3 types of solutions:

Specialized main thread: Assign a specialized thread to each plugin.

Reusable main thread: One thread corresponds to multiple (or single) plugins, at the same time threads can be used to execute other asynchronous tasks. It can save some resources, but it may cause its plugin callbacks to be delayed, which may come to results that are not in line with expectations.

Dynamic main thread: First assign the same thread to all plug-ins and dynamically decide whether the code of a time-consuming plugin should be called on a special main thread or several time-saving plugins in the same main thread based on the runtime data.

Obviously, the last solution is probably the best, but it need to clear the JVM thread cache when we adjust the correspondence between main threads and plugins. How to clear the JVM thread cache?

Body:
Background

I'm designing a plugin system, in which plugins can register event listeners and commands in their onEnable() method. We inevitably encounter the question of whether the thread of the callback onEnable() method is the same thread as the thread of the listener or command method registered by the callback plugin.

Question

Because plugin developers may not write thread-safe codes, which may cause unexpected results, we can design a mechanism so that all codes of the same plugin will be called in the same thread called its main thread. Every time the plugin system want to call a plugin code, it can invoke a method like this:

application.getTaskManager().submit(
    Task.builder()
        .plugin(plugin)
        .action(context -> {
             // ...
             plugin.onEnable();
             // ...
         })
        .build()
);

How to implement it gracefully?

Thinkings

Consider 3 types of solutions:

Specialized main thread: Assign a specialized thread to each plugin.

Reusable main thread: One thread corresponds to multiple (or single) plugins, at the same time threads can be used to execute other asynchronous tasks. It can save some resources, but it may cause its plugin callbacks to be delayed, which may come to results that are not in line with expectations.

Dynamic main thread: First assign the same thread to all plug-ins and dynamically decide whether the code of a time-consuming plugin should be called on a special main thread or several time-saving plugins in the same main thread based on the runtime data.

Obviously, the last solution is probably the best, but it need to clear the JVM thread cache when we adjust the correspondence between main threads and plugins. How to clear the JVM thread cache?


问:
How to set custom failure handler in flink elasticsearch connector?
I want to handle events on failure in flink elasticserach connector to send events another place.

I saw relevant docs on version 1.14 but that custom failure handler is removed since version 1.15 in docs.

And I'm using flink 1.15. Can I handle failure in flink elasticsearch connector 1.15 using custom failure handler?


问:
Deploy a php application on aws lightsail
I try to deploy my php application (https://github.com/Ulysssssssssssse/RGAPP) on aws lightsail but i have issues connecting my database.
I use this script that i found and tried to adapt to my case but it doesn't work.

```<code>cd /opt/bitnami/apache2/htdocs
rm -rf \*

git clone https://github.com/Ulysssssssssssse/RGAPP

chown bitnami:daemon RGAPP/config.php
chmod 666 config.php

cat /home/bitnami/htdocs/RGAPP/isepbike.sql | /opt/bitnami/mariadb/bin/my
sql -u root
</code>```

when I try to connect to my php site it gives me this error:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

So i created a new user for my database with all Privileges with username=lightsail and password=lightsail
and I changed the config.php file and the last instruction of the scritp but I still get the same error

I also tried this to change mariadb parameters it give me the same error

```<code>sudo mysql -u root

USE mysql;
UPDATE user SET plugin = '', password = '' WHERE User = 'root';
FLUSH PRIVILEGES;
</code>```

Body:
I try to deploy my php application (https://github.com/Ulysssssssssssse/RGAPP) on aws lightsail but i have issues connecting my database.
I use this script that i found and tried to adapt to my case but it doesn't work.

cd /opt/bitnami/apache2/htdocs
rm -rf \*

git clone https://github.com/Ulysssssssssssse/RGAPP

chown bitnami:daemon RGAPP/config.php
chmod 666 config.php

cat /home/bitnami/htdocs/RGAPP/isepbike.sql | /opt/bitnami/mariadb/bin/my
sql -u root

when I try to connect to my php site it gives me this error:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

So i created a new user for my database with all Privileges with username=lightsail and password=lightsail
and I changed the config.php file and the last instruction of the scritp but I still get the same error

I also tried this to change mariadb parameters it give me the same error

sudo mysql -u root

USE mysql;
UPDATE user SET plugin = '', password = '' WHERE User = 'root';
FLUSH PRIVILEGES;


问:
Python - A ton of file errors when typing 'pip' in terminal
I have earlier used pip to install cryptography and pygame. I am using VSCODE. I have no idea what has happened, because when I tried to install pyinstaller (pip install pyinstaller) I get a whole lot of file errors (posted under). When I just write pip these also return. What could be wrong and what could be the solution to get pip working again?

Thanks in advance!

```<code>PS C:\Users\Kristian Golin\Documents\GitHub\100-Days-of-Code> pip
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\__main__.py", line 16, in <module>
    from pip._internal import main as _main  # isort:skip # noqa
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_internal\__init__.py", line 40, in <module>
    from pip._internal.cli.autocompletion import autocomplete
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_internal\cli\autocompletion.py", line 8, in <module>
    from pip._internal.cli.main_parser import create_main_parser
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_internal\cli\main_parser.py", line 12, in <module>
    from pip._internal.commands import (
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_internal\commands\__init__.py", line 6, in <module>
    from pip._internal.commands.completion import CompletionCommand
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_internal\commands\completion.py", line 6, in <module>
    from pip._internal.cli.base_command import Command
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_internal\cli\base_command.py", line 23, in <module>
    from pip._internal.index import PackageFinder
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_internal\index.py", line 14, in <module>
    from pip._vendor import html5lib, requests, six
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\html5lib\__init__.py", line 25, in <module>
    from .html5parser import HTMLParser, parse, parseFragment
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\html5lib\html5parser.py", line 8, in <module>
    from . import _tokenizer
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\html5lib\_tokenizer.py", line 16, in <module>
    from ._trie import Trie
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\html5lib\_trie\__init__.py", line 3, in <module>
    from .py import Trie as PyTrie
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\html5lib\_trie\py.py", line 6, in <module>
    from ._base import Trie as ABCTrie
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\html5lib\_trie\_base.py", line 3, in <module>
    from collections import Mapping
ImportError: cannot import name 'Mapping' from 'collections' (C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\collections\__init__.py)

</code>```

I have struggled to find any answers online on people having the same problem. Tried running programs as administrator, restarting computer

Body:
I have earlier used pip to install cryptography and pygame. I am using VSCODE. I have no idea what has happened, because when I tried to install pyinstaller (pip install pyinstaller) I get a whole lot of file errors (posted under). When I just write pip these also return. What could be wrong and what could be the solution to get pip working again?

Thanks in advance!

PS C:\Users\Kristian Golin\Documents\GitHub\100-Days-of-Code> pip
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\__main__.py", line 16, in <module>
    from pip._internal import main as _main  # isort:skip # noqa
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_internal\__init__.py", line 40, in <module>
    from pip._internal.cli.autocompletion import autocomplete
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_internal\cli\autocompletion.py", line 8, in <module>
    from pip._internal.cli.main_parser import create_main_parser
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_internal\cli\main_parser.py", line 12, in <module>
    from pip._internal.commands import (
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_internal\commands\__init__.py", line 6, in <module>
    from pip._internal.commands.completion import CompletionCommand
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_internal\commands\completion.py", line 6, in <module>
    from pip._internal.cli.base_command import Command
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_internal\cli\base_command.py", line 23, in <module>
    from pip._internal.index import PackageFinder
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_internal\index.py", line 14, in <module>
    from pip._vendor import html5lib, requests, six
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\html5lib\__init__.py", line 25, in <module>
    from .html5parser import HTMLParser, parse, parseFragment
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\html5lib\html5parser.py", line 8, in <module>
    from . import _tokenizer
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\html5lib\_tokenizer.py", line 16, in <module>
    from ._trie import Trie
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\html5lib\_trie\__init__.py", line 3, in <module>
    from .py import Trie as PyTrie
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\html5lib\_trie\py.py", line 6, in <module>
    from ._base import Trie as ABCTrie
  File "C:\Users\Kristian Golin\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pip\_vendor\html5lib\_trie\_base.py", line 3, in <module>
    from collections import Mapping
ImportError: cannot import name 'Mapping' from 'collections' (C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.2544.0_x64__qbz5n2kfra8p0\lib\collections\__init__.py)

I have struggled to find any answers online on people having the same problem. Tried running programs as administrator, restarting computer


问:
How to prevent inheritance of static methods?
I have a base class X, which has a static method setDB( $db ), which accepts the database connection to be used by all its instantiated subclasses.

Everything works as expected.

Now I have a class Y, which extends X. When I type its class name (Y:: in this case), my autocompletion shows Y::setDB() as an option. It seems to be inherited from its parent class.

Is there a way to make the static method only available in the base class and not in the child class?


问:
Open Data of user geographical created content
I'm designing an open database in which users can upload geographical data (a sort of Open Street Map). For simplicity below I'll describe an example in which users can upload the position of the zebra crossing for a city.

My database table of the is something like (id_zebra_crossing, latitude, longitude, id_user) in which the id_user is a foreign key to a user table. The whole operations in the database will be accessible throw API.

Now my problems begin because I want to implement:

Interoperability (syntactic, semantic)

FAIR principles

I'm not sure how to design the metadata to implement the FAIR principles. Is this necessary when an open database is designed?


问:
Why does JavaScript use `variable_name: variable_value` in an object when only the variable itself is specified?
```<code>const partId = 10;

const newTask = {
  partId,
  'text': 'baz',
  'date': '2022-03-01'
}

console.log(newTask);
</code>```

partId literally has the value of 10, so I would expect this value to be substituted into newTask, i.e.

```<code>{
  10,
  'text': 'baz',
  'date': '2022-03-01'
}
</code>```

(which would be an invalid object).

Instead my output is:

```<code>{
partId: 10
text: "baz"
date: "2022-03-01"
}
</code>```

So it seems JavaScript will set the 'key' to the variable name when no 'key' is supplied.

Question: Why would this be desired behaviour? Or have I completely misunderstood how this works?

My understanding of coding is it is a discipline where being explicit/avoiding ambiguity is best

In this example it seems JavaScript is purposefully not interpreting code exactly as I have written it

My gut feeling is I would rather get an error, than for JavaScript to "fix" my code for me

NB: I am coming to Javascript from Python - am I holding on to "Explicit is better than implicit." too dearly?

Body:
const partId = 10;

const newTask = {
  partId,
  'text': 'baz',
  'date': '2022-03-01'
}

console.log(newTask);

partId literally has the value of 10, so I would expect this value to be substituted into newTask, i.e.

{
  10,
  'text': 'baz',
  'date': '2022-03-01'
}

(which would be an invalid object).

Instead my output is:

{
partId: 10
text: "baz"
date: "2022-03-01"
}

So it seems JavaScript will set the 'key' to the variable name when no 'key' is supplied.

Question: Why would this be desired behaviour? Or have I completely misunderstood how this works?

My understanding of coding is it is a discipline where being explicit/avoiding ambiguity is best

In this example it seems JavaScript is purposefully not interpreting code exactly as I have written it

My gut feeling is I would rather get an error, than for JavaScript to "fix" my code for me

NB: I am coming to Javascript from Python - am I holding on to "Explicit is better than implicit." too dearly?


问:
NTH_VALUE MySQL. First value is null why?
Why first value is null for nth value column??
Here's the query:

```<code>SELECT first_name, last_name, role_, dept, salary, NTH_VALUE(salary,2) OVER(ORDER BY salary ASC) FROM emp_table;
</code>```

The result:

```<code>Jenifer Jhones  Junior Data Scientist   Retail  2800    null
Katrina Allen   Junior Data Scientist   Retail  3000    3000
David   Smith   Associate Data Scientist    Retail  4000    3000
Claire  Brennan Associate Data Scientist    Automative  4300    3000
Steve   Hoffman Associate Data Scientist    Finance 5000    3000
Chad    Wilson  Associate Data Scientist    Healthcare  5000    3000
Dianna  Wilson  Senior Data Scientist   Healthcare  5500    3000
Nian    Zhen    Senior Data Scientist   Retail  6500    3000
Roy Collins Senior Data Scientist   Retail  7000    3000
Karene  Nowak   Senior Data Scientist   Automative  7500    3000
Dorothy Wilson  Senior Data Scientist   Healthcare  7700    3000
Eric    Hoffman Lead Data Scientist Finance 8500    3000
Tracy   Norris  Manager Retail  8500    3000
</code>```

Body:
Why first value is null for nth value column??
Here's the query:

SELECT first_name, last_name, role_, dept, salary, NTH_VALUE(salary,2) OVER(ORDER BY salary ASC) FROM emp_table;

The result:

Jenifer Jhones  Junior Data Scientist   Retail  2800    null
Katrina Allen   Junior Data Scientist   Retail  3000    3000
David   Smith   Associate Data Scientist    Retail  4000    3000
Claire  Brennan Associate Data Scientist    Automative  4300    3000
Steve   Hoffman Associate Data Scientist    Finance 5000    3000
Chad    Wilson  Associate Data Scientist    Healthcare  5000    3000
Dianna  Wilson  Senior Data Scientist   Healthcare  5500    3000
Nian    Zhen    Senior Data Scientist   Retail  6500    3000
Roy Collins Senior Data Scientist   Retail  7000    3000
Karene  Nowak   Senior Data Scientist   Automative  7500    3000
Dorothy Wilson  Senior Data Scientist   Healthcare  7700    3000
Eric    Hoffman Lead Data Scientist Finance 8500    3000
Tracy   Norris  Manager Retail  8500    3000


问:
Converting CoordinateMatrix to Pyspark Dataframe
how can I convert a CoordinateMatrix to a Pyspark Dataframe?

I have tried to convert my dataframe to a rowmatrix and then to a dataframe using this
df.toRowMatrix().rows.map(lambda x: (x, )).toDF()
but it looks really weird.

```<code>|                  _1|
+--------------------+
|(100,[20,21,22,23...|
|(100,[40,41,42,43...|
|(100,[35,36,37,38...|
|(100,[5,6,7,8,9,1...|
</code>```

Would appreciate any help, thanks!

Body:
how can I convert a CoordinateMatrix to a Pyspark Dataframe?

I have tried to convert my dataframe to a rowmatrix and then to a dataframe using this
df.toRowMatrix().rows.map(lambda x: (x, )).toDF()
but it looks really weird.

|                  _1|
+--------------------+
|(100,[20,21,22,23...|
|(100,[40,41,42,43...|
|(100,[35,36,37,38...|
|(100,[5,6,7,8,9,1...|

Would appreciate any help, thanks!


问:
How to pass authentication stage of SMB
I need to prepare a samba server and an SMB traffic captured between the samba server and smbclient. Then I want to replay the traffic to communicate with the server so I need to pass the auth stage.

First, I started the samba with the following config to disable authentication.

```<code>[global]
   Map to guest = Bad User
   ntlm auth = disabled

[sharedir]
   path = /mount/
   browsable = yes
   read only = no
   guest ok = yes
   write list = all
</code>```

Then, I used smbclient to connect the server via smbclient //172.17.0.1/sharedir -N and captured the traffic. However, the auth stage was not passed as shown in the captured traffic. What is the reason and how can I achieve the goal?

Title: How to pass authentication stage of SMB

Body:
I need to prepare a samba server and an SMB traffic captured between the samba server and smbclient. Then I want to replay the traffic to communicate with the server so I need to pass the auth stage.

First, I started the samba with the following config to disable authentication.

[global]
   Map to guest = Bad User
   ntlm auth = disabled

[sharedir]
   path = /mount/
   browsable = yes
   read only = no
   guest ok = yes
   write list = all

Then, I used smbclient to connect the server via smbclient //172.17.0.1/sharedir -N and captured the traffic. However, the auth stage was not passed as shown in the captured traffic. What is the reason and how can I achieve the goal?


问:
Eclipse JBoss Tools EL Autocomplete not working with Jakarta API
I just did fresh install of Eclipse & JBoss Tools but can't get the EL autocomplete to work.  I tracked it down to the use of Jakarta API.  If I use the older JavaEE API, the EL autocomplete works as expected, but nothing is displayed when using the Jakarta API in the pom.

Eclipse Version 2022-12 (4.26.0) using vm: JDK 17.0.4.1

JBoss Tools Version 4.26.0 Final (Installed from Marketplace)

Example using Jakarta

```<code><dependency>
    <groupId>jakarta.platform</groupId>
    <artifactId>jakarta.jakartaee-api</artifactId>
    <version>9.1.0</version>
    <scope>provided</scope>
</dependency>
</code>```

.

```<code>package test;
import java.io.Serializable;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Named;

@Named
@ViewScoped
public class JakartaNamedObject implements Serializable {
    private static final long serialVersionUID = 1L;

    //getters and setter

}
</code>```

Example using Javax

```<code><dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>8.0</version>
    <scope>provided</scope>
</dependency>
</code>```

.

```<code>package test;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.io.Serializable;

@Named
@ViewScoped
public class JavaxNamedObject implements Serializable {
    private static final long serialVersionUID = 1L;

    //getters and setter

}
</code>```

I used the Eclipse installer to install Eclipse 2022-12, with a brand new workspace and then Eclipse Marketplace to install JBoss Tools 4.26.

I guess the question is does EL autocomplete work with Jakarta and if so why is it not working in my fresh new setup?

Body:
I just did fresh install of Eclipse & JBoss Tools but can't get the EL autocomplete to work.  I tracked it down to the use of Jakarta API.  If I use the older JavaEE API, the EL autocomplete works as expected, but nothing is displayed when using the Jakarta API in the pom.

Eclipse Version 2022-12 (4.26.0) using vm: JDK 17.0.4.1

JBoss Tools Version 4.26.0 Final (Installed from Marketplace)

Example using Jakarta

<dependency>
    <groupId>jakarta.platform</groupId>
    <artifactId>jakarta.jakartaee-api</artifactId>
    <version>9.1.0</version>
    <scope>provided</scope>
</dependency>

.

package test;
import java.io.Serializable;
import jakarta.faces.view.ViewScoped;
import jakarta.inject.Named;

@Named
@ViewScoped
public class JakartaNamedObject implements Serializable {
    private static final long serialVersionUID = 1L;

    //getters and setter

}

Example using Javax

<dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>8.0</version>
    <scope>provided</scope>
</dependency>

.

package test;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
import java.io.Serializable;

@Named
@ViewScoped
public class JavaxNamedObject implements Serializable {
    private static final long serialVersionUID = 1L;

    //getters and setter

}

I used the Eclipse installer to install Eclipse 2022-12, with a brand new workspace and then Eclipse Marketplace to install JBoss Tools 4.26.

I guess the question is does EL autocomplete work with Jakarta and if so why is it not working in my fresh new setup?


问:
Sprignboot multipart temp location stay longer
I am using spring.servlet.multipart.location property for uploading temp directory, but i want to temp directory stay longer. Normally tmp directory is deleted when request send response but i need it even after response is sent. So is there any way to turn off automatic tmp deleting and delete it manually after all what i need to do or any other way? Thanks!


问:
Include Photos Folder in VB.NET Project
I'm trying to use the command below to access the Photos folder in my project:

Dim filePath As String = Application.StartupPath & "\Photos"

In the folder where my executable is, there are subfolders:

\bin\Debug

In which folder should I put my Photos folder, the Debug folder or the root folder of my project, so that the Application.StartupPath command accesses the folder correctly?

Title: Include Photos Folder in VB.NET Project


问:
Date output in Russian in js graph
Please tell me how to implement the date output in Russian? I watched similar scripts on the web, but due to lack of knowledge of js, I could not figure it out. The graph shows data for the last seven days. I get them from the DB and insert them into the graph by adding php code with the necessary data. Thank you for any answer.</p>
```<code>var ticketVolumeChartInit = function ticketVolumeChartInit() {
  var $ticketVolume = document.querySelector('.echart-ticket-volume');

  if ($ticketVolume) {
    var userOptions = utils.getData($ticketVolume, 'options');
    var chart = window.echarts.init($ticketVolume);
    var ticketVolumeLegend = document.querySelectorAll('[data-ticket-volume]');

    var getDefaultOptions = function getDefaultOptions() {
      return {
        color: [utils.getColors().primary, localStorage.getItem('theme') === 'dark' ? '#235FAD' : '#6AA2EC', localStorage.getItem('theme') === 'dark' ? '#1C4477' : '#AACAF4', localStorage.getItem('theme') === 'dark' ? '#152C48' : '#DFEBFB'],
        legend: {
          data: ['Посещения', 'Просмотры новостей', 'Просмотры офферов', 'Переходы по офферам'],
          show: false
        },
        xAxis: {
          type: 'category',
          data: utils.getPastDates(7),
          axisLine: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: utils.getGrays()['300']
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: utils.getGrays()['600'],
            formatter: function formatter(value) {
              return window.dayjs(value).format('MMM DD');
            }
          }
        },
        yAxis: {
          type: 'value',
          splitLine: {
            lineStyle: {
              color: utils.getGrays()['300']
            }
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: true,
            color: utils.getGrays()['600']
          }
        },
        tooltip: {
          trigger: 'axis',
          padding: [7, 10],
          axisPointer: {
            type: 'none'
          },
          backgroundColor: utils.getGrays()['100'],
          borderColor: utils.getGrays()['300'],
          textStyle: {
            color: utils.getColors().dark
          },
          borderWidth: 1,
          transitionDuration: 0,
          position: function position(pos, params, dom, rect, size) {
            return getPosition(pos, params, dom, rect, size);
          },
          formatter: tooltipFormatter
        },
        series: [{
          name: 'Посещения',
          type: 'bar',
          stack: 'total',
          data: <?php echo json_encode($visits); ?>,
          emphasis: {
            itemStyle: {
              color: utils.getColor('primary')
            }
          }
        }, {
          name: 'Просмотры новостей',
          type: 'bar',
          stack: 'total',
          data: <?php echo json_encode($news_views); ?>,
          emphasis: {
            itemStyle: {
              color: localStorage.getItem('theme') === 'dark' ? '#2567BD' : '#5595E9'
            }
          }
        }, {
          name: 'Просмотры офферов',
          type: 'bar',
          stack: 'total',
          data: <?php echo json_encode($views_offers); ?>,
          emphasis: {
            itemStyle: {
              color: localStorage.getItem('theme') === 'dark' ? '#205396' : '#7FB0EF'
            }
          }
        }, {
          name: 'Переходы по офферам',
          type: 'bar',
          stack: 'total',
          data: <?php echo json_encode($transitions); ?>,
          itemStyle: {
            barBorderRadius: [2, 2, 0, 0]
          },
          emphasis: {
            itemStyle: {
              color: localStorage.getItem('theme') === 'dark' ? '#1A3F6F' : '#AACAF4'
            }
          }
        }],
        grid: {
          right: '0px',
          left: '23px',
          bottom: '6%',
          top: '10%'
        }
      };
    };

    echartSetOption(chart, userOptions, getDefaultOptions);
    ticketVolumeLegend.forEach(function (el) {
      el.addEventListener('change', function () {
        chart.dispatchAction({
          type: 'legendToggleSelect',
          name: utils.getData(el, 'ticket-volume')
        });
      });
    });
  }
};
</code>```

Title: Date output in Russian in js graph

Body:
Please tell me how to implement the date output in Russian? I watched similar scripts on the web, but due to lack of knowledge of js, I could not figure it out. The graph shows data for the last seven days. I get them from the DB and insert them into the graph by adding php code with the necessary data. Thank you for any answer.

var ticketVolumeChartInit = function ticketVolumeChartInit() {
  var $ticketVolume = document.querySelector('.echart-ticket-volume');

  if ($ticketVolume) {
    var userOptions = utils.getData($ticketVolume, 'options');
    var chart = window.echarts.init($ticketVolume);
    var ticketVolumeLegend = document.querySelectorAll('[data-ticket-volume]');

    var getDefaultOptions = function getDefaultOptions() {
      return {
        color: [utils.getColors().primary, localStorage.getItem('theme') === 'dark' ? '#235FAD' : '#6AA2EC', localStorage.getItem('theme') === 'dark' ? '#1C4477' : '#AACAF4', localStorage.getItem('theme') === 'dark' ? '#152C48' : '#DFEBFB'],
        legend: {
          data: ['Посещения', 'Просмотры новостей', 'Просмотры офферов', 'Переходы по офферам'],
          show: false
        },
        xAxis: {
          type: 'category',
          data: utils.getPastDates(7),
          axisLine: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: utils.getGrays()['300']
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: utils.getGrays()['600'],
            formatter: function formatter(value) {
              return window.dayjs(value).format('MMM DD');
            }
          }
        },
        yAxis: {
          type: 'value',
          splitLine: {
            lineStyle: {
              color: utils.getGrays()['300']
            }
          },
          axisLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            show: true,
            color: utils.getGrays()['600']
          }
        },
        tooltip: {
          trigger: 'axis',
          padding: [7, 10],
          axisPointer: {
            type: 'none'
          },
          backgroundColor: utils.getGrays()['100'],
          borderColor: utils.getGrays()['300'],
          textStyle: {
            color: utils.getColors().dark
          },
          borderWidth: 1,
          transitionDuration: 0,
          position: function position(pos, params, dom, rect, size) {
            return getPosition(pos, params, dom, rect, size);
          },
          formatter: tooltipFormatter
        },
        series: [{
          name: 'Посещения',
          type: 'bar',
          stack: 'total',
          data: <?php echo json_encode($visits); ?>,
          emphasis: {
            itemStyle: {
              color: utils.getColor('primary')
            }
          }
        }, {
          name: 'Просмотры новостей',
          type: 'bar',
          stack: 'total',
          data: <?php echo json_encode($news_views); ?>,
          emphasis: {
            itemStyle: {
              color: localStorage.getItem('theme') === 'dark' ? '#2567BD' : '#5595E9'
            }
          }
        }, {
          name: 'Просмотры офферов',
          type: 'bar',
          stack: 'total',
          data: <?php echo json_encode($views_offers); ?>,
          emphasis: {
            itemStyle: {
              color: localStorage.getItem('theme') === 'dark' ? '#205396' : '#7FB0EF'
            }
          }
        }, {
          name: 'Переходы по офферам',
          type: 'bar',
          stack: 'total',
          data: <?php echo json_encode($transitions); ?>,
          itemStyle: {
            barBorderRadius: [2, 2, 0, 0]
          },
          emphasis: {
            itemStyle: {
              color: localStorage.getItem('theme') === 'dark' ? '#1A3F6F' : '#AACAF4'
            }
          }
        }],
        grid: {
          right: '0px',
          left: '23px',
          bottom: '6%',
          top: '10%'
        }
      };
    };

    echartSetOption(chart, userOptions, getDefaultOptions);
    ticketVolumeLegend.forEach(function (el) {
      el.addEventListener('change', function () {
        chart.dispatchAction({
          type: 'legendToggleSelect',
          name: utils.getData(el, 'ticket-volume')
        });
      });
    });
  }
};


问:
How do I execute a remotely hosted binary with python3 -c?
Inspired by Mr. Robot, I wrote the following one-liner:

python3 -c "from requests import get;exec(get('https://pastebin.com/raw/rrQ1CWpA').text)"
that executes remote_code.py, which is a simple program:

```<code>#!/usr/bin/env python3

print("Greetings from Github.")

</code>```

It crossed my mind to execute in such a way a binary:

python3 -c "from requests import get;exec(get('https://raw.githubusercontent.com/ficticioususer/fake_repo/main/a.out').content)"

where a.out is a standalone executable produced with gcc from this simple program in C:

```<code>#include<stdio.h>

int main() {
  puts("Greetings from Github written by C.");
  return 0;
}
</code>```

Sadly, when I run python3 -c "from requests import get;exec(get('https://raw.githubusercontent.com/ficticioususer/fake_repo/main/a.out').content)" in my shell I get the following output:

```<code>Traceback (most recent call last):
  File "<string>", line 1, in <module>
ValueError: source code string cannot contain null bytes

</code>```

I also tried python3 -c "from subprocess import run;from requests import get;run(get('https://raw.githubusercontent.com/ficticioususer/fake_repo/main/a.out').content
and python3 -c "from subprocess import run;from requests import get;run(get('https://raw.githubusercontent.com/ficticioususer/fake_repo/main/a.out').content, shell=True)" but I get the following error:

```<code>Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.10/subprocess.py", line 501, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib/python3.10/subprocess.py", line 969, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.10/subprocess.py", line 1778, in _execute_child
    self.pid = _posixsubprocess.fork_exec(
ValueError: embedded null byte

</code>```

Is it at all doable to execute remotely hosted binary with python -c command?
How might I accomplish that?

P.S. I don't want to doxx my Github account - ficticioususer is not my Github account, and the link to the executable does not work.

Body:
Inspired by Mr. Robot, I wrote the following one-liner:

python3 -c "from requests import get;exec(get('https://pastebin.com/raw/rrQ1CWpA').text)"
that executes remote_code.py, which is a simple program:

#!/usr/bin/env python3

print("Greetings from Github.")

It crossed my mind to execute in such a way a binary:

python3 -c "from requests import get;exec(get('https://raw.githubusercontent.com/ficticioususer/fake_repo/main/a.out').content)"

where a.out is a standalone executable produced with gcc from this simple program in C:

#include<stdio.h>

int main() {
  puts("Greetings from Github written by C.");
  return 0;
}

Sadly, when I run python3 -c "from requests import get;exec(get('https://raw.githubusercontent.com/ficticioususer/fake_repo/main/a.out').content)" in my shell I get the following output:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
ValueError: source code string cannot contain null bytes

I also tried python3 -c "from subprocess import run;from requests import get;run(get('https://raw.githubusercontent.com/ficticioususer/fake_repo/main/a.out').content
and python3 -c "from subprocess import run;from requests import get;run(get('https://raw.githubusercontent.com/ficticioususer/fake_repo/main/a.out').content, shell=True)" but I get the following error:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/usr/lib/python3.10/subprocess.py", line 501, in run
    with Popen(*popenargs, **kwargs) as process:
  File "/usr/lib/python3.10/subprocess.py", line 969, in __init__
    self._execute_child(args, executable, preexec_fn, close_fds,
  File "/usr/lib/python3.10/subprocess.py", line 1778, in _execute_child
    self.pid = _posixsubprocess.fork_exec(
ValueError: embedded null byte

Is it at all doable to execute remotely hosted binary with python -c command?
How might I accomplish that?

P.S. I don't want to doxx my Github account - ficticioususer is not my Github account, and the link to the executable does not work.


问:
I want to calculate the mean for every participant in a subset for 12 columns
I want to calculate the mean of a subset for different participants in a row. I tried a lot of things but there are errors everytime. What is a better approach? I listed below what I tried so far

# calculate positive subscale via mean
positive_subscale <- df_wide_final %>%
  select(GAAIS_Pos_item_1, GAAIS_Pos_item_2, GAAIS_Pos_item_3, GAAIS_Pos_item_4, GAAIS_Pos_item_5, GAAIS_Pos_Item_6, GAAIS_Pos_Item_7, GAAIS_Pos_Item_8, GAAIS_Pos_Item_9, GAAIS_Pos_Item_10, GAAIS_Pos_Item_11, GAAIS_Pos_Item_12)

pos_num <- lapply(positive_subscale, as.numeric)
pos_mean <- rowMeans(pos_num[drop = FALSE])

positive_subscale %>% summarise_each(funs(mean))

mean_pos <- sapply(Filter(is.numeric, positive_subscale), mean)

pos_character <- as.character(positive_subscale)
pos_numeric <- as.numeric(pos_character)

mean <- aggregate(positive_subscale$GAAIS_Pos_item_1, mean)

pos_numeric <- as.numeric(unlist(positive_subscale))
rowMeans(pos_numeric, na.rm = TRUE)

gemiddelde_pos <-  mean(strtoi(positive_subscale[1, ]))
lapply(positive_subscale, gemiddelde_pos)

rowMeans(strtoi(positive_subscale)[1, , drop = FALSE])
```

I tried different approaches to calculate the mean for every participant, but nothing worked so far

Body:
I want to calculate the mean of a subset for different participants in a row. I tried a lot of things but there are errors everytime. What is a better approach? I listed below what I tried so far

# calculate positive subscale via mean
positive_subscale <- df_wide_final %>%
  select(GAAIS_Pos_item_1, GAAIS_Pos_item_2, GAAIS_Pos_item_3, GAAIS_Pos_item_4, GAAIS_Pos_item_5, GAAIS_Pos_Item_6, GAAIS_Pos_Item_7, GAAIS_Pos_Item_8, GAAIS_Pos_Item_9, GAAIS_Pos_Item_10, GAAIS_Pos_Item_11, GAAIS_Pos_Item_12)

pos_num <- lapply(positive_subscale, as.numeric)
pos_mean <- rowMeans(pos_num[drop = FALSE])

positive_subscale %>% summarise_each(funs(mean))

mean_pos <- sapply(Filter(is.numeric, positive_subscale), mean)

pos_character <- as.character(positive_subscale)
pos_numeric <- as.numeric(pos_character)

mean <- aggregate(positive_subscale$GAAIS_Pos_item_1, mean)

pos_numeric <- as.numeric(unlist(positive_subscale))
rowMeans(pos_numeric, na.rm = TRUE)

gemiddelde_pos <-  mean(strtoi(positive_subscale[1, ]))
lapply(positive_subscale, gemiddelde_pos)

rowMeans(strtoi(positive_subscale)[1, , drop = FALSE])

I tried different approaches to calculate the mean for every participant, but nothing worked so far


问:
overriding validate_unique not raising a ValidationError
I am trying to override the validate_unique for on of my  models to validate that a record doesn't exist with duplicate fields (labeler, date), but It's not raising any validation error when i enter duplicate (labeler, date).

I've already looked through the issues here and here and constructed my view and model as follows:

my view:

```<code>class AttendanceCreateView(CreateView):
    model = Attendance
    template_name = "attendance/attendance_form.html"
    fields = [
        "team_lead",
        "labeler",
        "attendance",
    ]

    def get_success_url(self):
        return reverse("attendance-home")
</code>```

my model:

```<code>class Attendance(models.Model):
    id= models.AutoField(primary_key=True)
    attendance = models.IntegerField(blank=True, choices= CHOICES_ATTENDANCE, null=True)
    labeler = models.ForeignKey('Labelers', models.CASCADE, blank=True, null=True)
    team_lead = models.ForeignKey('TeamLeads', models.CASCADE, blank=True, null=True)
    date = models.DateField(auto_now_add=True, null=True)

    class Meta:
        managed = False
        db_table = "attendance"

    def validate_unique(self, *args, **kwargs):
        super().validate_unique(*args, **kwargs)
        if self.__class__.objects.filter(labeler= self.labeler, date= self.date).exists():
            raise ValidationError(message='a already record exists for date and labeler',)
</code>```

any idea why my code is not behaving as expected ?
thanks is advance.

Body:
I am trying to override the validate_unique for on of my  models to validate that a record doesn't exist with duplicate fields (labeler, date), but It's not raising any validation error when i enter duplicate (labeler, date).

I've already looked through the issues here and here and constructed my view and model as follows:

my view:

class AttendanceCreateView(CreateView):
    model = Attendance
    template_name = "attendance/attendance_form.html"
    fields = [
        "team_lead",
        "labeler",
        "attendance",
    ]

    def get_success_url(self):
        return reverse("attendance-home")

my model:

class Attendance(models.Model):
    id= models.AutoField(primary_key=True)
    attendance = models.IntegerField(blank=True, choices= CHOICES_ATTENDANCE, null=True)
    labeler = models.ForeignKey('Labelers', models.CASCADE, blank=True, null=True)
    team_lead = models.ForeignKey('TeamLeads', models.CASCADE, blank=True, null=True)
    date = models.DateField(auto_now_add=True, null=True)

    class Meta:
        managed = False
        db_table = "attendance"

    def validate_unique(self, *args, **kwargs):
        super().validate_unique(*args, **kwargs)
        if self.__class__.objects.filter(labeler= self.labeler, date= self.date).exists():
            raise ValidationError(message='a already record exists for date and labeler',)

any idea why my code is not behaving as expected ?
thanks is advance.


问:
How to programmatically generate all operator combinations of grouped variables (eg for regression analysis) in Python
My problem is similar to this answered question: stackoverflow.com/questions/42660752/how-to-create-all-possible-combinations-of-formulas-using-patsy-for-model-select. The accepted answer to that question uses a nested for loop comprising calls to itertools.permutations and itertools.product, which assumes that all possible combinations of all parameters are desired. In my case that leads to an infeasibly large number of combinations with majority redundancy, since my variables are arranged in groups, of which up to one (0-1) parameter should be selected for any given combination. (I'm also using statsmodels with patsy.)

Looking into itertools.product, (eg iq.opengenus.org/combination-one-element-list-python/), all combinations could be easily generated using one entry from each group, eg:

```<code>pars1 = ["par1a", "par1b"]
pars2 = ["par2a", "par2b"]
pars3 = ["par3a", "par3b"]
operators = '+ : *'.split()

all_combs = [expr for expr in itertools.product(*[pars1, operators, pars2, operators, pars3])]
</code>```

But this leaves out combinations where no entry from one or more of the parameter lists is included in the output expression (which would also require the corresponding operator from operators to be omitted). For example, how to also include all combinations like:

par1a + par2a

etc? That is, compactly, ie, without having to do it using a staged approach of building up the output list with repeats of the above code block using fewer of the parameter groups.

Body:
My problem is similar to this answered question: stackoverflow.com/questions/42660752/how-to-create-all-possible-combinations-of-formulas-using-patsy-for-model-select. The accepted answer to that question uses a nested for loop comprising calls to itertools.permutations and itertools.product, which assumes that all possible combinations of all parameters are desired. In my case that leads to an infeasibly large number of combinations with majority redundancy, since my variables are arranged in groups, of which up to one (0-1) parameter should be selected for any given combination. (I'm also using statsmodels with patsy.)

Looking into itertools.product, (eg iq.opengenus.org/combination-one-element-list-python/), all combinations could be easily generated using one entry from each group, eg:

pars1 = ["par1a", "par1b"]
pars2 = ["par2a", "par2b"]
pars3 = ["par3a", "par3b"]
operators = '+ : *'.split()

all_combs = [expr for expr in itertools.product(*[pars1, operators, pars2, operators, pars3])]

But this leaves out combinations where no entry from one or more of the parameter lists is included in the output expression (which would also require the corresponding operator from operators to be omitted). For example, how to also include all combinations like:

par1a + par2a

etc? That is, compactly, ie, without having to do it using a staged approach of building up the output list with repeats of the above code block using fewer of the parameter groups.


问:
How to add feature where it displays the number of people detected in YOLOv5?
How do I modify the code or add a feature in this yolov5 object detection python main script to display the detected number of people? In this particular code classes=0 means only people/person will be detected.

```<code># YOLOv5  by Ultralytics, GPL-3.0 license
"""
Run YOLOv5 detection inference on images, videos, directories, globs, YouTube, webcam, streams, etc.

Usage - sources:
    $ python detect.py --weights yolov5s.pt --source 0                               # webcam
                                                     img.jpg                         # image
                                                     vid.mp4                         # video
                                                     screen                          # screenshot
                                                     path/                           # directory
                                                     list.txt                        # list of images
                                                     list.streams                    # list of streams
                                                     'path/*.jpg'                    # glob
                                                     'https://youtu.be/Zgi9g1ksQHc'  # YouTube
                                                     'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP stream

Usage - formats:
    $ python detect.py --weights yolov5s.pt                 # PyTorch
                                 yolov5s.torchscript        # TorchScript
                                 yolov5s.onnx               # ONNX Runtime or OpenCV DNN with --dnn
                                 yolov5s_openvino_model     # OpenVINO
                                 yolov5s.engine             # TensorRT
                                 yolov5s.mlmodel            # CoreML (macOS-only)
                                 yolov5s_saved_model        # TensorFlow SavedModel
                                 yolov5s.pb                 # TensorFlow GraphDef
                                 yolov5s.tflite             # TensorFlow Lite
                                 yolov5s_edgetpu.tflite     # TensorFlow Edge TPU
                                 yolov5s_paddle_model       # PaddlePaddle
"""

import argparse
import os
import platform
import sys
from pathlib import Path

import torch

FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # YOLOv5 root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative

from models.common import DetectMultiBackend
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
                           increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh)
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device, smart_inference_mode

@smart_inference_mode()
def run(
        weights=ROOT / 'yolov5s.pt',  # model path or triton URL
        source=ROOT / 'data/images',  # file/dir/URL/glob/screen/0(webcam)
        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path
        imgsz=(640, 640),  # inference size (height, width)
        conf_thres=0.25,  # confidence threshold
        iou_thres=0.45,  # NMS IOU threshold
        max_det=1000,  # maximum detections per image
        device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu
        view_img=False,  # show results
        save_txt=False,  # save results to *.txt
        save_conf=False,  # save confidences in --save-txt labels
        save_crop=False,  # save cropped prediction boxes
        nosave=False,  # do not save images/videos
        classes=None,  # filter by class: --class 0, or --class 0 2 3
        agnostic_nms=False,  # class-agnostic NMS
        augment=False,  # augmented inference
        visualize=False,  # visualize features
        update=False,  # update all models
        project=ROOT / 'runs/detect',  # save results to project/name
        name='exp',  # save results to project/name
        exist_ok=False,  # existing project/name ok, do not increment
        line_thickness=3,  # bounding box thickness (pixels)
        hide_labels=False,  # hide labels
        hide_conf=False,  # hide confidences
        half=False,  # use FP16 half-precision inference
        dnn=False,  # use OpenCV DNN for ONNX inference
        vid_stride=1,  # video frame-rate stride
):
    source = str(source)
    save_img = not nosave and not source.endswith('.txt')  # save inference images
    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
    webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)
    screenshot = source.lower().startswith('screen')
    if is_url and is_file:
        source = check_file(source)  # download

    # Directories
    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir

    # Load model
    device = select_device(device)
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
    stride, names, pt = model.stride, model.names, model.pt
    imgsz = check_img_size(imgsz, s=stride)  # check image size

    # Dataloader
    bs = 1  # batch_size
    if webcam:
        view_img = check_imshow(warn=True)
        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
        bs = len(dataset)
    elif screenshot:
        dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
    else:
        dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
    vid_path, vid_writer = [None] * bs, [None] * bs

    # Run inference
    model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz))  # warmup
    seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
    for path, im, im0s, vid_cap, s in dataset:
        with dt[0]:
            im = torch.from_numpy(im).to(model.device)
            im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32
            im /= 255  # 0 - 255 to 0.0 - 1.0
            if len(im.shape) == 3:
                im = im[None]  # expand for batch dim

        # Inference
        with dt[1]:
            visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
            pred = model(im, augment=augment, visualize=visualize)

        # NMS
        with dt[2]:
            pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)

        # Second-stage classifier (optional)
        # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)

        # Process predictions
        for i, det in enumerate(pred):  # per image
            seen += 1
            if webcam:  # batch_size >= 1
                p, im0, frame = path[i], im0s[i].copy(), dataset.count
                s += f'{i}: '
            else:
                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)

            p = Path(p)  # to Path
            save_path = str(save_dir / p.name)  # im.jpg
            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt
            s += '%gx%g ' % im.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            imc = im0.copy() if save_crop else im0  # for save_crop
            annotator = Annotator(im0, line_width=line_thickness, example=str(names))
            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()

                # Print results
                for c in det[:, 5].unique():
                    n = (det[:, 5] == c).sum()  # detections per class
                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

                # Write results
                for *xyxy, conf, cls in reversed(det):
                    if save_txt:  # Write to file
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
                        line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format
                        with open(f'{txt_path}.txt', 'a') as f:
                            f.write(('%g ' * len(line)).rstrip() % line + '\n')

                    if save_img or save_crop or view_img:  # Add bbox to image
                        c = int(cls)  # integer class
                        label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
                        annotator.box_label(xyxy, label, color=colors(c, True))
                    if save_crop:
                        save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)

            # Stream results
            im0 = annotator.result()
            if view_img:
                if platform.system() == 'Linux' and p not in windows:
                    windows.append(p)
                    cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)
                    cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
                cv2.imshow(str(p), im0)
                cv2.waitKey(1)  # 1 millisecond

            # Save results (image with detections)
            if save_img:
                if dataset.mode == 'image':
                    cv2.imwrite(save_path, im0)
                else:  # 'video' or 'stream'
                    if vid_path[i] != save_path:  # new video
                        vid_path[i] = save_path
                        if isinstance(vid_writer[i], cv2.VideoWriter):
                            vid_writer[i].release()  # release previous video writer
                        if vid_cap:  # video
                            fps = vid_cap.get(cv2.CAP_PROP_FPS)
                            w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
                            h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
                        else:  # stream
                            fps, w, h = 30, im0.shape[1], im0.shape[0]
                        save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos
                        vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
                    vid_writer[i].write(im0)

        # Print time (inference-only)
        LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")

    # Print results
    t = tuple(x.t / seen * 1E3 for x in dt)  # speeds per image
    LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
    if save_txt or save_img:
        s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
        LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
    if update:
        strip_optimizer(weights[0])  # update model (to fix SourceChangeWarning)

def parse_opt():
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path or triton URL')
    parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')
    parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
    parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
    parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
    parser.add_argument('--view-img', action='store_true', help='show results')
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
    parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
    parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
    parser.add_argument('--augment', action='store_true', help='augmented inference')
    parser.add_argument('--visualize', action='store_true', help='visualize features')
    parser.add_argument('--update', action='store_true', help='update all models')
    parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
    parser.add_argument('--name', default='exp', help='save results to project/name')
    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
    parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
    parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
    parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
    parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
    opt = parser.parse_args()
    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand
    print_args(vars(opt))
    return opt

def main(opt):
    check_requirements(exclude=('tensorboard', 'thop'))
    run(**vars(opt))

if __name__ == "__main__":
    opt = parse_opt()
    main(opt)
</code>```

Please any ideas will be greatly appreciated.

I tried using these lines of codes but i encountered an error:

```<code>File "D:\Downloads\Compressed\yolov5-master\detect.py", line 276, in <module>
    main(opt)
  File "D:\Downloads\Compressed\yolov5-master\detect.py", line 271, in main
    run(**vars(opt))
  File "C:\Users\bsbul\anaconda3\lib\site-packages\torch\autograd\grad_mode.py", line 27, in decorate_context
    return func(*args, **kwargs)
  File "D:\Downloads\Compressed\yolov5-master\detect.py", line 133, in run
    if det['class'] == 0:  # class 0 is people/persons
IndexError: too many indices for tensor of dimension 3
</code>```

Body:
How do I modify the code or add a feature in this yolov5 object detection python main script to display the detected number of people? In this particular code classes=0 means only people/person will be detected.

# YOLOv5  by Ultralytics, GPL-3.0 license
"""
Run YOLOv5 detection inference on images, videos, directories, globs, YouTube, webcam, streams, etc.

Usage - sources:
    $ python detect.py --weights yolov5s.pt --source 0                               # webcam
                                                     img.jpg                         # image
                                                     vid.mp4                         # video
                                                     screen                          # screenshot
                                                     path/                           # directory
                                                     list.txt                        # list of images
                                                     list.streams                    # list of streams
                                                     'path/*.jpg'                    # glob
                                                     'https://youtu.be/Zgi9g1ksQHc'  # YouTube
                                                     'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP stream

Usage - formats:
    $ python detect.py --weights yolov5s.pt                 # PyTorch
                                 yolov5s.torchscript        # TorchScript
                                 yolov5s.onnx               # ONNX Runtime or OpenCV DNN with --dnn
                                 yolov5s_openvino_model     # OpenVINO
                                 yolov5s.engine             # TensorRT
                                 yolov5s.mlmodel            # CoreML (macOS-only)
                                 yolov5s_saved_model        # TensorFlow SavedModel
                                 yolov5s.pb                 # TensorFlow GraphDef
                                 yolov5s.tflite             # TensorFlow Lite
                                 yolov5s_edgetpu.tflite     # TensorFlow Edge TPU
                                 yolov5s_paddle_model       # PaddlePaddle
"""

import argparse
import os
import platform
import sys
from pathlib import Path

import torch

FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # YOLOv5 root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative

from models.common import DetectMultiBackend
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
                           increment_path, non_max_suppression, print_args, scale_boxes, strip_optimizer, xyxy2xywh)
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device, smart_inference_mode

@smart_inference_mode()
def run(
        weights=ROOT / 'yolov5s.pt',  # model path or triton URL
        source=ROOT / 'data/images',  # file/dir/URL/glob/screen/0(webcam)
        data=ROOT / 'data/coco128.yaml',  # dataset.yaml path
        imgsz=(640, 640),  # inference size (height, width)
        conf_thres=0.25,  # confidence threshold
        iou_thres=0.45,  # NMS IOU threshold
        max_det=1000,  # maximum detections per image
        device='',  # cuda device, i.e. 0 or 0,1,2,3 or cpu
        view_img=False,  # show results
        save_txt=False,  # save results to *.txt
        save_conf=False,  # save confidences in --save-txt labels
        save_crop=False,  # save cropped prediction boxes
        nosave=False,  # do not save images/videos
        classes=None,  # filter by class: --class 0, or --class 0 2 3
        agnostic_nms=False,  # class-agnostic NMS
        augment=False,  # augmented inference
        visualize=False,  # visualize features
        update=False,  # update all models
        project=ROOT / 'runs/detect',  # save results to project/name
        name='exp',  # save results to project/name
        exist_ok=False,  # existing project/name ok, do not increment
        line_thickness=3,  # bounding box thickness (pixels)
        hide_labels=False,  # hide labels
        hide_conf=False,  # hide confidences
        half=False,  # use FP16 half-precision inference
        dnn=False,  # use OpenCV DNN for ONNX inference
        vid_stride=1,  # video frame-rate stride
):
    source = str(source)
    save_img = not nosave and not source.endswith('.txt')  # save inference images
    is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
    is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
    webcam = source.isnumeric() or source.endswith('.streams') or (is_url and not is_file)
    screenshot = source.lower().startswith('screen')
    if is_url and is_file:
        source = check_file(source)  # download

    # Directories
    save_dir = increment_path(Path(project) / name, exist_ok=exist_ok)  # increment run
    (save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True)  # make dir

    # Load model
    device = select_device(device)
    model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
    stride, names, pt = model.stride, model.names, model.pt
    imgsz = check_img_size(imgsz, s=stride)  # check image size

    # Dataloader
    bs = 1  # batch_size
    if webcam:
        view_img = check_imshow(warn=True)
        dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
        bs = len(dataset)
    elif screenshot:
        dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
    else:
        dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
    vid_path, vid_writer = [None] * bs, [None] * bs

    # Run inference
    model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz))  # warmup
    seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
    for path, im, im0s, vid_cap, s in dataset:
        with dt[0]:
            im = torch.from_numpy(im).to(model.device)
            im = im.half() if model.fp16 else im.float()  # uint8 to fp16/32
            im /= 255  # 0 - 255 to 0.0 - 1.0
            if len(im.shape) == 3:
                im = im[None]  # expand for batch dim

        # Inference
        with dt[1]:
            visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
            pred = model(im, augment=augment, visualize=visualize)

        # NMS
        with dt[2]:
            pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)

        # Second-stage classifier (optional)
        # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)

        # Process predictions
        for i, det in enumerate(pred):  # per image
            seen += 1
            if webcam:  # batch_size >= 1
                p, im0, frame = path[i], im0s[i].copy(), dataset.count
                s += f'{i}: '
            else:
                p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)

            p = Path(p)  # to Path
            save_path = str(save_dir / p.name)  # im.jpg
            txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt
            s += '%gx%g ' % im.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            imc = im0.copy() if save_crop else im0  # for save_crop
            annotator = Annotator(im0, line_width=line_thickness, example=str(names))
            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()

                # Print results
                for c in det[:, 5].unique():
                    n = (det[:, 5] == c).sum()  # detections per class
                    s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string

                # Write results
                for *xyxy, conf, cls in reversed(det):
                    if save_txt:  # Write to file
                        xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
                        line = (cls, *xywh, conf) if save_conf else (cls, *xywh)  # label format
                        with open(f'{txt_path}.txt', 'a') as f:
                            f.write(('%g ' * len(line)).rstrip() % line + '\n')

                    if save_img or save_crop or view_img:  # Add bbox to image
                        c = int(cls)  # integer class
                        label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
                        annotator.box_label(xyxy, label, color=colors(c, True))
                    if save_crop:
                        save_one_box(xyxy, imc, file=save_dir / 'crops' / names[c] / f'{p.stem}.jpg', BGR=True)

            # Stream results
            im0 = annotator.result()
            if view_img:
                if platform.system() == 'Linux' and p not in windows:
                    windows.append(p)
                    cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)  # allow window resize (Linux)
                    cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
                cv2.imshow(str(p), im0)
                cv2.waitKey(1)  # 1 millisecond

            # Save results (image with detections)
            if save_img:
                if dataset.mode == 'image':
                    cv2.imwrite(save_path, im0)
                else:  # 'video' or 'stream'
                    if vid_path[i] != save_path:  # new video
                        vid_path[i] = save_path
                        if isinstance(vid_writer[i], cv2.VideoWriter):
                            vid_writer[i].release()  # release previous video writer
                        if vid_cap:  # video
                            fps = vid_cap.get(cv2.CAP_PROP_FPS)
                            w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
                            h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
                        else:  # stream
                            fps, w, h = 30, im0.shape[1], im0.shape[0]
                        save_path = str(Path(save_path).with_suffix('.mp4'))  # force *.mp4 suffix on results videos
                        vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
                    vid_writer[i].write(im0)

        # Print time (inference-only)
        LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")

    # Print results
    t = tuple(x.t / seen * 1E3 for x in dt)  # speeds per image
    LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
    if save_txt or save_img:
        s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
        LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
    if update:
        strip_optimizer(weights[0])  # update model (to fix SourceChangeWarning)

def parse_opt():
    parser = argparse.ArgumentParser()
    parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model path or triton URL')
    parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob/screen/0(webcam)')
    parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
    parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640], help='inference size h,w')
    parser.add_argument('--conf-thres', type=float, default=0.25, help='confidence threshold')
    parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
    parser.add_argument('--max-det', type=int, default=1000, help='maximum detections per image')
    parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
    parser.add_argument('--view-img', action='store_true', help='show results')
    parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
    parser.add_argument('--save-conf', action='store_true', help='save confidences in --save-txt labels')
    parser.add_argument('--save-crop', action='store_true', help='save cropped prediction boxes')
    parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
    parser.add_argument('--classes', nargs='+', type=int, help='filter by class: --classes 0, or --classes 0 2 3')
    parser.add_argument('--agnostic-nms', action='store_true', help='class-agnostic NMS')
    parser.add_argument('--augment', action='store_true', help='augmented inference')
    parser.add_argument('--visualize', action='store_true', help='visualize features')
    parser.add_argument('--update', action='store_true', help='update all models')
    parser.add_argument('--project', default=ROOT / 'runs/detect', help='save results to project/name')
    parser.add_argument('--name', default='exp', help='save results to project/name')
    parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
    parser.add_argument('--line-thickness', default=3, type=int, help='bounding box thickness (pixels)')
    parser.add_argument('--hide-labels', default=False, action='store_true', help='hide labels')
    parser.add_argument('--hide-conf', default=False, action='store_true', help='hide confidences')
    parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
    parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
    parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
    opt = parser.parse_args()
    opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1  # expand
    print_args(vars(opt))
    return opt

def main(opt):
    check_requirements(exclude=('tensorboard', 'thop'))
    run(**vars(opt))

if __name__ == "__main__":
    opt = parse_opt()
    main(opt)

Please any ideas will be greatly appreciated.

I tried using these lines of codes but i encountered an error:

File "D:\Downloads\Compressed\yolov5-master\detect.py", line 276, in <module>
    main(opt)
  File "D:\Downloads\Compressed\yolov5-master\detect.py", line 271, in main
    run(**vars(opt))
  File "C:\Users\bsbul\anaconda3\lib\site-packages\torch\autograd\grad_mode.py", line 27, in decorate_context
    return func(*args, **kwargs)
  File "D:\Downloads\Compressed\yolov5-master\detect.py", line 133, in run
    if det['class'] == 0:  # class 0 is people/persons
IndexError: too many indices for tensor of dimension 3


问:
CONVERT_TIMEZONE issue in Greenplum
I have a query in Snowflake which I need to represent in Greenplum

So I am facing with that problem. These date functions don't exist in Greenplum:

TO_TIMESTAMP_NTZ(CONVERT_TIMEZONE('UTC', CURRENT_TIMESTAMP))

How I can fix it in Greenplum?

Tried to find analogue functions

Title: CONVERT_TIMEZONE issue in Greenplum


问:
AWS Lambda - RDS Proxy creating a connection takes more time
As we can't use native DBCP or any kind of java connection pool in AWS Lambda I have been using RDS proxy to connect MYSQL DB, But Still it takes 5 to 6 secs to make connection but I need the response from the lambda in <1 secs it there any way of keeping the connection warm. I'm using DriverManager.getConnection to get connection from RDS proxy

I have tired to connect proxy using
java.sql.DriverManager

```<code>Connection con = DriverManager.getConnection(("DB_Primary_IP"),("DB_Username"),("DB_Password"));
</code>```

Body:
As we can't use native DBCP or any kind of java connection pool in AWS Lambda I have been using RDS proxy to connect MYSQL DB, But Still it takes 5 to 6 secs to make connection but I need the response from the lambda in <1 secs it there any way of keeping the connection warm. I'm using DriverManager.getConnection to get connection from RDS proxy

I have tired to connect proxy using
java.sql.DriverManager

Connection con = DriverManager.getConnection(("DB_Primary_IP"),("DB_Username"),("DB_Password"));