Title: How do I change the shape of the lines in a plot generated by a for loop?

Body:
I'm not sure how to change the shape and color of the for loop for data in a df, fish

structure(list(Region = structure(c(7L, 7L, 7L, 7L, 7L), .Label = c("American Samoa",
"Johnston Atoll", "Line Islands", "MHI", "Musicians Seamounts",
"Northern Marianas", "NWHI", "Southern Marianas", "Tokelau Ridge",
"Wake Island"), class = "factor"), ObservationYear = c(2015,
2015, 2015, 2015, 2015), `Mega-Habitat` = c("bank", "bank", "tablemount",
"bank", "atoll"), Total_fish = c(6, 10, 21, 11, 7), Lat = c(23.2227305,
25.0840027, 26.8267143809524, 26.8188378, 27.5178584285714),
    Long = c(-163.516748333333, -172.490419, -175.607307619048,
    -176.315991, -175.460592857143), Temperature = c(1.82256666666667,
    2.00518, 3.03555714285714, 2.01533, 1.5475), Salinity = c(34.64115,
    34.61702, 34.4760619047619, 34.61106, 34.6673857142857),
    Oxygen = c(3.16008333333333, 2.79735, 1.27077619047619, 2.58692,
    3.73167142857143), Distance = c(350, 960, 1130, 360, 460),
    `CTD Availability` = c(NA_character_, NA_character_, NA_character_,
    NA_character_, NA_character_), depth_bin = c("2000-3000",
    "1000-2000", "1000-2000", "1000-2000", "2000-3000"), EventID = c("D2-EX1504L2-01",
    "D2-EX1504L2-06", "D2-EX1504L2-08", "D2-EX1504L2-10", "D2-EX1504L2-12"
    ), Average_Depth = c(2160.20383333333, 1880.4596, 1217.94385,
    1890.1868, 2780.92557142857), POC_Flux = c(2.56732258067581,
    2.86961424536357, 3.38129564627503, 3.38129564627503, 3.80216410589398
    )), row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"
))

I ran a GAM before the loop:

g1 = mgcv::gam(Total_fish ~ s(Average_Depth, by = Region) + Region + offset(log(Distance)), data =fish,family= nb)

I tried defining shapes, but it did not work

shapes= c(0,1,2,3,4,5,6,7,8,9,10)
shapes <-shapes[as.numeric(fish$Region)]

colors.use = rainbow(nlevels(fish$Region))

for (i in 1:nlevels(fish$Region)) {
  predictions = predict(g1, type="response", newdata = data.frame(Distance= 1000, Average_Depth = seq(0,3000,length=1000), Region = levels(fish$Region)[i]))
  if (i == 1) plot(xlab= "Depth (m)", ylab = "fish/1000 m",seq(0,3000,length=1000), predictions, type = 'l', col=colors.use[i], pch=i)
if (i > 1) lines(seq(0,3000,length=1000), predictions,col=colors.use[i],pch=i)
}

I just need to be able to differentiate between the regions and the current rainbow colors alone are not very useful for that


来源: stackexchange

问:
Spring Data @lock(lockmodetype.pessimistic_write) not working as well
I am using Spring Boot and Oracle Database with Spring Data ORM,
when I use bellow code

```<code>@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT c FROM Customer c WHERE c.orgId = ?1")
public List<Customer> fetchCustomersByOrgId(Long orgId);
</code>```

I expect that another transaction can not select this record but when I run my Application the result is not in my expect, so first transaction1 select customer and wait for update and transaction2 can select customer before completing transation1 and this is my problem because I expect transaction2 wait for finishing transaction1 and after that can select customer.
If you have a solution for this problem please let me know, Thanks

ContentLicense: CC BY-SA 4.0

Body:
I am using Spring Boot and Oracle Database with Spring Data ORM,
when I use bellow code

@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT c FROM Customer c WHERE c.orgId = ?1")
public List<Customer> fetchCustomersByOrgId(Long orgId);

I expect that another transaction can not select this record but when I run my Application the result is not in my expect, so first transaction1 select customer and wait for update and transaction2 can select customer before completing transation1 and this is my problem because I expect transaction2 wait for finishing transaction1 and after that can select customer.
If you have a solution for this problem please let me know, Thanks


问:
Pip is not able to install any package due to Openssl
Whenever I try to install anything using pip I get an error as follows. I tried uninstalling and reinstalling OpenSSL and it didn't work. Any idea what could be causing it? It used to work flawlessly before and then out of the sudden when I try to install any package using pip or pip 3 it throw this error.</p>
```<code>File "/home/jan/.local/lib/python3.8/site-packages/OpenSSL/SSL.py", line 19, in <module>
    from OpenSSL.crypto import (
  File "/home/jan/.local/lib/python3.8/site-packages/OpenSSL/crypto.py", line 3224, in <module>
    utils.deprecated(
TypeError: deprecated() got an unexpected keyword argument 'name'
</code>```

Body:
Whenever I try to install anything using pip I get an error as follows. I tried uninstalling and reinstalling OpenSSL and it didn't work. Any idea what could be causing it? It used to work flawlessly before and then out of the sudden when I try to install any package using pip or pip 3 it throw this error.

File "/home/jan/.local/lib/python3.8/site-packages/OpenSSL/SSL.py", line 19, in <module>
    from OpenSSL.crypto import (
  File "/home/jan/.local/lib/python3.8/site-packages/OpenSSL/crypto.py", line 3224, in <module>
    utils.deprecated(
TypeError: deprecated() got an unexpected keyword argument 'name'


问:
Export to excel with pagination in Tableau
I have created pagination report in excel with 100 records in single page. There are 4 to 5 filters to apply for users. When I export data to excel it only download 100 records. what I can do for downloading all records after applying filters?

what I can do for downloading all records after applying filters?


问:
SwiftUI animation causes app to crash with AsyncRenderer
I have an animation to represent vibrations, this can play for several minutes. After 2-3 minutes, the app spikes from 30-100% + in CPU before crashing. Here is the animation:

```<code>ZStack {
ForEach(1..<10, id: \.self) { num in
   Circle()
      .stroke(Color.accentColor, lineWidth: CGFloat(num))
      .scaleEffect(patternManager.animate ? 1.0 : (0.1 * Double(num)))
      .mask {
         RadialGradient(colors: [.black, .clear],
                        center: .center,
                        startRadius: 0.0,
                        endRadius: size.width / 1.8)
      }
   }
   .frame(width: size.width, height: size.width)
   .opacity(patternManager.isVibrating ? 1.0 : 0.0)
   .animation(.linear(duration: 0.5).repeatForever(autoreverses: false),
                       value: patternManager.animate)
}

</code>```

Here is what I am getting back:

com.apple.SwiftUI.AsyncRenderer (40): EXC_BAD_ACCESS (code=2, address=0x16bc9fff0)

SwiftUI: closure #1 in KitRendererCommon(_:) + 168

Basically, every 0.1 seconds the patternManager.animate is toggled. The issue seems to be purely in the animation as remove the .scaleEffect() line will prevent any issues.

Why would this cause the app to crash?

Body:
I have an animation to represent vibrations, this can play for several minutes. After 2-3 minutes, the app spikes from 30-100% + in CPU before crashing. Here is the animation:

ZStack {
ForEach(1..<10, id: \.self) { num in
   Circle()
      .stroke(Color.accentColor, lineWidth: CGFloat(num))
      .scaleEffect(patternManager.animate ? 1.0 : (0.1 * Double(num)))
      .mask {
         RadialGradient(colors: [.black, .clear],
                        center: .center,
                        startRadius: 0.0,
                        endRadius: size.width / 1.8)
      }
   }
   .frame(width: size.width, height: size.width)
   .opacity(patternManager.isVibrating ? 1.0 : 0.0)
   .animation(.linear(duration: 0.5).repeatForever(autoreverses: false),
                       value: patternManager.animate)
}

Here is what I am getting back:

com.apple.SwiftUI.AsyncRenderer (40): EXC_BAD_ACCESS (code=2, address=0x16bc9fff0)

SwiftUI: closure #1 in KitRendererCommon(_:) + 168

Basically, every 0.1 seconds the patternManager.animate is toggled. The issue seems to be purely in the animation as remove the .scaleEffect() line will prevent any issues.

Why would this cause the app to crash?


问:
PDF-Print cuts the page improperly
I have a website with information, and I want to add the ability to print it out. However as you can see in the screenshot, sometimes the page breaks are making it necessary to see the previous page, to see what's going on. Is there a way to make the element skip to the next page if it's right in the middle of a page break?

EDIT. The data can change, resulting in a different layout of the file.

Title: PDF-Print cuts the page improperly


问:
Samsung Knox to 365 Integration
How would I migrate the Samsung Knox connector (that is currently on DC4) and move that integration to use SAML direct with my 365 tenants?</p>

Title: Samsung Knox to 365 Integration


问:
How to create many tkinter buttons that can print their place value
I want to create 10 buttons using a loop which, when pressed, print their their value. The first button prints 0 and the last should print 9.

I found that running the code below, it creates the 10 buttons but when any of them are pressed, it outputs the number 9 only

`

```<code>from tkinter import *
import tkinter as tk

root = tk.Tk()
root.geometry("500x500")
def pressed(i):
    print(i)
for i in range(10):
    Button(root, command=lambda:pressed(i)).pack()

root.mainloop()

</code>```

`

I tried this. I expected for the first button to print 0, the second to print 1 and continue until the last prints 9.

What I got instead was that every button prints 9

Body:
I want to create 10 buttons using a loop which, when pressed, print their their value. The first button prints 0 and the last should print 9.

I found that running the code below, it creates the 10 buttons but when any of them are pressed, it outputs the number 9 only

`

from tkinter import *
import tkinter as tk

root = tk.Tk()
root.geometry("500x500")
def pressed(i):
    print(i)
for i in range(10):
    Button(root, command=lambda:pressed(i)).pack()

root.mainloop()

`

I tried this. I expected for the first button to print 0, the second to print 1 and continue until the last prints 9.

What I got instead was that every button prints 9


问:
Make part of expression optional in regex
I want to convert span elements into React Components. I would need a regex expression that treats the title property as optional. I tried it with (\s*?:title="*"?)</p>
```<code>Works for:

<span class="fa fa-ballot-check fs-12">

let newdata = data.replace(/<span (class|className)=["'][a-z_\-][\w\-\s]*["'](\s*>|\s*\/>)/g , (n)=>{

          return <Symbol/>
}

Does not work for:

<span class="fa fa-ballot-check fs-12" title="Click me here"></i>

let newdata = data.replace(/<span (class|className)=["'][a-z_\-][\w\-\s]*["'](\s*?:title="*"?)(\s*>|\s*\/>)/g , (n)=>{

          return <Symbol/>
}

```
</code>```

Body:
I want to convert span elements into React Components. I would need a regex expression that treats the title property as optional. I tried it with (\s*?:title="*"?)

Works for:

let newdata = data.replace(/|\s*\/>)/g , (n)=>{

          return <Symbol/>
}

Does not work for:

let newdata = data.replace(/|\s*\/>)/g , (n)=>{

          return <Symbol/>
}

```


问:
Bus error: 10 when using NSLog with DoraemonKit
I am using DoraemonKit for debugging purposes. My NSLOG calls catching by DoraemonKit. I am getting crash reports from some of my users and I couldn't figure it out.

Crash log:

```<code>0   libsystem_platform.dylib        0x00000001e1622e2c _platform_memset + 140
1   libsystem_malloc.dylib          0x00000001a75a34cc small_malloc_should_clear + 1352 (magazine_small.c:0)
2   libsystem_malloc.dylib          0x00000001a759fd38 szone_malloc_should_clear + 136 (magazine_malloc.c:238)
3   libsystem_malloc.dylib          0x00000001a75ae618 _malloc_zone_calloc + 88 (malloc.c:1546)
4   Foundation                      0x000000019946abf8 -[_NSJSONReader parseData:options:] + 544 (NSJSONSerialization.m:2279)
5   Foundation                      0x000000019946a900 +[NSJSONSerialization JSONObjectWithData:options:error:] + 76 (NSJSONSerialization.m:2459)
6   DoraemonKit                     0x000000010ba7ffa4 -[NSDictionary(DoraemonUnicodeReadable) descriptionWithLocale:indent:] + 1024
7   Foundation                      0x0000000199564640 _NS_os_log_callback + 288 (NSPlatform.m:187)
8   libsystem_trace.dylib           0x00000001ae4cf15c _os_log_fmt_flatten_NSCF + 64 (format.m:54)
9   libsystem_trace.dylib           0x00000001ae4ce908 _os_log_fmt_flatten_object + 216 (format.m:316)
10  libsystem_trace.dylib           0x00000001ae4db940 _os_log_impl_flatten_and_send + 1736 (format.c:799)
11  libsystem_trace.dylib           0x00000001ae4de524 _os_log_with_args_impl + 388 (log.c:2604)
12  CoreFoundation                  0x00000001981f39ec _CFLogvEx3 + 188 (CFUtilities.c:1224)
13  Foundation                      0x0000000199566b84 _NSLogv + 108 (NSPlatform.m:0)
14  Foundation                      0x0000000199566be0 NSLog + 56 (NSPlatform.m:1321)
15  MyApp                       0x0000000106a3b914 -[Manager handleReceivedData:] + 72 (Manager.m:119)
16  CoreFoundation                  0x000000019816d9a0 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 28 (CFNotificationCenter.c:706)
</code>```

My Code:

```<code>- (void)handleReceivedData:(NSNotification *)notify {
    NSDictionary *receivedDic = [notify userInfo];

    NSLog(@"receivedDicbt: %@",receivedDic);
</code>```

It is pretty basic, actually. I am catching an NSNotification and printing to NSLOG.
Then DoraemonKit catches it, as you can see in the stack trace.

I've inspected the DoraemonKit  and found the Frame 6's file; it is here:

https://github.com/didi/DoKit/blob/bf05430692e7b549f4b89d2abec877cd79dafaf4/iOS/DoraemonKit/Src/Core/Category/Foundation%2BDoraemon.m#L45

Exception Type:

```<code>Exception Type:  EXC_CRASH (SIGBUS)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Termination Signal: Bus error: 10
Termination Reason: Namespace SIGNAL, Code 0xa
</code>```

What can cause to this problem and how to resolve it?

Body:
I am using DoraemonKit for debugging purposes. My NSLOG calls catching by DoraemonKit. I am getting crash reports from some of my users and I couldn't figure it out.

Crash log:

0   libsystem_platform.dylib        0x00000001e1622e2c _platform_memset + 140
1   libsystem_malloc.dylib          0x00000001a75a34cc small_malloc_should_clear + 1352 (magazine_small.c:0)
2   libsystem_malloc.dylib          0x00000001a759fd38 szone_malloc_should_clear + 136 (magazine_malloc.c:238)
3   libsystem_malloc.dylib          0x00000001a75ae618 _malloc_zone_calloc + 88 (malloc.c:1546)
4   Foundation                      0x000000019946abf8 -[_NSJSONReader parseData:options:] + 544 (NSJSONSerialization.m:2279)
5   Foundation                      0x000000019946a900 +[NSJSONSerialization JSONObjectWithData:options:error:] + 76 (NSJSONSerialization.m:2459)
6   DoraemonKit                     0x000000010ba7ffa4 -[NSDictionary(DoraemonUnicodeReadable) descriptionWithLocale:indent:] + 1024
7   Foundation                      0x0000000199564640 _NS_os_log_callback + 288 (NSPlatform.m:187)
8   libsystem_trace.dylib           0x00000001ae4cf15c _os_log_fmt_flatten_NSCF + 64 (format.m:54)
9   libsystem_trace.dylib           0x00000001ae4ce908 _os_log_fmt_flatten_object + 216 (format.m:316)
10  libsystem_trace.dylib           0x00000001ae4db940 _os_log_impl_flatten_and_send + 1736 (format.c:799)
11  libsystem_trace.dylib           0x00000001ae4de524 _os_log_with_args_impl + 388 (log.c:2604)
12  CoreFoundation                  0x00000001981f39ec _CFLogvEx3 + 188 (CFUtilities.c:1224)
13  Foundation                      0x0000000199566b84 _NSLogv + 108 (NSPlatform.m:0)
14  Foundation                      0x0000000199566be0 NSLog + 56 (NSPlatform.m:1321)
15  MyApp                       0x0000000106a3b914 -[Manager handleReceivedData:] + 72 (Manager.m:119)
16  CoreFoundation                  0x000000019816d9a0 __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 28 (CFNotificationCenter.c:706)

My Code:

- (void)handleReceivedData:(NSNotification *)notify {
    NSDictionary *receivedDic = [notify userInfo];

    NSLog(@"receivedDicbt: %@",receivedDic);

It is pretty basic, actually. I am catching an NSNotification and printing to NSLOG.
Then DoraemonKit catches it, as you can see in the stack trace.

I've inspected the DoraemonKit  and found the Frame 6's file; it is here:

https://github.com/didi/DoKit/blob/bf05430692e7b549f4b89d2abec877cd79dafaf4/iOS/DoraemonKit/Src/Core/Category/Foundation%2BDoraemon.m#L45

Exception Type:

Exception Type:  EXC_CRASH (SIGBUS)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Termination Signal: Bus error: 10
Termination Reason: Namespace SIGNAL, Code 0xa

What can cause to this problem and how to resolve it?


问:
Sending email through microsoft 365 api with XOAuth2 authentication using springboot
I'm developing an API that need to send an email using Microsoft 365 account.
As I understand Microsoft will disable the username and password login soon so i need to authenticate with OAuth2.

I wrote the following code but I keep getting an authentication error saying that i need to enable the SmtpClientAuthentication which will be deprecated soon.

I'm not sure what i'm doing wrong in my code.
See the following classes:

my @Configurations class has :

```<code> @Value("${spring.mail.host}")
    private String host;
   /* @Value("${nati.mail.protocol}")
    private String protocol;*/
    @Value("${spring.mail.port}")
    private Integer port;
    @Value("${spring.mail.username}")
    private String username;

    @Value("${spring.mail.password}")
    private String password;
    @Value("${spring.mail.properties.mail.smtp.auth.xoauth2.client.id}")
    private String clientId;

    @Value("${spring.mail.properties.mail.smtp.auth.xoauth2.client.secret}")
    private String clientSecret;

    @Value("${spring.mail.properties.mail.smtp.auth.xoauth2.scope}")
    private String scope;

    @Value("${spring.mail.properties.mail.smtp.auth.xoauth2.authority}")
    private String authority;

    @Bean
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(this.host);
        sender.setPort(this.port);
        //sender.setUsername(this.username);

        Properties props = sender.getJavaMailProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.debug", "true");

        if (StringUtils.isNoneBlank(this.clientId, this.clientSecret, this.scope, this.authority)) {
            try {
                System.out.println("Authenticating with Microsoft Graph api ....");
                final StringBuilder passwordBuilder = new StringBuilder();
                passwordBuilder
                        .append("user=").append(this.username).append('\u0001')
                        .append("auth=").append("Bearer ").append(getToken()
                                .accessToken())
                        .append('\u0001').append('\u0001');
               // System.out.println("password: "+passwordBuilder.toString());
                final String base64Password = Base64.getEncoder().encodeToString(passwordBuilder.toString().getBytes(StandardCharsets.UTF_8));
                sender.setUsername(this.username);
                sender.setPassword(base64Password);
                //sender.setPassword(this.password);
                System.out.println("Authenticated successfully");
            } catch (final MalformedURLException e) {
                e.printStackTrace();
                //throw new MessagingException("Impossible d'initialiser la connexion OAuth2", e);
            }
        }
        System.out.println(sender.getJavaMailProperties());
        return sender;
    }

    private IAuthenticationResult getToken() throws MalformedURLException {
        final IConfidentialClientApplication app = ConfidentialClientApplication.builder(
                        this.clientId,
                        ClientCredentialFactory.createFromSecret(this.clientSecret))
                .authority(this.authority)

                .build();
        final ClientCredentialParameters parameters = ClientCredentialParameters.builder(
                        Collections.singleton(this.scope))
                .build();
        return app
                .acquireToken(parameters)
                .join();
    }

</code>```

my @Service class has:

```<code>@Service
public class Microsoft365MailSender implements MailSenderProvider {

    @Autowired
    private JavaMailSender sender;

    /*@Value("${spring.mail.host}")
    private String host;
    @Value("${mail.transport.protocol}")
    private String protocol;
    @Value("${spring.mail.port}")
    private Integer port;*/

    public void sendMailMessage(SimpleMailMessage simpleMailMessage) {
        this.sender.send(simpleMailMessage);
    }

    public void send(Email email) throws MessagingException, IOException {

// Connect

        MimeMessage message = this.sender.createMimeMessage();

        // Add subject, from and to lines.
        message.setSubject(email.getSubject(), "UTF-8");
        message.setFrom(new InternetAddress(email.getFrom()));

        message.setRecipients(Message.RecipientType.TO, SystemUtils.parseEmailAddressesList(email.getTo()));
        if(email.getCc()!=null) {
            message.setRecipients(Message.RecipientType.CC, SystemUtils.parseEmailAddressesList(email.getCc()));
        }
        if(email.getBcc()!=null) {
            message.setRecipients(Message.RecipientType.BCC, SystemUtils.parseEmailAddressesList(email.getBcc()));
        }
        // Create a multipart/alternative child container.
        MimeMultipart msg_body = new MimeMultipart("alternative");

        // Create a wrapper for the HTML and text parts.
        MimeBodyPart wrap = new MimeBodyPart();

        // Define the text part.
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent("email.getBody()", "text/plain; charset=UTF-8");

        // Define the HTML part.
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(email.getBody(), "text/html;");
        htmlPart.setDisposition(MimeBodyPart.INLINE);
        // Add the text and HTML parts to the child container.
        msg_body.addBodyPart(textPart);
        msg_body.addBodyPart(htmlPart);

        // Add the child container to the wrapper object.
        wrap.setContent(msg_body);

        // Create a multipart/mixed parent container.
        MimeMultipart msg = new MimeMultipart("mixed");

        // Add the parent container to the message.
        message.setContent(msg);

        // Add the multipart/alternative part to the message.
        msg.addBodyPart(wrap);

        // Define the attachment
        for(Attachment attachment : email.getAttachments()) {
            MimeBodyPart att = new MimeBodyPart();
            DataSource fds = new ByteArrayDataSource(attachment.getContent(), attachment.getContentType());
            att.setDataHandler(new DataHandler(fds));

            att.setFileName(attachment.getName());
            msg.addBodyPart(att);
        }
        // Add the attachment to the message.

        // Try to send the email.

        System.out.println("Attempting to send an email through Microsoft 365 ...");

        // Print the raw email content on the console

        // Send the email.
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        assert message != null;
        message.writeTo(outputStream);
        RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));

        SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
        // .withConfigurationSetName(CONFIGURATION_SET);

        this.send(message);
        System.out.println("Email sent!");
    }

    public void send(final MimeMessage message) throws MessagingException {
        System.out.println("Sending email message");
        this.sender.send(message);
        System.out.println("Message sent successfully");
    }
}

</code>```

and my application properties is as the following:

```<code>spring.mail.properties.mail.smtp.sasl.mechanisms=XOAUTH2
spring.mail.properties.mail.smtp.auth.xoauth2.authority=https://login.microsoftonline.com/MY_TENANT_ID/oauth2/v2.0/token
spring.mail.properties.mail.smtp.auth.xoauth2.client.id=MY_CLIENT_ID
spring.mail.properties.mail.smtp.auth.xoauth2.client.secret=MY_SECRET
spring.mail.properties.mail.smtp.auth.xoauth2.scope=https://graph.microsoft.com/.default
###########

spring.mail.host=smtp.office365.com
spring.mail.port=587
spring.mail.username=rami@*****

spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.port=25
spring.mail.properties.mail.smtp.auth=false
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
</code>```

the debug logs im getting when i'm sending the email is as following:

```<code>Saving: Email(id=null, subject=test, body=test, from=system@natid.co.il, to=[ramix@mindolife.com], cc=null, bcc=null, replyTo=system@natid.co.il, host=null, password=null, status=UNSENT, sendingTrials=0, lastSMTPErrorCode=0, attachments=[])
DEBUG: Jakarta Mail version 1.6.7
DEBUG: URL jar:file:/C:/Users/rami4/.m2/repository/com/amazonaws/aws-java-sdk-ses/1.12.266/aws-java-sdk-ses-1.12.266.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: jar:file:/C:/Users/rami4/.m2/repository/com/amazonaws/aws-java-sdk-ses/1.12.266/aws-java-sdk-ses-1.12.266.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.amazonaws.services.simpleemail.AWSJavaMailTransport=javax.mail.Provider[TRANSPORT,aws,com.amazonaws.services.simpleemail.AWSJavaMailTransport,Amazon Web Services LLC], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle]}
DEBUG: Providers Listed By Protocol: {imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], aws=javax.mail.Provider[TRANSPORT,aws,com.amazonaws.services.simpleemail.AWSJavaMailTransport,Amazon Web Services LLC], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
Attempting to send an email through Microsoft 365 ...
Sending email message
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.office365.com", port 587, isSSL false
220 FR2P281CA0029.outlook.office365.com Microsoft ESMTP MAIL Service ready at Thu, 8 Dec 2022 08:59:31 +0000
DEBUG SMTP: connected to host "smtp.office365.com", port: 587
EHLO Rami-Laptop
250-FR2P281CA0029.outlook.office365.com Hello [77.137.67.174]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-STARTTLS
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
STARTTLS
220 2.0.0 SMTP server ready
EHLO Rami-Laptop
250-FR2P281CA0029.outlook.office365.com Hello [77.137.67.174]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-AUTH LOGIN XOAUTH2
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN XOAUTH2"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: protocolConnect login, host=smtp.office365.com, user=rami@*****, password=<non-null>
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM XOAUTH2
DEBUG SMTP: Using mechanism LOGIN
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN failed
org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 535 5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information. [FR2P281CA0029.DEUP281.PROD.OUTLOOK.COM]

</code>```

The permissions I have are:

```<code>User.Read
Mail.Send
</code>```

Body:
I'm developing an API that need to send an email using Microsoft 365 account.
As I understand Microsoft will disable the username and password login soon so i need to authenticate with OAuth2.

I wrote the following code but I keep getting an authentication error saying that i need to enable the SmtpClientAuthentication which will be deprecated soon.

I'm not sure what i'm doing wrong in my code.
See the following classes:

my @Configurations class has :

 @Value("${spring.mail.host}")
    private String host;
   /* @Value("${nati.mail.protocol}")
    private String protocol;*/
    @Value("${spring.mail.port}")
    private Integer port;
    @Value("${spring.mail.username}")
    private String username;

    @Value("${spring.mail.password}")
    private String password;
    @Value("${spring.mail.properties.mail.smtp.auth.xoauth2.client.id}")
    private String clientId;

    @Value("${spring.mail.properties.mail.smtp.auth.xoauth2.client.secret}")
    private String clientSecret;

    @Value("${spring.mail.properties.mail.smtp.auth.xoauth2.scope}")
    private String scope;

    @Value("${spring.mail.properties.mail.smtp.auth.xoauth2.authority}")
    private String authority;

    @Bean
    public JavaMailSender javaMailSender() {
        JavaMailSenderImpl sender = new JavaMailSenderImpl();
        sender.setHost(this.host);
        sender.setPort(this.port);
        //sender.setUsername(this.username);

        Properties props = sender.getJavaMailProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.debug", "true");

        if (StringUtils.isNoneBlank(this.clientId, this.clientSecret, this.scope, this.authority)) {
            try {
                System.out.println("Authenticating with Microsoft Graph api ....");
                final StringBuilder passwordBuilder = new StringBuilder();
                passwordBuilder
                        .append("user=").append(this.username).append('\u0001')
                        .append("auth=").append("Bearer ").append(getToken()
                                .accessToken())
                        .append('\u0001').append('\u0001');
               // System.out.println("password: "+passwordBuilder.toString());
                final String base64Password = Base64.getEncoder().encodeToString(passwordBuilder.toString().getBytes(StandardCharsets.UTF_8));
                sender.setUsername(this.username);
                sender.setPassword(base64Password);
                //sender.setPassword(this.password);
                System.out.println("Authenticated successfully");
            } catch (final MalformedURLException e) {
                e.printStackTrace();
                //throw new MessagingException("Impossible d'initialiser la connexion OAuth2", e);
            }
        }
        System.out.println(sender.getJavaMailProperties());
        return sender;
    }

    private IAuthenticationResult getToken() throws MalformedURLException {
        final IConfidentialClientApplication app = ConfidentialClientApplication.builder(
                        this.clientId,
                        ClientCredentialFactory.createFromSecret(this.clientSecret))
                .authority(this.authority)

                .build();
        final ClientCredentialParameters parameters = ClientCredentialParameters.builder(
                        Collections.singleton(this.scope))
                .build();
        return app
                .acquireToken(parameters)
                .join();
    }

my @Service class has:

@Service
public class Microsoft365MailSender implements MailSenderProvider {

    @Autowired
    private JavaMailSender sender;

    /*@Value("${spring.mail.host}")
    private String host;
    @Value("${mail.transport.protocol}")
    private String protocol;
    @Value("${spring.mail.port}")
    private Integer port;*/

    public void sendMailMessage(SimpleMailMessage simpleMailMessage) {
        this.sender.send(simpleMailMessage);
    }

    public void send(Email email) throws MessagingException, IOException {

// Connect

        MimeMessage message = this.sender.createMimeMessage();

        // Add subject, from and to lines.
        message.setSubject(email.getSubject(), "UTF-8");
        message.setFrom(new InternetAddress(email.getFrom()));

        message.setRecipients(Message.RecipientType.TO, SystemUtils.parseEmailAddressesList(email.getTo()));
        if(email.getCc()!=null) {
            message.setRecipients(Message.RecipientType.CC, SystemUtils.parseEmailAddressesList(email.getCc()));
        }
        if(email.getBcc()!=null) {
            message.setRecipients(Message.RecipientType.BCC, SystemUtils.parseEmailAddressesList(email.getBcc()));
        }
        // Create a multipart/alternative child container.
        MimeMultipart msg_body = new MimeMultipart("alternative");

        // Create a wrapper for the HTML and text parts.
        MimeBodyPart wrap = new MimeBodyPart();

        // Define the text part.
        MimeBodyPart textPart = new MimeBodyPart();
        textPart.setContent("email.getBody()", "text/plain; charset=UTF-8");

        // Define the HTML part.
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(email.getBody(), "text/html;");
        htmlPart.setDisposition(MimeBodyPart.INLINE);
        // Add the text and HTML parts to the child container.
        msg_body.addBodyPart(textPart);
        msg_body.addBodyPart(htmlPart);

        // Add the child container to the wrapper object.
        wrap.setContent(msg_body);

        // Create a multipart/mixed parent container.
        MimeMultipart msg = new MimeMultipart("mixed");

        // Add the parent container to the message.
        message.setContent(msg);

        // Add the multipart/alternative part to the message.
        msg.addBodyPart(wrap);

        // Define the attachment
        for(Attachment attachment : email.getAttachments()) {
            MimeBodyPart att = new MimeBodyPart();
            DataSource fds = new ByteArrayDataSource(attachment.getContent(), attachment.getContentType());
            att.setDataHandler(new DataHandler(fds));

            att.setFileName(attachment.getName());
            msg.addBodyPart(att);
        }
        // Add the attachment to the message.

        // Try to send the email.

        System.out.println("Attempting to send an email through Microsoft 365 ...");

        // Print the raw email content on the console

        // Send the email.
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        assert message != null;
        message.writeTo(outputStream);
        RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));

        SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);
        // .withConfigurationSetName(CONFIGURATION_SET);

        this.send(message);
        System.out.println("Email sent!");
    }

    public void send(final MimeMessage message) throws MessagingException {
        System.out.println("Sending email message");
        this.sender.send(message);
        System.out.println("Message sent successfully");
    }
}

and my application properties is as the following:

spring.mail.properties.mail.smtp.sasl.mechanisms=XOAUTH2
spring.mail.properties.mail.smtp.auth.xoauth2.authority=https://login.microsoftonline.com/MY_TENANT_ID/oauth2/v2.0/token
spring.mail.properties.mail.smtp.auth.xoauth2.client.id=MY_CLIENT_ID
spring.mail.properties.mail.smtp.auth.xoauth2.client.secret=MY_SECRET
spring.mail.properties.mail.smtp.auth.xoauth2.scope=https://graph.microsoft.com/.default
###########

spring.mail.host=smtp.office365.com
spring.mail.port=587
spring.mail.username=rami@*****

spring.mail.properties.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.port=25
spring.mail.properties.mail.smtp.auth=false
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true

the debug logs im getting when i'm sending the email is as following:

Saving: Email(id=null, subject=test, body=test, from=system@natid.co.il, to=[ramix@mindolife.com], cc=null, bcc=null, replyTo=system@natid.co.il, host=null, password=null, status=UNSENT, sendingTrials=0, lastSMTPErrorCode=0, attachments=[])
DEBUG: Jakarta Mail version 1.6.7
DEBUG: URL jar:file:/C:/Users/rami4/.m2/repository/com/amazonaws/aws-java-sdk-ses/1.12.266/aws-java-sdk-ses-1.12.266.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: jar:file:/C:/Users/rami4/.m2/repository/com/amazonaws/aws-java-sdk-ses/1.12.266/aws-java-sdk-ses-1.12.266.jar!/META-INF/javamail.providers
DEBUG: successfully loaded resource: /META-INF/javamail.default.providers
DEBUG: Tables of loaded providers
DEBUG: Providers Listed By Class Name: {com.sun.mail.smtp.SMTPTransport=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], com.sun.mail.imap.IMAPSSLStore=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], com.sun.mail.pop3.POP3Store=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], com.sun.mail.smtp.SMTPSSLTransport=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], com.amazonaws.services.simpleemail.AWSJavaMailTransport=javax.mail.Provider[TRANSPORT,aws,com.amazonaws.services.simpleemail.AWSJavaMailTransport,Amazon Web Services LLC], com.sun.mail.imap.IMAPStore=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], com.sun.mail.pop3.POP3SSLStore=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle]}
DEBUG: Providers Listed By Protocol: {imap=javax.mail.Provider[STORE,imap,com.sun.mail.imap.IMAPStore,Oracle], smtp=javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle], pop3=javax.mail.Provider[STORE,pop3,com.sun.mail.pop3.POP3Store,Oracle], imaps=javax.mail.Provider[STORE,imaps,com.sun.mail.imap.IMAPSSLStore,Oracle], smtps=javax.mail.Provider[TRANSPORT,smtps,com.sun.mail.smtp.SMTPSSLTransport,Oracle], aws=javax.mail.Provider[TRANSPORT,aws,com.amazonaws.services.simpleemail.AWSJavaMailTransport,Amazon Web Services LLC], pop3s=javax.mail.Provider[STORE,pop3s,com.sun.mail.pop3.POP3SSLStore,Oracle]}
DEBUG: successfully loaded resource: /META-INF/javamail.default.address.map
Attempting to send an email through Microsoft 365 ...
Sending email message
DEBUG: getProvider() returning javax.mail.Provider[TRANSPORT,smtp,com.sun.mail.smtp.SMTPTransport,Oracle]
DEBUG SMTP: useEhlo true, useAuth true
DEBUG SMTP: trying to connect to host "smtp.office365.com", port 587, isSSL false
220 FR2P281CA0029.outlook.office365.com Microsoft ESMTP MAIL Service ready at Thu, 8 Dec 2022 08:59:31 +0000
DEBUG SMTP: connected to host "smtp.office365.com", port: 587
EHLO Rami-Laptop
250-FR2P281CA0029.outlook.office365.com Hello [77.137.67.174]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-STARTTLS
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "STARTTLS", arg ""
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
STARTTLS
220 2.0.0 SMTP server ready
EHLO Rami-Laptop
250-FR2P281CA0029.outlook.office365.com Hello [77.137.67.174]
250-SIZE 157286400
250-PIPELINING
250-DSN
250-ENHANCEDSTATUSCODES
250-AUTH LOGIN XOAUTH2
250-8BITMIME
250-BINARYMIME
250-CHUNKING
250 SMTPUTF8
DEBUG SMTP: Found extension "SIZE", arg "157286400"
DEBUG SMTP: Found extension "PIPELINING", arg ""
DEBUG SMTP: Found extension "DSN", arg ""
DEBUG SMTP: Found extension "ENHANCEDSTATUSCODES", arg ""
DEBUG SMTP: Found extension "AUTH", arg "LOGIN XOAUTH2"
DEBUG SMTP: Found extension "8BITMIME", arg ""
DEBUG SMTP: Found extension "BINARYMIME", arg ""
DEBUG SMTP: Found extension "CHUNKING", arg ""
DEBUG SMTP: Found extension "SMTPUTF8", arg ""
DEBUG SMTP: protocolConnect login, host=smtp.office365.com, user=rami@*****, password=<non-null>
DEBUG SMTP: Attempt to authenticate using mechanisms: LOGIN PLAIN DIGEST-MD5 NTLM XOAUTH2
DEBUG SMTP: Using mechanism LOGIN
DEBUG SMTP: AUTH LOGIN command trace suppressed
DEBUG SMTP: AUTH LOGIN failed
org.springframework.mail.MailAuthenticationException: Authentication failed; nested exception is javax.mail.AuthenticationFailedException: 535 5.7.139 Authentication unsuccessful, SmtpClientAuthentication is disabled for the Tenant. Visit https://aka.ms/smtp_auth_disabled for more information. [FR2P281CA0029.DEUP281.PROD.OUTLOOK.COM]

The permissions I have are:

User.Read
Mail.Send


问:
System.NullReferenceException: 'Object reference not set to an instance of an object.' result was null
private void timer1_Tick(object sender, EventArgs e)
{

```<code>      //  try
       // {
            BarcodeReader reader = new BarcodeReader();
            Result result = reader.Decode((Bitmap)scanQRIMAGE.Image);
            string decoded = result.ToString().Trim();
            ID_text.Text = decoded;

           if (decoded != null)
          {

                con.Open();

                MySqlCommand coman = new MySqlCommand();
                coman.Connection = con;
                coman.CommandText = " select * from  hopetestdb  where id Like'%" + ID_text.Text + "%'";
                MySqlDataReader dr = coman.ExecuteReader();
                dr.Read();

                if (dr.HasRows)
                {

                    ID_text.Text = dr["id"].ToString();
                   tb_Fname.Text = dr["Firstname"].ToString();
                    tb_Lastname.Text = dr["Lastname"].ToString();
                    tb_Role.Text = dr["GymRole"].ToString();

                    byte[] img = ((byte[])dr["Photo"]);
                    MemoryStream ms = new MemoryStream(img);
                    IMAGEperson.Image = Image.FromStream(ms);

                }

                con.Close();
</code>```

even it detect something this always happen and  sometimes wrong data will appear
result was null  i check if i have wrong in the youtube that i  watch but nothing wrong

Body:
private void timer1_Tick(object sender, EventArgs e)
{

      //  try
       // {
            BarcodeReader reader = new BarcodeReader();
            Result result = reader.Decode((Bitmap)scanQRIMAGE.Image);
            string decoded = result.ToString().Trim();
            ID_text.Text = decoded;

           if (decoded != null)
          {

                con.Open();

                MySqlCommand coman = new MySqlCommand();
                coman.Connection = con;
                coman.CommandText = " select * from  hopetestdb  where id Like'%" + ID_text.Text + "%'";
                MySqlDataReader dr = coman.ExecuteReader();
                dr.Read();

                if (dr.HasRows)
                {

                    ID_text.Text = dr["id"].ToString();
                   tb_Fname.Text = dr["Firstname"].ToString();
                    tb_Lastname.Text = dr["Lastname"].ToString();
                    tb_Role.Text = dr["GymRole"].ToString();

                    byte[] img = ((byte[])dr["Photo"]);
                    MemoryStream ms = new MemoryStream(img);
                    IMAGEperson.Image = Image.FromStream(ms);

                }

                con.Close();

even it detect something this always happen and  sometimes wrong data will appear
result was null  i check if i have wrong in the youtube that i  watch but nothing wrong


问:
How to pass socket.io props to Route Component in Reactjs
In my application I need socket object to define globally and pass it to the required component

```<code>const App = () => {
    const socket   = useRef();
    useEffect(() => {
        socket.current = io(socketEND);
    },[])

    return (
        <Router>
            <Header socket={socket} />
                <main className='py-content-wrapper'>
                    <div className="content-wrapper">
                        <Switch>
                            <Route path='/login'  component={LoginScreen} />
                            <Route path='/chat'   component={(socket) => <Chat socket={socket} /> } />
                        </Switch>
                    </div>
                </main>
            <Footer />
        </Router>
    )
}
export default App
</code>```

In Header and Chat component socket.current is undefined, Can someone help me to fix this issue

Body:
In my application I need socket object to define globally and pass it to the required component

const App = () => {
    const socket   = useRef();
    useEffect(() => {
        socket.current = io(socketEND);
    },[])

    return (
        <Router>

                        <Switch>
                            <Route path='/login'  component={LoginScreen} />
                            <Route path='/chat'   component={(socket) => <Chat socket={socket} /> } />
                        </Switch>

        </Router>
    )
}
export default App

In Header and Chat component socket.current is undefined, Can someone help me to fix this issue


问:
How can i redirect the output to file?
i want to write my bash. i have a problem with redirects. in my algorithm i send the command(echo asd > file.txt) here again and again. (i couldn't see any solutions for this situtation in here) command.count is one before the ">", command.count is two after the ">". when i call the first time this function, i use dup2 for change de output way. i want to keep to result of the execve in the command.tmp_fd. when i call the second time this function, i find the file name(file.txt) from get_sub_type, and direct the old result to new file(file.txt). i can create the right file but i cant write anything in this file. is my algorithm wrong?

i wrote two way. in the first code i used struct for temporary file. in the second code i used the static variable for temporary file. when i write the "echo asd > file.txt" asd seems at the terminal, not in the file.

```<code>int redir_exec(t_command command)
{
    printf("command_count %d\n", command.count);
    pid_t pid;
    int result;
    char *path;
    char **type;
    int fd;

    fd = 0;
    result = 0;
    path = command_find_path(command.keyword);
    if (command.count == 1)
        type = create_type(command, path);
    signal(SIGINT, proc_signal_handler);
    pid = fork();
    if (pid < 0)
        return (-1);
    else if (pid == 0)
    {
        if (command.count == 1)
        {
            dup2(command.tmp_fd, STDOUT_FILENO);
            close(command.tmp_fd);
            result = execve(path, type, g_env.env);
            exit(command.tmp_fd);
        }
        if (result == -1)
            perror("error\n");
        return 0;
    }
    else if (pid > 0)
    {
        if (command.count > 1)
        {
            int tm = -1;
            wait(&tm);
            fd = get_sub_type(command);
            dup2(fd, tm);
            close(fd);
        }
    }
    wait(&pid);
    free(path);
    return (0);
}
</code>```
```<code>int redir_exec(t_command command)
{
    pid_t pid;
    int result;
    char *path;
    char **type;
    static int fd;
    int file;

    fd = 0;
    file = 0;
    result = 0;
    path = command_find_path(command.keyword);
    if (command.count == 1)
        type = create_type(command, path);
    signal(SIGINT, proc_signal_handler);
    pid = fork();
    if (pid < 0)
        return (-1);
    else if (pid == 0)
    {
        if (command.count == 1)
        {
            dup2(fd, STDOUT_FILENO);
            close(fd);
            result = execve(path, type, g_env.env);
        }
        if (result == -1)
            perror("error\n");
        return 0;
    }
    else if (pid > 0)
    {
        if (command.count > 1)
        {
            file = get_sub_type(command);
            dup2(file, fd);
            close(file);
        }
    }
    wait(&pid);
    free(path);
    return (0);
}
</code>```

Title: How can i redirect the output to file?

Body:
i want to write my bash. i have a problem with redirects. in my algorithm i send the command(echo asd > file.txt) here again and again. (i couldn't see any solutions for this situtation in here) command.count is one before the ">", command.count is two after the ">". when i call the first time this function, i use dup2 for change de output way. i want to keep to result of the execve in the command.tmp_fd. when i call the second time this function, i find the file name(file.txt) from get_sub_type, and direct the old result to new file(file.txt). i can create the right file but i cant write anything in this file. is my algorithm wrong?

i wrote two way. in the first code i used struct for temporary file. in the second code i used the static variable for temporary file. when i write the "echo asd > file.txt" asd seems at the terminal, not in the file.

int redir_exec(t_command command)
{
    printf("command_count %d\n", command.count);
    pid_t pid;
    int result;
    char *path;
    char **type;
    int fd;

    fd = 0;
    result = 0;
    path = command_find_path(command.keyword);
    if (command.count == 1)
        type = create_type(command, path);
    signal(SIGINT, proc_signal_handler);
    pid = fork();
    if (pid < 0)
        return (-1);
    else if (pid == 0)
    {
        if (command.count == 1)
        {
            dup2(command.tmp_fd, STDOUT_FILENO);
            close(command.tmp_fd);
            result = execve(path, type, g_env.env);
            exit(command.tmp_fd);
        }
        if (result == -1)
            perror("error\n");
        return 0;
    }
    else if (pid > 0)
    {
        if (command.count > 1)
        {
            int tm = -1;
            wait(&tm);
            fd = get_sub_type(command);
            dup2(fd, tm);
            close(fd);
        }
    }
    wait(&pid);
    free(path);
    return (0);
}

int redir_exec(t_command command)
{
    pid_t pid;
    int result;
    char *path;
    char **type;
    static int fd;
    int file;

    fd = 0;
    file = 0;
    result = 0;
    path = command_find_path(command.keyword);
    if (command.count == 1)
        type = create_type(command, path);
    signal(SIGINT, proc_signal_handler);
    pid = fork();
    if (pid < 0)
        return (-1);
    else if (pid == 0)
    {
        if (command.count == 1)
        {
            dup2(fd, STDOUT_FILENO);
            close(fd);
            result = execve(path, type, g_env.env);
        }
        if (result == -1)
            perror("error\n");
        return 0;
    }
    else if (pid > 0)
    {
        if (command.count > 1)
        {
            file = get_sub_type(command);
            dup2(file, fd);
            close(file);
        }
    }
    wait(&pid);
    free(path);
    return (0);
}


问:
uploadArchives into publishing for Gradle 7x | Android | Gradle
I have recently updated my project Gradle version to 7+ and it started giving me error for uploadArchives. It says could not find uploadArchives().

After a lot of finding I came across publishing and google removed uploadArchive.

```<code>uploadArchives {
    dependsOn build
    configuration = configurations.archives
    repositories.mavenDeployer {
        pom.groupId = GROUP_ID
        pom.artifactId = ARTIFACT_ID
        pom.version = ARTIFACT_VERSION
        configuration = configurations.deployerJar
        repository(url: "git:releases://https://" + USER_NAME + ":" + REPO_PASSWORD + "@bitbucket.org/android/sdk.git")
        pom.project {
            developers {
                developer {
                    id DEV_ID
                    name DEV_NAME
                    email DEV_EMAIL
                }
            }
        }
    }
}
</code>```

This is my previous code snippet. Please help me in converting it to publishing.

Thanks!

Body:
I have recently updated my project Gradle version to 7+ and it started giving me error for uploadArchives. It says could not find uploadArchives().

After a lot of finding I came across publishing and google removed uploadArchive.

uploadArchives {
    dependsOn build
    configuration = configurations.archives
    repositories.mavenDeployer {
        pom.groupId = GROUP_ID
        pom.artifactId = ARTIFACT_ID
        pom.version = ARTIFACT_VERSION
        configuration = configurations.deployerJar
        repository(url: "git:releases://https://" + USER_NAME + ":" + REPO_PASSWORD + "@bitbucket.org/android/sdk.git")
        pom.project {
            developers {
                developer {
                    id DEV_ID
                    name DEV_NAME
                    email DEV_EMAIL
                }
            }
        }
    }
}

This is my previous code snippet. Please help me in converting it to publishing.

Thanks!


问:
Why flutter assets image not show on embedded device on POS?
In Flutter application, Set splash screen with the Image.asset and timer to show image when loading from the asset folder, that only work on android device (android version 10) and not work on embedded android with POS device. How can I solve this problem?
But in embedded device instead of image, CircularProgressIndicator work well

Code

```<code>Timer loadTimer() {
    var duration = const Duration(seconds: 4);
    return Timer(duration, loadScreenRoute);
  }

void loadScreenRoute() async {
    SplashBloc bloc = Provider.of<SplashBloc>(context, listen: false);
    build(context);
    await bloc.isValidateToken().then((value) {
      if (value) {
        Navigator.of(context)
            .pushNamedAndRemoveUntil(LoginScreen.routeName, (route) => false);
      } else if ((bloc.shopID == null || bloc.shopID == '')) {
        Navigator.of(context)
            .pushNamedAndRemoveUntil(LoginScreen.routeName, (route) => false);
      } else {
        Navigator.of(context)
            .pushNamedAndRemoveUntil(MainScreen.routeName, (route) => false);
      }
    });
  }

Future<void> getIp() async {
    ipAddress = await RGetIp.internalIP;
    await TempStringData.setTempStringData(
        key: TempStringData.localhostAddress, value: ipAddress ?? '');
    print('=======> $ipAddress');
  }

@override
  void initState() {
    loadTimer();
    getIp();
    super.initState();
  }

return Scaffold(
          body: Center(
            child: SizedBox(
              width: 100,
              height: 100,
              child: Image.asset(
                'assets/images/logo&Text.png',
                width: 100,
              ),
            ),
            //child: CircularProgressIndicator(color: Colors.black,),
          ),
        );
</code>```

That code flow of splash screen and anything wrong with logic? But this logic work perfectly in android phone device.

I changed image with another images and small size images and test again but not woking in POS android device. Only that image not in splash screen not work and other assets local images showing well on that device.

Body:
In Flutter application, Set splash screen with the Image.asset and timer to show image when loading from the asset folder, that only work on android device (android version 10) and not work on embedded android with POS device. How can I solve this problem?
But in embedded device instead of image, CircularProgressIndicator work well

Code

Timer loadTimer() {
    var duration = const Duration(seconds: 4);
    return Timer(duration, loadScreenRoute);
  }

void loadScreenRoute() async {
    SplashBloc bloc = Provider.of<SplashBloc>(context, listen: false);
    build(context);
    await bloc.isValidateToken().then((value) {
      if (value) {
        Navigator.of(context)
            .pushNamedAndRemoveUntil(LoginScreen.routeName, (route) => false);
      } else if ((bloc.shopID == null || bloc.shopID == '')) {
        Navigator.of(context)
            .pushNamedAndRemoveUntil(LoginScreen.routeName, (route) => false);
      } else {
        Navigator.of(context)
            .pushNamedAndRemoveUntil(MainScreen.routeName, (route) => false);
      }
    });
  }

Future<void> getIp() async {
    ipAddress = await RGetIp.internalIP;
    await TempStringData.setTempStringData(
        key: TempStringData.localhostAddress, value: ipAddress ?? '');
    print('=======> $ipAddress');
  }

@override
  void initState() {
    loadTimer();
    getIp();
    super.initState();
  }

return Scaffold(
          body: Center(
            child: SizedBox(
              width: 100,
              height: 100,
              child: Image.asset(
                'assets/images/logo&Text.png',
                width: 100,
              ),
            ),
            //child: CircularProgressIndicator(color: Colors.black,),
          ),
        );

That code flow of splash screen and anything wrong with logic? But this logic work perfectly in android phone device.

I changed image with another images and small size images and test again but not woking in POS android device. Only that image not in splash screen not work and other assets local images showing well on that device.


问:
C++ extension intellisense using gcc not g++
I've assign a "new" file extension type to c++, by using Settings->Text Editor->Files mapping "*.xx" to "cpp". Turning on intellisense debug logging I see that the now file is being analysed by the intellisense extension:

```<code>define: __ATOMIC_RELEASE=3
define: __declspec(x)=attribute((x))
define: _DEBUG
define: UNICODE
define: _UNICODE
**other: --gcc
other: --gnu_version=110300**
stdver: c17
intelliSenseMode: linux-gcc-x64
Queueing IntelliSense update for files in translation unit of: E:\mfcl_engineering\workspace-eclipse\mfc_axis_example\src\mfc_axis_example.xx
</code>```

But the debug log above shows that C is being used as the analysis language not C++. Is this a bug in intellisense?

I've tried looking at the strings in cpptools.exe and found that the --gcc and --g++ are text strings within the binary, but looking at cpptools.exe source code I cant see that --gcc/--g++ is hard coded, so it should be picked up from the build config file..though I cant find it. If I can find how the language settings are being generated I think (I hope!) I can understand what config file/parameter I need to change in order to get intellisense to use the correct language.

Body:
I've assign a "new" file extension type to c++, by using Settings->Text Editor->Files mapping "*.xx" to "cpp". Turning on intellisense debug logging I see that the now file is being analysed by the intellisense extension:

define: __ATOMIC_RELEASE=3
define: __declspec(x)=attribute((x))
define: _DEBUG
define: UNICODE
define: _UNICODE
**other: --gcc
other: --gnu_version=110300**
stdver: c17
intelliSenseMode: linux-gcc-x64
Queueing IntelliSense update for files in translation unit of: E:\mfcl_engineering\workspace-eclipse\mfc_axis_example\src\mfc_axis_example.xx

But the debug log above shows that C is being used as the analysis language not C++. Is this a bug in intellisense?

I've tried looking at the strings in cpptools.exe and found that the --gcc and --g++ are text strings within the binary, but looking at cpptools.exe source code I cant see that --gcc/--g++ is hard coded, so it should be picked up from the build config file..though I cant find it. If I can find how the language settings are being generated I think (I hope!) I can understand what config file/parameter I need to change in order to get intellisense to use the correct language.


问:
Tests runs locally but fails in Azure DevOps Pipeline
The Problem:

We wrote a simple test which only fills a textfield, clicks on a button and checks for redirect. On our local machines the test runs without any problems. In the pipeline the test fills the textfield and says that he has clicked the button, but nothing happens and the next condition fails.

Our Pipeline steps:

npm install

gatsby build

gatsby serve -p 8000 & npx cypress run --record --key <KEY> --config video=false --e2e

Specs:

Cypress: 12.0.1

React: 18.2.0

Gatsby 4.24.0

Azure Pipeline running on Ubuntu 20.04

Our Test:

```<code>
cy.get('#search-field').should('be.visible').clear().type(searchText);

cy.get('#submit-search-button').click({ force: true });

cy.get('#search-results').children().its('length').should('be.gte', 3);
</code>```

What we tried:

Increasing Buildagent CPUs and Storage

Using different browsers (Chrome, Electron)

Disabling Video generation

Creating a new Pipeline (Windows)

Running all steps from the pipeline on our local machines

Body:
The Problem:

We wrote a simple test which only fills a textfield, clicks on a button and checks for redirect. On our local machines the test runs without any problems. In the pipeline the test fills the textfield and says that he has clicked the button, but nothing happens and the next condition fails.

Our Pipeline steps:

npm install

gatsby build

gatsby serve -p 8000 & npx cypress run --record --key <KEY> --config video=false --e2e

Specs:

Cypress: 12.0.1

React: 18.2.0

Gatsby 4.24.0

Azure Pipeline running on Ubuntu 20.04

Our Test:

cy.get('#search-field').should('be.visible').clear().type(searchText);

cy.get('#submit-search-button').click({ force: true });

cy.get('#search-results').children().its('length').should('be.gte', 3);

What we tried:

Increasing Buildagent CPUs and Storage

Using different browsers (Chrome, Electron)

Disabling Video generation

Creating a new Pipeline (Windows)

Running all steps from the pipeline on our local machines


问:
How can I return a reference of RefCell<String> as &str with lifetime of the Struct in which the RefCell is declared?
I am trying to learn Rust. I have the following problem, I am trying to get a reference of a RefCell<String> as &str with lifetime of the struct in which the RefCell is declared.
Snippets of code are below, (code is taken from Rust book)

trait State {
    fn content<'a>(&self, post: &'a Post) -> &'a str {""}
    fn add_text(&self, content: RefCell<String>,text: &str) {}
}
struct Post {
    state: Option<Box<dyn State>>,
    content: RefCell<String>,
}

struct Published {}
struct Draft {}

impl Published {
    pub fn content(&self) -> &str{
        self.state.as_ref().unwrap().content(&self)
    }
     fn add_text(&self, text: &str) {
        self.state
            .as_ref()
            .unwrap()
            .add_text(RefCell::clone(&self.content), text);
    }
}

impl State for Published {
    fn content<'a>(&self, post: &'a Post) -> &'a str {
        &post.content.borrow().as_str() "**//Line of error**"

    }
}
impl State for Draft {
    fn add_text(&self, content: RefCell<String>, text: &str) {
        &content.borrow_mut().push_str(text);
    }
}

```
<p><strong>This is the error I get:</strong></p>
<pre class="lang-none prettyprint-override"><code>error[E0515]:
cannot return value referencing temporary value
  src/lib.rs:113:9
113 |&post.content.borrow().as_str()
temporary value created here
returns a value referencing data owned by the current
</code>```

The line of the error is commented in the code.

Could someone explain me please what I am doing wrong, and why?

What I am trying to achieve is to another Trait to be able to mutate the content String of the Post struct, and another Trait also to return it.

Thanks in advance

Body:
I am trying to learn Rust. I have the following problem, I am trying to get a reference of a RefCell<String> as &str with lifetime of the struct in which the RefCell is declared.
Snippets of code are below, (code is taken from Rust book)

trait State {
    fn content<'a>(&self, post: &'a Post) -> &'a str {""}
    fn add_text(&self, content: RefCell<String>,text: &str) {}
}
struct Post {
    state: Option<Box<dyn State>>,
    content: RefCell<String>,
}

struct Published {}
struct Draft {}

impl Published {
    pub fn content(&self) -> &str{
        self.state.as_ref().unwrap().content(&self)
    }
     fn add_text(&self, text: &str) {
        self.state
            .as_ref()
            .unwrap()
            .add_text(RefCell::clone(&self.content), text);
    }
}

impl State for Published {
    fn content<'a>(&self, post: &'a Post) -> &'a str {
        &post.content.borrow().as_str() "**//Line of error**"

    }
}
impl State for Draft {
    fn add_text(&self, content: RefCell<String>, text: &str) {
        &content.borrow_mut().push_str(text);
    }
}

This is the error I get:

error[E0515]:
cannot return value referencing temporary value
  src/lib.rs:113:9
113 |&post.content.borrow().as_str()
temporary value created here
returns a value referencing data owned by the current

The line of the error is commented in the code.

Could someone explain me please what I am doing wrong, and why?

What I am trying to achieve is to another Trait to be able to mutate the content String of the Post struct, and another Trait also to return it.

Thanks in advance


问:
Uncaught TypeError: Cannot read properties of undefined (reading 'deferred')
I am trying to make a panel in wordpress, with wp.customize wordpress object but i got this error.

Uncaught TypeError: Cannot read properties of undefined (reading 'deferred')

```<code>(function ($, api) {

    api.panel.add(new api.Panel('my_panel', {
        'title': 'My Panel',
        'priority': 10,
    }))

})(jQuery, wp.customize);

</code>```
```<code>add_action('customize_controls_enqueue_scripts', function () {
    $custom_controls_react_deps = array(
        'wp-i18n',
        'wp-components',
        'jquery',
        'wp-element',
        'wp-media-utils',
        'wp-block-editor',
    );

    wp_enqueue_script('my-code', get_template_directory_uri() . '/inc/customizer/extend/index.js', $custom_controls_react_deps, 1, true);
});
</code>```

Body:
I am trying to make a panel in wordpress, with wp.customize wordpress object but i got this error.

Uncaught TypeError: Cannot read properties of undefined (reading 'deferred')

(function ($, api) {

    api.panel.add(new api.Panel('my_panel', {
        'title': 'My Panel',
        'priority': 10,
    }))

})(jQuery, wp.customize);

add_action('customize_controls_enqueue_scripts', function () {
    $custom_controls_react_deps = array(
        'wp-i18n',
        'wp-components',
        'jquery',
        'wp-element',
        'wp-media-utils',
        'wp-block-editor',
    );

    wp_enqueue_script('my-code', get_template_directory_uri() . '/inc/customizer/extend/index.js', $custom_controls_react_deps, 1, true);
});


问:
Python typing: How to extract the "inner" type of a generic class from another generic class?
I've boiled down my current design to this unit test:

import typing as typ

T1 = typ.TypeVar("T1")

class Foo(typ.Generic[T1]):
    def process(self) -> T1:
        pass
        # (As an example, this class would be inherited using Foo[str] and this method would spit out a str)

T2 = typ.TypeVar("T2", bound = Foo)
class Bar(typ.Generic[T2]):
    def __init__(self, foo_obj: T2, process_result: ???): # ???? should be T1 from inside Foo[T1]
        self.foo_obj = foo_obj
        self.process_result = process_result

class TestCase1Foo(Foo[str]):
    def process(self) -> str:
        return "test"

class TestCase1Bar(Bar[TestCase1Foo]):
    pass

# TestCase1Bar(TestCase1Foo(), TestCase1Foo().process()).process_result should be str according to a static type checker

class TestCase2Foo(Foo[int]):
    def process(self) -> int:
        return 69

class TestCase2Bar(Bar[TestCase2Foo]):
    pass

# TestCase2Bar(TestCase2Foo(), TestCase2Foo().process()).process_result should be int according to a static type checker
```

Bar is a generic where you can pass in Foo, and the Foo type itself is generic. Foo() contains an method whose return type is determined by the type passed in.

The constructor of Bar requires the Foo() object itself as well as the result of the process method inside Foo().

What should I do to get the intended behavior in the test cases?

Body:
I've boiled down my current design to this unit test:

import typing as typ

T1 = typ.TypeVar("T1")

class Foo(typ.Generic[T1]):
    def process(self) -> T1:
        pass
        # (As an example, this class would be inherited using Foo[str] and this method would spit out a str)

T2 = typ.TypeVar("T2", bound = Foo)
class Bar(typ.Generic[T2]):
    def __init__(self, foo_obj: T2, process_result: ???): # ???? should be T1 from inside Foo[T1]
        self.foo_obj = foo_obj
        self.process_result = process_result

class TestCase1Foo(Foo[str]):
    def process(self) -> str:
        return "test"

class TestCase1Bar(Bar[TestCase1Foo]):
    pass

# TestCase1Bar(TestCase1Foo(), TestCase1Foo().process()).process_result should be str according to a static type checker

class TestCase2Foo(Foo[int]):
    def process(self) -> int:
        return 69

class TestCase2Bar(Bar[TestCase2Foo]):
    pass

# TestCase2Bar(TestCase2Foo(), TestCase2Foo().process()).process_result should be int according to a static type checker

Bar is a generic where you can pass in Foo, and the Foo type itself is generic. Foo() contains an method whose return type is determined by the type passed in.

The constructor of Bar requires the Foo() object itself as well as the result of the process method inside Foo().

What should I do to get the intended behavior in the test cases?


问:
Reactjs, Websocket - state in subscribe callback is in default state
When I get a message on the channel

```<code>/topic/game-player-connected/
</code>```

I set the received number of connected people in callback "numberOfPeopleConnectedToRoom" to the array of objects with the status 'not ready'.

When I get a message on another channel

```<code>/topic/get-number-of-players-ready-for-round/
</code>```

with the number of people who are ready to play, then in the callback "numberOfPeopleReady", I want to change the status of the objects, but when I refer to the status 'peopleConnected' I have an empty array.

The "setPeopleConnected(newState);" works for sure, because in the React Developer Tools extension, I can see that the status is changing.

```<code>  const [peopleConnected, setPeopleConnected] = useState([]);
  const [peopleReady, setPeopleReady] = useState(0)

  const onConnected = (frame) => {
    setConnected(true);
    console.log("Connected: " + frame);
    stompClient.subscribe("/topic/get-number-of-players-ready-for-round/" + gameUuid, (messageOutput) => numberOfPeopleReady(messageOutput));
    stompClient.subscribe("/topic/game-player-connected/" + gameUuid, (messageOutput) => numberOfPeopleConnectedToRoom(messageOutput));
  };

  const numberOfPeopleConnectedToRoom = (messageOutput) => {
    const numberOfPeopleConnected = JSON.parse(messageOutput.body).numberOfPlayersSubscribedToTopic;
    console.log("Connected people: " + numberOfPeopleConnected);
    let newState = [];
    for (let i = 0; i < numberOfPeopleConnected; i++) {
      newState.push({ ready: false });
    }

    setPeopleConnected(newState);
  };

  const numberOfPeopleReady = (messageOutput) => {
    let peopleReady= JSON.parse(messageOutput.body).numberOfPlayersReadyForRound;
    console.log("Ready people from websocket " + peopleReady)
    console.log(peopleConnected)  <----- this doesnt work

    setPeopleReady(peopleReady)
  };
</code>```

After change state in "numberOfPeopleReady"

```<code>  useEffect(() => {
    console.log(peopleConnected);   <- this work

  }, [peopleReady]);
</code>```

I tried change the status of the players and there I was able to refer to this array, but then it did not work for me as it should display the changed array of objects, so I try to change the array in the callback "numberOfPeopleReady".

Body:
When I get a message on the channel

/topic/game-player-connected/

I set the received number of connected people in callback "numberOfPeopleConnectedToRoom" to the array of objects with the status 'not ready'.

When I get a message on another channel

/topic/get-number-of-players-ready-for-round/

with the number of people who are ready to play, then in the callback "numberOfPeopleReady", I want to change the status of the objects, but when I refer to the status 'peopleConnected' I have an empty array.

The "setPeopleConnected(newState);" works for sure, because in the React Developer Tools extension, I can see that the status is changing.

  const [peopleConnected, setPeopleConnected] = useState([]);
  const [peopleReady, setPeopleReady] = useState(0)

  const onConnected = (frame) => {
    setConnected(true);
    console.log("Connected: " + frame);
    stompClient.subscribe("/topic/get-number-of-players-ready-for-round/" + gameUuid, (messageOutput) => numberOfPeopleReady(messageOutput));
    stompClient.subscribe("/topic/game-player-connected/" + gameUuid, (messageOutput) => numberOfPeopleConnectedToRoom(messageOutput));
  };

  const numberOfPeopleConnectedToRoom = (messageOutput) => {
    const numberOfPeopleConnected = JSON.parse(messageOutput.body).numberOfPlayersSubscribedToTopic;
    console.log("Connected people: " + numberOfPeopleConnected);
    let newState = [];
    for (let i = 0; i < numberOfPeopleConnected; i++) {
      newState.push({ ready: false });
    }

    setPeopleConnected(newState);
  };

  const numberOfPeopleReady = (messageOutput) => {
    let peopleReady= JSON.parse(messageOutput.body).numberOfPlayersReadyForRound;
    console.log("Ready people from websocket " + peopleReady)
    console.log(peopleConnected)  <----- this doesnt work

    setPeopleReady(peopleReady)
  };

After change state in "numberOfPeopleReady"

  useEffect(() => {
    console.log(peopleConnected);   <- this work

  }, [peopleReady]);

I tried change the status of the players and there I was able to refer to this array, but then it did not work for me as it should display the changed array of objects, so I try to change the array in the callback "numberOfPeopleReady".


问:
How to automatically set range based on maximum value of visible points in QChart?
I'm trying to plot a chart where it sets Y axis range from 0.0 to maximum value in plot. However I do not want to set the range maximum to be maximum value of all data, because I'm not plotting all data, but the last 10 seconds of the incoming data.
How can I achieve that? I know how to set range maximum of all data inserted to series, but that is not what I want to achieve. In this example the maximum is set taking in all the incoming data -- this is not what I want. I want my plot to automatically adjust to whatever is the maximum plotted Y value of all visible points, so points in chart area.

I set the X axis range to show only last 10 seconds. I want to set the range of Y axis to stop at maximum of actually plotted points. Is there a way to get maximum value of only plotted points that are in QLineSeries?


问:
Manipulating sql database data
There is a column called "enc_cmd_num" which is the order number.

Another one is called "enc_paye" which displays 1 (if the order is paid), 0 (if the order is not paid)

All this comes from a table called "encaissement".

My problem is as follows:

I can display the data that come from a Microsoft database in which I use OBDC.

I would like to be able to display in a screen when the order number (which comes from the table "enc_cmd_num") is paid, (display that it is put in preparation), but if this one is not paid, that it is in "waiting for payment".

Thanks again for your precious help.

I tried to search the internet but no one is concrete in what they say....

Title: Manipulating sql database data


问:
How to enforce an issues workflow in Gitlab?
As described in this issue is-there-a-mylyn-connector-for-gitlab, it is not possibe to enforce issues workflow with Gitlab.

There are some issues opened on Gitlab about this subject, but Gitlab teams do not seem to want to provide a such feature.

Does someone know how to change gitlab code to implement some issues workflow rules ? It should be implemented in parts about labels management.


问:
Threadsafety in MongoDB read and write access
I am trying to update an entity called StaticsModel in a MongoDb database. This entity has properties such as mapped (int), date (DATE), sent (int) ,id (primary key) etc. I am updating the same entity for a particular date in different API-s , for instance in one API I update the number of sent, in one other API I update the number of mapped etc. Is the following code threadsafe ? Because when several PC-s hit several API-s at the same time I get different results for the same date. For instance when I update the number of mapped ,the number of sent gets another random variable. How can I make this code threadsafe? I presumed that setting the properties as atomic would solve the issue but I am having doubts now. Thanks

```<code>  StatisticsModel statisticsModel = new Statistics();
    String today = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
    statisticsModel.setDate(today);
    List<StatisticsModel > statisticsCreate = statisticsRepository.findByDate(today);
    if (statisticsCreate .size() < 1)
        atomicLong.set(0);
    for (StatisticsModel statisticsModelRes : statisticsCreate ) {
        statisticsModel.setMapped(statisticsModelRes.getMapped());
        statisticsModel.setSent(statisticsModelRes.getSent());
    }
    statisticsModel.setReceived(atomicLong.incrementAndGet());
    statisticsRepository.upsert(statisticsModel );
</code>```

Edit: I think my problem is almost similar to this one:

It's not possible to lock a mongodb document. What if I need to?

Body:
I am trying to update an entity called StaticsModel in a MongoDb database. This entity has properties such as mapped (int), date (DATE), sent (int) ,id (primary key) etc. I am updating the same entity for a particular date in different API-s , for instance in one API I update the number of sent, in one other API I update the number of mapped etc. Is the following code threadsafe ? Because when several PC-s hit several API-s at the same time I get different results for the same date. For instance when I update the number of mapped ,the number of sent gets another random variable. How can I make this code threadsafe? I presumed that setting the properties as atomic would solve the issue but I am having doubts now. Thanks

  StatisticsModel statisticsModel = new Statistics();
    String today = new SimpleDateFormat("dd-MM-yyyy").format(new Date());
    statisticsModel.setDate(today);
    List<StatisticsModel > statisticsCreate = statisticsRepository.findByDate(today);
    if (statisticsCreate .size() < 1)
        atomicLong.set(0);
    for (StatisticsModel statisticsModelRes : statisticsCreate ) {
        statisticsModel.setMapped(statisticsModelRes.getMapped());
        statisticsModel.setSent(statisticsModelRes.getSent());
    }
    statisticsModel.setReceived(atomicLong.incrementAndGet());
    statisticsRepository.upsert(statisticsModel );

Edit: I think my problem is almost similar to this one:

It's not possible to lock a mongodb document. What if I need to?


问:
how do i replace a rectangle with an image in a class for pygame
i tried multiple ways to replace the pygame.draw.rect() in this class to different ways to make it display an image instead but it doesn't seem to work so far

first try

```<code>class Enemy():
    def __init__(self, x, y, mode, dist, walk=3):
        #mode 0 = vertical
        #mode 1 = horizontal
        self.x = x
        self.y = y
        self.walk = walk
        self.mode = mode
        self.dist = dist
        self.hp = 100
        self.counter = 0
        pygame.sprite.Sprite.__init__(self)
        self.original_image = pygame.transform.scale(pygame.image.load('enemy1.png'), (100, 120))
        self.image = self.original_image
        self.rect = self.image.get_rect(center = (x, y))

    def main(self, display):
        if self.mode == 0:
            self.y += self.walk
            self.counter += 1
            if self.counter >= self.dist:
                self.counter = 0
                self.walk *= -1
        if self.mode == 1:
            self.x += self.walk
            self.counter += 1
            if self.counter >= self.dist:
                self.counter = 0
                self.walk *= -1

        pygame.draw.rect(display, (255, 0, 0), (self.x, self.y, 16, 16), True)

</code>```

this try only displayed the drawn rectangle coded for in the bottom and i don't know how to get it to be replaced by the image

Body:
i tried multiple ways to replace the pygame.draw.rect() in this class to different ways to make it display an image instead but it doesn't seem to work so far

first try

class Enemy():
    def __init__(self, x, y, mode, dist, walk=3):
        #mode 0 = vertical
        #mode 1 = horizontal
        self.x = x
        self.y = y
        self.walk = walk
        self.mode = mode
        self.dist = dist
        self.hp = 100
        self.counter = 0
        pygame.sprite.Sprite.__init__(self)
        self.original_image = pygame.transform.scale(pygame.image.load('enemy1.png'), (100, 120))
        self.image = self.original_image
        self.rect = self.image.get_rect(center = (x, y))

    def main(self, display):
        if self.mode == 0:
            self.y += self.walk
            self.counter += 1
            if self.counter >= self.dist:
                self.counter = 0
                self.walk *= -1
        if self.mode == 1:
            self.x += self.walk
            self.counter += 1
            if self.counter >= self.dist:
                self.counter = 0
                self.walk *= -1

        pygame.draw.rect(display, (255, 0, 0), (self.x, self.y, 16, 16), True)

this try only displayed the drawn rectangle coded for in the bottom and i don't know how to get it to be replaced by the image


问:
How to write iterative cumulative sums of characters in R?
i am writing a model codes with this model specification below:
enter image description here

This model contains cumulative sums of lambdas as N increases (n=1~15).

The model that I specified is like below:

```<code>    jcode <- "model{
    for (i in 1:length(N)){
    n.pos[i] ~ dbinom(seropos_est[i],N[i]) #fit to binomial data
    seropos_est[i] = ifelse(age[i]>1 && age[i]<20, 1-exp(-2.5*lambda1)
       ,ifelse(age[i]>20 && age[i]<40, 1-exp(-(5*lambda1+2.5*lambda2)),
       ifelse(age[i]>40 && age[i]<60, 1-exp(-(5*lambda1+5*lambda2+2.5*lambda3)),
       1-exp(-(5*lambda1+5*lambda2+5*lambda3+2.5*lambda4)))))
    # time-varying catalytic model
    }

    #  prior dists
  lambda1 ~ dunif(0,1)       #uninformative prior
  lambda2 ~ dunif(0,1)       #uninformative prior
  lambda3 ~ dunif(0,1)       #uninformative prior
  lambda4 ~ dunif(0,1)       #uninformative prior

}"
</code>```

However, I want to make the above equation divided into 15 different age groups with each group having cumulative sums of lambdas until (n-1).

Instead of iteratively writing down 5lambda1+5lambda2+5lambda3 .....+ 5lambda14 and so on, is there any way that I can sum up the 14 lambdas at once?

One way I considered was to store lambdas into a list and then sum up the lambdalist[1:2], lambdalist[1:3] .... lambdalist[1:14] but this doesn't work since elements inside the list are all character values, not numerical values.

I would like to reduce the iterative codes but I don't know how to specify the cumulative sums over the 15 age groups as in the model specification in the picture.

Also, is there a way that I can reduce the codes rather than using "if" function for the calculation in each age group??

Thank you

Body:
i am writing a model codes with this model specification below:
enter image description here

This model contains cumulative sums of lambdas as N increases (n=1~15).

The model that I specified is like below:

    jcode <- "model{
    for (i in 1:length(N)){
    n.pos[i] ~ dbinom(seropos_est[i],N[i]) #fit to binomial data
    seropos_est[i] = ifelse(age[i]>1 && age[i]<20, 1-exp(-2.5*lambda1)
       ,ifelse(age[i]>20 && age[i]<40, 1-exp(-(5*lambda1+2.5*lambda2)),
       ifelse(age[i]>40 && age[i]<60, 1-exp(-(5*lambda1+5*lambda2+2.5*lambda3)),
       1-exp(-(5*lambda1+5*lambda2+5*lambda3+2.5*lambda4)))))
    # time-varying catalytic model
    }

    #  prior dists
  lambda1 ~ dunif(0,1)       #uninformative prior
  lambda2 ~ dunif(0,1)       #uninformative prior
  lambda3 ~ dunif(0,1)       #uninformative prior
  lambda4 ~ dunif(0,1)       #uninformative prior

}"

However, I want to make the above equation divided into 15 different age groups with each group having cumulative sums of lambdas until (n-1).

Instead of iteratively writing down 5lambda1+5lambda2+5lambda3 .....+ 5lambda14 and so on, is there any way that I can sum up the 14 lambdas at once?

One way I considered was to store lambdas into a list and then sum up the lambdalist[1:2], lambdalist[1:3] .... lambdalist[1:14] but this doesn't work since elements inside the list are all character values, not numerical values.

I would like to reduce the iterative codes but I don't know how to specify the cumulative sums over the 15 age groups as in the model specification in the picture.

Also, is there a way that I can reduce the codes rather than using "if" function for the calculation in each age group??

Thank you


问:
How app can restore data after clearing by user?
I develop an Android application which dynamically creates some files and stores them to /data/data/{my-app}/files directory. If user cleared app data using Android Settings, all that files will be deleted. How can I persist them to be restored when user launch my app again?

I've noticed that TikTok app can store files located in it's private directory (/data/data/com.zhiliaoapp.musically/) and restore them after clearing app data. How can app do it?

I've tested such behavour on rooted Android 11 device:

cp /storage/emulated/0/Download/foo.txt /data/data/com.zhiliaoapp.musically/files/foo.txt

Clear TikTok data

Launch TikTok again

foo.txt will appear in /data/data/com.zhiliaoapp.musically/files/foo.txt

Phone has no google account and backup is disabled. Google play is disabled also.
I thought that TikTok downloads data from server. So I changed all possible identifiers (android id, advertising id, imei, etc) after clearing data and disabled Internet access, but foo.txt still restores. So it definitely persists locally.

How can I implement same behaviour in my app?


问:
Accessing a Subfolder of a Subfolder in Outlook with Python
In my main Outlook folder I have got a subfolder called 'Update' under which I've got another subfolder called 'Test'

Structure:

```<code>Inbox
    >Update
           >Test
</code>```

How can I acess a subfolder of a subfolder with Python?
I know that I can acess the mails of the folder 'Update' using win32.com with the following code:

```<code>from win32com.client import Dispatch

outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders.Item("Update")
</code>```

Now I want to access the mails of the sub-sub-folder 'Test', lets say just to print the subject of the each mail.

```<code>messages = inbox.Items
for i in msg:
    print(msg.subject)
</code>```

Body:
In my main Outlook folder I have got a subfolder called 'Update' under which I've got another subfolder called 'Test'

Structure:

Inbox
    >Update
           >Test

How can I acess a subfolder of a subfolder with Python?
I know that I can acess the mails of the folder 'Update' using win32.com with the following code:

from win32com.client import Dispatch

outlook = Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6).Folders.Item("Update")

Now I want to access the mails of the sub-sub-folder 'Test', lets say just to print the subject of the each mail.

messages = inbox.Items
for i in msg:
    print(msg.subject)


问:
salt-stack master v3005.1 with minion v3000.5 cp module problem
I have allowed 4505 and 4506 port on the master node system.
When I want to use 'cp.get_dir' to transfer a directory to minion v3000.5(CentOS6 arch), it took a long time, and then returned:

```<code>    Minion did not return. [No response]
    The minions may not have all finished running and any remaining minions will return upon completion. To look up the return data for this job later, run the following command:

    salt-run jobs.lookup_jid 20221208081502397105
</code>```

and the minion log shows:

2022-12-08 16:16:25,987 [salt.utils.parsers                                    :1082][WARNING ][21455] Minion received a SIGTERM. Exiting.
2022-12-08 16:16:28,141 [salt.minion                                           :2003][WARNING ][21819] The minion failed to return the job information for job 20221208081547958420. This is often due to the master be
ing shut down or overloaded. If the master is running, consider increasing the worker_threads value.

When I use the same command to transfer the same directory to minion v3005.1(CentOS7 arch), it works.

And I tried several CentOS6 minion nodes, got the same error returns.
It can transfer the name of first file and directory to minion, but with empty content in the file. It seems like the communication between the master and the minion is broken when the first file start to be transfered.
But when I use cmd.run module command, it works.

Body:
I have allowed 4505 and 4506 port on the master node system.
When I want to use 'cp.get_dir' to transfer a directory to minion v3000.5(CentOS6 arch), it took a long time, and then returned:

    Minion did not return. [No response]
    The minions may not have all finished running and any remaining minions will return upon completion. To look up the return data for this job later, run the following command:

    salt-run jobs.lookup_jid 20221208081502397105

and the minion log shows:

2022-12-08 16:16:25,987 [salt.utils.parsers                                    :1082][WARNING ][21455] Minion received a SIGTERM. Exiting.
2022-12-08 16:16:28,141 [salt.minion                                           :2003][WARNING ][21819] The minion failed to return the job information for job 20221208081547958420. This is often due to the master be
ing shut down or overloaded. If the master is running, consider increasing the worker_threads value.

When I use the same command to transfer the same directory to minion v3005.1(CentOS7 arch), it works.

And I tried several CentOS6 minion nodes, got the same error returns.
It can transfer the name of first file and directory to minion, but with empty content in the file. It seems like the communication between the master and the minion is broken when the first file start to be transfered.
But when I use cmd.run module command, it works.


问:
Can someone tell in kafkaJs how is default value is assigned
I have a component using kafkaJs library, it has default connectionTimeout, I have tried searching where it is set can't find, please help me find it, I know I can set it in client properties, but I want to know from where default value, comes.</p>


问:
keyv iterator not a fucntion error in npmjs keyv library
I'm using https://www.npmjs.com/package/keyv

I'm able to access individual items using key.get, but Im unable to iterator through all items.
In the below piece of code, test is printed correctly, but im unable to access keyv.iterator.

```<code>async function testReadDB()
{
  let keyv = new Keyv('sqlite://test.sqlite');
  test = await keyv.get("test_key")
  console.log(test)

  try {
    for (const [key, value] of keyv.iterator()) {
      console.log(key, value);
    };
  }
  catch (e) {
    console.log(e.message)
  }
}

</code>```

Error:
keyv.iterator is not a function or its return value is not iterable

Body:
I'm using https://www.npmjs.com/package/keyv

I'm able to access individual items using key.get, but Im unable to iterator through all items.
In the below piece of code, test is printed correctly, but im unable to access keyv.iterator.

async function testReadDB()
{
  let keyv = new Keyv('sqlite://test.sqlite');
  test = await keyv.get("test_key")
  console.log(test)

  try {
    for (const [key, value] of keyv.iterator()) {
      console.log(key, value);
    };
  }
  catch (e) {
    console.log(e.message)
  }
}

Error:
keyv.iterator is not a function or its return value is not iterable


问:
@After annotation doesnt recognize driver
As the title says I have created a Browser class where I initialize my WebDriver element with the browser I need. My issue comes in the @After class I am using that I call to close the browser window.

In my actions class I initialize the Webdriver and then I call iAmUsingBrowser to pass to my Browser class which browser I need to use

actions.java class contains the following code

```<code>Webdriver driver;

public void iAmUsingBrowser(String browser) {
driver = Browser.startBrowser(browser)
}
</code>```

Browser.java contains the following code

```<code>static WebDriver driver;

public static WebDriver startBrowser(String browserName) {
    switch (browserName.toUpperCase()) {
        case "FIREFOX" -> {
            System.setProperty("webdriver.firefox.geckodriver", "src/main/java/BrowserFiles/geckodriver.exe");
            driver = new FirefoxDriver();
        }
        case "EDGE" -> {
            System.setProperty("webdriver.edge.driver", "src/main/java/BrowserFiles/msedgedriver.exe");
            driver = new EdgeDriver();
        }
        case "SAFARI" -> {
            System.setProperty("webdriver.safari.driver", "");
            driver = new SafariDriver();
        }
        default -> {
            System.setProperty("webdriver.chrome.driver", "src/main/java/BrowserFiles/chromedriver.exe");
            driver = new ChromeDriver();
        }
    }
    return driver;
}
</code>```

My issue comes in the actions.java class where i want to call driver.quit() and close the browser window.

```<code>@After
public void destroy() {
 driver.quit();
}
</code>```

When I use the above lines I get a nullPointerException for driver, but everywhere else I can use driver without any issues. What am I doing wrong and in my @After annotated class driver is null?

Body:
As the title says I have created a Browser class where I initialize my WebDriver element with the browser I need. My issue comes in the @After class I am using that I call to close the browser window.

In my actions class I initialize the Webdriver and then I call iAmUsingBrowser to pass to my Browser class which browser I need to use

actions.java class contains the following code

Webdriver driver;

public void iAmUsingBrowser(String browser) {
driver = Browser.startBrowser(browser)
}

Browser.java contains the following code

static WebDriver driver;

public static WebDriver startBrowser(String browserName) {
    switch (browserName.toUpperCase()) {
        case "FIREFOX" -> {
            System.setProperty("webdriver.firefox.geckodriver", "src/main/java/BrowserFiles/geckodriver.exe");
            driver = new FirefoxDriver();
        }
        case "EDGE" -> {
            System.setProperty("webdriver.edge.driver", "src/main/java/BrowserFiles/msedgedriver.exe");
            driver = new EdgeDriver();
        }
        case "SAFARI" -> {
            System.setProperty("webdriver.safari.driver", "");
            driver = new SafariDriver();
        }
        default -> {
            System.setProperty("webdriver.chrome.driver", "src/main/java/BrowserFiles/chromedriver.exe");
            driver = new ChromeDriver();
        }
    }
    return driver;
}

My issue comes in the actions.java class where i want to call driver.quit() and close the browser window.

@After
public void destroy() {
 driver.quit();
}

When I use the above lines I get a nullPointerException for driver, but everywhere else I can use driver without any issues. What am I doing wrong and in my @After annotated class driver is null?