问:
JHipster: Invalid values not being detected
I was using JHipster, with its autogenerated code. And ran into the following issue regarding detecting whether the request is valid or not based on the following:
I have a schema of the following:

movie:
      type: object
      properties:
        title:
          type: string
        director:
          type: string
        description:
          type: string
        rating:
          type: number
          maximum: 5
          minimum: 0
      example:
        title: The Dark Knight
        director: Christopher Nolan
        description: |
          When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, Batman must accept one of the greatest psychological and physical tests of his ability to fight injustice.
        rating: 4.5
      required:
        - title
        - director
        - description
        - rating
```
<p>And I have a  test case that invokes the API with the body:</p>
<pre class="lang-json prettyprint-override"><code>{
    "director":"director",
    "title":true,
    "description":"description",
    "rating":4.5
}
</code>```

However, I am getting the response

{
    "title": "true",
    "director": "director",
    "description": "description",
    "rating": 4.5
}
```
<p>It is not detecting that the parameter "title" is of type boolean not string, causing the testcase to fail. Interestingly, the error validation detects the error when it is set to null, but not when it is boolean.</p>
<p>I have tried debugging by looking at the way the json is parsed by JHipster. However, it is parsing it as a string, not as a Boolean value.</p>
<p>The implemented delegator</p>
<pre class="lang-java prettyprint-override"><code>    @Service
    @Slf4j
    @RequiredArgsConstructor
    public class Api implements DefaultApiDelegate {
        static ObjectMapper mapper = new ObjectMapper();
        private final NativeWebRequest nativeWebRequest = null;
        static List<Movie> movies = null;
        private final ApplicationProperties applicationProperties = new ApplicationProperties();

        @Value("${jhipster.clientApp.name}")
        private String applicationName;

        @Override
        public Optional<NativeWebRequest> getRequest() {
            return Optional.ofNullable(nativeWebRequest);
        }

        @Override
        public ResponseEntity<List<Movie>> allMovieGet() {
            getMovies();
            System.out.println("GET request");
            ResponseEntity<List<Movie>> res = new ResponseEntity<List<Movie>>(movies.subList(0, 24), HttpStatus.OK);;

            return res;
        }

        @Override
        public ResponseEntity<Movie> addMoviePost(Movie movie){
            getMovies();
            System.out.println(movie.toString());
            System.out.println(movie.getTitle().getClass());
            movies.add(movie);
            ResponseEntity<Movie> res = new ResponseEntity<Movie>(movies.get(movies.size()-1), HttpStatus.CREATED);
            return res;
        }

        public void getMovies(){
            try {
                movies = mapper.readValue(new File("src/main/resources/movies.json"), new TypeReference<List<Movie>>(){});
            } catch (JsonParseException e) {
                e.printStackTrace();
            } catch (JsonMappingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
</code>```

I have not made any other changes to the autogenerated code from JHipster's generate-sources. It is a very simple API that I was creating for a prototype

Body:
I was using JHipster, with its autogenerated code. And ran into the following issue regarding detecting whether the request is valid or not based on the following:
I have a schema of the following:

movie:
      type: object
      properties:
        title:
          type: string
        director:
          type: string
        description:
          type: string
        rating:
          type: number
          maximum: 5
          minimum: 0
      example:
        title: The Dark Knight
        director: Christopher Nolan
        description: |
          When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, Batman must accept one of the greatest psychological and physical tests of his ability to fight injustice.
        rating: 4.5
      required:
        - title
        - director
        - description
        - rating

And I have a  test case that invokes the API with the body:

{
    "director":"director",
    "title":true,
    "description":"description",
    "rating":4.5
}

However, I am getting the response

{
    "title": "true",
    "director": "director",
    "description": "description",
    "rating": 4.5
}

It is not detecting that the parameter "title" is of type boolean not string, causing the testcase to fail. Interestingly, the error validation detects the error when it is set to null, but not when it is boolean.

I have tried debugging by looking at the way the json is parsed by JHipster. However, it is parsing it as a string, not as a Boolean value.

The implemented delegator

    @Service
    @Slf4j
    @RequiredArgsConstructor
    public class Api implements DefaultApiDelegate {
        static ObjectMapper mapper = new ObjectMapper();
        private final NativeWebRequest nativeWebRequest = null;
        static List<Movie> movies = null;
        private final ApplicationProperties applicationProperties = new ApplicationProperties();

        @Value("${jhipster.clientApp.name}")
        private String applicationName;

        @Override
        public Optional<NativeWebRequest> getRequest() {
            return Optional.ofNullable(nativeWebRequest);
        }

        @Override
        public ResponseEntity<List<Movie>> allMovieGet() {
            getMovies();
            System.out.println("GET request");
            ResponseEntity<List<Movie>> res = new ResponseEntity<List<Movie>>(movies.subList(0, 24), HttpStatus.OK);;

            return res;
        }

        @Override
        public ResponseEntity<Movie> addMoviePost(Movie movie){
            getMovies();
            System.out.println(movie.toString());
            System.out.println(movie.getTitle().getClass());
            movies.add(movie);
            ResponseEntity<Movie> res = new ResponseEntity<Movie>(movies.get(movies.size()-1), HttpStatus.CREATED);
            return res;
        }

        public void getMovies(){
            try {
                movies = mapper.readValue(new File("src/main/resources/movies.json"), new TypeReference<List<Movie>>(){});
            } catch (JsonParseException e) {
                e.printStackTrace();
            } catch (JsonMappingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

I have not made any other changes to the autogenerated code from JHipster's generate-sources. It is a very simple API that I was creating for a prototype


来源: stackexchange

问:
How to setup multi instance Websockets in AWS?
Trying to build a websocket based application in Spring Boot to be hosted on ec2 instance of AWS. However, whenever I try to deploy it in a multi instance setup, some of the messages are not being received. I suspect that because of connection being made to a different server and of some of the request being processed by another server, those messages are not being received by the client. Once I run the application as single instance, it works fine.

I checked the documentation for Spring Cloud but that was not of much help iin case of AWS EC2.

How can I deploy websocket based Spring Boot application on AWS in more than one instance?

Websocket configuration is as follows:

```<code>@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

  @Override
  public void configureMessageBroker(MessageBrokerRegistry config) {
    config.enableSimpleBroker("/topic", "/user");
    config.setApplicationDestinationPrefixes("/app");
    config.setUserDestinationPrefix("/user");
  }

  @Override
  public void registerStompEndpoints(StompEndpointRegistry registry) {
      registry.addEndpoint("/websocket").setAllowedOriginPatterns("*");
      registry.addEndpoint("/websocket").setAllowedOriginPatterns("*").withSockJS();
  }

}
</code>```

Sending the message to specific user using SimpMessagingTemplate:

```<code>simpMessagingTemplate.convertAndSendToUser(message.getUserId(), "/send",
                        message);
</code>```

What changes should I do on the configuration side? or while deploying on ec2 instance?

ContentLicense: CC BY-SA 4.0

Body:
Trying to build a websocket based application in Spring Boot to be hosted on ec2 instance of AWS. However, whenever I try to deploy it in a multi instance setup, some of the messages are not being received. I suspect that because of connection being made to a different server and of some of the request being processed by another server, those messages are not being received by the client. Once I run the application as single instance, it works fine.

I checked the documentation for Spring Cloud but that was not of much help iin case of AWS EC2.

How can I deploy websocket based Spring Boot application on AWS in more than one instance?

Websocket configuration is as follows:

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

  @Override
  public void configureMessageBroker(MessageBrokerRegistry config) {
    config.enableSimpleBroker("/topic", "/user");
    config.setApplicationDestinationPrefixes("/app");
    config.setUserDestinationPrefix("/user");
  }

  @Override
  public void registerStompEndpoints(StompEndpointRegistry registry) {
      registry.addEndpoint("/websocket").setAllowedOriginPatterns("*");
      registry.addEndpoint("/websocket").setAllowedOriginPatterns("*").withSockJS();
  }

}

Sending the message to specific user using SimpMessagingTemplate:

simpMessagingTemplate.convertAndSendToUser(message.getUserId(), "/send",
                        message);

What changes should I do on the configuration side? or while deploying on ec2 instance?


问:
System.Reflection.TargetInvocationException error when navigating to another page in Xamarin forms app using OnAppearing() to reload
I have this HostOffices.xaml.cs page below which allows a host to view a list of offices using a Listview, and allows the host to select an office, as well as navigate to a page for adding a new office or editing an existing office. The navigation to the EditOffice page used to work fine, however after including the OnAppearing function to set the binding context to a new instance of HostOfficesVM, the app throws a 'System.Reflection.TargetInvocationException' error when I click on an office in the list to try to navigate to the EditOffice page.

I used a try/catch block in the OfficesView_SelectionChanged method to better understand the error and it says: exception has been thrown by the target of an invocation.
I also set a breakpoint to the 'OfficesView_SelectionChanged' async void method and stepped into the app shell routing to my 'EditOffice' page. This redirected me to my 'EditOfficeVM' ViewModel which calls a 'LoadOffice()' function. It seems this is where the error is thrown because when I step into that, the error pops up at the 3rd line of the function ('Location = selectedOffice.Location;)

Clicking the details of the exception shows errors (see attached screenshot) in the TargetSite-->Declaring Type as well as the InnerException-->base-->base-->TargetSite-->Declaring type.

Any ideas on how to solve the error from here??
The referred scripts are shown below:

HostOffices.xaml.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Teamworks_2.ViewModels;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Teamworks_2.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class HostOffices : ContentPage
    {
        ViewModels.HostOfficesVM hostofficesvm;
        //Make reference to the global class
        App globalref = (App)Application.Current;

        public HostOffices()
        {
            InitializeComponent();

            hostofficesvm = new ViewModels.HostOfficesVM();
            BindingContext = hostofficesvm;
        }

        private async void OfficesView_SelectionChanged(System.Object sender, Xamarin.Forms.SelectionChangedEventArgs e)
        {
            if (e.CurrentSelection != null)
            {
                globalref.SelectedOffice = hostofficesvm.SelectedOffice;
                //Models.Office thisoffice = e.CurrentSelection[0];
                //await Shell.Current.GoToAsync($"{nameof(BookNow)}?{nameof(ViewModels.BookNowVM.CurrentOffice)}={officesvm.SelectedOffice}");
                try
                {
                    await Shell.Current.GoToAsync("EditOffice");
                }
                catch (Exception ex)
                {
                    await DisplayAlert("Error", "An error occurred while navigating to the EditOffice page: " + ex.Message, "OK");
                }
            }
        }

        void OfficesView_ItemSelected(System.Object sender, Xamarin.Forms.SelectedItemChangedEventArgs e)
        {
        }

        private async void ToolbarItem_Clicked(System.Object sender, System.EventArgs e)
        {
            await Shell.Current.GoToAsync("AddOffice");
        }
        //private async void MainMovieView_SelectionChanged(System.Object sender, Xamarin.Forms.SelectionChangedEventArgs e)

        //{
        //    if (e.CurrentSelection != null)
        //    {
        //        globalref.SelectedOffice = SelectedOffice;
        //        await Navigation.PushModalAsync(new NavigationPage(new OfficeDetails()));
        //    }
        //}

        protected override void OnAppearing()
        {
            base.OnAppearing();
            this.BindingContext = new HostOfficesVM();
        }
    }
}

</code>```

EditOfficeVM.cs (showing LoadOffice definition and declaration)

```<code>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
using Xamarin.Forms;

namespace Teamworks_2.ViewModels
{
    public class EditOfficeVM : INotifyPropertyChanged
    {
        Services.Database DBInstance = new Services.Database();

        App globalref = (App)Application.Current;

        public EditOfficeVM()
        {
            LoadOffice();
        }

     public void LoadOffice()
        {
            Models.Office selectedOffice = globalref.SelectedOffice;
            Office_name = selectedOffice.Name;
            Location = selectedOffice.Location;
            Num_guests = selectedOffice.NumGuests;
            Sqft = selectedOffice.Sqft;
            Description = selectedOffice.Description;
            pricePerhour = selectedOffice.Hourly;
            MinHours = selectedOffice.MinHours;
            Amenities = selectedOffice.Amenities;
            Features = selectedOffice.Features;
        }

</code>```

I was expecting to navigate to my EditOffice page, which used to work fine. However, after adding the Onappearing() function to refresh the ListView with the newly added office, a System.Reflection.TargetInvocationException is thrown when I try to navigate to the EditOffice page.

Body:
I have this HostOffices.xaml.cs page below which allows a host to view a list of offices using a Listview, and allows the host to select an office, as well as navigate to a page for adding a new office or editing an existing office. The navigation to the EditOffice page used to work fine, however after including the OnAppearing function to set the binding context to a new instance of HostOfficesVM, the app throws a 'System.Reflection.TargetInvocationException' error when I click on an office in the list to try to navigate to the EditOffice page.

I used a try/catch block in the OfficesView_SelectionChanged method to better understand the error and it says: exception has been thrown by the target of an invocation.
I also set a breakpoint to the 'OfficesView_SelectionChanged' async void method and stepped into the app shell routing to my 'EditOffice' page. This redirected me to my 'EditOfficeVM' ViewModel which calls a 'LoadOffice()' function. It seems this is where the error is thrown because when I step into that, the error pops up at the 3rd line of the function ('Location = selectedOffice.Location;)

Clicking the details of the exception shows errors (see attached screenshot) in the TargetSite-->Declaring Type as well as the InnerException-->base-->base-->TargetSite-->Declaring type.

Any ideas on how to solve the error from here??
The referred scripts are shown below:

HostOffices.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Teamworks_2.ViewModels;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace Teamworks_2.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class HostOffices : ContentPage
    {
        ViewModels.HostOfficesVM hostofficesvm;
        //Make reference to the global class
        App globalref = (App)Application.Current;

        public HostOffices()
        {
            InitializeComponent();

            hostofficesvm = new ViewModels.HostOfficesVM();
            BindingContext = hostofficesvm;
        }

        private async void OfficesView_SelectionChanged(System.Object sender, Xamarin.Forms.SelectionChangedEventArgs e)
        {
            if (e.CurrentSelection != null)
            {
                globalref.SelectedOffice = hostofficesvm.SelectedOffice;
                //Models.Office thisoffice = e.CurrentSelection[0];
                //await Shell.Current.GoToAsync($"{nameof(BookNow)}?{nameof(ViewModels.BookNowVM.CurrentOffice)}={officesvm.SelectedOffice}");
                try
                {
                    await Shell.Current.GoToAsync("EditOffice");
                }
                catch (Exception ex)
                {
                    await DisplayAlert("Error", "An error occurred while navigating to the EditOffice page: " + ex.Message, "OK");
                }
            }
        }

        void OfficesView_ItemSelected(System.Object sender, Xamarin.Forms.SelectedItemChangedEventArgs e)
        {
        }

        private async void ToolbarItem_Clicked(System.Object sender, System.EventArgs e)
        {
            await Shell.Current.GoToAsync("AddOffice");
        }
        //private async void MainMovieView_SelectionChanged(System.Object sender, Xamarin.Forms.SelectionChangedEventArgs e)

        //{
        //    if (e.CurrentSelection != null)
        //    {
        //        globalref.SelectedOffice = SelectedOffice;
        //        await Navigation.PushModalAsync(new NavigationPage(new OfficeDetails()));
        //    }
        //}

        protected override void OnAppearing()
        {
            base.OnAppearing();
            this.BindingContext = new HostOfficesVM();
        }
    }
}

EditOfficeVM.cs (showing LoadOffice definition and declaration)

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Text;
using Xamarin.Forms;

namespace Teamworks_2.ViewModels
{
    public class EditOfficeVM : INotifyPropertyChanged
    {
        Services.Database DBInstance = new Services.Database();

        App globalref = (App)Application.Current;

        public EditOfficeVM()
        {
            LoadOffice();
        }

     public void LoadOffice()
        {
            Models.Office selectedOffice = globalref.SelectedOffice;
            Office_name = selectedOffice.Name;
            Location = selectedOffice.Location;
            Num_guests = selectedOffice.NumGuests;
            Sqft = selectedOffice.Sqft;
            Description = selectedOffice.Description;
            pricePerhour = selectedOffice.Hourly;
            MinHours = selectedOffice.MinHours;
            Amenities = selectedOffice.Amenities;
            Features = selectedOffice.Features;
        }

I was expecting to navigate to my EditOffice page, which used to work fine. However, after adding the Onappearing() function to refresh the ListView with the newly added office, a System.Reflection.TargetInvocationException is thrown when I try to navigate to the EditOffice page.


问:
FFMPEG + PHP capture still from live video?
I'm trying to capture a new frame every X seconds from a live video on a local webserver using PHP and save it as an image file.  Obviously, we have the normal thumbnail generation of

```<code>$ffmpeg -i $vidFile -an -ss $time -s $size $imageFilename.
</code>```

But that is only for video files.  What would be the way of doing that using a live stream?

I don't even know where to start on a livestream to do this...I'm using LAMP on an ubuntu server for this.

Body:
I'm trying to capture a new frame every X seconds from a live video on a local webserver using PHP and save it as an image file.  Obviously, we have the normal thumbnail generation of

$ffmpeg -i $vidFile -an -ss $time -s $size $imageFilename.

But that is only for video files.  What would be the way of doing that using a live stream?

I don't even know where to start on a livestream to do this...I'm using LAMP on an ubuntu server for this.


问:
SmartBreadCrumbs disable Url encoding RouteValues in .net core
I am trying to set up SmartBreadCrumbs to follow the Url pattern on my website.

My category urls should look like this... /shop/Category/4/Ladies/Shoes

Shop is the area, Category is the controller, 4 is the id and /Ladies/Shoes is set up as categoryName which are set as route values.

So in my breadcrumb node I have this set out..

```<code>_node = new MvcBreadcrumbNode("Index", "Category", category.Name, areaName: "Shop") { Parent = _node, RouteValues = new { id = category.Id, categoryName = string.Join("/", categoryNames)} };
</code>```

The problem is that it is url encoding the backslash
https://localhost:7018/shop/Category/4/Women%2FShoes

Is there any way to stop RouteValues being url encoded for this specific segment?

Body:
I am trying to set up SmartBreadCrumbs to follow the Url pattern on my website.

My category urls should look like this... /shop/Category/4/Ladies/Shoes

Shop is the area, Category is the controller, 4 is the id and /Ladies/Shoes is set up as categoryName which are set as route values.

So in my breadcrumb node I have this set out..

_node = new MvcBreadcrumbNode("Index", "Category", category.Name, areaName: "Shop") { Parent = _node, RouteValues = new { id = category.Id, categoryName = string.Join("/", categoryNames)} };

The problem is that it is url encoding the backslash
https://localhost:7018/shop/Category/4/Women%2FShoes

Is there any way to stop RouteValues being url encoded for this specific segment?


问:
How to convert ByteArray to sound with Exo player
Hello I'm trying to convert Byte Array to sound with EXO PLAYER but i got issue .

When working with raw resources file every thing working fine .
this blow code belong to imported song to resources .

```<code>private suspend fun createByteArray(): Deferred<ByteArray> = withContext(Dispatchers.IO) {
    val raw = applicationContext.resources.openRawResource(R.raw.god_father)

        val buff = ByteArray(2048)

       val baos = ByteArrayOutputStream()
       while (raw.read(buff, 0, buff.size) > 0) {
          baos.write(buff, 0, buff.size)
       }
       ByteArrayInputStream(buff)
    return@withContext async { baos.toByteArray() }
}
</code>```
```<code>
fun createMediaSource(bytes: ByteArray): MediaSource {
    val byteArrayDataSource = ByteArrayDataSource(bytes)
    val factory = DataSource.Factory {
        return@Factory byteArrayDataSource
    }
    return ProgressiveMediaSource.Factory(factory).createMediaSource(
        MediaItem.fromUri(
            Uri.EMPTY
        )
    )
}
</code>```
```<code>private fun playAudio(bytes: ByteArray) {
    lifecycleScope.launch {
        // Finally assign this media source to the player
        player!!.apply {
            setMediaSource(createMediaSource(bytes))
            playWhenReady = true // start playing when the exoplayer has setup
            prepare() // Change the state from idle.
        }

    }
}

</code>```

But when I'm trying to work with Byte Array from server exo Crashing
Unrecognized Input Format Exception: None of the available extractors
After this I changed part of ProgressiveMediaSourceFactory to Below code

```<code>fun createMediaSource(bytes: ByteArray): MediaSource {
val byteArrayDataSource = ByteArrayDataSource(bytes)
val factory = DataSource.Factory {
return@Factory byteArrayDataSource
     }
return ProgressiveMediaSource.Factory(factory,
ExtractorsFactory { return@ExtractorsFactory arrayOf(Mp3Extractor()) }).createMediaSource(
MediaItem.fromUri(
Uri.EMPTY
        )
     )
 }
</code>```

And Here we go again
Second Error happened

Would you please HELP !

```<code></code>```

Body:
Hello I'm trying to convert Byte Array to sound with EXO PLAYER but i got issue .

When working with raw resources file every thing working fine .
this blow code belong to imported song to resources .

private suspend fun createByteArray(): Deferred<ByteArray> = withContext(Dispatchers.IO) {
    val raw = applicationContext.resources.openRawResource(R.raw.god_father)

        val buff = ByteArray(2048)

       val baos = ByteArrayOutputStream()
       while (raw.read(buff, 0, buff.size) > 0) {
          baos.write(buff, 0, buff.size)
       }
       ByteArrayInputStream(buff)
    return@withContext async { baos.toByteArray() }
}

fun createMediaSource(bytes: ByteArray): MediaSource {
    val byteArrayDataSource = ByteArrayDataSource(bytes)
    val factory = DataSource.Factory {
        return@Factory byteArrayDataSource
    }
    return ProgressiveMediaSource.Factory(factory).createMediaSource(
        MediaItem.fromUri(
            Uri.EMPTY
        )
    )
}

private fun playAudio(bytes: ByteArray) {
    lifecycleScope.launch {
        // Finally assign this media source to the player
        player!!.apply {
            setMediaSource(createMediaSource(bytes))
            playWhenReady = true // start playing when the exoplayer has setup
            prepare() // Change the state from idle.
        }

    }
}

But when I'm trying to work with Byte Array from server exo Crashing
Unrecognized Input Format Exception: None of the available extractors
After this I changed part of ProgressiveMediaSourceFactory to Below code

fun createMediaSource(bytes: ByteArray): MediaSource {
val byteArrayDataSource = ByteArrayDataSource(bytes)
val factory = DataSource.Factory {
return@Factory byteArrayDataSource
     }
return ProgressiveMediaSource.Factory(factory,
ExtractorsFactory { return@ExtractorsFactory arrayOf(Mp3Extractor()) }).createMediaSource(
MediaItem.fromUri(
Uri.EMPTY
        )
     )
 }

And Here we go again
Second Error happened

Would you please HELP !


问:
response.download("file") sending empty file. NodeJs, express
So, I have this function that read from a file, process the data and Writes to another, and then I do:

```<code>response.status(200).download("data/out.csv");
</code>```

The file generates fine locally, but is empty when I call the route, I tried all the events: close, finish, elc. But nothing works. I even tried to do something with couters (the commeted part) but it wont work

```<code>import { Request, Response } from "express";
import axios from 'axios';
import { parse } from '@fast-csv/parse';
import fs, { WriteStream } from "fs";

class AddressController {
  async address(request: Request, response: Response) {

    const saida = fs.createWriteStream('data/out.csv');
    const entrada = fs.createReadStream(`data/in.csv`)
    const streamCSV = parse().
      on(`data`, data => forwardGeocoding(data.join(" "), saida)).
      on("end", function(){
        response.status(200).download("data/out.csv");
      });

    entrada.pipe(streamCSV)
  }
}

// class AddressController {
//   counter = 0;

//   async address(request: Request, response: Response) {
//     var contador = 0

//     const saida = fs.createWriteStream('data/out.csv');
//     const entrada = fs.createReadStream(`data/in.csv`)
//     const streamCSV = parse().on(`data`, data => {
//       forwardGeocoding(data.join(" "), saida);
//       contador++;
//       console.log(contador)
//     });
//     entrada.pipe(streamCSV);

//     streamCSV.on('drain', () => {
//       if (contador == 200) {
//         console.log(contador)
//         saida.end()
//         response.status(200).download("data/out.csv");
//       }
//     });
//   }
// }

async function forwardGeocoding(address, saida: WriteStream) {
  var ACCESS_TOKEN = 'pk.eyJ1IjoibWF0ZXVzMmsyIiwiYSI6ImNsYmd4ZmV3MzA2ZTkzd2xjMDgzdWR2ejYifQ.RudfKTpz0CtaADWcoei8WA';

  var url = 'https://api.mapbox.com/geocoding/v5/mapbox.places/'
    + encodeURIComponent(address) + '.json?access_token='
    + ACCESS_TOKEN + '&limit=1';

  try {
    const response = await axios.get(url);

    if (response.data.features.length == 0) {
      console.log('Localização não encontrada.');
      return;
    }

    let id = Math.random() * (1000000 - 10000) + 10000
    let longitude = response.data.features[0].center[0]
    let latitude = response.data.features[0].center[1]
    let location = response.data.features[0].place_name

    saida.write(`${id},${longitude},${latitude},${location}\n`);
    // console.log(`${id},${longitude},${latitude},${location}\n`);

  } catch (error) {
    console.log('Falha na API MabBox');
    throw error;
  }

}

export { AddressController };

</code>```

Its above. The events, the couters.

Body:
So, I have this function that read from a file, process the data and Writes to another, and then I do:

response.status(200).download("data/out.csv");

The file generates fine locally, but is empty when I call the route, I tried all the events: close, finish, elc. But nothing works. I even tried to do something with couters (the commeted part) but it wont work

import { Request, Response } from "express";
import axios from 'axios';
import { parse } from '@fast-csv/parse';
import fs, { WriteStream } from "fs";

class AddressController {
  async address(request: Request, response: Response) {

    const saida = fs.createWriteStream('data/out.csv');
    const entrada = fs.createReadStream(`data/in.csv`)
    const streamCSV = parse().
      on(`data`, data => forwardGeocoding(data.join(" "), saida)).
      on("end", function(){
        response.status(200).download("data/out.csv");
      });

    entrada.pipe(streamCSV)
  }
}

// class AddressController {
//   counter = 0;

//   async address(request: Request, response: Response) {
//     var contador = 0

//     const saida = fs.createWriteStream('data/out.csv');
//     const entrada = fs.createReadStream(`data/in.csv`)
//     const streamCSV = parse().on(`data`, data => {
//       forwardGeocoding(data.join(" "), saida);
//       contador++;
//       console.log(contador)
//     });
//     entrada.pipe(streamCSV);

//     streamCSV.on('drain', () => {
//       if (contador == 200) {
//         console.log(contador)
//         saida.end()
//         response.status(200).download("data/out.csv");
//       }
//     });
//   }
// }

async function forwardGeocoding(address, saida: WriteStream) {
  var ACCESS_TOKEN = 'pk.eyJ1IjoibWF0ZXVzMmsyIiwiYSI6ImNsYmd4ZmV3MzA2ZTkzd2xjMDgzdWR2ejYifQ.RudfKTpz0CtaADWcoei8WA';

  var url = 'https://api.mapbox.com/geocoding/v5/mapbox.places/'
    + encodeURIComponent(address) + '.json?access_token='
    + ACCESS_TOKEN + '&limit=1';

  try {
    const response = await axios.get(url);

    if (response.data.features.length == 0) {
      console.log('Localização não encontrada.');
      return;
    }

    let id = Math.random() * (1000000 - 10000) + 10000
    let longitude = response.data.features[0].center[0]
    let latitude = response.data.features[0].center[1]
    let location = response.data.features[0].place_name

    saida.write(`${id},${longitude},${latitude},${location}\n`);
    // console.log(`${id},${longitude},${latitude},${location}\n`);

  } catch (error) {
    console.log('Falha na API MabBox');
    throw error;
  }

}

export { AddressController };

Its above. The events, the couters.


问:
I am trying to fix the Nuxt Js Mixed content error, unable to solve
I am getting bellow error

Mixed Content: The page at 'https://example.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://x.xxx.1x.xxx:x000/api/v1/users/slots?type=NIGHT&duration='.

But in localhost site runs smoothly with no issues. Only when i upload the build to online then i am getting this error.

this is how i configured Axios

```<code>  axios: {
    proxy: true
  },
  axios: {
    baseURL: 'http://x.xxx.x1.xxx:x000/api/v1',
  },
</code>```

Body:
I am getting bellow error

Mixed Content: The page at 'https://example.com/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://x.xxx.1x.xxx:x000/api/v1/users/slots?type=NIGHT&duration='.

But in localhost site runs smoothly with no issues. Only when i upload the build to online then i am getting this error.

this is how i configured Axios

  axios: {
    proxy: true
  },
  axios: {
    baseURL: 'http://x.xxx.x1.xxx:x000/api/v1',
  },


Title: Create a MethylSet class to hold preprocessed data for Illumina methylation microarrays

Body:
I want to generate a class met.ms to hold the preprocessed data for an Illumina methylation microarray. I used the getM function, which returns an empty matrix with 0 values.

library(minfi)

met <- as.matrix(met)
met.ms <- getM(MethylSet(Meth = met, Unmeth = met))

dput(met[1:10,1:10])

structure(c(0.461440642939772, 0.143910373119058, 0.847164847154162,
0.737361955793681, 0.716794733144112, 0.351877113536983, 0.248986769373366,
0.0121360989202765, 0.876303885229884, 0.944311384947134, 0.595894468074615,
0.0807243779293262, 0.867305510246114, 0.70680600651273, 0.217862460492399,
0.169408257004071, 0.173115013795265, 0.0108902025634162, 0.813866558997356,
0.938576461648791, 0.481304782143526, 0.437447195378987, 0.898927359292032,
0.758108726247342, 0.868604834806246, 0.577744851436078, 0.567241575633452,
0.0122683781097633, 0.881366097769717, 0.936584647488041, 0.553849599144766,
0.0642332527783939, 0.917290578229414, 0.675537604266578, 0.543087013952312,
0.85044433769089, 0.470810530680518, 0.0125681212511168, 0.870735609192125,
0.956356142020249, 0.184349035247422, 0.126118535539944, 0.928017823091886,
0.677846427070521, 0.850473788130218, 0.44473521937132, 0.204529155293748,
0.0122330126903632, 0.906102120405464, 0.938145301973259, 0.368324568853624,
0.112151024422993, 0.881981171862823, 0.695606438687072, 0.846718372472362,
0.757733166615607, 0.172813874013867, 0.0124341091006015, 0.875702288602203,
0.949350493096875, 0.17338171975844, 0.559088973726113, 0.901815470518336,
0.805920947304252, 0.640825631457383, 0.621308654785173, 0.0722588860930127,
0.0100408106849315, 0.856460615834933, 0.945808996938907, 0.805217631945182,
0.0993225901397478, 0.889537978677822, 0.691597185851671, 0.813122933295151,
0.710712761159508, 0.579117830986195, 0.0145401029579807, 0.833725365229449,
0.930732020027994, 0.113336454896178, 0.0871408483321741, 0.879968490399937,
0.549769911227498, 0.283154379541085, 0.48310833426734, 0.0694935460463862,
0.0126142511240202, 0.885015967416138, 0.933393915741336, 0.451013557269167,
0.0954830889751504, 0.877101253439035, 0.700443114118019, 0.645773476077286,
0.446177255074733, 0.389318735766059, 0.0155373951272166, 0.882984941909313,
0.92890097781832), dim = c(10L, 10L), dimnames = list(c("cg00000029",
"cg00000165", "cg00000236", "cg00000289", "cg00000292", "cg00000321",
"cg00000363", "cg00000622", "cg00000658", "cg00000721"), c("TCGA-2K-A9WE-01A",
"TCGA-2Z-A9J1-01A", "TCGA-2Z-A9J2-01A", "TCGA-2Z-A9J3-01A", "TCGA-2Z-A9J5-01A",
"TCGA-2Z-A9J6-01A", "TCGA-2Z-A9J7-01A", "TCGA-2Z-A9J8-01A", "TCGA-2Z-A9J9-01A",
"TCGA-2Z-A9JD-01A")))


问:
Transpose specific columns to rows in Pandas
I have a situation where I would like to transpose a certain set of columns in my dataframe to rows. The columns range which I want to transpose starts from the fourth column till the last column. There are multiple datasets so one of the datasets can have 10 columns the other one could have 20. The idea is to transpose the columns starting from fourth to the last column.

My example dataset looks like this:

```<code>s_date       e_date       response_id   Q1    Q2    Q3    Q4   Q5
12/12/2020   12/12/2020   1             Yes   No    Good  No   Yes
</code>```

I want this set to transposed as following:

```<code>s_date       e_date       response_id   Question_text    Question_Response
12/12/2020   12/12/2020   1             Q1               Yes
16/12/2020   17/12/2020   1             Q2               No
15/12/2020   18/12/2020   1             Q3               Good
14/12/2020   19/12/2020   1             Q4               No
13/12/2020   20/12/2020   1             Q5               Yes
</code>```

How can I achieve this?

Body:
I have a situation where I would like to transpose a certain set of columns in my dataframe to rows. The columns range which I want to transpose starts from the fourth column till the last column. There are multiple datasets so one of the datasets can have 10 columns the other one could have 20. The idea is to transpose the columns starting from fourth to the last column.

My example dataset looks like this:

s_date       e_date       response_id   Q1    Q2    Q3    Q4   Q5
12/12/2020   12/12/2020   1             Yes   No    Good  No   Yes

I want this set to transposed as following:

s_date       e_date       response_id   Question_text    Question_Response
12/12/2020   12/12/2020   1             Q1               Yes
16/12/2020   17/12/2020   1             Q2               No
15/12/2020   18/12/2020   1             Q3               Good
14/12/2020   19/12/2020   1             Q4               No
13/12/2020   20/12/2020   1             Q5               Yes

How can I achieve this?


问:
check my array if the route element exist in my array
- Set up the basis for CRUD

```<code>const movies = { title: 'Jaws', year: 1975, rating: 8 },{ title: 'Avatar', year: 2009, rating: 7.8 },{ title: 'Brazil', year: 1985, rating: 8 },{ title: 'The Shaw shank', year: 1992, rating: 6.2 }
</code>```

With Express, make it so that when the URL /movies/read is requested, you answer with

```<code>{status:200, data:\<MOVIES\> }
</code>```

where \<MOVIES\> is the list of movies    i tried to put if condition but not work with me

Body:
- Set up the basis for CRUD

const movies = { title: 'Jaws', year: 1975, rating: 8 },{ title: 'Avatar', year: 2009, rating: 7.8 },{ title: 'Brazil', year: 1985, rating: 8 },{ title: 'The Shaw shank', year: 1992, rating: 6.2 }

With Express, make it so that when the URL /movies/read is requested, you answer with

{status:200, data:\<MOVIES\> }

where \<MOVIES\> is the list of movies    i tried to put if condition but not work with me


问:
on-disk B-tree: defer appending new pages to file
I am implementing an on-disk B-tree, and I have a question about creating new pages. According to the little information I found, when need to add new page I should append a new block to the B-tree file and then read it through buffer manager. I read the code of some databases, and found that basically they all append a new block to file before writing the corresponding buffer. I am wondering can I defer writing to disk when creating new pages.

Can I just keep a next_page_id record for each file in memory, add new pages in buffer pool, write those pages, and append them to files in the order of page_id when flushing pages? Are there any problems in this approach?


问:
Rewrite LearnDash Wordpress(WP) Permalinks
I've looked through a bunch of similar questions and can't seem to find an answer for my circumstances. I have LearnDash(LD) installed on my WP site and the default permalinks that it shows are as follows:

```<code>COURSES
/courses/COURSE-TITLE/
LESSONS
/courses/COURSE-TITLE/lessons/LESSON-TITLE/
TOPICS
/courses/COURSE-TITLE/lessons/LESSON-TITLE/topics/TOPIC-TITLE/
QUIZZES
/courses/COURSE-TITLE/lessons/LESSON-TITLE/quizzes/QUIZ-TITLE/
</code>```

What I am trying to accomplish is when you publish or view a lesson, the slug would be the course title and the # of the lesson within the course. So as follows

```<code>coursetitle/#
</code>```

and then a similar slug with the topics and quizzes

```<code>coursetitle/#/topic or quiz title/
</code>```

I got the coding figured out for the lesson number, and have it set as a variable, but can't figure out the rest.

I know it's possible as LD describes most of what I am trying to do in their documentation, but I have tried to follow it and can't figure out how to get it to work. I either end up with a 404 error or nothing changes at all. I know I have to add the generate_rewrite_rules hook and possibly also the post_type_link filter, but I have never worked with either of these and am kinda lost as nothing is working for me.

I've spent hours trying to figure this out without any luck so if you have any ideas or thoughts on how to accomplish what I am trying to do, any help would be much appreciated.

Body:
I've looked through a bunch of similar questions and can't seem to find an answer for my circumstances. I have LearnDash(LD) installed on my WP site and the default permalinks that it shows are as follows:

COURSES
/courses/COURSE-TITLE/
LESSONS
/courses/COURSE-TITLE/lessons/LESSON-TITLE/
TOPICS
/courses/COURSE-TITLE/lessons/LESSON-TITLE/topics/TOPIC-TITLE/
QUIZZES
/courses/COURSE-TITLE/lessons/LESSON-TITLE/quizzes/QUIZ-TITLE/

What I am trying to accomplish is when you publish or view a lesson, the slug would be the course title and the # of the lesson within the course. So as follows

coursetitle/#

and then a similar slug with the topics and quizzes

coursetitle/#/topic or quiz title/

I got the coding figured out for the lesson number, and have it set as a variable, but can't figure out the rest.

I know it's possible as LD describes most of what I am trying to do in their documentation, but I have tried to follow it and can't figure out how to get it to work. I either end up with a 404 error or nothing changes at all. I know I have to add the generate_rewrite_rules hook and possibly also the post_type_link filter, but I have never worked with either of these and am kinda lost as nothing is working for me.

I've spent hours trying to figure this out without any luck so if you have any ideas or thoughts on how to accomplish what I am trying to do, any help would be much appreciated.


问:
how to update stdscr size with python curses after resizing the terminal
I tried searching everywhere on the internet, but nowhere did I find an answer that worked for me, so I'm asking a new question.

In my code, I'm telling curses to get the terminal size and update some variables according to it. On my first try, I did something like this (this is the function that gets called after the window has been resized manually):

```<code>def resize():
    rows, cols = stdscr.getmaxyx()
    #some more code irrelevant to the question
</code>```

When I found out that doesn't work, I realised that the stdscr is probably not getting resized, even though the terminal is. So I tried closing the stdscr and initialising it again:

```<code>def resize():
    curses.endwin()
    curses.wrapper(initialise)
    #some more code that's irrelevant to the question

#showing the initialise function just in case:
def initialise(stdscrarg):
    global stdscr
    stdscr = stdscrarg
</code>```

That, however, also didn't work. In other words, the stdscr initialised in the size that the terminal had before resizing. i.e. if I had a terminal over a quarter of my screen and then resized it to full screen, the function would correctly deal with the warping of the text, but it would redraw the content adjusted to just the original quarter of the screen, and would leave the junk characters in the rest of the screen, like this:

Before resizing

After resizing, before refreshing

After refreshing.

As you can see, the stdscr has initialised to its original size instead of taking on the size of the terminal. And I have tested it and confirmed that it really is the size of the stdscr, and not just the text printed on it (as when I gradually add strings to it, it throws an error when it reaches the end of the original size screen, instead of continuing to the end of the terminal screen and only then throwing an error.)

My question is: How can I get the new size of the terminal and make stdscr initialise with this new size?

Working on Windows 11, Python 3.10, module curses (though when installing it through pip, its name is windows-curses)

Body:
I tried searching everywhere on the internet, but nowhere did I find an answer that worked for me, so I'm asking a new question.

In my code, I'm telling curses to get the terminal size and update some variables according to it. On my first try, I did something like this (this is the function that gets called after the window has been resized manually):

def resize():
    rows, cols = stdscr.getmaxyx()
    #some more code irrelevant to the question

When I found out that doesn't work, I realised that the stdscr is probably not getting resized, even though the terminal is. So I tried closing the stdscr and initialising it again:

def resize():
    curses.endwin()
    curses.wrapper(initialise)
    #some more code that's irrelevant to the question

#showing the initialise function just in case:
def initialise(stdscrarg):
    global stdscr
    stdscr = stdscrarg

That, however, also didn't work. In other words, the stdscr initialised in the size that the terminal had before resizing. i.e. if I had a terminal over a quarter of my screen and then resized it to full screen, the function would correctly deal with the warping of the text, but it would redraw the content adjusted to just the original quarter of the screen, and would leave the junk characters in the rest of the screen, like this:

Before resizing

After resizing, before refreshing

After refreshing.

As you can see, the stdscr has initialised to its original size instead of taking on the size of the terminal. And I have tested it and confirmed that it really is the size of the stdscr, and not just the text printed on it (as when I gradually add strings to it, it throws an error when it reaches the end of the original size screen, instead of continuing to the end of the terminal screen and only then throwing an error.)

My question is: How can I get the new size of the terminal and make stdscr initialise with this new size?

Working on Windows 11, Python 3.10, module curses (though when installing it through pip, its name is windows-curses)


问:
How to generate a uuid in form of [u8; 16] in rust dfinity ICP?
I tried this way, but the canister seems to have difficulties serialise the [u8; 16], I also tried to use the Uuid package and the canister failed even when I just use Uuid::preload::*;

#[update]
#[candid_method(update)]
pub async fn test_create_id() -> String {
    let id: ([u8; 16], ) = ic_cdk::api::call::call(
        ic_cdk::export::Principal::management_canister(),
        "raw_rand",
        (),
    ).await.unwrap(); //<---- it is Panicking here?
    return format!("{:#?}", id)
}
```
<pre class="lang-none prettyprint-override"><code>[Canister rrkah-fqaaa-aaaaa-aaaaq-cai] Panicked at 'called `Result::unwrap()` on an `Err` value: (CanisterError, "failed to decode canister response as (): Trailing value after finishing deserialization")', canisters/backend/src/files/update.rs:73:34
[Canister rrkah-fqaaa-aaaaa-aaaaq-cai] Panicked at 'called `Result::unwrap()` on an `Err` value: (NoError, "cleanup")', canisters/backend/src/files/update.rs:73:34
</code>```

Maybe there are other ways to generate Uuids?

Body:
I tried this way, but the canister seems to have difficulties serialise the [u8; 16], I also tried to use the Uuid package and the canister failed even when I just use Uuid::preload::*;

#[update]
#[candid_method(update)]
pub async fn test_create_id() -> String {
    let id: ([u8; 16], ) = ic_cdk::api::call::call(
        ic_cdk::export::Principal::management_canister(),
        "raw_rand",
        (),
    ).await.unwrap(); //<---- it is Panicking here?
    return format!("{:#?}", id)
}

[Canister rrkah-fqaaa-aaaaa-aaaaq-cai] Panicked at 'called `Result::unwrap()` on an `Err` value: (CanisterError, "failed to decode canister response as (): Trailing value after finishing deserialization")', canisters/backend/src/files/update.rs:73:34
[Canister rrkah-fqaaa-aaaaa-aaaaq-cai] Panicked at 'called `Result::unwrap()` on an `Err` value: (NoError, "cleanup")', canisters/backend/src/files/update.rs:73:34

Maybe there are other ways to generate Uuids?


问:
C++ Text Adventure, Trying to use vector as validation to create individualized story for that path and arrays if path is choosen
Im looking to take my vector and depending on the p_room[] choosen give a special dialog and crerate a array for that specific vector. for example if the user goes from startingRoom to startingEast then to eastlvl1 i want a special dialog for the eastlvl1 i tried if statments but they appear when the app is first ran. i want a way to create path specific dialog along with creating arrays along that path so if they reach a certain point and find an object i can create an array and store the object. but i dont want the user to always have an inventory i only want it to exist once they find an object if they find

```<code>#include <iostream>
#include <vector>
#include <string>
#include "Room.h"

using namespace std;

class Program{
    public:
    Program();
    ~Program();
    void setUpRooms();

    void Run();

    private:

    int createRoom(string name, string description);

    void handleUserInput();
    Room* p_ptrCurrentRooms;
    vector<Room*> p_rooms;
    bool p_done;

    Room customRoom();
};

Program::Program(){
    p_ptrCurrentRooms = nullptr;
    setUpRooms();
    p_done = false;
}

void Program::Run() {
    string status = "";

    while (!p_done){

        p_ptrCurrentRooms->outputRoomInfo();

        handleUserInput() ;

         Menu::Pause();
    }
}
void Program::setUpRooms() {

    int spawn = createRoom("your house","theres a flash of light");

    int startingRoom = createRoom("Town Center","You appear in a mysteries town");
    int startingNorth = createRoom("Capital","You enter the capital");
    int startingSouth = createRoom("Dense Forest","You enter a forest where light can barely reach the ground");
    int startingEast = createRoom("Ocean","You have reached an ocean");
    int startingWest = createRoom("Town","you have traveled deeper into town");

    int northLevel1 = createRoom("Castle","you find a massive castle");
    int northSthLevel1 = createRoom("Town center","Back at the town center but it looks different from before, yet you are unsure how");
    int northEstLevel1 = createRoom("Ocean","You have reached a port");
    int northWstLevel1 = createRoom("Slums","A dirtier and much more unpleasant place compared to previous surroundings ");

    int northLvl2 = createRoom("Castle","you reach the castle gate and are stopped by guards, you explain your situation. They look you over and can clearly tell you arent"
                                        " from there at least and allow you to pass with an escort. continue north to proceed with your escort.  ");
    //northSthLevel1
    int northEstLvl2 = createRoom("Castle","You walk the castle wall, it is miles long and even taller. made from a hard stone you've never seen before");
    int northWstLvl2 = createRoom("Castle","You walk the castle wall, it is miles long and even taller. made from a hard stone you've never seen before");

    int southLevel1 = createRoom("Dense Forest","You travel deeper into the the dense forest, nothing interesting found");
    int southNorthLevel1 = createRoom("Dense forest","The forest was so dark and dense when you entered... are you lost?");
    int southEstLevel1 = createRoom("Dense Forest","just more forest nothing interesting.");
    int southWstLevel1 = createRoom("Dense Forest","just more forest nothing interesting.");
    int southLevel2 = createRoom("Dense Forest","You travel deeper into the the dense forest, nothing interesting found");
    int southNrthLvl2 = createRoom("Dense Forest","You reach the edge of the forest, you've made it out.");
    int southEstLvl2 = createRoom("Dense Forest","just more forest nothing interesting. its starting to get dark");
    int southWstLvl2 = createRoom("Dense Forest","just more forest nothing interesting. its starting to get dark");

    int eastLvl1 = createRoom("Ocean","You have entered the ocean continue east to swim further into ocean");
    int eastNrthLvl1 = createRoom("Port","you found a port, continue east from here to board a ship");
    int eastSthlvl1 = createRoom("Market","you find a market that sells a variety of the days catches");
    //use northsthlvl1
    int eastlvl2 = createRoom("Ocean","you have started your swim into the ocean");
    int eastNrthLvl2 = createRoom("Port","you continue along the port, continue east from here to board a ship");
    int eastSthlvl2 = createRoom("Market","you continue along the market that sells a variety of the days catches");
    //use northSouthLevel1

    int westLvl1 = createRoom("Town","The path you where walking opens into a large square with shops spread throughout the square");
    int westNrthLvl1 = createRoom("Town","You come across a building marked Guild. by its stature maybe it has some importance or information. continue North to enter");
    int westSthLvl1 = createRoom("Town","Hunters Lodge... wonder what information they may carry");
    // use northSthLevel1

    int westLvl2 = createRoom("Town square","You've entered teh center of the town square you are surrounded by shops. continue North, South, West to enter a shop and east to back up");
    int westNrthLvl2 = createRoom("Guild","you've entered the guild the building seems bigger on the inside, it seems over whelming. - Continue North, West, or East to venture through guild and south to exit");
    int westSthLvl2 = createRoom("Hunters Lodge","you have entered the lodge there are mounts of unknown animals on the wall. - Continue South, West, East to explore lodge and North to exit");
    //use northSthLevel1

    // NORTH, SOUTH, EAST, WEST
    p_rooms[spawn]->setNeighbors( p_rooms[startingRoom],p_rooms[startingRoom], p_rooms[startingRoom], p_rooms[startingRoom]);
    p_rooms[startingRoom]->setNeighbors(p_rooms[startingNorth],p_rooms[startingSouth],p_rooms[startingEast], p_rooms[startingWest]);
    p_rooms[startingNorth]->setNeighbors(p_rooms[northLevel1], p_rooms[northSthLevel1], p_rooms[northEstLevel1], p_rooms[northWstLevel1]);
    p_rooms[startingSouth]->setNeighbors(p_rooms[southNorthLevel1],p_rooms[southLevel1],p_rooms[southEstLevel1],p_rooms[southWstLevel1]);
    p_rooms[startingEast]->setNeighbors(p_rooms[eastNrthLvl1],p_rooms[eastSthlvl1],p_rooms[eastLvl1],p_rooms[northSthLevel1]);
    p_rooms[startingWest]->setNeighbors(p_rooms[westNrthLvl1], p_rooms[westSthLvl1], p_rooms[northSthLevel1], p_rooms[westLvl1]);
    p_rooms[northLevel1]->setNeighbors(p_rooms[northLvl2],p_rooms[northSthLevel1], p_rooms[northEstLvl2], p_rooms[northWstLvl2]);
    p_rooms[southLevel1]->setNeighbors(p_rooms[southNrthLvl2], p_rooms[southLevel2], p_rooms[southEstLvl2], p_rooms[southWstLvl2]);
    p_rooms[eastLvl1]->setNeighbors(p_rooms[eastNrthLvl2], p_rooms[eastSthlvl2], p_rooms[eastlvl2], p_rooms[northSthLevel1]);
    p_rooms[westLvl1]->setNeighbors(p_rooms[westNrthLvl2], p_rooms[westSthLvl2], p_rooms[northSthLevel1], p_rooms[westLvl2]);

p_ptrCurrentRooms = p_rooms[spawn];
}
int Program::createRoom(string name, string description){
    int index = p_rooms.size();

    Room* room = new Room;

    room->setUp(name, description);
    p_rooms.push_back(room);

    return index;
}

void Program::handleUserInput(){
    string userIn;
    userIn = Menu::GetStringLine("What would you like to do next");
    if(StringUtil::ToLower(userIn) == "north" || StringUtil::ToLower(userIn) == "n"){

        if(p_ptrCurrentRooms->canGo(NORTH)){
           cout << "you went North";
            p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborNorth;
        }else{
            cout << "you cant go north";
        }
    }
    else if(StringUtil::ToLower(userIn) == "south" || StringUtil::ToLower(userIn) == "s"){
        if(p_ptrCurrentRooms->canGo(SOUTH)){
            cout << "you went South";
            p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborSouth;
        }else{
            cout << "you cant go South";
        }
    }
    else if(StringUtil::ToLower(userIn) == "east" || StringUtil::ToLower(userIn) == "e"){
        if(p_ptrCurrentRooms->canGo(EAST)){
            cout << "you went East";
            p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborEast;

        }else{
            cout << "you cant go East";
        }
    }
   else if(StringUtil::ToLower(userIn) == "west" ||StringUtil::ToLower(userIn) == "w" ){
        if(p_ptrCurrentRooms->canGo(WEST)){
            cout<< "you went west";
            p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborWest;
        }else{
            cout<< "you cant go west";
        }
    } else{
       cout<< "Unknown command";
   }
}
Program::~Program(){
    for(auto ptrRoom : p_rooms){
        if(ptrRoom!= nullptr){
            delete ptrRoom;
        }
    }

}
</code>```

ive tried p_room.at() or declaring the specific room in if staments but all that does is print the message first in the console

Body:
Im looking to take my vector and depending on the p_room[] choosen give a special dialog and crerate a array for that specific vector. for example if the user goes from startingRoom to startingEast then to eastlvl1 i want a special dialog for the eastlvl1 i tried if statments but they appear when the app is first ran. i want a way to create path specific dialog along with creating arrays along that path so if they reach a certain point and find an object i can create an array and store the object. but i dont want the user to always have an inventory i only want it to exist once they find an object if they find

#include <iostream>
#include <vector>
#include <string>
#include "Room.h"

using namespace std;

class Program{
    public:
    Program();
    ~Program();
    void setUpRooms();

    void Run();

    private:

    int createRoom(string name, string description);

    void handleUserInput();
    Room* p_ptrCurrentRooms;
    vector<Room*> p_rooms;
    bool p_done;

    Room customRoom();
};

Program::Program(){
    p_ptrCurrentRooms = nullptr;
    setUpRooms();
    p_done = false;
}

void Program::Run() {
    string status = "";

    while (!p_done){

        p_ptrCurrentRooms->outputRoomInfo();

        handleUserInput() ;

         Menu::Pause();
    }
}
void Program::setUpRooms() {

    int spawn = createRoom("your house","theres a flash of light");

    int startingRoom = createRoom("Town Center","You appear in a mysteries town");
    int startingNorth = createRoom("Capital","You enter the capital");
    int startingSouth = createRoom("Dense Forest","You enter a forest where light can barely reach the ground");
    int startingEast = createRoom("Ocean","You have reached an ocean");
    int startingWest = createRoom("Town","you have traveled deeper into town");

    int northLevel1 = createRoom("Castle","you find a massive castle");
    int northSthLevel1 = createRoom("Town center","Back at the town center but it looks different from before, yet you are unsure how");
    int northEstLevel1 = createRoom("Ocean","You have reached a port");
    int northWstLevel1 = createRoom("Slums","A dirtier and much more unpleasant place compared to previous surroundings ");

    int northLvl2 = createRoom("Castle","you reach the castle gate and are stopped by guards, you explain your situation. They look you over and can clearly tell you arent"
                                        " from there at least and allow you to pass with an escort. continue north to proceed with your escort.  ");
    //northSthLevel1
    int northEstLvl2 = createRoom("Castle","You walk the castle wall, it is miles long and even taller. made from a hard stone you've never seen before");
    int northWstLvl2 = createRoom("Castle","You walk the castle wall, it is miles long and even taller. made from a hard stone you've never seen before");

    int southLevel1 = createRoom("Dense Forest","You travel deeper into the the dense forest, nothing interesting found");
    int southNorthLevel1 = createRoom("Dense forest","The forest was so dark and dense when you entered... are you lost?");
    int southEstLevel1 = createRoom("Dense Forest","just more forest nothing interesting.");
    int southWstLevel1 = createRoom("Dense Forest","just more forest nothing interesting.");
    int southLevel2 = createRoom("Dense Forest","You travel deeper into the the dense forest, nothing interesting found");
    int southNrthLvl2 = createRoom("Dense Forest","You reach the edge of the forest, you've made it out.");
    int southEstLvl2 = createRoom("Dense Forest","just more forest nothing interesting. its starting to get dark");
    int southWstLvl2 = createRoom("Dense Forest","just more forest nothing interesting. its starting to get dark");

    int eastLvl1 = createRoom("Ocean","You have entered the ocean continue east to swim further into ocean");
    int eastNrthLvl1 = createRoom("Port","you found a port, continue east from here to board a ship");
    int eastSthlvl1 = createRoom("Market","you find a market that sells a variety of the days catches");
    //use northsthlvl1
    int eastlvl2 = createRoom("Ocean","you have started your swim into the ocean");
    int eastNrthLvl2 = createRoom("Port","you continue along the port, continue east from here to board a ship");
    int eastSthlvl2 = createRoom("Market","you continue along the market that sells a variety of the days catches");
    //use northSouthLevel1

    int westLvl1 = createRoom("Town","The path you where walking opens into a large square with shops spread throughout the square");
    int westNrthLvl1 = createRoom("Town","You come across a building marked Guild. by its stature maybe it has some importance or information. continue North to enter");
    int westSthLvl1 = createRoom("Town","Hunters Lodge... wonder what information they may carry");
    // use northSthLevel1

    int westLvl2 = createRoom("Town square","You've entered teh center of the town square you are surrounded by shops. continue North, South, West to enter a shop and east to back up");
    int westNrthLvl2 = createRoom("Guild","you've entered the guild the building seems bigger on the inside, it seems over whelming. - Continue North, West, or East to venture through guild and south to exit");
    int westSthLvl2 = createRoom("Hunters Lodge","you have entered the lodge there are mounts of unknown animals on the wall. - Continue South, West, East to explore lodge and North to exit");
    //use northSthLevel1

    // NORTH, SOUTH, EAST, WEST
    p_rooms[spawn]->setNeighbors( p_rooms[startingRoom],p_rooms[startingRoom], p_rooms[startingRoom], p_rooms[startingRoom]);
    p_rooms[startingRoom]->setNeighbors(p_rooms[startingNorth],p_rooms[startingSouth],p_rooms[startingEast], p_rooms[startingWest]);
    p_rooms[startingNorth]->setNeighbors(p_rooms[northLevel1], p_rooms[northSthLevel1], p_rooms[northEstLevel1], p_rooms[northWstLevel1]);
    p_rooms[startingSouth]->setNeighbors(p_rooms[southNorthLevel1],p_rooms[southLevel1],p_rooms[southEstLevel1],p_rooms[southWstLevel1]);
    p_rooms[startingEast]->setNeighbors(p_rooms[eastNrthLvl1],p_rooms[eastSthlvl1],p_rooms[eastLvl1],p_rooms[northSthLevel1]);
    p_rooms[startingWest]->setNeighbors(p_rooms[westNrthLvl1], p_rooms[westSthLvl1], p_rooms[northSthLevel1], p_rooms[westLvl1]);
    p_rooms[northLevel1]->setNeighbors(p_rooms[northLvl2],p_rooms[northSthLevel1], p_rooms[northEstLvl2], p_rooms[northWstLvl2]);
    p_rooms[southLevel1]->setNeighbors(p_rooms[southNrthLvl2], p_rooms[southLevel2], p_rooms[southEstLvl2], p_rooms[southWstLvl2]);
    p_rooms[eastLvl1]->setNeighbors(p_rooms[eastNrthLvl2], p_rooms[eastSthlvl2], p_rooms[eastlvl2], p_rooms[northSthLevel1]);
    p_rooms[westLvl1]->setNeighbors(p_rooms[westNrthLvl2], p_rooms[westSthLvl2], p_rooms[northSthLevel1], p_rooms[westLvl2]);

p_ptrCurrentRooms = p_rooms[spawn];
}
int Program::createRoom(string name, string description){
    int index = p_rooms.size();

    Room* room = new Room;

    room->setUp(name, description);
    p_rooms.push_back(room);

    return index;
}

void Program::handleUserInput(){
    string userIn;
    userIn = Menu::GetStringLine("What would you like to do next");
    if(StringUtil::ToLower(userIn) == "north" || StringUtil::ToLower(userIn) == "n"){

        if(p_ptrCurrentRooms->canGo(NORTH)){
           cout << "you went North";
            p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborNorth;
        }else{
            cout << "you cant go north";
        }
    }
    else if(StringUtil::ToLower(userIn) == "south" || StringUtil::ToLower(userIn) == "s"){
        if(p_ptrCurrentRooms->canGo(SOUTH)){
            cout << "you went South";
            p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborSouth;
        }else{
            cout << "you cant go South";
        }
    }
    else if(StringUtil::ToLower(userIn) == "east" || StringUtil::ToLower(userIn) == "e"){
        if(p_ptrCurrentRooms->canGo(EAST)){
            cout << "you went East";
            p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborEast;

        }else{
            cout << "you cant go East";
        }
    }
   else if(StringUtil::ToLower(userIn) == "west" ||StringUtil::ToLower(userIn) == "w" ){
        if(p_ptrCurrentRooms->canGo(WEST)){
            cout<< "you went west";
            p_ptrCurrentRooms = p_ptrCurrentRooms->ptrNeighborWest;
        }else{
            cout<< "you cant go west";
        }
    } else{
       cout<< "Unknown command";
   }
}
Program::~Program(){
    for(auto ptrRoom : p_rooms){
        if(ptrRoom!= nullptr){
            delete ptrRoom;
        }
    }

}

ive tried p_room.at() or declaring the specific room in if staments but all that does is print the message first in the console


问:
How to create this dynamic PIVOT view where the price of 3 fruits are not changing simultaneously?
The Initial Data View, we have
Lets consider this table as Table A.
Here we can see that there are 3 markets: A,B,C and there are 3 fruits: Apple, Banana, Strawberry.
There is Start Date and End Date for each of the fruits of each market. These dates imply that the price of the fruit is applicable b/w that interval of dates. If the End Date is empty that means the rate is still applicable.

Now from this table, we want a transposed view of the table. And the final output we want is:
The View, we want
Lets consider this table as Table B.

This looks like a simple PIVOT function in SQL to transpose the rates and we tried that. But the result we are getting is not expected. The output is coming out to be:
The Output, we are getting
Lets consider this table as Table C.

The problem is that as in markets A and B, the rates of the 3 fruits are not simultaneously changing, the PIVOT function is not giving expected results.

We have tried the simple pivot function on the Table A:

The code we are using for the PIVOT-

PIVOT(MAX(PRICE/kg)) FOR FRUIT IN
('Apple_Price', 'Banana_Price', 'Strawberry_Price')
AS (MARKET, START_DATE, END_DATE, Apple_Price, Banana_Price, Strawberry_Price)

We have also tried another method where we tried to join 3 times separately Table A. But it is also not working.


问:
Console not printing fast enough c#
I am writing a small libary to draw "graphics" to a console to make writing console games easier, but whenever a frame is renedered, it is very slow
I am new to c#, however I have been coding for 8 months.

I have optimized it as much as I can but I have had no succsess(keep in mind i'm writing this on an ASUS 2016 laptop)

So here is the code:

```<code>Console.Title = "Pyrite";
int winWidth = Console.BufferWidth;
int winHeight = Console.BufferHeight / 190;
char[,] screen = new char[winWidth, winHeight];
ConsoleColor[,] screenColours = new ConsoleColor[winWidth, winHeight];

for(int j = 0; j < screen.GetLength(1); j += 1){
    for(int i = 0; i < screen.GetLength(0); i += 1){
        screenColours[i, j] = ConsoleColor.Green;
        screen[i, j] = '■';
    }
}

void drawPixel(int x, int y, char character, ConsoleColor colour){
    screenColours[x, y] = colour;
    screen[x, y] = character;
}

void drawRect(int x, int y, int width, int height, char character, bool outlineOnly, ConsoleColor colour){
    if(!outlineOnly){
        for(int j = 0; j < height + 1; j += 1){
            for(int i = 0; i < width + 1; i += 1){
                drawPixel(i + x, j + y, character, colour);
            }
        }
    }else{
        for(int i = 0; i < width + 1; i += 1){
            drawPixel(x + i, y, character, colour);
        }

        for(int i = 0; i < width + 1; i += 1){
            drawPixel(x + i, y + height, character, colour);
        }

        for(int i = 0; i < height + 1; i += 1){
            drawPixel(x, y + i, character, colour);
        }

        for(int i = 0; i < height + 1; i += 1){
            drawPixel(x + width, y + i, character, colour);
        }
    }
}

void draw(){
    for(int j = 0; j < screen.GetLength(1); j += 1){
        for(int i = 0; i < screen.GetLength(0); i += 1){
            Console.ForegroundColor = screenColours[i, j];
            Console.Write(screen[i, j]);
        }
    }
}

while(true){
    drawPixel(20, 20, '■', ConsoleColor.Cyan);
    drawRect(0, 0, 25, 15, '■', true, ConsoleColor.DarkMagenta);
    draw();
    Console.Clear();
    Console.ResetColor();
}
Console.ReadKey();

</code>```

Title: Console not printing fast enough c#

Body:
I am writing a small libary to draw "graphics" to a console to make writing console games easier, but whenever a frame is renedered, it is very slow
I am new to c#, however I have been coding for 8 months.

I have optimized it as much as I can but I have had no succsess(keep in mind i'm writing this on an ASUS 2016 laptop)

So here is the code:

Console.Title = "Pyrite";
int winWidth = Console.BufferWidth;
int winHeight = Console.BufferHeight / 190;
char[,] screen = new char[winWidth, winHeight];
ConsoleColor[,] screenColours = new ConsoleColor[winWidth, winHeight];

for(int j = 0; j < screen.GetLength(1); j += 1){
    for(int i = 0; i < screen.GetLength(0); i += 1){
        screenColours[i, j] = ConsoleColor.Green;
        screen[i, j] = '■';
    }
}

void drawPixel(int x, int y, char character, ConsoleColor colour){
    screenColours[x, y] = colour;
    screen[x, y] = character;
}

void drawRect(int x, int y, int width, int height, char character, bool outlineOnly, ConsoleColor colour){
    if(!outlineOnly){
        for(int j = 0; j < height + 1; j += 1){
            for(int i = 0; i < width + 1; i += 1){
                drawPixel(i + x, j + y, character, colour);
            }
        }
    }else{
        for(int i = 0; i < width + 1; i += 1){
            drawPixel(x + i, y, character, colour);
        }

        for(int i = 0; i < width + 1; i += 1){
            drawPixel(x + i, y + height, character, colour);
        }

        for(int i = 0; i < height + 1; i += 1){
            drawPixel(x, y + i, character, colour);
        }

        for(int i = 0; i < height + 1; i += 1){
            drawPixel(x + width, y + i, character, colour);
        }
    }
}

void draw(){
    for(int j = 0; j < screen.GetLength(1); j += 1){
        for(int i = 0; i < screen.GetLength(0); i += 1){
            Console.ForegroundColor = screenColours[i, j];
            Console.Write(screen[i, j]);
        }
    }
}

while(true){
    drawPixel(20, 20, '■', ConsoleColor.Cyan);
    drawRect(0, 0, 25, 15, '■', true, ConsoleColor.DarkMagenta);
    draw();
    Console.Clear();
    Console.ResetColor();
}
Console.ReadKey();


问:
AWS API Signature Does Not Match
```<code>{
    "errors": [
        {
            "message": "<below>",
            "code": "InvalidSignature"
        }
    ]
}
</code>```

Message:

The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details. The Canonical String for this request should have been [[redacted]]

However my inputs are

```<code><cfscript>
    // define a struct for arguments
    args={}
    // Input fields
    args.requestMethod='GET'
    args.hostName='[[hostname]]'
    args.requestURI='[[requestURL]]'
    args.requestBody=""
    args.requestHeaders={}
    args.requestParams={}
    args.signedPayload=true
    args.excludeHeaders=[]
    args.regionName='us-east-1'
    args.serviceName='execute-api'
    args.amzDate=aDate
    args.dateStamp=dateStamp
    args.signatureData={}
    args.tokenData={}
</cfscript>

<cfhttp method="put" url="[[URL]]" result="result">
    <cfhttpparam type="header" name="Authorization" value="#signatureData.AUTHORIZATIONHEADER#">
    <cfhttpparam type="header" name="x-amz-access-token" value="#tokenData.access_token#">
    <cfhttpparam type="header" name="X-Amz-Date" value="#aDate#">
</cfhttp>
</code>```

Title: AWS API Signature Does Not Match

Body:
{
    "errors": [
        {
            "message": "<below>",
            "code": "InvalidSignature"
        }
    ]
}

Message:

The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details. The Canonical String for this request should have been [[redacted]]

However my inputs are

<cfscript>
    // define a struct for arguments
    args={}
    // Input fields
    args.requestMethod='GET'
    args.hostName='[[hostname]]'
    args.requestURI='[[requestURL]]'
    args.requestBody=""
    args.requestHeaders={}
    args.requestParams={}
    args.signedPayload=true
    args.excludeHeaders=[]
    args.regionName='us-east-1'
    args.serviceName='execute-api'
    args.amzDate=aDate
    args.dateStamp=dateStamp
    args.signatureData={}
    args.tokenData={}
</cfscript>

<cfhttp method="put" url="[[URL]]" result="result">
    <cfhttpparam type="header" name="Authorization" value="#signatureData.AUTHORIZATIONHEADER#">
    <cfhttpparam type="header" name="x-amz-access-token" value="#tokenData.access_token#">
    <cfhttpparam type="header" name="X-Amz-Date" value="#aDate#">
</cfhttp>


问:
Can you define a setter with the same name as a final field?
I found out you can do this:

```<code>class Foo {
  Foo(this.x);

  final Object x;
  set x(Object value) => print("custom setter");
}

</code>```

and that it seems to be equivalent to this:

```<code>class Foo {
  Foo(this.x);

  final Object _x;
  Object get x => _x;
  set x(Object value) => print("custom setter");
}

</code>```

Is this the case? And if so, is it intended / encouraged? (If so I think it's fantastic because the first option is less verbose.)

PS. Here is my use case for adding a setter to a final field (or that looks as though it belongs to that field).

I have a class of objects which are conceptually mutable but whose actual implementation is immutable, because they are just snapshots from a database and what should be modified is the database itself not the local model, so the "fake" setters modify the data in the database (which in turn causes a new snapshot to be pushed to the client, creating the illusion that the object is indeed mutable).

Body:
I found out you can do this:

class Foo {
  Foo(this.x);

  final Object x;
  set x(Object value) => print("custom setter");
}

and that it seems to be equivalent to this:

class Foo {
  Foo(this.x);

  final Object _x;
  Object get x => _x;
  set x(Object value) => print("custom setter");
}

Is this the case? And if so, is it intended / encouraged? (If so I think it's fantastic because the first option is less verbose.)

PS. Here is my use case for adding a setter to a final field (or that looks as though it belongs to that field).

I have a class of objects which are conceptually mutable but whose actual implementation is immutable, because they are just snapshots from a database and what should be modified is the database itself not the local model, so the "fake" setters modify the data in the database (which in turn causes a new snapshot to be pushed to the client, creating the illusion that the object is indeed mutable).


问:
What is the specific version of VSCode for building Spring boot project?
I am using VSCode version 1.51.1.
But not running perfectly.
I think the version of VSCode may be problem.
What is that?

And have already installed extensions for java.


问:
Svelte: files imported through index.html are not building
I am building a Svelte app, where I have to reference some local .js files. I'm doing that like so (referencing then in index.html file):

All works just fine in dev preview, the issue appears when I try to build the project. Then all the references in index.html file stay the same but referenced files do not make it through build.

I'm guessing there is something wrong with either my importing process or project structure, but I can't seem to figure out what.


问:
PHPOffice: PHP Fatal error: Interface 'Psr\SimpleCache\CacheInterface' not found
I have custom WordPress plugin where I giving option for admins to download export of survey. The plugin using package phpoffice
I have test hosting with PHP 7.3 where export goes well and the production hosting is on PHP 7.3.3 (before it was PHP 7.4) where the exactly same problem does not work.

I'm expecting to resolve this error and make the option for download exports working..
I've tried searching for google but I didn't find solution exactly for my problem.
I tried this stuffs:

Upgrade memory_limit from 256MB to 512MB

Tried to downgrade production hosting PHP version from 7.4 to 7.3.3

When production hosting PHP version was 7.4 it gived this error in PHP error log:

```<code>[22-Dec-2022 08:45:24 UTC] PHP Fatal error:  Uncaught Error: Interface 'Psr\SimpleCache\CacheInterface' not found in /www/doc/www.digitalniagora.cz/www/wp-content/plugins/agora_survey/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php:14
Stack trace:
#0 /www/doc/www.digitalniagora.cz/www/wp-content/plugins/agora_survey/vendor/composer/ClassLoader.php(571): include()
#1 /www/doc/www.digitalniagora.cz/www/wp-content/plugins/agora_survey/vendor/composer/ClassLoader.php(428): Composer\Autoload\includeFile('/www/doc/www.di...')
#2 [internal function]: Composer\Autoload\ClassLoader->loadClass('PhpOffice\\PhpSp...')
#3 /www/doc/www.digitalniagora.cz/www/wp-content/plugins/agora_survey/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Settings.php(164): spl_autoload_call('PhpOffice\\PhpSp...')
#4 /www/doc/www.digitalniagora.cz/www/wp-content/plugins/agora_survey/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/CellsFactory.php(19): PhpOffice\PhpSpreadsheet\Settings::getCache()
#5 /www/doc/www.digitalniagora.cz/www/wp-content/ in /www/doc/www.digitalniagora.cz/www/wp-content/plugins/agora_survey/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php on line 14
</code>```

After I downgraded the PHP version to 7.3.3 (because I haven't option to downgrade to PHP 7.3) I getting just this error:

```<code>[27-Dec-2022 15:43:23 UTC] PHP Fatal error:  Interface 'Psr\SimpleCache\CacheInterface' not found in /www/doc/www.digitalniagora.cz/www/wp-content/plugins/agora_survey/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php on line 14
</code>```

EDIT 29.12.2022:
I tried update PHP version on test hosting to the same version as production hosting is but on test version it working well and production version code does not work.

But the code is exactly same as on test hosting where everything works well and also the code is exactly same after downgrade PHP version..
Can anybody give me some hints to find the solution?

Body:
I have custom WordPress plugin where I giving option for admins to download export of survey. The plugin using package phpoffice
I have test hosting with PHP 7.3 where export goes well and the production hosting is on PHP 7.3.3 (before it was PHP 7.4) where the exactly same problem does not work.

I'm expecting to resolve this error and make the option for download exports working..
I've tried searching for google but I didn't find solution exactly for my problem.
I tried this stuffs:

Upgrade memory_limit from 256MB to 512MB

Tried to downgrade production hosting PHP version from 7.4 to 7.3.3

When production hosting PHP version was 7.4 it gived this error in PHP error log:

[22-Dec-2022 08:45:24 UTC] PHP Fatal error:  Uncaught Error: Interface 'Psr\SimpleCache\CacheInterface' not found in /www/doc/www.digitalniagora.cz/www/wp-content/plugins/agora_survey/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php:14
Stack trace:
#0 /www/doc/www.digitalniagora.cz/www/wp-content/plugins/agora_survey/vendor/composer/ClassLoader.php(571): include()
#1 /www/doc/www.digitalniagora.cz/www/wp-content/plugins/agora_survey/vendor/composer/ClassLoader.php(428): Composer\Autoload\includeFile('/www/doc/www.di...')
#2 [internal function]: Composer\Autoload\ClassLoader->loadClass('PhpOffice\\PhpSp...')
#3 /www/doc/www.digitalniagora.cz/www/wp-content/plugins/agora_survey/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Settings.php(164): spl_autoload_call('PhpOffice\\PhpSp...')
#4 /www/doc/www.digitalniagora.cz/www/wp-content/plugins/agora_survey/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/CellsFactory.php(19): PhpOffice\PhpSpreadsheet\Settings::getCache()
#5 /www/doc/www.digitalniagora.cz/www/wp-content/ in /www/doc/www.digitalniagora.cz/www/wp-content/plugins/agora_survey/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php on line 14

After I downgraded the PHP version to 7.3.3 (because I haven't option to downgrade to PHP 7.3) I getting just this error:

[27-Dec-2022 15:43:23 UTC] PHP Fatal error:  Interface 'Psr\SimpleCache\CacheInterface' not found in /www/doc/www.digitalniagora.cz/www/wp-content/plugins/agora_survey/vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/Collection/Memory.php on line 14

EDIT 29.12.2022:
I tried update PHP version on test hosting to the same version as production hosting is but on test version it working well and production version code does not work.

But the code is exactly same as on test hosting where everything works well and also the code is exactly same after downgrade PHP version..
Can anybody give me some hints to find the solution?


问:
chrome.tabs.query was used, so that i could grab links from the current tab, which is a feature needed for a extension i am making
//the html is below

```<code>     <button id="tab-el">SAVE TAB</button>
</code>```

//the javascript is below

```<code>tabEl.addEventListener("click", function(){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        myLeads.push(tabs[0].url)
        localStorage.setItem("myLeads", JSON.stringify(myLeads) )
        render(myLeads)
    })
})
</code>```

//the JSON file is below

```<code>
{
    "manifest_version": 3,
    "version": "1.0",
    "name": "Leads tracker",
    "action": {
        "default_popup": "index.html",
        "default_icon": "icon.png"
    },
        "permissions": [
          "tabs"
        ]

}
</code>```

//the error my chrome console is showing is below

```<code>Script.js:51 Uncaught TypeError: Cannot read properties of undefined (reading 'query')
    at HTMLButtonElement.<anonymous> (Script.js:51:17)
</code>```

//tired to grab links from websites to create a bookmark extension
but so far not working

Body:
//the html is below

     <button id="tab-el">SAVE TAB</button>

//the javascript is below

tabEl.addEventListener("click", function(){
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
        myLeads.push(tabs[0].url)
        localStorage.setItem("myLeads", JSON.stringify(myLeads) )
        render(myLeads)
    })
})

//the JSON file is below

{
    "manifest_version": 3,
    "version": "1.0",
    "name": "Leads tracker",
    "action": {
        "default_popup": "index.html",
        "default_icon": "icon.png"
    },
        "permissions": [
          "tabs"
        ]

}

//the error my chrome console is showing is below

Script.js:51 Uncaught TypeError: Cannot read properties of undefined (reading 'query')
    at HTMLButtonElement.<anonymous> (Script.js:51:17)

//tired to grab links from websites to create a bookmark extension
but so far not working


问:
Updating multiple SQL Server lines in a php form submit
I have a form with multiple lines and have not figured out how to update them from a single submit button on the form. I know the issue is with the submit portion, but I haven't figured out how to loop through the data on the form yet. Any ideas?

SQL/PHP Submit:

```<code>if(isset($_POST['SubmitButton'])){

        foreach($_POST['lineid'] as $lineid){

        $itemdesc = $_POST['itemdesc'];
        $uom = $_POST['uom'];
        $class = $_POST['class'];

        $query = "UPDATE dbo.order_line
                    SET item_desc = ?, uom = ?, classification = ?
                    WHERE id = ?";

        $parms = array($itemdesc, $uom, $class, $lineid);

        $result = sqlsrv_query($conn, $query, $parms) or die (print_r ( sqlsrv_errors(), true));
        }

        sqlsrv_close($conn);

    }
</code>```

Form:

```<code><form method='POST' id ='edit' name = 'edit' action='". $_SERVER['PHP_SELF'] ."'>
<table>
foreach($orders as $order){

                $content .= "
                        <tr>
                            <td>ID</td>
                            <td><input type='text' value ='".$order[0]."' name='lineid' /></td>
                            <td>Item Desc</td>
                            <td><input type='text' value ='".$order[1]."' name='itemdesc' /></td>
                            <td>UOM</td>
                            <td><input type='text' value ='".$order[2]."' name='uom' /></td>
                            <td>Class</td>
                            <td><input type='text' value ='".$order[3]."' name='class' /></td>

                        </tr>
                        ";
}
        $content .="</table>
                    <input type='submit' class='submit' name='SubmitButton'></input></form>";
</code>```

Body:
I have a form with multiple lines and have not figured out how to update them from a single submit button on the form. I know the issue is with the submit portion, but I haven't figured out how to loop through the data on the form yet. Any ideas?

SQL/PHP Submit:

if(isset($_POST['SubmitButton'])){

        foreach($_POST['lineid'] as $lineid){

        $itemdesc = $_POST['itemdesc'];
        $uom = $_POST['uom'];
        $class = $_POST['class'];

        $query = "UPDATE dbo.order_line
                    SET item_desc = ?, uom = ?, classification = ?
                    WHERE id = ?";

        $parms = array($itemdesc, $uom, $class, $lineid);

        $result = sqlsrv_query($conn, $query, $parms) or die (print_r ( sqlsrv_errors(), true));
        }

        sqlsrv_close($conn);

    }

Form:

<form method='POST' id ='edit' name = 'edit' action='". $_SERVER['PHP_SELF'] ."'>

foreach($orders as $order){

                $content .= "

                            ID
                            <input type='text' value ='".$order[0]."' name='lineid' />
                            Item Desc
                            <input type='text' value ='".$order[1]."' name='itemdesc' />
                            UOM
                            <input type='text' value ='".$order[2]."' name='uom' />
                            Class
                            <input type='text' value ='".$order[3]."' name='class' />

                        ";
}
        $content .="

                    <input type='submit' class='submit' name='SubmitButton'></input></form>";


问:
Pandas: How to calculate median for next 4 weeks then repeat the process for next 4 weeks?
I am having one pandas dataframe it consists of 3 columns 'Date','Day','Value'. Date starts from 01/02/2022 to 31/12/2022. I want to calculate median for next 4 weeks then repeat the process for next 4 weeks.</p>
```<code>Ex: - for 01/02/2022 the median will be value of (08/02/2022,15/02/2022,22/02/2022,01/03/2022), similarly for 08/02/2022 the median will be ( 15/02/2022,22/02/2022,01/03/2022,08/03/2022) for 02/02/2022 median will be value of (09/02/2022,16/02/2022,23/02/2022,02/03/2022).
</code>```
```<code># Convert the "date" column to a datetime datatype
df["Date"] = pd.to_datetime(df["Date"])

df.set_index("Date", inplace=True)

df_grouped = df.groupby(pd.Grouper(freq="W"))

# Calculate the median for each 4-week period
df_median = df_grouped["Value"].median().resample("4W").median()

# Print the resulting dataframe
print(df_median)
</code>```

Body:
I am having one pandas dataframe it consists of 3 columns 'Date','Day','Value'. Date starts from 01/02/2022 to 31/12/2022. I want to calculate median for next 4 weeks then repeat the process for next 4 weeks.

Ex: - for 01/02/2022 the median will be value of (08/02/2022,15/02/2022,22/02/2022,01/03/2022), similarly for 08/02/2022 the median will be ( 15/02/2022,22/02/2022,01/03/2022,08/03/2022) for 02/02/2022 median will be value of (09/02/2022,16/02/2022,23/02/2022,02/03/2022).

# Convert the "date" column to a datetime datatype
df["Date"] = pd.to_datetime(df["Date"])

df.set_index("Date", inplace=True)

df_grouped = df.groupby(pd.Grouper(freq="W"))

# Calculate the median for each 4-week period
df_median = df_grouped["Value"].median().resample("4W").median()

# Print the resulting dataframe
print(df_median)


问:
Trying to pip install but get ```TypeError: 'Version' object is not subscriptable```
I'm on ubuntu and tried to install tardis by using:

```<code>pip install tardis-sn
</code>```

but the output i got was:

```<code>Defaulting to user installation because normal site-packages is not writeable
Collecting tardis-sn
  Using cached tardis-sn-1.0.1.tar.gz (1.1 MB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [14 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "/tmp/pip-install-4mc4s8kc/tardis-sn_98dc7e578b0a49ada4013a6ad17ba118/setup.py", line 8, in <module>
          import ah_bootstrap
        File "/tmp/pip-install-4mc4s8kc/tardis-sn_98dc7e578b0a49ada4013a6ad17ba118/ah_bootstrap.py", line 530, in <module>
          _main()
        File "/tmp/pip-install-4mc4s8kc/tardis-sn_98dc7e578b0a49ada4013a6ad17ba118/ah_bootstrap.py", line 527, in _main
          use_astropy_helpers(**kwargs)
        File "/tmp/pip-install-4mc4s8kc/tardis-sn_98dc7e578b0a49ada4013a6ad17ba118/ah_bootstrap.py", line 198, in use_astropy_helpers
          upgrade = _do_upgrade(dist, index_url)
        File "/tmp/pip-install-4mc4s8kc/tardis-sn_98dc7e578b0a49ada4013a6ad17ba118/ah_bootstrap.py", line 285, in _do_upgrade
          major, minor = (int(part) for part in dist.parsed_version[:2])
      TypeError: 'Version' object is not subscriptable
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.
</code>```

Please help me get rid of this error

I have tried using

```<code>pip install tardis-sn --use-deprecated=legacy-resolver
</code>```

but the output i got was still the same

Body:
I'm on ubuntu and tried to install tardis by using:

pip install tardis-sn

but the output i got was:

Defaulting to user installation because normal site-packages is not writeable
Collecting tardis-sn
  Using cached tardis-sn-1.0.1.tar.gz (1.1 MB)
  Preparing metadata (setup.py) ... error
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [14 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "/tmp/pip-install-4mc4s8kc/tardis-sn_98dc7e578b0a49ada4013a6ad17ba118/setup.py", line 8, in <module>
          import ah_bootstrap
        File "/tmp/pip-install-4mc4s8kc/tardis-sn_98dc7e578b0a49ada4013a6ad17ba118/ah_bootstrap.py", line 530, in <module>
          _main()
        File "/tmp/pip-install-4mc4s8kc/tardis-sn_98dc7e578b0a49ada4013a6ad17ba118/ah_bootstrap.py", line 527, in _main
          use_astropy_helpers(**kwargs)
        File "/tmp/pip-install-4mc4s8kc/tardis-sn_98dc7e578b0a49ada4013a6ad17ba118/ah_bootstrap.py", line 198, in use_astropy_helpers
          upgrade = _do_upgrade(dist, index_url)
        File "/tmp/pip-install-4mc4s8kc/tardis-sn_98dc7e578b0a49ada4013a6ad17ba118/ah_bootstrap.py", line 285, in _do_upgrade
          major, minor = (int(part) for part in dist.parsed_version[:2])
      TypeError: 'Version' object is not subscriptable
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

Please help me get rid of this error

I have tried using

pip install tardis-sn --use-deprecated=legacy-resolver

but the output i got was still the same


问:
c16rtomb()/c32rtomb() locale-independent conversion?
C++11 introduced the c16rtomb()/c32rtomb() conversion functions, along with the inverse (mbrtoc16()/mbrtoc32()). c16rtomb() clearly states in the reference documentation here:

The multibyte encoding used by this function is specified by the currently active C locale

The documentation for c32rtomb() states the same. Both the C and C++ versions agree that these are locale-dependent conversions (as they should be, according to the naming convention of the functions themselves).

However, MSVC seems to have taken a different approach and made them locale-independent (not using the current C locale) according to this document. These conversion functions are specified under the heading Locale-independent multibyte routines.

C++20 adds to the confusion by including the c8rtomb()/mbrtoc8() functions, which if locale-independent would basically do nothing, converting UTF-8 input to UTF-8 output.

Two questions arise from this:

Do any other compilers actually follow the standard and implement locale-dependent Unicode multibyte conversion routines? I couldn't find any concrete information after extensive searching.

Is this a bug in MSVC's implementation?


问:
count how many got the calculated 100% in Tableau per month
I created a calculated field in tableau that computes percentage of a part by the whole

```<code>IF SUM([part]) = 0 THEN 1
ELSE SUM([part])/SUM([ALL])
END
</code>```

I got part of what was needed in my chart. But what I wanted is to count how many got 100% per month.

I thought by creating a calculated field with conditional will do the trick

```<code>CASE [percent] WHEN 1 THEN 1 ELSE 0 END
</code>```

but I ended up with an aggregated summary and not able to count what I needed.

What I would like to create is a bar/line chart that shows the count of 100%s per month

Body:
I created a calculated field in tableau that computes percentage of a part by the whole

IF SUM([part]) = 0 THEN 1
ELSE SUM([part])/SUM([ALL])
END

I got part of what was needed in my chart. But what I wanted is to count how many got 100% per month.

I thought by creating a calculated field with conditional will do the trick

CASE [percent] WHEN 1 THEN 1 ELSE 0 END

but I ended up with an aggregated summary and not able to count what I needed.

What I would like to create is a bar/line chart that shows the count of 100%s per month