问:
Multiple time allocation and release
I am creating a quiz app for iPhone/iPad(universal app).It is working fine on simulator but on real device there are some problem i am facing..

I am creating UILabels and UIButtons programmatically and i am using them so many times for displaying questions and answers one by one.

problem is when i reach around question 20 to 22 the application crashes. I don't know why. there is no memory leak i found. I release all the labels and buttons at the -dealloc function.

may be it happens because 22 questions takes some memory and not release till dealloc function call.

What i want is , Is there any way to release labels and buttons after every question and then it will allocate again? or any way in which i can use less memory for allocation labels and buttons??

I am using this code :

```<code>//lbl ref to btn1
ans1 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 292, 697, 100)] autorelease];
ans1.numberOfLines = 0;
ans1.font = [UIFont systemFontOfSize:26];
ans1.text = [theQuiz objectAtIndex:row+1];
ans1.lineBreakMode = UILineBreakModeWordWrap;
[ans1 sizeToFit];
//[self.view addSubview:ans1];
//lbl ref to btn2
ans2 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 312 + ans1.frame.size.height , 697, 100)] autorelease];
ans2.numberOfLines = 0;
ans2.font = [UIFont systemFontOfSize:26];
ans2.text = [theQuiz objectAtIndex:row+2];
ans2.lineBreakMode = UILineBreakModeWordWrap;
[ans2 sizeToFit];
// [self.view addSubview:ans2];
//lbl ref to btn3
ans3 = [[[UILabel alloc] initWithFrame:CGRectMake(36 ,332 + ans1.frame.size.height + ans2.frame.size.height , 697 , 100)] autorelease];
ans3.numberOfLines = 0;
ans3.font = [UIFont systemFontOfSize:26];
ans3.text = [theQuiz objectAtIndex:row+3] ;
ans3.lineBreakMode = UILineBreakModeWordWrap;
[ans3 sizeToFit];
// [self.view addSubview:ans3];
//lbl ref to btn4
ans4 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 352 + ans1.frame.size.height + ans2.frame.size.height + ans3.frame.size.height, 697, 100)] autorelease];
ans4.numberOfLines = 0;
ans4.font = [UIFont systemFontOfSize:26];
ans4.text = [theQuiz objectAtIndex:row+4];
ans4.lineBreakMode = UILineBreakModeWordWrap;
[ans4 sizeToFit];
// [self.view addSubview:ans4];

rightAnswer = [[theQuiz objectAtIndex:row+5] intValue];

Question = [[[UILabel alloc] initWithFrame:CGRectMake(22, 130, 725, 160)] autorelease];
Question.numberOfLines = 0;
//Question.font = [UIFont systemFontOfSize:27];
Question.text = [NSString stringWithFormat:@"%@" ,selected1];
Question.lineBreakMode = UILineBreakModeWordWrap;
[Question setFont:[UIFont fontWithName:@"Futura" size:26]];
Question.backgroundColor = [UIColor clearColor];
[Question sizeToFit];
[self.view addSubview:Question];

//For 1st Option.
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
           action:@selector(buttonOne)
 forControlEvents:UIControlEventTouchDown];
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button.titleLabel.font = [UIFont systemFontOfSize:24];
[button setTitle:[theQuiz objectAtIndex:row+1] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.frame = CGRectMake(34, 200 + Question.frame.size.height , 700, ans1.frame.size.height + 20) ;
[self.view addSubview:button];
button.layer.borderWidth = 3;
button.layer.borderColor = [[UIColor purpleColor ] CGColor];
button.layer.cornerRadius = 10.0;
[button setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 2nd Option.
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self
            action:@selector(buttonTwo)
  forControlEvents:UIControlEventTouchDown];
[button2 setTitle:[theQuiz objectAtIndex:row+2] forState:UIControlStateNormal];
[button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button2.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button2.titleLabel.font = [UIFont systemFontOfSize:24];
button2.frame = CGRectMake(34, 230 + Question.frame.size.height + button.frame.size.height , 700, ans2.frame.size.height + 20);
button2.layer.borderWidth = 3;
button2.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button2.layer.cornerRadius = 10.0;
[self.view addSubview:button2];
[button2 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button2.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 3rd Option.
button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 addTarget:self
            action:@selector(buttonThree)
  forControlEvents:UIControlEventTouchDown];
[button3 setTitle:[theQuiz objectAtIndex:row+3] forState:UIControlStateNormal];
[button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button3.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button3.titleLabel.font = [UIFont systemFontOfSize:24];
button3.frame = CGRectMake(34, 260 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height , 700, ans3.frame.size.height + 20);
button3.layer.borderWidth = 3;
button3.layer.borderColor = [[UIColor purpleColor ] CGColor];
button3.layer.cornerRadius = 10.0;

[self.view addSubview:button3];
[button3 setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button3.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 4th Option.
button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 addTarget:self
            action:@selector(buttonFour)
  forControlEvents:UIControlEventTouchDown];
[button4 setTitle:[theQuiz objectAtIndex:row+4] forState:UIControlStateNormal];
[button4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button4.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button4.titleLabel.font = [UIFont systemFontOfSize:24];
button4.frame = CGRectMake(34, 290 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height + button3.frame.size.height , 700, ans4.frame.size.height + 20);
button4.layer.borderWidth = 3;
button4.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button4.layer.cornerRadius = 10.0;
[self.view addSubview:button4];
[button4 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button4.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

NSString *strright = [theQuiz objectAtIndex:row+7];
//NSString *strtext = [[NSString alloc] initWithFormat:@"%@" , strright];

rightans = [[[UILabel alloc] initWithFrame:CGRectMake(50, 330, 650, 150)]autorelease];
rightans.numberOfLines = 0;
rightans.text = [NSString stringWithFormat:@"%@" , strright];
rightans.backgroundColor = [UIColor clearColor];
rightans.font = [UIFont systemFontOfSize:26];
[self.view addSubview:rightans];
[rightans sizeToFit];
[rightans setHidden:YES];

//Description.
NSString *des = [theQuiz objectAtIndex:row+6];
//  NSString *destext = [[NSString alloc] initWithFormat:@"\n> Explanation :\n%@\n\n" , des];

Description = [[[UILabel alloc] initWithFrame:CGRectMake(40, 400 + rightans.frame.size.height , 690, 150)] autorelease];
Description.numberOfLines = 0;
// Description.font = [UIFont systemFontOfSize:13.5];
Description.text = [NSString stringWithFormat:@"\n> Explanation :\n%@\n\n" , des];
[Description setFont:[UIFont fontWithName:@"Futura" size:26]];
Description.lineBreakMode = UILineBreakModeWordWrap;
Description.backgroundColor = [UIColor clearColor];
[Description sizeToFit];
[self.view addSubview:Description];
[Description setHidden:YES];

ContainerView = [[UIView alloc] initWithFrame:CGRectMake(30, 400 + rightans.frame.size.height , 700 ,Description.frame.size.height)];
ContainerView.backgroundColor = [UIColor clearColor];
ContainerView.layer.cornerRadius = 10.0;
ContainerView.layer.borderColor = [[UIColor grayColor] CGColor];
ContainerView.layer.borderWidth = 3;
// [ContainerView addSubview:Description];
[self.view addSubview:ContainerView];
[ContainerView setHidden:YES];
</code>```

Any help??

Thank you.

答: You should not release autorelease objects.</p>

Title: Multiple time allocation and release

Body:
I am creating a quiz app for iPhone/iPad(universal app).It is working fine on simulator but on real device there are some problem i am facing..

I am creating UILabels and UIButtons programmatically and i am using them so many times for displaying questions and answers one by one.

problem is when i reach around question 20 to 22 the application crashes. I don't know why. there is no memory leak i found. I release all the labels and buttons at the -dealloc function.

may be it happens because 22 questions takes some memory and not release till dealloc function call.

What i want is , Is there any way to release labels and buttons after every question and then it will allocate again? or any way in which i can use less memory for allocation labels and buttons??

I am using this code :

//lbl ref to btn1
ans1 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 292, 697, 100)] autorelease];
ans1.numberOfLines = 0;
ans1.font = [UIFont systemFontOfSize:26];
ans1.text = [theQuiz objectAtIndex:row+1];
ans1.lineBreakMode = UILineBreakModeWordWrap;
[ans1 sizeToFit];
//[self.view addSubview:ans1];
//lbl ref to btn2
ans2 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 312 + ans1.frame.size.height , 697, 100)] autorelease];
ans2.numberOfLines = 0;
ans2.font = [UIFont systemFontOfSize:26];
ans2.text = [theQuiz objectAtIndex:row+2];
ans2.lineBreakMode = UILineBreakModeWordWrap;
[ans2 sizeToFit];
// [self.view addSubview:ans2];
//lbl ref to btn3
ans3 = [[[UILabel alloc] initWithFrame:CGRectMake(36 ,332 + ans1.frame.size.height + ans2.frame.size.height , 697 , 100)] autorelease];
ans3.numberOfLines = 0;
ans3.font = [UIFont systemFontOfSize:26];
ans3.text = [theQuiz objectAtIndex:row+3] ;
ans3.lineBreakMode = UILineBreakModeWordWrap;
[ans3 sizeToFit];
// [self.view addSubview:ans3];
//lbl ref to btn4
ans4 = [[[UILabel alloc] initWithFrame:CGRectMake(36, 352 + ans1.frame.size.height + ans2.frame.size.height + ans3.frame.size.height, 697, 100)] autorelease];
ans4.numberOfLines = 0;
ans4.font = [UIFont systemFontOfSize:26];
ans4.text = [theQuiz objectAtIndex:row+4];
ans4.lineBreakMode = UILineBreakModeWordWrap;
[ans4 sizeToFit];
// [self.view addSubview:ans4];

rightAnswer = [[theQuiz objectAtIndex:row+5] intValue];

Question = [[[UILabel alloc] initWithFrame:CGRectMake(22, 130, 725, 160)] autorelease];
Question.numberOfLines = 0;
//Question.font = [UIFont systemFontOfSize:27];
Question.text = [NSString stringWithFormat:@"%@" ,selected1];
Question.lineBreakMode = UILineBreakModeWordWrap;
[Question setFont:[UIFont fontWithName:@"Futura" size:26]];
Question.backgroundColor = [UIColor clearColor];
[Question sizeToFit];
[self.view addSubview:Question];

//For 1st Option.
button = [UIButton buttonWithType:UIButtonTypeCustom];
[button addTarget:self
           action:@selector(buttonOne)
 forControlEvents:UIControlEventTouchDown];
button.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button.titleLabel.font = [UIFont systemFontOfSize:24];
[button setTitle:[theQuiz objectAtIndex:row+1] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button.frame = CGRectMake(34, 200 + Question.frame.size.height , 700, ans1.frame.size.height + 20) ;
[self.view addSubview:button];
button.layer.borderWidth = 3;
button.layer.borderColor = [[UIColor purpleColor ] CGColor];
button.layer.cornerRadius = 10.0;
[button setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 2nd Option.
button2 = [UIButton buttonWithType:UIButtonTypeCustom];
[button2 addTarget:self
            action:@selector(buttonTwo)
  forControlEvents:UIControlEventTouchDown];
[button2 setTitle:[theQuiz objectAtIndex:row+2] forState:UIControlStateNormal];
[button2 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button2.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button2.titleLabel.font = [UIFont systemFontOfSize:24];
button2.frame = CGRectMake(34, 230 + Question.frame.size.height + button.frame.size.height , 700, ans2.frame.size.height + 20);
button2.layer.borderWidth = 3;
button2.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button2.layer.cornerRadius = 10.0;
[self.view addSubview:button2];
[button2 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button2.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 3rd Option.
button3 = [UIButton buttonWithType:UIButtonTypeCustom];
[button3 addTarget:self
            action:@selector(buttonThree)
  forControlEvents:UIControlEventTouchDown];
[button3 setTitle:[theQuiz objectAtIndex:row+3] forState:UIControlStateNormal];
[button3 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button3.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button3.titleLabel.font = [UIFont systemFontOfSize:24];
button3.frame = CGRectMake(34, 260 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height , 700, ans3.frame.size.height + 20);
button3.layer.borderWidth = 3;
button3.layer.borderColor = [[UIColor purpleColor ] CGColor];
button3.layer.cornerRadius = 10.0;

[self.view addSubview:button3];
[button3 setBackgroundImage:[UIImage imageNamed:@"buttun.png"] forState:UIControlStateNormal];
button3.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

//For 4th Option.
button4 = [UIButton buttonWithType:UIButtonTypeCustom];
[button4 addTarget:self
            action:@selector(buttonFour)
  forControlEvents:UIControlEventTouchDown];
[button4 setTitle:[theQuiz objectAtIndex:row+4] forState:UIControlStateNormal];
[button4 setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
button4.titleLabel.lineBreakMode = UILineBreakModeWordWrap;
button4.titleLabel.font = [UIFont systemFontOfSize:24];
button4.frame = CGRectMake(34, 290 + Question.frame.size.height + button.frame.size.height + button2.frame.size.height + button3.frame.size.height , 700, ans4.frame.size.height + 20);
button4.layer.borderWidth = 3;
button4.layer.borderColor = [[UIColor darkGrayColor ] CGColor];
button4.layer.cornerRadius = 10.0;
[self.view addSubview:button4];
[button4 setBackgroundImage:[UIImage imageNamed:@"buttun2.png"] forState:UIControlStateNormal];
button4.titleEdgeInsets = UIEdgeInsetsMake(5, 5, 5, 5);

NSString *strright = [theQuiz objectAtIndex:row+7];
//NSString *strtext = [[NSString alloc] initWithFormat:@"%@" , strright];

rightans = [[[UILabel alloc] initWithFrame:CGRectMake(50, 330, 650, 150)]autorelease];
rightans.numberOfLines = 0;
rightans.text = [NSString stringWithFormat:@"%@" , strright];
rightans.backgroundColor = [UIColor clearColor];
rightans.font = [UIFont systemFontOfSize:26];
[self.view addSubview:rightans];
[rightans sizeToFit];
[rightans setHidden:YES];

//Description.
NSString *des = [theQuiz objectAtIndex:row+6];
//  NSString *destext = [[NSString alloc] initWithFormat:@"\n> Explanation :\n%@\n\n" , des];

Description = [[[UILabel alloc] initWithFrame:CGRectMake(40, 400 + rightans.frame.size.height , 690, 150)] autorelease];
Description.numberOfLines = 0;
// Description.font = [UIFont systemFontOfSize:13.5];
Description.text = [NSString stringWithFormat:@"\n> Explanation :\n%@\n\n" , des];
[Description setFont:[UIFont fontWithName:@"Futura" size:26]];
Description.lineBreakMode = UILineBreakModeWordWrap;
Description.backgroundColor = [UIColor clearColor];
[Description sizeToFit];
[self.view addSubview:Description];
[Description setHidden:YES];

ContainerView = [[UIView alloc] initWithFrame:CGRectMake(30, 400 + rightans.frame.size.height , 700 ,Description.frame.size.height)];
ContainerView.backgroundColor = [UIColor clearColor];
ContainerView.layer.cornerRadius = 10.0;
ContainerView.layer.borderColor = [[UIColor grayColor] CGColor];
ContainerView.layer.borderWidth = 3;
// [ContainerView addSubview:Description];
[self.view addSubview:ContainerView];
[ContainerView setHidden:YES];

Any help??

Thank you.


来源: stackexchange

问:
Github project can't open
I'm getting this issue while I import github project
This version of the Android Support plugin for IntelliJ IDEA (or Android Studio) cannot open this project, please retry with version 2021.1.1 or newer.  how to solve this issue</p>

答: Because the gradle.properties of the project is not compatible with your android studio version... I Suggest click on Windows>Check For Updates and download all the files !!

ContentLicense: CC BY-SA 4.0

Title: Github project can't open


问:
Wanting to have seperate policies for SignIn and SignUp while using MSAL.net - both receiving webhook for AuthorizationCodeReceived
I have a .net mvc project based on b2c-webapi-dotnet ([https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi][1]) where I can register users or allow them to sign in via b2c (both operations having the same SignUpSignIn policy). This works as I expect.

I'm now trying to split this single policy into two, so having a SignUp policy and an additional SignIn policy

As part of this, both policies need to hit the AuthorizationCodeReceived hook so that I can pull out the b2c oid guid. This is used to find additional information on a user stored in a separate database.

What I am finding is that OnAuthorizationCodeReceived is only called when using one of my policies, its the default policy that I set into the MetadataAddress property when setting up the authorization.

In the code below, whichever policy I set for Settings.B2C_DefaultPolicyId (either SignIn or SignUp) is the one that has OnAuthorizationCodeReceived called.

Can anyone tell me if there is a way to have both policies be able to call OnAuthorizationCodeReceived ?

I appreciate any help you can give.

```<code>public void ConfigureAuth(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        // ASP.NET web host compatible cookie manager
        CookieManager = new SystemWebChunkingCookieManager()
    });

    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            // Generate the metadata address using the tenant and policy information
            MetadataAddress = String.Format(WellKnownMetadata, Common.Settings.AppSettings.B2C_Tenant, Settings.B2C_DefaultPolicyId),

            // These are standard OpenID Connect parameters, with values pulled from web.config
            ClientId = Settings.AppSettings.B2C_ClientID,
            RedirectUri = RedirectUri,
            PostLogoutRedirectUri = PostLogoutRedirectUri,

            // Specify the callbacks for each type of notifications
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                RedirectToIdentityProvider = OnRedirectToIdentityProvider,
                AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                AuthenticationFailed = OnAuthenticationFailed,
            },

            // Specify the claim type that specifies the Name property.
            TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name",
                ValidateIssuer = false
            },

            // Specify the scope by appending all of the scopes requested into one string (separated by a blank space)
            Scope = $"openid profile offline_access {Settings.AppSettings.B2C_ReadTasksScope} {Settings.AppSettings.B2C_WriteTasksScope}",

            // ASP.NET web host compatible cookie manager
            CookieManager = new SystemWebCookieManager()
        }
    );
}
</code>```

答:
I've figured it out with the help of a colleague

From the example code I had, one of the callbacks had some code that needed to be updated

```<code>private Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
    var policy = notification.OwinContext.Get<string>("Policy");

    if (!string.IsNullOrEmpty(policy) && !policy.Equals(Globals.DefaultPolicy))
    {
        notification.ProtocolMessage.Scope = OpenIdConnectScope.OpenId;
        notification.ProtocolMessage.ResponseType = OpenIdConnectResponseType.IdToken;
        notification.ProtocolMessage.IssuerAddress = notification.ProtocolMessage.IssuerAddress.ToLower().Replace(Globals.DefaultPolicy.ToLower(), policy.ToLower());
    }

    return Task.FromResult(0);
}
</code>```

The ResponseType needs to be changed from IdToken to CodeIdToken. Doing this means the non default Policy also hits the callback AuthorizationCodeReceived

One side affect of doing this is that after OnAuthorizationCodeReceived is hit, the callback for AuthenticationFailed is also hit.

To handle this, I've just put a conditional statement in the OnAuthenticationFailed method that returns to the root view (notification.Response.Redirect("/"))

Body:
I have a .net mvc project based on b2c-webapi-dotnet ([https://github.com/Azure-Samples/active-directory-b2c-dotnet-webapp-and-webapi][1]) where I can register users or allow them to sign in via b2c (both operations having the same SignUpSignIn policy). This works as I expect.

I'm now trying to split this single policy into two, so having a SignUp policy and an additional SignIn policy

As part of this, both policies need to hit the AuthorizationCodeReceived hook so that I can pull out the b2c oid guid. This is used to find additional information on a user stored in a separate database.

What I am finding is that OnAuthorizationCodeReceived is only called when using one of my policies, its the default policy that I set into the MetadataAddress property when setting up the authorization.

In the code below, whichever policy I set for Settings.B2C_DefaultPolicyId (either SignIn or SignUp) is the one that has OnAuthorizationCodeReceived called.

Can anyone tell me if there is a way to have both policies be able to call OnAuthorizationCodeReceived ?

I appreciate any help you can give.

public void ConfigureAuth(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

    app.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        // ASP.NET web host compatible cookie manager
        CookieManager = new SystemWebChunkingCookieManager()
    });

    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            // Generate the metadata address using the tenant and policy information
            MetadataAddress = String.Format(WellKnownMetadata, Common.Settings.AppSettings.B2C_Tenant, Settings.B2C_DefaultPolicyId),

            // These are standard OpenID Connect parameters, with values pulled from web.config
            ClientId = Settings.AppSettings.B2C_ClientID,
            RedirectUri = RedirectUri,
            PostLogoutRedirectUri = PostLogoutRedirectUri,

            // Specify the callbacks for each type of notifications
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                RedirectToIdentityProvider = OnRedirectToIdentityProvider,
                AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                AuthenticationFailed = OnAuthenticationFailed,
            },

            // Specify the claim type that specifies the Name property.
            TokenValidationParameters = new TokenValidationParameters
            {
                NameClaimType = "name",
                ValidateIssuer = false
            },

            // Specify the scope by appending all of the scopes requested into one string (separated by a blank space)
            Scope = $"openid profile offline_access {Settings.AppSettings.B2C_ReadTasksScope} {Settings.AppSettings.B2C_WriteTasksScope}",

            // ASP.NET web host compatible cookie manager
            CookieManager = new SystemWebCookieManager()
        }
    );
}

Body:
I've figured it out with the help of a colleague

From the example code I had, one of the callbacks had some code that needed to be updated

private Task OnRedirectToIdentityProvider(RedirectToIdentityProviderNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
{
    var policy = notification.OwinContext.Get<string>("Policy");

    if (!string.IsNullOrEmpty(policy) && !policy.Equals(Globals.DefaultPolicy))
    {
        notification.ProtocolMessage.Scope = OpenIdConnectScope.OpenId;
        notification.ProtocolMessage.ResponseType = OpenIdConnectResponseType.IdToken;
        notification.ProtocolMessage.IssuerAddress = notification.ProtocolMessage.IssuerAddress.ToLower().Replace(Globals.DefaultPolicy.ToLower(), policy.ToLower());
    }

    return Task.FromResult(0);
}

The ResponseType needs to be changed from IdToken to CodeIdToken. Doing this means the non default Policy also hits the callback AuthorizationCodeReceived

One side affect of doing this is that after OnAuthorizationCodeReceived is hit, the callback for AuthenticationFailed is also hit.

To handle this, I've just put a conditional statement in the OnAuthenticationFailed method that returns to the root view (notification.Response.Redirect("/"))


问:
AWS SQL Server. Unable to complete login process due to delay in opening server connection
I have an on-premise SQL Server and SSIS 2014. I also have a SQL Server database (Microsoft SQL Server 2019 Standard Edition (64-bit)) in AWS RDS. There is a simple package in on-premise SSIS than must get data from tables in AWS SQL Server and transfer it to an on-premise database. For connection to AWS I use SQL Server Native Client 11.0.

After successful transferring data from several tables, I get the exception

Error: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0x80004005.

An OLE DB record is available.  Source: "Microsoft SQL Server Native Client 11.0"  Hresult: 0x80004005  Description: "Unable to complete login process due to delay in opening server connection".

I tried different scenarios:

loading per 8 tables simultaneously, then next 8 tables and etc.

loading per 6 tables simultaneously, then next 6 tables and etc.

loading per 2 tables simultaneously, then next 2 tables and etc.

loading data with waitings

But every time I get an exception mentioned above.

For AWS SQL Server are applied the next settings:

Any ideas what the reason could be?

答: The reason is it was used the connection string to the listener. When the 'listener' was deleted from the connection string the data transfer became work fastly and without any issues.</p>


问:
problem understanding c++ namespace and using-declaration in terms of inheritance
```<code>struct A { int i; };
struct B: A {};
struct C: A {};
struct D: B, C {
    using B::i;
    void f() {
        i = 0;
    }
};
</code>```

It seems like I specified to use i from A from B, but compiler says

error: 'A' is an ambiguous base of 'D'

To be honest, I don't really understand what using B::i does. As far as I know, it brings i from namespace B, to namespace D. But does namespace B contain i because it inherits i from A, or is it only namespace A that contains i? If latter, why

```<code>//A, B, C is same with above
struct D: B, C {
    void f() {
        B::i = 0;
    }
};
</code>```

this just compiles with no problem?

As you can see, I'm confusing with whole concept of namespaces in terms of class inheritance. Can anyone explain how rules of namespaces, inheritance, etc. works with these examples?

答:
I think this is a good example of the famous 'diamond problem'. This arises in multiple inheritance when two parent classes inherit from the same grandparent class, and both parent classes are inherited by a single child class.
How about you try this</p>
```<code>struct A { int i; };
struct B: A { void f() {
  i = 0;
}};
</code>```

Body:
struct A { int i; };
struct B: A {};
struct C: A {};
struct D: B, C {
    using B::i;
    void f() {
        i = 0;
    }
};

It seems like I specified to use i from A from B, but compiler says

error: 'A' is an ambiguous base of 'D'

To be honest, I don't really understand what using B::i does. As far as I know, it brings i from namespace B, to namespace D. But does namespace B contain i because it inherits i from A, or is it only namespace A that contains i? If latter, why

//A, B, C is same with above
struct D: B, C {
    void f() {
        B::i = 0;
    }
};

this just compiles with no problem?

As you can see, I'm confusing with whole concept of namespaces in terms of class inheritance. Can anyone explain how rules of namespaces, inheritance, etc. works with these examples?

Body:
I think this is a good example of the famous 'diamond problem'. This arises in multiple inheritance when two parent classes inherit from the same grandparent class, and both parent classes are inherited by a single child class.
How about you try this

struct A { int i; };
struct B: A { void f() {
  i = 0;
}};


问:
How to print Escape Sequence characters in Swift?
Sorry if the title is not clear.

What I mean is this:
If I have a variable, we'll call that a, with a value of "Hello\nWorld", it would be written as

```<code>var a = "Hello\nWorld
</code>```

And if I were to print it, I'd get

```<code>Hello
World
</code>```

How could I print it as:

```<code>Hello\nWorld
</code>```

答:
Late to the party but the answer to this question is to map the String UnicodeScalarView Unicode.Scalar elements converting them to escaped ascii strings. Then you can simply join back the string:

```<code>extension Unicode.Scalar {
    var asciiEscaped: String { escaped(asASCII: true) }
}
</code>```

```<code>extension StringProtocol {
    var asciiEscaped: String {
        unicodeScalars.map(\.asciiEscaped).joined()
    }
}
</code>```

```<code>print("Hello\nWorld".asciiEscaped)   // Hello\nWorld
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Sorry if the title is not clear.

What I mean is this:
If I have a variable, we'll call that a, with a value of "Hello\nWorld", it would be written as

var a = "Hello\nWorld

And if I were to print it, I'd get

Hello
World

How could I print it as:

Hello\nWorld

Body:
Late to the party but the answer to this question is to map the String UnicodeScalarView Unicode.Scalar elements converting them to escaped ascii strings. Then you can simply join back the string:

extension Unicode.Scalar {
    var asciiEscaped: String { escaped(asASCII: true) }
}

extension StringProtocol {
    var asciiEscaped: String {
        unicodeScalars.map(\.asciiEscaped).joined()
    }
}

print("Hello\nWorld".asciiEscaped)   // Hello\nWorld


问:
Certificate has either expired or has been revoked
A while ago I started coding a new iOS app. After a long break from it, I'm working on it again and have it almost complete.

I tested it on the simulator but when I tried to install it on my iPhone 6 (something I have already done in the past), I got an error telling me that my app cannot be installed since the certificate that was used to sign this app expired or has been revoked.

I tried many things:

I deleted all certificates and provisioning profiles from Xcode, keychain, and apple developer and let Xcode create me new ones

I deleted Xcode and did the whole process from the beginning

But this didn't fix my issue.

Any idea what might be the problem?

答:
I had this issue and I fixed that.

Go to XCode Menu> Accounts

Select Accounts > Team > View Details

Select Manage Certificates... and You'll see signing certificates menu will pop.

Click on the Apple Development and and press Done button.


问:
How to dockerize to access on-premises NFS file from ECS Fargate (Linux/Windows)
I need to access the on-premises NFS file from docker orchestration on ECS Fargate (Linux/Windows). On-premises and AWS are connected via Direct Connect. I am unsure if the docker on ECS Fargate task can be mounted NFS/Samba to access NFS file.
Question:

If I choose to mount AWS EFS on docker and sync data to this volume from on-premises via DataSync - Is this solution acceptable?

Any other AWS service that can be used to pick NFS file and consume using docker container orchestrated on ECS Fargate ?

答:
The docs stated that only these volumes are allowed in ECS:

Amazon EFS volumes

FSx for Windows File Server volumes

Docker volumes

Bind mounts

So it currently does not support on-premises NFS file.

Another solution is to mount the EFS on-prem. Then you alter whatever the existing workload on-prem to write to the EFS, instead of (or in addition to) the current NFS.


问:
How to get the part of a file after the first line that matches a regular expression
I have a file with about 1000 lines. I want the part of my file after the line which matches my grep statement.

That is:

```<code>cat file | grep 'TERMINATE'     # It is found on line 534
</code>```

So, I want the file from line 535 to line 1000 for further processing.

How can I do that?

答:
If for any reason, you want to avoid using sed, the following will print the line matching TERMINATE till the end of the file:

```<code>tail -n "+$(grep -n 'TERMINATE' file | head -n 1 | cut -d ":" -f 1)" file
</code>```

And the following will print from the following line matching TERMINATE till the end of the file:

```<code>tail -n "+$(($(grep -n 'TERMINATE' file | head -n 1 | cut -d ":" -f 1)+1))" file
</code>```

It takes two processes to do what sed can do in one process, and if the file changes between the execution of grep and tail, the result can be incoherent, so I recommend using sed.  Moreover, if the file doesn’t not contain TERMINATE, the first command fails.

Body:
I have a file with about 1000 lines. I want the part of my file after the line which matches my grep statement.

That is:

cat file | grep 'TERMINATE'     # It is found on line 534

So, I want the file from line 535 to line 1000 for further processing.

How can I do that?

Body:
If for any reason, you want to avoid using sed, the following will print the line matching TERMINATE till the end of the file:

tail -n "+$(grep -n 'TERMINATE' file | head -n 1 | cut -d ":" -f 1)" file

And the following will print from the following line matching TERMINATE till the end of the file:

tail -n "+$(($(grep -n 'TERMINATE' file | head -n 1 | cut -d ":" -f 1)+1))" file

It takes two processes to do what sed can do in one process, and if the file changes between the execution of grep and tail, the result can be incoherent, so I recommend using sed.  Moreover, if the file doesn’t not contain TERMINATE, the first command fails.


问:
How to add recycler view animation like telegram?
I am currently making a chat app and i want to add a feature like telegram. As you can see here, there is a animation in the recycler view as if i=t zooming or decreasing its size. You can also notice that animation while opening and closing the navigation drawer. I too tried to do that using this but i get no animation in the recycler view. See this. Actually not this but like this. I took this gif from the README of the repo. So is that possible? If so, can you please tell me a simple implementation ?

Thanks in advance and i will be waiting

答:
Add overridePendingTransition in onBackPressed() method:

```<code>@Override
public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(0, R.anim.slide_out_right);
}
</code>```

res->anim->slide_out_right.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="0"
        android:toXDelta="100%p" />
</set>
</code>```

Body:
Add overridePendingTransition in onBackPressed() method:

@Override
public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(0, R.anim.slide_out_right);
}

res->anim->slide_out_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromXDelta="0"
        android:toXDelta="100%p" />
</set>


问:
how to get only one value from array data and convert it into comma separted values. using javascript without template literals
i have array data in the format given below

```<code>const data=  [
  {
    name: "productname",
    id: "1356",
    price: "0.00",
    category: "Health",
    position: "1",
    list: "New Products",
    stocklevel: "20",
    brand: "Health"
  },
  {
    name: "productname2",
    id: "5263",
    price: "0",
    category: "Hair",
    position: "2",
    list: "New Products",
    stocklevel: "",
    brand: "Hair"
  }]
</code>```

from this data i want only product name of each product by difference of product1 , product2.
for example i want the data in format of string by comma separated values like given below:-

```<code>product1name: "productname",
product2name: "productname2",
...
</code>```

i tried using map function but not able to take only one or two values from whole array data.
here is the code what i tried

```<code>    var dataByComa = '';

  var Values = data
  .map(function (p, i) {
    return Object.keys(data[i]).map(function (k) {
      return "prod" +" " + ": " + JSON.stringify(data[i][k]);
    });
  }).map(function (v) {
    return v.join(",\n"); });
  var commaValues = Values.join(",\n");
return commaValues;
</code>```

with this code i can able to convert array data into comma separated values but i want only productnames.

Note :- Without using template template literals.

答:
Edit: I'm more clear on what the OP was looking for now - here is an answer that fulfills all the requirements</p>
```<code>let commaValues = ""
for (let i = 0; i < data.length; i++) {
    commaValues += ("product" + (i + 1) + "name: " + "\"" + data[i]["name"] + "\", ")
}
// result: 'product1name: "productname", product2name: "productname2", '
</code>```

Body:
i have array data in the format given below

const data=  [
  {
    name: "productname",
    id: "1356",
    price: "0.00",
    category: "Health",
    position: "1",
    list: "New Products",
    stocklevel: "20",
    brand: "Health"
  },
  {
    name: "productname2",
    id: "5263",
    price: "0",
    category: "Hair",
    position: "2",
    list: "New Products",
    stocklevel: "",
    brand: "Hair"
  }]

from this data i want only product name of each product by difference of product1 , product2.
for example i want the data in format of string by comma separated values like given below:-

product1name: "productname",
product2name: "productname2",
...

i tried using map function but not able to take only one or two values from whole array data.
here is the code what i tried

    var dataByComa = '';

  var Values = data
  .map(function (p, i) {
    return Object.keys(data[i]).map(function (k) {
      return "prod" +" " + ": " + JSON.stringify(data[i][k]);
    });
  }).map(function (v) {
    return v.join(",\n"); });
  var commaValues = Values.join(",\n");
return commaValues;

with this code i can able to convert array data into comma separated values but i want only productnames.

Note :- Without using template template literals.

Body:
Edit: I'm more clear on what the OP was looking for now - here is an answer that fulfills all the requirements

let commaValues = ""
for (let i = 0; i < data.length; i++) {
    commaValues += ("product" + (i + 1) + "name: " + "\"" + data[i]["name"] + "\", ")
}
// result: 'product1name: "productname", product2name: "productname2", '


问:
What's the correct way to use scanf_s in using string arrays?

char array1[10];
scanf_s("%9s", array1, (unsigned)_countof(array1);
```

What's mean of (unsigned)_countof(array1)?

and what's different from use scanf_s("%9s", array1, sizeof(array1);?

both worked, but I want to understand about it more surely

答:
This question is compiler based, GCC 11.1.0 on Arch Linux does not have functions like scanf_s and _countof. These functions/macros might be valid in Windows.

I read some docs on Microsoft docs. So, _countof is a macro which calls sizeof() internally and scanf_s is similar to scanf in standard C17.

What's mean of (unsigned)_countof(array1)? and what's different from use scanf_s("%9s", array1, sizeof(array1);? both work, but I want to understand about it more surely

Here the macro _countof is counting the length of the stack stored array, which in this case is 10.

_countof macro expands to:

```<code>#define _countof(x) (sizeof(x) / sizeof(x[0]))
// the operation goes for `array1` like this:
// 10 * 1 byte / 1 byte
// 1 byte is the sizeof char
// hence, 10 is returned as the result of the above operation
</code>```

And (unsigned) is just type casting the value of the above operation.

NOTE: As _countof is calling sizeof() do not use this inside a function the get the length of an array. Because sizeof(arr_ptr) will return the size of pointer which is 8 bytes in my case (x86_64 architecture).

Conclusion:

There no _countof is just calling sizeof(). I would like to suggest you to use sizeof and scanf functions because they are cross-platform and portable throughout the C standards.

Body:
char array1[10];
scanf_s("%9s", array1, (unsigned)_countof(array1);

What's mean of (unsigned)_countof(array1)?

and what's different from use scanf_s("%9s", array1, sizeof(array1);?

both worked, but I want to understand about it more surely

Body:
This question is compiler based, GCC 11.1.0 on Arch Linux does not have functions like scanf_s and _countof. These functions/macros might be valid in Windows.

I read some docs on Microsoft docs. So, _countof is a macro which calls sizeof() internally and scanf_s is similar to scanf in standard C17.

What's mean of (unsigned)_countof(array1)? and what's different from use scanf_s("%9s", array1, sizeof(array1);? both work, but I want to understand about it more surely

Here the macro _countof is counting the length of the stack stored array, which in this case is 10.

_countof macro expands to:

#define _countof(x) (sizeof(x) / sizeof(x[0]))
// the operation goes for `array1` like this:
// 10 * 1 byte / 1 byte
// 1 byte is the sizeof char
// hence, 10 is returned as the result of the above operation

And (unsigned) is just type casting the value of the above operation.

NOTE: As _countof is calling sizeof() do not use this inside a function the get the length of an array. Because sizeof(arr_ptr) will return the size of pointer which is 8 bytes in my case (x86_64 architecture).

Conclusion:

There no _countof is just calling sizeof(). I would like to suggest you to use sizeof and scanf functions because they are cross-platform and portable throughout the C standards.


问:
when i run composer require laravel/ui this command
[Composer\Downloader\TransportException]
Unable to use a proxy: malformed http_proxy url

require [--dev] [--dry-run] [--prefer-source] [--prefer-dist] [--prefer-install PREFER-INSTALL] [--fixed] [--no-suggest] [--no-progress] [--no-update] [--no-install] [--update-no-dev] [-w|--update-with-dependencies] [-W|--update-with-all-dependencies] [--with-dependencies] [--with-all-dependencies] [--ignore-platform-req IGNORE-PLATFORM-REQ] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--apcu-autoloader-prefix APCU-AUTOLOADER-PREFIX] [--] []...

答:
Try this</p>
```<code>composer global require laravel/ui
</code>```

Body:
Try this

composer global require laravel/ui


答:
sizeof and _countof are different.
(edit:) In this case you should use countof.

sizeof is an operator in C that returns the memory size occupied by a variable, in bytes.
In this case, array1 is an array of 10 chars, so it's size is ten times the size of a char, and sizeof(char) is 1 byte. So the value of sizeof(array1) is 10 * 1 = 10 bytes.

Note that in C you can use sizeof on any variable (e.g. sizeof(array1)) or on any type (e.g. sizeof(int)).

_countof is a macro (only available on Microsoft platforms) that gives you the number of elements declared in an array variable. In this case your array1 variable has 10 elements, so _countof(array1) will be 10.

Now in your precise case this happens to be the same result because the size of each char is 1, but this wouldn't be the same if, for example, your variable was an array of ints.

```<code>int array2[10];

sizeof(array2);  // = 40
_countof(array2); // = 10
</code>```

An int is (usually) 4 bytes, so an array of 10 ints will have a size of 10*4 = 40 bytes. On the other hand, _countof will just count how many elements are declared in the array, and still return 10.

In fact, we can see that the definition of _countof is litterally sizeof(array) divided by sizeof(array[0]), that is, the size of an individual element.

Since scanf_s with "%s" expects a number of items, you should be using _countof. (edit).

You might also want to be careful with sizeof (and _countof) on arrays, and avoid using them on pointers. Also be aware that _countof will not work outside of Visual Studio. See these related answers.

Title: What's the correct way to use scanf_s in using string arrays?

Body:
sizeof and _countof are different.
(edit:) In this case you should use countof.

sizeof is an operator in C that returns the memory size occupied by a variable, in bytes.
In this case, array1 is an array of 10 chars, so it's size is ten times the size of a char, and sizeof(char) is 1 byte. So the value of sizeof(array1) is 10 * 1 = 10 bytes.

Note that in C you can use sizeof on any variable (e.g. sizeof(array1)) or on any type (e.g. sizeof(int)).

_countof is a macro (only available on Microsoft platforms) that gives you the number of elements declared in an array variable. In this case your array1 variable has 10 elements, so _countof(array1) will be 10.

Now in your precise case this happens to be the same result because the size of each char is 1, but this wouldn't be the same if, for example, your variable was an array of ints.

int array2[10];

sizeof(array2);  // = 40
_countof(array2); // = 10

An int is (usually) 4 bytes, so an array of 10 ints will have a size of 10*4 = 40 bytes. On the other hand, _countof will just count how many elements are declared in the array, and still return 10.

In fact, we can see that the definition of _countof is litterally sizeof(array) divided by sizeof(array[0]), that is, the size of an individual element.

Since scanf_s with "%s" expects a number of items, you should be using _countof. (edit).

You might also want to be careful with sizeof (and _countof) on arrays, and avoid using them on pointers. Also be aware that _countof will not work outside of Visual Studio. See these related answers.


问:
Error: Requiring module "node_modules\react-native-reanimated\src\Animated.js",
I am trying to use createDrawerNavigator from import { createDrawerNavigator } from '@react-navigation/drawer'; in react native. However, I am getting the error below, which I don't know how to solve.

Error: Requiring module
"node_modules\react-native-reanimated\src\Animated.js", which threw an
exception: Error: Reanimated 2 failed to create a worklet, maybe you
forgot to add Reanimated's babel plugin?

In babel.config.js I tried to add the below code but not working as well

module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
    plugins: [
      'react-native-reanimated/plugin',
    ]
  };
};
```
<p>The Below code is my component</p>
<pre class="lang-js prettyprint-override"><code>import * as React from 'react';
import { Button, View } from 'react-native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button
        onPress={() => navigation.navigate('Notifications')}
        title="Go to notifications"
      />
    </View>
  );
}

function NotificationsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button onPress={() => navigation.goBack()} title="Go back home" />
    </View>
  );
}

const Drawer = createDrawerNavigator();

export default function MyDrawer() {
  return (
    <NavigationContainer>
      <Drawer.Navigator initialRouteName="Home">
        <Drawer.Screen name="Home" component={HomeScreen} />
        <Drawer.Screen name="Notifications" component={NotificationsScreen} />
      </Drawer.Navigator>
    </NavigationContainer>
  );
}
</code>```

答:
You must install according to these instructions:

[https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/installation/][1]

Also, make no mistake Be careful where you write the following code

```<code>@Override
protected JSIModulePackage getJSIModulePackage() {
return new ReanimatedJSIModulePackage();  }
</code>```

Body:
I am trying to use createDrawerNavigator from import { createDrawerNavigator } from '@react-navigation/drawer'; in react native. However, I am getting the error below, which I don't know how to solve.

Error: Requiring module
"node_modules\react-native-reanimated\src\Animated.js", which threw an
exception: Error: Reanimated 2 failed to create a worklet, maybe you
forgot to add Reanimated's babel plugin?

In babel.config.js I tried to add the below code but not working as well

module.exports = function(api) {
  api.cache(true);
  return {
    presets: ['babel-preset-expo'],
    plugins: [
      'react-native-reanimated/plugin',
    ]
  };
};

The Below code is my component

import * as React from 'react';
import { Button, View } from 'react-native';
import { createDrawerNavigator } from '@react-navigation/drawer';
import { NavigationContainer } from '@react-navigation/native';

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button
        onPress={() => navigation.navigate('Notifications')}
        title="Go to notifications"
      />
    </View>
  );
}

function NotificationsScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Button onPress={() => navigation.goBack()} title="Go back home" />
    </View>
  );
}

const Drawer = createDrawerNavigator();

export default function MyDrawer() {
  return (
    <NavigationContainer>
      <Drawer.Navigator initialRouteName="Home">
        <Drawer.Screen name="Home" component={HomeScreen} />
        <Drawer.Screen name="Notifications" component={NotificationsScreen} />
      </Drawer.Navigator>
    </NavigationContainer>
  );
}

Body:
You must install according to these instructions:

[https://docs.swmansion.com/react-native-reanimated/docs/fundamentals/installation/][1]

Also, make no mistake Be careful where you write the following code

@Override
protected JSIModulePackage getJSIModulePackage() {
return new ReanimatedJSIModulePackage();  }


问:
Add image just into a bottom or top in QT App with StyleSheet(QStyle)
How can i add image just into the bottom or up of the Form in QT with Stylesheet.
for example, i want to add image that you can see it at image below and then set padding of the form:

link of image:
http://0000.2.img98.net/out.php/i11716_bg-header2.jpg

Please explain it with CSS Commands.

答:
You can do it with qss (css). But in order to enable the stylesheets in your custom QWidget you will have to handle the Paint event.

mywidget.cpp

```<code>void QMyWidget::paintEvent(QPaintEvent *)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
</code>```

Add your css (qss) in the resources and add alias name, which will be used as filename for loading.

You can add this method in the main window, to load stylesheet.

mymainwindow.cpp

```<code>void QMyMainWindow::loadStyleSheet(QString path)
{
    QFile data(path);
    QString style;
    if(!data.open(QFile::ReadOnly))
        return false;

    QTextStream styleIn(&data);
    style = styleIn.readAll();
    data.close();

    qApp->setStyleSheet(qApp->styleSheet().append(style));
}
</code>```

Then call this function with the resource alias name of QSS (CSS) file. You can do this in the constructor or in resize event (for mobile development) to track and load different styles for different resolutions.

Body:
You can do it with qss (css). But in order to enable the stylesheets in your custom QWidget you will have to handle the Paint event.

mywidget.cpp

void QMyWidget::paintEvent(QPaintEvent *)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

Add your css (qss) in the resources and add alias name, which will be used as filename for loading.

You can add this method in the main window, to load stylesheet.

mymainwindow.cpp

void QMyMainWindow::loadStyleSheet(QString path)
{
    QFile data(path);
    QString style;
    if(!data.open(QFile::ReadOnly))
        return false;

    QTextStream styleIn(&data);
    style = styleIn.readAll();
    data.close();

    qApp->setStyleSheet(qApp->styleSheet().append(style));
}

Then call this function with the resource alias name of QSS (CSS) file. You can do this in the constructor or in resize event (for mobile development) to track and load different styles for different resolutions.


问:
Enum.TryParse doesn't accept my out parameter as an object
I have the following line:

var parseSortField = (BasicProfileSortableFields?)Enum.TryParse(typeof(BasicProfileSortableFields?), sortOptions.SortColumn, out BasicProfileSortableFields? sortField);

Around the out parameter, I'm getting an error that says

Argument 3: cannot convert from 'out Services.Models.BasicProfileSortableFields?' to 'out object?'

Regular parsing works but I'm trying to catch a scenario where my string is not in the mentioned enum. Also the enum I'm referencing is from a nuget package and not actually written by me if that helps.

答:
Enum.TryParse returns a boolean, and the 3rd parameter is out object?. You may want to use Enum.Parse instead? In which case, just eliminate the third parameter, and wrap the call in a try..catch if you care to handle when the parse fails.

Also, I think you want the first parameter to be the type of your enum, not the type of a Nullable wrapper for your enum, but I could be mistaken on that.

Alternatively, to keep using TryParse, you should first check the result to see if the parse failed, and get the out parameter as an object?, which you can then cast to your target type if the parse succeeded, like this:

```<code>BasicProfileSortableFields parseSortField;

if(Enum.TryParse(typeof(BasicProfileSortableFields), sortOptions.SortColumn, out object? sortField))
{
    parseSortField = (BasicProfileSortableFields)sortField.Value;
}
else
{
    // Handle failed parse condition here
}
</code>```

Body:
Enum.TryParse returns a boolean, and the 3rd parameter is out object?. You may want to use Enum.Parse instead? In which case, just eliminate the third parameter, and wrap the call in a try..catch if you care to handle when the parse fails.

Also, I think you want the first parameter to be the type of your enum, not the type of a Nullable wrapper for your enum, but I could be mistaken on that.

Alternatively, to keep using TryParse, you should first check the result to see if the parse failed, and get the out parameter as an object?, which you can then cast to your target type if the parse succeeded, like this:

BasicProfileSortableFields parseSortField;

if(Enum.TryParse(typeof(BasicProfileSortableFields), sortOptions.SortColumn, out object? sortField))
{
    parseSortField = (BasicProfileSortableFields)sortField.Value;
}
else
{
    // Handle failed parse condition here
}


问:
Set Default Value on SalesOrderForm in Microsoft Dynamics using COC
I have added field in salesTable and on the salesTable form. I want to put the default values like created when the sales order is created and Updated when sales order is updated. All I have to do is using chain of command.</p>

答:
You create a new class,extension of SalesTable, with something like this:</p>
```<code>[ExtensionOf(tablestr(SalesTable))]
final class SalesTable_MyExt_Extension
{
    void initValue(SalesType _salesType)
    {
        next initValue();

        this.myField = "foo";
    }

    public void update()
    {
        this.myField = "bar";

        next update();
    }

}
</code>```

Body:
You create a new class,extension of SalesTable, with something like this:

[ExtensionOf(tablestr(SalesTable))]
final class SalesTable_MyExt_Extension
{
    void initValue(SalesType _salesType)
    {
        next initValue();

        this.myField = "foo";
    }

    public void update()
    {
        this.myField = "bar";

        next update();
    }

}


问:
I am trying to make "Game of Set" but don't know how to correctly check the set
Hi so I just started to learn coding and ruby is my first language. I am trying to make a game called "Game of Set" the rules can be checked in here or wikipedia

I am able to get users cards and enter them in different arrays. However, I have been spending a lot of time trying to figure out how to validate the set. I tried to compare the arrays index by index but the result is not what I wanted.
Example:

```<code>first = ['two', 'purple', 'stripe', 'diamond']
second = ['one', 'purple', 'solid', 'diamond']
third = ['three', 'purple', 'empty', 'diamond']
</code>```

this should be correct because all are purple, all are diamond, different number, and different filters.

```<code>first = ['one', 'green', 'stripe', 'squiggle']
second = ['one', 'purple', 'solid', 'diamond']
third = ['two', 'green', 'empty', 'oval']
</code>```

This is wrong because because two have the same number and one does not, similarly with the color.

This is the game of set that I want to achieve here

Please help thank you!

答:
In this game, a __set is defined as:

Several games can be played with these cards, all involving the concept of a set. A set consists of three cards satisfying all of these conditions:

They all have the same number or have three different numbers.

They all have the same shape or have three different shapes.

They all have the same shading or have three different shadings.

They all have the same color or have three different colors.

-- Wikipedia

That can be checked with a one-liner:

```<code>first = ['two', 'purple', 'stripe', 'diamond']
second = ['one', 'purple', 'solid', 'diamond']
third = ['three', 'purple', 'empty', 'diamond']
first.zip(second, third).all? { |array| [1,3].include?(array.uniq.length) }
#=> true

first = ['one', 'green', 'stripe', 'squiggle']
second = ['one', 'purple', 'solid', 'diamond']
third = ['two', 'green', 'empty', 'oval']
first.zip(second, third).all? { |array| [1,3].include?(array.uniq.length) }
#=> false
</code>```

How does this work in detail?

```<code>first
  .zip(second, third) #=> [["two", "one", "three"], ["purple", "purple", "purple"], ["stripe", "solid", "empty"], ["diamond", "diamond", "diamond"]]
  .all? { |array|
     # do all nested arrays comply with the set conditions and
     # contain only the same element or three different ones?
    [1,3].include?(array.uniq.length)
  }
</code>```

Body:
Hi so I just started to learn coding and ruby is my first language. I am trying to make a game called "Game of Set" the rules can be checked in here or wikipedia

I am able to get users cards and enter them in different arrays. However, I have been spending a lot of time trying to figure out how to validate the set. I tried to compare the arrays index by index but the result is not what I wanted.
Example:

first = ['two', 'purple', 'stripe', 'diamond']
second = ['one', 'purple', 'solid', 'diamond']
third = ['three', 'purple', 'empty', 'diamond']

this should be correct because all are purple, all are diamond, different number, and different filters.

first = ['one', 'green', 'stripe', 'squiggle']
second = ['one', 'purple', 'solid', 'diamond']
third = ['two', 'green', 'empty', 'oval']

This is wrong because because two have the same number and one does not, similarly with the color.

This is the game of set that I want to achieve here

Please help thank you!

Body:
In this game, a __set is defined as:

Several games can be played with these cards, all involving the concept of a set. A set consists of three cards satisfying all of these conditions:

They all have the same number or have three different numbers.

They all have the same shape or have three different shapes.

They all have the same shading or have three different shadings.

They all have the same color or have three different colors.

-- Wikipedia

That can be checked with a one-liner:

first = ['two', 'purple', 'stripe', 'diamond']
second = ['one', 'purple', 'solid', 'diamond']
third = ['three', 'purple', 'empty', 'diamond']
first.zip(second, third).all? { |array| [1,3].include?(array.uniq.length) }
#=> true

first = ['one', 'green', 'stripe', 'squiggle']
second = ['one', 'purple', 'solid', 'diamond']
third = ['two', 'green', 'empty', 'oval']
first.zip(second, third).all? { |array| [1,3].include?(array.uniq.length) }
#=> false

How does this work in detail?

first
  .zip(second, third) #=> [["two", "one", "three"], ["purple", "purple", "purple"], ["stripe", "solid", "empty"], ["diamond", "diamond", "diamond"]]
  .all? { |array|
     # do all nested arrays comply with the set conditions and
     # contain only the same element or three different ones?
    [1,3].include?(array.uniq.length)
  }


问:
CircleCI-Slack integration formatting is not working as it used to be
After an upgrade to slack api, the formatting of circle-ci messages into slack channels is not working properly. I am trying to see what i can do in the config.yaml file to add some colour to it, i am a novice so thought this would be a small task i could take on from the dev team, but I've hit a roadblock

Is there a better way to format this

```<code>  "elements": [
                                  {
                                      "type": "button",
                                      "text": {
                                          "type": "plain_text",
                                          "text": "View Job"
                                      },
                                      "url": "${CIRCLE_BUILD_URL}"
                                  }
                              ]
</code>```

Adding emoji: true doesn't really change anything, is there a way to change the formatting of the text and to print out better descriptive messages in a fail and a pas scenario?

答:
If you want to use emojis in your build, besides adding emoji: true you need to add the emojis at the text too. I'll share an example, feel free to edit it.

```<code>{
   "text":"CircleCI job succeeded!",
   "blocks":[
      {
         "type":"header",
         "text":{
            "type":"plain_text",
            "text":"Deployment Successful! :tada:",
            "emoji":true
         }
      },
      {
         "type":"section",
         "fields":[
            {
               "type":"mrkdwn",
               "text":"*Project*: $CIRCLE_PROJECT_REPONAME"
            },
            {
               "type":"mrkdwn",
               "text":"*When*: $(date +'%m/%d/%Y %T')"
            },
            {
               "type":"mrkdwn",
               "text":"*Tag*: $CIRCLE_TAG"
            }
         ],
         "accessory":{
            "type":"image",
            "image_url":"https://assets.brandfolder.com/otz5mn-bw4j2w-6jzqo8/original/circle-logo-badge-black.png",
            "alt_text":"CircleCI logo"
         }
      },
      {
         "type":"actions",
         "elements":[
            {
               "type":"button",
               "text":{
                  "type":"plain_text",
                  "text":"View Job"
               },
               "url":"${CIRCLE_BUILD_URL}"
            }
         ]
      }
   ]
}
</code>```

See the first text block, there is a :tada emoji, also the message is separated into blocks, see the screenshot of this config:

Body:
After an upgrade to slack api, the formatting of circle-ci messages into slack channels is not working properly. I am trying to see what i can do in the config.yaml file to add some colour to it, i am a novice so thought this would be a small task i could take on from the dev team, but I've hit a roadblock

Is there a better way to format this

  "elements": [
                                  {
                                      "type": "button",
                                      "text": {
                                          "type": "plain_text",
                                          "text": "View Job"
                                      },
                                      "url": "${CIRCLE_BUILD_URL}"
                                  }
                              ]

Adding emoji: true doesn't really change anything, is there a way to change the formatting of the text and to print out better descriptive messages in a fail and a pas scenario?

Body:
If you want to use emojis in your build, besides adding emoji: true you need to add the emojis at the text too. I'll share an example, feel free to edit it.

{
   "text":"CircleCI job succeeded!",
   "blocks":[
      {
         "type":"header",
         "text":{
            "type":"plain_text",
            "text":"Deployment Successful! :tada:",
            "emoji":true
         }
      },
      {
         "type":"section",
         "fields":[
            {
               "type":"mrkdwn",
               "text":"*Project*: $CIRCLE_PROJECT_REPONAME"
            },
            {
               "type":"mrkdwn",
               "text":"*When*: $(date +'%m/%d/%Y %T')"
            },
            {
               "type":"mrkdwn",
               "text":"*Tag*: $CIRCLE_TAG"
            }
         ],
         "accessory":{
            "type":"image",
            "image_url":"https://assets.brandfolder.com/otz5mn-bw4j2w-6jzqo8/original/circle-logo-badge-black.png",
            "alt_text":"CircleCI logo"
         }
      },
      {
         "type":"actions",
         "elements":[
            {
               "type":"button",
               "text":{
                  "type":"plain_text",
                  "text":"View Job"
               },
               "url":"${CIRCLE_BUILD_URL}"
            }
         ]
      }
   ]
}

See the first text block, there is a :tada emoji, also the message is separated into blocks, see the screenshot of this config:


问:
Resolving the 'WinMain@16' Link Error for Console
I've been using the default template in Code::Blocks to create a DLL, but when I compile, I get the undefined reference to'WinMain@16' error.

I Googled out this error and it seems that the main() I'm using is for a Window application rather than console application but there's no clear solution to this problem.

Now, do I just replace this line

```<code>BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
</code>```

by this
int main()?

Also, I want to insist that whatever alternative causes the least security gap and/or is the most correct solution.

Thanks!

答:
I did encounter this same error sometime ago, just replacing some part of the code fixes it. I was using SDL in my program. This was the main function:

```<code>int main(int argc, char** argv)
</code>```

I relaced it with the windows main function:

```<code>int WinMain(int argc, char** argv)
</code>```

but it did end up with giving a warning for the same however the code runs.

Body:
I've been using the default template in Code::Blocks to create a DLL, but when I compile, I get the undefined reference to'WinMain@16' error.

I Googled out this error and it seems that the main() I'm using is for a Window application rather than console application but there's no clear solution to this problem.

Now, do I just replace this line

BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)

by this
int main()?

Also, I want to insist that whatever alternative causes the least security gap and/or is the most correct solution.

Thanks!

Body:
I did encounter this same error sometime ago, just replacing some part of the code fixes it. I was using SDL in my program. This was the main function:

int main(int argc, char** argv)

I relaced it with the windows main function:

int WinMain(int argc, char** argv)

but it did end up with giving a warning for the same however the code runs.


问:
Activity never becomes requested state "[DESTROYED, RESUMED, STARTED, CREATED]" (last lifecycle transition = "PRE_ON_CREATE")
This is not a duplicate question.

I have already looked at similar questions. I have added the questions I have referred to at the last.

My problem is that the test executes, but I have to open the app manually for every test.

You can see that I had been waiting for 18 seconds before opening the app. It waits till I open the app manually or it shows this error after a timeout.

Activity never becomes requested state "[DESTROYED, RESUMED, STARTED, CREATED]" (last lifecycle transition = "PRE_ON_CREATE")

From this post, I assume the issue is with the device as I am using Redmi Note 5.

I have disabled animations as well as the MIUI optimization option.

Any help is appreciated to run the tests on Xiaomi devices automatically.

No point in running automated UI tests manually.

Update 1

It executes only for launcher / main activity.

It is not working for other activities.

Update 2

I also happen to have a Redmi 4. The tests work on that device as expected without any code changes.

Referred SO questions

AndroidX.Test ActivityScenario: java.lang.AssertionError: Activity never becomes requested state "[RESUMED]" (last lifecycle transition = "STOPPED")

Android device doesn't launch activities on the screen while espresso testing

Activity never becomes requested state in UI Testing

java.lang.AssertionError: Activity never becomes requested state

Android instrumented test throws exception: Activity never becomes requested state "[RESUMED, DESTROYED, STARTED, CREATED]"

How do I fix this error java.lang.AssertionError: Activity never becomes requested state "[DESTROYED]" (last lifecycle transition = "RESUMED")

And related issues,

https://github.com/android/android-test/issues/143

https://github.com/android/android-test/issues/496

Adding code snippets and dependencies for anyone who wants to have a look,

Test code

```<code>import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4ClassRunner::class)
class MainActivityTest {
    @Test
    fun test_isActivityInView() {
        val activityScenario = ActivityScenario.launch(MainActivity::class.java)
        onView(withId(R.id.layout_activity_main)).check(matches(isDisplayed()))
    }
}
</code>```

Dependencies

```<code>testImplementation "junit:junit:4.13.2"
androidTestImplementation "androidx.test:core:1.4.0"
androidTestImplementation "androidx.test:runner:1.4.0"
androidTestImplementation "androidx.test:rules:1.4.0"
androidTestImplementation "androidx.test.ext:junit-ktx:1.1.3"
androidTestImplementation "androidx.test.espresso:espresso-core:3.4.0"
</code>```

答:
I was getting following error on my Android 11 device

java.lang.AssertionError: Activity never becomes requested state "[STARTED, RESUMED, CREATED, DESTROYED]" (last lifecycle transition = "PRE_ON_CREATE")

I wasted a good amount of time on it and found the solution when I switched my device to Android 10.

If anybody facing such issue, please do following things to resolve it,

Enable autostart in app setting

Grant the permission to "Display pop_up windows while running in the background" from app permission settings

Body:
This is not a duplicate question.

I have already looked at similar questions. I have added the questions I have referred to at the last.

My problem is that the test executes, but I have to open the app manually for every test.

You can see that I had been waiting for 18 seconds before opening the app. It waits till I open the app manually or it shows this error after a timeout.

Activity never becomes requested state "[DESTROYED, RESUMED, STARTED, CREATED]" (last lifecycle transition = "PRE_ON_CREATE")

From this post, I assume the issue is with the device as I am using Redmi Note 5.

I have disabled animations as well as the MIUI optimization option.

Any help is appreciated to run the tests on Xiaomi devices automatically.

No point in running automated UI tests manually.

Update 1

It executes only for launcher / main activity.

It is not working for other activities.

Update 2

I also happen to have a Redmi 4. The tests work on that device as expected without any code changes.

Referred SO questions

AndroidX.Test ActivityScenario: java.lang.AssertionError: Activity never becomes requested state "[RESUMED]" (last lifecycle transition = "STOPPED")

Android device doesn't launch activities on the screen while espresso testing

Activity never becomes requested state in UI Testing

java.lang.AssertionError: Activity never becomes requested state

Android instrumented test throws exception: Activity never becomes requested state "[RESUMED, DESTROYED, STARTED, CREATED]"

How do I fix this error java.lang.AssertionError: Activity never becomes requested state "[DESTROYED]" (last lifecycle transition = "RESUMED")

And related issues,

https://github.com/android/android-test/issues/143

https://github.com/android/android-test/issues/496

Adding code snippets and dependencies for anyone who wants to have a look,

Test code

import androidx.test.core.app.ActivityScenario
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4ClassRunner::class)
class MainActivityTest {
    @Test
    fun test_isActivityInView() {
        val activityScenario = ActivityScenario.launch(MainActivity::class.java)
        onView(withId(R.id.layout_activity_main)).check(matches(isDisplayed()))
    }
}

Dependencies

testImplementation "junit:junit:4.13.2"
androidTestImplementation "androidx.test:core:1.4.0"
androidTestImplementation "androidx.test:runner:1.4.0"
androidTestImplementation "androidx.test:rules:1.4.0"
androidTestImplementation "androidx.test.ext:junit-ktx:1.1.3"
androidTestImplementation "androidx.test.espresso:espresso-core:3.4.0"


问:
Cannot deserialize instance of `org.json.JSONObject`
I have a basic SpringBoot 2.1.5.RELEASE app. Using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file with some RestControllers.

In 1 of the controller this is the body I send:

```<code>{
    "depositHotel": "xxx",
    "destinationHotel": "aaa",
    "depositHotelAmount": "0.2",
    "destinationHotelAmount": "4",
    "destinationAddress": [{
        "address": "asdf",
        "tag": ""
    }],
    "refundAddress": [{
        "address": "pio",
        "tag": ""
    }]
}
</code>```

so I create this class to use it as a RequestBody:

```<code>public class HotelswitchHotelOrderRequestBody {

    public static class Builder {

        private String depositHotel;
        private String destinationHotel;
        private Float depositHotelAmount;
        private Float destinationHotelAmount;
        private JSONObject destinationAddress;
        private JSONObject refundAddress;

        public Builder(String depositHotel, String destinationHotel) {
            this.depositHotel = depositHotel;
            this.destinationHotel = destinationHotel;
        }

        public Builder withDepositHotelAmount (Float depositHotelAmount) {
            this.depositHotelAmount = depositHotelAmount;
            return this;
        }

        public Builder withDestinationHotelAmount (Float destinationHotelAmount) {
            this.destinationHotelAmount = destinationHotelAmount;
            return this;
        }

        public Builder toDestinationAddress (JSONObject destinationAddress) {
            this.destinationAddress = destinationAddress;
            return this;
        }

        public Builder toRefundAddress (JSONObject refundAddress) {
            this.refundAddress = refundAddress;
            return this;
        }

        public HotelswitchHotelOrderRequestBody build(){

            HotelswitchHotelOrderRequestBody order = new HotelswitchHotelOrderRequestBody();
            order.depositHotel = this.depositHotel;
            order.depositHotelAmount = this.depositHotelAmount;
            order.destinationAddress = this.destinationAddress;
            order.destinationHotel = this.destinationHotel;
            order.destinationHotelAmount = this.destinationHotelAmount;
            order.refundAddress = this.refundAddress;

            return order;

        }
    }

    private String depositHotel;
    private String destinationHotel;
    private Float depositHotelAmount;
    private Float destinationHotelAmount;
    private JSONObject destinationAddress;
    private JSONObject refundAddress;

    private HotelswitchHotelOrderRequestBody () {
        //Constructor is now private.
    }

    public String getDepositHotel() {
        return depositHotel;
    }

    public void setDepositHotel(String depositHotel) {
        this.depositHotel = depositHotel;
    }

    public String getDestinationHotel() {
        return destinationHotel;
    }

    public void setDestinationHotel(String destinationHotel) {
        this.destinationHotel = destinationHotel;
    }

    public Float getDepositHotelAmount() {
        return depositHotelAmount;
    }

    public void setDepositHotelAmount(Float depositHotelAmount) {
        this.depositHotelAmount = depositHotelAmount;
    }

    public Float getDestinationHotelAmount() {
        return destinationHotelAmount;
    }

    public void setDestinationHotelAmount(Float destinationHotelAmount) {
        this.destinationHotelAmount = destinationHotelAmount;
    }

    public JSONObject getDestinationAddress() {
        return destinationAddress;
    }

    public void setDestinationAddress(JSONObject destinationAddress) {
        this.destinationAddress = destinationAddress;
    }

    public JSONObject getRefundAddress() {
        return refundAddress;
    }

    public void setRefundAddress(JSONObject refundAddress) {
        this.refundAddress = refundAddress;
    }

}
</code>```

But I have this error when receiving the object:

```<code>JSON parse error:  out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `org.json.JSONObject` out of START_ARRAY token
</code>```

答: I had a similar usecase , where I could not define the json to a POJO. Using com.fasterxml.jackson.databind.JsonNode instead of the JSONObject worked.

Body:
I have a basic SpringBoot 2.1.5.RELEASE app. Using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file with some RestControllers.

In 1 of the controller this is the body I send:

{
    "depositHotel": "xxx",
    "destinationHotel": "aaa",
    "depositHotelAmount": "0.2",
    "destinationHotelAmount": "4",
    "destinationAddress": [{
        "address": "asdf",
        "tag": ""
    }],
    "refundAddress": [{
        "address": "pio",
        "tag": ""
    }]
}

so I create this class to use it as a RequestBody:

public class HotelswitchHotelOrderRequestBody {

    public static class Builder {

        private String depositHotel;
        private String destinationHotel;
        private Float depositHotelAmount;
        private Float destinationHotelAmount;
        private JSONObject destinationAddress;
        private JSONObject refundAddress;

        public Builder(String depositHotel, String destinationHotel) {
            this.depositHotel = depositHotel;
            this.destinationHotel = destinationHotel;
        }

        public Builder withDepositHotelAmount (Float depositHotelAmount) {
            this.depositHotelAmount = depositHotelAmount;
            return this;
        }

        public Builder withDestinationHotelAmount (Float destinationHotelAmount) {
            this.destinationHotelAmount = destinationHotelAmount;
            return this;
        }

        public Builder toDestinationAddress (JSONObject destinationAddress) {
            this.destinationAddress = destinationAddress;
            return this;
        }

        public Builder toRefundAddress (JSONObject refundAddress) {
            this.refundAddress = refundAddress;
            return this;
        }

        public HotelswitchHotelOrderRequestBody build(){

            HotelswitchHotelOrderRequestBody order = new HotelswitchHotelOrderRequestBody();
            order.depositHotel = this.depositHotel;
            order.depositHotelAmount = this.depositHotelAmount;
            order.destinationAddress = this.destinationAddress;
            order.destinationHotel = this.destinationHotel;
            order.destinationHotelAmount = this.destinationHotelAmount;
            order.refundAddress = this.refundAddress;

            return order;

        }
    }

    private String depositHotel;
    private String destinationHotel;
    private Float depositHotelAmount;
    private Float destinationHotelAmount;
    private JSONObject destinationAddress;
    private JSONObject refundAddress;

    private HotelswitchHotelOrderRequestBody () {
        //Constructor is now private.
    }

    public String getDepositHotel() {
        return depositHotel;
    }

    public void setDepositHotel(String depositHotel) {
        this.depositHotel = depositHotel;
    }

    public String getDestinationHotel() {
        return destinationHotel;
    }

    public void setDestinationHotel(String destinationHotel) {
        this.destinationHotel = destinationHotel;
    }

    public Float getDepositHotelAmount() {
        return depositHotelAmount;
    }

    public void setDepositHotelAmount(Float depositHotelAmount) {
        this.depositHotelAmount = depositHotelAmount;
    }

    public Float getDestinationHotelAmount() {
        return destinationHotelAmount;
    }

    public void setDestinationHotelAmount(Float destinationHotelAmount) {
        this.destinationHotelAmount = destinationHotelAmount;
    }

    public JSONObject getDestinationAddress() {
        return destinationAddress;
    }

    public void setDestinationAddress(JSONObject destinationAddress) {
        this.destinationAddress = destinationAddress;
    }

    public JSONObject getRefundAddress() {
        return refundAddress;
    }

    public void setRefundAddress(JSONObject refundAddress) {
        this.refundAddress = refundAddress;
    }

}

But I have this error when receiving the object:

JSON parse error:  out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `org.json.JSONObject` out of START_ARRAY token


问:
TypeError: data.map is not a function i am getting an error while api call and an error called id is not defined
i want to navigate to other page while clicking on the button and while clicking the button i also have to call an api.but its not working can anyone tell me whats the problem
[its the api link] [1]: https://api.tvmaze.com/shows/$%7Bid%7D its my contact component</p>
```<code>import React,{useState,useEffect} from 'react';
import axios from 'axios';

export const Contact = () => {
  const url = `https://api.tvmaze.com/shows/${id}`;

  const [data, setData] = useState([]);

  useEffect(() => {
    axios.get(url).then((json) => setData(json.data));
  }, []);

  const renderTable = () => {
    return data.map((user, i) => {
     return (
     <tr key={i}>
      <td>{user.show?.name}</td>
      <td>{user.show?.language}</td>
      <td>{user.show?.genres}</td>
      <td>{user.show?.runtime}</td>
      <td>{user.show?.premiered}</td>
      <td>{user.show?.rating?.average}</td>
      <td>{user.show?.network?.country?.name}</td>
      <td>
        <img src={user?.show?.image?.medium} alt="poster" />
      </td>
    </tr>
      );
    });
  };

  return (
    <div>
      <table className=" table table-bordered">
        <thead>
          <tr>
            <th scope="col">Name</th>
            <th scope="col">language</th>
            <th scope="col">genres</th>
            <th scope="col">runtime</th>
            <th scope="col">premiered</th>
            <th scope="col">Rating</th>
            <th scope="col">country name</th>
            <th scope="col">image</th>
          </tr>
        </thead>
        <tbody>{renderTable()}</tbody>
      </table>
    </div>
  );
};
</code>```

答:
Here You can use this , No Error will occured</p>
```<code>  const renderTable = () => {
   return data && data.length > 0 &&  data.map((user, i) => {
    return (
    <tr key={i}>
     <td>{user.show?.name}</td>
     <td>{user.show?.language}</td>
     <td>{user.show?.genres}</td>
     <td>{user.show?.runtime}</td>
     <td>{user.show?.premiered}</td>
     <td>{user.show?.rating?.average}</td>
     <td>{user.show?.network?.country?.name}</td>
     <td>
      <img src={user?.show?.image?.medium} alt="poster" />
    </td>
 </tr>
   );
 });
};
</code>```

Body:
i want to navigate to other page while clicking on the button and while clicking the button i also have to call an api.but its not working can anyone tell me whats the problem
[its the api link] [1]: https://api.tvmaze.com/shows/$%7Bid%7D its my contact component

import React,{useState,useEffect} from 'react';
import axios from 'axios';

export const Contact = () => {
  const url = `https://api.tvmaze.com/shows/${id}`;

  const [data, setData] = useState([]);

  useEffect(() => {
    axios.get(url).then((json) => setData(json.data));
  }, []);

  const renderTable = () => {
    return data.map((user, i) => {
     return (

      {user.show?.name}
      {user.show?.language}
      {user.show?.genres}
      {user.show?.runtime}
      {user.show?.premiered}
      {user.show?.rating?.average}
      {user.show?.network?.country?.name}

      );
    });
  };

  return (

            Name
            language
            genres
            runtime
            premiered
            Rating
            country name
            image

{renderTable()}

  );
};

Body:
Here You can use this , No Error will occured

  const renderTable = () => {
   return data && data.length > 0 &&  data.map((user, i) => {
    return (
    <tr key={i}>
     <td>{user.show?.name}</td>
     <td>{user.show?.language}</td>
     <td>{user.show?.genres}</td>
     <td>{user.show?.runtime}</td>
     <td>{user.show?.premiered}</td>
     <td>{user.show?.rating?.average}</td>
     <td>{user.show?.network?.country?.name}</td>
     <td>
      <img src={user?.show?.image?.medium} alt="poster" />
    </td>
 </tr>
   );
 });
};


问:
JavaScript doesn't work as expected in Thymeleaf and Spring Boot
JavaScript doesn't work in thymeleaf.

In Spring Boot Thymeleaf, first thing can open modal. But second, third ... things can not open modal.

Every thing has className, but only first thing can open modal.

I think JavaScript works only the first thing, and doesn't work other things.

```<code><tr th:each="board, i : ${boards}">
                        <th scope="row" th:text="${i.count}">1</th>
                        <td>
                            <p class="show" th:text="${board.title}">Title</p>
                            <div class="modal"> .... </modal>
                        </td>
                        <td th:text="${board.writer}">Son</td>
                        <td th:text="${board.createDate}">2022-02-01</td></p>
</tr>
</code>```

js

```<code>function show() {
    document.querySelector(".background").className = "background show";
}

function close() {
    document.querySelector(".background").className = "background";
}

document.querySelector(".show").addEventListener("click", show);
document.querySelector(".close").addEventListener("click", close);
</code>```

please help me

答:
With your code you are only adding event listener to the first element of the class ".show". You should be adding event listeners to all members of the class. The following code should do the work:

```<code>document.querySelectorAll('.show').forEach(item => {
  item.addEventListener('click', show);
})
</code>```

Body:
JavaScript doesn't work in thymeleaf.

In Spring Boot Thymeleaf, first thing can open modal. But second, third ... things can not open modal.

Every thing has className, but only first thing can open modal.

I think JavaScript works only the first thing, and doesn't work other things.

                        1

Title

 .... </modal>

                        Son
                        2022-02-01

js

function show() {
    document.querySelector(".background").className = "background show";
}

function close() {
    document.querySelector(".background").className = "background";
}

document.querySelector(".show").addEventListener("click", show);
document.querySelector(".close").addEventListener("click", close);

please help me

Body:
With your code you are only adding event listener to the first element of the class ".show". You should be adding event listeners to all members of the class. The following code should do the work:

document.querySelectorAll('.show').forEach(item => {
  item.addEventListener('click', show);
})


问:
Configuration of GitHub Actions: Avoid running CI twice when merging PR into main
I am using GitHub a
ctions to manage my CI and the following events trigger my workflow:

on:
  pull_request:
    branches: main
  push:
    branches: main
```

I observed the following "problem":
When I create a PR, the CI is run. If the test passes and I merge it into main, the tests are run again (which I don'
t want in specific cases). How can I setup my workflow such that the CI is not triggered when merging a PR, where the CI already passed for the PR?

Thanks in advance!

答:
You might consider an if conditional in your case:

jobs.<job_id>.if

You can use the jobs.<job_id>.if conditional to prevent a job from running unless a condition is met. You can use any supported context and expression to create a conditional.

When you use expressions in an if conditional, you may omit the expression syntax (${{ }}) because GitHub automatically evaluates the if conditional as an expression. For more information, see "Expressions".

jobs:
  build:
    if: github.event.pull_request.merged == false
    . . .
```

That would still trigger the workflow, but it can skip the jobs in the workflow.

Alternatives exist in this thread, which deals with the opposite requirements ("Trigger workflow only on pull request merge"): it can be adapted to do what you need (not trigger a workflow, or at least do the same job twice, on PR merge)

Body:
I am using GitHub a
ctions to manage my CI and the following events trigger my workflow:

on:
  pull_request:
    branches: main
  push:
    branches: main

I observed the following "problem":
When I create a PR, the CI is run. If the test passes and I merge it into main, the tests are run again (which I don'
t want in specific cases). How can I setup my workflow such that the CI is not triggered when merging a PR, where the CI already passed for the PR?

Thanks in advance!

Body:
You might consider an if conditional in your case:

jobs.<job_id>.if

You can use the jobs.<job_id>.if conditional to prevent a job from running unless a condition is met. You can use any supported context and expression to create a conditional.

When you use expressions in an if conditional, you may omit the expression syntax (${{ }}) because GitHub automatically evaluates the if conditional as an expression. For more information, see "Expressions".

jobs:
  build:
    if: github.event.pull_request.merged == false
    . . .

That would still trigger the workflow, but it can skip the jobs in the workflow.

Alternatives exist in this thread, which deals with the opposite requirements ("Trigger workflow only on pull request merge"): it can be adapted to do what you need (not trigger a workflow, or at least do the same job twice, on PR merge)


问:
cv::dnn::Net forward function is very slow for YOLO object detection
this->net.forward(outs, getOutputsNames(this->net));
The forward function of cv::dnn::net is very slow. Is there any way to optimize it? I am using it for object detection through YOLO v3. It takes around 2 seconds per image.</p>
```<code>void ObjectDetector::runInference(cv::Mat& frame, std::string item, std::string output_path, std::string imagename)
{

    cv::Mat blob;
    cv::dnn::blobFromImage(frame, blob, 1/255.0, cv::Size(416, 416), cv::Scalar(0,0,0), true, false);

    //Sets the input to the network
    this->net.setInput(blob);

    // Runs the forward pass to get output of the output layers
    std::vector<cv::Mat> outs;

       clock_t start, end;

    /* Recording the starting clock tick.*/
    start = clock();

    /* below code is very slow */
    this->net.forward(outs, getOutputsNames(this->net));
    /* above code is very slow */

    end = clock();
    double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
    std::cout << "Time taken for getOutputnames is : " << std::fixed
         << time_taken << std::setprecision(5);
    std::cout << " sec " << std::endl;

    postprocess(frame, outs, item, output_path, imagename);
}

</code>```

答:
It seems you are running your code via on CPU backend. Since you are running a huge weight files, its normal to get lower fps in today's CPUs. Actually there are 2 ways you can increase your speed:

This solution comes with a trade-off. You get speed but lose
accuracy. This solution is decreasing width of network's input
image. Your current values are (416,416) you may decrease these
2 values and you will speed up your fps. However, your accuracy will
get down.

The cleanest solution is using GPU. If you have a gpu
hardware(CUDA capable), then you can change the network backend
to GPU and you will get speed with the same accuracy.

Body:
this->net.forward(outs, getOutputsNames(this->net));
The forward function of cv::dnn::net is very slow. Is there any way to optimize it? I am using it for object detection through YOLO v3. It takes around 2 seconds per image.

void ObjectDetector::runInference(cv::Mat& frame, std::string item, std::string output_path, std::string imagename)
{

    cv::Mat blob;
    cv::dnn::blobFromImage(frame, blob, 1/255.0, cv::Size(416, 416), cv::Scalar(0,0,0), true, false);

    //Sets the input to the network
    this->net.setInput(blob);

    // Runs the forward pass to get output of the output layers
    std::vector<cv::Mat> outs;

       clock_t start, end;

    /* Recording the starting clock tick.*/
    start = clock();

    /* below code is very slow */
    this->net.forward(outs, getOutputsNames(this->net));
    /* above code is very slow */

    end = clock();
    double time_taken = double(end - start) / double(CLOCKS_PER_SEC);
    std::cout << "Time taken for getOutputnames is : " << std::fixed
         << time_taken << std::setprecision(5);
    std::cout << " sec " << std::endl;

    postprocess(frame, outs, item, output_path, imagename);
}


问:
Django: substitute unique_together with UniqueConstraint
I am trying to enforce a constraint upon a Vote model in my Django application, namely that a user cannot vote more than once the same object.

To do so I am using unique_together:

```<code>class Vote(models.Model):
    vote = models.SmallIntegerField(choices=VOTES, null=True, blank=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE,
        related_name="user_votes")
    definition = models.ForeignKey(Definition, on_delete=models.CASCADE,
        related_name="definition_votes")

    class Meta:
        # Ensure user cannot vote more than once.
        unique_together = ["user", "definition"]
</code>```

This works, I think.

However, in Django's documentation for unique_together it is noted that

UniqueConstraint provides more functionality than
unique_together. unique_together may be deprecated in the future.

How can I substitute the above code using unique_together with code using UniqueConstraint?

答:
The biggest confusion is the UniqueConstraint documentation can be arrived at directly from unique_togther, but it skips the Metas.constraint documentation:

constraints

Options.constraints

A list of constraints that you want to define on the model:

```<code>from django.db import models

class Customer(models.Model):
    age = models.IntegerField()

    class Meta:
        constraints = [
            models.CheckConstraint(check=models.Q(age__gte=18), name='age_gte_18'),
        ]
</code>```

The sample code quickly tells you how to use the constraints.

Body:
I am trying to enforce a constraint upon a Vote model in my Django application, namely that a user cannot vote more than once the same object.

To do so I am using unique_together:

class Vote(models.Model):
    vote = models.SmallIntegerField(choices=VOTES, null=True, blank=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE,
        related_name="user_votes")
    definition = models.ForeignKey(Definition, on_delete=models.CASCADE,
        related_name="definition_votes")

    class Meta:
        # Ensure user cannot vote more than once.
        unique_together = ["user", "definition"]

This works, I think.

However, in Django's documentation for unique_together it is noted that

UniqueConstraint provides more functionality than
unique_together. unique_together may be deprecated in the future.

How can I substitute the above code using unique_together with code using UniqueConstraint?

Body:
The biggest confusion is the UniqueConstraint documentation can be arrived at directly from unique_togther, but it skips the Metas.constraint documentation:

constraints

Options.constraints

A list of constraints that you want to define on the model:

from django.db import models

class Customer(models.Model):
    age = models.IntegerField()

    class Meta:
        constraints = [
            models.CheckConstraint(check=models.Q(age__gte=18), name='age_gte_18'),
        ]

The sample code quickly tells you how to use the constraints.