问:
or [self dealloc] work?
I make a object that use the camera to decode a bar code. If it was successful it send a delegate message to next action, if not, it only go out, and next screen start to work.

If am I in the last command of the object, can I send [self release] to free the memory? But, the problem is: the retainCount can be more than on one?

Like

```<code>  ObjectToDealloc *test = [[ObjectToDealloc alloc] init];
  [test doYourJob];
  //can't release here, it broke my program
</code>```

in the last thing that this object do, it run:

```<code>  -(void)destroyYourself {
     [self release];
     [self dealloc];
  }
</code>```

This will work? I will release the memory? Or I have to make "test" in global visibility (not only function visibility) and do a:

```<code>   [test release];
</code>```

答:
There are a couple of instances where I have seen classes that retain themselves in order to keep themselves around until they perform work.  NEVER, EVER, EVER CALL DEALLOC*.  Dealloc is not for you, but the runtime.  If you no longer need an object, just appropriately release it.  It is only the runtime's duty to call that method.

Here's an example of some code that I regularly use where the object retains itself and then appropriately releases itself when done with its work:  UIAlertView+Blocks  This code does this because the object is suppose to stick around, even after it has been released by the instantiating class so that it can run and finish the blocks it was given to execute.

*Except when calling your super's dealloc within your own dealloc, but this goes without saying.

Title: or [self dealloc] work?

Body:
I make a object that use the camera to decode a bar code. If it was successful it send a delegate message to next action, if not, it only go out, and next screen start to work.

If am I in the last command of the object, can I send [self release] to free the memory? But, the problem is: the retainCount can be more than on one?

Like

  ObjectToDealloc *test = [[ObjectToDealloc alloc] init];
  [test doYourJob];
  //can't release here, it broke my program

in the last thing that this object do, it run:

  -(void)destroyYourself {
     [self release];
     [self dealloc];
  }

This will work? I will release the memory? Or I have to make "test" in global visibility (not only function visibility) and do a:

   [test release];


来源: stackexchange

问:
Tomcat manager/html is not available?
Hi I just installed Tomcat and and am trying to get it up and running however whenever I try to navigate to manager/html it gives me this error "The requested resource (/manager/html) is not available".

The homepage, /docs, /examples all work fine and my logs show nothing. How do I fix this? I'm using Tomcat 6.0.20 and JDK 1.6.0_21 on Windows 7 64bit.

答: After entering the roles and users in tomcat-users still if does not work make sure your tomact server location point to the right server location</p>

ContentLicense: CC BY-SA 2.5

Title: Tomcat manager/html is not available?

ContentLicense: CC BY-SA 4.0


问:
setState is not updating in my other method
I'm very new to react and i'm confused why my state is not updated in another method of mine see example below.

```<code>fetchMovies = () => {
    const self = this;
    axios.get("https://api.themoviedb.org/3/trending/movie/day?api_key=XXXXXXX")
        .then(function(response){
            console.log(response.data)
            self.setState({
                collection: response.data.results
            })
            console.log(self.state.collection)
        });
}

makeRow = () => {
    console.log(this.state.collection.length);
    if(this.state.collection.length !== 0) {
        var movieRows = [];
        this.state.collection.forEach(function (i) {
            movieRows.push(<p>{i.id}</p>);
        });

        this.setState({
            movieRow: movieRows
        })
    }

}

componentDidMount() {
    this.fetchMovies();
    this.makeRow();
}
</code>```

When inside of fetchMovies function i can access collection and it has all the data but this is the part i can't understand in the makeRow function when i console log the state i would of expected the updated state to show here but it doesn't i'm even executing the functions in sequence.

Thanks in advance.

答:
The setState() documentation contains the following paragraph:

Think of setState() as a request rather than an immediate command
  to update the component. For better perceived performance, React may
  delay it, and then update several components in a single pass. React
  does not guarantee that the state changes are applied immediately.

To access the modified state you need to use the function signature setState(updater, [callback]), so in your case it should be;

```<code>self.setState({
    collection: response.data.results
}, () => { // Will be executed after state update
  console.log(self.state.collection)
  // Call your make row function here and remove it from componentDidMount if that is all it does.
  self.makeRow()
} )
</code>```

Body:
I'm very new to react and i'm confused why my state is not updated in another method of mine see example below.

fetchMovies = () => {
    const self = this;
    axios.get("https://api.themoviedb.org/3/trending/movie/day?api_key=XXXXXXX")
        .then(function(response){
            console.log(response.data)
            self.setState({
                collection: response.data.results
            })
            console.log(self.state.collection)
        });
}

makeRow = () => {
    console.log(this.state.collection.length);
    if(this.state.collection.length !== 0) {
        var movieRows = [];
        this.state.collection.forEach(function (i) {
            movieRows.push(
{i.id}
);
        });

        this.setState({
            movieRow: movieRows
        })
    }

}

componentDidMount() {
    this.fetchMovies();
    this.makeRow();
}

When inside of fetchMovies function i can access collection and it has all the data but this is the part i can't understand in the makeRow function when i console log the state i would of expected the updated state to show here but it doesn't i'm even executing the functions in sequence.

Thanks in advance.

Body:
The setState() documentation contains the following paragraph:

Think of setState() as a request rather than an immediate command
  to update the component. For better perceived performance, React may
  delay it, and then update several components in a single pass. React
  does not guarantee that the state changes are applied immediately.

To access the modified state you need to use the function signature setState(updater, [callback]), so in your case it should be;

self.setState({
    collection: response.data.results
}, () => { // Will be executed after state update
  console.log(self.state.collection)
  // Call your make row function here and remove it from componentDidMount if that is all it does.
  self.makeRow()
} )


问:
JSON reformatting in PostgreSQL
In a PostgreSQL table I have a column with a JSON like:

{"elements":[{"val":"value1", "column":"column1"}, {"val":"val2", "column":"column2"}, ...]}.

Is any way to transform this to result set like:

```<code>column1 | column2 | ...
-----------------------
value1  | value2  | ...
</code>```

I worked around PostgreSQL JSON functions but didn't find an answer.

答:
Based on @a_horse_with_no_name proposal:

```<code>select
    jsonb_path_query_first(raw_data_1thbase.data -> 'elements', '$[*] ? (@.column == "column1").val' ) #>> '{}' as column1,
    jsonb_path_query_first(raw_data_1thbase.data -> 'elements', '$[*] ? (@.column == "column2").val' ) #>> '{}' as column2
from data;
</code>```

worked for me.

Title: JSON reformatting in PostgreSQL

Body:
In a PostgreSQL table I have a column with a JSON like:

{"elements":[{"val":"value1", "column":"column1"}, {"val":"val2", "column":"column2"}, ...]}.

Is any way to transform this to result set like:

column1 | column2 | ...
-----------------------
value1  | value2  | ...

I worked around PostgreSQL JSON functions but didn't find an answer.

Body:
Based on @a_horse_with_no_name proposal:

select
    jsonb_path_query_first(raw_data_1thbase.data -> 'elements', '$[*] ? (@.column == "column1").val' ) #>> '{}' as column1,
    jsonb_path_query_first(raw_data_1thbase.data -> 'elements', '$[*] ? (@.column == "column2").val' ) #>> '{}' as column2
from data;

worked for me.


问:
Updated row in table only by valid values and skip undefined values
I have next method which updates row:

```<code>  await db.query(`
    UPDATE some_table
    SET value1 = $1, value12 = $2, value2 = $3
    WHERE id $5
  `, [value1, value2, value3, id]);
</code>```

How to modify this query, that it will skip for example value2 and value3, if they are undefined and update only column value1?

答:
You can use a CASE expression: </p>

```<code>UPDATE some_table
  SET value1 = $1,
      value12 = case when when value12 = 'undefined' then $2 else value12 end,
      value2 = case when value2 = 'undefined' then $3 else value2 end
WHERE id = $5
</code>```

Body:
I have next method which updates row:

  await db.query(`
    UPDATE some_table
    SET value1 = $1, value12 = $2, value2 = $3
    WHERE id $5
  `, [value1, value2, value3, id]);

How to modify this query, that it will skip for example value2 and value3, if they are undefined and update only column value1?

Body:
You can use a CASE expression:

UPDATE some_table
  SET value1 = $1,
      value12 = case when when value12 = 'undefined' then $2 else value12 end,
      value2 = case when value2 = 'undefined' then $3 else value2 end
WHERE id = $5


问:
How to access a SOAP webservice from my iPhone app
```<code>I am new to iPhone application development and also this stackoverflow,if I made any mistakes sorry. I have some of the questions
</code>```

1) Do I need to install any other external framework into my application. I am using SDK Simulator 4.2

2) I have gone through some of the material which was posted here, I found some code and I made some modification to suits my application When I am requesting for a URL it is returning me NULL.

3) My task is to send a three parameters into database.

```<code> NSString *post =[NSString stringWithFormat:@"?FirstName=%@?Surname=%@?IDNumber=%@?DOB=%@",namestring,surnamestring,cidstring,dobstring];

 NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

 NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSLog(@"Post Length:",[postData length]);

 NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

[request setURL:[NSURL URLWithString:@"http://www.esoft.co.za/MDS/Service1.asmx?op=InsertSuppliers"]];

 [request setHTTPMethod:@"GET"];

 [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

 [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

 [request setHTTPBody:postData];

 NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(@"response data is: %@",[responseData length] );
 NSString *data = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
 NSLog(@"Data: %@",data);
</code>```

Thanks in Advance Guys...Please provide me any sample code or material..

答:
I think it's because you're trying to send invalid request. Just try to check and log error message to see what's wrong.

What you're trying to do is to send POST data over GET request, which is wrong anyway. I'm also not sure about those "Post" data format, but when you'll check error message you'll find what's wrong.

```<code>NSLog(@"Request failed with error: %@", [err localizedDescription]);
</code>```

best

ContentLicense: CC BY-SA 3.0

Body:
I am new to iPhone application development and also this stackoverflow,if I made any mistakes sorry. I have some of the questions

1) Do I need to install any other external framework into my application. I am using SDK Simulator 4.2

2) I have gone through some of the material which was posted here, I found some code and I made some modification to suits my application When I am requesting for a URL it is returning me NULL.

3) My task is to send a three parameters into database.

 NSString *post =[NSString stringWithFormat:@"?FirstName=%@?Surname=%@?IDNumber=%@?DOB=%@",namestring,surnamestring,cidstring,dobstring];

 NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

 NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSLog(@"Post Length:",[postData length]);

 NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

[request setURL:[NSURL URLWithString:@"http://www.esoft.co.za/MDS/Service1.asmx?op=InsertSuppliers"]];

 [request setHTTPMethod:@"GET"];

 [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

 [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

 [request setHTTPBody:postData];

 NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(@"response data is: %@",[responseData length] );
 NSString *data = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
 NSLog(@"Data: %@",data);

Thanks in Advance Guys...Please provide me any sample code or material..

Body:
I think it's because you're trying to send invalid request. Just try to check and log error message to see what's wrong.

What you're trying to do is to send POST data over GET request, which is wrong anyway. I'm also not sure about those "Post" data format, but when you'll check error message you'll find what's wrong.

NSLog(@"Request failed with error: %@", [err localizedDescription]);

best


问:
Monte Carlo Tree Search: Getting a value from the rollout
I am currently writing an implementation of Monte Carlo Tree Search for a strategy game AI, and have a question about the Rollout (simulation phase).

Descriptions of the algorithm suggest that you should run a simulation until a terminal state is reached, but this is impractical when you have a large search space and a finite time. In my case, I limit the number of simulation steps to a certain value (or finish early if terminating).

At each step in the simulation I evaluate the state but since a simulation consists of a sequence of random actions the evaluated value can increase or decrease during a simulation. The question is: For a non-terminal state simulation, should I return the last state evaluation, or the best state evaluation that was observed during that run?

答:
Typically you would use the value at the end of the simulation. But, MCTS is regularly adapted for many different domains, so you are free to adapt it in a way that gives you the best possible performance.

This idea was, to my knowledge, first proposed for amazons. There they only used a random walk of "about 6 moves" before applying the evaluation function.


答:
the collection is set after the async call is resolved. Even though makeRow method is called after fetchMoview, coz of async call, u will never know when the call will be resolved and collection state will be set.

There is no need to keep movieRows in the state as that is just needed for rendering. Keeping html mockup in the state is never a good idea.

So u should just call fetchMoviews in the componentDidMount and render the data in as follows:

```<code>render() {
 const { collection } = this.state;

 return (
  <>
   {
     collection.map(c => <p>{c.id}</p>)
   }
  </>
 )
}
</code>```

make sure the initial value for collection in the state is [] .

Title: setState is not updating in my other method

Body:
the collection is set after the async call is resolved. Even though makeRow method is called after fetchMoview, coz of async call, u will never know when the call will be resolved and collection state will be set.

There is no need to keep movieRows in the state as that is just needed for rendering. Keeping html mockup in the state is never a good idea.

So u should just call fetchMoviews in the componentDidMount and render the data in as follows:

render() {
 const { collection } = this.state;

 return (
  <>
   {
     collection.map(c => <p>{c.id}</p>)
   }
  </>
 )
}

make sure the initial value for collection in the state is [] .


问:
"String @NotNull []" syntax causes "'@NotNull' not applicable to type use" in intellij IDEA plugin
I am trying to fix a few bugs in an old, now open-sourced intellij IDEA plugin (the CFML Plugin)

The following Syntax appears several times in multiple files and generates an error:

```<code>String @NotNull []
</code>```

This is what the error looks like:

The example is from the following file:
https://github.com/JetBrains/intellij-plugins/blob/master/CFML/src/com/intellij/coldFusion/model/CfmlUtil.java#L249

What does this syntax do?
I haven't found any information on it. It seems like @NotNull String[] would do exactly the same thing without the error.

How do I get this to work?
I have followed the setup instructions for setting up a development environment and creating a plugin project exactly. What is my environment missing to run this code?

答:
I suspect that you don't have the JetBrains Annotations library installed. Please follow the installation guide here.

The String @NotNull [] syntax consists of the @NotNull annotation applied to the String[] type. Note that this is different from @NotNull String[], in which @NotNull only applies to the String type. The annotation is used in this way to say that the string array returned will not be null, but the strings inside it might be.

Compare:

@NotNull String @Nullable []: strings in the returned array must be non null, but a null array could be returned.

@NotNull String @NotNull []: strings in the returned array must be non null, and the array must also be non null

@Nullable String @NotNull []: The string array must be non null, but the strings inside it might be null

@Nullable String @Nullable []: The string array could be null, and there might be null strings in it too

Body:
I am trying to fix a few bugs in an old, now open-sourced intellij IDEA plugin (the CFML Plugin)

The following Syntax appears several times in multiple files and generates an error:

String @NotNull []

This is what the error looks like:

The example is from the following file:
https://github.com/JetBrains/intellij-plugins/blob/master/CFML/src/com/intellij/coldFusion/model/CfmlUtil.java#L249

What does this syntax do?
I haven't found any information on it. It seems like @NotNull String[] would do exactly the same thing without the error.

How do I get this to work?
I have followed the setup instructions for setting up a development environment and creating a plugin project exactly. What is my environment missing to run this code?


问:
Specifying amount of people to mention from choice
I am trying to make a command that selects more than one person in a voice channel and mentions them.

Currently, I have made it so one person is mentioned:

```<code>@commands.command()
async def hns(self, message):
    await message.channel.send(choice(tuple(member.mention for member in message.author.voice.channel.members if not member.bot)))
    await message.channel.send("You have been chosen to seek.")
</code>```

I have been trying to add an argument in the command such as arg, but I am not sure where to go from there.

Possible solutions:

I am not used to using the message argument so I'm not sure but maybe using ctx instead would allow for more?

Any ideas?

答:
The first argument in commands using decorators are always context objects, they're just called ctx by convention. This means that your message arg is actually the context object.

Another possible solution could be shuffling the list of members and then choosing x number of them, like so:

@commands.command()
async def hns(self, ctx, amount: int):
    members = [m.mention for m in ctx.author.voice.channel.members if not m.bot]
    random.shuffle(members) # shuffles it in place, i.e. doesn't return the list
    selected = members[:amount]
    await ctx.send(f"{', '.join(selected)}, you've been chosen to seek!")
```

The usage of the command would be:

!hns 3

Selecting 3 users randomly. This would avoid having to use a hard-coded value, although you can do it that way if you want to.

References:

random.shuffle()

VoiceChannel.members

Member.mention

commands.Context

Body:
I am trying to make a command that selects more than one person in a voice channel and mentions them.

Currently, I have made it so one person is mentioned:

@commands.command()
async def hns(self, message):
    await message.channel.send(choice(tuple(member.mention for member in message.author.voice.channel.members if not member.bot)))
    await message.channel.send("You have been chosen to seek.")

I have been trying to add an argument in the command such as arg, but I am not sure where to go from there.

Possible solutions:

I am not used to using the message argument so I'm not sure but maybe using ctx instead would allow for more?

Any ideas?

Body:
The first argument in commands using decorators are always context objects, they're just called ctx by convention. This means that your message arg is actually the context object.

Another possible solution could be shuffling the list of members and then choosing x number of them, like so:

@commands.command()
async def hns(self, ctx, amount: int):
    members = [m.mention for m in ctx.author.voice.channel.members if not m.bot]
    random.shuffle(members) # shuffles it in place, i.e. doesn't return the list
    selected = members[:amount]
    await ctx.send(f"{', '.join(selected)}, you've been chosen to seek!")

The usage of the command would be:

!hns 3

Selecting 3 users randomly. This would avoid having to use a hard-coded value, although you can do it that way if you want to.

References:

random.shuffle()

VoiceChannel.members

Member.mention

commands.Context


问:
Analyzing data in order of column and then row in R
I have a dataset of logged data at 5 minutes intervals that also includes data at 1 minute intervals denoted by _1 - _5 in the header.
Each row represents a 5 minute interval.

```<code>datetime            temp  speed_1  speed_2  speed_3  speed_4  speed_5
20190710 09:00:00   21    13       14       26       29       32
20190710 09:05:00   21    28       28       29       38       12
20190710 09:10:00   20    8        15       29       30       19
20190711 11:12:00   18    6        9        18       51       49
20190711 11:17:00   17    49       48       48       30       10
</code>```

The actual dataset has an additional 25 columns of data logged at 5 minute intervals and consists of approximately 25000 rows.

I'm looking for an efficient way of analyzing the speed for each day.
For example, if I wanted to plot the speed for each day it would take speed_1 to speed_5 from the earliest entry on a particular day, say 09:00:00, then speed_1 to speed_5 from the next time, 09:05:00, and so on for the whole day.

Currently I have created an additional dataframe for the speed that fills in the times to give:

```<code>datetime            speed
20190710 09:00:00   13
20190710 09:01:00   14
20190710 09:02:00   26
20190710 09:03:00   29
20190710 09:04:00   32
</code>```

This results in having a second df of 125000 entries. I was wondering if there was a more memory efficient way of analyzing the original dataset as the datasets may grow considerably in the future.

Edit: Reproducible code added

structure(list(time = structure(1:3, .Label = c("20190710 09-00-00", "20190710 09-05-00", "20190710 09-10-00"), class = "factor"), temp = c(21, 21, 20), speed_1 = c(13, 28, 8), speed_2 = c(14, 28, 15), speed_3 = c(26, 29, 29), speed_4 = c(29, 38, 30), speed_5 = c(32, 12, 19)), .Names = c("time", "temp", "speed_1", "speed_2", "speed_3", "speed_4", "speed_5"), row.names = c(NA, -3L), class = "data.frame")

Body:
I have a dataset of logged data at 5 minutes intervals that also includes data at 1 minute intervals denoted by _1 - _5 in the header.
Each row represents a 5 minute interval.

datetime            temp  speed_1  speed_2  speed_3  speed_4  speed_5
20190710 09:00:00   21    13       14       26       29       32
20190710 09:05:00   21    28       28       29       38       12
20190710 09:10:00   20    8        15       29       30       19
20190711 11:12:00   18    6        9        18       51       49
20190711 11:17:00   17    49       48       48       30       10

The actual dataset has an additional 25 columns of data logged at 5 minute intervals and consists of approximately 25000 rows.

I'm looking for an efficient way of analyzing the speed for each day.
For example, if I wanted to plot the speed for each day it would take speed_1 to speed_5 from the earliest entry on a particular day, say 09:00:00, then speed_1 to speed_5 from the next time, 09:05:00, and so on for the whole day.

Currently I have created an additional dataframe for the speed that fills in the times to give:

datetime            speed
20190710 09:00:00   13
20190710 09:01:00   14
20190710 09:02:00   26
20190710 09:03:00   29
20190710 09:04:00   32

This results in having a second df of 125000 entries. I was wondering if there was a more memory efficient way of analyzing the original dataset as the datasets may grow considerably in the future.

Edit: Reproducible code added

structure(list(time = structure(1:3, .Label = c("20190710 09-00-00", "20190710 09-05-00", "20190710 09-10-00"), class = "factor"), temp = c(21, 21, 20), speed_1 = c(13, 28, 8), speed_2 = c(14, 28, 15), speed_3 = c(26, 29, 29), speed_4 = c(29, 38, 30), speed_5 = c(32, 12, 19)), .Names = c("time", "temp", "speed_1", "speed_2", "speed_3", "speed_4", "speed_5"), row.names = c(NA, -3L), class = "data.frame")

Body:
Here is something raw using data.table:

library(data.table)
setDT(df)
df[, time := as.POSIXct(time, format="%Y%m%d %H-%M-%OS")]
out <-
  df[, !"temp"
   ][, melt(.SD, id.vars = "time")
     ][, time := time + (rleid(variable)-1)*60, time
       ][order(time), !"variable"]
out

#                    time value
#  1: 2019-07-10 09:00:00    13
#  2: 2019-07-10 09:01:00    14
#  3: 2019-07-10 09:02:00    26
#  4: 2019-07-10 09:03:00    29
#  5: 2019-07-10 09:04:00    32
#  6: 2019-07-10 09:05:00    28
#  7: 2019-07-10 09:06:00    28
#  8: 2019-07-10 09:07:00    29
#  9: 2019-07-10 09:08:00    38
# 10: 2019-07-10 09:09:00    12
# 11: 2019-07-10 09:10:00     8
# 12: 2019-07-10 09:11:00    15
# 13: 2019-07-10 09:12:00    29
# 14: 2019-07-10 09:13:00    30
# 15: 2019-07-10 09:14:00    19

Data:

df <- data.frame(
  time = factor(c("20190710 09-00-00", "20190710 09-05-00", "20190710 09-10-00")),
  temp = c(21, 21, 20),
  speed_1 = c(13, 28, 8),
  speed_2 = c(14, 28, 15),
  speed_3 = c(26, 29, 29),
  speed_4 = c(29, 38, 30),
  speed_5 = c(32, 12, 19)
)


问:
Alter column script not working SQL Server
I need to alter my column length, using below query i tried but the result was not what i expected

```<code>alter table clear.tbl_wlist_data_alias_dtls
  alter column entity_name nvarchar(500);
</code>```

Earlier, the column size is 1200  and i tried to decrease it to 500 but after executing above query column length changed to 1000.

Facing the same scenario even if i increase the column length.

My column is having constraint, is that restricting ??

Thanks in advance,
AnilSrinivas

答: Tq @Martin, sp_help shows the actual size(in bytes) required by the column to store the data on the database. since column is of type nvarchar so it require double space to store the data hence it show the 1000 bytes as column length to store the 500 characters.</p>

Body:
I need to alter my column length, using below query i tried but the result was not what i expected

alter table clear.tbl_wlist_data_alias_dtls
  alter column entity_name nvarchar(500);

Earlier, the column size is 1200  and i tried to decrease it to 500 but after executing above query column length changed to 1000.

Facing the same scenario even if i increase the column length.

My column is having constraint, is that restricting ??

Thanks in advance,
AnilSrinivas


问:
can't change value by key
I'm new to JavaScript. I have a tree structure and I want to change "tags" property value from an array of strings to a string when the array length is bigger than 5.

```<code>ChangeTags(obj) {
    Object.keys(obj).forEach(key => {
      (key === 'tags' && obj[key].length > 5) && obj["tags"] = "some value" ||
      (obj[key] && typeof obj[key] === 'object') && this.removeEmptyNodes(obj[key]);
    });
    return obj;
  };
</code>```

The interpreter does not allow me to do the assignment in the 4th line. What am I doing wrong?

答:
i think your problem is brackets. try this:</p>

```<code>ChangeTags(obj) {
Object.keys(obj).forEach(key => {
  ((key === 'tags' && obj[key].length > 5) && obj["tags"] = "some value") ||
  ((obj[key] && typeof obj[key] === 'object') && this.removeEmptyNodes(obj[key]));
});
return obj;
};
</code>```

Title: can't change value by key

Body:
I'm new to JavaScript. I have a tree structure and I want to change "tags" property value from an array of strings to a string when the array length is bigger than 5.

ChangeTags(obj) {
    Object.keys(obj).forEach(key => {
      (key === 'tags' && obj[key].length > 5) && obj["tags"] = "some value" ||
      (obj[key] && typeof obj[key] === 'object') && this.removeEmptyNodes(obj[key]);
    });
    return obj;
  };

The interpreter does not allow me to do the assignment in the 4th line. What am I doing wrong?

Body:
i think your problem is brackets. try this:

ChangeTags(obj) {
Object.keys(obj).forEach(key => {
  ((key === 'tags' && obj[key].length > 5) && obj["tags"] = "some value") ||
  ((obj[key] && typeof obj[key] === 'object') && this.removeEmptyNodes(obj[key]));
});
return obj;
};


问:
Liferay - Hook for GroupWrapper
I'm trying to override the getDescriptiveName() method in com.liferay.portal.model.Group

I found a wrapper (com.liferay.portal.model.GroupWrapper), so I tried to write a hook as written in the documentation :

liferay-hook.xml:

<service>
    <service-type>com.liferay.portal.model.GroupWrapper</service-type>
    <service-impl>fr.villedeniort.hook.expando.GroupWrapperImpl</service-impl>
</service>
```

<p><code>fr.villedeniort.hook.expando.GroupWrapperImpl.java</code>:</p>

<pre class="lang-java prettyprint-override"><code>public class GroupWrapperImpl extends GroupWrapper {
    public GroupWrapperImpl(Group group) {
    super(group);
}

@Override
public java.lang.String getDescriptiveName()
  throws com.liferay.portal.kernel.exception.PortalException,
  com.liferay.portal.kernel.exception.SystemException {
    return super.getDescriptiveName();
}
</code>```

When the hook is deployed, it raises an exception :

```<code>java.lang.NoSuchMethodException: fr.villedeniort.hook.expando.GroupWrapperImpl.<init>(com.liferay.portal.model.GroupWrapper)
</code>```

I browse the code I found out that it breaks at this part for a reason I ignore:

Constructor<?> serviceImplConstructor = serviceImplClass.getConstructor(new Class<?>[] {serviceTypeClass});
```

<p>At this point, variables have theses values:</p>

```serviceType "com.liferay.portal.model.GroupWrapper" (id=14829)
serviceImpl "fr.villedeniort.hook.expando.GroupWrapperImpl" (id=14830)
serviceTypeClass Class<T> (com.liferay.portal.model.GroupWrapper) (id=14831)
serviceImplClass Class<T> (fr.villedeniort.hook.expando.GroupWrapperImpl) (id=14832)
```

Do you have any idea?

Thanks!

答:
You should have also a constructor without any argument. Now you have one with constuctor arguments, but there is no pure class constructor that java searches when it makes class instance. After calling the pure constructor java then calls the argumented one.

I had similar case in some other context and this was the solution. <init> tag on the error message refers on this kind of issue.

Title: Liferay - Hook for GroupWrapper

Body:
I'm trying to override the getDescriptiveName() method in com.liferay.portal.model.Group

I found a wrapper (com.liferay.portal.model.GroupWrapper), so I tried to write a hook as written in the documentation :

liferay-hook.xml:

<service>
    <service-type>com.liferay.portal.model.GroupWrapper</service-type>
    <service-impl>fr.villedeniort.hook.expando.GroupWrapperImpl</service-impl>
</service>

fr.villedeniort.hook.expando.GroupWrapperImpl.java:

public class GroupWrapperImpl extends GroupWrapper {
    public GroupWrapperImpl(Group group) {
    super(group);
}

@Override
public java.lang.String getDescriptiveName()
  throws com.liferay.portal.kernel.exception.PortalException,
  com.liferay.portal.kernel.exception.SystemException {
    return super.getDescriptiveName();
}

When the hook is deployed, it raises an exception :

java.lang.NoSuchMethodException: fr.villedeniort.hook.expando.GroupWrapperImpl.<init>(com.liferay.portal.model.GroupWrapper)

I browse the code I found out that it breaks at this part for a reason I ignore:

Constructor<?> serviceImplConstructor = serviceImplClass.getConstructor(new Class<?>[] {serviceTypeClass});

At this point, variables have theses values:

serviceType "com.liferay.portal.model.GroupWrapper" (id=14829)
serviceImpl "fr.villedeniort.hook.expando.GroupWrapperImpl" (id=14830)
serviceTypeClass Class<T> (com.liferay.portal.model.GroupWrapper) (id=14831)
serviceImplClass Class<T> (fr.villedeniort.hook.expando.GroupWrapperImpl) (id=14832)

Do you have any idea?

Thanks!


答:
A bit late to the party here. This one-liner in Base-R

```<code>lapply(split(df,df$Agent), function(x) paste0(unique(df$Date)[!unique(df$Date) %in% x$Date], collapse="; "))
</code>```

gives

```<code>$A
[1] ""

$B
[1] "2020-02-11; 2020-02-13; 2020-02-14"

$C
[1] "2020-02-12; 2020-02-13"
</code>```

Title: Extract rows from dataframe which were absent on certain days

Body:
I have a dataframe:

Date          Agent
2020-02-10    A
2020-02-11    A
2020-02-12    A
2020-02-13    A
2020-02-14    A
2020-02-10    B
2020-02-12    B
2020-02-10    C
2020-02-11    C
2020-02-14    C

I want to get a data frame with those row which were absent at certain days from 2020-02-10 to 2020-02-14. So desired output is:

Agent  Days_absent
B      2020-02-11; 2020-02-13; 2020-02-14
C      2020-02-12; 2020-02-13

or

Date          Agent
2020-02-11    B
2020-02-13    B
2020-02-14    B
2020-02-12    C
2020-02-13    C

How could i do that?

Body:
A bit late to the party here. This one-liner in Base-R

lapply(split(df,df$Agent), function(x) paste0(unique(df$Date)[!unique(df$Date) %in% x$Date], collapse="; "))

gives

$A
[1] ""

$B
[1] "2020-02-11; 2020-02-13; 2020-02-14"

$C
[1] "2020-02-12; 2020-02-13"


问:
Python: Verify Credit Card digits
I  need to implement a function called “verify” that takes a single parameter
called “number” and then checks the following rules:

The first digit must be a 4.

The fourth digit must be one greater than the fifth digit; keep in mind that these
are separated by a dash since the format is ####-####-####.

The sum of all digits must be evenly divisible by 4.

If you treat the first two digits as a two-digit number, and the seventh and eighth
digits as a two-digit number, their sum must be 100

This is what I have come up with so far:

```<code>def verify(number): # do not change this line!

  list_number=list(number.split(''))
  Check=false

# write your code here so that it verifies the card number

    if list_number[0]==4:
    if list_number[3]==list_number[5]+1:
    if list_number.sum() % 4==0:
    if int(str(list_number[0])+str(list_number[1]))+int(str(list_number[7])+str(list_number[8])) ==100:

    Check = true

    else:
    check = false

input = "4094-3460-2754" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output
</code>```

答:
Your code is way to poorly written</p>

```<code>list_number = "4094-3460-2754"
list_number = list_number.replace('-','')

if list_number[0]=='4' and int(list_number[3])==int(list_number[5])+1 and list_number.sum() % 4==0 and int(list_number[0])+int(list_number[1])==int(list_number[7])+int(list_number[8]):
    check = True
else:
    check = False
</code>```

Title: Python: Verify Credit Card digits

Body:
I  need to implement a function called “verify” that takes a single parameter
called “number” and then checks the following rules:

The first digit must be a 4.

The fourth digit must be one greater than the fifth digit; keep in mind that these
are separated by a dash since the format is ####-####-####.

The sum of all digits must be evenly divisible by 4.

If you treat the first two digits as a two-digit number, and the seventh and eighth
digits as a two-digit number, their sum must be 100

This is what I have come up with so far:

def verify(number): # do not change this line!

  list_number=list(number.split(''))
  Check=false

# write your code here so that it verifies the card number

    if list_number[0]==4:
    if list_number[3]==list_number[5]+1:
    if list_number.sum() % 4==0:
    if int(str(list_number[0])+str(list_number[1]))+int(str(list_number[7])+str(list_number[8])) ==100:

    Check = true

    else:
    check = false

input = "4094-3460-2754" # change this as you test your function
output = verify(input) # invoke the method using a test input
print(output) # prints the output

Body:
Your code is way to poorly written

list_number = "4094-3460-2754"
list_number = list_number.replace('-','')

if list_number[0]=='4' and int(list_number[3])==int(list_number[5])+1 and list_number.sum() % 4==0 and int(list_number[0])+int(list_number[1])==int(list_number[7])+int(list_number[8]):
    check = True
else:
    check = False


问:
Getting a strange error 403 forbidden for accessing an API through python
I am trying to access some email stats: My code:

```<code>import json
import os
from sendgrid.helpers.stats import *
from sendgrid import *

# NOTE: you will need move this file to the root directory of this project to execute properly.

# Assumes you set your environment variable:
# https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key
sg = SendGridAPIClient(os.environ.get('SG****'))

def pprint_json(json_raw):
    print(json.dumps(json.loads(json_raw), indent=2, sort_keys=True))

def build_global_stats():
    global_stats = Stats()
    global_stats.start_date = '2020-01-13'
    global_stats.end_date = '2020-01-14'
    global_stats.aggregated_by = 'day'
    return global_stats.get()

def get_global_stats():
    stats_params = build_global_stats()
    response = sg.client.stats.get(query_params=stats_params)
    print(response.status_code)
    print(response.headers)
    pprint_json(response.body)

get_global_stats()
Traceback (most recent call last):

  File "<ipython-input-10-cee8ef5434a2>", line 35, in <module>
    get_global_stats()

  File "<ipython-input-10-cee8ef5434a2>", line 29, in get_global_stats
    response = sg.client.stats.get(query_params=stats_params)

  File "C:\Users\blah\AppData\Local\Continuum\anaconda3\lib\site-packages\python_http_client\client.py", line 262, in http_request
    self._make_request(opener, request, timeout=timeout)

  File "C:\Users\blah\AppData\Local\Continuum\anaconda3\lib\site-packages\python_http_client\client.py", line 178, in _make_request
    raise exc

ForbiddenError: HTTP Error 403: FORBIDDEN
</code>```

As can be noticed, I get this forbidden error. What is the reason for this?How do i solve this? this is not a blocked site on my end, so not sure why I get this error

答:
For me, it only works after add a new sender on SendGrid and uses this sender on the "from" parameter.

Follow this tutorial:

https://sendgrid.com/docs/ui/sending-email/senders/

then, go to the email registered and confirm the Sender Identity. After that, you should be able to send emails.

Body:
I am trying to access some email stats: My code:

import json
import os
from sendgrid.helpers.stats import *
from sendgrid import *

# NOTE: you will need move this file to the root directory of this project to execute properly.

# Assumes you set your environment variable:
# https://github.com/sendgrid/sendgrid-python/blob/master/TROUBLESHOOTING.md#environment-variables-and-your-sendgrid-api-key
sg = SendGridAPIClient(os.environ.get('SG****'))

def pprint_json(json_raw):
    print(json.dumps(json.loads(json_raw), indent=2, sort_keys=True))

def build_global_stats():
    global_stats = Stats()
    global_stats.start_date = '2020-01-13'
    global_stats.end_date = '2020-01-14'
    global_stats.aggregated_by = 'day'
    return global_stats.get()

def get_global_stats():
    stats_params = build_global_stats()
    response = sg.client.stats.get(query_params=stats_params)
    print(response.status_code)
    print(response.headers)
    pprint_json(response.body)

get_global_stats()
Traceback (most recent call last):

  File "<ipython-input-10-cee8ef5434a2>", line 35, in <module>
    get_global_stats()

  File "<ipython-input-10-cee8ef5434a2>", line 29, in get_global_stats
    response = sg.client.stats.get(query_params=stats_params)

  File "C:\Users\blah\AppData\Local\Continuum\anaconda3\lib\site-packages\python_http_client\client.py", line 262, in http_request
    self._make_request(opener, request, timeout=timeout)

  File "C:\Users\blah\AppData\Local\Continuum\anaconda3\lib\site-packages\python_http_client\client.py", line 178, in _make_request
    raise exc

ForbiddenError: HTTP Error 403: FORBIDDEN

As can be noticed, I get this forbidden error. What is the reason for this?How do i solve this? this is not a blocked site on my end, so not sure why I get this error


问:
How to add model's relationed condition to Eloquent query in Laravel 6.x?
In my Laravel 6.x project I have Product model, ProductCategory and WarehouseProduct models.

In the Product I store the base information of my products. In ProductCategory model I store the category informations of products. In the WarehouseProduct I store the stock amount informations about products in warehouse. Of course I have many warehouses with many products.

My Product looks like this:

class Product extends Model
{
    protected $fillable = [
        'name',
        'item_number',
        // ...
    ];

    public function categories() {
        return $this->belongsToMany(ProductCategory::class, 'product_category_products',
            'product_id', 'product_category_id');
    }
}
```

<p>The ProductCategory looks like this:</p>

<pre class="lang-php prettyprint-override"><code>class ProductCategory extends Model
{
    protected $fillable = [
        'name',
        'description',
        // ...
    ];

    public function products() {
        return $this->belongsToMany(Product::class, 'product_category_products',
            'product_category_id', 'product_id');
    }
}
</code>```

The WarehouseProduct looks like this:

class WarehouseProduct extends Model
{
    protected $fillable = [
        'product_id',
        'warehouse_id',
        'amount',
        // ...
    ];

    public function product() {
        return $this->belongsTo(Product::class, 'product_id');
    }
}
```

<p>I have this query now:</p>

<pre class="lang-php prettyprint-override"><code>$query = WarehouseProduct::select([
    'product_id',
    'warehouse_id',
    DB::raw('SUM(free_amount)'),
    DB::raw('SUM(booked_amount)'),
    // ...
]);

if (isset($request->warehouse_id)) {
    $query->where([['warehouse_id', '=', $request->warehouse_id]]);
}

if (isset($request->product_category_id)) {
    // ???
}
</code>```

How can I add a where condition to the query what said: products from this category?

答:
You can query the Relationship Existence. As it is a relationship through another model (Product) you could reduce the query if you defined that Has Many Through relationship, but I think that this will be enough for this particular query.

```<code>$warehouse_id = $request->warehouse_id;
$product_category_id = $request->product_category_id;

$query = WarehouseProduct::select([
    'product_id',
    'warehouse_id',
    DB::raw('SUM(free_amount)'),
    DB::raw('SUM(booked_amount)'),
    // ...
])
->when($warehouse_id, function ($query) use ($warehouse_id) {
    $query->where('warehouse_id', $warehouse_id);
})
->when($product_category_id, function ($query) use ($product_category_id) {
    $query->whereHas('product', function ($que) use ($product_category_id) {
        $que->whereHas('categories', function ($q) use ($product_category_id) {
            $q->where('id', $product_category_id);
        })
    })
});

$results = $query->get();
</code>```

Note that I am using the when method for the conditional clauses, but you can continue with the ifs as you was doing.

Body:
In my Laravel 6.x project I have Product model, ProductCategory and WarehouseProduct models.

In the Product I store the base information of my products. In ProductCategory model I store the category informations of products. In the WarehouseProduct I store the stock amount informations about products in warehouse. Of course I have many warehouses with many products.

My Product looks like this:

class Product extends Model
{
    protected $fillable = [
        'name',
        'item_number',
        // ...
    ];

    public function categories() {
        return $this->belongsToMany(ProductCategory::class, 'product_category_products',
            'product_id', 'product_category_id');
    }
}

The ProductCategory looks like this:

class ProductCategory extends Model
{
    protected $fillable = [
        'name',
        'description',
        // ...
    ];

    public function products() {
        return $this->belongsToMany(Product::class, 'product_category_products',
            'product_category_id', 'product_id');
    }
}

The WarehouseProduct looks like this:

class WarehouseProduct extends Model
{
    protected $fillable = [
        'product_id',
        'warehouse_id',
        'amount',
        // ...
    ];

    public function product() {
        return $this->belongsTo(Product::class, 'product_id');
    }
}

I have this query now:

$query = WarehouseProduct::select([
    'product_id',
    'warehouse_id',
    DB::raw('SUM(free_amount)'),
    DB::raw('SUM(booked_amount)'),
    // ...
]);

if (isset($request->warehouse_id)) {
    $query->where([['warehouse_id', '=', $request->warehouse_id]]);
}

if (isset($request->product_category_id)) {
    // ???
}

How can I add a where condition to the query what said: products from this category?

Body:
You can query the Relationship Existence. As it is a relationship through another model (Product) you could reduce the query if you defined that Has Many Through relationship, but I think that this will be enough for this particular query.

$warehouse_id = $request->warehouse_id;
$product_category_id = $request->product_category_id;

$query = WarehouseProduct::select([
    'product_id',
    'warehouse_id',
    DB::raw('SUM(free_amount)'),
    DB::raw('SUM(booked_amount)'),
    // ...
])
->when($warehouse_id, function ($query) use ($warehouse_id) {
    $query->where('warehouse_id', $warehouse_id);
})
->when($product_category_id, function ($query) use ($product_category_id) {
    $query->whereHas('product', function ($que) use ($product_category_id) {
        $que->whereHas('categories', function ($q) use ($product_category_id) {
            $q->where('id', $product_category_id);
        })
    })
});

$results = $query->get();

Note that I am using the when method for the conditional clauses, but you can continue with the ifs as you was doing.


问:
TypeScript error when I perform addition to a number and pass as a prop?
I have a heading component which takes a level as a prop:

In Heading.tsx

```<code>type Props = {
  level?: 1 | 2 | 3 | 4 | 5 | 6;
  children: string;
};
</code>```

My other component needs to add a number to a prop it's given, and make that the level:

In MyComponent.tsx:

```<code>type Props = {
  componentLevel: 1 | 2 | 3;
};

const MyComponent = ({ componentLevel }) => (
  <Heading level={componentLevel + 1}>My Component Heading text</Heading>
)
</code>```

Logically I can see that Heading will always get the props that it needs, however TypeScript gives me an error:

TS2322: Type 'number' is not assignable to type '1 | 2 | 3 | 4 | 5 | 6'.

答:
You could do:

In Heading.tsx

```<code>type HeadingProps = {
  level?: HeadingLevel;
  children: string;
};

type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
</code>```

In MyComponent.tsx

```<code><Heading level={(componentLevel + 1) as HeadingLevel}>My Component Heading text</Heading>
</code>```

Body:
I have a heading component which takes a level as a prop:

In Heading.tsx

type Props = {
  level?: 1 | 2 | 3 | 4 | 5 | 6;
  children: string;
};

My other component needs to add a number to a prop it's given, and make that the level:

In MyComponent.tsx:

type Props = {
  componentLevel: 1 | 2 | 3;
};

const MyComponent = ({ componentLevel }) => (
  <Heading level={componentLevel + 1}>My Component Heading text</Heading>
)

Logically I can see that Heading will always get the props that it needs, however TypeScript gives me an error:

TS2322: Type 'number' is not assignable to type '1 | 2 | 3 | 4 | 5 | 6'.

Body:
You could do:

In Heading.tsx

type HeadingProps = {
  level?: HeadingLevel;
  children: string;
};

type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;

In MyComponent.tsx

<Heading level={(componentLevel + 1) as HeadingLevel}>My Component Heading text</Heading>


问:
Can .addField value write an array that contains file "names"?
So I'm currently making a discord bot, and I made a ~play command that reads files from a folder (songs) and stores them in an array, then it picks a random file and plays it in the voice channel.

Right now I want to make a ~songs that makes the bot send an embed in the chat that contains .setTitle("These are that I have:"), and then .addField({name: "songs:", value: "*all the songs in the array"}).

The reason I want all songs in one Field value is that there are too many songs, and there are only 25 field that I can use. I tried forEach in the value and outside the field but none of them worked well.

Here's my code:

```<code>const discord = require("discord.js");
const fs = require("fs");

module.exports.run = async (bot, message, args) => {
  const songFiles = fs
    .readdirSync("./commands/Workout/")
    .filter((file) => file.endsWith(".mp3"));

  let songsEmbed = new discord.MessageEmbed()
    .setColor("RANDOM")
    .setTitle("These are that I have:");

  //.addField('Songname:',commandFiles.forEach())//doesn't work

  for (i = 0; i < commandFiles.length; i++) {
    songsEmbed.addField({ name: "Song name:", value: `${commandFiles[i]},` });
  } //That just create field for every song

  message.reply(songsEmbed);
};

module.exports.help = {
  name: "songs",
};
</code>```

答:
You can use the .join() function to create a string with the entries.

Let's say we have this array:

```<code>const songArray = [
  "Toto - Africa.mp3",
  "Rick Astley - Never Gonna Give You Up.mp3"
  "Bag Raiders - Shooting Stars.mp3"
]
</code>```

We can then run .join() to create a string with each song in that array. Note that \n indicates a new line.

songArray.join('\n')

/*
Toto - Africa.mp3
Rick Astley - Never Gonna Give You Up.mp3
Bag Raiders - Shooting Stars.mp3
*/
```

<p>So your code would look like this:</p>

<pre class="lang-js prettyprint-override"><code>.addField('Songname:', commandFiles.join('\n'))
</code>```

Body:
So I'm currently making a discord bot, and I made a ~play command that reads files from a folder (songs) and stores them in an array, then it picks a random file and plays it in the voice channel.

Right now I want to make a ~songs that makes the bot send an embed in the chat that contains .setTitle("These are that I have:"), and then .addField({name: "songs:", value: "*all the songs in the array"}).

The reason I want all songs in one Field value is that there are too many songs, and there are only 25 field that I can use. I tried forEach in the value and outside the field but none of them worked well.

Here's my code:

const discord = require("discord.js");
const fs = require("fs");

module.exports.run = async (bot, message, args) => {
  const songFiles = fs
    .readdirSync("./commands/Workout/")
    .filter((file) => file.endsWith(".mp3"));

  let songsEmbed = new discord.MessageEmbed()
    .setColor("RANDOM")
    .setTitle("These are that I have:");

  //.addField('Songname:',commandFiles.forEach())//doesn't work

  for (i = 0; i < commandFiles.length; i++) {
    songsEmbed.addField({ name: "Song name:", value: `${commandFiles[i]},` });
  } //That just create field for every song

  message.reply(songsEmbed);
};

module.exports.help = {
  name: "songs",
};

Body:
You can use the .join() function to create a string with the entries.

Let's say we have this array:

const songArray = [
  "Toto - Africa.mp3",
  "Rick Astley - Never Gonna Give You Up.mp3"
  "Bag Raiders - Shooting Stars.mp3"
]

We can then run .join() to create a string with each song in that array. Note that \n indicates a new line.

songArray.join('\n')

/*
Toto - Africa.mp3
Rick Astley - Never Gonna Give You Up.mp3
Bag Raiders - Shooting Stars.mp3
*/

So your code would look like this:

.addField('Songname:', commandFiles.join('\n'))


答:
Typescript isn't able to tell that if you take something of type 1 | 2 | 3 and add one to it then it's type becomes 2 | 3 | 4. Instead, the result is just a number, which is too broad for what Heading is expecting. You will need to assert that it's the correct type.

```<code><Heading level={(componentLevel + 1) as 1 | 2 | 3 | 4 | 5 | 6}>My Component Heading text</Heading>
</code>```

You might want to give this type an alias so it's easier to refer to:

```<code>type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6

type Props = {
  level?: HeadingLevel,
  children: string
}

// ...
<Heading level={(componentLevel + 1) as HeadingLevel}>My Component Heading text</Heading>
</code>```

Title: TypeScript error when I perform addition to a number and pass as a prop?

Body:
Typescript isn't able to tell that if you take something of type 1 | 2 | 3 and add one to it then it's type becomes 2 | 3 | 4. Instead, the result is just a number, which is too broad for what Heading is expecting. You will need to assert that it's the correct type.

<Heading level={(componentLevel + 1) as 1 | 2 | 3 | 4 | 5 | 6}>My Component Heading text</Heading>

You might want to give this type an alias so it's easier to refer to:

type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6

type Props = {
  level?: HeadingLevel,
  children: string
}

// ...
<Heading level={(componentLevel + 1) as HeadingLevel}>My Component Heading text</Heading>


问:
How do you change the default homepage in a Grails application?
What is the configuration setting for modifying the default homepage in a Grails application to no longer be appName/index.gsp? Of course you can set that page to be a redirect but there must be a better way.</p>

答:
Edit UrlMappings.groovy

Add for example add this rule, to handle the root with a HomeController.

"/"(controller:'home')

OwnerDisplayName: dahernan


问:
"Fixing" the first few columns in an SWT table to prevent them from scrolling horizontally
We have implemented a table-based editor with an SWT tree table. It pretty much does what we want it to, except that we can't find a way to ensure that the first few columns remain at their position when the user scrolls horizontally (so that one can identify the row being edited).

There are a number of third-party table controls in various degrees of being incomplete or abandoned, and a snippet that shows how to use two tables (which get out of sync when they're being scrolled vertically).

What's the best way to solve this?

答:
This 'official' SWT snippet does what you want to do, at least on my machine - it does not get out of sync on vertical scroll. But the price is a second scrollbar - way ugly. To prevent this, you can add the style SWT.NO_SCROLL in the constructor of the left table.

To improve the thing you will have to add a Listener on SWT.Traverse to both Tables, which syncs them if the user navigated using keys, something like this:

```<code>  leftTable.addListener(SWT.Traverse, new Listener() {

     public void handleEvent( Event event ) {
        rightTable.setTopIndex(leftTable.getTopIndex());
     }
  });
</code>```

I wouldn't go with another Table implementation, since you lose the biggest advantage you have with SWT: using a native widget, which looks and feels 'right' in each OS. If you want to do that anyway, Grid from the Nebula project is much more mature than the alpha tag implies. Don't know if it can do what you want, though.

OwnerDisplayName: Stefan Tilkov

LastEditorDisplayName: Jared

Body:
This 'official' SWT snippet does what you want to do, at least on my machine - it does not get out of sync on vertical scroll. But the price is a second scrollbar - way ugly. To prevent this, you can add the style SWT.NO_SCROLL in the constructor of the left table.

To improve the thing you will have to add a Listener on SWT.Traverse to both Tables, which syncs them if the user navigated using keys, something like this:

  leftTable.addListener(SWT.Traverse, new Listener() {

     public void handleEvent( Event event ) {
        rightTable.setTopIndex(leftTable.getTopIndex());
     }
  });

I wouldn't go with another Table implementation, since you lose the biggest advantage you have with SWT: using a native widget, which looks and feels 'right' in each OS. If you want to do that anyway, Grid from the Nebula project is much more mature than the alpha tag implies. Don't know if it can do what you want, though.


问:
Devise - Confirmable not sending emails
Just to get it out of the way: I do have emails working in my app.

I just added :confirmable to my user model.

app/models/user.rb

```<code>devise :database_authenticatable, :registerable, :omniauthable,
   :recoverable, :rememberable, :trackable, :validatable, :confirmable
</code>```

I do have the confirmable part in the db:

db/schema.rb

```<code>create_table "users", :force => true do |t|
  ...
  t.string   "confirmation_token"
  t.datetime "confirmed_at"
  t.datetime "confirmation_sent_at"
end
</code>```

Because of the omniauth I have overwritten registrations_controller:

app/controllers/registrations_controller.rb

```<code>def create
  super
  session[:omniauth] = nil unless @user.new_record?
end
</code>```

So what I'm trying to figure out is… what do I need to add in order to:

Get confirmation email sent after the user signs up

Redirect the user to a custom page explaining the email is waiting to be confirmed (which they would get to if they tried signing in again without confirming)  (answered here)

(should be taken care of automatically?) When the user is verified redirect them to given page

Update: Right now, when I create a user it is automatically confirmed. Why is that?

答:
Ok, so I didn't realize I had the following in my user model:

```<code>def send_confirmation_instructions
  # stops Devise from automatically sending a confirmation email
end

def confirmation_required?
  skip_confirmation!
end
</code>```

Commenting them out gets the email to be sent. Still trying to figure out how to redirect after sign in if the user isn't confirmed. And trying to figure out how to properly use confirmation_required?

Title: Devise - Confirmable not sending emails

Body:
Just to get it out of the way: I do have emails working in my app.

I just added :confirmable to my user model.

app/models/user.rb

devise :database_authenticatable, :registerable, :omniauthable,
   :recoverable, :rememberable, :trackable, :validatable, :confirmable

I do have the confirmable part in the db:

db/schema.rb

create_table "users", :force => true do |t|
  ...
  t.string   "confirmation_token"
  t.datetime "confirmed_at"
  t.datetime "confirmation_sent_at"
end

Because of the omniauth I have overwritten registrations_controller:

app/controllers/registrations_controller.rb

def create
  super
  session[:omniauth] = nil unless @user.new_record?
end

So what I'm trying to figure out is… what do I need to add in order to:

Get confirmation email sent after the user signs up

Redirect the user to a custom page explaining the email is waiting to be confirmed (which they would get to if they tried signing in again without confirming)  (answered here)

(should be taken care of automatically?) When the user is verified redirect them to given page

Update: Right now, when I create a user it is automatically confirmed. Why is that?

Body:
Ok, so I didn't realize I had the following in my user model:

def send_confirmation_instructions
  # stops Devise from automatically sending a confirmation email
end

def confirmation_required?
  skip_confirmation!
end

Commenting them out gets the email to be sent. Still trying to figure out how to redirect after sign in if the user isn't confirmed. And trying to figure out how to properly use confirmation_required?


问:
Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code
```<code>Showing Recent Messages:-1: mkdir -p /Users/spritzindia/Library/Developer/Xcode/DerivedData/Contigo-atftiouzrdopcmcpprphpilawwzm/Build/Products/Debug-iphonesimulator/Contigo.app/Frameworks

Showing Recent Messages:-1: rsync --delete -av --filter P .*.?????? --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "/Users/pothi/Library/Developer/Xcode/DerivedData/Contigo-atftiouzrdopcmcpprphpilawwzm/Build/Products/Debug-iphonesimulator/IQKeyboardManagerSwift/IQKeyboardManagerSwift.framework" "/Users/pothi/Library/Developer/Xcode/DerivedData/Contigo-atftiouzrdopcmcpprphpilawwzm/Build/Products/Debug-iphonesimulator/Contigo.app/Frameworks"
</code>```

Command PhaseScriptExecution failed with a nonzero exit code

I deleted derived data.
i have tried :

keychain access -> right click on login -> lock & unlock again ->
  clear Xcode project

Restarted machine, no use

How do I resolve "Command PhaseScriptExecution failed with a nonzero exit code" error when trying to archive project.

And I am using those librarys

```<code>pod 'IQKeyboardManagerSwift'
pod 'SDWebImage', '~> 4.0'
pod 'KRPullLoader'
pod 'Paytm-Payments'
</code>```

答:
I had the same problem in Xcode 11.5 after revoking a certificate through Apple's developer homepage and adding it again (even though it looked different afterwards):

Every time I tried to archive my app, it would fail at the very end (not the pods but my actual app) with the same PhaseScriptExecution failed with a nonzero exit code error message. There is/was a valid team with an "Apple Development" signing certificate in "Signing & Capabilities" (project file in Xcode) and locking & unlocking the keychain, cleaning & building the project, restarting,... didn't work.

The problem was caused by having two active certificates of the same type that I must have added on accident, in addition to the renewed one. I deleted both the renewed one and the duplicate and it worked again.

You can find your certificates here or find the page like this:

https://developer.apple.com/

"Account" (at the top)

Log in

"Certificates, IDs & Profiles" (on the left)

Also check that there aren't any duplicates in your keychain! Be careful though - don't delete or add anything unless you know what you're doing, otherwise you might create a huge mess!

Body:
Showing Recent Messages:-1: mkdir -p /Users/spritzindia/Library/Developer/Xcode/DerivedData/Contigo-atftiouzrdopcmcpprphpilawwzm/Build/Products/Debug-iphonesimulator/Contigo.app/Frameworks

Showing Recent Messages:-1: rsync --delete -av --filter P .*.?????? --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "/Users/pothi/Library/Developer/Xcode/DerivedData/Contigo-atftiouzrdopcmcpprphpilawwzm/Build/Products/Debug-iphonesimulator/IQKeyboardManagerSwift/IQKeyboardManagerSwift.framework" "/Users/pothi/Library/Developer/Xcode/DerivedData/Contigo-atftiouzrdopcmcpprphpilawwzm/Build/Products/Debug-iphonesimulator/Contigo.app/Frameworks"

Command PhaseScriptExecution failed with a nonzero exit code

I deleted derived data.
i have tried :

keychain access -> right click on login -> lock & unlock again ->
  clear Xcode project

Restarted machine, no use

How do I resolve "Command PhaseScriptExecution failed with a nonzero exit code" error when trying to archive project.

And I am using those librarys

pod 'IQKeyboardManagerSwift'
pod 'SDWebImage', '~> 4.0'
pod 'KRPullLoader'
pod 'Paytm-Payments'


问:
Roam array of arrays by position in Python
I have this array of arrays:

```<code>A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
</code>```

And I want to convert it to have an array like this (having an array with 1st elements, next array with 2nd elements, ...):

```<code>AUX = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
</code>```

I've tried with

```<code>for i in A:
   for j in i:
      #code
</code>```

But with that I'm just getting the sequence of the original array [1, 2, 3, 4, 5, 6, 7, 8, 9]

答:
You can use zip to transpose the array:

```<code>result = [list(x) for x in zip(*A)]
</code>```

If you're using Numpy you can just use the transpose function:

```<code>result = np.transpose(np.array(A))
result = np.array(A).T  # equivalent
</code>```

Body:
I have this array of arrays:

A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

And I want to convert it to have an array like this (having an array with 1st elements, next array with 2nd elements, ...):

AUX = [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

I've tried with

for i in A:
   for j in i:
      #code

But with that I'm just getting the sequence of the original array [1, 2, 3, 4, 5, 6, 7, 8, 9]

Body:
You can use zip to transpose the array:

result = [list(x) for x in zip(*A)]

If you're using Numpy you can just use the transpose function:

result = np.transpose(np.array(A))
result = np.array(A).T  # equivalent


问:
filling pandas dataframe columns based on another dataframe's columns
I have a dataframe that looks like this(df):

```<code>HOUSEID    PERSONID      WHY_TRP
20000017      1            1
20000017      1            1
20000017      1            1
20000017      2            1
20000017      2            3
20000231      1            11
20000231      1            11
20000231      2            11
20000521      1            11
20000521      2            11
20000521      2            3
</code>```

Each row describes a trip made by a person. I have another dataframe of the same kind in which each row describes a person(df_p):

```<code>    HOUSEID   PERSONID
    20000017      1
    20000017      2
    20000231      1
    20000231      2
    20000521      1
    20000521      2
</code>```

I want to make three new columns in the second dataframe to show the frequency of 1, 3 and 11 for each person. basically I already have a second dataframe (df_p) with other features so I shouldn't use groupby. for some reason the first and second dataframe don't have the same number of people. that's why I needed the strategy below. This is the code I tried but took hours to complete(1 million iterations):

```<code>df_p.insert(2, 'WHY_TRP_1', 0)
df_p.insert(3, 'WHY_TRP_2', 0)
df_p.insert(4, 'WHY_TRP_3', 0)

def trip_counter(i, r):
  if r[2] == 1:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] == r[1]), ['WHY_TRP_1']] += 1
  elif r[2] == 3:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_3']] += 1
  elif r[2] == 11:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_11']] += 1

for i ,r in df.iterrows():
  trip_counter(i ,r)
</code>```

output:

```<code>     HOUSEID   PERSONID   WHY_TRP_1     WHY_TRP_3      WHY_TRP_11
    20000017      1            3            0            0
    20000017      2            1            1            0
    20000231      1            0            0            2
    20000231      2            0            0            1
    20000521      1            0            0            1
    20000521      2            0            1            1
</code>```

Is there a faster way to do this?

thank you

Body:
I have a dataframe that looks like this(df):

HOUSEID    PERSONID      WHY_TRP
20000017      1            1
20000017      1            1
20000017      1            1
20000017      2            1
20000017      2            3
20000231      1            11
20000231      1            11
20000231      2            11
20000521      1            11
20000521      2            11
20000521      2            3

Each row describes a trip made by a person. I have another dataframe of the same kind in which each row describes a person(df_p):

    HOUSEID   PERSONID
    20000017      1
    20000017      2
    20000231      1
    20000231      2
    20000521      1
    20000521      2

I want to make three new columns in the second dataframe to show the frequency of 1, 3 and 11 for each person. basically I already have a second dataframe (df_p) with other features so I shouldn't use groupby. for some reason the first and second dataframe don't have the same number of people. that's why I needed the strategy below. This is the code I tried but took hours to complete(1 million iterations):

df_p.insert(2, 'WHY_TRP_1', 0)
df_p.insert(3, 'WHY_TRP_2', 0)
df_p.insert(4, 'WHY_TRP_3', 0)

def trip_counter(i, r):
  if r[2] == 1:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] == r[1]), ['WHY_TRP_1']] += 1
  elif r[2] == 3:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_3']] += 1
  elif r[2] == 11:
    df_p.loc[(df_p['HOUSEID'] == r[0]) & (df_p['PERSONID'] ==  r[1]), ['WHY_TRP_11']] += 1

for i ,r in df.iterrows():
  trip_counter(i ,r)

output:

     HOUSEID   PERSONID   WHY_TRP_1     WHY_TRP_3      WHY_TRP_11
    20000017      1            3            0            0
    20000017      2            1            1            0
    20000231      1            0            0            2
    20000231      2            0            0            1
    20000521      1            0            0            1
    20000521      2            0            1            1

Is there a faster way to do this?

thank you

Body:
Code:

(df.groupby(['HOUSEID','PERSONID'])
  .WHY_TRP.value_counts()
  .unstack(fill_value=0)
  .add_prefix('WHY_TRP_')
  .reset_index()
)

Output:

WHY_TRP   HOUSEID  PERSONID  WHY_TRP_1  WHY_TRP_3  WHY_TRP_11
0        20000017         1          3          0           0
1        20000017         2          1          1           0
2        20000231         1          0          0           2
3        20000231         2          0          0           1
4        20000521         1          0          0           1
5        20000521         2          0          1           1


问:
Are single queries that update multiple rows in MySQL Atomic?
I have a single query in a MySQL InnoDb table being executed in SpringJPA that updates multiple rows. I want to make sure that the query completes and that the rows it will update cannot be updated by any other process. This is in a multi-cpu environment so I have to do the locking at the database level.

I first select the rows with a query like this:

```<code>select * from tablea where status = 1;
</code>```

Let's say this returns 3 rows - primary ids 1,2,3

I want to prevent concurrent update and I do this update:

```<code>update tablea set status=2 where status=1 and primaryIds in (1,2,3);
</code>```

What I'm trying to accomplish is to check that all the rows I'm trying to update still have the original value in status and have not been updated underneath me. I then get the count of rows updated and compare it to the number of primary ids (3) to know if my query has updated all rows. My question is this query atomic - will it either return 3 or 0. And if the number of rows is much greater will it yield allowing another thread, trying to do the same update to update some rows. I have tested this with one row and it works fine.

答:
Yes, they are. Assuming you have auto-commit enabled (this is the default when you haven't started a transaction), InnoDB will automatically put a transaction around each query, which makes it atomic. It's effectively equivalent to:</p>

```<code>START TRANSACTION;
update tablea set status=2 where status=1 and primaryIds in (1,2,3);
COMMIT;
</code>```

Body:
I have a single query in a MySQL InnoDb table being executed in SpringJPA that updates multiple rows. I want to make sure that the query completes and that the rows it will update cannot be updated by any other process. This is in a multi-cpu environment so I have to do the locking at the database level.

I first select the rows with a query like this:

select * from tablea where status = 1;

Let's say this returns 3 rows - primary ids 1,2,3

I want to prevent concurrent update and I do this update:

update tablea set status=2 where status=1 and primaryIds in (1,2,3);

What I'm trying to accomplish is to check that all the rows I'm trying to update still have the original value in status and have not been updated underneath me. I then get the count of rows updated and compare it to the number of primary ids (3) to know if my query has updated all rows. My question is this query atomic - will it either return 3 or 0. And if the number of rows is much greater will it yield allowing another thread, trying to do the same update to update some rows. I have tested this with one row and it works fine.

Body:
Yes, they are. Assuming you have auto-commit enabled (this is the default when you haven't started a transaction), InnoDB will automatically put a transaction around each query, which makes it atomic. It's effectively equivalent to:

START TRANSACTION;
update tablea set status=2 where status=1 and primaryIds in (1,2,3);
COMMIT;


问:
Spring boot app fails with Jackson2ObjectMapperBuilder.visibility doesn't exist
In my spring boot app, I have a very few dependencies:

```<code>implementation "org.springframework.boot:spring-boot-starter:$springBootVersion"
testImplementation "org.springframework.boot:spring-boot-starter-test:$springBootVersion"
</code>```

The application fails to start:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

    java.lang.invoke.MethodHandleNatives.resolve(Native Method)

The following method did not exist:

    org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.visibility(Lcom/fasterxml/jackson/annotation/PropertyAccessor;Lcom/fasterxml/jackson/annotation/JsonAutoDetect$Visibility;)Lorg/springframework/http/converter/json/Jackson2ObjectMapperBuilder;

The method's class, org.springframework.http.converter.json.Jackson2ObjectMapperBuilder, is available from the following locations:

    jar:file:/Users/me/.gradle/caches/modules-2/files-2.1/org.springframework/spring-web/4.3.25.RELEASE/76d29c076153e09961c8e6fd9b2d5c50bb80b902/spring-web-4.3.25.RELEASE.jar!/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.class

It was loaded from the following location:

    file:/Users/me/.gradle/caches/modules-2/files-2.1/org.springframework/spring-web/4.3.25.RELEASE/76d29c076153e09961c8e6fd9b2d5c50bb80b902/spring-web-4.3.25.RELEASE.jar

Action:

Correct the classpath of your application so that it contains a single, compatible version of org.springframework.http.converter.json.Jackson2ObjectMapperBuilder

Disconnected from the target VM, address: '127.0.0.1:57370', transport: 'socket'

Process finished with exit code 1
</code>```

springBootVersion is 2.2.6.RELEASE

答:
The spring-boot-starter dependency does not seem to include spring-web where the needed class resides.
Add implementation "org.springframework.boot:spring-boot-starter-web:$springBootVersion" to your Gradle file and try again.

Body:
In my spring boot app, I have a very few dependencies:

implementation "org.springframework.boot:spring-boot-starter:$springBootVersion"
testImplementation "org.springframework.boot:spring-boot-starter-test:$springBootVersion"

The application fails to start:

***************************
APPLICATION FAILED TO START
***************************

Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

    java.lang.invoke.MethodHandleNatives.resolve(Native Method)

The following method did not exist:

    org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.visibility(Lcom/fasterxml/jackson/annotation/PropertyAccessor;Lcom/fasterxml/jackson/annotation/JsonAutoDetect$Visibility;)Lorg/springframework/http/converter/json/Jackson2ObjectMapperBuilder;

The method's class, org.springframework.http.converter.json.Jackson2ObjectMapperBuilder, is available from the following locations:

    jar:file:/Users/me/.gradle/caches/modules-2/files-2.1/org.springframework/spring-web/4.3.25.RELEASE/76d29c076153e09961c8e6fd9b2d5c50bb80b902/spring-web-4.3.25.RELEASE.jar!/org/springframework/http/converter/json/Jackson2ObjectMapperBuilder.class

It was loaded from the following location:

    file:/Users/me/.gradle/caches/modules-2/files-2.1/org.springframework/spring-web/4.3.25.RELEASE/76d29c076153e09961c8e6fd9b2d5c50bb80b902/spring-web-4.3.25.RELEASE.jar

Action:

Correct the classpath of your application so that it contains a single, compatible version of org.springframework.http.converter.json.Jackson2ObjectMapperBuilder

Disconnected from the target VM, address: '127.0.0.1:57370', transport: 'socket'

Process finished with exit code 1

springBootVersion is 2.2.6.RELEASE


问:
Locating MySQL tables, they are not in datadir and the files cannot be found on disc
I have a problem with locating tables in mySQL. I know this question was asked milion times
e.g. Location of database tables - MySQL - Windows XP
but the answers do not seem to help. The tables are not in the dir given in my.ini. And there is also no file named as my database on disc. please help. thank you.</p>

答:
If you are using Windows you should to be careful, because sometimes there are more than one options file, so you have to be sure of which file the mysql server is loading, you can view that path running this query in any mysql client:</p>

```<code>SELECT * FROM information_schema.session_variables
WHERE VARIABLE_NAME = 'DATADIR';
</code>```

Body:
If you are using Windows you should to be careful, because sometimes there are more than one options file, so you have to be sure of which file the mysql server is loading, you can view that path running this query in any mysql client:

SELECT * FROM information_schema.session_variables
WHERE VARIABLE_NAME = 'DATADIR';


问:
How should I implement delayed topic architecture in Kafka
If my consumers fails to process the message for the time being, I want it to push to 5 minutes delayed Topic and if it fails to process from there also I want it to push to 30 minutes delayed topic. If it fails here as well, would like to push it to Dead-Letter-Queue.

5 minutes delayed topic : Consumer should listen after 5 minutes from first processing.

30 minutes delayed topic : Consumer should listen after 30 minutes from previous failure.

How should I design the delayed queue? It's easy to push to Kafka topic after failure but how should my consumer/listener listen that after 5 minutes or 30 minutes delay?

I am using SpringKafka for consumers to listen from a topic like below-

@KafkaListener(topics = "${kafka.topic}")
public void receive1(String payload) {
    logger.info("Getting message on receiver-1");
    submitPayloadToExecutor(payload);
}
```
<p>I have below implementation for my own project, can someone point out the fallback and any new suggestion ??</p>
```    @KafkaListener(topics = "${kafka.topic}")
    public void receive3(String payload) {

        logger.info("Getting message on receiver-3");
        submitPayloadToExecutor(payload);
    }

    private void submitPayloadToExecutor(String payload) {

        StartupService startupService = StartupServiceSingleton.INSTANCE.getStartupServiceInstance();

        ObjectMapper mapper = startupService.getConverter().getObjectMapper();

        PublishPostProcessorEntity publishPostProcessorEntity = null;
        try {
            publishPostProcessorEntity = mapper.readValue(payload, PublishPostProcessorEntity.class);

            sleepForDelayedPublishedEntity(publishPostProcessorEntity);

            // ... do some work

            topicExecutorService.submit(publishPostProcessorEntity);
        } catch (Exception e) {
            // Work on exception
        }
    }

    private void sleepForDelayedPublishedEntity(PublishPostProcessorEntity publishPostProcessorEntity) {

        if (publishPostProcessorEntity instanceof DelayedPublishPostProcessorEntity) {

            DelayedPublishPostProcessorEntity delayedPublishPostProcessorEntity = (DelayedPublishPostProcessorEntity) publishPostProcessorEntity;

            // Fetch the topicName and sleep based on the configuration
            long pushedTimeStamp = delayedPublishPostProcessorEntity.getPushedTimeStamp();
            delayedPublishPostProcessorEntity.setComingTopicName(delayedPublishPostProcessorEntity.getNextTopicName());

            long currentTimeStamp = System.currentTimeMillis();

            if (CMSKafkaConstants.FIVE_MINUTES_DELAYED_TOPIC
                    .equalsIgnoreCase(delayedPublishPostProcessorEntity.getNextTopicName())) {

                long timeElapsed = currentTimeStamp - pushedTimeStamp;
                if ((Long.parseLong(firstDelay)-timeElapsed) > 0) {
                    // wait for timeToWait
                    try {
                        Thread.sleep(Long.parseLong(firstDelay)-timeElapsed);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            } else if (CMSKafkaConstants.THRITY_MINUTES_DELAYED_TOPIC
                    .equalsIgnoreCase(delayedPublishPostProcessorEntity.getNextTopicName())) {

                long timeElapsed = currentTimeStamp - pushedTimeStamp;
                if ((Long.parseLong(secondDelay)-timeElapsed) > 0) {
                    try {
                        Thread.sleep(Long.parseLong(secondDelay)-timeElapsed);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }

        }

    }
```

答: You can stop and start consumers as needed via the KafkaListenerEndpointRegistry (use getListenerContainer(id).start()).

Body:
If my consumers fails to process the message for the time being, I want it to push to 5 minutes delayed Topic and if it fails to process from there also I want it to push to 30 minutes delayed topic. If it fails here as well, would like to push it to Dead-Letter-Queue.

5 minutes delayed topic : Consumer should listen after 5 minutes from first processing.

30 minutes delayed topic : Consumer should listen after 30 minutes from previous failure.

How should I design the delayed queue? It's easy to push to Kafka topic after failure but how should my consumer/listener listen that after 5 minutes or 30 minutes delay?

I am using SpringKafka for consumers to listen from a topic like below-

@KafkaListener(topics = "${kafka.topic}")
public void receive1(String payload) {
    logger.info("Getting message on receiver-1");
    submitPayloadToExecutor(payload);
}

I have below implementation for my own project, can someone point out the fallback and any new suggestion ??

    @KafkaListener(topics = "${kafka.topic}")
    public void receive3(String payload) {

        logger.info("Getting message on receiver-3");
        submitPayloadToExecutor(payload);
    }

    private void submitPayloadToExecutor(String payload) {

        StartupService startupService = StartupServiceSingleton.INSTANCE.getStartupServiceInstance();

        ObjectMapper mapper = startupService.getConverter().getObjectMapper();

        PublishPostProcessorEntity publishPostProcessorEntity = null;
        try {
            publishPostProcessorEntity = mapper.readValue(payload, PublishPostProcessorEntity.class);

            sleepForDelayedPublishedEntity(publishPostProcessorEntity);

            // ... do some work

            topicExecutorService.submit(publishPostProcessorEntity);
        } catch (Exception e) {
            // Work on exception
        }
    }

    private void sleepForDelayedPublishedEntity(PublishPostProcessorEntity publishPostProcessorEntity) {

        if (publishPostProcessorEntity instanceof DelayedPublishPostProcessorEntity) {

            DelayedPublishPostProcessorEntity delayedPublishPostProcessorEntity = (DelayedPublishPostProcessorEntity) publishPostProcessorEntity;

            // Fetch the topicName and sleep based on the configuration
            long pushedTimeStamp = delayedPublishPostProcessorEntity.getPushedTimeStamp();
            delayedPublishPostProcessorEntity.setComingTopicName(delayedPublishPostProcessorEntity.getNextTopicName());

            long currentTimeStamp = System.currentTimeMillis();

            if (CMSKafkaConstants.FIVE_MINUTES_DELAYED_TOPIC
                    .equalsIgnoreCase(delayedPublishPostProcessorEntity.getNextTopicName())) {

                long timeElapsed = currentTimeStamp - pushedTimeStamp;
                if ((Long.parseLong(firstDelay)-timeElapsed) > 0) {
                    // wait for timeToWait
                    try {
                        Thread.sleep(Long.parseLong(firstDelay)-timeElapsed);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            } else if (CMSKafkaConstants.THRITY_MINUTES_DELAYED_TOPIC
                    .equalsIgnoreCase(delayedPublishPostProcessorEntity.getNextTopicName())) {

                long timeElapsed = currentTimeStamp - pushedTimeStamp;
                if ((Long.parseLong(secondDelay)-timeElapsed) > 0) {
                    try {
                        Thread.sleep(Long.parseLong(secondDelay)-timeElapsed);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }

        }

    }


问:
SimpleInjector Lazy in a Reflection
We are using SimpleInjector as a Dependency Injector, and we are registering all interface types using assembly iteration.

public static void RegisterInterfaceTypes(this Container container, Assembly assembly)
{
    assembly.GetExportedTypes()
        .Select(t => new {
            Type = t,
            Interface = t.GetInterfaces().FirstOrDefault()
        })
        .ToList()
        .ForEach(t =>
        {
            container.Register(t.Interface, t.Type, Lifestyle.Transient);
        });
}
```

<p>We also have lazy classes to register. We can register these classes like below one by one. But we want to register all lazy types with similar iteration using reflection.</p>

```container.Register(() => new Lazy<ICommonBusiness>(container.GetInstance<CommonBusiness>));
```

答:
You can make use of the ResolveUnregisteredType extension method to make last-minute registrations for resolve Lazy<T> dependencies:

Source:

public static void AllowResolvingLazyFactories(this Container container)
{
    container.ResolveUnregisteredType += (sender, e) =>
    {
        if (e.UnregisteredServiceType.IsGenericType &&
            e.UnregisteredServiceType.GetGenericTypeDefinition() == typeof(Lazy<>))
        {
            Type serviceType = e.UnregisteredServiceType.GetGenericArguments()[0];

            InstanceProducer registration = container.GetRegistration(serviceType, true);

            Type funcType = typeof(Func<>).MakeGenericType(serviceType);
            Type lazyType = typeof(Lazy<>).MakeGenericType(serviceType);

            var factoryDelegate = Expression.Lambda(funcType, registration.BuildExpression()).Compile();

            var lazyConstructor = (
                from ctor in lazyType.GetConstructors()
                where ctor.GetParameters().Length == 1
                where ctor.GetParameters()[0].ParameterType == funcType
                select ctor)
                .Single();

            var expression = Expression.New(lazyConstructor, Expression.Constant(factoryDelegate));

            var lazyRegistration = registration.Lifestyle.CreateRegistration(
                serviceType: lazyType,
                instanceCreator: Expression.Lambda<Func<object>>(expression).Compile(),
                container: container);

            e.Register(lazyRegistration);
        }
    };
}
```

<p>Usage:</p>

<pre class="lang-cs prettyprint-override"><code>container.AllowResolvingLazyFactories();
</code>```

But please note the warnings from the documentation:

Warning: Registering [Lazy<T>] by default is a design smell. The use of [Lazy<T>] makes your design harder to follow and your system harder to maintain and test. Your system should only have a few of those [...] at most. If you have many constructors in your system that depend on a [Lazy<T>], please take a good look at your dependency strategy. The following article goes into details about why [this is] a design smell.

Warning: [...] the constructors of your components should be simple, reliable and quick (as explained in this blog post by Mark Seemann). That would remove the need for lazy initialization. For more information about creating an application and container configuration that can be successfully verified, please read the How To Verify the container’s configuration.

Title: SimpleInjector Lazy in a Reflection

Body:
We are using SimpleInjector as a Dependency Injector, and we are registering all interface types using assembly iteration.

public static void RegisterInterfaceTypes(this Container container, Assembly assembly)
{
    assembly.GetExportedTypes()
        .Select(t => new {
            Type = t,
            Interface = t.GetInterfaces().FirstOrDefault()
        })
        .ToList()
        .ForEach(t =>
        {
            container.Register(t.Interface, t.Type, Lifestyle.Transient);
        });
}

We also have lazy classes to register. We can register these classes like below one by one. But we want to register all lazy types with similar iteration using reflection.

container.Register(() => new Lazy<ICommonBusiness>(container.GetInstance<CommonBusiness>));

Body:
You can make use of the ResolveUnregisteredType extension method to make last-minute registrations for resolve Lazy<T> dependencies:

Source:

public static void AllowResolvingLazyFactories(this Container container)
{
    container.ResolveUnregisteredType += (sender, e) =>
    {
        if (e.UnregisteredServiceType.IsGenericType &&
            e.UnregisteredServiceType.GetGenericTypeDefinition() == typeof(Lazy<>))
        {
            Type serviceType = e.UnregisteredServiceType.GetGenericArguments()[0];

            InstanceProducer registration = container.GetRegistration(serviceType, true);

            Type funcType = typeof(Func<>).MakeGenericType(serviceType);
            Type lazyType = typeof(Lazy<>).MakeGenericType(serviceType);

            var factoryDelegate = Expression.Lambda(funcType, registration.BuildExpression()).Compile();

            var lazyConstructor = (
                from ctor in lazyType.GetConstructors()
                where ctor.GetParameters().Length == 1
                where ctor.GetParameters()[0].ParameterType == funcType
                select ctor)
                .Single();

            var expression = Expression.New(lazyConstructor, Expression.Constant(factoryDelegate));

            var lazyRegistration = registration.Lifestyle.CreateRegistration(
                serviceType: lazyType,
                instanceCreator: Expression.Lambda<Func<object>>(expression).Compile(),
                container: container);

            e.Register(lazyRegistration);
        }
    };
}

Usage:

container.AllowResolvingLazyFactories();

But please note the warnings from the documentation:

Warning: Registering [Lazy<T>] by default is a design smell. The use of [Lazy<T>] makes your design harder to follow and your system harder to maintain and test. Your system should only have a few of those [...] at most. If you have many constructors in your system that depend on a [Lazy<T>], please take a good look at your dependency strategy. The following article goes into details about why [this is] a design smell.

Warning: [...] the constructors of your components should be simple, reliable and quick (as explained in this blog post by Mark Seemann). That would remove the need for lazy initialization. For more information about creating an application and container configuration that can be successfully verified, please read the How To Verify the container’s configuration.


问:
can't change value by key
I'm new to JavaScript. I have a tree structure and I want to change "tags" property value from an array of strings to a string when the array length is bigger than 5.

```<code>ChangeTags(obj) {
    Object.keys(obj).forEach(key => {
      (key === 'tags' && obj[key].length > 5) && obj["tags"] = "some value" ||
      (obj[key] && typeof obj[key] === 'object') && this.removeEmptyNodes(obj[key]);
    });
    return obj;
  };
</code>```

The interpreter does not allow me to do the assignment in the 4th line. What am I doing wrong?

答:
Does this meet your needs?

//  I have a tree structure and I want to change "tags" field value from array of strings to string when the array length is bigger than 5

const objs = [
  { id: 1, tags: ['first', 'second'] },
  { id: 2, tags: ['first'] },
  { id: 3, tags: ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'] }
];

function changeTags(arr) {
  for (let obj of arr) {
    obj.tags.length > 5 && (obj.tags = "some value");
  }
}

changeTags(objs);
console.log(objs);```
</div>
</div>
</p>

<p>Or for each case as you do in your example (you were missing parenthesis in the assignment):</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const obj = { tags: [1,2,3,4,5,6] };
const obj2 = { tags: ["a", "b"] };

function ChangeTags(obj) {
    Object.keys(obj).forEach(key => {
      (key === 'tags' && obj[key].length > 5) && (obj["tags"] = "some value") ||
      (obj[key] && typeof obj[key] === 'object')  // && this.removeEmptyNodes(obj[key]); commented this out for the test
    });
    return obj;
};

console.log(ChangeTags(obj));
console.log(ChangeTags(obj2));</code>```

Title: can't change value by key

Body:
I'm new to JavaScript. I have a tree structure and I want to change "tags" property value from an array of strings to a string when the array length is bigger than 5.

ChangeTags(obj) {
    Object.keys(obj).forEach(key => {
      (key === 'tags' && obj[key].length > 5) && obj["tags"] = "some value" ||
      (obj[key] && typeof obj[key] === 'object') && this.removeEmptyNodes(obj[key]);
    });
    return obj;
  };

The interpreter does not allow me to do the assignment in the 4th line. What am I doing wrong?

Body:
Does this meet your needs?

//  I have a tree structure and I want to change "tags" field value from array of strings to string when the array length is bigger than 5

const objs = [
  { id: 1, tags: ['first', 'second'] },
  { id: 2, tags: ['first'] },
  { id: 3, tags: ['first', 'second', 'third', 'fourth', 'fifth', 'sixth'] }
];

function changeTags(arr) {
  for (let obj of arr) {
    obj.tags.length > 5 && (obj.tags = "some value");
  }
}

changeTags(objs);
console.log(objs);

Or for each case as you do in your example (you were missing parenthesis in the assignment):

const obj = { tags: [1,2,3,4,5,6] };
const obj2 = { tags: ["a", "b"] };

function ChangeTags(obj) {
    Object.keys(obj).forEach(key => {
      (key === 'tags' && obj[key].length > 5) && (obj["tags"] = "some value") ||
      (obj[key] && typeof obj[key] === 'object')  // && this.removeEmptyNodes(obj[key]); commented this out for the test
    });
    return obj;
};

console.log(ChangeTags(obj));
console.log(ChangeTags(obj2));