问:
Hexo - why can't I use nbsp to insert space
I just want to insert some space in a markdown file with "& nbsp;", but it doesn't work while hexo displays the page.

My code:

```<code>1   2   8  9
2   4   9   12
4   7   10   13
5   8   11   15
</code>```

The hexo page

So, why doesn't "& nbsp;" work?

答:
Source and rendered page.

I'm using hexo-renderer-markdown-it and it can correctly renderer  .

Body:
I just want to insert some space in a markdown file with "& nbsp;", but it doesn't work while hexo displays the page.

My code:

1   2   8  9
2   4   9   12
4   7   10   13
5   8   11   15

The hexo page

So, why doesn't "& nbsp;" work?

Body:
Source and rendered page.

I'm using hexo-renderer-markdown-it and it can correctly renderer &nbsp;.


来源: stackexchange

问:
NjsonSchema Validation If Property1 is equal to Something then require Property2
I seem to not be able to get const or enum working as part of an if-then-else JSON schema validation.

They seem to be interchangeable when 1 validation value is concerned. (Reference)

Here is my JSON schema

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "title": "Test_Schema",
      "description": "A schema for validating a test object",
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "GeneralData": {
          "type": "object",
          "description": "Advsor and admin customer information",
          "properties": {
            "Name": {
              "type": [ "string", "null" ],
              "description": "Customer's advisor name"
            },
            "Age": {
              "type": [ "string", "null" ],
              "description": "Customer's advisor email"
            },
            "Location": {
              "type": [ "string", "null" ],
              "description": "The advisor's manager email'"
            }
          },
          "required": [ "Name", "Location", "Age" ]
        },
        "ClientData": {
          "type": "object",
          "description": "Customer's information",
          "additionalProperties": false,
          "properties": {
            "Title": {
              "type": [ "string", "null" ]
            },
            "Forename": {
              "type": [ "string", "null" ]
            },
            "Surname": {
              "type": [ "string" ]
            }
          },
          "required": [ "Title" ],
          "if": {
            "properties": {
              "Forename": { "enum": [ "Soameonea" ] }
            },
            "required": [ "Forename" ]
          },
          "then": { "required": [ "Surname" ] },
          "else": false
        }
      }
    }
```
<p>If Forename = "Someone" I want Surname to be required.</p>
<p>Here is my jsonObject after serialization:</p>
```     {
        "GeneralData": {
            "Name": "Not Relevant",
            "Age": "Not Relevant",
            "Location": "Not Relevant"
        },
        "ClientData": {
            "Title": "SomeTitle",
            "Forename": "Someone",
            "Surname": null
        }
    }
```
<p>Validation code:</p>
```     internal void ValidateDataObjectOnSchema()
            {
                var dataObject = PopulateDataObject();
                var json = JsonConvert.SerializeObject(dataObject);
                var result = GetSchema().Validate(json);
                var errors = result.Select(x =>
                {
                    return new Errors() { Title = x.Property, Description = x.Schema.Description };
                });
                var i = errors;

            }

      internal JsonSchema GetSchema()
            {
                return JsonSchema.FromFileAsync("Test/testSchema.json").Result;
            }
```

Right now it still requires Surname, even though the enum Soameonea != Someone and I only require Title. <== Issue1

In the JSON schema if I set "Surname":{"type":["string","null]} then the error disappears and still I don't get the error if I then change the if condition for the Forename enum to "Someone". <== Issue 2

I cannot get a different validation output if I replace Enum with Const, So if I can get one to work I'm sure the other will follow.

I've found several answers to this question (Answer 1), I try to implement the same thing and for some reason, it fails in my case.

What am I missing?

答:
Update:
As @Relequestial mentioned in one of the comments it seems NJson Schema only supports up to Draft 04, this is why if-then-else did not work and implication should be used instead. Below is my solution with an alternative package.

The same code and json work with the package Newtonsoft.Json.Schema (Reference)

Code:

```<code>  internal void ValidateDataObjectOnSchemaWithNewtonSoftJson()
        {
            var dataObject = PopulateDataObject();
            var settings = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore

            };
            var jsonDataObjectString = JsonConvert.SerializeObject(dataObject, settings);
            JObject jsonDataObject = JObject.Parse(jsonDataObjectString);
            var jsonSchemaFile = File.ReadAllText("Test/testSchema.json");
            var schema = JSchema.Parse(jsonSchemaFile);
            ;
            IList<ValidationError> messages;
            var result = jsonDataObject.IsValid(schema, out messages);
            var errors = GetReadableResult(result, messages);

        }

        private List<Errors> GetReadableResult(bool result, IList<ValidationError> messages)
        {
            var errors = new List<Errors>();

            if (!result)
            {
                foreach (var error in messages)
                {
                    if (error.ChildErrors.Count > 0)
                    {
                        errors.Add(
                            new Errors()
                            {
                                Path = error.ChildErrors.FirstOrDefault()?.Path,
                                Kind = error.ChildErrors.FirstOrDefault()?.Message
                            });
                    }
                    else
                    {
                        errors.Add(new Errors()
                        {
                            Path = error.Path,
                            Kind = error.Message
                        });
                    }
                }
            }

            return errors;
        }
</code>```

JsonSchema:

```<code>{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Test_Schema",
  "description": "A schema for validating a test object",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "GeneralData": {
      "type": "object",
      "description": "Advsor and admin customer information",
      "properties": {
        "Name": {
          "type": [ "string", "null" ],
          "description": "Customer's advisor name"
        },
        "Age": {
          "type": [ "string", "null" ],
          "description": "Customer's advisor email"
        },
        "Location": {
          "type": [ "string", "null" ],
          "description": "The advisor's manager email'"
        }
      },
      "required": [ "Name", "Location", "Age" ]
    },
    "ClientData": {
      "type": "object",
      "description": "Customer's information",
      "additionalProperties": false,
      "properties": {
        "Title": {
          "type": [ "string", "null" ]
        },
        "Forename": {
          "type": "string"
        },
        "Surname": {
          "type": [ "string" ]
        }
      },
      "required": [ "Title" ],
      "if": {
        "properties": {
          "Forename": { "enum": [ "Someone" ] }
        },
        "required": [ "Forename" ]
      },
      "then": { "required": [ "Surname" ] },
      "else": {}
    }
  }
}
</code>```

The only addition would be to make the GetReadableResult recursive for Errors which have multiple child items.

ContentLicense: CC BY-SA 4.0

Body:
I seem to not be able to get const or enum working as part of an if-then-else JSON schema validation.

They seem to be interchangeable when 1 validation value is concerned. (Reference)

Here is my JSON schema

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "title": "Test_Schema",
      "description": "A schema for validating a test object",
      "type": "object",
      "additionalProperties": false,
      "properties": {
        "GeneralData": {
          "type": "object",
          "description": "Advsor and admin customer information",
          "properties": {
            "Name": {
              "type": [ "string", "null" ],
              "description": "Customer's advisor name"
            },
            "Age": {
              "type": [ "string", "null" ],
              "description": "Customer's advisor email"
            },
            "Location": {
              "type": [ "string", "null" ],
              "description": "The advisor's manager email'"
            }
          },
          "required": [ "Name", "Location", "Age" ]
        },
        "ClientData": {
          "type": "object",
          "description": "Customer's information",
          "additionalProperties": false,
          "properties": {
            "Title": {
              "type": [ "string", "null" ]
            },
            "Forename": {
              "type": [ "string", "null" ]
            },
            "Surname": {
              "type": [ "string" ]
            }
          },
          "required": [ "Title" ],
          "if": {
            "properties": {
              "Forename": { "enum": [ "Soameonea" ] }
            },
            "required": [ "Forename" ]
          },
          "then": { "required": [ "Surname" ] },
          "else": false
        }
      }
    }

If Forename = "Someone" I want Surname to be required.

Here is my jsonObject after serialization:

     {
        "GeneralData": {
            "Name": "Not Relevant",
            "Age": "Not Relevant",
            "Location": "Not Relevant"
        },
        "ClientData": {
            "Title": "SomeTitle",
            "Forename": "Someone",
            "Surname": null
        }
    }

Validation code:

     internal void ValidateDataObjectOnSchema()
            {
                var dataObject = PopulateDataObject();
                var json = JsonConvert.SerializeObject(dataObject);
                var result = GetSchema().Validate(json);
                var errors = result.Select(x =>
                {
                    return new Errors() { Title = x.Property, Description = x.Schema.Description };
                });
                var i = errors;

            }

      internal JsonSchema GetSchema()
            {
                return JsonSchema.FromFileAsync("Test/testSchema.json").Result;
            }

Right now it still requires Surname, even though the enum Soameonea != Someone and I only require Title. <== Issue1

In the JSON schema if I set "Surname":{"type":["string","null]} then the error disappears and still I don't get the error if I then change the if condition for the Forename enum to "Someone". <== Issue 2

I cannot get a different validation output if I replace Enum with Const, So if I can get one to work I'm sure the other will follow.

I've found several answers to this question (Answer 1), I try to implement the same thing and for some reason, it fails in my case.

What am I missing?

Body:
Update:
As @Relequestial mentioned in one of the comments it seems NJson Schema only supports up to Draft 04, this is why if-then-else did not work and implication should be used instead. Below is my solution with an alternative package.

The same code and json work with the package Newtonsoft.Json.Schema (Reference)

Code:

  internal void ValidateDataObjectOnSchemaWithNewtonSoftJson()
        {
            var dataObject = PopulateDataObject();
            var settings = new JsonSerializerSettings()
            {
                NullValueHandling = NullValueHandling.Ignore

            };
            var jsonDataObjectString = JsonConvert.SerializeObject(dataObject, settings);
            JObject jsonDataObject = JObject.Parse(jsonDataObjectString);
            var jsonSchemaFile = File.ReadAllText("Test/testSchema.json");
            var schema = JSchema.Parse(jsonSchemaFile);
            ;
            IList<ValidationError> messages;
            var result = jsonDataObject.IsValid(schema, out messages);
            var errors = GetReadableResult(result, messages);

        }

        private List<Errors> GetReadableResult(bool result, IList<ValidationError> messages)
        {
            var errors = new List<Errors>();

            if (!result)
            {
                foreach (var error in messages)
                {
                    if (error.ChildErrors.Count > 0)
                    {
                        errors.Add(
                            new Errors()
                            {
                                Path = error.ChildErrors.FirstOrDefault()?.Path,
                                Kind = error.ChildErrors.FirstOrDefault()?.Message
                            });
                    }
                    else
                    {
                        errors.Add(new Errors()
                        {
                            Path = error.Path,
                            Kind = error.Message
                        });
                    }
                }
            }

            return errors;
        }

JsonSchema:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Test_Schema",
  "description": "A schema for validating a test object",
  "type": "object",
  "additionalProperties": false,
  "properties": {
    "GeneralData": {
      "type": "object",
      "description": "Advsor and admin customer information",
      "properties": {
        "Name": {
          "type": [ "string", "null" ],
          "description": "Customer's advisor name"
        },
        "Age": {
          "type": [ "string", "null" ],
          "description": "Customer's advisor email"
        },
        "Location": {
          "type": [ "string", "null" ],
          "description": "The advisor's manager email'"
        }
      },
      "required": [ "Name", "Location", "Age" ]
    },
    "ClientData": {
      "type": "object",
      "description": "Customer's information",
      "additionalProperties": false,
      "properties": {
        "Title": {
          "type": [ "string", "null" ]
        },
        "Forename": {
          "type": "string"
        },
        "Surname": {
          "type": [ "string" ]
        }
      },
      "required": [ "Title" ],
      "if": {
        "properties": {
          "Forename": { "enum": [ "Someone" ] }
        },
        "required": [ "Forename" ]
      },
      "then": { "required": [ "Surname" ] },
      "else": {}
    }
  }
}

The only addition would be to make the GetReadableResult recursive for Errors which have multiple child items.


问:
JUnit test case for Camel route for ActiveMQ
I have a camel route in MyRouteBuilder.java file which is consuming messages from ActiveMQ:

```<code>from("activemq:queue:myQueue" )
.process(consumeDroppedMessage)
.log(">>> I am here");
</code>```

I wrote a test case for the following like this :

@Override
public RouteBuilder createRouteBuilder() throws Exception {
    return new MyRouteBuilder();
}

@Test
void testMyTest() throws Exception {
    String queueInputMessage = "My Msg";
    template.sendBody("activemq:queue:myQueue", queueInputMessage);
    assertMockEndpointsSatisfied();

}
```
<p>When I run the unit test case I get this strange error:</p>
```7:53:26.175 [main] DEBUG org.apache.camel.impl.engine.InternalRouteStartupManager - Route: route1 >>> Route[activemq://queue:null -> null]
17:53:26.175 [main] DEBUG org.apache.camel.impl.engine.InternalRouteStartupManager - Starting consumer (order: 1000) on route: route1
17:53:26.175 [main] DEBUG org.apache.camel.support.DefaultConsumer - Build consumer: Consumer[activemq://queue:null]
17:53:26.185 [main] DEBUG org.apache.camel.support.DefaultConsumer - Init consumer: Consumer[activemq://queue:null]
17:53:26.185 [main] DEBUG org.apache.camel.support.DefaultConsumer - Starting consumer: Consumer[activemq://queue:null]
17:53:26.213 [main] DEBUG org.apache.activemq.thread.TaskRunnerFactory - Initialized TaskRunnerFactory[ActiveMQ Task] using ExecutorService: java.util.concurrent.ThreadPoolExecutor@3fffff43[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
17:53:26.215 [main] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Reconnect was triggered but transport is not started yet. Wait for start to connect the transport.
17:53:26.334 [main] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Started unconnected
17:53:26.334 [main] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Waking up reconnect task
17:53:26.335 [ActiveMQ Task-1] DEBUG org.apache.activemq.transport.failover.FailoverTransport - urlList connectionList:[tcp://localhost:61616], from: [tcp://localhost:61616]
17:53:26.339 [main] DEBUG org.apache.camel.component.jms.DefaultJmsMessageListenerContainer - Established shared JMS Connection
17:53:26.340 [main] DEBUG org.apache.camel.component.jms.DefaultJmsMessageListenerContainer - Resumed paused task: org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker@58c34bb3
17:53:26.372 [ActiveMQ Task-1] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Attempting 0th connect to: tcp://localhost:61616
17:53:28.393 [ActiveMQ Task-1] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Connect fail to: tcp://localhost:61616, reason: {}
```
<p>I am especially stumped to see these messages:</p>
```Route: route1 >>> Route[activemq://queue:null -> null]
```
<p>and</p>
```urlList connectionList:[tcp://localhost:61616], from: [tcp://localhost:61616]
```

Why is the queue coming up as null though I have a proper queue name? Also why is the broker url tcp://localhost:61616?

I want to run this unit test case so that it runs properly in all environments like: local,  DIT , SIT, PROD etc. So, for that I cannot afford the broker url to be: tcp://localhost:61616.

Any ideas as to what I am doing wrong here and what I should be doing?

EDIT 1:

One of the issues that I am seeing is even before the test class is called, the MyRouteBuilder() inside createRouteBuilder() is invoked, leading to the issues that I see in the log.

答:
Instead of setting up an explicit active mq broker , I started using a VM broker .

```<code>@Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() {
                ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
                ActiveMQComponent activeMQComponent = new ActiveMQComponent();
                activeMQComponent.setConnectionFactory(connectionFactory);
                context.addComponent("activemq", activeMQComponent);
                from("activemq:queue:myQueue").to("mock:collector");
            }
        };
    }
</code>```

Also , I mistook camel junit as a traditional junit . We don't need to call explicitly the actual route builder class . Instead after setting up my activeMq component up above , I was able to write my test methods, mock my end points for queue and send messages and assert them . Camel is truly versatile . Requires a lot of study though .

Body:
I have a camel route in MyRouteBuilder.java file which is consuming messages from ActiveMQ:

from("activemq:queue:myQueue" )
.process(consumeDroppedMessage)
.log(">>> I am here");

I wrote a test case for the following like this :

@Override
public RouteBuilder createRouteBuilder() throws Exception {
    return new MyRouteBuilder();
}

@Test
void testMyTest() throws Exception {
    String queueInputMessage = "My Msg";
    template.sendBody("activemq:queue:myQueue", queueInputMessage);
    assertMockEndpointsSatisfied();

}

When I run the unit test case I get this strange error:

7:53:26.175 [main] DEBUG org.apache.camel.impl.engine.InternalRouteStartupManager - Route: route1 >>> Route[activemq://queue:null -> null]
17:53:26.175 [main] DEBUG org.apache.camel.impl.engine.InternalRouteStartupManager - Starting consumer (order: 1000) on route: route1
17:53:26.175 [main] DEBUG org.apache.camel.support.DefaultConsumer - Build consumer: Consumer[activemq://queue:null]
17:53:26.185 [main] DEBUG org.apache.camel.support.DefaultConsumer - Init consumer: Consumer[activemq://queue:null]
17:53:26.185 [main] DEBUG org.apache.camel.support.DefaultConsumer - Starting consumer: Consumer[activemq://queue:null]
17:53:26.213 [main] DEBUG org.apache.activemq.thread.TaskRunnerFactory - Initialized TaskRunnerFactory[ActiveMQ Task] using ExecutorService: java.util.concurrent.ThreadPoolExecutor@3fffff43[Running, pool size = 0, active threads = 0, queued tasks = 0, completed tasks = 0]
17:53:26.215 [main] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Reconnect was triggered but transport is not started yet. Wait for start to connect the transport.
17:53:26.334 [main] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Started unconnected
17:53:26.334 [main] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Waking up reconnect task
17:53:26.335 [ActiveMQ Task-1] DEBUG org.apache.activemq.transport.failover.FailoverTransport - urlList connectionList:[tcp://localhost:61616], from: [tcp://localhost:61616]
17:53:26.339 [main] DEBUG org.apache.camel.component.jms.DefaultJmsMessageListenerContainer - Established shared JMS Connection
17:53:26.340 [main] DEBUG org.apache.camel.component.jms.DefaultJmsMessageListenerContainer - Resumed paused task: org.springframework.jms.listener.DefaultMessageListenerContainer$AsyncMessageListenerInvoker@58c34bb3
17:53:26.372 [ActiveMQ Task-1] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Attempting 0th connect to: tcp://localhost:61616
17:53:28.393 [ActiveMQ Task-1] DEBUG org.apache.activemq.transport.failover.FailoverTransport - Connect fail to: tcp://localhost:61616, reason: {}

I am especially stumped to see these messages:

Route: route1 >>> Route[activemq://queue:null -> null]

and

urlList connectionList:[tcp://localhost:61616], from: [tcp://localhost:61616]

Why is the queue coming up as null though I have a proper queue name? Also why is the broker url tcp://localhost:61616?

I want to run this unit test case so that it runs properly in all environments like: local,  DIT , SIT, PROD etc. So, for that I cannot afford the broker url to be: tcp://localhost:61616.

Any ideas as to what I am doing wrong here and what I should be doing?

EDIT 1:

One of the issues that I am seeing is even before the test class is called, the MyRouteBuilder() inside createRouteBuilder() is invoked, leading to the issues that I see in the log.

Body:
Instead of setting up an explicit active mq broker , I started using a VM broker .

@Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() {
                ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
                ActiveMQComponent activeMQComponent = new ActiveMQComponent();
                activeMQComponent.setConnectionFactory(connectionFactory);
                context.addComponent("activemq", activeMQComponent);
                from("activemq:queue:myQueue").to("mock:collector");
            }
        };
    }

Also , I mistook camel junit as a traditional junit . We don't need to call explicitly the actual route builder class . Instead after setting up my activeMq component up above , I was able to write my test methods, mock my end points for queue and send messages and assert them . Camel is truly versatile . Requires a lot of study though .


问:
How do I clone a subdirectory only of a Git repository?
I have my Git repository which, at the root, has two sub directories:

```<code>/finisht
/static
</code>```

When this was in SVN, /finisht was checked out in one place, while /static was checked out elsewhere, like so:

```<code>svn co svn+ssh://admin@domain.example/home/admin/repos/finisht/static static
</code>```

Is there a way to do this with Git?

答:
degit makes copies of git repositories. When you run degit
some-user/some-repo, it will find the latest commit on
https://github.com/some-user/some-repo and download the associated tar
file to ~/.degit/some-user/some-repo/commithash.tar.gz if it doesn't
already exist locally. (This is much quicker than using git clone,
because you're not downloading the entire git history.)

```<code>degit <https://github.com/user/repo/subdirectory> <output folder>
</code>```

Find out more https://www.npmjs.com/package/degit

OwnerDisplayName: Nick Sergeant

Body:
I have my Git repository which, at the root, has two sub directories:

/finisht
/static

When this was in SVN, /finisht was checked out in one place, while /static was checked out elsewhere, like so:

svn co svn+ssh://admin@domain.example/home/admin/repos/finisht/static static

Is there a way to do this with Git?

Body:
degit makes copies of git repositories. When you run degit
some-user/some-repo, it will find the latest commit on
https://github.com/some-user/some-repo and download the associated tar
file to ~/.degit/some-user/some-repo/commithash.tar.gz if it doesn't
already exist locally. (This is much quicker than using git clone,
because you're not downloading the entire git history.)

degit <https://github.com/user/repo/subdirectory> <output folder>

Find out more https://www.npmjs.com/package/degit


问:
Having difficulty using rle command within a mutate step in r to count the max number of consecutive characters in a word
I created this function to count the maximum number of consecutive characters in a word.

```<code>max(rle(unlist(strsplit("happy", split = "")))$lengths)
</code>```

The function works on individual words, but when I try to use the function within a mutate step it doesn't work.  Here is the code that involves the mutate step.

```<code>text3 <- "The most pressing of those issues, considering the franchise's
stated goal of competing for championships above all else, is an apparent
disconnect between Lakers vice president of basketball operations and general manager"

text3_df <- tibble(line = 1:1, text3)

text3_df %>%
  unnest_tokens(word, text3) %>%
  mutate(
    num_letters = nchar(word),
    num_vowels = get_count(word),
    num_consec_char = max(rle(unlist(strsplit(word, split = "")))$lengths)
  )
</code>```

The variables num_letters and num_vowels work fine, but I get a 2 for every value of num_consec_char.  I can't figure out what I'm doing wrong.

答:
This command rle(unlist(strsplit(word, split = "")))$lengths is not vectorized and thus is operating on the entire list of words for each row thus the same result for each row.

You will need to use some type of loop (ie for, apply, purrr::map) to solve it.

```<code>library(dplyr)
library(tidytext)

text3 <- "The most pressing of those issues, considering the franchise's
stated goal of competing for championships above all else, is an apparent
disconnect between Lakers vice president of basketball operations and general manager"

text3_df <- tibble(line = 1:1, text3)

output<- text3_df %>%
   unnest_tokens(word, text3) %>%
   mutate(
      num_letters = nchar(word),
    #  num_vowels = get_count(word),
   )

output$num_consec_char<- sapply(output$word, function(word){
   max(rle(unlist(strsplit(word, split = "")))$lengths)
})
output

# A tibble: 32 × 4
line word        num_letters num_consec_char
<int> <chr>             <int>           <int>
   1     1 the                   3               1
   2     1 most                  4               1
   3     1 pressing              8               2
   4     1 of                    2               1
   5     1 those                 5               1
   6     1 issues                6               2
   7     1 considering          11               1
</code>```

Body:
I created this function to count the maximum number of consecutive characters in a word.

max(rle(unlist(strsplit("happy", split = "")))$lengths)

The function works on individual words, but when I try to use the function within a mutate step it doesn't work.  Here is the code that involves the mutate step.

text3 <- "The most pressing of those issues, considering the franchise's
stated goal of competing for championships above all else, is an apparent
disconnect between Lakers vice president of basketball operations and general manager"

text3_df <- tibble(line = 1:1, text3)

text3_df %>%
  unnest_tokens(word, text3) %>%
  mutate(
    num_letters = nchar(word),
    num_vowels = get_count(word),
    num_consec_char = max(rle(unlist(strsplit(word, split = "")))$lengths)
  )

The variables num_letters and num_vowels work fine, but I get a 2 for every value of num_consec_char.  I can't figure out what I'm doing wrong.

Body:
This command rle(unlist(strsplit(word, split = "")))$lengths is not vectorized and thus is operating on the entire list of words for each row thus the same result for each row.

You will need to use some type of loop (ie for, apply, purrr::map) to solve it.

library(dplyr)
library(tidytext)

text3 <- "The most pressing of those issues, considering the franchise's
stated goal of competing for championships above all else, is an apparent
disconnect between Lakers vice president of basketball operations and general manager"

text3_df <- tibble(line = 1:1, text3)

output<- text3_df %>%
   unnest_tokens(word, text3) %>%
   mutate(
      num_letters = nchar(word),
    #  num_vowels = get_count(word),
   )

output$num_consec_char<- sapply(output$word, function(word){
   max(rle(unlist(strsplit(word, split = "")))$lengths)
})
output

# A tibble: 32 × 4
line word        num_letters num_consec_char
<int> <chr>             <int>           <int>
   1     1 the                   3               1
   2     1 most                  4               1
   3     1 pressing              8               2
   4     1 of                    2               1
   5     1 those                 5               1
   6     1 issues                6               2
   7     1 considering          11               1


问:
Error : Mongoose Schema is required in Node.js
I am learning from a udemy course where we build a Yelp like site but for campgrounds.

I am getting a problem every time I try to update the campground.

```<code>Error: "campground" is required
    at module.exports.validateCampground (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/middleware.js:19:9)
    at Layer.handle [as handle_request] (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/layer.js:95:5)
    at next (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/route.js:137:13)
    at module.exports.isLoggedIn (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/middleware.js:12:3)
    at Layer.handle [as handle_request] (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/layer.js:95:5)
    at next (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/route.js:137:13)
    at next (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/route.js:131:14)
    at Route.dispatch (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/layer.js:95:5)
    at /Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/index.js:281:22
</code>```

I looked through the relevant methods and schemas but cannot find anything that is causing the error. Can someone please help ?

My Joi schema looks like this

```<code>const Joi = require('joi');
module.exports.campgroundSchema = Joi.object({
    campground: Joi.object({
        title: Joi.string().required(),
        price: Joi.number().required().min(0),
        //image: Joi.string(),
        location: Joi.string().required(),
        description: Joi.string().required()
    }).required()
});
</code>```

The code for updating campground :

```<code>module.exports.updateCampground = async (req, res) => {
const { id } = req.params;
const campgrounds = await campground.findByIdAndUpdate(id, { ...req.body.campground });
const imgs = req.files.map((f) => ({ url: f.path, filename: f.filename }));
campgrounds.images.push(...imgs);
await campgrounds.save();
req.flash('success', 'Successfully updated Campground');
res.redirect(`/campgrounds/${campgrounds._id}`);
};
</code>```

The validateCampground method is like this :

```<code>module.exports.validateCampground = (req, res, next) => {
    const { error } = campgroundSchema.validate(req.body);
    if (error) {
        const msg = error.details.map((el) => el.message).join(',');
        throw new ExpressError(msg, 400);
    } else {
        next();
    }
};
</code>```

Can anyone please help ?

答:
The validateCampground method should be like this:</p>
```<code>const { error } = campgroundSchema.validate(req.body.campground);
</code>```

Body:
I am learning from a udemy course where we build a Yelp like site but for campgrounds.

I am getting a problem every time I try to update the campground.

Error: "campground" is required
    at module.exports.validateCampground (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/middleware.js:19:9)
    at Layer.handle [as handle_request] (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/layer.js:95:5)
    at next (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/route.js:137:13)
    at module.exports.isLoggedIn (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/middleware.js:12:3)
    at Layer.handle [as handle_request] (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/layer.js:95:5)
    at next (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/route.js:137:13)
    at next (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/route.js:131:14)
    at Route.dispatch (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/layer.js:95:5)
    at /Volumes/Samip/ColtHTML/Node/Mongoose/YelpCamp/node_modules/express/lib/router/index.js:281:22

I looked through the relevant methods and schemas but cannot find anything that is causing the error. Can someone please help ?

My Joi schema looks like this

const Joi = require('joi');
module.exports.campgroundSchema = Joi.object({
    campground: Joi.object({
        title: Joi.string().required(),
        price: Joi.number().required().min(0),
        //image: Joi.string(),
        location: Joi.string().required(),
        description: Joi.string().required()
    }).required()
});

The code for updating campground :

module.exports.updateCampground = async (req, res) => {
const { id } = req.params;
const campgrounds = await campground.findByIdAndUpdate(id, { ...req.body.campground });
const imgs = req.files.map((f) => ({ url: f.path, filename: f.filename }));
campgrounds.images.push(...imgs);
await campgrounds.save();
req.flash('success', 'Successfully updated Campground');
res.redirect(`/campgrounds/${campgrounds._id}`);
};

The validateCampground method is like this :

module.exports.validateCampground = (req, res, next) => {
    const { error } = campgroundSchema.validate(req.body);
    if (error) {
        const msg = error.details.map((el) => el.message).join(',');
        throw new ExpressError(msg, 400);
    } else {
        next();
    }
};

Can anyone please help ?

Body:
The validateCampground method should be like this:

const { error } = campgroundSchema.validate(req.body.campground);


问:
Spring boot Kafka Health check not working
I'm working on a spring boot app that consume Kafka messages.
I consume perfectly my Kafka events using a @KafkaListener... and now I want to implement Kafka health check using spring actuator.
i used this example : https://medium.com/dna-technology/kafka-consumers-health-check-in-spring-boot-actuator-d00f9017e89d
but it doesn't work and I can't find the import for the two classes HealthRow All Status

```<code>private final KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;

@Override
protected void doHealthCheck(Builder builder) {
  Map<String, HealthRow> consumersHealth = new TreeMap<>(Comparator.naturalOrder());
  final AllStatus allStatus = new AllStatus();
  final Collection<MessageListenerContainer> allListenerContainers = kafkaListenerEndpointRegistry
      .getAllListenerContainers();

  for (MessageListenerContainer messageListenerContainer : allListenerContainers) {
    ConsumerDetails consumerDetails = buildConsumerDetails(messageListenerContainer);
    consumersHealth.put(consumerDetails.getName(), consumerDetails);
    updateAllStatus(allStatus, consumerDetails);
  }

  consumersHealth.put(allStatus.getName(), allStatus);

  builder.withDetails(consumersHealth);
  builder.status(allStatus.getStatus());
}
</code>```

Anyone please knows how to implement Kafka health check correctly using spring boot?
Regards.

答:
Did come across same issue. The way how I solved was to implement my own inner HealthRow class. The fields name and status I use only internally to decide on lower level status to be inherited at the higher level and for the name to then add the Map as an entry at the outer Map ...

```<code>static class HealthRow extends LinkedHashMap<String, Object> {
   private String name;
   private Status status;

   String getName() {return name;};
   Status getStatus() {return status;}:
   void setName (String name) (this.name = name;}
   void setstatus (Status status) (this.status = status;};
   Map‹String, Object› getDetails() {return this;};
}
</code>```

Created my own inner StreamApplicationDetails class

```<code>private static class StreamApplicationDetails extends HelathRow {

    public StreamApplicationDetails(StreamsBuilderFactoryBean streamsBuilderFactoryBean) {
        final KafkaStreams kafkaStreams = streamsBuilderFactoryBean.getKafkaStreams();
        if (kafkaStreams != null) {
            setName(streamsBuilderFactoryBean.getStreamsConfiguration().getProperty("application.id", "Undefined"));
            setStatus(kafkaStreams.state().isRunningOrRebalancing() ? Status.UP : Status.DOWN);
            put("status", getstatus());

            final HealthRow streamThreads = new HealthRow();
            put("streamThreads", streamThreads);
            for (ThreadMetadata threadMetadata : kafkaStreams.metadataForLocalThreads()) {
                final HealthRow streamThread = buildThreadStatus(threadMetadata);
                if (streamThread.getStatus() != Status.UP) {
                    // if one of the threads as down, mark the service down as well
                    setStatus(Status.DOWN);
                }
                streamThreads.put(streamThread.getName(), streamThread);
            }
        } else {
            setStatus(Status.UNKNOWN);
            Log.warn("Healthcheck: StreamApplication status is ()", getstatus());
        }
    }

    private HealthRow buildThreadStatus(ThreadMetadata threadMetadata) {
        final HealthRow details = new HealthRow();
        details.setName(threadMetadata.threadName());
        details.setStatus(((threadMetadata.threadState() == "RUNNING") || (threadMetadata.threadState() == "CREATED")) ? Status.UP : Status.DOWN);
        details.put("status", details.getStatus());
        details.put("activeTasksCount", threadMetadata.activeTasks().size());
        details.put("threadState", threadMetadata.threadState());

        final HealthRow standbyTasks = new HealthRow() :
        details.put("standbyTasks", standbyTasks);
        for (TaskMetadata taskMetadata : threadMetadata.standbyTasks()) {
            final HealthRow standbyTask = buildTaskStatus(taskMetadata);
            standbyTasks.put(standbyTask.getName(), standbyTask);
        }

        final HealthRow activeTasks = new HealthRow();
        details.pt("activeTasks", activeTasks):
        for (TaskMetadata taskMetadata : threadMetadata.activeTasks()) {
            final HealthRow activeTask = buildTaskStatus(taskMetadata);
            activeTasks.put(activeTask.getName(), activeTask);
        }
        return details;
    }

    private HealthRow buildTaskStatus(TaskMetadata taskMetadata) {
        final HealthRow details = new HealthRow();
        details.setName(taskMetadata.taskId().toString());
        details.setStatus(Status.UNKNOWN);
        for (TopicPartition topicPartition : taskMetadata.topicPartitions()) {
            details.put("partition", topicPartition.partition());
            details.put("topic", topicPartition.topic());
        }
        return details;
    }
}
</code>```

And changed the HealthCheck class as follows

```<code>private final List<StreamBuilderFactoryBean> streamsBuilder;

@Autowired
public StreamsHealthIndicator(List<StreamBuilderFactoryBean> streamsBuilder) {
    this.streamsBuilder = streamsBuilder;
}

@Override
protected void doHealthCheck(Health.Builder builder) {
    final Map<String, HealthRow> streamsHealth = new TreeMap<>(Comperator.naturalOrder());
    Status serviceStatus = Status.UP;

    for (StreamBuilderFactoryBean:streamBuilderFactoryBean : streamsBuilder) {
        final StreamApplicationDetails streamApplicationDetails = new StreamApplicationDetails(streamBuilderFactoryBean);
        streamsHealth.put(streamApplicationDetails.getName(), streamApplicationDetails);
        if (streamApplicationDetails.getStatus() != Status.UP) {
            serviceStatus = Status.DOWN;
        }
    }
    builder.withDetails(streamsHealth);
    builder.status(serviceStatus);
}
</code>```

What is still somewhat open is to clarify by when the status really should be up meaning that my StreamProcessor(s) are up and running and I for instance could start using interactive queries against materialized views etc.

Hope this helps you further.

Body:
I'm working on a spring boot app that consume Kafka messages.
I consume perfectly my Kafka events using a @KafkaListener... and now I want to implement Kafka health check using spring actuator.
i used this example : https://medium.com/dna-technology/kafka-consumers-health-check-in-spring-boot-actuator-d00f9017e89d
but it doesn't work and I can't find the import for the two classes HealthRow All Status

private final KafkaListenerEndpointRegistry kafkaListenerEndpointRegistry;

@Override
protected void doHealthCheck(Builder builder) {
  Map<String, HealthRow> consumersHealth = new TreeMap<>(Comparator.naturalOrder());
  final AllStatus allStatus = new AllStatus();
  final Collection<MessageListenerContainer> allListenerContainers = kafkaListenerEndpointRegistry
      .getAllListenerContainers();

  for (MessageListenerContainer messageListenerContainer : allListenerContainers) {
    ConsumerDetails consumerDetails = buildConsumerDetails(messageListenerContainer);
    consumersHealth.put(consumerDetails.getName(), consumerDetails);
    updateAllStatus(allStatus, consumerDetails);
  }

  consumersHealth.put(allStatus.getName(), allStatus);

  builder.withDetails(consumersHealth);
  builder.status(allStatus.getStatus());
}

Anyone please knows how to implement Kafka health check correctly using spring boot?
Regards.

Body:
Did come across same issue. The way how I solved was to implement my own inner HealthRow class. The fields name and status I use only internally to decide on lower level status to be inherited at the higher level and for the name to then add the Map as an entry at the outer Map ...

static class HealthRow extends LinkedHashMap<String, Object> {
   private String name;
   private Status status;

   String getName() {return name;};
   Status getStatus() {return status;}:
   void setName (String name) (this.name = name;}
   void setstatus (Status status) (this.status = status;};
   Map‹String, Object› getDetails() {return this;};
}

Created my own inner StreamApplicationDetails class

private static class StreamApplicationDetails extends HelathRow {

    public StreamApplicationDetails(StreamsBuilderFactoryBean streamsBuilderFactoryBean) {
        final KafkaStreams kafkaStreams = streamsBuilderFactoryBean.getKafkaStreams();
        if (kafkaStreams != null) {
            setName(streamsBuilderFactoryBean.getStreamsConfiguration().getProperty("application.id", "Undefined"));
            setStatus(kafkaStreams.state().isRunningOrRebalancing() ? Status.UP : Status.DOWN);
            put("status", getstatus());

            final HealthRow streamThreads = new HealthRow();
            put("streamThreads", streamThreads);
            for (ThreadMetadata threadMetadata : kafkaStreams.metadataForLocalThreads()) {
                final HealthRow streamThread = buildThreadStatus(threadMetadata);
                if (streamThread.getStatus() != Status.UP) {
                    // if one of the threads as down, mark the service down as well
                    setStatus(Status.DOWN);
                }
                streamThreads.put(streamThread.getName(), streamThread);
            }
        } else {
            setStatus(Status.UNKNOWN);
            Log.warn("Healthcheck: StreamApplication status is ()", getstatus());
        }
    }

    private HealthRow buildThreadStatus(ThreadMetadata threadMetadata) {
        final HealthRow details = new HealthRow();
        details.setName(threadMetadata.threadName());
        details.setStatus(((threadMetadata.threadState() == "RUNNING") || (threadMetadata.threadState() == "CREATED")) ? Status.UP : Status.DOWN);
        details.put("status", details.getStatus());
        details.put("activeTasksCount", threadMetadata.activeTasks().size());
        details.put("threadState", threadMetadata.threadState());

        final HealthRow standbyTasks = new HealthRow() :
        details.put("standbyTasks", standbyTasks);
        for (TaskMetadata taskMetadata : threadMetadata.standbyTasks()) {
            final HealthRow standbyTask = buildTaskStatus(taskMetadata);
            standbyTasks.put(standbyTask.getName(), standbyTask);
        }

        final HealthRow activeTasks = new HealthRow();
        details.pt("activeTasks", activeTasks):
        for (TaskMetadata taskMetadata : threadMetadata.activeTasks()) {
            final HealthRow activeTask = buildTaskStatus(taskMetadata);
            activeTasks.put(activeTask.getName(), activeTask);
        }
        return details;
    }

    private HealthRow buildTaskStatus(TaskMetadata taskMetadata) {
        final HealthRow details = new HealthRow();
        details.setName(taskMetadata.taskId().toString());
        details.setStatus(Status.UNKNOWN);
        for (TopicPartition topicPartition : taskMetadata.topicPartitions()) {
            details.put("partition", topicPartition.partition());
            details.put("topic", topicPartition.topic());
        }
        return details;
    }
}

And changed the HealthCheck class as follows

private final List<StreamBuilderFactoryBean> streamsBuilder;

@Autowired
public StreamsHealthIndicator(List<StreamBuilderFactoryBean> streamsBuilder) {
    this.streamsBuilder = streamsBuilder;
}

@Override
protected void doHealthCheck(Health.Builder builder) {
    final Map<String, HealthRow> streamsHealth = new TreeMap<>(Comperator.naturalOrder());
    Status serviceStatus = Status.UP;

    for (StreamBuilderFactoryBean:streamBuilderFactoryBean : streamsBuilder) {
        final StreamApplicationDetails streamApplicationDetails = new StreamApplicationDetails(streamBuilderFactoryBean);
        streamsHealth.put(streamApplicationDetails.getName(), streamApplicationDetails);
        if (streamApplicationDetails.getStatus() != Status.UP) {
            serviceStatus = Status.DOWN;
        }
    }
    builder.withDetails(streamsHealth);
    builder.status(serviceStatus);
}

What is still somewhat open is to clarify by when the status really should be up meaning that my StreamProcessor(s) are up and running and I for instance could start using interactive queries against materialized views etc.

Hope this helps you further.


问:
What is the purpose of stepfun in ecdf()?
```<code>R> ecdf
function (x)
{
    x <- sort(x)
    n <- length(x)
    if (n < 1)
        stop("'x' must have 1 or more non-missing values")
    vals <- unique(x)
    rval <- approxfun(vals, cumsum(tabulate(match(x, vals)))/n,
        method = "constant", yleft = 0, yright = 1, f = 0, ties = "ordered")
    class(rval) <- c("ecdf", "stepfun", class(rval))
    assign("nobs", n, envir = environment(rval))
    attr(rval, "call") <- sys.call()
    rval
}
</code>```

The above is the code of ecdf(). I see that the return value is assigned with class stepfun. I don't understand what it is for. Given approxfun() does linear interpolation, why is stepfun needed? What is the purpose of adding stepfun to the class?

答:
In the call to approxfun() in ecdf(), the method is "constant", which means it isn't doing linear interpolation, it's generating a step function.

To find out what the class on the result affects, you can use the methods() function:

methods(class="stepfun")
#> [1] knots   lines   plot    print   summary
#> see '?methods' for accessing help and source code
```
<p><sup>Created on 2022-02-12 by the reprex package (v2.0.1.9000)</sup></p>
<p>So potentially if you call any of the <code>knots()</code>, <code>lines()</code>, <code>plot()</code>, <code>print()</code> or <code>summary()</code> functions on the result you'll get behaviour tailored to step functions.  However, the class of the result is computed as <code>c("ecdf", "stepfun", class(rval))</code>, so there might be <code>"ecdf"</code> methods that override the <code>"stepfun"</code> methods:</p>
<pre class="lang-r prettyprint-override"><code>methods(class="ecdf")
#> [1] plot     print    quantile summary
#> see '?methods' for accessing help and source code
</code>```

Created on 2022-02-12 by the reprex package (v2.0.1.9000)

Yes, the plot(), print() and summary() functions will call the "ecdf" methods in preference to the "stepfun" methods.  That still leaves knots() and lines(), and conceivably the others could call NextMethod() to get to the "stepfun" methods.

One clarification:  the method argument to approxfun() is just the name of an argument; in the discussion above, "methods" was used to refer to one of the ways R does object oriented programming, using methods and classes.

Body:
R> ecdf
function (x)
{
    x <- sort(x)
    n <- length(x)
    if (n < 1)
        stop("'x' must have 1 or more non-missing values")
    vals <- unique(x)
    rval <- approxfun(vals, cumsum(tabulate(match(x, vals)))/n,
        method = "constant", yleft = 0, yright = 1, f = 0, ties = "ordered")
    class(rval) <- c("ecdf", "stepfun", class(rval))
    assign("nobs", n, envir = environment(rval))
    attr(rval, "call") <- sys.call()
    rval
}

The above is the code of ecdf(). I see that the return value is assigned with class stepfun. I don't understand what it is for. Given approxfun() does linear interpolation, why is stepfun needed? What is the purpose of adding stepfun to the class?

Body:
In the call to approxfun() in ecdf(), the method is "constant", which means it isn't doing linear interpolation, it's generating a step function.

To find out what the class on the result affects, you can use the methods() function:

methods(class="stepfun")
#> [1] knots   lines   plot    print   summary
#> see '?methods' for accessing help and source code

Created on 2022-02-12 by the reprex package (v2.0.1.9000)

So potentially if you call any of the knots(), lines(), plot(), print() or summary() functions on the result you'll get behaviour tailored to step functions.  However, the class of the result is computed as c("ecdf", "stepfun", class(rval)), so there might be "ecdf" methods that override the "stepfun" methods:

methods(class="ecdf")
#> [1] plot     print    quantile summary
#> see '?methods' for accessing help and source code

Created on 2022-02-12 by the reprex package (v2.0.1.9000)

Yes, the plot(), print() and summary() functions will call the "ecdf" methods in preference to the "stepfun" methods.  That still leaves knots() and lines(), and conceivably the others could call NextMethod() to get to the "stepfun" methods.

One clarification:  the method argument to approxfun() is just the name of an argument; in the discussion above, "methods" was used to refer to one of the ways R does object oriented programming, using methods and classes.


问:
Node.js event queues, Promises, and setTimeout() -- in what sequence?
SYNOPSIS:

In Node.js event queues, and code like "new Promise((r) => setTimeout(r, t));", is the setTimeout() evaluated NOW, in the microqueue for Promise resolves, or where?

DETAILS:

I'm reading through Distributed Systems with Node.js (Thomas Hunter II, O'Reilly, 3rd release of First Edition).  It tells me that Node.js goes thru each queue in turn:

Poll: for most things, including I/O callbacks

Check: for setImmediate callbacks

Close: when closing connections

Timers: when setTimeout and setInterval resolve

Pending: special system events

There are also two microqueues evaluated after each queue is empty, one for promises and one for nextTick().

On the book's p.13 he has an example where an await calls a function that returns "new Promise((r) => setTimeout(r, t));".  The book code is:

```<code>const sleep_st = (t) => new Promise((r) => setTimeout(r, t));
const sleep_im = () => new Promise((r) => setImmediate(r));

(async () => {
  setImmediate(() => console.log(1));
  console.log(2);
  await sleep_st(0);
  setImmediate(() => console.log(3));
  console.log(4);
</code>```

That is,

```<code>setImmediate(() => console.log(1));
console.log(2);
Promise.resolve().then(() => setTimeout(() => {
  setImmediate(() => console.log(3));
  console.log(4);
</code>```

This is what I think is going on:

The program starts with a task in the Poll queue, the p.13 code.  It starts running.

The Check queue gets a task and the "2" printed to the console.

The "await sleep_st(0)" will have called setTimeout, which puts a
task on the Timer queue.  Since the timeout is zero, by the time we
access the Timer queue there will be work to do. The sleep_st(0)
returns a Promise.

This ends the work of the Poll queue.

Now the result micro queue starts.  My code resumes executing. This should start with
setImmediate() and console.log(4).

This means that the output to the console is "2 4".  However, the book says the proper sequence is "2 1 4 3".  That is, the event queue for Check, and perhaps Timer, gets involved.

What, then, happens in the promise result microqueue?

答:
by the time we access the Timer queue there will be work to do

Before get to timer phase, there is check phase, so "1" is printed before "3",
but i exectued the code on my window, the result is 2 4 1 3, that is setTimeout and setImmediate will race for exectued, sometime setTimeout first, sometile second, i executed the example code in this book for many time in a short time

Body:
SYNOPSIS:

In Node.js event queues, and code like "new Promise((r) => setTimeout(r, t));", is the setTimeout() evaluated NOW, in the microqueue for Promise resolves, or where?

DETAILS:

I'm reading through Distributed Systems with Node.js (Thomas Hunter II, O'Reilly, 3rd release of First Edition).  It tells me that Node.js goes thru each queue in turn:

Poll: for most things, including I/O callbacks

Check: for setImmediate callbacks

Close: when closing connections

Timers: when setTimeout and setInterval resolve

Pending: special system events

There are also two microqueues evaluated after each queue is empty, one for promises and one for nextTick().

On the book's p.13 he has an example where an await calls a function that returns "new Promise((r) => setTimeout(r, t));".  The book code is:

const sleep_st = (t) => new Promise((r) => setTimeout(r, t));
const sleep_im = () => new Promise((r) => setImmediate(r));

(async () => {
  setImmediate(() => console.log(1));
  console.log(2);
  await sleep_st(0);
  setImmediate(() => console.log(3));
  console.log(4);

That is,

setImmediate(() => console.log(1));
console.log(2);
Promise.resolve().then(() => setTimeout(() => {
  setImmediate(() => console.log(3));
  console.log(4);

This is what I think is going on:

The program starts with a task in the Poll queue, the p.13 code.  It starts running.

The Check queue gets a task and the "2" printed to the console.

The "await sleep_st(0)" will have called setTimeout, which puts a
task on the Timer queue.  Since the timeout is zero, by the time we
access the Timer queue there will be work to do. The sleep_st(0)
returns a Promise.

This ends the work of the Poll queue.

Now the result micro queue starts.  My code resumes executing. This should start with
setImmediate() and console.log(4).

This means that the output to the console is "2 4".  However, the book says the proper sequence is "2 1 4 3".  That is, the event queue for Check, and perhaps Timer, gets involved.

What, then, happens in the promise result microqueue?


问:
File uploading rails 3
I have a rails 3 app that has a comment system that allows a user to make comments. What I now wish to do is extend this further by enabling the user to attach/upload files to the comment system. Fairly easy question I am about to ask. What is the best tool/plugin or gem to use so that I can achieve this? I've done some thorough research and found that alot of these plugins such as carrierwave, paperclip and a few others are used to upload photos and I am not trying to do this.

Requirements

User should be able to upload/attach files

Can upload word, powerpoint or execel docuements

答: You can use even dragonfly - https://github.com/markevans/dragonfly/</p>

ContentLicense: CC BY-SA 3.0

Title: File uploading rails 3


问:
How to capture subdomain in nginx ingress
I want to capture subdomain and rewrite URL with /subdomain, For example bhautik.bhau.tk rewrite to bhau.tk/bhautik.

I also https://github.com/google/re2/wiki/Syntax tried group syntax

Here is my nginx ingress config:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: subdomain
  namespace: subdomain
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: "true"
    # nginx.ingress.kubernetes.io/rewrite-target: /$sub
    nginx.ingress.kubernetes.io/server-snippet: |
      set $prefix abcd;
      if ($host ~ ^(\w+).bhau\.tk$) {
        // TODO?
      }
    nginx.ingress.kubernetes.io/rewrite-target: /$prefix/$uri
spec:
  rules:
  - host: "*.bhau.tk"
    http:
      paths:
      - pathType: Prefix
        path: "/"
        backend:
          service:
            name: subdomain
            port:
              number: 80
```

How do I capture subdomain from $host?

答:
I believe you want a redirect instead of rewrite. Here is the server-snippet you need:

```<code>nginx.ingress.kubernetes.io/server-snippet: |
  if ($host ~ ^(?<subdom>\w+)\.(?<basedom>bhau\.tk)$) {
    return 302 https://$basedom/$subdom/ ;
  }
</code>```

If you really want a rewrite where the URL that the user sees remains unchanged but instead the request will be routed to a subpath served by the same service:

```<code>nginx.ingress.kubernetes.io/server-snippet: |
  if ($host ~ ^(?<subdom>\w+)\.(?<basedom>bhau\.tk)$) {
    rewrite ^/(.*)$ /$subdom/$1 ;
  }
</code>```

Remove the rewrite-target annotation that specifies $prefix. You don't need it.

The ?<capturename> and $capturename pair is the trick you are looking for.

Body:
I want to capture subdomain and rewrite URL with /subdomain, For example bhautik.bhau.tk rewrite to bhau.tk/bhautik.

I also https://github.com/google/re2/wiki/Syntax tried group syntax

Here is my nginx ingress config:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: subdomain
  namespace: subdomain
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/use-regex: "true"
    # nginx.ingress.kubernetes.io/rewrite-target: /$sub
    nginx.ingress.kubernetes.io/server-snippet: |
      set $prefix abcd;
      if ($host ~ ^(\w+).bhau\.tk$) {
        // TODO?
      }
    nginx.ingress.kubernetes.io/rewrite-target: /$prefix/$uri
spec:
  rules:
  - host: "*.bhau.tk"
    http:
      paths:
      - pathType: Prefix
        path: "/"
        backend:
          service:
            name: subdomain
            port:
              number: 80

How do I capture subdomain from $host?

Body:
I believe you want a redirect instead of rewrite. Here is the server-snippet you need:

nginx.ingress.kubernetes.io/server-snippet: |
  if ($host ~ ^(?<subdom>\w+)\.(?<basedom>bhau\.tk)$) {
    return 302 https://$basedom/$subdom/ ;
  }

If you really want a rewrite where the URL that the user sees remains unchanged but instead the request will be routed to a subpath served by the same service:

nginx.ingress.kubernetes.io/server-snippet: |
  if ($host ~ ^(?<subdom>\w+)\.(?<basedom>bhau\.tk)$) {
    rewrite ^/(.*)$ /$subdom/$1 ;
  }

Remove the rewrite-target annotation that specifies $prefix. You don't need it.

The ?<capturename> and $capturename pair is the trick you are looking for.


问:
String Symmetry Program
Hey I could use a little bit of help to figure out why my program isn't working. The question is to make a program using recursion that figures if it the text given is a palindrome or not after all the punctuation and white spaces are removed. While the program so far compiles, it returns every value as false. We are only allowed to change the isSymmetrical method. I could use whatever help possible trying to figure out how to make this work. Thank you.

```<code>public class StringSymmetry {

public static boolean isSymmetrical(String inputText)
{
    if(inputText.length() == 0 || inputText.length() ==1)
        return true;

    if(inputText.charAt(0) == inputText.charAt(inputText.length()-1))
        return isSymmetrical(inputText.substring(1,inputText.length()-1));

        return false;
}

public static void main(String[] args) {
    String[] sampleData =
        { "Don't nod",
          "Dogma: I am God",
          "Too bad - I hid a boot",
          "Rats live on no evil star",
          "No trace; not one carton",
          "Was it Eliot's toilet I saw?",
          "Murder for a jar of red rum",
          "May a moody baby doom a yam?",
          "Go hang a salami; I'm a lasagna hog!",
          "Name is Bond, James Bond"
        };

    for (String s : sampleData)
    {
        System.out.println("isSymmetrical (" + s + ") returns " + isSymmetrical(s));
    }

}
</code>```

}

答:
Check the following function:

```<code>public static boolean isPalindrome(String str, int x) {
    if(x == 0) return true;

    if(str.charAt(0) == str.charAt((str.length() - 1)))
        return isPalindrome(str.substring(1, str.length() - 1), x - 1);
    return false;
}
</code>```

Explanation:

A recursive function with the following parameter's:

str - a String object which will be tested for symmetry.

x - Integer that represent's the recursive tester parameter and decides for how far you want to iterate and check for two sided symmetry.

The base case is set to zero and return's true when you finished the desired iteration number.

The second if-condition statement is used to check the corner's of the string that is given, and its return statement will recursively enter another testing loop with shorter corner's of the original String( . . . corner's will be shorter by one).

Title: String Symmetry Program

Body:
Hey I could use a little bit of help to figure out why my program isn't working. The question is to make a program using recursion that figures if it the text given is a palindrome or not after all the punctuation and white spaces are removed. While the program so far compiles, it returns every value as false. We are only allowed to change the isSymmetrical method. I could use whatever help possible trying to figure out how to make this work. Thank you.

public class StringSymmetry {

public static boolean isSymmetrical(String inputText)
{
    if(inputText.length() == 0 || inputText.length() ==1)
        return true;

    if(inputText.charAt(0) == inputText.charAt(inputText.length()-1))
        return isSymmetrical(inputText.substring(1,inputText.length()-1));

        return false;
}

public static void main(String[] args) {
    String[] sampleData =
        { "Don't nod",
          "Dogma: I am God",
          "Too bad - I hid a boot",
          "Rats live on no evil star",
          "No trace; not one carton",
          "Was it Eliot's toilet I saw?",
          "Murder for a jar of red rum",
          "May a moody baby doom a yam?",
          "Go hang a salami; I'm a lasagna hog!",
          "Name is Bond, James Bond"
        };

    for (String s : sampleData)
    {
        System.out.println("isSymmetrical (" + s + ") returns " + isSymmetrical(s));
    }

}

}

Body:
Check the following function:

public static boolean isPalindrome(String str, int x) {
    if(x == 0) return true;

    if(str.charAt(0) == str.charAt((str.length() - 1)))
        return isPalindrome(str.substring(1, str.length() - 1), x - 1);
    return false;
}

Explanation:

A recursive function with the following parameter's:

str - a String object which will be tested for symmetry.

x - Integer that represent's the recursive tester parameter and decides for how far you want to iterate and check for two sided symmetry.

The base case is set to zero and return's true when you finished the desired iteration number.

The second if-condition statement is used to check the corner's of the string that is given, and its return statement will recursively enter another testing loop with shorter corner's of the original String( . . . corner's will be shorter by one).


问:
java split with unknown result
for the following code,

why there is empty string in position 2,3,5,6,8?

then why "b", ":andf", "1" has no empty string behind?

```<code>    String[] splitStrs = "booo:and:fooo1o".split("o", -1);
    System.out.println(splitStrs.length);
    for (int i=0; i<splitStrs.length; i++) {
        System.out.println("\"" + splitStrs[i]+ "\"");
    }
</code>```

output is:

8

"b"

""

""

":and:f"

""

""

"1"

""

答:
why there is empty string in position 2,3,5,6,8?

When splitting on "o", there's nothing between the o's in "ooo", thus empty strings.

then why "b", ":andf", "1" has no empty string behind?

But there is an empty string at the end of your output, i.e., behind "1".

Per the documentation, a negative 2nd arg specifically means "trailing empty strings not discarded".

Always read the doc.

Title: java split with unknown result

Body:
for the following code,

why there is empty string in position 2,3,5,6,8?

then why "b", ":andf", "1" has no empty string behind?

    String[] splitStrs = "booo:and:fooo1o".split("o", -1);
    System.out.println(splitStrs.length);
    for (int i=0; i<splitStrs.length; i++) {
        System.out.println("\"" + splitStrs[i]+ "\"");
    }

output is:

8

"b"

""

""

":and:f"

""

""

"1"

""


问:
For Loop Construction Turned Functional
I am currently learning Racket and want to do the following simple task: Construct a list which contains all tuples (i,j) : Int * Int  with 0 <= i < N and 0 <= j < M.

In, let's say Python, I would immediately know how to approach this, by using for loops:

# Not using any modules on purpose here
a = []
for i in range(5):
    for j in range(6):
        a.append((i,j))
```
<p>But I have trouble doing this in Racket. By now I have found a solution which replicates the <em>for</em>-loop approach by using a recursively defined function which for <code>a : A</code> and <code>f : Int -> A -> A</code> satisfies the equations</p>
```for 0 a f = (f 0) a
for n a f = for (n-1) ( (f n) a ) f
```
<p>which results in a chain of applications: <code>for n a f = ( (f 0) ∘ ... ∘ (f n) )(a)</code>. (By <code>f ∘ g </code> I mean composition of <code>f</code> and <code>g</code>). So first <code>f n</code> is applied to <code>a</code>, then <code>f (n - 1)</code> to the result of that, etc.</p>
<p>Given I basically want to do something like <code>((f 0 0) ∘ (f 0 1) ∘ ... ∘ (f N M)) (a)</code>, it can be split up as:</p>
``` (((f 0 0) ... (f 0 M)) ∘ ... ∘ ((f N 0) ... (f N M))) (a)
= ((λz. for M z (f 0)) ∘ ... ∘ (λz. for M z (f N))) (a)
= for N a (λi z. for M z (f i))
```
<p>Which then translates to the following Racket code:</p>
<pre class="lang-lisp prettyprint-override"><code>(define (for n a f)   ;; (for n '() cons) = range(n) = (0 1 ... n-1)
    (if (< 0 n)
        (for (- n 1) (f (- n 1) a) f)
        a))

(define a '())
(define (append i j x) (cons (cons i j) x))

(for 5 a (λ(i x)
       (for 6 x (λ(j y)
              (append i j y)))))
</code>```

The answer produces the desired result and is at least nice regarding that it is obvious how to extend this construction with any number of additional loops.

But I am still wondering whether there isn't a neater functional way to do this.

I'm happy with any answer  that does or does not use functions which might already be present in some library and which I have simply missed so far.

答:
The for*/$@! forms are compact, but Scheme ("Programming languages should be designed not by piling feature on top of feature...") is still there:

```<code>(define (range-pairs m n)  ;; Nat Nat -> (Listof (Cons Nat Nat))
  ;; produce (range m) ⨯ (range n)
  (do ([i (sub1 m) (sub1 i)]
       [a '() (do ([j (sub1 n) (sub1 j)]
                   [a a (cons (cons i j) a)])
                ((negative? j) a))])
    ((negative? i) a)))
</code>```

Title: For Loop Construction Turned Functional

Body:
I am currently learning Racket and want to do the following simple task: Construct a list which contains all tuples (i,j) : Int * Int  with 0 <= i < N and 0 <= j < M.

In, let's say Python, I would immediately know how to approach this, by using for loops:

# Not using any modules on purpose here
a = []
for i in range(5):
    for j in range(6):
        a.append((i,j))

But I have trouble doing this in Racket. By now I have found a solution which replicates the for-loop approach by using a recursively defined function which for a : A and f : Int -> A -> A satisfies the equations

for 0 a f = (f 0) a
for n a f = for (n-1) ( (f n) a ) f

which results in a chain of applications: for n a f = ( (f 0) ∘ ... ∘ (f n) )(a). (By f ∘ g  I mean composition of f and g). So first f n is applied to a, then f (n - 1) to the result of that, etc.

Given I basically want to do something like ((f 0 0) ∘ (f 0 1) ∘ ... ∘ (f N M)) (a), it can be split up as:

 (((f 0 0) ... (f 0 M)) ∘ ... ∘ ((f N 0) ... (f N M))) (a)
= ((λz. for M z (f 0)) ∘ ... ∘ (λz. for M z (f N))) (a)
= for N a (λi z. for M z (f i))

Which then translates to the following Racket code:

(define (for n a f)   ;; (for n '() cons) = range(n) = (0 1 ... n-1)
    (if (< 0 n)
        (for (- n 1) (f (- n 1) a) f)
        a))

(define a '())
(define (append i j x) (cons (cons i j) x))

(for 5 a (λ(i x)
       (for 6 x (λ(j y)
              (append i j y)))))

The answer produces the desired result and is at least nice regarding that it is obvious how to extend this construction with any number of additional loops.

But I am still wondering whether there isn't a neater functional way to do this.

I'm happy with any answer  that does or does not use functions which might already be present in some library and which I have simply missed so far.

Body:
The for*/$@! forms are compact, but Scheme ("Programming languages should be designed not by piling feature on top of feature...") is still there:

(define (range-pairs m n)  ;; Nat Nat -> (Listof (Cons Nat Nat))
  ;; produce (range m) ⨯ (range n)
  (do ([i (sub1 m) (sub1 i)]
       [a '() (do ([j (sub1 n) (sub1 j)]
                   [a a (cons (cons i j) a)])
                ((negative? j) a))])
    ((negative? i) a)))


问:
audio not send react-native-webrtc
In prepareWebrtc function at the end I have the following code:

```<code>MediaStreamTrack.getSources(sourceInfos => {
  var isFront = camera_front
  console.log(sourceInfos);
  let videoSourceId;
  for (const i = 0; i < sourceInfos.length; i++) {
    const sourceInfo = sourceInfos[i];
    if(sourceInfo.kind == "video" &&
       sourceInfo.facing == (isFront ? "front" : "back")) {
      videoSourceId = sourceInfo.id;
    }
  }
  console.log("videoSourceId:" + videoSourceId)
  getUserMedia({
    "audio": true,
    "video":false
  }, (stream) => {
    streamsDone(handleId, jsep, media, callbacks, stream)
  },
  // TODO: add error handling
  () => undefined
  );
});
</code>```

When "video" is true for android and when video is{optional: [{sourceId: videoSourceId}] } for ios, audio gets transmitted, however, then I have to ask for camera permissions which I don't want to do. When I do "video":false, audio can be received by my app; however, it doesn't get send.

答:
as @Anupam Chaplot just said about permissions should be correctly set

After that out of the way now
react-native-webrtc supports audio only stream as well.

imagine receiving remote audio stream, no video, just plain audio stream
All you have to do is to make sure your PeerConnection status is connected
as what you always do with video stream.
and react-native-webrtc will play your audio for you. so you dont have to call things like RTCView as you did with video stream.

You can just use PeerConnection and don't set stream's URL to a RTCView

Title: audio not send react-native-webrtc

Body:
In prepareWebrtc function at the end I have the following code:

MediaStreamTrack.getSources(sourceInfos => {
  var isFront = camera_front
  console.log(sourceInfos);
  let videoSourceId;
  for (const i = 0; i < sourceInfos.length; i++) {
    const sourceInfo = sourceInfos[i];
    if(sourceInfo.kind == "video" &&
       sourceInfo.facing == (isFront ? "front" : "back")) {
      videoSourceId = sourceInfo.id;
    }
  }
  console.log("videoSourceId:" + videoSourceId)
  getUserMedia({
    "audio": true,
    "video":false
  }, (stream) => {
    streamsDone(handleId, jsep, media, callbacks, stream)
  },
  // TODO: add error handling
  () => undefined
  );
});

When "video" is true for android and when video is{optional: [{sourceId: videoSourceId}] } for ios, audio gets transmitted, however, then I have to ask for camera permissions which I don't want to do. When I do "video":false, audio can be received by my app; however, it doesn't get send.


问:
Heroku app successfully deploying, but receiving an application error when loading site
The message is that the app was successfully deployed but when I load the app it display this error:

An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command

My logs are indicating some errors but what is that I am doing wrong?

when run:

$ heroku logs -a disastresponse --tail

this is the output:

```<code>2022-02-11T04:06:42.642514+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
2022-02-11T04:06:42.642515+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2022-02-11T04:06:42.642516+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
2022-02-11T04:06:42.642516+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
2022-02-11T04:06:42.642516+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
2022-02-11T04:06:42.642517+00:00 app[web.1]: ModuleNotFoundError: No module named 'app'
2022-02-11T04:06:42.642579+00:00 app[web.1]: [2022-02-11 04:06:42 +0000] [10] [INFO] Worker exiting (pid: 10)
2022-02-11T04:06:42.676775+00:00 app[web.1]: [2022-02-11 04:06:42 +0000] [4] [WARNING] Worker with pid 10 was terminated due to signal 15
2022-02-11T04:06:42.776963+00:00 app[web.1]: [2022-02-11 04:06:42 +0000] [4] [INFO] Shutting down: Master
2022-02-11T04:06:42.777013+00:00 app[web.1]: [2022-02-11 04:06:42 +0000] [4] [INFO] Reason: Worker failed to boot.
</code>```

Procfile:

```<code>web: gunicorn app:run
</code>```

requirements.txt

```<code>flask==2.0.2
gunicorn==20.1.0
joblib==1.1.0
nltk==3.6.5
plotly==5.1.0
numpy==1.22.2
pandas==1.4.0
pip==21.2.4
regex==2021.8.3
scikit-learn==1.0.1
scipy==1.7.3
sqlalchemy==1.4.27
</code>```

Here all my run.py imports:

```<code>import json
import plotly
import pandas as pd
import numpy as np
import os

from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize

from flask import Flask
from flask import render_template, request, jsonify
from plotly.graph_objs import Bar
# from sklearn.externals import joblib
import joblib
from sqlalchemy import create_engine

app = Flask(__name__)
</code>```

Am I missing something?

答:
Your Gunicorn argument is backwards.

Since your app object is called app and it is in a file called run.py, you should launch Gunicorn like this:

```<code>web: gunicorn run:app
</code>```

Body:
The message is that the app was successfully deployed but when I load the app it display this error:

An error occurred in the application and your page could not be served. If you are the application owner, check your logs for details. You can do this from the Heroku CLI with the command

My logs are indicating some errors but what is that I am doing wrong?

when run:

$ heroku logs -a disastresponse --tail

this is the output:

2022-02-11T04:06:42.642514+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module
2022-02-11T04:06:42.642515+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level)
2022-02-11T04:06:42.642516+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
2022-02-11T04:06:42.642516+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
2022-02-11T04:06:42.642516+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked
2022-02-11T04:06:42.642517+00:00 app[web.1]: ModuleNotFoundError: No module named 'app'
2022-02-11T04:06:42.642579+00:00 app[web.1]: [2022-02-11 04:06:42 +0000] [10] [INFO] Worker exiting (pid: 10)
2022-02-11T04:06:42.676775+00:00 app[web.1]: [2022-02-11 04:06:42 +0000] [4] [WARNING] Worker with pid 10 was terminated due to signal 15
2022-02-11T04:06:42.776963+00:00 app[web.1]: [2022-02-11 04:06:42 +0000] [4] [INFO] Shutting down: Master
2022-02-11T04:06:42.777013+00:00 app[web.1]: [2022-02-11 04:06:42 +0000] [4] [INFO] Reason: Worker failed to boot.

Procfile:

web: gunicorn app:run

requirements.txt

flask==2.0.2
gunicorn==20.1.0
joblib==1.1.0
nltk==3.6.5
plotly==5.1.0
numpy==1.22.2
pandas==1.4.0
pip==21.2.4
regex==2021.8.3
scikit-learn==1.0.1
scipy==1.7.3
sqlalchemy==1.4.27

Here all my run.py imports:

import json
import plotly
import pandas as pd
import numpy as np
import os

from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize

from flask import Flask
from flask import render_template, request, jsonify
from plotly.graph_objs import Bar
# from sklearn.externals import joblib
import joblib
from sqlalchemy import create_engine

app = Flask(__name__)

Am I missing something?

Body:
Your Gunicorn argument is backwards.

Since your app object is called app and it is in a file called run.py, you should launch Gunicorn like this:

web: gunicorn run:app


问:
Iranian Grade Average Regex
I need a regex to handle the Iranian Grade average, regex should cover all these rules

Range of number should be between 0 to 20.

Numbers could be decimal except 20.

Integer part and decimal part should include one or two numbers.

If you use '.' you should have at least one decimal number.

examples:

20      true

19.99   true

14.5    true

12      true

4       true

0.22    true

00.02   true

10      true

14.23   true

09.23   true

21      false

30      false

123     false

12.222  false

09.     false

4.      false

.2      false

099     false

1.123   false

Title: Iranian Grade Average Regex

Body:
I tested this pattern and it works:

/(?<!\S)(([0-1]?[0-9])(.)([0-9]?[0-9])|([0-1][0-9])|\d{1}|(20))(?!\S)/


问:
How to play audio in 'react-native-webrtc'
I am working on an audio call app and was able to integrate the react-native-webrtc succesfully using this example https://github.com/jdmg94/react-native-webrtc-example/blob/master/App.js

I am able to stream the video between both devices but unable to stream audio. I am also using react-native-incall-manager for playing incoming call/ outgoing call ringtone. But no idea how to play the audio from the remote steam.

Can anyone please help me out.

答:
imagine receiving remote audio stream, no video, just plain audio stream All you have to do is to make sure your PeerConnection status is connected as what you always do with video stream. and react-native-webrtc will play your audio for you. so you dont have to call things like RTCView as you did with video stream.

You can just use PeerConnection and don't set stream's URL to a RTCView


问:
SQL join on N-M realtion with AND condition
I have TableA and TableB and a relation TableAB for a many to many (N-M) relation

TableA JOIN TableAB JOIN TableB

How can I add an AND-condition to check if TableAB has entries for multiple conditions in TableB

Maybe a stupid but simple example:

```<code>TableA = firstnames
TableB = lastnames
</code>```

I want all firstnames that are used in combination with lastname "Smith", "Black" AND "Taylor"

I thought about using

WHERE lastname = "Smith" or lastname = "Black" or lastname = "Taylor"

GROUP BY firstname and check if count(*) = 3

But this seems to be not the right way, as lastname = "Smith" or lastname = "Smith" or lastname = "Smith" should not return an empty table.

And it should be easy to extend, as the filter is user input, and don't know how many conditions I get.

Bonus question: I use Sequelize with a Many-to-Many Association, not sure how to put this in here

EDIT:

Example:
TableA

id
firstname

1
Tom

2
Alice

3
Bob

TableB

id
lastname

1
Smith

2
Black

3
Taylor

TableAB

id
id_firstname
id_lastname

1
1
1

2
2
1

3
2
2

2
3
3

Meaning we have Tom Smith, Alice Smith, Alice Black, Bob Taylor

Query: Give me all firstnames with lastname Smith AND Black

Result: Alice

答:
as always: there are different ways to achieve that. One is a multiple join of the NM table. Check the select on the end of the script (written for MS SQL Server). The rest of the script is just to create the sample data.

```<code>create table TableA (
    ID int not null,
    Firstname nvarchar(255) not null);

create table TableB (
    ID int not null,
    Lastname nvarchar(255) not null);

create table TableAB(
    IDA int not null,
    IDB int not null);

GO

insert into TableA values (1, 'Tom');
insert into TableA values (2, 'Alice');
insert into TableA values (3, 'Bob');

insert into TableB values (1, 'Smith');
insert into TableB values (2, 'Black');
insert into TableB values (3, 'Taylor');

insert into TableAB values (1, 1);
insert into TableAB values (2, 1);
insert into TableAB values (2, 2);
insert into TableAB values (3, 3);

GO

select A.Firstname
from TableA A
inner join TableAB AB1 on A.ID = AB1.IDA
inner join TableB B1 on B1.ID = AB1.IDB
inner join TableAB AB2 on A.ID = AB2.IDA
inner join TableB B2 on B2.ID = AB2.IDB
where B1.Lastname = 'Smith'
  and B2.Lastname = 'Black'
</code>```

other way would be a sub-select to return all combinations of Lastname + Firstname and then filter for the requested Lastname and count the occurance:

```<code>select Firstname
from (
    select distinct A.Firstname, B.Lastname
    from TableA A
    inner join TableAB AB on A.ID = AB.IDA
    inner join TableB B on B.ID = AB.IDB
) t
where Lastname in ('Smith', 'Black')
group by Firstname
having count(*) = 2
</code>```

Both ways will return Alice as a result only.

Body:
I have TableA and TableB and a relation TableAB for a many to many (N-M) relation

TableA JOIN TableAB JOIN TableB

How can I add an AND-condition to check if TableAB has entries for multiple conditions in TableB

Maybe a stupid but simple example:

TableA = firstnames
TableB = lastnames

I want all firstnames that are used in combination with lastname "Smith", "Black" AND "Taylor"

I thought about using

WHERE lastname = "Smith" or lastname = "Black" or lastname = "Taylor"

GROUP BY firstname and check if count(*) = 3

But this seems to be not the right way, as lastname = "Smith" or lastname = "Smith" or lastname = "Smith" should not return an empty table.

And it should be easy to extend, as the filter is user input, and don't know how many conditions I get.

Bonus question: I use Sequelize with a Many-to-Many Association, not sure how to put this in here

EDIT:

Example:
TableA

id
firstname

1
Tom

2
Alice

3
Bob

TableB

id
lastname

1
Smith

2
Black

3
Taylor

TableAB

id
id_firstname
id_lastname

1
1
1

2
2
1

3
2
2

2
3
3

Meaning we have Tom Smith, Alice Smith, Alice Black, Bob Taylor

Query: Give me all firstnames with lastname Smith AND Black

Result: Alice

Body:
as always: there are different ways to achieve that. One is a multiple join of the NM table. Check the select on the end of the script (written for MS SQL Server). The rest of the script is just to create the sample data.

create table TableA (
    ID int not null,
    Firstname nvarchar(255) not null);

create table TableB (
    ID int not null,
    Lastname nvarchar(255) not null);

create table TableAB(
    IDA int not null,
    IDB int not null);

GO

insert into TableA values (1, 'Tom');
insert into TableA values (2, 'Alice');
insert into TableA values (3, 'Bob');

insert into TableB values (1, 'Smith');
insert into TableB values (2, 'Black');
insert into TableB values (3, 'Taylor');

insert into TableAB values (1, 1);
insert into TableAB values (2, 1);
insert into TableAB values (2, 2);
insert into TableAB values (3, 3);

GO

select A.Firstname
from TableA A
inner join TableAB AB1 on A.ID = AB1.IDA
inner join TableB B1 on B1.ID = AB1.IDB
inner join TableAB AB2 on A.ID = AB2.IDA
inner join TableB B2 on B2.ID = AB2.IDB
where B1.Lastname = 'Smith'
  and B2.Lastname = 'Black'

other way would be a sub-select to return all combinations of Lastname + Firstname and then filter for the requested Lastname and count the occurance:

select Firstname
from (
    select distinct A.Firstname, B.Lastname
    from TableA A
    inner join TableAB AB on A.ID = AB.IDA
    inner join TableB B on B.ID = AB.IDB
) t
where Lastname in ('Smith', 'Black')
group by Firstname
having count(*) = 2

Both ways will return Alice as a result only.


问:
Unable to delete a file after using it with FileSystemResource in spring boot webapp?
I am trying to delete a file after uploading a file to a cloud storage location using a rest call by attaching the file in headers.(upload process is successful).
but i am unable to delete the file after upload got successful.
is there any way i can upload a large file(max 150 MB) through rest post call and afterwards i need to delete the file.

this is a production application so i need to opt for a best solution. i am using this above approach and also thinking to test with another approach - converting the file to MultipartFile and then uploading it to cloud . and then delete the file and MultipartFile afterwards.

```<code>
public void fileHandlingService(DocumentFileDetails documentFileDetails,UploadFileRequest uploadFileRequest){
 File file = new File(documentFileDetails.getFolderDirectory() + documentFileDetails.getFileName()
                + documentFileDetails.getFileExtension());
 uploadingFile(file,uploadFileRequest);

 //delete the file whether the upload is success or failure

 if (file.exists()) {
     //TODO unable to delete file here upload is successful but file resource is getting locked i guess
    FileUtils.forceDelete(file);
 }

}

public boolean uploadingFile(File file, UploadFileRequest uploadFileRequest) throws IOException {
        Resource fileResource=new FileSystemResource(file);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        PresignedFields fields = uploadFileRequest.getPresignedPost().getFields();
        //attaching some file details to the body
        //body.....

        body.add("Content-Disposition", "attachment; filename=\"" + uploadFileRequest.getFileName() + "\"");
        body.add("Content-Type", uploadFileRequest.getDocumentType());

        //file is getting upload to the cloud (need to upload file having size 150 mb)
        body.add("file", fileResource);

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        String serverUrl = uploadFileRequest.getPostUrl();
        try {
            ResponseEntity<Object> response = restTemplate.postForEntity(serverUrl, requestEntity, Object.class);

            if (response.getStatusCode() == HttpStatus.NO_CONTENT) {
                log.info("Successfully uploaded document", null);
                return true;
            }

            return false;
        } catch (Exception exception) {
            log.error("Exception when uploading file" + exception.getMessage(), null);
            throw new Exception(ErrorCode.FAILED_UPLOAD.getCode());
        }

    }

}
</code>```

using above code it is failing at this  line with IO exception  (guessing that fileSystemResource is not releasing the lock on the file)

```<code>FileUtils.forceDelete(file);
</code>```

Exception:

```<code>java.io.IOException: Cannot delete file: D:\TempFolder\TestFolder\Testfile.txt
    at org.apache.commons.io.FileUtils.forceDelete(FileUtils.java:1344) ~[commons-io-2.11.0.jar:2.11.0]
</code>```

答:
Identified my own mistake, so answering my own question.

FileUtils.forceDelete(file);

will delete the file if that file is not opened or not getting used any where by the code or machine.

In my case this file is being used by some cloud storage sync operation (like google drive) which is using this file to upload . so FileUtils is unable to delete  that file.

fixed the issue by not syncing the folder.

Body:
I am trying to delete a file after uploading a file to a cloud storage location using a rest call by attaching the file in headers.(upload process is successful).
but i am unable to delete the file after upload got successful.
is there any way i can upload a large file(max 150 MB) through rest post call and afterwards i need to delete the file.

this is a production application so i need to opt for a best solution. i am using this above approach and also thinking to test with another approach - converting the file to MultipartFile and then uploading it to cloud . and then delete the file and MultipartFile afterwards.

public void fileHandlingService(DocumentFileDetails documentFileDetails,UploadFileRequest uploadFileRequest){
 File file = new File(documentFileDetails.getFolderDirectory() + documentFileDetails.getFileName()
                + documentFileDetails.getFileExtension());
 uploadingFile(file,uploadFileRequest);

 //delete the file whether the upload is success or failure

 if (file.exists()) {
     //TODO unable to delete file here upload is successful but file resource is getting locked i guess
    FileUtils.forceDelete(file);
 }

}

public boolean uploadingFile(File file, UploadFileRequest uploadFileRequest) throws IOException {
        Resource fileResource=new FileSystemResource(file);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        PresignedFields fields = uploadFileRequest.getPresignedPost().getFields();
        //attaching some file details to the body
        //body.....

        body.add("Content-Disposition", "attachment; filename=\"" + uploadFileRequest.getFileName() + "\"");
        body.add("Content-Type", uploadFileRequest.getDocumentType());

        //file is getting upload to the cloud (need to upload file having size 150 mb)
        body.add("file", fileResource);

        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);
        String serverUrl = uploadFileRequest.getPostUrl();
        try {
            ResponseEntity<Object> response = restTemplate.postForEntity(serverUrl, requestEntity, Object.class);

            if (response.getStatusCode() == HttpStatus.NO_CONTENT) {
                log.info("Successfully uploaded document", null);
                return true;
            }

            return false;
        } catch (Exception exception) {
            log.error("Exception when uploading file" + exception.getMessage(), null);
            throw new Exception(ErrorCode.FAILED_UPLOAD.getCode());
        }

    }

}

using above code it is failing at this  line with IO exception  (guessing that fileSystemResource is not releasing the lock on the file)

FileUtils.forceDelete(file);

Exception:

java.io.IOException: Cannot delete file: D:\TempFolder\TestFolder\Testfile.txt
    at org.apache.commons.io.FileUtils.forceDelete(FileUtils.java:1344) ~[commons-io-2.11.0.jar:2.11.0]