问:
Check for an unwanted character to throw a BadCharException
so what I'm trying to do is to write code that checks whether any of two actual parameters of type String contain one of two illegal characters, and if so, to throw an exception which states which one of the two characters it is and the index in which it is located. The only way I can think of doing it is to create a bunch of if statements, to check for each individual case:

```<code>        if (firstName.contains("!") || firstName.contains(":") || lastName.contains("!") || lastName.contains(":")){
            if (firstName.contains("!"))
                throw new BadCharException('!', firstName.indexOf('!'));
            if (firstName.contains(":"))
                throw new BadCharException(':', firstName.indexOf(':'));
            if (lastName.contains("!"))
                throw new BadCharException('!', lastName.indexOf('!'));
            if (lastName.contains(":"))
                throw new BadCharException(':', lastName.indexOf(':'));
</code>```

Is there a cleaner or better or more efficient way of going about this?

答:
Here's a more cleaner way:</p>
```<code>    char[] unwantedChars = {'!', ':'};
    for(char character: unwantedChars) {
        if(firstName.contains(character))
            throw new BadCharException(character, firstName.indexOf(character));
        if(lastName.contains(character))
            throw new BadCharException(character, lastName.indexOf(character));

    }
</code>```

Body:
so what I'm trying to do is to write code that checks whether any of two actual parameters of type String contain one of two illegal characters, and if so, to throw an exception which states which one of the two characters it is and the index in which it is located. The only way I can think of doing it is to create a bunch of if statements, to check for each individual case:

        if (firstName.contains("!") || firstName.contains(":") || lastName.contains("!") || lastName.contains(":")){
            if (firstName.contains("!"))
                throw new BadCharException('!', firstName.indexOf('!'));
            if (firstName.contains(":"))
                throw new BadCharException(':', firstName.indexOf(':'));
            if (lastName.contains("!"))
                throw new BadCharException('!', lastName.indexOf('!'));
            if (lastName.contains(":"))
                throw new BadCharException(':', lastName.indexOf(':'));

Is there a cleaner or better or more efficient way of going about this?

Body:
Here's a more cleaner way:

    char[] unwantedChars = {'!', ':'};
    for(char character: unwantedChars) {
        if(firstName.contains(character))
            throw new BadCharException(character, firstName.indexOf(character));
        if(lastName.contains(character))
            throw new BadCharException(character, lastName.indexOf(character));

    }


来源: stackexchange

问:
Out of memory during loading images taken with the camera
I am loading an image scale it to screen size and after that the user can draw some text on it using his hand.

After that user can save it to SD card. I need to save it to same width and height as original image has. For others sample image it is working fine. But when i am loading the image captured by camera and once i draw something on draw. I try to scale image back to original height and width but it is giving Exception "Out of Memory Exception" for all the images captured by camera. The code is as follows:

```<code>private void saveView(View view) {
        Bitmap b = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
                Bitmap.Config.ARGB_8888);
        String filePath="/sdcard/";
        Canvas c = new Canvas(b);

        view.draw(c);
        float scaleHeight=((float)getHeight()/b.getHeight());
        float scaleWidth=((float)getWidth()/b.getWidth());
        Matrix matrix=new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Log.e("getWidth()", ":"+getWidth());
        Log.e("getHeight()", ":"+getHeight());

              **//Giving Exception at below Line as i am trying to scat it to origenal size.
        b=Bitmap.createBitmap(b,0,0,b.getWidth(),b.getHeight(),matrix,true);**
</code>```

答:
You need to resize your bitmap as below.+

```<code>Bitmap resizedBitmap = getResizedBitmap(myBitmap, 150, 150);
</code>```

and the method

```<code>    public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;

    // create a matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);
    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
                    matrix, false);
    return resizedBitmap;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am loading an image scale it to screen size and after that the user can draw some text on it using his hand.

After that user can save it to SD card. I need to save it to same width and height as original image has. For others sample image it is working fine. But when i am loading the image captured by camera and once i draw something on draw. I try to scale image back to original height and width but it is giving Exception "Out of Memory Exception" for all the images captured by camera. The code is as follows:

private void saveView(View view) {
        Bitmap b = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
                Bitmap.Config.ARGB_8888);
        String filePath="/sdcard/";
        Canvas c = new Canvas(b);

        view.draw(c);
        float scaleHeight=((float)getHeight()/b.getHeight());
        float scaleWidth=((float)getWidth()/b.getWidth());
        Matrix matrix=new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        Log.e("getWidth()", ":"+getWidth());
        Log.e("getHeight()", ":"+getHeight());

              **//Giving Exception at below Line as i am trying to scat it to origenal size.
        b=Bitmap.createBitmap(b,0,0,b.getWidth(),b.getHeight(),matrix,true);**

Body:
You need to resize your bitmap as below.+

Bitmap resizedBitmap = getResizedBitmap(myBitmap, 150, 150);

and the method

    public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
    int width = bm.getWidth();
    int height = bm.getHeight();
    float scaleWidth = ((float) newWidth) / width;
    float scaleHeight = ((float) newHeight) / height;

    // create a matrix for the manipulation
    Matrix matrix = new Matrix();
    // resize the bit map
    matrix.postScale(scaleWidth, scaleHeight);
    // recreate the new Bitmap
    Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height,
                    matrix, false);
    return resizedBitmap;
}


问:
error with the result of a replication procedure
I have a problem with the following procedure:

```<code>library(igraph)
k <- cbind(c(.2,.2),c(.2,0))

sbm_centr <- replicate(
  2000,
  sample_sbm(49, pref.matrix = k, block.sizes = c(24, 25)) %>%
    centr_degree(.)$centralization
)
</code>```

The issue is that the function generates a result with two arguments (in addition to the ID of each replication), so the procedure reports an error: Error in .$centr_degree(.) : 3 arguments passed to '$' requiring 2"

I tried, unsuccessfully, to save one of the arguments with the following expression: centr_degree(.)$centralization[1])

But the list contains only 0s. Thanks in advance for your comments.

答:
We can use [[ in the pipe like below

```<code>sbm_centr <- replicate(
  1,
  sample_sbm(49, pref.matrix = k, block.sizes = c(24, 25)) %>%
    centr_degree(.) %>%
    `[[`("centralization")
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem with the following procedure:

library(igraph)
k <- cbind(c(.2,.2),c(.2,0))

sbm_centr <- replicate(
  2000,
  sample_sbm(49, pref.matrix = k, block.sizes = c(24, 25)) %>%
    centr_degree(.)$centralization
)

The issue is that the function generates a result with two arguments (in addition to the ID of each replication), so the procedure reports an error: Error in .$centr_degree(.) : 3 arguments passed to '$' requiring 2"

I tried, unsuccessfully, to save one of the arguments with the following expression: centr_degree(.)$centralization[1])

But the list contains only 0s. Thanks in advance for your comments.

Body:
We can use [[ in the pipe like below

sbm_centr <- replicate(
  1,
  sample_sbm(49, pref.matrix = k, block.sizes = c(24, 25)) %>%
    centr_degree(.) %>%
    `[[`("centralization")
)


问:
inline style vs className in Componet context
Hello I try to understand when it's necessary to use inline style instead className in this case. I take a long time to solve my problem of translation. At the beginning I want to translate component by using classNameand that's don't work. it's very weird because in my point of view there is no reason that's happen. So I figure there is something wrong in my code, but what... I have not yet found. So I finish trying to translate by using a inline style. Miracle, that's work fine.

My question is why ?

Work well

export function Content() {
  return (

        <Test/>

)
}
```
<p>don't work</p>
<pre class="lang-js prettyprint-override"><code>export function Content() {
  return (
    <div className={container_content}>
        <Test/>
        <Footer />
        </div>
        )
}
</code>```

css

.container_content {
    transform: translateY(100px);
}

```
<p>Nota bene :
The problem is not from the method. To use className in my <code>jsx</code>
must be like that:</p>
<pre class="lang-js prettyprint-override"><code>import { container_content } from "./test.module.css";

</code>```

and next

```

So this part of code is good, the issue seems to come from elsewhere...

答:
inside the js file, you need to import the CSS file like this

import " css-file-dir";

and then you can Reference to the CSS classes inside your component as a string

example :

```<code>className="container_content"
</code>```

Body:
Hello I try to understand when it's necessary to use inline style instead className in this case. I take a long time to solve my problem of translation. At the beginning I want to translate component by using classNameand that's don't work. it's very weird because in my point of view there is no reason that's happen. So I figure there is something wrong in my code, but what... I have not yet found. So I finish trying to translate by using a inline style. Miracle, that's work fine.

My question is why ?

Work well

export function Content() {
  return (

        <Test/>

)
}

don't work

export function Content() {
  return (

        <Test/>

        )
}

css

.container_content {
    transform: translateY(100px);
}

Nota bene :
The problem is not from the method. To use className in my jsx
must be like that:

import { container_content } from "./test.module.css";

and next

So this part of code is good, the issue seems to come from elsewhere...

Body:
inside the js file, you need to import the CSS file like this

import " css-file-dir";

and then you can Reference to the CSS classes inside your component as a string

example :

className="container_content"


问:
How do I forcibly disconnect all currently connected clients to my TCP or HTTP server during shutdown?
I have a fake HTTP server that I use as a fixture in my testing. At some point in the test, I want to stop the server regardless of any still open connections. Clients on these open connections should get a TCP FIN.

I am aware that usually production servers need to solve different problem, that of quiescing, sometimes called graceful shutdown. This is the opposite of what I want.

With a standalone process, it is usually possible to simply get the process to quit and the OS will take care of the rest. (Forcibly killing processes is easy, while forcibly killing threads is not.)  My fake server is, however, running in a thread of the test process itself, so I don't have this option (and I don't want to externalize it if there is other way around).

I investigated this issue in Python, with the HTTPServer class, where I was not able to find any solution.

I also investigated this in Go, where I was able to find the concept of Contexts, which is close to what I need, but it works the other way around: a http server would propagate a Context that can be used to cancel e.g. a database lookup if a client disconnected.

Edit: looks like Go actually does what I need and has a separate graceful and nongraceful shutdown methods, with the nongraceful being net/http#Server.Close.

server = http.server.HTTPServer(...)
thread = threading.Thread(run=server.serve_forever)
thread.start()

# a client has connected ....

server.shutdown()
# at this point I want to have the server stopped,
# without waiting for the request handling to complete

```

答:
I've implemented the Go solution in Python. When new client connects, I remember the client socket, and when I want to quit, I shutdown all remembered sockets.

It seems to work.

import socket
import http.server.HTTPServer

class MyHTTPServer(HTTPServer):
    """Adds a method to the HTTPServer to allow it to exit gracefully"""

    def __init__(self, addr, handler_cls):
        super().__init__(addr, handler_cls)
        self._client_sockets: List[socket.socket] = []

        self.server_killed = False

    def get_request(self) -> Tuple[socket.socket, Any]:
        """Remember the client socket"""
        sock, addr = super().get_request()
        self._client_sockets.append(sock)
        return sock, addr

    def shutdown_request(self, request: socket.socket) -> None:
        """Forget the client socket"""
        self._client_sockets.remove(request)
        print(f"{self._client_sockets=}")
        super().shutdown_request(request)

    def force_disconnect_clients(self) -> None:
        """Shutdown the remembered sockets"""
        for client in self._client_sockets:
            client.shutdown(socket.SHUT_RDWR)
```
<h2>Usage</h2>
<pre class="lang-py prettyprint-override"><code>server = MyHTTPServer(server_addr, MyRequestHandler)

# in a new thread
while not server.server_killed:
    self._server.handle_request()

# ... use the server (keep in mind it can have at most one client at a time) ...

# in the main program
server.server_killed = True
server.force_disconnect_clients()
server.server_close()
</code>```

Body:
I've implemented the Go solution in Python. When new client connects, I remember the client socket, and when I want to quit, I shutdown all remembered sockets.

It seems to work.

import socket
import http.server.HTTPServer

class MyHTTPServer(HTTPServer):
    """Adds a method to the HTTPServer to allow it to exit gracefully"""

    def __init__(self, addr, handler_cls):
        super().__init__(addr, handler_cls)
        self._client_sockets: List[socket.socket] = []

        self.server_killed = False

    def get_request(self) -> Tuple[socket.socket, Any]:
        """Remember the client socket"""
        sock, addr = super().get_request()
        self._client_sockets.append(sock)
        return sock, addr

    def shutdown_request(self, request: socket.socket) -> None:
        """Forget the client socket"""
        self._client_sockets.remove(request)
        print(f"{self._client_sockets=}")
        super().shutdown_request(request)

    def force_disconnect_clients(self) -> None:
        """Shutdown the remembered sockets"""
        for client in self._client_sockets:
            client.shutdown(socket.SHUT_RDWR)

Usage

server = MyHTTPServer(server_addr, MyRequestHandler)

# in a new thread
while not server.server_killed:
    self._server.handle_request()

# ... use the server (keep in mind it can have at most one client at a time) ...

# in the main program
server.server_killed = True
server.force_disconnect_clients()
server.server_close()


问:
How do I remove a word that contains special characters
I am new to python. I need help figuring out how do I remove a word from a list of strings that contains special characters?

x = ["I", "@prerkls", "saw"]

How do I remove the word that contain the @ sign?

答:
The below will remove the non-desirable words from the original list of words (mutates the input list).

```<code>def remove(words, special):
    wr_idx = 0 # effectively the new size of the modified list
    for curr_idx in range(len(words)):
        if special in words[curr_idx]: # remove by not copying back
            continue
        words[wr_idx] = words[curr_idx]
        wr_idx += 1

    del words[wr_idx:]
</code>```

For your case we'd do:

```<code>x = ["I", "@prerkls", "saw"]
remove(x, '@')
print(x)
</code>```

Output

```<code>['I', 'saw']
</code>```

Body:
The below will remove the non-desirable words from the original list of words (mutates the input list).

def remove(words, special):
    wr_idx = 0 # effectively the new size of the modified list
    for curr_idx in range(len(words)):
        if special in words[curr_idx]: # remove by not copying back
            continue
        words[wr_idx] = words[curr_idx]
        wr_idx += 1

    del words[wr_idx:]

For your case we'd do:

x = ["I", "@prerkls", "saw"]
remove(x, '@')
print(x)

Output

['I', 'saw']


问:
Spring Boot: Load common config application properties file using bootstrap.yml
In our config server we have following application properties files:

```<code>helloApp-dev.properties //dev env properties
helloApp-commonConfig.properties //common properties across env
</code>```

The properties are accessible from URI like:

```<code>https://myapp.abc.com/1234/helloApp-dev.properties
https://myapp.abc.com/1234/helloApp-commonConfig.properties
</code>```

Below is our bootstrap.yml of helloApp application:

```<code>---
spring:
  application:
    name: helloApp

---
spring
  profiles: dev
  cloud:
    config:
      label: 1234
      name: {spring.application.name}
      uri: https://myapp.abc.com/
</code>```

I am using Spring boot version 2.2.4. The helloApp-dev.properties are loading successfully in application but not commonConfig.

答:
The configuration in commonConfig is not being loaded because you are not indicating to Spring that it should load that profile/config, because you are activating only the dev profile - and the configuration for that profile is the one which is being loaded:

---
spring
  profiles: dev
```
<p>In addition to the good solutions proposed by @akozintsov in his/her answer, if you need to include certain common configuration in different environments or profiles, let's say <code>dev</code>, <code>qa</code> or <code>prod</code>, you can use the <code>spring.profiles.include</code> configuration property and include, as a comma separated list of values, if using <code>properties</code> files, or as a list, if using yaml, the different common profiles and corresponding configurations you need to.</p>
<p>In your example, in <code>helloApp-dev.properties</code> you need to include the following information within the rest of your configuration:</p>
```spring.profiles.include=commonConfig
```

These related SO question and this article could be of help as well.

Body:
In our config server we have following application properties files:

helloApp-dev.properties //dev env properties
helloApp-commonConfig.properties //common properties across env

The properties are accessible from URI like:

https://myapp.abc.com/1234/helloApp-dev.properties
https://myapp.abc.com/1234/helloApp-commonConfig.properties

Below is our bootstrap.yml of helloApp application:

---
spring:
  application:
    name: helloApp

---
spring
  profiles: dev
  cloud:
    config:
      label: 1234
      name: {spring.application.name}
      uri: https://myapp.abc.com/

I am using Spring boot version 2.2.4. The helloApp-dev.properties are loading successfully in application but not commonConfig.

Body:
The configuration in commonConfig is not being loaded because you are not indicating to Spring that it should load that profile/config, because you are activating only the dev profile - and the configuration for that profile is the one which is being loaded:

---
spring
  profiles: dev

In addition to the good solutions proposed by @akozintsov in his/her answer, if you need to include certain common configuration in different environments or profiles, let's say dev, qa or prod, you can use the spring.profiles.include configuration property and include, as a comma separated list of values, if using properties files, or as a list, if using yaml, the different common profiles and corresponding configurations you need to.

In your example, in helloApp-dev.properties you need to include the following information within the rest of your configuration:

spring.profiles.include=commonConfig

These related SO question and this article could be of help as well.


问:
infinitetly loop array with setTimeout javascript
I have an array of strings that I'm passing to a for loop with a setTimeout inside.
I've tried to for(; ;) and while(true) the function but this just causes the browser to crash.

I've also tried adding an if statement inside the function

```<code>if (x == links.length) { loopUrls() }
</code>```

Which works kind of but skips the entire interval section of the function, cycling the entire array infinitely with no wait.

```<code>        function loopUrls() {
            for (var x = 0, ln = links.length; x < ln; x++) {
                setTimeout(function (y) {
                    document.getElementById('ifURLS').src = links[y];
                },x * 500,x);
            }
    };

    loopUrls();
</code>```

The aim is to have a list of urls that infinitely assigned to the iframe to show reports on a sreen. (the time interval is just small for testing purposes)

答:
There is no need to have multiple timeouts. You can achieve this using setInterval which executes a function every x amount of time. Then in that funciton you keep a state of the current url so you can show the next time the function is run

```<code>// creates a function that iterates over the array and every time its called returns the next element
function createIterator(array){
    let sourceArray = [...array];
    // starts at the end so it resets automatically
  let topIndex = sourceArray.length;
    let currentIndex = topIndex - 1;
    return function (){
        currentIndex++;
        // if the limit is reached, its reseated
        if (currentIndex === topIndex) {
            currentIndex = 0;
        }
        return sourceArray[currentIndex];
    }
}
// your urls
let urls = ["a", "b", "c"];
// uses the function to create the iterator
let iterator = createIterator(urls);

setInterval(function() {
    let currentUrl = iterator();
    document.getElementById('ifURLS').src = currentUrl;
},1000);
</code>```

No need for loops, as the iterator handles seamlessly

Body:
I have an array of strings that I'm passing to a for loop with a setTimeout inside.
I've tried to for(; ;) and while(true) the function but this just causes the browser to crash.

I've also tried adding an if statement inside the function

if (x == links.length) { loopUrls() }

Which works kind of but skips the entire interval section of the function, cycling the entire array infinitely with no wait.

        function loopUrls() {
            for (var x = 0, ln = links.length; x < ln; x++) {
                setTimeout(function (y) {
                    document.getElementById('ifURLS').src = links[y];
                },x * 500,x);
            }
    };

    loopUrls();

The aim is to have a list of urls that infinitely assigned to the iframe to show reports on a sreen. (the time interval is just small for testing purposes)

Body:
There is no need to have multiple timeouts. You can achieve this using setInterval which executes a function every x amount of time. Then in that funciton you keep a state of the current url so you can show the next time the function is run

// creates a function that iterates over the array and every time its called returns the next element
function createIterator(array){
    let sourceArray = [...array];
    // starts at the end so it resets automatically
  let topIndex = sourceArray.length;
    let currentIndex = topIndex - 1;
    return function (){
        currentIndex++;
        // if the limit is reached, its reseated
        if (currentIndex === topIndex) {
            currentIndex = 0;
        }
        return sourceArray[currentIndex];
    }
}
// your urls
let urls = ["a", "b", "c"];
// uses the function to create the iterator
let iterator = createIterator(urls);

setInterval(function() {
    let currentUrl = iterator();
    document.getElementById('ifURLS').src = currentUrl;
},1000);

No need for loops, as the iterator handles seamlessly


问:
how to check network change iphone
I'm checking the network connection using this example from Apple:

```<code>- (void) checkNetworkStatus:(NSNotification *)notice
{
    // called after network status changes
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    switch (internetStatus)
    {
        case NotReachable:
        {
            NSLog(@"The internet is down.");
            self.internetActive = NO;

            break;

        }
        case ReachableViaWiFi:
        {
            NSLog(@"The internet is working via WIFI.");
            self.internetActive = YES;

            break;

        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN.");
            self.internetActive = YES;

            break;

        }
    }

    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus)
    {
        case NotReachable:
        {
            NSLog(@"A gateway to the host server is down.");
            self.hostActive = NO;

            break;

        }
        case ReachableViaWiFi:
        {
            NSLog(@"A gateway to the host server is working via WIFI.");
            self.hostActive = YES;

            break;

        }
        case ReachableViaWWAN:
        {
            NSLog(@"A gateway to the host server is working via WWAN.");
            self.hostActive = YES;

            break;

        }
    }
}
</code>```

My intention is to first check that there's a connection and then send an email. The problem is that it takes too long to check if the the app can connect to a host let's say www.google.com it takes like almost a minute. Is there a faster way to check for this?

The other question is how to check if the connection was changed from wi-fi to 3G.

Thanks in advance!

答:
Why do you want to determine the internet connection before emailing? Won't it be better if the email sits in the Outbox until a connection is established? That's generally how email clients work. Outlook or Gmail don't stop you from pressing the send button even if you are not connected. In the many MFMailComposer implementations that I have seen, I have never seen any one checking for connection.

Regarding the 2nd question (again, I can't understand the reason behind this), I don't think there will be a callback that will tell you about WIFI changing to 3G. Naturally, you will have to keep polling. Keep calling checkNetworkStatus repeatedly and see which case is satisfied.

Title: how to check network change iphone

Body:
I'm checking the network connection using this example from Apple:

- (void) checkNetworkStatus:(NSNotification *)notice
{
    // called after network status changes
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
    switch (internetStatus)
    {
        case NotReachable:
        {
            NSLog(@"The internet is down.");
            self.internetActive = NO;

            break;

        }
        case ReachableViaWiFi:
        {
            NSLog(@"The internet is working via WIFI.");
            self.internetActive = YES;

            break;

        }
        case ReachableViaWWAN:
        {
            NSLog(@"The internet is working via WWAN.");
            self.internetActive = YES;

            break;

        }
    }

    NetworkStatus hostStatus = [hostReachable currentReachabilityStatus];
    switch (hostStatus)
    {
        case NotReachable:
        {
            NSLog(@"A gateway to the host server is down.");
            self.hostActive = NO;

            break;

        }
        case ReachableViaWiFi:
        {
            NSLog(@"A gateway to the host server is working via WIFI.");
            self.hostActive = YES;

            break;

        }
        case ReachableViaWWAN:
        {
            NSLog(@"A gateway to the host server is working via WWAN.");
            self.hostActive = YES;

            break;

        }
    }
}

My intention is to first check that there's a connection and then send an email. The problem is that it takes too long to check if the the app can connect to a host let's say www.google.com it takes like almost a minute. Is there a faster way to check for this?

The other question is how to check if the connection was changed from wi-fi to 3G.

Thanks in advance!


问:
How to change the color of the floating combat text in World of Warcraft Retail with lua
I just started programming my own addon for WoW to modify the interface. Now I would like to change the color of the floating combat text from yellow to all white.

I reviewed the add-ons "NameplateSCT" and "MikScrollingBattleText", but as I understand they create their own text frame and do not change the actual floating combat text of the game.

Is it possible to do it with simple lua code in one file? I want my addon to be the least cluttered and only provide the functionality to make it efficient. Here might be a relevant lua repository for the wow interface.

I'm quite new to lua programming, so I haven't tried anything because I don't know where to start. My best guess is going with something like:

CombatFeedback_OnCombatEvent = function(self, event, flags, amount, type)
r = 1.0; g = 1.0; b = 1.0;
end

答:
In the default UI there is "scrolling combat text" for self and "floating combat text" on units in the 3D world.

There are a few CVars that can modify the behavior for the 3D world text like floatingCombatText* and worldText* but changing font color does not seem to be available.


问:
discord py bot has no attribute slash_command
That is all of the imports I have, it works on my pc however when I tried to run it on my pi4 I got the error saying no attribute slash_command, I installed all the packages I thought I needed which was, py-cord, discord.py. Any help would be appreciated.

答:
It isn't commands.Bot, it's discord.Bot

Try this:

```<code>bot = discord.Bot(intents=intents)

bot.slash_command(description="Test")
async def test(ctx):
    ctx.respond("This is a test!")
</code>```

commands.Bot doesn't support slash commands.

Body:
It isn't commands.Bot, it's discord.Bot

Try this:

bot = discord.Bot(intents=intents)

bot.slash_command(description="Test")
async def test(ctx):
    ctx.respond("This is a test!")

commands.Bot doesn't support slash commands.


问:
Vue js - :v-for loop is not iterating through array to create list items
I am struggling to get my v-for loop to create a list based on the size of an array. I thought it was straight forward but am having a hard time figuring out where I've gone wrong. I can only seem to get it to produce the first list item. Any ideas? When I inspect in dev tools I see the following:

.vue:

```<code><template>
    <ul>
        <li :v-for="item in items">item
        </li>
    </ul>

</template>

<script>

export default {

    data(){
        return{
            items: [
                {name: 'item1'},
                {name: 'item2'},
                {name: 'item3'},
                {name: 'item4'},
            ]
        }
    }
}

</script>
</code>```

答:
The v-for is a directive and it's automatically bound to the expression without using the binding sign :, also you should wrap the item with {{}} in order to be rendered:

{{item.name}}

```

Body:
I am struggling to get my v-for loop to create a list based on the size of an array. I thought it was straight forward but am having a hard time figuring out where I've gone wrong. I can only seem to get it to produce the first list item. Any ideas? When I inspect in dev tools I see the following:

.vue:

<template>

item

</template>

Body:
The v-for is a directive and it's automatically bound to the expression without using the binding sign :, also you should wrap the item with {{}} in order to be rendered:

  <li v-for="item in items" :key="item.name">{{item.name}}</li>


问:
Cannot replace fragment from a click on image
I have a navigationDrawer and a RecyclerView of a Cardview. I want that if I click on an image on Cardview, my Fragment changes, but nothing happens
This is the code:

CardAdapter.java

```<code>public class CardAdapter extends FirebaseRecyclerAdapter<Spesa, CardAdapter.cardViewholder> {

    // Constructor
    public CardAdapter(
            FragmentActivity activity, @NonNull FirebaseRecyclerOptions<Spesa> options){
        super(options);
    }

    @Override
    protected void
    onBindViewHolder(@NonNull cardViewholder holder,
                     int position, @NonNull Spesa model)
    {

        holder.amount.setText(model.getDesc());
        holder.who.setText(String.valueOf(model.getCosto()));
        holder.Description.setText(model.getCategoria());
        holder.modifica.setImageResource(R.drawable.edit);

        String str = model.getchi();
        if(model.getchi().equals("Francesco")){
            holder.chiSpende.setImageResource(R.drawable.fra);
        }
        else if(model.getchi().equals("Angela")){
            holder.chiSpende.setImageResource(R.drawable.angela);
        }
holder.modifica.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppCompatActivity activity = (AppCompatActivity) v.getContext();
                Fragment myFragment = new InserisciSpesaFragment();
                activity.getSupportFragmentManager().beginTransaction().replace(R.id.nav_resoconto, myFragment).addToBackStack(null).commit();

            }
    }

    @NonNull
    @Override
    public cardViewholder
    onCreateViewHolder(@NonNull ViewGroup parent,
                       int viewType)
    {
        View view
                = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_layout, parent, false);
        return new CardAdapter.cardViewholder(view);
    }

    class cardViewholder extends RecyclerView.ViewHolder {
        CardView cw;
        TextView amount, who, Description;
        ImageView chiSpende, cancella, modifica;
        public cardViewholder(@NonNull View itemView)
        {
            super(itemView);
            amount = itemView.findViewById(R.id.idAmount);
            who = itemView.findViewById(R.id.idChiSpende);
            Description = itemView.findViewById(R.id.idDescrizioneSpesa);
            chiSpende = itemView.findViewById(R.id.ImgSpese);
            cancella = itemView.findViewById(R.id.bin);
            modifica = itemView.findViewById(R.id.edit);
            cw = itemView.findViewById(R.id.myCardView);

            });

            modifica.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    AppCompatActivity activity = (AppCompatActivity) v.getContext();
                    Fragment frag = new InserisciSpesaFragment();
                    activity.getSupportFragmentManager().beginTransaction()
                            .replace(R.id.nav_resoconto, frag).commit();
                }
            });
        }
    }
}
</code>```

this is the class in which I want to jump: InserisciSpesaFragment.java

```<code>public class InserisciSpesaFragment extends Fragment {
   private Firebase mref;
    FirebaseDatabase database = FirebaseDatabase.getInstance();

    private InserisciSpesa inserisciSpesa;
    private FragmentInserisciBinding binding;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        inserisciSpesa =
                new ViewModelProvider(this).get(InserisciSpesa.class);
        binding = FragmentInserisciBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        Button btn = (Button) binding.BtnInsert;
        EditText txtcosto = (EditText) binding.EdittextCosto;
        EditText txtdesc = (EditText) binding.EdittextSpesa;
        Spinner spinCat = (Spinner) binding.spinnerCategorie;
        Spinner spinChi = (Spinner) binding.spinnerChi;
        DatePicker datePicker = (DatePicker) binding.DatePicker;

       ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                String my = (String) snapshot.getValue();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        };
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!CampiVuoti(txtdesc.getText().toString(), txtcosto.getText().toString())){
                    Snackbar.make(view, "Attenzione, sono presenti campi vuoti!", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                }
                else {
                    Spesa spesa = new Spesa(txtdesc.getText().toString(), Double.parseDouble(txtcosto.getText().toString()),
                            spinCat.getSelectedItem().toString(), spinChi.getSelectedItem().toString(),
                            datePicker.getDayOfMonth(), datePicker.getMonth() + 1, datePicker.getYear());
                    addDatatoFirebase(spesa);
                    Snackbar.make(view, "Spesa inserita correttamente", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            }
        });

        inserisciSpesa.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                //textView.setText(s);
            }
        });
        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}
</code>```

The problem is in the onclick, Especially in:

```<code>            public void onClick(View v) {

                Fragment frag = new InserisciSpesaFragment();
                FragmentManager fm = frag.getActivity().getSupportFragmentManager();
                fm.beginTransaction()
                        .replace(R.id.nav_resoconto, frag)
                        .commit();
            }
</code>```

Thisi is the xml file of the mobile_navigation.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mobile_navigation"
    app:startDestination="@+id/nav_home">

    <fragment
        android:id="@+id/nav_home"
        android:name="com.example.frangela.ui.home.HomeFragment"
        android:label="@string/menu_home"
        tools:layout="@layout/fragment_home" />

    <fragment
        android:id="@+id/nav_gallery"
        android:name="com.example.frangela.ui.gallery.GalleryFragment"
        android:label="@string/menu_gallery"
        tools:layout="@layout/fragment_gallery" />

    <fragment
        android:id="@+id/nav_slideshow"
        android:name="com.example.frangela.ui.slideshow.InserisciSpesaFragment"
        android:label="@string/menu_slideshow"
        tools:layout="@layout/fragment_inserisci" />
    <fragment
        android:id="@+id/nav_stipendio"
        android:name="com.example.frangela.ui.stipendio.InserisciStipendioFragment"
        android:label="@string/menu_stipendio"
        tools:layout="@layout/fragment_stipendio" />

    <fragment
        android:id="@+id/nav_resoconto"
        android:name="com.example.frangela.ui.resocard.ResocardFragment"
        android:label="@string/Resoconto"
        tools:layout="@layout/fragment_resocard" />

</navigation>
</code>```

Thanks

答:
you are creating new fragment

```<code>Fragment frag = new InserisciSpesaFragment();
</code>```

and just after that you are trying to obtain an Activity from it

```<code>FragmentManager fm = frag.getActivity().getSupportFragmentManager();
</code>```

this fragment isn't added to any Activity at the moment of this getActivity() call, you should get an NullPointerException in here... (crash, more than "nothing happens")

consider keeping reference to FragmentManager obtained in constructor

```<code>public class CardAdapter extends FirebaseRecyclerAdapter<Spesa, CardAdapter.cardViewholder> {

    private FragmentManager fm;

    // Constructor
    public CardAdapter(FragmentActivity activity, @NonNull FirebaseRecyclerOptions<Spesa> options){
        super(options);
        fm = activity.getSupportFragmentManager();
    }
</code>```

and then in onClick just use it instead of trying to get it from not-added Fragment

```<code>       public void onClick(View v) {
            Fragment frag = new InserisciSpesaFragment();
            //FragmentManager fm = frag.getActivity().getSupportFragmentManager();
            fm.beginTransaction() // use fm obtained in constructor
                    .replace(R.id.nav_resoconto, frag)
                    .commit();
        }
</code>```

btw. I doubt this code will work as R.id.nav_resoconto is an id of already declared fragment in XML. replace(...) method needs reference to fragment container view (in doc named containerViewId). read doc carefully for proper navigation switching

Body:
I have a navigationDrawer and a RecyclerView of a Cardview. I want that if I click on an image on Cardview, my Fragment changes, but nothing happens
This is the code:

CardAdapter.java

public class CardAdapter extends FirebaseRecyclerAdapter<Spesa, CardAdapter.cardViewholder> {

    // Constructor
    public CardAdapter(
            FragmentActivity activity, @NonNull FirebaseRecyclerOptions<Spesa> options){
        super(options);
    }

    @Override
    protected void
    onBindViewHolder(@NonNull cardViewholder holder,
                     int position, @NonNull Spesa model)
    {

        holder.amount.setText(model.getDesc());
        holder.who.setText(String.valueOf(model.getCosto()));
        holder.Description.setText(model.getCategoria());
        holder.modifica.setImageResource(R.drawable.edit);

        String str = model.getchi();
        if(model.getchi().equals("Francesco")){
            holder.chiSpende.setImageResource(R.drawable.fra);
        }
        else if(model.getchi().equals("Angela")){
            holder.chiSpende.setImageResource(R.drawable.angela);
        }
holder.modifica.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AppCompatActivity activity = (AppCompatActivity) v.getContext();
                Fragment myFragment = new InserisciSpesaFragment();
                activity.getSupportFragmentManager().beginTransaction().replace(R.id.nav_resoconto, myFragment).addToBackStack(null).commit();

            }
    }

    @NonNull
    @Override
    public cardViewholder
    onCreateViewHolder(@NonNull ViewGroup parent,
                       int viewType)
    {
        View view
                = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_layout, parent, false);
        return new CardAdapter.cardViewholder(view);
    }

    class cardViewholder extends RecyclerView.ViewHolder {
        CardView cw;
        TextView amount, who, Description;
        ImageView chiSpende, cancella, modifica;
        public cardViewholder(@NonNull View itemView)
        {
            super(itemView);
            amount = itemView.findViewById(R.id.idAmount);
            who = itemView.findViewById(R.id.idChiSpende);
            Description = itemView.findViewById(R.id.idDescrizioneSpesa);
            chiSpende = itemView.findViewById(R.id.ImgSpese);
            cancella = itemView.findViewById(R.id.bin);
            modifica = itemView.findViewById(R.id.edit);
            cw = itemView.findViewById(R.id.myCardView);

            });

            modifica.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    AppCompatActivity activity = (AppCompatActivity) v.getContext();
                    Fragment frag = new InserisciSpesaFragment();
                    activity.getSupportFragmentManager().beginTransaction()
                            .replace(R.id.nav_resoconto, frag).commit();
                }
            });
        }
    }
}

this is the class in which I want to jump: InserisciSpesaFragment.java

public class InserisciSpesaFragment extends Fragment {
   private Firebase mref;
    FirebaseDatabase database = FirebaseDatabase.getInstance();

    private InserisciSpesa inserisciSpesa;
    private FragmentInserisciBinding binding;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        inserisciSpesa =
                new ViewModelProvider(this).get(InserisciSpesa.class);
        binding = FragmentInserisciBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        Button btn = (Button) binding.BtnInsert;
        EditText txtcosto = (EditText) binding.EdittextCosto;
        EditText txtdesc = (EditText) binding.EdittextSpesa;
        Spinner spinCat = (Spinner) binding.spinnerCategorie;
        Spinner spinChi = (Spinner) binding.spinnerChi;
        DatePicker datePicker = (DatePicker) binding.DatePicker;

       ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                String my = (String) snapshot.getValue();
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        };
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!CampiVuoti(txtdesc.getText().toString(), txtcosto.getText().toString())){
                    Snackbar.make(view, "Attenzione, sono presenti campi vuoti!", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
                }
                else {
                    Spesa spesa = new Spesa(txtdesc.getText().toString(), Double.parseDouble(txtcosto.getText().toString()),
                            spinCat.getSelectedItem().toString(), spinChi.getSelectedItem().toString(),
                            datePicker.getDayOfMonth(), datePicker.getMonth() + 1, datePicker.getYear());
                    addDatatoFirebase(spesa);
                    Snackbar.make(view, "Spesa inserita correttamente", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            }
        });

        inserisciSpesa.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                //textView.setText(s);
            }
        });
        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}

The problem is in the onclick, Especially in:

            public void onClick(View v) {

                Fragment frag = new InserisciSpesaFragment();
                FragmentManager fm = frag.getActivity().getSupportFragmentManager();
                fm.beginTransaction()
                        .replace(R.id.nav_resoconto, frag)
                        .commit();
            }

Thisi is the xml file of the mobile_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mobile_navigation"
    app:startDestination="@+id/nav_home">

    <fragment
        android:id="@+id/nav_home"
        android:name="com.example.frangela.ui.home.HomeFragment"
        android:label="@string/menu_home"
        tools:layout="@layout/fragment_home" />

    <fragment
        android:id="@+id/nav_gallery"
        android:name="com.example.frangela.ui.gallery.GalleryFragment"
        android:label="@string/menu_gallery"
        tools:layout="@layout/fragment_gallery" />

    <fragment
        android:id="@+id/nav_slideshow"
        android:name="com.example.frangela.ui.slideshow.InserisciSpesaFragment"
        android:label="@string/menu_slideshow"
        tools:layout="@layout/fragment_inserisci" />
    <fragment
        android:id="@+id/nav_stipendio"
        android:name="com.example.frangela.ui.stipendio.InserisciStipendioFragment"
        android:label="@string/menu_stipendio"
        tools:layout="@layout/fragment_stipendio" />

    <fragment
        android:id="@+id/nav_resoconto"
        android:name="com.example.frangela.ui.resocard.ResocardFragment"
        android:label="@string/Resoconto"
        tools:layout="@layout/fragment_resocard" />

</navigation>

Thanks

Body:
you are creating new fragment

Fragment frag = new InserisciSpesaFragment();

and just after that you are trying to obtain an Activity from it

FragmentManager fm = frag.getActivity().getSupportFragmentManager();

this fragment isn't added to any Activity at the moment of this getActivity() call, you should get an NullPointerException in here... (crash, more than "nothing happens")

consider keeping reference to FragmentManager obtained in constructor

public class CardAdapter extends FirebaseRecyclerAdapter<Spesa, CardAdapter.cardViewholder> {

    private FragmentManager fm;

    // Constructor
    public CardAdapter(FragmentActivity activity, @NonNull FirebaseRecyclerOptions<Spesa> options){
        super(options);
        fm = activity.getSupportFragmentManager();
    }

and then in onClick just use it instead of trying to get it from not-added Fragment

       public void onClick(View v) {
            Fragment frag = new InserisciSpesaFragment();
            //FragmentManager fm = frag.getActivity().getSupportFragmentManager();
            fm.beginTransaction() // use fm obtained in constructor
                    .replace(R.id.nav_resoconto, frag)
                    .commit();
        }

btw. I doubt this code will work as R.id.nav_resoconto is an id of already declared fragment in XML. replace(...) method needs reference to fragment container view (in doc named containerViewId). read doc carefully for proper navigation switching


问:
Array is undefined when trying to push into it
I am trying to push into an array some values from a model.

public model: WeekDays[];

WeekDays is an enum of this type

```<code>export enum WeekDays {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday,
}
</code>```

So i have a save function which should do the following:

```<code>public save(){
        this.model.forEach(function (value){
            this.arr.push(WeekDays[value]);
        })
    }
</code>```

I want to get each element of the model and add the value of the days.
For example, if i have Monday and Tuesday in model, when performing

```<code>console.log(WeekDays[value])
</code>```

the output is

```<code>0
1
</code>```

And these values i want to add in my array but i get the "Cannot read properties of undefined (reading 'arr')" error.

The array is defined as

```<code>arr = Array(7);
</code>```

What i am doing wrong?

答:
You need to use => to declare your forEach callback.

Functions declared with => capture the value of this from the scope they were created in. function does not. So this is not what you think it is. It's most likely the global object, not your class instance.

Try this instead:

```<code>this.model.forEach((value) => {
  this.arr.push(WeekDays[value]);
})
</code>```

Body:
I am trying to push into an array some values from a model.

public model: WeekDays[];

WeekDays is an enum of this type

export enum WeekDays {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday,
}

So i have a save function which should do the following:

public save(){
        this.model.forEach(function (value){
            this.arr.push(WeekDays[value]);
        })
    }

I want to get each element of the model and add the value of the days.
For example, if i have Monday and Tuesday in model, when performing

console.log(WeekDays[value])

the output is

0
1

And these values i want to add in my array but i get the "Cannot read properties of undefined (reading 'arr')" error.

The array is defined as

arr = Array(7);

What i am doing wrong?

Body:
You need to use => to declare your forEach callback.

Functions declared with => capture the value of this from the scope they were created in. function does not. So this is not what you think it is. It's most likely the global object, not your class instance.

Try this instead:

this.model.forEach((value) => {
  this.arr.push(WeekDays[value]);
})


问:
deploy web site on IIS 7 with and without www prefix
I want to deploy website on IIS 7 with www and also without www prefix. Do I need to create twoo web sites in IIS. e.g. www.something.com and something.com or is there another option how can I do it only with one web site in IIS.

thanks

答: Create 1 website and add 2 host bindings. Using inetmgr, when you click on the website the bindings should be on the right side. You'd add two bindings with the same IP and different host name "www.host.com" and "host.com". You also need to make sure your DNS server has both host entries pointing to your websites IP.</p>


问:
OpenVINO GStreamer gvadetect is not applying model
I am super new to OpenVINO and GStreamer. I am trying to apply a pipeline in GStreamer plugin using OpenVINO. I downloaded the model as well it's proc files. I am trying to apply the model and it's proc to a video. For some reason I am not getting any output in the video.

I don't know how to debug the GStreamer pipeline. I added one text overlay for debugging and found out every step is working but the final output is not having any results. I get the same input video as output (with text overlay). Could anyone help me out here?

```<code># Model is downloaded from model downloader's downloader.py
# Model-proc is downloaded from
# https://github.com/openvinotoolkit/dlstreamer_gst/blob/master/samples/model_proc/intel/human_pose_estimation/human-pose-estimation-0001.json

VIDEO_FILE = 'HumanPoseEstimation/Sample_Video/face-demographics-walking.mp4'
ESTIMATION_MODEL = "HumanPoseEstimation/Models/intel/human-pose-estimation-0001/FP32/human-pose-estimation-0001.xml"
ESTIMATION_MODEL_PROC = "HumanPoseEstimation/Models/intel/human-pose-estimation-0001/human-post-estimation-0001-proc.json"
SINK_LOCATION = "HumanPoseEstimation/output.mp4"

# GStreamer pipeline
GST_PIPELINE = f'''
filesrc location={VIDEO_FILE}
! decodebin
! videoconvert
! queue
! gvaclassify model={ESTIMATION_MODEL} model-proc={ESTIMATION_MODEL_PROC} device=CPU
! queue
! textoverlay text="Human Pose Estimation"
! gvawatermark
! x264enc
! filesink location={SINK_LOCATION}
'''
</code>```

答:
You may be missing some part at the end of the pipeline for muxing into a mp4-compliant file container. You may try:</p>
```<code>...
! x264enc
! h264parse
! qtmux
! filesink location={SINK_LOCATION}
</code>```

Body:
I am super new to OpenVINO and GStreamer. I am trying to apply a pipeline in GStreamer plugin using OpenVINO. I downloaded the model as well it's proc files. I am trying to apply the model and it's proc to a video. For some reason I am not getting any output in the video.

I don't know how to debug the GStreamer pipeline. I added one text overlay for debugging and found out every step is working but the final output is not having any results. I get the same input video as output (with text overlay). Could anyone help me out here?

# Model is downloaded from model downloader's downloader.py
# Model-proc is downloaded from
# https://github.com/openvinotoolkit/dlstreamer_gst/blob/master/samples/model_proc/intel/human_pose_estimation/human-pose-estimation-0001.json

VIDEO_FILE = 'HumanPoseEstimation/Sample_Video/face-demographics-walking.mp4'
ESTIMATION_MODEL = "HumanPoseEstimation/Models/intel/human-pose-estimation-0001/FP32/human-pose-estimation-0001.xml"
ESTIMATION_MODEL_PROC = "HumanPoseEstimation/Models/intel/human-pose-estimation-0001/human-post-estimation-0001-proc.json"
SINK_LOCATION = "HumanPoseEstimation/output.mp4"

# GStreamer pipeline
GST_PIPELINE = f'''
filesrc location={VIDEO_FILE}
! decodebin
! videoconvert
! queue
! gvaclassify model={ESTIMATION_MODEL} model-proc={ESTIMATION_MODEL_PROC} device=CPU
! queue
! textoverlay text="Human Pose Estimation"
! gvawatermark
! x264enc
! filesink location={SINK_LOCATION}
'''

Body:
You may be missing some part at the end of the pipeline for muxing into a mp4-compliant file container. You may try:

...
! x264enc
! h264parse
! qtmux
! filesink location={SINK_LOCATION}


问:
fail2ban test send email
I am trying to test the sending of emails with fail2ban, apparently mta = mail should do the trick and I also tried the mail action. But I am not sure how to test if it is working. From what I read action_mwl sends email on start and stop, but it is not doing so. Could you please let me know how to test.
Thanks</p>

```<code>[default]
bantime  = 600
findtime = 300
banaction = ufw
banaction_allports = iptables-allports
destemail = XXXXXX@gmail.com
sendername = Fail2ban
mta = mail
action = %(action_mwl)s
         mail[name=ssh, dest=XXXXXX@gmail.com]

[sshd]
enabled = true
port = XXXXXX
filter = sshd
logpath = /var/log/auth.log
maxretry = 3

[postfix-sasl]
enabled  = true
findtime  = 10800
bantime = 7200
port     = smtp,465,587 submission,imap2,imap3,imaps,pop3,pop3s
filter   = postfix[mode=auth]
logpath  = /var/log/fail2ban-postfix.log
backend  = %(postfix_backend)s
maxretry = 2
</code>```

答:
This works - Feb 2022

A previous answer of mine was deleted, something I find to be a mistake to do.

The answer, gives a GOOD answer to the question, is a unique solution, where this won't be found on the web.

This solution regarding Fail2Ban is also a solution for ModSecurity Email alert notification, where for ModSecurity blocking a Fail2Ban filter-jail is configured, and then an email for such filter-jail enables the Fail2Ban alert notification for a ModSecurity event.

I have conducted a lot of tests to find the solution, which answers several asked questions.

The solution is to add a second action line with the content:

```<code>sendmail[mailcmd='/usr/sbin/sendmail -f "<sender>" "<dest>"', dest="email@recipient.com", sender="fail2ban", sendername="Fail2Ban", name="jail_name"]
</code>```

Title: fail2ban test send email

Body:
I am trying to test the sending of emails with fail2ban, apparently mta = mail should do the trick and I also tried the mail action. But I am not sure how to test if it is working. From what I read action_mwl sends email on start and stop, but it is not doing so. Could you please let me know how to test.
Thanks

[default]
bantime  = 600
findtime = 300
banaction = ufw
banaction_allports = iptables-allports
destemail = XXXXXX@gmail.com
sendername = Fail2ban
mta = mail
action = %(action_mwl)s
         mail[name=ssh, dest=XXXXXX@gmail.com]

[sshd]
enabled = true
port = XXXXXX
filter = sshd
logpath = /var/log/auth.log
maxretry = 3

[postfix-sasl]
enabled  = true
findtime  = 10800
bantime = 7200
port     = smtp,465,587 submission,imap2,imap3,imaps,pop3,pop3s
filter   = postfix[mode=auth]
logpath  = /var/log/fail2ban-postfix.log
backend  = %(postfix_backend)s
maxretry = 2

Body:
This works - Feb 2022

A previous answer of mine was deleted, something I find to be a mistake to do.

The answer, gives a GOOD answer to the question, is a unique solution, where this won't be found on the web.

This solution regarding Fail2Ban is also a solution for ModSecurity Email alert notification, where for ModSecurity blocking a Fail2Ban filter-jail is configured, and then an email for such filter-jail enables the Fail2Ban alert notification for a ModSecurity event.

I have conducted a lot of tests to find the solution, which answers several asked questions.

The solution is to add a second action line with the content:

sendmail[mailcmd='/usr/sbin/sendmail -f "<sender>" "<dest>"', dest="email@recipient.com", sender="fail2ban", sendername="Fail2Ban", name="jail_name"]


问:
Dictionary with tuple keys and two lists as values, where a value is added to just one of the lists
I have a set of integers in the form of a tuple forming my keys (a,b).
I need to construct a dictionary where, for each key, a value (float) is put in one of the two lists that acts as pair-value:

```<code>(a,b) : [x_list,y_list]
</code>```

I am constructing the dictionary from a txt file where each line has the tuple (a,b) and ONE of either x or y-type value that should be added to the list. However, I fail to understand how this can be done.

To be more precise:

if the txt file contains:

```<code>15,17,x_type,-1.1
15,17,y_type,44
1,2,y_type,-0.38
15,17,y_type,5
</code>```

the dictionary should produce

```<code>d: {(1,2): [[], [-0.38]] , (15,17): [[-1.1], [5,44]]
</code>```

What I am trying:

```<code>example = ['15,17,x_type,-1.1','15,17,y_type,44','1,2,y_type,-0.38','15,17,y_type,5']

for _ in example:
    [a,b,val_type,val] = _.split(',')
    if val_type == 'x_type':
       d[(a,b)] = [val,]
    if val_type == 'y_type':
       d[(a,b)] = [,val]
</code>```

The syntax allows for [x,], but does not for [,y]. Why?

答:
Lists can contain trailing commas. [x,] is the same as [x]. To append to a specific nested list, select the one you want by index:

```<code>if type == 'x_type':
   d[(a,b)][0].append(x)
elif type == 'y_type':
   d[(a,b)][1].append(y)
</code>```

This assumes that you make a new nested list as soon as you encounter a key:

```<code>if (a, b) not in d:
    d[a, b] = [[], []]
</code>```

Another nice syntactic trick is that anything with commas in an indexing expression is interpreted as a tuple. That means that you can write d[(a, b)] as d[a, b].

Body:
I have a set of integers in the form of a tuple forming my keys (a,b).
I need to construct a dictionary where, for each key, a value (float) is put in one of the two lists that acts as pair-value:

(a,b) : [x_list,y_list]

I am constructing the dictionary from a txt file where each line has the tuple (a,b) and ONE of either x or y-type value that should be added to the list. However, I fail to understand how this can be done.

To be more precise:

if the txt file contains:

15,17,x_type,-1.1
15,17,y_type,44
1,2,y_type,-0.38
15,17,y_type,5

the dictionary should produce

d: {(1,2): [[], [-0.38]] , (15,17): [[-1.1], [5,44]]

What I am trying:

example = ['15,17,x_type,-1.1','15,17,y_type,44','1,2,y_type,-0.38','15,17,y_type,5']

for _ in example:
    [a,b,val_type,val] = _.split(',')
    if val_type == 'x_type':
       d[(a,b)] = [val,]
    if val_type == 'y_type':
       d[(a,b)] = [,val]

The syntax allows for [x,], but does not for [,y]. Why?

Body:
Lists can contain trailing commas. [x,] is the same as [x]. To append to a specific nested list, select the one you want by index:

if type == 'x_type':
   d[(a,b)][0].append(x)
elif type == 'y_type':
   d[(a,b)][1].append(y)

This assumes that you make a new nested list as soon as you encounter a key:

if (a, b) not in d:
    d[a, b] = [[], []]

Another nice syntactic trick is that anything with commas in an indexing expression is interpreted as a tuple. That means that you can write d[(a, b)] as d[a, b].


问:
Show highlighted image in UITableViewCell
I have set an image and a background image to a UITableViewCell.
But when I click on it, it show the standard blue high-lightening and not mine.

Do you know how I can change this mecanism ?

Thanks, Niels

答:
Use this in your table view delegate:

```<code>- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.backgroundColor = [UIColor redColor];
}
</code>```

You can also set the cell's selectedBackgroundView to a custom view and set its backgroundColor.

Body:
Use this in your table view delegate:

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    cell.backgroundColor = [UIColor redColor];
}

You can also set the cell's selectedBackgroundView to a custom view and set its backgroundColor.


问:
json parse error in ajax return with an html comment
The attached image shows what is coming back from an ajax call to a PHP script.  The script builds the simple array that you see, and for some reason it adds the html comment before the array.

```<code><!-- translation function -->
</code>```

No idea where this is coming from, or what it is for. I'm just wondering what this is and if anyone has ever seen it before.  It is causing a json parse error, unexpected token <

Thanks!

答:
I don't know what it is and searched for it on Google, found no sensible results. So it is probably something related to your project or some tool that it uses. While you do not know the exact source yet, you can remove the comment of a JSON using a function like this:

function stripHTMLComments(json) {
    let parts = json.split('') >= 0) parts[index] = parts[index].substring(parts[index].indexOf('-->') + 3)
    }
    return parts.join("");
}

console.log(stripHTMLComments("{'a': 1, 'b': 2}"));```

Body:
The attached image shows what is coming back from an ajax call to a PHP script.  The script builds the simple array that you see, and for some reason it adds the html comment before the array.

No idea where this is coming from, or what it is for. I'm just wondering what this is and if anyone has ever seen it before.  It is causing a json parse error, unexpected token <

Thanks!

Body:
I don't know what it is and searched for it on Google, found no sensible results. So it is probably something related to your project or some tool that it uses. While you do not know the exact source yet, you can remove the comment of a JSON using a function like this:

function stripHTMLComments(json) {
    let parts = json.split('<!--');
    for (let index = 0; index < parts.length; index++) {
        if (parts[index].indexOf('-->') >= 0) parts[index] = parts[index].substring(parts[index].indexOf('-->') + 3)
    }
    return parts.join("");
}

console.log(stripHTMLComments("<!-- foobar -->{'a': 1, 'b': 2}"));


问:
Python: Why do i need to use pd.Timestamp. and datetime.datetime. to find difference in days between two dates
I'm trying to find the difference in two dates (today and dataframe cell) and if the difference is > than 2years I need to remove the relevant row from the dataframe.
I'm sure there is a better way than the one I have put together (it has taken me a few days to get this far).  I found a way that seems to work ok by using pd.Timestamp. and datetime.datetime.

My code is:

```<code># why do i need to use pd.Timestamp. and datetime.datetime.  ?
sd2 = pd.Timestamp.today().strftime('%d-%b-%y')
d2 = datetime.datetime.strptime(sd2, "%d-%b-%y")

# get data from xlsx file
path = (r"C:\Users\chris\Documents\UKHR\PythonSand\PY_Scripts\CleanModules\Racecards")
hist_file = "\RC_jkyhist_NaN.xlsx"
racecard_path = path + hist_file
df_hist = pd.read_excel(racecard_path)
df_hist = df_hist.dropna()          # Remove rows with NaN NaT
df_hist = df_hist.reset_index(drop=True) #clear index ready iterating

# remove all rows where the date is older than 2years, 365 x 2 = 730 days
# first replace the cell with NaT if date delta > 730
cnt = -1  # loc counter
for i in df_hist['RaceDate']:
    cnt = cnt + 1
    date_str = df_hist.loc[cnt, 'RaceDate']
    d1 = datetime.datetime.strptime(date_str, "%d-%b-%y")
    delta =  abs((d2 - d1).days)

    if delta > 730:
        df_hist.loc[cnt, 'RaceDate'] = pd.NaT
    else:
        df_hist.loc[cnt, 'RaceDate'] = df_hist.loc[cnt, 'RaceDate']

df_hist = df_hist.dropna()          # Remove rows with NaN NaT
df_hist = df_hist.reset_index(drop=True) #clear index ready for merging
print(df_hist)
</code>```

A sample of the xlsx file is (sorry I am not sure how to insert the table properly):

```<code>    Jockey  Code    Course  RaceDate    Ran FPos    TotalBtn
Harry Burns AW  Chelmsford City 01-Sep-18   9   4   4.5
Harry Burns AW  Newcastle   01-Oct-21   14  6   4.75
Harry Burns AW  Kempton 01-Nov-21   11  4   4.25
Harry Burns AW  Southwell   01-Jan-22   12  4   3.75
Harry Burns AW  Wolverhampton   01-Feb-22   12  5   4.75
Christian Howarth   AW  Kempton 01-Dec-21   14  5   3.5
Harry Davies    AW
Jonathan Fisher AW  Southwell   01-Dec-17   14  9   10.5
Jonathan Fisher AW  Chelmsford City 01-Dec-17   10  8   4.82
Jonathan Fisher AW  Southwell   01-Jan-22   12  5   7.75
Jonathan Fisher AW  Southwell   01-Jan-22   14  4   3
Jonathan Fisher AW  Wolverhampton   01-Feb-22   7   4   2
Jonathan Fisher AW  Wolverhampton   01-Feb-22   11  8   3
</code>```

答:
With some input from @enke on this post - Python: remove all rows from a dataframe where the date is over 2 years ago

Final code becomes:

```<code>import pandas as pd import datetime
# get data from xlsx file
path = (r"C:\Users\chris\Documents\UKHR\PythonSand\PY_Scripts\CleanModules\Racecards")
hist_file = "\RC_jkyhist_NaN.xlsx"
racecard_path = path + hist_file
df_hist = pd.read_excel(racecard_path)
df_hist = df_hist.dropna()          # Remove rows with NaN NaT

date_now = datetime.datetime.now().date()
df_hist['RaceDate'] = pd.to_datetime(df_hist['RaceDate'])

msk = df_hist['RaceDate'].rsub(pd.to_datetime(date_now)).astype('timedelta64[Y]') < 2

new_df = df_hist[msk]
</code>```

Body:
I'm trying to find the difference in two dates (today and dataframe cell) and if the difference is > than 2years I need to remove the relevant row from the dataframe.
I'm sure there is a better way than the one I have put together (it has taken me a few days to get this far).  I found a way that seems to work ok by using pd.Timestamp. and datetime.datetime.

My code is:

# why do i need to use pd.Timestamp. and datetime.datetime.  ?
sd2 = pd.Timestamp.today().strftime('%d-%b-%y')
d2 = datetime.datetime.strptime(sd2, "%d-%b-%y")

# get data from xlsx file
path = (r"C:\Users\chris\Documents\UKHR\PythonSand\PY_Scripts\CleanModules\Racecards")
hist_file = "\RC_jkyhist_NaN.xlsx"
racecard_path = path + hist_file
df_hist = pd.read_excel(racecard_path)
df_hist = df_hist.dropna()          # Remove rows with NaN NaT
df_hist = df_hist.reset_index(drop=True) #clear index ready iterating

# remove all rows where the date is older than 2years, 365 x 2 = 730 days
# first replace the cell with NaT if date delta > 730
cnt = -1  # loc counter
for i in df_hist['RaceDate']:
    cnt = cnt + 1
    date_str = df_hist.loc[cnt, 'RaceDate']
    d1 = datetime.datetime.strptime(date_str, "%d-%b-%y")
    delta =  abs((d2 - d1).days)

    if delta > 730:
        df_hist.loc[cnt, 'RaceDate'] = pd.NaT
    else:
        df_hist.loc[cnt, 'RaceDate'] = df_hist.loc[cnt, 'RaceDate']

df_hist = df_hist.dropna()          # Remove rows with NaN NaT
df_hist = df_hist.reset_index(drop=True) #clear index ready for merging
print(df_hist)

A sample of the xlsx file is (sorry I am not sure how to insert the table properly):

    Jockey  Code    Course  RaceDate    Ran FPos    TotalBtn
Harry Burns AW  Chelmsford City 01-Sep-18   9   4   4.5
Harry Burns AW  Newcastle   01-Oct-21   14  6   4.75
Harry Burns AW  Kempton 01-Nov-21   11  4   4.25
Harry Burns AW  Southwell   01-Jan-22   12  4   3.75
Harry Burns AW  Wolverhampton   01-Feb-22   12  5   4.75
Christian Howarth   AW  Kempton 01-Dec-21   14  5   3.5
Harry Davies    AW
Jonathan Fisher AW  Southwell   01-Dec-17   14  9   10.5
Jonathan Fisher AW  Chelmsford City 01-Dec-17   10  8   4.82
Jonathan Fisher AW  Southwell   01-Jan-22   12  5   7.75
Jonathan Fisher AW  Southwell   01-Jan-22   14  4   3
Jonathan Fisher AW  Wolverhampton   01-Feb-22   7   4   2
Jonathan Fisher AW  Wolverhampton   01-Feb-22   11  8   3

Body:
With some input from @enke on this post - Python: remove all rows from a dataframe where the date is over 2 years ago

Final code becomes:

import pandas as pd import datetime
# get data from xlsx file
path = (r"C:\Users\chris\Documents\UKHR\PythonSand\PY_Scripts\CleanModules\Racecards")
hist_file = "\RC_jkyhist_NaN.xlsx"
racecard_path = path + hist_file
df_hist = pd.read_excel(racecard_path)
df_hist = df_hist.dropna()          # Remove rows with NaN NaT

date_now = datetime.datetime.now().date()
df_hist['RaceDate'] = pd.to_datetime(df_hist['RaceDate'])

msk = df_hist['RaceDate'].rsub(pd.to_datetime(date_now)).astype('timedelta64[Y]') < 2

new_df = df_hist[msk]


问:
regex replace last occurance of number in between 2 chars javascript
I am trying to replace the last number of each match in between parenthesis.

so if I had cos(3 * 3)

before this regex

result = result.replace(/\d+(?:\.\d+)?/g, x => `${x}deg`)
```

would turn cos(3 * 3) into cos(3deg * 3deg)

I need only the last number to be changed to deg

So if  I had cos(3 * 3) + cos(3 * 2) it would be cos(3 * 3deg) + cos(3 * 2deg)

What regular expression magic could I use to do this.

答:
... /\((?<first>.*?)(?<last>[\d.]+)\)/g ...

// see ... [https://regex101.com/r/aDXe3B/1]
const regXLastNumberWithinParentheses =
  /\((?<first>.*?)(?<last>[\d.]+)\)/g;

const sampleData =
`cos(3 * 3) + cos(3 * 24.5), cos(2 * 3) + cos(3 * 2.4)
cos(3 * 3.4) + cos(3 * 45), cos(4 * 2) + cos(3 * 245)`;

console.log(
  sampleData.replace(
    regXLastNumberWithinParentheses,
    (match, first, last) => `(${ first }${ last }deg)`
  )
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { min-height: 100%!important; top: 0; }</code>```

1st Edit

Any idea why in this (3*(2+1+1)-12/5) is coming out as (3*(2+1+1deg)-12/5) it needs to match the last number regardless so it would be (3 *(2+1+1deg) - 23/5deg) – Nik Hendricks

@NikHendricks ... "Any idea why ...?" Yes of cause. Though the above regex matches anything and a final number in between parentheses, it does so just for un-nested parentheses (any nested structures can not be recognized). ... Question: Could one assume that the passed string does always feature validly nested parentheses? If yes, it leads to more straightforward regex replacement patterns because a regex then does not need to also validate the parentheses syntax. – Peter Seliger

... regex update ... /(?<![.\d])(?<number>\d*(?:\.\d+)?)\s*\)/g

// see ... [https://regex101.com/r/aDXe3B/2]
const regXLastNumberBeforeClosingParenthesis =
  /(?<![.\d])(?<number>\d*(?:\.\d+)?)\s*\)/g;

const sampleData =
`cos(3 * 3) + cos(3 * 24.5  ), cos(2 * 3  ) + cos(3 * 2.4)
cos(3 * 3.4) + cos(3 * 45  ), cos(4 * 2  ) + cos(3 * 245)

(3 * (2 + 1 + 1) - 23/5)`;

console.log(
  sampleData.replace(
    regXLastNumberBeforeClosingParenthesis,
    (match, number) => `${ number }deg)`
  )
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { min-height: 100%!important; top: 0; }</code>```

2nd Edit

for me the desired result for 3*(1571-sin(1 * 12)) would be 3*(1571deg -sin(1 * 12deg)) the last or only occurrence of a number is replaced with xdeg – Nik Hendricks

... regex update ... /(?<number>(?<!\.)\d+(?:\.\d+)?|(?<![\d.])(?:\.\d+)(?!\.))(?<termination>\s*[-+)])/g

// see ... [https://regex101.com/r/aDXe3B/3]
const regXValidNumberBeforePlusOrMinusOrClosingParenthesis =
  /(?<number>(?<!\.)\d+(?:\.\d+)?|(?<![\d.])(?:\.\d+)(?!\.))(?<termination>\s*[-+)])/g;

const sampleData =
`cos(3 * 3) + cos(3 * 24.5  ), cos(2 * 3  ) + cos(3 * .2.4)
cos(3 * 3.4) + cos(3 * 45  ), cos(4 * .24) + cos(3 * 245 )

(3 *(2 + 1 + 1) - 23/5 )

3 * (1571 - sin(12))`;

console.log(
  sampleData.replace(
    regXValidNumberBeforePlusOrMinusOrClosingParenthesis, '$1deg$2'
  )
);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { min-height: 100%!important; top: 0; }</code>```

Regarding the last iteration/edit ... in case number validation is not important (because the input is trusted), one of cause could achieve the same result with a less strict, thus simpler, regex which does not exclusively match valid numbers ... /(?<dotsAndDigits>[.\d]+)(?<termination>\s*[-+)])/g.

Body:
I am trying to replace the last number of each match in between parenthesis.

so if I had cos(3 * 3)

before this regex

result = result.replace(/\d+(?:\.\d+)?/g, x => `${x}deg`)

would turn cos(3 * 3) into cos(3deg * 3deg)

I need only the last number to be changed to deg

So if  I had cos(3 * 3) + cos(3 * 2) it would be cos(3 * 3deg) + cos(3 * 2deg)

What regular expression magic could I use to do this.

Body:
... /\((?<first>.*?)(?<last>[\d.]+)\)/g ...

// see ... [https://regex101.com/r/aDXe3B/1]
const regXLastNumberWithinParentheses =
  /\((?<first>.*?)(?<last>[\d.]+)\)/g;

const sampleData =
`cos(3 * 3) + cos(3 * 24.5), cos(2 * 3) + cos(3 * 2.4)
cos(3 * 3.4) + cos(3 * 45), cos(4 * 2) + cos(3 * 245)`;

console.log(
  sampleData.replace(
    regXLastNumberWithinParentheses,
    (match, first, last) => `(${ first }${ last }deg)`
  )
);

.as-console-wrapper { min-height: 100%!important; top: 0; }

1st Edit

Any idea why in this (3*(2+1+1)-12/5) is coming out as (3*(2+1+1deg)-12/5) it needs to match the last number regardless so it would be (3 *(2+1+1deg) - 23/5deg) – Nik Hendricks

@NikHendricks ... "Any idea why ...?" Yes of cause. Though the above regex matches anything and a final number in between parentheses, it does so just for un-nested parentheses (any nested structures can not be recognized). ... Question: Could one assume that the passed string does always feature validly nested parentheses? If yes, it leads to more straightforward regex replacement patterns because a regex then does not need to also validate the parentheses syntax. – Peter Seliger

... regex update ... /(?<![.\d])(?<number>\d*(?:\.\d+)?)\s*\)/g

// see ... [https://regex101.com/r/aDXe3B/2]
const regXLastNumberBeforeClosingParenthesis =
  /(?<![.\d])(?<number>\d*(?:\.\d+)?)\s*\)/g;

const sampleData =
`cos(3 * 3) + cos(3 * 24.5  ), cos(2 * 3  ) + cos(3 * 2.4)
cos(3 * 3.4) + cos(3 * 45  ), cos(4 * 2  ) + cos(3 * 245)

(3 * (2 + 1 + 1) - 23/5)`;

console.log(
  sampleData.replace(
    regXLastNumberBeforeClosingParenthesis,
    (match, number) => `${ number }deg)`
  )
);

.as-console-wrapper { min-height: 100%!important; top: 0; }

2nd Edit

for me the desired result for 3*(1571-sin(1 * 12)) would be 3*(1571deg -sin(1 * 12deg)) the last or only occurrence of a number is replaced with xdeg – Nik Hendricks

... regex update ... /(?<number>(?<!\.)\d+(?:\.\d+)?|(?<![\d.])(?:\.\d+)(?!\.))(?<termination>\s*[-+)])/g

// see ... [https://regex101.com/r/aDXe3B/3]
const regXValidNumberBeforePlusOrMinusOrClosingParenthesis =
  /(?<number>(?<!\.)\d+(?:\.\d+)?|(?<![\d.])(?:\.\d+)(?!\.))(?<termination>\s*[-+)])/g;

const sampleData =
`cos(3 * 3) + cos(3 * 24.5  ), cos(2 * 3  ) + cos(3 * .2.4)
cos(3 * 3.4) + cos(3 * 45  ), cos(4 * .24) + cos(3 * 245 )

(3 *(2 + 1 + 1) - 23/5 )

3 * (1571 - sin(12))`;

console.log(
  sampleData.replace(
    regXValidNumberBeforePlusOrMinusOrClosingParenthesis, '$1deg$2'
  )
);

.as-console-wrapper { min-height: 100%!important; top: 0; }

Regarding the last iteration/edit ... in case number validation is not important (because the input is trusted), one of cause could achieve the same result with a less strict, thus simpler, regex which does not exclusively match valid numbers ... /(?<dotsAndDigits>[.\d]+)(?<termination>\s*[-+)])/g.


问:
Download all blobs within an Azure Storage container
I've managed to write a python script to list out all the blobs within a container.

```<code>import azure
from azure.storage.blob import BlobService
from azure.storage import *

blob_service = BlobService(account_name='<CONTAINER>', account_key='<ACCOUNT_KEY>')

blobs = []
marker = None
while True:
    batch = blob_service.list_blobs('<CONAINER>', marker=marker)
    blobs.extend(batch)
    if not batch.next_marker:
        break
    marker = batch.next_marker
for blob in blobs:
    print(blob.name)
</code>```

Like I said this only lists the blobs that I want to download. I've moved onto the Azure CLI to see if that could aid in what I want to do. I'm able to download a single blob with

```<code>azure storage blob download [container]
</code>```

it then prompts me specify a blob which I can grab from the python script. The way I would have to download all those blobs is to copy and paste them into the prompt after the command used above. Is there a way I can either:

A. Write a bash script to iterate through the list of blobs by executing the command, then pasting the next blob name in the prompt.

B. Specify to download the container in either the python script or Azure CLI. Is there something I'm not seeing to download the whole container?

答:
Here is a simple script (PowerShell) that will iterate through a single container and download everything in there to the $Destination you provide

#
# Download All Blobs in a Container
#

# Connect to Azure Account
Connect-AzAccount

# Set Variables
$Destination="C:\Software"
$ResourceGroupName = 'resource group name'
$ContainerName = 'container name'
$storageAccName = 'storage account name'

# Function to download all blob contents
Function DownloadBlobContents
{
    Write-Host -ForegroundColor Green "Download blob contents from storage container.."
    # Get the storage account
    $StorageAcc = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccName
    # Get the storage account context
    $Ctx = $StorageAcc.Context
    # Get all containers
    $Containers = Get-AzStorageContainer -Context $Ctx
    Write-Host -ForegroundColor Magenta $Container.Name "Creating or checking folder presence"
    # Create or check folder presence
    New-Item -ItemType Directory -Path $Destination -Force
    # Get the blob contents from the container
    $BlobConents = Get-AzStorageBlob -Container $ContainerName -Context $Ctx
    # Loop through each blob and download each one until they are all complete
    foreach($BlobConent in $BlobConents)
    {
        # Download the blob content
        Get-AzStorageBlobContent -Container $ContainerName -Context $Ctx -Blob $BlobConent.Name -Destination $Destination -Force
        Write-Host -ForegroundColor Green "Downloaded a blob content"
    }
}

DownloadBlobContents```

Something I would like to learn is to not have to use the Connect-AzAccount but instead call the keys to the storage account therefore I can run this without having to authenticate in

Body:
I've managed to write a python script to list out all the blobs within a container.

import azure
from azure.storage.blob import BlobService
from azure.storage import *

blob_service = BlobService(account_name='<CONTAINER>', account_key='<ACCOUNT_KEY>')

blobs = []
marker = None
while True:
    batch = blob_service.list_blobs('<CONAINER>', marker=marker)
    blobs.extend(batch)
    if not batch.next_marker:
        break
    marker = batch.next_marker
for blob in blobs:
    print(blob.name)

Like I said this only lists the blobs that I want to download. I've moved onto the Azure CLI to see if that could aid in what I want to do. I'm able to download a single blob with

azure storage blob download [container]

it then prompts me specify a blob which I can grab from the python script. The way I would have to download all those blobs is to copy and paste them into the prompt after the command used above. Is there a way I can either:

A. Write a bash script to iterate through the list of blobs by executing the command, then pasting the next blob name in the prompt.

B. Specify to download the container in either the python script or Azure CLI. Is there something I'm not seeing to download the whole container?

Body:
Here is a simple script (PowerShell) that will iterate through a single container and download everything in there to the $Destination you provide

#
# Download All Blobs in a Container
#

# Connect to Azure Account
Connect-AzAccount

# Set Variables
$Destination="C:\Software"
$ResourceGroupName = 'resource group name'
$ContainerName = 'container name'
$storageAccName = 'storage account name'

# Function to download all blob contents
Function DownloadBlobContents
{
    Write-Host -ForegroundColor Green "Download blob contents from storage container.."
    # Get the storage account
    $StorageAcc = Get-AzStorageAccount -ResourceGroupName $resourceGroupName -Name $storageAccName
    # Get the storage account context
    $Ctx = $StorageAcc.Context
    # Get all containers
    $Containers = Get-AzStorageContainer -Context $Ctx
    Write-Host -ForegroundColor Magenta $Container.Name "Creating or checking folder presence"
    # Create or check folder presence
    New-Item -ItemType Directory -Path $Destination -Force
    # Get the blob contents from the container
    $BlobConents = Get-AzStorageBlob -Container $ContainerName -Context $Ctx
    # Loop through each blob and download each one until they are all complete
    foreach($BlobConent in $BlobConents)
    {
        # Download the blob content
        Get-AzStorageBlobContent -Container $ContainerName -Context $Ctx -Blob $BlobConent.Name -Destination $Destination -Force
        Write-Host -ForegroundColor Green "Downloaded a blob content"
    }
}

DownloadBlobContents

Something I would like to learn is to not have to use the Connect-AzAccount but instead call the keys to the storage account therefore I can run this without having to authenticate in


问:
Removing event listeners before closing a module
I add an instance of this module to the dispay list and then remove it.
Will the event listener attached to foo create a leak?
A simplified module:</p>

```<code><s:Module creationComplete="init()">
    <fx:Script>
        protected var foo:Bar = new Bar();
        protected function init() {
          foo.addEventListener(MouseEvent.CLICK, foo_clickHandler);
        }

        protected function foo_clickHandler(event:MouseEvent):void {
            //do something
        }
    </fx:Script>
</s:Module>
</code>```

答:
It will. You should remove the listener, or use weak references when creating the listener.</p>

```<code>foo.addEventListener(MouseEvent.CLICK, foo_clickHandler, false, 0, true);
</code>```

Body:
I add an instance of this module to the dispay list and then remove it.
Will the event listener attached to foo create a leak?
A simplified module:

<s:Module creationComplete="init()">
    <fx:Script>
        protected var foo:Bar = new Bar();
        protected function init() {
          foo.addEventListener(MouseEvent.CLICK, foo_clickHandler);
        }

        protected function foo_clickHandler(event:MouseEvent):void {
            //do something
        }
    </fx:Script>
</s:Module>

Body:
It will. You should remove the listener, or use weak references when creating the listener.

foo.addEventListener(MouseEvent.CLICK, foo_clickHandler, false, 0, true);


问:
Delete all tables in one shot in Ms access
Here is my VBA code, which tries to loop through all the tables which contains PB (PB is the first two letters of all of the tables) in their name and delete them. I get the error msg at DoCmd line

```<code>Option Compare Database
Option Explicit

Public Sub del_all_tables()
   Dim db As DAO.Database
   Dim tdf As DAO.TableDef
   Set db = CurrentDb

   For Each tdf In db.TableDefs
       If Not (tdf.Name Like "PB*") Then
           DoCmd.DeleteObject acTable, tdf.Name
       End If
   Next
End Sub
</code>```

Edit: I would like to not to delete the tables itself but delete the records inside the tables

答:
My original code is to delete the all the tables what did not work. I took the source from here.  https://access-excel.tips/access-vba-loop-through-all-tables/

But if you would like to delete all the records in multiple tables with one shot, you need to create delete queries for each table separately.

Then you can use VBA to  openeach query and run with the following code:

```<code>Option Compare Database
Option Explicit

Public Function RunMyqueries()
DoCmd.OpenQuery "Query1"
DoCmd.OpenQuery "Query2"

MsgBox "Done!"

End Function
</code>```

In my case I have 2 queries, if you have more just continue added them.

Also, you might want to turn off the Warning everytime before deleting the records with  DoCmd.SetWarnings False

Body:
Here is my VBA code, which tries to loop through all the tables which contains PB (PB is the first two letters of all of the tables) in their name and delete them. I get the error msg at DoCmd line

Option Compare Database
Option Explicit

Public Sub del_all_tables()
   Dim db As DAO.Database
   Dim tdf As DAO.TableDef
   Set db = CurrentDb

   For Each tdf In db.TableDefs
       If Not (tdf.Name Like "PB*") Then
           DoCmd.DeleteObject acTable, tdf.Name
       End If
   Next
End Sub

Edit: I would like to not to delete the tables itself but delete the records inside the tables

Body:
My original code is to delete the all the tables what did not work. I took the source from here.  https://access-excel.tips/access-vba-loop-through-all-tables/

But if you would like to delete all the records in multiple tables with one shot, you need to create delete queries for each table separately.

Then you can use VBA to  openeach query and run with the following code:

Option Compare Database
Option Explicit

Public Function RunMyqueries()
DoCmd.OpenQuery "Query1"
DoCmd.OpenQuery "Query2"

MsgBox "Done!"

End Function

In my case I have 2 queries, if you have more just continue added them.

Also, you might want to turn off the Warning everytime before deleting the records with  DoCmd.SetWarnings False


问:
Oracle convert hhmmss to hh:mm:ss
I have some timestamp data in an old Oracle database that needs converting into HH:MM:SS. After trying to use to_char function, the value I give is not readable (E.g. 105001, to_char('105001','HH24:MI:SS)), this SQL will break. I can convert sysdate into the incorrect format but I can't reverse the procedure.

For example:

```<code>select to_char(sysdate, 'HHmiss')from table
</code>```

returns '105001'

I need something that will convert the hhmmss format into HH:MM:SS so when I produce a select statement it is in a readable format.

答:
Assuming that your values are a NUMBER in the database which is six-digits long and represents an HHMMSS value you can format it as you want by using SUBSTR:

```<code>SELECT SUBSTR(TO_CHAR(SOME_TIMESTAMP, 'FM000000'), 1, 2) || ':' ||
       SUBSTR(TO_CHAR(SOME_TIMESTAMP, 'FM000000'), 3, 2) || ':' ||
       SUBSTR(TO_CHAR(SOME_TIMESTAMP, 'FM000000'), 5, 2)
  FROM cteNumbers
</code>```

db<>fiddle here

Title: Oracle convert hhmmss to hh:mm:ss

Body:
I have some timestamp data in an old Oracle database that needs converting into HH:MM:SS. After trying to use to_char function, the value I give is not readable (E.g. 105001, to_char('105001','HH24:MI:SS)), this SQL will break. I can convert sysdate into the incorrect format but I can't reverse the procedure.

For example:

select to_char(sysdate, 'HHmiss')from table

returns '105001'

I need something that will convert the hhmmss format into HH:MM:SS so when I produce a select statement it is in a readable format.

Body:
Assuming that your values are a NUMBER in the database which is six-digits long and represents an HHMMSS value you can format it as you want by using SUBSTR:

SELECT SUBSTR(TO_CHAR(SOME_TIMESTAMP, 'FM000000'), 1, 2) || ':' ||
       SUBSTR(TO_CHAR(SOME_TIMESTAMP, 'FM000000'), 3, 2) || ':' ||
       SUBSTR(TO_CHAR(SOME_TIMESTAMP, 'FM000000'), 5, 2)
  FROM cteNumbers

db<>fiddle here


问:
How can define an enum for Shape with defined and custom shapes
If we look to clipShape modifier .clipShape(shape: Shape) it is a function that takes a shape and do it works! I have no problem to adapt this kind input value of usage in my codes, the thing that I am looking is an enum type parameter, for example I want that I be able use ShapeType.circle for referencing to Circle() or ShapeType.rectangle for Rectangle() and also having a case for custom shape as well.
What I tried so for is like this:

```<code>extension View {

    // Issue is here!!! Reference to generic type 'ShapeType' requires arguments in <...>

    func backShape(shape: ShapeType) -> some View {

    return self
            .background(shape.fill(Color.red))
    }
}

enum ShapeType<ShapeContent: Shape> {
    case circle
    case rectangle
    case custom(shape: ShapeContent)
}
</code>```

having cases of circle or rectangle makes no issue, but having a case for custom shape make issue because I need to access the Shape protocol as ShapeContent. And that make issue for use case in function parameter! Xcode asking for Shape type or kind before get decided from user or developer, I fully understand the issue and I know why that happens, but I cannot help myself to use my approach for making my goal of enum shape for function parameter.

答:
Enums do not work for this in Swift. That is why SE-0299 came about—to emulate what code would look like if enums could do what you want.

func backShape<Shape: SwiftUI.Shape>(_ shape: Shape) -> some View {
  background(shape.fill(Color.red))
}
```
<pre class="lang-swift prettyprint-override"><code>extension Shape where Self == Circle {
  static var circle: Self { .init() }
}

extension Shape where Self == Rectangle {
  static var rectangle: Self { .init() }
}
</code>```

backShape(.circle)
backShape(.rectangle)
backShape(RoundedRectangle(cornerSize: 10))
```

Body:
If we look to clipShape modifier .clipShape(shape: Shape) it is a function that takes a shape and do it works! I have no problem to adapt this kind input value of usage in my codes, the thing that I am looking is an enum type parameter, for example I want that I be able use ShapeType.circle for referencing to Circle() or ShapeType.rectangle for Rectangle() and also having a case for custom shape as well.
What I tried so for is like this:

extension View {

    // Issue is here!!! Reference to generic type 'ShapeType' requires arguments in <...>

    func backShape(shape: ShapeType) -> some View {

    return self
            .background(shape.fill(Color.red))
    }
}

enum ShapeType<ShapeContent: Shape> {
    case circle
    case rectangle
    case custom(shape: ShapeContent)
}

having cases of circle or rectangle makes no issue, but having a case for custom shape make issue because I need to access the Shape protocol as ShapeContent. And that make issue for use case in function parameter! Xcode asking for Shape type or kind before get decided from user or developer, I fully understand the issue and I know why that happens, but I cannot help myself to use my approach for making my goal of enum shape for function parameter.

Body:
Enums do not work for this in Swift. That is why SE-0299 came about—to emulate what code would look like if enums could do what you want.

func backShape<Shape: SwiftUI.Shape>(_ shape: Shape) -> some View {
  background(shape.fill(Color.red))
}

extension Shape where Self == Circle {
  static var circle: Self { .init() }
}

extension Shape where Self == Rectangle {
  static var rectangle: Self { .init() }
}

backShape(.circle)
backShape(.rectangle)
backShape(RoundedRectangle(cornerSize: 10))