问:
How to fix "Non-exhaustive switch expression failed to match its input. Unmatched value was Unchanged."
A user can add an event they want to their favorites. Below are the entities I have opened for this and the links between them.

Event:

```<code>public class Event : EntitySoftDeletableIntKey
{
    public string Title { get; set; }
    public string ShortContent { get; set; }
    public string Place { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public int EventDetailId { get; set; }
    public EventDetail EventDetail { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
    public List<Tag>? Tags { get; set; } = new List<Tag>();
    public List<Comment>? Comments { get; set; } = new List<Comment>();
    public ApplicationUser? ApplicationUser { get; set; }
    public int? ApplicationUserId { get; set; }
    public List<AttendedEvent>? AttendedEvents { get; set; } = new List<AttendedEvent>();
    public List<FavoriteEvent>? FavoriteEvents { get; set; }

}
</code>```

User:

```<code>public class ApplicationUser : IdentityUser<int>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<FavoriteEvent>? FavoriteEvents { get; set; } = new List<FavoriteEvent>();
    public List<Event>? Events { get; set; } = new List<Event>();
    public List<AttendedEvent>? AttendedEvents { get; set; } = new List<AttendedEvent>();
}
</code>```

FavoriteEvent :

```<code>public class FavoriteEvent : EntitySoftDeletableIntKey
{
    public int? EventId;

    public Event? Event;
    public int? ApplicationUserId { get; set; }
    public ApplicationUser? ApplicationUser { get; set; }
}
</code>```

Link Bbetween :

```<code>modelBuilder.Entity<FavoriteEvent>()
            .HasKey(fe => new { fe.EventId, fe.ApplicationUserId });
modelBuilder.Entity<FavoriteEvent>()
            .HasOne(fe => fe.Event)
            .WithMany(e => e.FavoriteEvents)
            .HasForeignKey(ae => ae.EventId).OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<FavoriteEvent>()
            .HasOne(fe => fe.ApplicationUser)
            .WithMany(u => u.FavoriteEvents)
            .HasForeignKey(fe => fe.ApplicationUserId).OnDelete(DeleteBehavior.Restrict);
</code>```

When the user adds an event to the favoriteevent list, I get the error in the header. I couldn't solve it anyway. Thank you in advance for your help.

```<code>public async Task<Unit> Handle(AddEventToFavCommandRequest request, CancellationToken cancellationToken)
{
    var @event = await _unitOfWork.GetReadRepository<Event>().GetSingle(e => e.Id == request.EventId);

    var currentUser = await _userManager.Users.FirstOrDefaultAsync(u => u.Id == request.ApplicationUserId);

    currentUser.FavoriteEvents.Add(new FavoriteEvent()
    {
        EventId = @event.Id,
        ApplicationUserId = currentUser.Id
    });

    return Unit.Value;
}
</code>```
```<code>public async Task<int> Save(CancellationToken cancellationToken = new CancellationToken())
{
    var datas = _context.ChangeTracker.Entries<EntitySoftDeletableIntKey>();
    foreach (var data in datas)
    {
        _ = data.State switch
        {
            EntityState.Added => data.Entity.CreatedDate = DateTime.UtcNow,
            EntityState.Modified => data.Entity.ModifiedDate = DateTime.UtcNow,
        };
    }

    return await _context.SaveChangesAsync(cancellationToken);
}
</code>```

Body:
A user can add an event they want to their favorites. Below are the entities I have opened for this and the links between them.

Event:

public class Event : EntitySoftDeletableIntKey
{
    public string Title { get; set; }
    public string ShortContent { get; set; }
    public string Place { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public int EventDetailId { get; set; }
    public EventDetail EventDetail { get; set; }
    public int CategoryId { get; set; }
    public Category Category { get; set; }
    public List<Tag>? Tags { get; set; } = new List<Tag>();
    public List<Comment>? Comments { get; set; } = new List<Comment>();
    public ApplicationUser? ApplicationUser { get; set; }
    public int? ApplicationUserId { get; set; }
    public List<AttendedEvent>? AttendedEvents { get; set; } = new List<AttendedEvent>();
    public List<FavoriteEvent>? FavoriteEvents { get; set; }

}

User:

public class ApplicationUser : IdentityUser<int>
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public List<FavoriteEvent>? FavoriteEvents { get; set; } = new List<FavoriteEvent>();
    public List<Event>? Events { get; set; } = new List<Event>();
    public List<AttendedEvent>? AttendedEvents { get; set; } = new List<AttendedEvent>();
}

FavoriteEvent :

public class FavoriteEvent : EntitySoftDeletableIntKey
{
    public int? EventId;

    public Event? Event;
    public int? ApplicationUserId { get; set; }
    public ApplicationUser? ApplicationUser { get; set; }
}

Link Bbetween :

modelBuilder.Entity<FavoriteEvent>()
            .HasKey(fe => new { fe.EventId, fe.ApplicationUserId });
modelBuilder.Entity<FavoriteEvent>()
            .HasOne(fe => fe.Event)
            .WithMany(e => e.FavoriteEvents)
            .HasForeignKey(ae => ae.EventId).OnDelete(DeleteBehavior.Restrict);
modelBuilder.Entity<FavoriteEvent>()
            .HasOne(fe => fe.ApplicationUser)
            .WithMany(u => u.FavoriteEvents)
            .HasForeignKey(fe => fe.ApplicationUserId).OnDelete(DeleteBehavior.Restrict);

When the user adds an event to the favoriteevent list, I get the error in the header. I couldn't solve it anyway. Thank you in advance for your help.

public async Task<Unit> Handle(AddEventToFavCommandRequest request, CancellationToken cancellationToken)
{
    var @event = await _unitOfWork.GetReadRepository<Event>().GetSingle(e => e.Id == request.EventId);

    var currentUser = await _userManager.Users.FirstOrDefaultAsync(u => u.Id == request.ApplicationUserId);

    currentUser.FavoriteEvents.Add(new FavoriteEvent()
    {
        EventId = @event.Id,
        ApplicationUserId = currentUser.Id
    });

    return Unit.Value;
}

public async Task<int> Save(CancellationToken cancellationToken = new CancellationToken())
{
    var datas = _context.ChangeTracker.Entries<EntitySoftDeletableIntKey>();
    foreach (var data in datas)
    {
        _ = data.State switch
        {
            EntityState.Added => data.Entity.CreatedDate = DateTime.UtcNow,
            EntityState.Modified => data.Entity.ModifiedDate = DateTime.UtcNow,
        };
    }

    return await _context.SaveChangesAsync(cancellationToken);
}


来源: stackexchange

问:
HuggingFace Transformers for regression
I am working on a regression problem and I am looking forward to using Transformers for it but before jumping into the implementation and all stuff, I am curious that did any of you use transformers for a regression problem? I have around 90 features (floating points) and one target. I couldn’t find any paper on transformers for regression problems so please let me know if any of you used transformers for this purpose.

I am working on a problem where I am having tabular data having more than 90 features and one target and all the features are in integers (continuous). I want to use pre-trained BERT, GPT2 but when it comes to the tokenizer the tokenizer is expecting the input in the text format. I can change the integer data in the text format like this:

original_data    = [1,2,3,4,5,…,94]
transformed_data = ["1,2,3,4,5,…,94"]
```

Now if I pass the transformed_data to the tokenizer then surely it will work but I wanna know if someone tried to use transformers for this purpose and if yes, then what was the outcome, and how did the results look like?

How can I use huggingface transformer library for this purpose all the tokenizers are trained for the text data so I am kinda lost. Any help will be appreciated. Thanks

ContentLicense: CC BY-SA 4.0

Title: HuggingFace Transformers for regression

Body:
I am working on a regression problem and I am looking forward to using Transformers for it but before jumping into the implementation and all stuff, I am curious that did any of you use transformers for a regression problem? I have around 90 features (floating points) and one target. I couldn’t find any paper on transformers for regression problems so please let me know if any of you used transformers for this purpose.

I am working on a problem where I am having tabular data having more than 90 features and one target and all the features are in integers (continuous). I want to use pre-trained BERT, GPT2 but when it comes to the tokenizer the tokenizer is expecting the input in the text format. I can change the integer data in the text format like this:

original_data    = [1,2,3,4,5,…,94]
transformed_data = ["1,2,3,4,5,…,94"]

Now if I pass the transformed_data to the tokenizer then surely it will work but I wanna know if someone tried to use transformers for this purpose and if yes, then what was the outcome, and how did the results look like?

How can I use huggingface transformer library for this purpose all the tokenizers are trained for the text data so I am kinda lost. Any help will be appreciated. Thanks


问:
Unity Localization getting stuck on Black Screen in IOS
enter image description hereLocalization is working fine on Editor but Upon running the Build of IOS game is stuck on black screen after the splash screen with following logs in Xcode.

I followed the guide, Build the addressables and included the meta data for IOS and its working fin in editor.


问:
Test flux endpoint with WebTestClient
I am experiencing a problem doing an integration test on a responsive endpoint using spring and Flux.
Specifically, it is a simple chat mechanism.
I have one endpoint that exposes a Flux object of Messages and a second endpoint that, via post, publishes the message on the flux object.
Below are the service class and controller

package com.giane.reactiveangularchat.core.usecases;

import com.giane.reactiveangularchat.core.entities.Message;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;

@Service
public class MessageService {
    private final Sinks.Many<Message> sink;

    public MessageService() {
        sink = Sinks.many().multicast().directAllOrNothing();
    }

    public void save(Message message) {
        sink.emitNext(message, Sinks.EmitFailureHandler.FAIL_FAST);
        sink.tryEmitNext(message);
    }

    /**
     * This method return a Flux of ServerSentEvent. The ServerSentEvent is a reactive stream filtered by user.
     * @param user the user to filter the stream
     * @return a Flux of ServerSentEvent
     */
    public Flux<ServerSentEvent<Message>> getMessage(String project) {
        return sink.asFlux()
            .filter(message -> message.getTo().equals(project))
            .map(message -> ServerSentEvent.builder(message).build());
    }
}
```
<pre class="lang-java prettyprint-override"><code>package com.giane.reactiveangularchat.entrypoints.rest;

import com.giane.reactiveangularchat.core.entities.Message;
import com.giane.reactiveangularchat.core.usecases.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.net.URI;

@RestController
@RequestMapping("/api/messages")
@CrossOrigin(originPatterns = "*", allowedHeaders = "*")
@Slf4j
public class MessageController {
    private final MessageService messageService;

    public MessageController(MessageService messageService) {
        this.messageService = messageService;
    }

    @PostMapping
    public ResponseEntity<Message> postMessage(@RequestBody Message message) {
        log.info("Received message {}", message);
        messageService.save(message);
        return ResponseEntity.created(URI.create("")).body(message);
    }

    @GetMapping(path = "/stream/{user}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<Message>> getMessages(@PathVariable String user) {
        log.info("Received request for user {}", user);
        return messageService.getMessage(user);
    }
}
</code>```

My test should involve the following flow.

Connection to the flux endpoint.

Sending the message

Checking the received message on the stream

The following is the test method.

@Test
    void contextLoads3() throws InterruptedException {

        FluxExchangeResult<Message> fluxFluxExchangeResult = webTestClient.get()
            .uri("/api/messages/stream/user1").exchange().expectStatus().is2xxSuccessful().returnResult(Message.class);
        Flux<Message> messages = fluxFluxExchangeResult.getResponseBody();

        webTestClient.post().uri("/api/messages").bodyValue(new Message("message", "user1")).exchange().expectStatus().is2xxSuccessful();

        StepVerifier
            .create(messages)
            .expectSubscription()
            .assertNext(it->{
                assertThat(it).isNotNull();
                assertThat(it.getMessageContent()).isEqualTo("message");
                assertThat(it.getTo()).isEqualTo("user1");
            })
            .thenCancel()
            .verify(Duration.ofSeconds(10));
    }
```

My problem now is that webtestclient's exchange method is blocked until the first event is received. But I cannot send the first event until the exchange method unlocks.

Can someone explain how I can test this use case?

Title: Test flux endpoint with WebTestClient

Body:
I am experiencing a problem doing an integration test on a responsive endpoint using spring and Flux.
Specifically, it is a simple chat mechanism.
I have one endpoint that exposes a Flux object of Messages and a second endpoint that, via post, publishes the message on the flux object.
Below are the service class and controller

package com.giane.reactiveangularchat.core.usecases;

import com.giane.reactiveangularchat.core.entities.Message;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;

@Service
public class MessageService {
    private final Sinks.Many<Message> sink;

    public MessageService() {
        sink = Sinks.many().multicast().directAllOrNothing();
    }

    public void save(Message message) {
        sink.emitNext(message, Sinks.EmitFailureHandler.FAIL_FAST);
        sink.tryEmitNext(message);
    }

    /**
     * This method return a Flux of ServerSentEvent. The ServerSentEvent is a reactive stream filtered by user.
     * @param user the user to filter the stream
     * @return a Flux of ServerSentEvent
     */
    public Flux<ServerSentEvent<Message>> getMessage(String project) {
        return sink.asFlux()
            .filter(message -> message.getTo().equals(project))
            .map(message -> ServerSentEvent.builder(message).build());
    }
}

package com.giane.reactiveangularchat.entrypoints.rest;

import com.giane.reactiveangularchat.core.entities.Message;
import com.giane.reactiveangularchat.core.usecases.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.net.URI;

@RestController
@RequestMapping("/api/messages")
@CrossOrigin(originPatterns = "*", allowedHeaders = "*")
@Slf4j
public class MessageController {
    private final MessageService messageService;

    public MessageController(MessageService messageService) {
        this.messageService = messageService;
    }

    @PostMapping
    public ResponseEntity<Message> postMessage(@RequestBody Message message) {
        log.info("Received message {}", message);
        messageService.save(message);
        return ResponseEntity.created(URI.create("")).body(message);
    }

    @GetMapping(path = "/stream/{user}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<ServerSentEvent<Message>> getMessages(@PathVariable String user) {
        log.info("Received request for user {}", user);
        return messageService.getMessage(user);
    }
}

My test should involve the following flow.

Connection to the flux endpoint.

Sending the message

Checking the received message on the stream

The following is the test method.

@Test
    void contextLoads3() throws InterruptedException {

        FluxExchangeResult<Message> fluxFluxExchangeResult = webTestClient.get()
            .uri("/api/messages/stream/user1").exchange().expectStatus().is2xxSuccessful().returnResult(Message.class);
        Flux<Message> messages = fluxFluxExchangeResult.getResponseBody();

        webTestClient.post().uri("/api/messages").bodyValue(new Message("message", "user1")).exchange().expectStatus().is2xxSuccessful();

        StepVerifier
            .create(messages)
            .expectSubscription()
            .assertNext(it->{
                assertThat(it).isNotNull();
                assertThat(it.getMessageContent()).isEqualTo("message");
                assertThat(it.getTo()).isEqualTo("user1");
            })
            .thenCancel()
            .verify(Duration.ofSeconds(10));
    }

My problem now is that webtestclient's exchange method is blocked until the first event is received. But I cannot send the first event until the exchange method unlocks.

Can someone explain how I can test this use case?


问:
Cannot modified data frame to desired structure using if-else statements
I have a data set like this

```<code>data = {'Name': ['Ron','Charlie','Harry','Hermione','Luna','Hagrid','Draco']}
kdf = pd.DataFrame(data)
</code>```

After this I add a column to my data frame as

```<code>kdf['x'] = 0
</code>```

Now I want to fill the column x with 1's in specific places according to the list below

```<code>ls = [True, True , False, True, False, False, False]
</code>```

For example I want 1's to be in Ron,Charlie and Hermione's row for that I wrote the below code

```<code>for i in ls:
    if i:
        kdf['x'] = 1
        print(i)
    else:
        kdf['x'] = 0
</code>```

But the data set after this modification had 0's in all rows of column x, if I change 0 to 2 in else statement all rows in column x has 2, if I remove else statement complete all rows of column x have 1's in them

I don't understand why is this happening I also added print(i) in if statement to see if all of them are somehow understood as True but print(i) returns 3 True's so that seems okay.

I was expecting to my data frame to be modified such that could x has 1's in 1st, 2nd and 4th row but I am getting 1's in all rows of column x;if I change 0 to 2 in else statement all rows in column x has 2, if I remove else statement complete all rows of column x have 1's in them;I also added print(i) in if statement to see if all of them are somehow understood as True but print(i) returns 3 True's so that seems okay.

Edit: Someone suggested me this link Pandas conditional creation of a series/dataframe column and this is great I appreciate it but I want to understand what is the problem with my code not working in desired way.

Body:
I have a data set like this

data = {'Name': ['Ron','Charlie','Harry','Hermione','Luna','Hagrid','Draco']}
kdf = pd.DataFrame(data)

After this I add a column to my data frame as

kdf['x'] = 0

Now I want to fill the column x with 1's in specific places according to the list below

ls = [True, True , False, True, False, False, False]

For example I want 1's to be in Ron,Charlie and Hermione's row for that I wrote the below code

for i in ls:
    if i:
        kdf['x'] = 1
        print(i)
    else:
        kdf['x'] = 0

But the data set after this modification had 0's in all rows of column x, if I change 0 to 2 in else statement all rows in column x has 2, if I remove else statement complete all rows of column x have 1's in them

I don't understand why is this happening I also added print(i) in if statement to see if all of them are somehow understood as True but print(i) returns 3 True's so that seems okay.

I was expecting to my data frame to be modified such that could x has 1's in 1st, 2nd and 4th row but I am getting 1's in all rows of column x;if I change 0 to 2 in else statement all rows in column x has 2, if I remove else statement complete all rows of column x have 1's in them;I also added print(i) in if statement to see if all of them are somehow understood as True but print(i) returns 3 True's so that seems okay.

Edit: Someone suggested me this link Pandas conditional creation of a series/dataframe column and this is great I appreciate it but I want to understand what is the problem with my code not working in desired way.


问:
Android reading a 917KB file from web causes memory error?
```<code>            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()),1024*32);

            StringBuffer sb = new StringBuffer();

            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line.replace("  ", ""));
            }
            rd.close();
            result = sb.toString();
</code>```

I am suspecting that it is the fact that too many strings are being created. How can i see wether a readline is possible and stick the lineread straight into the stringbuilder. What other way is there to do this?  The file is just under 1MB

Here is the log:

09-27 12:56:07.740: ERROR/ERROR: Problem in LDataListView: refreshError
09-27 12:56:07.740: ERROR/ERROR: -------------------------------------------
09-27 12:56:13.339: ERROR/Dhcpcd(10598): sending DHCP_REQUEST with xid 0x5a93b3de, next in 3.58 seconds
09-27 12:56:13.549: ERROR/dalvikvm-heap(12862): Out of memory on a 6064234-byte allocation.
09-27 12:56:13.549: ERROR/dalvikvm(12862): Out of memory: Heap Size=15687KB, Allocated=6704KB, Bitmap Size=8617KB
09-27 12:56:13.559: ERROR/AndroidRuntime(12862): FATAL EXCEPTION: main
09-27 12:56:13.559: ERROR/AndroidRuntime(12862): java.lang.OutOfMemoryError
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:97)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:117)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at java.lang.StringBuilder.append(StringBuilder.java:250)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at se.brickit.foundation.data.BrHttpClient.sendGetRequest(BrHttpClient.java:56)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at se.brickit.foundation.data.BrDataProvider.(BrDataProvider.java:100)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at se.brickit.foundation.iviews.LisaDataListView$RefreshTask.onPostExecute(LisaDataListView.java:110)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at se.brickit.foundation.iviews.LisaDataListView$RefreshTask.onPostExecute(LisaDataListView.java:1)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at android.os.AsyncTask.finish(AsyncTask.java:417)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at android.os.Looper.loop(Looper.java:144)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at android.app.ActivityThread.main(ActivityThread.java:4937)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at java.lang.reflect.Method.invokeNative(Native Method)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at java.lang.reflect.Method.invoke(Method.java:521)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at dalvik.system.NativeStart.main(Native Method)
09-27 12:56:14.819: ERROR/ActivityManager(101): fail to set top app changed!
09-27 12:56:48.499: ERROR/BluetoothHeadsetService(201): java.util.NoSuchElementException

Edit:::

more info:

It is a JSON string. basically a single object with an array of items.  The whole feed is littered with encoded images which makes it much larger than it should be (unfortuntely it is not my feed). the iphone seem to read it, but my HTC phone does sometimes, but usually hits a memory exception on the sb append line.

I have also tried just a straight read on it eg:

```<code>            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            InputStream iFile = conn.getInputStream();

            result = inputStreamToString(iFile);
</code>```

but same problem there too.

ContentLicense: CC BY-SA 3.0

Body:
            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()),1024*32);

            StringBuffer sb = new StringBuffer();

            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line.replace("  ", ""));
            }
            rd.close();
            result = sb.toString();

I am suspecting that it is the fact that too many strings are being created. How can i see wether a readline is possible and stick the lineread straight into the stringbuilder. What other way is there to do this?  The file is just under 1MB

Here is the log:

09-27 12:56:07.740: ERROR/ERROR: Problem in LDataListView: refreshError
09-27 12:56:07.740: ERROR/ERROR: -------------------------------------------
09-27 12:56:13.339: ERROR/Dhcpcd(10598): sending DHCP_REQUEST with xid 0x5a93b3de, next in 3.58 seconds
09-27 12:56:13.549: ERROR/dalvikvm-heap(12862): Out of memory on a 6064234-byte allocation.
09-27 12:56:13.549: ERROR/dalvikvm(12862): Out of memory: Heap Size=15687KB, Allocated=6704KB, Bitmap Size=8617KB
09-27 12:56:13.559: ERROR/AndroidRuntime(12862): FATAL EXCEPTION: main
09-27 12:56:13.559: ERROR/AndroidRuntime(12862): java.lang.OutOfMemoryError
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:97)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:117)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at java.lang.StringBuilder.append(StringBuilder.java:250)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at se.brickit.foundation.data.BrHttpClient.sendGetRequest(BrHttpClient.java:56)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at se.brickit.foundation.data.BrDataProvider.(BrDataProvider.java:100)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at se.brickit.foundation.iviews.LisaDataListView$RefreshTask.onPostExecute(LisaDataListView.java:110)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at se.brickit.foundation.iviews.LisaDataListView$RefreshTask.onPostExecute(LisaDataListView.java:1)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at android.os.AsyncTask.finish(AsyncTask.java:417)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at android.os.Looper.loop(Looper.java:144)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at android.app.ActivityThread.main(ActivityThread.java:4937)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at java.lang.reflect.Method.invokeNative(Native Method)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at java.lang.reflect.Method.invoke(Method.java:521)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-27 12:56:13.559: ERROR/AndroidRuntime(12862):     at dalvik.system.NativeStart.main(Native Method)
09-27 12:56:14.819: ERROR/ActivityManager(101): fail to set top app changed!
09-27 12:56:48.499: ERROR/BluetoothHeadsetService(201): java.util.NoSuchElementException

Edit:::

more info:

It is a JSON string. basically a single object with an array of items.  The whole feed is littered with encoded images which makes it much larger than it should be (unfortuntely it is not my feed). the iphone seem to read it, but my HTC phone does sometimes, but usually hits a memory exception on the sb append line.

I have also tried just a straight read on it eg:

            URL url = new URL(urlStr);
            URLConnection conn = url.openConnection();
            InputStream iFile = conn.getInputStream();

            result = inputStreamToString(iFile);

but same problem there too.


问:
How to use PIL (pillow) with libraqm in AWS Lambda?
I have a simple code which writes some text on an image. I have uploaded all the required files as a zip package and the imported dependencies as layers.

One dependency - PIL needs libraqm to work and I am unable to figure out how to add that dependency. In my local system I installed libraqm with apt.

What I tried till now

Downloaded libraqm v 0.6 by using an unofficial rpm build. It did not resolve the issue.

Manually build the latest libraqm from the official github source. Did not work.

Thanks in advance


问:
Untrusted data is embedded straight into the output
I am currently facing Checkmarx scan issue for the below snippet:

The application's getResponse embeds untrusted data in the generated output with setCatList, at line 10 of MyClass.java.
This untrusted data is embedded straight into the output without proper sanitization or encoding, enabling an attacker to inject malicious code into the output.
This can enable a Reflected Cross-Site Scripting (XSS) attack.

GetCatSP sp = getCatSP(); // GetCatSP extends StoredProcedure
Map<String, Object> output = sp.getMyData(inParams); // This executes super.execute(inParams) and returns it
List<Cat> catList = (List<Cat>) output.get("cat_info");

response.setCatList(catList);
```

How do I handle this?

Body:
I am currently facing Checkmarx scan issue for the below snippet:

The application's getResponse embeds untrusted data in the generated output with setCatList, at line 10 of MyClass.java.
This untrusted data is embedded straight into the output without proper sanitization or encoding, enabling an attacker to inject malicious code into the output.
This can enable a Reflected Cross-Site Scripting (XSS) attack.

GetCatSP sp = getCatSP(); // GetCatSP extends StoredProcedure
Map<String, Object> output = sp.getMyData(inParams); // This executes super.execute(inParams) and returns it
List<Cat> catList = (List<Cat>) output.get("cat_info");

response.setCatList(catList);

How do I handle this?


问:
Using lag and call it in efcore
How I can calculate the differences of multiple rows which are contain datetime by using lag in SQl and use it in EfCore

I try to grouping multiple rows and use lag function

Title: Using lag and call it in efcore


问:
DateTime::diff() expects parameter 1 to be DateTimeInterface, bool given
Every $firstTransaction is different, but comes is essentially just an array of dates generated by  date('Y-m-d H:i:s', time()) and the first is used.

This code has worked flawlessly before, but I just moved hosting providers and this one seems to be giving me trouble even though the PHP version is exactly the same as the last host.

```<code>$start_date = new DateTime();
$ts1 = $start_date->createFromFormat('Y-m-d H:i:s', $firstTransaction[0]);
$ts2 = new DateTime('now');

$diff = $ts2->diff($ts1);
</code>```

The error in question:

```<code>DateTime::diff() expects parameter 1 to be DateTimeInterface, bool given
</code>```

Any help would be appreciated as I am at a total loss.

EDIT: The exact date in question was:

```<code>$firstTransaction[0] = '2023-01-03 00:55:15';
</code>```

Body:
Every $firstTransaction is different, but comes is essentially just an array of dates generated by  date('Y-m-d H:i:s', time()) and the first is used.

This code has worked flawlessly before, but I just moved hosting providers and this one seems to be giving me trouble even though the PHP version is exactly the same as the last host.

$start_date = new DateTime();
$ts1 = $start_date->createFromFormat('Y-m-d H:i:s', $firstTransaction[0]);
$ts2 = new DateTime('now');

$diff = $ts2->diff($ts1);

The error in question:

DateTime::diff() expects parameter 1 to be DateTimeInterface, bool given

Any help would be appreciated as I am at a total loss.

EDIT: The exact date in question was:

$firstTransaction[0] = '2023-01-03 00:55:15';


问:
Chrome devtools crashing
I have a MacOS 12.6 running Chrome 108.0.5359.124 and when I open this page, open developer tools -> search everywhere tab, and try to search for availability, devtools consistently crashes. Can this be fixed?

So far I've tried:

Opening in incognito mode

Vivaldi browser

Opening in VirtualBox Win10

Opening different pages on same site.

Nothing helped. Works fine on different sites.

Title: Chrome devtools crashing


问:
How plot a inflexible violin plot with unsoft transition?
Normal violin plots have a soft transition.

I want to plot a violin plot with unsoft transition.
Just like the violin plot below:


问:
Vitepress deploy on vercel
when I deploy my Vitepress project on Vercel, it deploys incompletely. For example, a menu does not appear. Any ideas?

when i deploy on vercel

it's should be

thanks.

i try redeploying, yarn..npm..

Title: Vitepress deploy on vercel


问:
How to generate a form based on a configuration and retrieve all values from it on submit?
When launching my Vue 3 app it asks for a configuration from an external API. This returns an array of

```<code>interface FieldConfig {
  fieldId: string;
  dataType: 'string' | 'boolean' | 'number';
  defaultValueFunction?: () => Promise<unknown> | unknown;
}
</code>```

Based on those field configurations I want to create a form ( where each dataType decides which input to render ) and whenever I click the submit button I want the form to collect all the field values so I can add them as a payload to a POST request body.

Since everything should be reactive and the communication should be bidirectional I'm struggling to create a form with v-models out of nowhere so I started with a basic component rendering the a single input

FormField.vue

```<code><script setup lang="ts">
import { FieldConfig } from "./FieldConfig.ts";

defineProps<{
  fieldConfiguration: FieldConfig;
  fieldValue: boolean | string | number | null | undefined
}>();

const emit = defineEmits<{
  (e: "update:modelValue", newValue: boolean | string | number | null | undefined): void;
}>();

function emitNewValue(newValue: boolean | string | number | null | undefined) {
  emit("update:modelValue", newValue);
}
</script>

<template>
  <v-checkbox v-if="fieldConfiguration.dataType === 'boolean'" label="boolean" :model-value="fieldValue" @update:modelValue="emitNewValue" />
  <v-text-field v-else-if="fieldConfiguration.dataType === 'number'" type="number" label="number or null" :model-value="fieldValue" clearable @update:modelValue="emitNewValue" />
  <v-text-field v-else-if="fieldConfiguration.dataType === 'string'" label="string or null" :model-value="fieldValue" clearable @update:modelValue="emitNewValue" />
</template>
</code>```

Now the tricky part: I created a form that must be able to hold all the field values based on the props ( holding the field configurations ). You will see that I created a local ref variable holding all the form values. I initialize the variable inside the onMounted hook

CreateForm.vue

```<code><script setup lang="ts">
import { ref, onMounted } from "vue";
import { FieldConfig } from "./FieldConfig.ts";
import FormField from "./FormField.vue";

const props = defineProps<{
  fieldConfigurations: FieldConfig[]
}>();

const emit = defineEmits<{
  (e: "create", payload: Record<string, unknown>): void;
}>();

const createForm = ref<VForm>();
const payload: [string, unknown][] = ref([]);

onMounted(() => {
  resetForm();
});

function create() {
  let payloadAsRecord: Record<string, unknown> = {};

  payload.value.forEach(([fieldId, fieldValue]) => {
        payloadAsRecord[fieldId] = fieldValue;
  });

  emit("create", payloadAsRecord);

  resetForm();
}

function onValueChanged(fieldId: string, newValue: unknown) {
  payload.value = payload.value.map(([currentFieldId, currentFieldValue]) => {
    if(currentFieldId === fieldId) {
        return [currentFieldId, newValue];
    }

    return [currentFieldId, currentFieldValue];
  });
}

/* async */ function resetForm() {
  payload.value = props.fieldConfigurations.map(fieldConfiguration => {
    let initialValue = null;

    if(fieldConfiguration.dataType === 'boolean') {
      initialValue = false;
    }

    // call async defaultValueFunction if defined

    return [fieldConfiguration.fieldId, initialValue];
  });
}
</script>

<template>
    <v-card>
      <v-card-text>
        <v-form ref="createForm">
          <form-field
            v-for="([fieldId, fieldValue], fieldIndex) in payload"
            :key="fieldIndex"
            :fieldConfiguration="fieldConfigurations.find(fieldConfig => fieldConfig.fieldId === fieldId)!"
            :fieldValue="fieldValue"
            @update:modelValue="onValueChanged(fieldId, $event)"
          />
        </v-form>
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn @click="create">Submit</v-btn>
      </v-card-actions>
    </v-card>
</template>
</code>```

For testing purposes I consume this form component with the following mock data

```<code>const fieldConfigurations: Ref<FieldConfig[]> = ref([
  { fieldId: 'field-1', dataType: 'boolean' },
  { fieldId: '2', dataType: 'string', defaultValueFunction: () => 'foo' },
  { fieldId: 'numeric', dataType: 'number', defaultValueFunction: async () => {
    await new Promise(resolve => setTimeout(resolve, 1000));

    return 42;
  }}
]);
</code>```

You can play around with the code here

I would like to know if there are any better ways to solve this. I think the component runs into troubles whenever the props change because the onMounted hook does not run again.

And maybe I don't even know the local payload ref variable because this can be solved "smarter"... I basically want to generate a form based on the field configurations and ask the form for all values whenever I want to submit them.

Body:
When launching my Vue 3 app it asks for a configuration from an external API. This returns an array of

interface FieldConfig {
  fieldId: string;
  dataType: 'string' | 'boolean' | 'number';
  defaultValueFunction?: () => Promise<unknown> | unknown;
}

Based on those field configurations I want to create a form ( where each dataType decides which input to render ) and whenever I click the submit button I want the form to collect all the field values so I can add them as a payload to a POST request body.

Since everything should be reactive and the communication should be bidirectional I'm struggling to create a form with v-models out of nowhere so I started with a basic component rendering the a single input

FormField.vue

<template>
  <v-checkbox v-if="fieldConfiguration.dataType === 'boolean'" label="boolean" :model-value="fieldValue" @update:modelValue="emitNewValue" />
  <v-text-field v-else-if="fieldConfiguration.dataType === 'number'" type="number" label="number or null" :model-value="fieldValue" clearable @update:modelValue="emitNewValue" />
  <v-text-field v-else-if="fieldConfiguration.dataType === 'string'" label="string or null" :model-value="fieldValue" clearable @update:modelValue="emitNewValue" />
</template>

Now the tricky part: I created a form that must be able to hold all the field values based on the props ( holding the field configurations ). You will see that I created a local ref variable holding all the form values. I initialize the variable inside the onMounted hook

CreateForm.vue

<template>
    <v-card>
      <v-card-text>
        <v-form ref="createForm">
          <form-field
            v-for="([fieldId, fieldValue], fieldIndex) in payload"
            :key="fieldIndex"
            :fieldConfiguration="fieldConfigurations.find(fieldConfig => fieldConfig.fieldId === fieldId)!"
            :fieldValue="fieldValue"
            @update:modelValue="onValueChanged(fieldId, $event)"
          />
        </v-form>
      </v-card-text>
      <v-card-actions>
        <v-spacer />
        <v-btn @click="create">Submit</v-btn>
      </v-card-actions>
    </v-card>
</template>

For testing purposes I consume this form component with the following mock data

const fieldConfigurations: Ref<FieldConfig[]> = ref([
  { fieldId: 'field-1', dataType: 'boolean' },
  { fieldId: '2', dataType: 'string', defaultValueFunction: () => 'foo' },
  { fieldId: 'numeric', dataType: 'number', defaultValueFunction: async () => {
    await new Promise(resolve => setTimeout(resolve, 1000));

    return 42;
  }}
]);

You can play around with the code <a href="https://play.vuetifyjs.com/#eNq9WF1v2zYU/SucMCBOYEtp1+1BdbIUQQPkYcPQFX2J/CBLVKJFIgWKchJk/u87/LJES2ncAmseAvHy8twPXh5e+uY5+NA04aajQRwsJa2bKpX0PGGELDeLtGn0px7UacnsCONMUCguCi5qEhclrfJLzorythOpLDlrz5JgQpoE5MKsxLz5gChyRqKBFTUw9pfRwC8M20yUjSQtlV1DqpTdAksCGrNl3XAhyTMRtJiTT7QgW1IIXpMjRHg0mL/qfXMqSRBGA3GoIN/vllxqZ69UuDvtXqYSqLUTliFMSSZij5U/y4GFm9U5OVOezm5UwM9m0XUekyP9tXhzNCd5KtPPTw2FcM15RVN2RLbzff23vmYrRclulYwWaVfJL2nV0auOZcqRmMyOydk5jHA+hcW6mooy8xEhXFPxImLaPrHM4j6bzUwf0lISRh/IX8hX2dKZoC2vNlTpYO8+lzXlnXTSOXlzenp6fIwcqtXmv8AWC0bevdXS7TZhK6WQsMJaJqaGZk36VPEU3n+iGRf50iRgTjp2z/gDOz82Xqm9QQ7Dit+6JQoPuMvIVBVqKJgHZs9Ri034T8sZjoZentgJFEbswkwCvfUxPu6kbNo4ijrW3N+GGa+jC8xFomMSsS5yXl/8Er4N3/0a5WUrh/KQtvViLfhDSwUsJoHeFAsuy+LpJQN2Grin4W8G1ooU5AgqAv6GioWgLKeCiq/6vafr+b43N/JfbxcSi1xWJbtv99KYtTqFNyuj4p86qJVMUlGkGfXOqV68q1OzxbowxpVP/h0cF3zb8jXaExX8uzsUtlaXrnCw2H6aOkkYfdR8IGFvn0cQik8JilMPZivO/uAoCZr3hORY5ftpS3miZwfKTjQirUbwpgUlIUMlo0hF0y77pO+zmcdkSM75zJxNg0VrnH4H9REDCzXDLvXUPyevntyYbHiZq+z7BgyEJmRNossv6tvo2HB66GJ5swe8GrCvJZXdBswGRAZ6olIha+DtNP1YeqnozuiH1sTzYlyw/bzVYMStCTeqJENcqR/T7G42u7G1Pjf51wW7cp4lMpF7tpz+Ctj9CkOdxm+it2U2kX+HYfh3InAvbM409OUdyhnp2juTc8X6WiF24doEeYHCSz9w0C2CzjoBWpG6ulTsw7GfAkVrZTHzF5CzMxv9dW6tIh5pb5IRuvN09d7dOYh0dAEd4FSfZp2q6MTeiScR2aVtkNIX8qGOXDhx2nRuxvJBIlTtlayUZVpph4DGuqryrlMka4wROvbUmdux5i53WObDFmnVmqraS1Z04rIdRQSnv6W0bom8owTN29OtwOHKSdkSxiVJ1xUlkoMf0oo8lPLOpivjOR1iJrjLJp2eIPGBy1jmO226kQOBdMUbGBvgSTRVFRNwuyM7tO8Xx6DVwMBruXWfnaUi7/tsM15I+qgWGKEW684b9LVrpFVh6WvFKUFNKS20T0MxIXo5Vk5zjB1c43J/PEYkrk7Nvd7/xff0yfX5WnmkMM7Q9LsAeWOWR+zthsoeDF1evdP907Q5HYMzowf7ehddg6KncY1iMzsE9WlOm5Of6QYn/djHcC8W92pRee73DILxprmdTHWJtf5mtg2aHeHDbhZryfBcqsrsfvBaOv+7W4PElRHMj436+E7sP6NUzzXsAg7tUw5vPxKUw6tNhNdD6DPS71lMLBOhAzPXCj5MG6c/qkq3ZsYKqvub2o/R/qubsL+0vsXyRH+y43vlxJ8Wdfad8IbT7LX9Vb9fpxdVgnc0u1/zRzBAqajj4PsAz/QqXdMKa6wIEuPJQl9feydu+pANM7J7+MMtdVIMT8ExivvlQO9sXw8o1Y9jhREMnLWZ5UKn9hWfM8Ql9NX0Q7y3j5WBt7Yg/i9vvV9Sgu08MG860IF+QAar/wCwZiXv" rel="nofollow noreferrer">here

I would like to know if there are any better ways to solve this. I think the component runs into troubles whenever the props change because the onMounted hook does not run again.

And maybe I don't even know the local payload ref variable because this can be solved "smarter"... I basically want to generate a form based on the field configurations and ask the form for all values whenever I want to submit them.


问:
Get an user name of authorized Reddit user (without API)
I'm doing some automation for Reddit via Chrome extension, and ran into a problem that I can not get the name of the authorized user. I have access to cookies/session storage, but Reddit doesn't store the username there. I tried GET-request to https://www.reddit.com/api/v1/me but getting only some settings for authorized account. Is there any way to get authorized user name? Will be grateful to any help!


问:
lubridate conversion functions stopped working after R update
Until today, I was using R 4.0.X, and used lubridate functions dmy_hms, ymd_hms, etc. to convert dates as strings into datetime objects in dataframes.
So, this MWE worked just fine:

```<code>library('lubridate');
a <- '13/06/2019 18:00';
dmy_hm(a);
</code>```

After an update to R 4.2.2 (and an update of lubridate package), this does not works anymore, and yields, without more information:

```<code>All formats failed to parse. No formats found.
</code>```

Function parse_date_time seems to work (see below), but I would need to update all of my scripts that are using dmy_hm (or other) functions.

```<code>> parse_date_time(a, "dmy HM")
 1 parsed with %d/%Om/%Y %H:%M
[1] "2019-06-13 18:00:00 UTC"
</code>```

Does anyone knows how to make these functions work?
Thanks

Also, if this could help:

```<code>> Sys.getlocale (category = "LC_ALL")
[1] "LC_COLLATE=French_France.1252;LC_CTYPE=French_France.1252;LC_MONETARY=French_France.1252;LC_NUMERIC=C;LC_TIME=French_France.1252"

> version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
crt            ucrt
system         x86_64, mingw32
status
major          4
minor          2.2
year           2022
month          10
day            31
svn rev        83211
language       R
version.string R version 4.2.2 (2022-10-31 ucrt)
nickname       Innocent and Trusting
</code>```

Body:
Until today, I was using R 4.0.X, and used lubridate functions dmy_hms, ymd_hms, etc. to convert dates as strings into datetime objects in dataframes.
So, this MWE worked just fine:

library('lubridate');
a <- '13/06/2019 18:00';
dmy_hm(a);

After an update to R 4.2.2 (and an update of lubridate package), this does not works anymore, and yields, without more information:

All formats failed to parse. No formats found.

Function parse_date_time seems to work (see below), but I would need to update all of my scripts that are using dmy_hm (or other) functions.

> parse_date_time(a, "dmy HM")
 1 parsed with %d/%Om/%Y %H:%M
[1] "2019-06-13 18:00:00 UTC"

Does anyone knows how to make these functions work?
Thanks

Also, if this could help:

> Sys.getlocale (category = "LC_ALL")
[1] "LC_COLLATE=French_France.1252;LC_CTYPE=French_France.1252;LC_MONETARY=French_France.1252;LC_NUMERIC=C;LC_TIME=French_France.1252"

> version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
crt            ucrt
system         x86_64, mingw32
status
major          4
minor          2.2
year           2022
month          10
day            31
svn rev        83211
language       R
version.string R version 4.2.2 (2022-10-31 ucrt)
nickname       Innocent and Trusting


问:
Prevent PhpSpreadSheet from adding the @ symbol
I am working with PhpSpreadsheet. When I use a formula that copies cell values, it adds to the formula the @ symbol. This cause constant an error.
I need to prevent PhpSpreadsheet from adding this @ symbol.
When I remove the @, the formula works perfectly.

```<code>
//** Create a new Spreadsheet Object **//
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet(); //get current active sheet (first sheet)

        //** Set and load the reader **//
        $inputFileName = $basePath;
        $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); // Create a new Reader of type xlsx
        $reader->setReadDataOnly(false); // Keeping the style
        $spreadsheet = $reader->load($inputFileName); // Load $inputFileName to a Spreadsheet Object

$spreadsheet->getActiveSheet()->fromArray($ufields, null, 'A8', true);
 $attrs = $spreadsheet->getActiveSheet()->getCell("A10")->getFormulaAttributes();
 $attrs['t'] = 'array';
$spreadsheet->getActiveSheet()->getCell("A10")->setFormulaAttributes($attrs);
$spreadsheet->getActiveSheet()->setCellValue("A10",'=IF(all_details!A8:I8<>"", all_details!A8:I8, "")');

$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
                    $writer->setPreCalculateFormulas(false);
                    $writer->save($inputFileName);

    //Export sheet code
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$reportOriginalname.'"');
        header('Cache-Control: max-age=0');

</code>```

** I read and tried the solution suggested here, but it didn't work for me.

Body:
I am working with PhpSpreadsheet. When I use a formula that copies cell values, it adds to the formula the @ symbol. This cause constant an error.
I need to prevent PhpSpreadsheet from adding this @ symbol.
When I remove the @, the formula works perfectly.

//** Create a new Spreadsheet Object **//
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet(); //get current active sheet (first sheet)

        //** Set and load the reader **//
        $inputFileName = $basePath;
        $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx(); // Create a new Reader of type xlsx
        $reader->setReadDataOnly(false); // Keeping the style
        $spreadsheet = $reader->load($inputFileName); // Load $inputFileName to a Spreadsheet Object

$spreadsheet->getActiveSheet()->fromArray($ufields, null, 'A8', true);
 $attrs = $spreadsheet->getActiveSheet()->getCell("A10")->getFormulaAttributes();
 $attrs['t'] = 'array';
$spreadsheet->getActiveSheet()->getCell("A10")->setFormulaAttributes($attrs);
$spreadsheet->getActiveSheet()->setCellValue("A10",'=IF(all_details!A8:I8<>"", all_details!A8:I8, "")');

$writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
                    $writer->setPreCalculateFormulas(false);
                    $writer->save($inputFileName);

    //Export sheet code
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$reportOriginalname.'"');
        header('Cache-Control: max-age=0');

** I read and tried the solution suggested here, but it didn't work for me.


问:
react-native-google-mobile-ads dont work with mediation, Meta, AdColony And Unity Ads
I'm facing several issues when trying to mediate with Meta Audience Network, Adcolony and Unity Ads.
On Faebook with bidding it gives the error of 'No Ad Config'
In Unity Ads and Adcolony with waterfall gives the error:
Adcolony SDK requires an Activity context to initialize Ads
Unity Ads require an Activity context to load Ads

I'm using the latest version of google mobile ads:

```<code>"react-native-google-mobile-ads": "^8.2.2",

</code>```

I put everything right in app/build.gradle

```<code>implementation 'com.google.android.gms:play-services-ads:21.3.0'
implementation 'com.google.ads.mediation:facebook:6.12.0.0'
implementation 'com.google.ads.mediation:adcolony:4.8.0.0'
implementation 'com.unity3d.ads:unity-ads:4.5.0'
implementation 'com.google.ads.mediation:unity:4.5.0.0'
</code>```

Even the ad inspection shows that everything is correct

I've tried to do several things and several tests but without success!

Note: All ads I'm trying to load are in test mode, I've already configured the device on Meta, Unity and AdColony platforms if activated in placement

Body:
I'm facing several issues when trying to mediate with Meta Audience Network, Adcolony and Unity Ads.
On Faebook with bidding it gives the error of 'No Ad Config'
In Unity Ads and Adcolony with waterfall gives the error:
Adcolony SDK requires an Activity context to initialize Ads
Unity Ads require an Activity context to load Ads

I'm using the latest version of google mobile ads:

"react-native-google-mobile-ads": "^8.2.2",

I put everything right in app/build.gradle

implementation 'com.google.android.gms:play-services-ads:21.3.0'
implementation 'com.google.ads.mediation:facebook:6.12.0.0'
implementation 'com.google.ads.mediation:adcolony:4.8.0.0'
implementation 'com.unity3d.ads:unity-ads:4.5.0'
implementation 'com.google.ads.mediation:unity:4.5.0.0'

Even the ad inspection shows that everything is correct

I've tried to do several things and several tests but without success!

Note: All ads I'm trying to load are in test mode, I've already configured the device on Meta, Unity and AdColony platforms if activated in placement


问:
Trying to package Reactjs with Java Spring boot and get MojoFailureException
I am trying to package my front-end with my back-end, reactjs and java spring boot. I am getting this error and I can´t find a way to solve it. I got the latest npm, node and react installed.

Here is my pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>integritaback</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>integritaback</name>
    <description>Projeto Clinica Integrita</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>com.github.eirslett</groupId>
                <artifactId>frontend-maven-plugin</artifactId>
                <version>1.12.1</version>

                <executions>
                    <!-- installing node and npm -->
                    <execution>
                        <id>Install node and npm</id>
                        <goals>
                            <goal>install-node-and-npm</goal>
                        </goals>
                        <phase>generate-resources</phase>
                        <configuration>
                            <nodeVersion>v18.12.1</nodeVersion>
                            <npmVersion>8.19.2</npmVersion>
                        </configuration>
                    </execution>

                    <!-- running npm install -->
                    <execution>
                        <id>npm install</id>
                        <goals>
                            <goal>npm</goal>
                        </goals>
                        <phase>generate-resources</phase>
                        <configuration>
                            <arguments>install</arguments>
                        </configuration>
                    </execution>

                    <!-- build our production version -->
                    <execution>
                        <id>npm run build</id>
                        <goals>
                            <goal>npm</goal>
                        </goals>
                        <phase>generate-resources</phase>
                        <configuration>
                            <arguments>run build</arguments>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <nodeVersion>v18.12.1</nodeVersion>
                    <workingDirectory>src/main/Integrita</workingDirectory>
                </configuration>
        </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <executions>
                    <execution>
                        <id>Copy JavaScript app into SpringBoot</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/classes/static</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>src/main/Integrita/build</directory>
                                    <filtering>true</filtering>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

So when I try to run .\mvnw clean install it goes fine until this error appear:

```<code>[INFO] --- frontend-maven-plugin:1.11.3:npm (npm install) @ integritaback ---
[INFO] Running 'npm install' in C:\Users\LuisR\Documents\Integrita\integritaback\src\main\Integrita
[INFO] npm ERR! code ERESOLVE
[INFO] npm ERR! ERESOLVE could not resolve
[INFO] npm ERR!
[INFO] npm ERR! While resolving: @react-pdf/renderer@3.0.1
[INFO] npm ERR! Found: react@18.2.0
[INFO] npm ERR! node_modules/react
[INFO] npm ERR!   react@"^18.2.0" from the root project
[INFO] npm ERR!   peer react@">=16.8.0" from @emotion/react@11.10.4
[INFO] npm ERR!   node_modules/@emotion/react
[INFO] npm ERR!     @emotion/react@"^11.10.4" from the root project
[INFO] npm ERR!     peer @emotion/react@"^11.0.0-rc.0" from @emotion/styled@11.10.4
[INFO] npm ERR!     node_modules/@emotion/styled
[INFO] npm ERR!       @emotion/styled@"^11.10.4" from the root project
[INFO] npm ERR!       4 more (@mui/material, @mui/styled-engine, @mui/system, @mui/x-date-pickers)
[INFO] npm ERR!     4 more (@mui/material, @mui/styled-engine, @mui/system, @mui/x-date-pickers)
[INFO] npm ERR!   39 more (@emotion/styled, ...)
[INFO] npm ERR!
[INFO] npm ERR! Could not resolve dependency:
[INFO] npm ERR! peer react@"^16.8.6 || ^17.0.0" from @react-pdf/renderer@3.0.1
[INFO] npm ERR! node_modules/@react-pdf/renderer
[INFO] npm ERR!   @react-pdf/renderer@"^3.0.1" from the root project
[INFO] npm ERR!
[INFO] npm ERR! Conflicting peer dependency: react@17.0.2
[INFO] npm ERR! node_modules/react
[INFO] npm ERR!   peer react@"^16.8.6 || ^17.0.0" from @react-pdf/renderer@3.0.1
[INFO] npm ERR!   node_modules/@react-pdf/renderer
[INFO] npm ERR!     @react-pdf/renderer@"^3.0.1" from the root project
[INFO] npm ERR!
[INFO] npm ERR! Fix the upstream dependency conflict, or retry
[INFO] npm ERR! this command with --force, or --legacy-peer-deps
[INFO] npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
[INFO] npm ERR!
[INFO] npm ERR! See C:\Users\LuisR\AppData\Local\npm-cache\eresolve-report.txt for a full report.
[INFO]
[INFO] npm ERR! A complete log of this run can be found in:
[INFO] npm ERR!     C:\Users\LuisR\AppData\Local\npm-cache\_logs\2023-01-03T12_02_46_084Z-debug-0.log
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  17.384 s
[INFO] Finished at: 2023-01-03T09:02:49-03:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.11.3:npm (npm install) on project integritaback: Failed to run task: 'npm install' failed. org.apache.commons.exec.Ex
ecuteException: Process exited with an error: 1 (Exit value: 1) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
</code>```

Can anyone help me out. I don´t know what else to do.

Body:
I am trying to package my front-end with my back-end, reactjs and java spring boot. I am getting this error and I can´t find a way to solve it. I got the latest npm, node and react installed.

Here is my pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>integritaback</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>integritaback</name>
    <description>Projeto Clinica Integrita</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>

            <plugin>
                <groupId>com.github.eirslett</groupId>
                <artifactId>frontend-maven-plugin</artifactId>
                <version>1.12.1</version>

                <executions>

                    <execution>
                        <id>Install node and npm</id>
                        <goals>
                            <goal>install-node-and-npm</goal>
                        </goals>
                        <phase>generate-resources</phase>
                        <configuration>
                            <nodeVersion>v18.12.1</nodeVersion>
                            <npmVersion>8.19.2</npmVersion>
                        </configuration>
                    </execution>

                    <execution>
                        <id>npm install</id>
                        <goals>
                            <goal>npm</goal>
                        </goals>
                        <phase>generate-resources</phase>
                        <configuration>
                            <arguments>install</arguments>
                        </configuration>
                    </execution>

                    <execution>
                        <id>npm run build</id>
                        <goals>
                            <goal>npm</goal>
                        </goals>
                        <phase>generate-resources</phase>
                        <configuration>
                            <arguments>run build</arguments>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <nodeVersion>v18.12.1</nodeVersion>
                    <workingDirectory>src/main/Integrita</workingDirectory>
                </configuration>
        </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <executions>
                    <execution>
                        <id>Copy JavaScript app into SpringBoot</id>
                        <phase>process-resources</phase>
                        <goals>
                            <goal>copy-resources</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>target/classes/static</outputDirectory>
                            <resources>
                                <resource>
                                    <directory>src/main/Integrita/build</directory>
                                    <filtering>true</filtering>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

So when I try to run .\mvnw clean install it goes fine until this error appear:

[INFO] --- frontend-maven-plugin:1.11.3:npm (npm install) @ integritaback ---
[INFO] Running 'npm install' in C:\Users\LuisR\Documents\Integrita\integritaback\src\main\Integrita
[INFO] npm ERR! code ERESOLVE
[INFO] npm ERR! ERESOLVE could not resolve
[INFO] npm ERR!
[INFO] npm ERR! While resolving: @react-pdf/renderer@3.0.1
[INFO] npm ERR! Found: react@18.2.0
[INFO] npm ERR! node_modules/react
[INFO] npm ERR!   react@"^18.2.0" from the root project
[INFO] npm ERR!   peer react@">=16.8.0" from @emotion/react@11.10.4
[INFO] npm ERR!   node_modules/@emotion/react
[INFO] npm ERR!     @emotion/react@"^11.10.4" from the root project
[INFO] npm ERR!     peer @emotion/react@"^11.0.0-rc.0" from @emotion/styled@11.10.4
[INFO] npm ERR!     node_modules/@emotion/styled
[INFO] npm ERR!       @emotion/styled@"^11.10.4" from the root project
[INFO] npm ERR!       4 more (@mui/material, @mui/styled-engine, @mui/system, @mui/x-date-pickers)
[INFO] npm ERR!     4 more (@mui/material, @mui/styled-engine, @mui/system, @mui/x-date-pickers)
[INFO] npm ERR!   39 more (@emotion/styled, ...)
[INFO] npm ERR!
[INFO] npm ERR! Could not resolve dependency:
[INFO] npm ERR! peer react@"^16.8.6 || ^17.0.0" from @react-pdf/renderer@3.0.1
[INFO] npm ERR! node_modules/@react-pdf/renderer
[INFO] npm ERR!   @react-pdf/renderer@"^3.0.1" from the root project
[INFO] npm ERR!
[INFO] npm ERR! Conflicting peer dependency: react@17.0.2
[INFO] npm ERR! node_modules/react
[INFO] npm ERR!   peer react@"^16.8.6 || ^17.0.0" from @react-pdf/renderer@3.0.1
[INFO] npm ERR!   node_modules/@react-pdf/renderer
[INFO] npm ERR!     @react-pdf/renderer@"^3.0.1" from the root project
[INFO] npm ERR!
[INFO] npm ERR! Fix the upstream dependency conflict, or retry
[INFO] npm ERR! this command with --force, or --legacy-peer-deps
[INFO] npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
[INFO] npm ERR!
[INFO] npm ERR! See C:\Users\LuisR\AppData\Local\npm-cache\eresolve-report.txt for a full report.
[INFO]
[INFO] npm ERR! A complete log of this run can be found in:
[INFO] npm ERR!     C:\Users\LuisR\AppData\Local\npm-cache\_logs\2023-01-03T12_02_46_084Z-debug-0.log
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  17.384 s
[INFO] Finished at: 2023-01-03T09:02:49-03:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.11.3:npm (npm install) on project integritaback: Failed to run task: 'npm install' failed. org.apache.commons.exec.Ex
ecuteException: Process exited with an error: 1 (Exit value: 1) -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException

Can anyone help me out. I don´t know what else to do.


问:
Using OWIN ApiController and AspNet ControllerBase with a common API
I have a requirement to add an HTTP REST api to an application that will need to run on .net framework 4.7.2 as well as .net core. The core logic is targeting .net standard 2.0 and uses autofac for dependency injection. I’m planning to use OWIN for the framework dependent build and aspnet webApi for the core build.

Ideally I would like to create common API controllers used by both applications. I can certainly inject services into the different controller types but that would get hard to maintain long term and tough to catch mismatched routes etc. I could probably also just use OWIN everywhere and not leverage aspnet core but don’t want to, the framework build will probably have a 2yr requirement before I no longer need to maintain it and would prefer aspnet webApi long term.

Is there a way to add ApiControllers to an aspnet core application or abstract between the two?

Currently I’ve only been able to inject common services with APIs into the two different controller types to accomplish my required results.

Example Injectable Service with Api:

Main library containing services target .Net Standard 2.0

```<code>public interface IDebuggingLevelUtility
{
    LogEventLevel Level { get; }
    void ChangeDebugLevel(LogEventLevel loggingLevel);
}
</code>```

Example of an Api ControllerBase hosted in a .net Core WebApi Application

```<code>[ApiController]
[Route("api/debugging")]
public class DebuggingController : ControllerBase
{
    private readonly ILogger<DebuggingController> _logger;
    private readonly IDebuggingLevelUtility _debugging;

    public DebuggingController(ILogger<DebuggingController> logger, IDebuggingLevelUtility debugging)
    {
        _logger = logger;
        _debugging = debugging;
    }

    [HttpGet]
    public ActionResult<string> GetLoggerLevel()
    {
        try
        {
            return _debugging.Level.ToString();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to change logging Level");
            return NotFound();
        }
    }

    [HttpPost("{level}")]
    [ProducesResponseType(typeof(bool), 200)]
    [ProducesResponseType(typeof(BadRequestResult), 500)]
    public  ActionResult<string> PostLoggerLevel(LogEventLevel level)
    {
        try
        {
            _logger.LogWarning("Changing debugging level from {current} => {new}", LoggingLevel.Level.MinimumLevel, level);
            _debugging.ChangeDebugLevel(level);
            return _debugging.Level.ToString();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to change logging Level");
            return BadRequest();
        }
    }
}
</code>```

Example ApiController hosted in a .Net Framework 4.7.2 application using OWIN self hosted

```<code>[RoutePrefix("api/debugging")]
public class DebuggingController : ApiController
{
    private readonly ILogger _logger;
    private readonly IDebuggingLevelUtility _debuggingLevelUtility;

    public DebuggingController(ILogger logger, IDebuggingLevelUtility debuggingLevelUtility)
    {
        _logger = logger;
        _debuggingLevelUtility = debuggingLevelUtility;
    }

    [HttpGet]
    [Route("")]
    public void GetLoggerLevel()
    {
        //DONT WANT TO CREATE CONTROLLERS TWICE
    }...
}
</code>```

Ideally I would abstract the two controllers and create my custom Api Route Handlers centrally located.  I believe these use source generators so I'm not entirely sure where to be begin.  Ideally I have "MySuperCoolApiController" and inject the required services.  This ApiController can be mapped to both the OWIN self hosted api and the AspNet core WebApi. Hope this provide some better clarity.

Body:
I have a requirement to add an HTTP REST api to an application that will need to run on .net framework 4.7.2 as well as .net core. The core logic is targeting .net standard 2.0 and uses autofac for dependency injection. I’m planning to use OWIN for the framework dependent build and aspnet webApi for the core build.

Ideally I would like to create common API controllers used by both applications. I can certainly inject services into the different controller types but that would get hard to maintain long term and tough to catch mismatched routes etc. I could probably also just use OWIN everywhere and not leverage aspnet core but don’t want to, the framework build will probably have a 2yr requirement before I no longer need to maintain it and would prefer aspnet webApi long term.

Is there a way to add ApiControllers to an aspnet core application or abstract between the two?

Currently I’ve only been able to inject common services with APIs into the two different controller types to accomplish my required results.

Example Injectable Service with Api:

Main library containing services target .Net Standard 2.0

public interface IDebuggingLevelUtility
{
    LogEventLevel Level { get; }
    void ChangeDebugLevel(LogEventLevel loggingLevel);
}

Example of an Api ControllerBase hosted in a .net Core WebApi Application

[ApiController]
[Route("api/debugging")]
public class DebuggingController : ControllerBase
{
    private readonly ILogger<DebuggingController> _logger;
    private readonly IDebuggingLevelUtility _debugging;

    public DebuggingController(ILogger<DebuggingController> logger, IDebuggingLevelUtility debugging)
    {
        _logger = logger;
        _debugging = debugging;
    }

    [HttpGet]
    public ActionResult<string> GetLoggerLevel()
    {
        try
        {
            return _debugging.Level.ToString();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to change logging Level");
            return NotFound();
        }
    }

    [HttpPost("{level}")]
    [ProducesResponseType(typeof(bool), 200)]
    [ProducesResponseType(typeof(BadRequestResult), 500)]
    public  ActionResult<string> PostLoggerLevel(LogEventLevel level)
    {
        try
        {
            _logger.LogWarning("Changing debugging level from {current} => {new}", LoggingLevel.Level.MinimumLevel, level);
            _debugging.ChangeDebugLevel(level);
            return _debugging.Level.ToString();
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to change logging Level");
            return BadRequest();
        }
    }
}

Example ApiController hosted in a .Net Framework 4.7.2 application using OWIN self hosted

[RoutePrefix("api/debugging")]
public class DebuggingController : ApiController
{
    private readonly ILogger _logger;
    private readonly IDebuggingLevelUtility _debuggingLevelUtility;

    public DebuggingController(ILogger logger, IDebuggingLevelUtility debuggingLevelUtility)
    {
        _logger = logger;
        _debuggingLevelUtility = debuggingLevelUtility;
    }

    [HttpGet]
    [Route("")]
    public void GetLoggerLevel()
    {
        //DONT WANT TO CREATE CONTROLLERS TWICE
    }...
}

Ideally I would abstract the two controllers and create my custom Api Route Handlers centrally located.  I believe these use source generators so I'm not entirely sure where to be begin.  Ideally I have "MySuperCoolApiController" and inject the required services.  This ApiController can be mapped to both the OWIN self hosted api and the AspNet core WebApi. Hope this provide some better clarity.


问:
Chrome Mobile - .focus not working after alert
I am trying to focus an input element after an alert message in Google Chrome on Android.

The problem is that the focus isnt set on the input element. The keyboard opens but I cant type anything in.

This is my input:

```<code><input id="input" type="text">
<button id="button">Button</button>
</code>```

I am trying to focus the input on button click

```<code>const btn = document.getElementById('button')
btn.addEventListener('click', () => {
    alert("Some information")
    const input = document.getElementById('input')
    input.focus()
})
</code>```

I tried to add a timeOut to focus but it didnt work.

Is this a Chrome Mobile problem? Because in Firefox Mobile its working as expected.

Body:
I am trying to focus an input element after an alert message in Google Chrome on Android.

The problem is that the focus isnt set on the input element. The keyboard opens but I cant type anything in.

This is my input:

<input id="input" type="text">
<button id="button">Button</button>

I am trying to focus the input on button click

const btn = document.getElementById('button')
btn.addEventListener('click', () => {
    alert("Some information")
    const input = document.getElementById('input')
    input.focus()
})

I tried to add a timeOut to focus but it didnt work.

Is this a Chrome Mobile problem? Because in Firefox Mobile its working as expected.


问:
SenML parser for C# .net
I am looking for a viable solution to parse SenML data into JSON using C#.NET.

Preferably the following types -

application/senml+json

application/senml+cbor

I have seen packages in Python namely - senml & cbor which are used to read and parse the SenML data to JSON arrays but looking for a similar and stable C# alternative.

Any help will me much appreciated.

Thanks!

Title: SenML parser for C# .net


问:
SOLVED: Pass data between pages in mern stack
So i have a mern project. The dashboard page on my website is fetching "project" documents from the db and using the map() function displaying the data and an open project button. When a user presses on one of those "open project" buttons, i want to redirect them to another page. Which will display the tickets that have the same id as the project relative to the button the user pressed. But for that, in the new page. I need to know on which project they pressed the button. How do i do that. I can think of a few possible solutions:

Using react context to make a global variable, on which project they pressed. But that feels super weird and could be a security breach.

making a page for every "project" document in the database. But i dont know how and if it´s possible since i cant sit and manually create all those pages.

All help is very appreciated, thank you!:)

I haven´t tried any solutions yet, cause i feel like .1 just wont do the job smoothly. and i dont know how to do .2


问:
Summarise+Group_by+mean+sd various columns
I need to have a new df with gender separation of means (several columns) and sd, and later do my graphs. After of hours of work I did it but in a silly way :D one by one.

For me that I'm a super beginner, I'm trying-mistaking during hours until something work. But I know with a teacher or more explanation I would do better.

```<code>" mediapi<-rowMeans(datos[1:325,c(31,37)])
Sdbi<-rowSds(as.matrix(datos[1:325,c(6:18)])). "

al later one by one, because I tried in one table and it does not work...

datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediaci), # calculates the mean
            s = sd(mediaci),   # calculates the standard deviation
            n = n()) %>%     # calculates the total number of observations
  ungroup()

datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediaii), # calculates the mean
            s = sd(mediaii),   # calculates the standard deviation
            n = n()) %>%     # calculates the total number of observations
  ungroup()

datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediabi), # calculates the mean
            s = sd(mediabi),   # calculates the standard deviation
            n = n()) %>%     # calculates the total number of observations
  ungroup()

datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediaai), # calculates the mean
            s = sd(mediaai),   # calculates the standard deviation
            n = n()) %>%     # calculates the total number of observations
  ungroup()

datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediabai), # calculates the mean
            s = sd(mediabai),   # calculates the standard deviation
            n = n()) %>%     # calculates the total number of observations
  ungroup()

  datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediapi),# calculates the mean
            s = sd(mediapi),
            n = n()) %>%     # calculates the total number of observations
  ungroup()

   datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediandi),# calculates the mean
            s = sd(mediandi),
            n = n()) %>%     # calculates the total number of observations
  ungroup()
     datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediansi),# calculates the mean
            s = sd(mediansi),
            n = n()) %>%     # calculates the total number of observations
  ungroup()

Can someone tell me an easiest and efficient way? Thanks a lot

</code>```

Body:
I need to have a new df with gender separation of means (several columns) and sd, and later do my graphs. After of hours of work I did it but in a silly way :D one by one.

For me that I'm a super beginner, I'm trying-mistaking during hours until something work. But I know with a teacher or more explanation I would do better.

" mediapi<-rowMeans(datos[1:325,c(31,37)])
Sdbi<-rowSds(as.matrix(datos[1:325,c(6:18)])). "

al later one by one, because I tried in one table and it does not work...

datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediaci), # calculates the mean
            s = sd(mediaci),   # calculates the standard deviation
            n = n()) %>%     # calculates the total number of observations
  ungroup()

datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediaii), # calculates the mean
            s = sd(mediaii),   # calculates the standard deviation
            n = n()) %>%     # calculates the total number of observations
  ungroup()

datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediabi), # calculates the mean
            s = sd(mediabi),   # calculates the standard deviation
            n = n()) %>%     # calculates the total number of observations
  ungroup()

datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediaai), # calculates the mean
            s = sd(mediaai),   # calculates the standard deviation
            n = n()) %>%     # calculates the total number of observations
  ungroup()

datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediabai), # calculates the mean
            s = sd(mediabai),   # calculates the standard deviation
            n = n()) %>%     # calculates the total number of observations
  ungroup()

  datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediapi),# calculates the mean
            s = sd(mediapi),
            n = n()) %>%     # calculates the total number of observations
  ungroup()

   datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediandi),# calculates the mean
            s = sd(mediandi),
            n = n()) %>%     # calculates the total number of observations
  ungroup()
     datos %>%
  group_by(Sexo) %>%
  summarize(m = mean(mediansi),# calculates the mean
            s = sd(mediansi),
            n = n()) %>%     # calculates the total number of observations
  ungroup()

Can someone tell me an easiest and efficient way? Thanks a lot


问:
How python knows which string should be checked thru .isdigit() method?
```<code>def is_acceptable_password(password: str) -> bool:
    cond1 = len(password) > 6
    cond2 = any(map(str.isdigit, password))
    if cond1 & cond2 == True:
        return True
    else:
        return False
</code>```

In this code I do not understands how "str.isdigit" works. In my logic I need to write it like "password.isdigit", because I want to check whether the digit is in it, but only "str.isdigit" works.

Body:
def is_acceptable_password(password: str) -> bool:
    cond1 = len(password) > 6
    cond2 = any(map(str.isdigit, password))
    if cond1 & cond2 == True:
        return True
    else:
        return False

In this code I do not understands how "str.isdigit" works. In my logic I need to write it like "password.isdigit", because I want to check whether the digit is in it, but only "str.isdigit" works.


问:
How to print top 3 total spending for each quarter in MS SQL?
I want to find out the top 3 spending from each quarter. My current code is printing all the spending from each quarter but i want to show only the top 3 from each quarter.</p>
```<code>SELECT SUM(f.Spend) AS Total_Spend, e.expenset_id,e.[Expense Type],
ROW_NUMBER() OVER(PARTITION BY e.expenset_id ORDER BY SUM(f.Spend) DESC) Rank,
CASE
    WHEN DATEPART(mm,f.Date) IN (4,5,6) THEN 'Q2'
    WHEN DATEPART(mm,f.Date) IN (7,8,9) THEN 'Q3'
    WHEN DATEPART(mm,f.Date) IN (10,11,12) THEN 'Q4'
    ELSE 'Q1'
    END AS Quarter
FROM fact_tbl f
JOIN expense_type e ON f.expenset_id=e.expenset_id
GROUP BY e.[Expense Type],e.expenset_id,DATEPART(mm,f.Date)
ORDER BY SUM(f.Spend) DESC
</code>```

Body:
I want to find out the top 3 spending from each quarter. My current code is printing all the spending from each quarter but i want to show only the top 3 from each quarter.

SELECT SUM(f.Spend) AS Total_Spend, e.expenset_id,e.[Expense Type],
ROW_NUMBER() OVER(PARTITION BY e.expenset_id ORDER BY SUM(f.Spend) DESC) Rank,
CASE
    WHEN DATEPART(mm,f.Date) IN (4,5,6) THEN 'Q2'
    WHEN DATEPART(mm,f.Date) IN (7,8,9) THEN 'Q3'
    WHEN DATEPART(mm,f.Date) IN (10,11,12) THEN 'Q4'
    ELSE 'Q1'
    END AS Quarter
FROM fact_tbl f
JOIN expense_type e ON f.expenset_id=e.expenset_id
GROUP BY e.[Expense Type],e.expenset_id,DATEPART(mm,f.Date)
ORDER BY SUM(f.Spend) DESC


问:
How can I remove items with similar productName?
So I have this script which puts every product into the value "all" and then displays them but how can I make it so it doesn't display duplicates of the same product?

For example: I have the same product under different categories but I only want to display one of them within the all category, this is my script.

function filterProduct(value) {

    let buttons = document.querySelectorAll(".button-value");
    buttons.forEach((button) => {

      if (value.toUpperCase() == button.innerText.toUpperCase()) {
        button.classList.add("active");
      } else {
        button.classList.remove("active");
      }
    });

    let elements = document.querySelectorAll(".card");

    elements.forEach((element) => {

      if (value == "all") {
        element.classList.remove("hide");
      } else {

        if (element.classList.contains(value)) {

          element.classList.remove("hide");
        } else {

          element.classList.add("hide");
        }
      }
    });
  }```

I tried many different things but I really couldn't get it to work, I'm basically stuck at zero right now.

Body:
So I have this script which puts every product into the value "all" and then displays them but how can I make it so it doesn't display duplicates of the same product?

For example: I have the same product under different categories but I only want to display one of them within the all category, this is my script.

function filterProduct(value) {

    let buttons = document.querySelectorAll(".button-value");
    buttons.forEach((button) => {

      if (value.toUpperCase() == button.innerText.toUpperCase()) {
        button.classList.add("active");
      } else {
        button.classList.remove("active");
      }
    });

    let elements = document.querySelectorAll(".card");

    elements.forEach((element) => {

      if (value == "all") {
        element.classList.remove("hide");
      } else {

        if (element.classList.contains(value)) {

          element.classList.remove("hide");
        } else {

          element.classList.add("hide");
        }
      }
    });
  }

I tried many different things but I really couldn't get it to work, I'm basically stuck at zero right now.


问:
How to select all columns within a JSON structure in aws databrew?
Databrew recipes can be written under JSON for transformations that will be used more than once for multiple datasets.

This is an example that i copied from Databrew Developer Guide to do joins between datasets:

`

```<code>{
    "Action": {
        "Operation": "JOIN",
        "Parameters": {
            "joinKeys": "[{\"key\":\"assembly_session\",\"value\":\"assembly_session\"},{\"key\":\"state_code\",\"value\":\"state_code\"}]",
            "joinType": "INNER_JOIN",
            "leftColumns": "[\"year\",\"assembly_session\",\"state_code\",\"state_name\",\"all_votes\",\"yes_votes\",\"no_votes\",\"abstain\",\"idealpoint_estimate\",\"affinityscore_usa\",\"affinityscore_russia\",\"affinityscore_china\",\"affinityscore_india\",\"affinityscore_brazil\",\"affinityscore_israel\"]",
            "rightColumns": "[\"assembly_session\",\"vote_id\",\"resolution\",\"state_code\",\"state_name\",\"member\",\"vote\"]",
            "secondInputLocation": "s3://databrew-public-datasets-us-east-1/votes.csv",
            "secondaryDatasetName": "votes"
        }
    }
}
</code>```

`

It's possible to select all columns with a * within "leftColumns" or anything close to that?

I've tried to add only * but it doesn't work.
I will do the same transformations in multiple tables and this functionality would work great if i could select everything on a left join, without needing to specify all the columns.

Body:
Databrew recipes can be written under JSON for transformations that will be used more than once for multiple datasets.

This is an example that i copied from Databrew Developer Guide to do joins between datasets:

`

{
    "Action": {
        "Operation": "JOIN",
        "Parameters": {
            "joinKeys": "[{\"key\":\"assembly_session\",\"value\":\"assembly_session\"},{\"key\":\"state_code\",\"value\":\"state_code\"}]",
            "joinType": "INNER_JOIN",
            "leftColumns": "[\"year\",\"assembly_session\",\"state_code\",\"state_name\",\"all_votes\",\"yes_votes\",\"no_votes\",\"abstain\",\"idealpoint_estimate\",\"affinityscore_usa\",\"affinityscore_russia\",\"affinityscore_china\",\"affinityscore_india\",\"affinityscore_brazil\",\"affinityscore_israel\"]",
            "rightColumns": "[\"assembly_session\",\"vote_id\",\"resolution\",\"state_code\",\"state_name\",\"member\",\"vote\"]",
            "secondInputLocation": "s3://databrew-public-datasets-us-east-1/votes.csv",
            "secondaryDatasetName": "votes"
        }
    }
}

`

It's possible to select all columns with a * within "leftColumns" or anything close to that?

I've tried to add only * but it doesn't work.
I will do the same transformations in multiple tables and this functionality would work great if i could select everything on a left join, without needing to specify all the columns.


问:
How to add time with timezone column using knex js?
I'm using knex version "^2.3.0" and Postgresql.
When using time method it creates column with data type time without timezone but that's not what I want.

Is there any way that I can create a column with data type time with timezone?
Thanks in advance.

```<code>      table.time('timeColumnWithTimezone'); // but creates time without timezone

</code>```

Body:
I'm using knex version "^2.3.0" and Postgresql.
When using time method it creates column with data type time without timezone but that's not what I want.

Is there any way that I can create a column with data type time with timezone?
Thanks in advance.

      table.time('timeColumnWithTimezone'); // but creates time without timezone


问:
Why am I getting huge slowdown when parallelising with OpenMP and using static scheduling?
I'm working to parallelise a disease spread model in c using OpenMP but am only seeing massive (order of magnitude) slowdown. I'll point out at the outset that I am a complete novice with both OpenMP and c.

The code loops over every point in the simulation and checks its status (susceptible, infected, recovered) and for each status, follows an algorithm to determine its status at the next time step.

I'll give the loop for infected points for illustrative purposes. Lpoints is a list of indices for points in the simulation, Nneigh gives the number of neighbours each point has and Lneigh gives the indices of these neighbours.

```<code>for (ipoint=0;ipoint<Nland;ipoint++) { //loop over all points
      if (Lpoints_old[ipoint]==I) { //act on infected points

        /* Probability Prec of infected population recovering */
        xi = genrand();
        if (xi<Pvac) { /* This point recovers (I->R) */

          Lpoints[ipoint] = R;
          /* printf("Point %d gained immunity\n",ipoint); */
        }
        else {
          /* Probability of being blockaded by neighbours */
          nsn = 0;
          for (in=0;in<Nneigh[ipoint];in++) { /*count susceptible neighbours (nsn)*/
                  //if (npoint<0) printf("Bad npoint 1: %d in=%d\n",ipoint,in);
                  //fflush(stdout);
            npoint = Lneigh[ipoint][in];
            if (Lpoints_old[npoint]==S) nsn++;
          }
          Prob = (double)nsn*Pblo;
          xi = genrand();
          if (xi<Prob) { /* The population point is blockaded (I->R)*/

            Lpoints[ipoint] = R;
          }
          else { /* Still infected */

            Lpoints[ipoint] = I;
          }
        } /*else*/
      } /*infected*/
    } /*for*/
</code>```

I tried to parallelise by adding #pragma omp parallel for default(shared) private(ipoint,xi,in,npoint,nsn,Prob) before the for loop. (I tried using default(none) as is generally recommended but it wouldn't compile.) On the small grid I am using to test the original series code runs in about 5 seconds and the OpenMP version runs in around 50.

I have searched for ages online and every similar problem seems to be the result of false cache sharing and has been solved by using static scheduling with a chunk size divisible by 8. I tried varying the chunk size to no effect whatsoever, only getting the timings to the original order when the chunk size surpassed the size of the problem (i.e. back to linearly carrying out on one thread.)

Slowdown doesn't seem any better when the problem is more appropriately scaled as far as I can tell either. I have no idea why this isn't working and what's going wrong. Any help greatly appreciated.

Body:
I'm working to parallelise a disease spread model in c using OpenMP but am only seeing massive (order of magnitude) slowdown. I'll point out at the outset that I am a complete novice with both OpenMP and c.

The code loops over every point in the simulation and checks its status (susceptible, infected, recovered) and for each status, follows an algorithm to determine its status at the next time step.

I'll give the loop for infected points for illustrative purposes. Lpoints is a list of indices for points in the simulation, Nneigh gives the number of neighbours each point has and Lneigh gives the indices of these neighbours.

for (ipoint=0;ipoint<Nland;ipoint++) { //loop over all points
      if (Lpoints_old[ipoint]==I) { //act on infected points

        /* Probability Prec of infected population recovering */
        xi = genrand();
        if (xi<Pvac) { /* This point recovers (I->R) */

          Lpoints[ipoint] = R;
          /* printf("Point %d gained immunity\n",ipoint); */
        }
        else {
          /* Probability of being blockaded by neighbours */
          nsn = 0;
          for (in=0;in<Nneigh[ipoint];in++) { /*count susceptible neighbours (nsn)*/
                  //if (npoint<0) printf("Bad npoint 1: %d in=%d\n",ipoint,in);
                  //fflush(stdout);
            npoint = Lneigh[ipoint][in];
            if (Lpoints_old[npoint]==S) nsn++;
          }
          Prob = (double)nsn*Pblo;
          xi = genrand();
          if (xi<Prob) { /* The population point is blockaded (I->R)*/

            Lpoints[ipoint] = R;
          }
          else { /* Still infected */

            Lpoints[ipoint] = I;
          }
        } /*else*/
      } /*infected*/
    } /*for*/

I tried to parallelise by adding #pragma omp parallel for default(shared) private(ipoint,xi,in,npoint,nsn,Prob) before the for loop. (I tried using default(none) as is generally recommended but it wouldn't compile.) On the small grid I am using to test the original series code runs in about 5 seconds and the OpenMP version runs in around 50.

I have searched for ages online and every similar problem seems to be the result of false cache sharing and has been solved by using static scheduling with a chunk size divisible by 8. I tried varying the chunk size to no effect whatsoever, only getting the timings to the original order when the chunk size surpassed the size of the problem (i.e. back to linearly carrying out on one thread.)

Slowdown doesn't seem any better when the problem is more appropriately scaled as far as I can tell either. I have no idea why this isn't working and what's going wrong. Any help greatly appreciated.


问:
Jquery can't find content of div which itself show that div
I show hidden div via $('#something').show() but when

I search in content via jQuery, jQuery can't find my search, but jQuery can find already displayed div!

Why?

In the beginning class full_text's display equal none, then when I click on the index tags the browser should scroll to finded text in all page:

tag1

tag2

tag3

        ...

        ...

```

But jQuery can find in this page other divs which displayed before:

Body:
I show hidden div via $('#something').show() but when

I search in content via jQuery, jQuery can't find my search, but jQuery can find already displayed div!

Why?

In the beginning class full_text's display equal none, then when I click on the index tags the browser should scroll to finded text in all page:

tag1

tag2

tag3

        ...

        ...

But jQuery can find in this page other divs which displayed before: