问:
useState hook within useEffect hook is not rerendering the component. Why?
I am trying to make a sliding tiles puzzle web application where a user can upload an image and a scrambled puzzle is then output which can be solved by the user. The app works fine with the default image.

But when a new Image is uploaded by the user, the corresponding sliding tiles puzzle does not show up.

When tinkering with the code, I found that if I enter a new Image, I have to manually change something in the returned part of the SlidingTiles function for the puzzle of the new image to show up. This change can be as small as entering a space in some div's content.

I expected that a new scrambled puzzle to come on its own as soon as new image is uploaded.

Update : Adding codesandbox.io link : https://lsujef.csb.app/

I am adding the code for reference :

```<code>*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    background-color: rgb(230.57, 243.38, 247.56);
}
.container{
}
.game-area{
    display: flex;
    flex-wrap: wrap;
    justify-content: space-evenly;
    align-items: center;
    margin: 5% auto;
    width: 100%;
}

.grid{
    display: flex;
    width: 480px;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border: 10px solid brown;
}

.row{
    display: flex;
    width: 100%;
    flex-direction: row;
    color: whitesmoke;
}

.show{
    width : 33.333333333%;
    height : 160px;
    border: 0.1px solid black;
    color: whitesmoke;
    font-size: x-large;
    font-weight: bolder;
    background-size: 100% 100%;
    padding: 0;
    margin: 0;
}

.transparent{
    background-color: transparent;
    color: transparent;
}

#init-img{
    background-size: 500px 500px;
    width: 500px;
    height: 500px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.btn-area{
    display: flex;
    width: 100%;
    justify-content: space-evenly;
    align-items: center;
    column-gap: 10rem;
}

.btn-refresh,.btn-change{
    color: darkblue;
    border: 2px solid darkblue;
    padding: 0.5rem 1rem;
    border-radius: 1vh;
    transition-duration: 0.2s;
}

.btn-refresh:hover,.btn-change:hover{
    color: white;
    border: 2px solid white;
    background-color: darkblue;
}

#submit-img{
    visibility: hidden;
    display: none;
}
</code>```
```<code>import React from "react";
import "./styles.css";
import manyfood from "./manyfood.jpg";

const SlidingTiles = () => {
  const genTile = () => {
    const createTile = () => {
      let initTile = [];
      let currRow = [];
      for (let a = 1; a <= 25; a++) {
        currRow.push(0);
        if (a % 5 === 0) {
          initTile.push(currRow);
          currRow = [];
        }
      }
      let a = 1;
      for (let i = 1; i <= 3; i++) {
        for (let j = 1; j <= 3; j++) {
          initTile[i][j] = a;
          a += 1;
        }
      }
      return initTile;
    };

    const randomMove = (initTile, lastPos, currPos) => {
      const allMoves = [
        [-1, 0],
        [1, 0],
        [0, -1],
        [0, 1],
      ];

      const nextPosList = allMoves.map((item, index) => {
        let [addx, addy] = item;
        let [currx, curry] = currPos;
        return [currx + addx, curry + addy];
      });
      const filtNextPosList = nextPosList.filter((item) => {
        let [x, y] = item;
        return initTile[x][y] !== 0 && item.toString() !== lastPos.toString();
      });

      const nextPos =
        filtNextPosList[Math.floor(Math.random() * filtNextPosList.length)];
      const swapPos = () => {
        let [nextx, nexty] = nextPos;
        let [currx, curry] = currPos;
        [initTile[nextx][nexty], initTile[currx][curry]] = [
          initTile[currx][curry],
          initTile[nextx][nexty],
        ];
      };

      swapPos();
      return nextPos;
    };

    let lastPos = [3, 4];
    let currPos = [3, 3];
    let initTile = createTile();
    for (let i = 1; i <= 100; i++) {
      let nextPos = randomMove(initTile, lastPos, currPos);
      [lastPos, currPos] = [currPos, nextPos];
    }
    return initTile;
  };

  const slideTile = (currPos) => {
    let initTile = currTile;
    const allMoves = [
      [-1, 0],
      [1, 0],
      [0, -1],
      [0, 1],
    ];
    const nextPosList = allMoves.map((item, index) => {
      let [addx, addy] = item;
      let [currx, curry] = currPos;
      return [currx + addx, curry + addy];
    });
    const filtNextPosList = nextPosList.filter((item) => {
      let [x, y] = item;
      return initTile[x][y] === 9;
    });
    if (filtNextPosList.length) {
      const nextPos = filtNextPosList[0];
      const swapPos = () => {
        let [nextx, nexty] = nextPos;
        let [currx, curry] = currPos;
        [initTile[nextx][nexty], initTile[currx][curry]] = [
          initTile[currx][curry],
          initTile[nextx][nexty],
        ];
      };
      swapPos();
      setCurrTile([...currTile]);
    } else {
      alert("No space to move");
    }
  };

  const loadCanvas = (currImg) => {
    var img = new Image();
    img.src = currImg;
    var width = img.width / 3;
    var height = img.height / 3;

    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    var ctx = canvas.getContext("2d");

    const clipImg = (x, y, width, height) => {
      ctx.drawImage(img, x, y, width, height, 0, 0, width, height);
    };

    let imgList = [];

    for (let id = 1; id <= 9; id++) {
      var x = (id - 1) % 3;
      var y = Math.floor((id - 1) / 3);
      clipImg(x * width, y * height, width, height);
      imgList.push(canvas.toDataURL("image/png", 0.2));
    }
    return imgList;
  };

  const [currTile, setCurrTile] = React.useState(genTile());
  const [imgList, setImgList] = React.useState([]);
  const [currImg, setCurrImg] = React.useState(manyfood);

  React.useEffect(() => {
    setImgList(loadCanvas(currImg));
  }, [currImg]);

  return (
    <>
      <div className="container">
        <div className="game-area">
          <img
            id="init-img"
            src={currImg}
            onLoad={() => {
              console.log(imgList);
            }}
          />
          <div className="grid">
            {currTile.map((currRow, indexx) => {
              return (
                <div className="row" key={indexx}>
                  {currRow.map((item, indexy) => {
                    if (item) {
                      if (item !== 9) {
                        return (
                          <div
                            className="show"
                            style={{
                              backgroundImage: "url(" + imgList[item - 1] + ")",
                            }}
                            id={item}
                            onClick={() => slideTile([indexx, indexy])}
                            key={indexy}
                          ></div>
                        );
                      } else {
                        return (
                          <div className="show transparent" key={indexy}></div>
                        );
                      }
                    }
                  })}
                </div>
              );
            })}
          </div>
        </div>
        <div className="btn-area">
          <form>
            <label htmlFor="submit-img" className="btn-change">
              New Image{" "}
            </label>
            <input
              id="submit-img"
              type="file"
              onChange={(e) => {
                setCurrImg(URL.createObjectURL(e.target.files[0]));
              }}
            />
          </form>
          <button
            className="btn-refresh"
            onClick={() => setCurrTile(genTile())}
          >
            New Game
          </button>
        </div>
      </div>
    </>
  );
};

export default SlidingTiles;
</code>```

I believe the problem is with setImgList, since I found that it returns an empty array when it is called within the useEffect hook.

Body:
I am trying to make a sliding tiles puzzle web application where a user can upload an image and a scrambled puzzle is then output which can be solved by the user. The app works fine with the default image.

But when a new Image is uploaded by the user, the corresponding sliding tiles puzzle does not show up.

When tinkering with the code, I found that if I enter a new Image, I have to manually change something in the returned part of the SlidingTiles function for the puzzle of the new image to show up. This change can be as small as entering a space in some div's content.

I expected that a new scrambled puzzle to come on its own as soon as new image is uploaded.

Update : Adding codesandbox.io link : https://lsujef.csb.app/

I am adding the code for reference :

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    background-color: rgb(230.57, 243.38, 247.56);
}
.container{
}
.game-area{
    display: flex;
    flex-wrap: wrap;
    justify-content: space-evenly;
    align-items: center;
    margin: 5% auto;
    width: 100%;
}

.grid{
    display: flex;
    width: 480px;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    border: 10px solid brown;
}

.row{
    display: flex;
    width: 100%;
    flex-direction: row;
    color: whitesmoke;
}

.show{
    width : 33.333333333%;
    height : 160px;
    border: 0.1px solid black;
    color: whitesmoke;
    font-size: x-large;
    font-weight: bolder;
    background-size: 100% 100%;
    padding: 0;
    margin: 0;
}

.transparent{
    background-color: transparent;
    color: transparent;
}

#init-img{
    background-size: 500px 500px;
    width: 500px;
    height: 500px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.btn-area{
    display: flex;
    width: 100%;
    justify-content: space-evenly;
    align-items: center;
    column-gap: 10rem;
}

.btn-refresh,.btn-change{
    color: darkblue;
    border: 2px solid darkblue;
    padding: 0.5rem 1rem;
    border-radius: 1vh;
    transition-duration: 0.2s;
}

.btn-refresh:hover,.btn-change:hover{
    color: white;
    border: 2px solid white;
    background-color: darkblue;
}

#submit-img{
    visibility: hidden;
    display: none;
}

import React from "react";
import "./styles.css";
import manyfood from "./manyfood.jpg";

const SlidingTiles = () => {
  const genTile = () => {
    const createTile = () => {
      let initTile = [];
      let currRow = [];
      for (let a = 1; a <= 25; a++) {
        currRow.push(0);
        if (a % 5 === 0) {
          initTile.push(currRow);
          currRow = [];
        }
      }
      let a = 1;
      for (let i = 1; i <= 3; i++) {
        for (let j = 1; j <= 3; j++) {
          initTile[i][j] = a;
          a += 1;
        }
      }
      return initTile;
    };

    const randomMove = (initTile, lastPos, currPos) => {
      const allMoves = [
        [-1, 0],
        [1, 0],
        [0, -1],
        [0, 1],
      ];

      const nextPosList = allMoves.map((item, index) => {
        let [addx, addy] = item;
        let [currx, curry] = currPos;
        return [currx + addx, curry + addy];
      });
      const filtNextPosList = nextPosList.filter((item) => {
        let [x, y] = item;
        return initTile[x][y] !== 0 && item.toString() !== lastPos.toString();
      });

      const nextPos =
        filtNextPosList[Math.floor(Math.random() * filtNextPosList.length)];
      const swapPos = () => {
        let [nextx, nexty] = nextPos;
        let [currx, curry] = currPos;
        [initTile[nextx][nexty], initTile[currx][curry]] = [
          initTile[currx][curry],
          initTile[nextx][nexty],
        ];
      };

      swapPos();
      return nextPos;
    };

    let lastPos = [3, 4];
    let currPos = [3, 3];
    let initTile = createTile();
    for (let i = 1; i <= 100; i++) {
      let nextPos = randomMove(initTile, lastPos, currPos);
      [lastPos, currPos] = [currPos, nextPos];
    }
    return initTile;
  };

  const slideTile = (currPos) => {
    let initTile = currTile;
    const allMoves = [
      [-1, 0],
      [1, 0],
      [0, -1],
      [0, 1],
    ];
    const nextPosList = allMoves.map((item, index) => {
      let [addx, addy] = item;
      let [currx, curry] = currPos;
      return [currx + addx, curry + addy];
    });
    const filtNextPosList = nextPosList.filter((item) => {
      let [x, y] = item;
      return initTile[x][y] === 9;
    });
    if (filtNextPosList.length) {
      const nextPos = filtNextPosList[0];
      const swapPos = () => {
        let [nextx, nexty] = nextPos;
        let [currx, curry] = currPos;
        [initTile[nextx][nexty], initTile[currx][curry]] = [
          initTile[currx][curry],
          initTile[nextx][nexty],
        ];
      };
      swapPos();
      setCurrTile([...currTile]);
    } else {
      alert("No space to move");
    }
  };

  const loadCanvas = (currImg) => {
    var img = new Image();
    img.src = currImg;
    var width = img.width / 3;
    var height = img.height / 3;

    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;
    var ctx = canvas.getContext("2d");

    const clipImg = (x, y, width, height) => {
      ctx.drawImage(img, x, y, width, height, 0, 0, width, height);
    };

    let imgList = [];

    for (let id = 1; id <= 9; id++) {
      var x = (id - 1) % 3;
      var y = Math.floor((id - 1) / 3);
      clipImg(x * width, y * height, width, height);
      imgList.push(canvas.toDataURL("image/png", 0.2));
    }
    return imgList;
  };

  const [currTile, setCurrTile] = React.useState(genTile());
  const [imgList, setImgList] = React.useState([]);
  const [currImg, setCurrImg] = React.useState(manyfood);

  React.useEffect(() => {
    setImgList(loadCanvas(currImg));
  }, [currImg]);

  return (
    <>

           {
              console.log(imgList);
            }}
          />

            {currTile.map((currRow, indexx) => {
              return (

                  {currRow.map((item, indexy) => {
                    if (item) {
                      if (item !== 9) {
                        return (

 slideTile([indexx, indexy])}
                            key={indexy}
                          >

                        );
                      } else {
                        return (

                        );
                      }
                    }
                  })}

              );
            })}

          <form>

              New Image{" "}

            <input
              id="submit-img"
              type="file"
              onChange={(e) => {
                setCurrImg(URL.createObjectURL(e.target.files[0]));
              }}
            />
          </form>
          <button
            className="btn-refresh"
            onClick={() => setCurrTile(genTile())}
          >
            New Game
          </button>

    </>
  );
};

export default SlidingTiles;

I believe the problem is with setImgList, since I found that it returns an empty array when it is called within the useEffect hook.


来源: stackexchange

问:
Use of const inside a loop which goes through elements of an array
```<code>
function orbitalPeriod(arr) {
  const GM = 398600.4418;
  const earthRadius = 6367.4447;
  const newArr = [];

  //Looping through each key in arr object
  for (let elem in arr) {
    //Rounding off the orbital period value
    const orbitalPer = Math.round(
      2 * Math.PI * Math.sqrt(Math.pow(arr[elem].avgAlt + earthRadius, 3) / GM)
    );
    //Adding new object with orbitalPeriod property
    newArr.push({name: arr[elem].name, orbitalPeriod: orbitalPer});
  }

  return newArr;
}

// test here
orbitalPeriod([{ name: "sputnik", avgAlt: 35873.5553 }]);
</code>```

This is from a freeCodeCamp challenge (Link)

Why is 'orbitalPer' declared as a const inside the for loop? Once a const is declared with value, it is not possible to change the value isn't it? Here if the array has more than one object, when the loop runs more than once, wont having const encounter an error?

ContentLicense: CC BY-SA 4.0

Body:
function orbitalPeriod(arr) {
  const GM = 398600.4418;
  const earthRadius = 6367.4447;
  const newArr = [];

  //Looping through each key in arr object
  for (let elem in arr) {
    //Rounding off the orbital period value
    const orbitalPer = Math.round(
      2 * Math.PI * Math.sqrt(Math.pow(arr[elem].avgAlt + earthRadius, 3) / GM)
    );
    //Adding new object with orbitalPeriod property
    newArr.push({name: arr[elem].name, orbitalPeriod: orbitalPer});
  }

  return newArr;
}

// test here
orbitalPeriod([{ name: "sputnik", avgAlt: 35873.5553 }]);

This is from a freeCodeCamp challenge (Link)

Why is 'orbitalPer' declared as a const inside the for loop? Once a const is declared with value, it is not possible to change the value isn't it? Here if the array has more than one object, when the loop runs more than once, wont having const encounter an error?


问:
Firebase Cloud Messaging daily notification programmatically
Is there a way to create a daily notification programmatically with Firebase Cloud Messaing? I found this question on SO but that only shows how to do it within Firebase.

Couldn't find anything on this so I'm happy for every help!


问:
ASP.Net Core 7.0 Angular SPA and integration tests via WebApplicationFactory
I'm trying to set up an Angular application with ASP.Net Core 7.0 including integration tests. For the integration tests, I utilize a WebApplicationFactory, but somehow every request during the tests returns 404.

So I tried the same setup with a classic ASP.Net Core Web App and this seems to return the correct pages including status code 200.

I'm aware that my pages will be created client side, but I at least expect something to be returned from my server, so what am I missing here?

Code of the Angular app:

In my main project

Program.cs:

```<code>public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseSetting(WebHostDefaults.ApplicationKey, typeof(Startup).Assembly.GetName().Name);
                webBuilder.UseStartup<Startup>();
            });

}
</code>```

Startup.cs:

```<code>public class Startup
{
    private readonly IConfiguration _configuration;

    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public virtual void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

    public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (!env.IsDevelopment())
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");

            endpoints.MapFallbackToFile("index.html");
        });
    }
}
</code>```

In my integration test project

HomeControllerTests.cs:

```<code>public class HomeControllerTests: IClassFixture<WebApplicationFactory<Startup>>
{
    private readonly WebApplicationFactory<Startup> _factory;

    public HomeControllerTests(WebApplicationFactory<Startup> factory)
    {
        _factory = factory;
    }

    [Theory]
    [InlineData("/")]
    [InlineData("/fetch-data")]
    public async Task Get_EndpointsReturnSuccessAndCorrectContentType(string url)
    {
        // Arrange
        using var client = _factory.CreateClient();

        // Act
        using var response = await client.GetAsync(url);

        // Assert
        response.EnsureSuccessStatusCode();
        Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType.ToString());
    }
}
</code>```

Code of the classic Web App

In my main project

Program.cs:

```<code>public static class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseSetting(WebHostDefaults.ApplicationKey, typeof(Startup).Assembly.GetName().Name);
                webBuilder.UseStartup<Startup>();
            });

}
</code>```

Startup.cs:

```<code>public class Startup
{
    private readonly IConfiguration _configuration;

    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public virtual void ConfigureServices(IServiceCollection services)
    {
        // Add services to the container.
        services.AddRazorPages();
    }

    public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Configure the HTTP request pipeline.
        if (!env.IsDevelopment())
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}
</code>```

In my integration test project

HomeControllerTests.cs:

```<code>public class HomeControllerTests: IClassFixture<WebApplicationFactory<Startup>>
{
    private readonly WebApplicationFactory<Startup> _factory;

    public HomeControllerTests(WebApplicationFactory<Startup> factory)
    {
        _factory = factory;
    }

    [Theory]
    [InlineData("/")]
    [InlineData("/Privacy")]
    public async Task Get_EndpointsReturnSuccessAndCorrectContentType(string url)
    {
        // Arrange
        using var client = _factory.CreateClient();

        // Act
        using var response = await client.GetAsync(url);

        // Assert
        response.EnsureSuccessStatusCode();
        Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType.ToString());
    }
</code>```

Body:
I'm trying to set up an Angular application with ASP.Net Core 7.0 including integration tests. For the integration tests, I utilize a WebApplicationFactory, but somehow every request during the tests returns 404.

So I tried the same setup with a classic ASP.Net Core Web App and this seems to return the correct pages including status code 200.

I'm aware that my pages will be created client side, but I at least expect something to be returned from my server, so what am I missing here?

Code of the Angular app:

In my main project

Program.cs:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseSetting(WebHostDefaults.ApplicationKey, typeof(Startup).Assembly.GetName().Name);
                webBuilder.UseStartup<Startup>();
            });

}

Startup.cs:

public class Startup
{
    private readonly IConfiguration _configuration;

    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public virtual void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
    }

    public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (!env.IsDevelopment())
        {
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");

            endpoints.MapFallbackToFile("index.html");
        });
    }
}

In my integration test project

HomeControllerTests.cs:

public class HomeControllerTests: IClassFixture<WebApplicationFactory<Startup>>
{
    private readonly WebApplicationFactory<Startup> _factory;

    public HomeControllerTests(WebApplicationFactory<Startup> factory)
    {
        _factory = factory;
    }

    [Theory]
    [InlineData("/")]
    [InlineData("/fetch-data")]
    public async Task Get_EndpointsReturnSuccessAndCorrectContentType(string url)
    {
        // Arrange
        using var client = _factory.CreateClient();

        // Act
        using var response = await client.GetAsync(url);

        // Assert
        response.EnsureSuccessStatusCode();
        Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType.ToString());
    }
}

Code of the classic Web App

In my main project

Program.cs:

public static class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseSetting(WebHostDefaults.ApplicationKey, typeof(Startup).Assembly.GetName().Name);
                webBuilder.UseStartup<Startup>();
            });

}

Startup.cs:

public class Startup
{
    private readonly IConfiguration _configuration;

    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public virtual void ConfigureServices(IServiceCollection services)
    {
        // Add services to the container.
        services.AddRazorPages();
    }

    public virtual void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // Configure the HTTP request pipeline.
        if (!env.IsDevelopment())
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
        });
    }
}

In my integration test project

HomeControllerTests.cs:

public class HomeControllerTests: IClassFixture<WebApplicationFactory<Startup>>
{
    private readonly WebApplicationFactory<Startup> _factory;

    public HomeControllerTests(WebApplicationFactory<Startup> factory)
    {
        _factory = factory;
    }

    [Theory]
    [InlineData("/")]
    [InlineData("/Privacy")]
    public async Task Get_EndpointsReturnSuccessAndCorrectContentType(string url)
    {
        // Arrange
        using var client = _factory.CreateClient();

        // Act
        using var response = await client.GetAsync(url);

        // Assert
        response.EnsureSuccessStatusCode();
        Assert.Equal("text/html; charset=utf-8", response.Content.Headers.ContentType.ToString());
    }


问:
Matlab and Simulink for home image processing?
I'm trying to learn image processing for a new job--e.g. sharpening, noise reduction, edge detection, white balancing, color reconstruction, scaling--and all I have for my current work MatLab is the basic 2017b package with no additional toolboxes. I'm perfectly willing to pay a few hundred dollars for home use of MatLab plus some toolboxes and the appropriate Simulink package. Simulink seems to be necessary for several of the tasks I mentioned such as sharpening and edge detection. Can someone who does image processing please list what packages I should purchase? I'd be very grateful! I'm starting a Udemy course on image processing but it only does some very basic image manipulation.

Trying to use Matlab 2017b. Doesn't have the necessary functionality do do advanced image processing.


问:
Warning: An unhandled error was caught from submitForm(), [Error: Network Error]
I have been trying to create a sign-in/sign-up with React Native, MongoDB, Axios and Expo

I have encountered a very strange error.

The app works perfectly fine on the postman, and it gets registered on MongoDB:

but when I try to run it on Visual Studio Code it gives me an error:

Front end, Sign-up code:

```<code>import React, { useState } from 'react';
import { View, StyleSheet, Text } from 'react-native';

import { isValidEmail, isValidObjField, updateError } from '../utils/methods';
import FormContainer from './FormContainer';
import FormInput from './FormInput';
import FormSubmitButton from './FormSubmitButton';
import { StackActions } from '@react-navigation/native';

import { Formik } from 'formik';
import * as Yup from 'yup';

import client from '../api/client';

const validationSchema = Yup.object({
  fullname: Yup.string()
    .trim()
    .min(3, 'Invalid name!')
    .required('Name is required!'),
  email: Yup.string().email('Invalid email!').required('Email is required!'),
  password: Yup.string()
    .trim()
    .min(8, 'Password is too short!')
    .required('Password is required!'),
  confirmPassword: Yup.string().equals(
    [Yup.ref('password'), null],
    'Password does not match!'
  ),
});

const SignupForm = ({ navigation }) => {
  const userInfo = {
    fullname: '',
    email: '',
    password: '',
    confirmPassword: '',
  };

  const [error, setError] = useState('');

  const { fullname, email, password, confirmPassword } = userInfo;

  const handleOnChangeText = (value, fieldName) => {
    setUserInfo({ ...userInfo, [fieldName]: value });
  };

  const isValidForm = () => {
    // we will accept only if all of the fields have value
    if (!isValidObjField(userInfo))
      return updateError('Required all fields!', setError);
    // if valid name with 3 or more characters
    if (!fullname.trim() || fullname.length < 3)
      return updateError('Invalid name!', setError);
    // only valid email id is allowed
    if (!isValidEmail(email)) return updateError('Invalid email!', setError);
    // password must have 8 or more characters
    if (!password.trim() || password.length < 8)
      return updateError('Password is less then 8 characters!', setError);
    // password and confirm password must be the same
    if (password !== confirmPassword)
      return updateError('Password does not match!', setError);

    return true;
  };

  const sumbitForm = () => {
    if (isValidForm()) {
      // submit form
      console.log(userInfo);
    }
  };

  const signUp = async (values, formikActions) => {
    const res = await client.post('/create-user', {
      ...values,
    });

    if (res.data.success) {
      const signInRes = await client.post('/sign-in', {
        email: values.email,
        password: values.password,
      });
      if (signInRes.data.success) {
        navigation.dispatch(
          StackActions.replace('ImageUpload', {
            token: signInRes.data.token,
          })
        );
      }
    }

    formikActions.resetForm();
    formikActions.setSubmitting(false);
  };

  return (
    <FormContainer>
      <Formik
        initialValues={userInfo}
        validationSchema={validationSchema}
        onSubmit={signUp}
      >
        {({
          values,
          errors,
          touched,
          isSubmitting,
          handleChange,
          handleBlur,
          handleSubmit,
        }) => {
          const { fullname, email, password, confirmPassword } = values;
          return (
            <>
              <FormInput
                value={fullname}
                error={touched.fullname && errors.fullname}
                onChangeText={handleChange('fullname')}
                onBlur={handleBlur('fullname')}
                label='Full Name'
                placeholder='John Smith'
              />
              <FormInput
                value={email}
                error={touched.email && errors.email}
                onChangeText={handleChange('email')}
                onBlur={handleBlur('email')}
                autoCapitalize='none'
                label='Email'
                placeholder='example@email.com'
              />
              <FormInput
                value={password}
                error={touched.password && errors.password}
                onChangeText={handleChange('password')}
                onBlur={handleBlur('password')}
                autoCapitalize='none'
                secureTextEntry
                label='Password'
                placeholder='********'
              />
              <FormInput
                value={confirmPassword}
                error={touched.confirmPassword && errors.confirmPassword}
                onChangeText={handleChange('confirmPassword')}
                onBlur={handleBlur('confirmPassword')}
                autoCapitalize='none'
                secureTextEntry
                label='Confirm Password'
                placeholder='********'
              />
              <FormSubmitButton
                submitting={isSubmitting}
                onPress={handleSubmit}
                title='Sign up'
              />
            </>
          );
        }}
      </Formik>
    </FormContainer>
  );
};

const styles = StyleSheet.create({});

export default SignupForm;
</code>```

Backend API Code:

```<code>  const express = require('express');

const router = express.Router();
const {
  createUser,
  userSignIn,
  uploadProfile,
  signOut,
} = require('../controllers/user');
const { isAuth } = require('../middlewares/auth');
const {
  validateUserSignUp,
  userVlidation,
  validateUserSignIn,
} = require('../middlewares/validation/user');

const multer = require('multer');

const storage = multer.diskStorage({});

const fileFilter = (req, file, cb) => {
  if (file.mimetype.startsWith('image')) {
    cb(null, true);
  } else {
    cb('invalid image file!', false);
  }
};
const uploads = multer({ storage, fileFilter });

router.post('/create-user', validateUserSignUp, userVlidation, createUser);
router.post('/sign-in', validateUserSignIn, userVlidation, userSignIn);
router.post('/sign-out', isAuth, signOut);
router.post(
  '/upload-profile',
  isAuth,
  uploads.single('profile'),
  uploadProfile
);

module.exports = router;
</code>```

Creating new user backend:

```<code>exports.createUser = async (req, res) => {
  const { fullname, email, password } = req.body;
  const isNewUser = await User.isThisEmailInUse(email);
  if (!isNewUser)
    return res.json({
      success: false,
      message: 'This email is already in use, try sign-in',
    });
  const user = await User({
    fullname,
    email,
    password,
  });
  await user.save();
  res.json({ success: true, user });
};
</code>```

Body:
I have been trying to create a sign-in/sign-up with React Native, MongoDB, Axios and Expo

I have encountered a very strange error.

The app works perfectly fine on the postman, and it gets registered on MongoDB:

but when I try to run it on Visual Studio Code it gives me an error:

Front end, Sign-up code:

import React, { useState } from 'react';
import { View, StyleSheet, Text } from 'react-native';

import { isValidEmail, isValidObjField, updateError } from '../utils/methods';
import FormContainer from './FormContainer';
import FormInput from './FormInput';
import FormSubmitButton from './FormSubmitButton';
import { StackActions } from '@react-navigation/native';

import { Formik } from 'formik';
import * as Yup from 'yup';

import client from '../api/client';

const validationSchema = Yup.object({
  fullname: Yup.string()
    .trim()
    .min(3, 'Invalid name!')
    .required('Name is required!'),
  email: Yup.string().email('Invalid email!').required('Email is required!'),
  password: Yup.string()
    .trim()
    .min(8, 'Password is too short!')
    .required('Password is required!'),
  confirmPassword: Yup.string().equals(
    [Yup.ref('password'), null],
    'Password does not match!'
  ),
});

const SignupForm = ({ navigation }) => {
  const userInfo = {
    fullname: '',
    email: '',
    password: '',
    confirmPassword: '',
  };

  const [error, setError] = useState('');

  const { fullname, email, password, confirmPassword } = userInfo;

  const handleOnChangeText = (value, fieldName) => {
    setUserInfo({ ...userInfo, [fieldName]: value });
  };

  const isValidForm = () => {
    // we will accept only if all of the fields have value
    if (!isValidObjField(userInfo))
      return updateError('Required all fields!', setError);
    // if valid name with 3 or more characters
    if (!fullname.trim() || fullname.length < 3)
      return updateError('Invalid name!', setError);
    // only valid email id is allowed
    if (!isValidEmail(email)) return updateError('Invalid email!', setError);
    // password must have 8 or more characters
    if (!password.trim() || password.length < 8)
      return updateError('Password is less then 8 characters!', setError);
    // password and confirm password must be the same
    if (password !== confirmPassword)
      return updateError('Password does not match!', setError);

    return true;
  };

  const sumbitForm = () => {
    if (isValidForm()) {
      // submit form
      console.log(userInfo);
    }
  };

  const signUp = async (values, formikActions) => {
    const res = await client.post('/create-user', {
      ...values,
    });

    if (res.data.success) {
      const signInRes = await client.post('/sign-in', {
        email: values.email,
        password: values.password,
      });
      if (signInRes.data.success) {
        navigation.dispatch(
          StackActions.replace('ImageUpload', {
            token: signInRes.data.token,
          })
        );
      }
    }

    formikActions.resetForm();
    formikActions.setSubmitting(false);
  };

  return (
    <FormContainer>
      <Formik
        initialValues={userInfo}
        validationSchema={validationSchema}
        onSubmit={signUp}
      >
        {({
          values,
          errors,
          touched,
          isSubmitting,
          handleChange,
          handleBlur,
          handleSubmit,
        }) => {
          const { fullname, email, password, confirmPassword } = values;
          return (
            <>
              <FormInput
                value={fullname}
                error={touched.fullname && errors.fullname}
                onChangeText={handleChange('fullname')}
                onBlur={handleBlur('fullname')}
                label='Full Name'
                placeholder='John Smith'
              />
              <FormInput
                value={email}
                error={touched.email && errors.email}
                onChangeText={handleChange('email')}
                onBlur={handleBlur('email')}
                autoCapitalize='none'
                label='Email'
                placeholder='example@email.com'
              />
              <FormInput
                value={password}
                error={touched.password && errors.password}
                onChangeText={handleChange('password')}
                onBlur={handleBlur('password')}
                autoCapitalize='none'
                secureTextEntry
                label='Password'
                placeholder='********'
              />
              <FormInput
                value={confirmPassword}
                error={touched.confirmPassword && errors.confirmPassword}
                onChangeText={handleChange('confirmPassword')}
                onBlur={handleBlur('confirmPassword')}
                autoCapitalize='none'
                secureTextEntry
                label='Confirm Password'
                placeholder='********'
              />
              <FormSubmitButton
                submitting={isSubmitting}
                onPress={handleSubmit}
                title='Sign up'
              />
            </>
          );
        }}
      </Formik>
    </FormContainer>
  );
};

const styles = StyleSheet.create({});

export default SignupForm;

Backend API Code:

  const express = require('express');

const router = express.Router();
const {
  createUser,
  userSignIn,
  uploadProfile,
  signOut,
} = require('../controllers/user');
const { isAuth } = require('../middlewares/auth');
const {
  validateUserSignUp,
  userVlidation,
  validateUserSignIn,
} = require('../middlewares/validation/user');

const multer = require('multer');

const storage = multer.diskStorage({});

const fileFilter = (req, file, cb) => {
  if (file.mimetype.startsWith('image')) {
    cb(null, true);
  } else {
    cb('invalid image file!', false);
  }
};
const uploads = multer({ storage, fileFilter });

router.post('/create-user', validateUserSignUp, userVlidation, createUser);
router.post('/sign-in', validateUserSignIn, userVlidation, userSignIn);
router.post('/sign-out', isAuth, signOut);
router.post(
  '/upload-profile',
  isAuth,
  uploads.single('profile'),
  uploadProfile
);

module.exports = router;

Creating new user backend:

exports.createUser = async (req, res) => {
  const { fullname, email, password } = req.body;
  const isNewUser = await User.isThisEmailInUse(email);
  if (!isNewUser)
    return res.json({
      success: false,
      message: 'This email is already in use, try sign-in',
    });
  const user = await User({
    fullname,
    email,
    password,
  });
  await user.save();
  res.json({ success: true, user });
};


问:
Change button color and text color onclick using ionic react
I'm using Ionic React in my project to create a mood selection tab. When a user selects/clicks a mood (button), the emoji, button color, and button text color will change. If the user then clicks another button, the previous button will revert back to its original color.

like this:

but I can only change the emoji image. I tried using --color-activated and --background-activated to change the color of the button color and text color but nothing change. anyone know how to do it? any help will be appreciated

here's my code:

```<code>const Tab1: React.FC = () => {
  const user = useContext(UserContext);

  const [imageClicked, setImageClicked] = useState({
    noEmoji: true,
    great: false,
    happy: false,
    okay: false,
    sad: false,
    angry: false
  });

  const onClickHandler = (order: any) => {
    const resetimages = {
      noEmoji: false,
      great: false,
      happy: false,
      okay: false,
      sad: false,
      angry: false
    };
    setImageClicked({
      ...resetimages,
      [order]: true,
    });
  };

  return (
    <IonPage>
      <IonHeader translucent={true} mode="ios" class="ion-no-border">
        <IonToolbar>
          <IonTitle id="headerTitle">Select Your Mood</IonTitle>
          <IonButtons slot="start">
            <IonButton id="headerSettings" routerLink="/userProfile">
              <IonIcon slot="icon-only" size="large" icon={personCircleOutline} />
            </IonButton>
          </IonButtons>
        </IonToolbar>
      </IonHeader>

      <IonContent fullscreen>
        <IonTitle class="ion-text-center" id="welcomeTitle">
          <div>
            Hello {user?.displayName},
          </div>
          <div>
            How are you today?
          </div>
        </IonTitle>

        <IonGrid>
          <div>
            {imageClicked.noEmoji && <img src={noEmoji} alt="noEmoji" id="noEmoji" />}
            {imageClicked.great && <img src={great} alt="great" id="emojisImage" />}
            {imageClicked.happy && <img src={happy} alt="happy" id="emojisImage" />}
            {imageClicked.okay && <img src={okay} alt="okay" id="emojisImage" />}
            {imageClicked.sad && <img src={sad} alt="sad" id="emojisImage" />}
            {imageClicked.angry && <img src={angry} alt="angry" id="emojisImage" />}
          </div>

          <div id="emojisButtonContainer">
            <IonRow>
              <IonButton
              id="greatButton"
              shape="round"
              expand="block"
              onClick={() => onClickHandler('great')}
              >Great</IonButton>

              <IonButton
              id="happyButton"
              shape="round"
              expand="block"
              onClick={() => onClickHandler('happy')}
              >Happy</IonButton>
            </IonRow>

            <IonRow>
              <IonButton
              id="okayButton"
              shape="round"
              expand="block"
              onClick={() => onClickHandler('okay')}
              >Okay</IonButton>

              <IonButton
              id="sadButton"
              shape="round"
              expand="block"
              onClick={() => onClickHandler('sad')}
              >Sad</IonButton>

              <IonButton
              id="angryButton"
              shape="round"
              expand="block"
              onClick={() => onClickHandler('angry')}
              >Mad</IonButton>
            </IonRow>
          </div>
        </IonGrid>

        <IonButton
        id="Create"
        shape="round"
        expand="block"
        routerLink="/addnote"
        >Create +</IonButton>

      </IonContent>
    </IonPage>
  );
};
</code>```

Body:
I'm using Ionic React in my project to create a mood selection tab. When a user selects/clicks a mood (button), the emoji, button color, and button text color will change. If the user then clicks another button, the previous button will revert back to its original color.

like this:

but I can only change the emoji image. I tried using --color-activated and --background-activated to change the color of the button color and text color but nothing change. anyone know how to do it? any help will be appreciated

here's my code:

const Tab1: React.FC = () => {
  const user = useContext(UserContext);

  const [imageClicked, setImageClicked] = useState({
    noEmoji: true,
    great: false,
    happy: false,
    okay: false,
    sad: false,
    angry: false
  });

  const onClickHandler = (order: any) => {
    const resetimages = {
      noEmoji: false,
      great: false,
      happy: false,
      okay: false,
      sad: false,
      angry: false
    };
    setImageClicked({
      ...resetimages,
      [order]: true,
    });
  };

  return (
    <IonPage>
      <IonHeader translucent={true} mode="ios" class="ion-no-border">
        <IonToolbar>
          <IonTitle id="headerTitle">Select Your Mood</IonTitle>
          <IonButtons slot="start">
            <IonButton id="headerSettings" routerLink="/userProfile">
              <IonIcon slot="icon-only" size="large" icon={personCircleOutline} />
            </IonButton>
          </IonButtons>
        </IonToolbar>
      </IonHeader>

      <IonContent fullscreen>
        <IonTitle class="ion-text-center" id="welcomeTitle">

            Hello {user?.displayName},

            How are you today?

        </IonTitle>

        <IonGrid>

            {imageClicked.noEmoji && }
            {imageClicked.great && }
            {imageClicked.happy && }
            {imageClicked.okay && }
            {imageClicked.sad && }
            {imageClicked.angry && }

            <IonRow>
              <IonButton
              id="greatButton"
              shape="round"
              expand="block"
              onClick={() => onClickHandler('great')}
              >Great</IonButton>

              <IonButton
              id="happyButton"
              shape="round"
              expand="block"
              onClick={() => onClickHandler('happy')}
              >Happy</IonButton>
            </IonRow>

            <IonRow>
              <IonButton
              id="okayButton"
              shape="round"
              expand="block"
              onClick={() => onClickHandler('okay')}
              >Okay</IonButton>

              <IonButton
              id="sadButton"
              shape="round"
              expand="block"
              onClick={() => onClickHandler('sad')}
              >Sad</IonButton>

              <IonButton
              id="angryButton"
              shape="round"
              expand="block"
              onClick={() => onClickHandler('angry')}
              >Mad</IonButton>
            </IonRow>

        </IonGrid>

        <IonButton
        id="Create"
        shape="round"
        expand="block"
        routerLink="/addnote"
        >Create +</IonButton>

      </IonContent>
    </IonPage>
  );
};


问:
How to create custom sdk with android hidden api
i'm trying to use some classes from android's hidden api, but i can't use it in default android studio. So i decide to do some custom and make sdk with hidden apis with this instruction click. I tried to get framework.jar from 3 emulated devices and 1 physical, but in all cases it was about 1kb (api 28).

So the questions: how can i use hidden api in android studio without reflection? Is it possible to make custom sdk with hidden apis in 2023?


问:
How do I run javascript from extension console to the main page console?
I know on stackoverflow there are many solutions but still I failed, I cannot do it.
I want to print hello world in main page console from extension. How can I do it?
I will share what I did until now.

(As you see in the picture, there is nothing on the main console.)

html of extension:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>Saitama Techno</title>
    </head>
    <body>
        <h1>Welcome to Saitama Techno</h1>
        <button id="mybutton">Click me</button>
        <script src="myscript.js"></script>
    </body>
</html>
</code>```

javascript code:

```<code>function btnclicked(){
    console.log("Hello from extension");
    chrome.extension.getBackgroundPage().console.log('hello to main console');
}
document.getElementById("mybutton").addEventListener("click", btnclicked);

</code>```

manifest.json:

```<code>{
    "name": "Saitama Techno scraping",
    "version": "1.0.0",
    "description": "webscraping duuuuuuude",
    "manifest_version": 3,
    "author": "Enes Telli",
    "action": {
        "default_popup": "index.html",
        "default_title": "Saitama Techno"
    },
    "permissions": ["https://*/*",
    "http://*/*", "storage", "tabs", "declarativeContent", "activeTab", "scripting"]
}
</code>```

Body:
I know on stackoverflow there are many solutions but still I failed, I cannot do it.
I want to print hello world in main page console from extension. How can I do it?
I will share what I did until now.

(As you see in the picture, there is nothing on the main console.)

html of extension:

<!DOCTYPE html>

        <title>Saitama Techno</title>

Welcome to Saitama Techno

        <button id="mybutton">Click me</button>

javascript code:

function btnclicked(){
    console.log("Hello from extension");
    chrome.extension.getBackgroundPage().console.log('hello to main console');
}
document.getElementById("mybutton").addEventListener("click", btnclicked);

manifest.json:

{
    "name": "Saitama Techno scraping",
    "version": "1.0.0",
    "description": "webscraping duuuuuuude",
    "manifest_version": 3,
    "author": "Enes Telli",
    "action": {
        "default_popup": "index.html",
        "default_title": "Saitama Techno"
    },
    "permissions": ["https://*/*",
    "http://*/*", "storage", "tabs", "declarativeContent", "activeTab", "scripting"]
}


问:
Calling opensearch service via lambda, but reqest not getting posted
Posting data on opensearch service via lambda, but when I am going to opensearch service Endpoint URL to check getting below error.

{
"error" : "no handler found for uri [/lambda-s3-index/lambda-type/_search] and method [GET]"
}

Tried printing the response while posting, getting 400. below is the code

```import boto3
import requests
from requests_aws4auth import AWS4Auth
import os
import json
import datetime

region = 'us-east-1'
service = 'es'
credentials = boto3.Session().get_credentials()
awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)

index = 'lambda-s3-index'
type = 'lambda-type'
host = os.environ['ES_DOMAIN_URL']
url = host + '/' + index + '/' + type

headers = { "Content-Type": "application/json" }

s3 = boto3.client('s3')
bucket = os.environ['S3_BUCKET']

# Lambda execution starts here
def handler(event, context):
    sensorID = event['sensorID']
    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    temperature = event['temperature']

    document = { "sensorID": sensorID, "timestamp": timestamp, "temperature": temperature }
    print(document)
    # post to S3 for storage
    s3.put_object(Body=json.dumps(document).encode(), Bucket=bucket, Key=sensorID+"-"+timestamp+".json")
    # post to amazon elastic search for indexing and kibana use
    r = requests.post(url, auth=awsauth, json=document, headers=headers)
    print(r)
    response = "Data Uploaded"
    return {
        "Response" : response,
        "sensorID" : sensorID,
        "temperature": temperature
    }
</code>```

Body:
Posting data on opensearch service via lambda, but when I am going to opensearch service Endpoint URL to check getting below error.

{
"error" : "no handler found for uri [/lambda-s3-index/lambda-type/_search] and method [GET]"
}

Tried printing the response while posting, getting 400. below is the code

import boto3
import requests
from requests_aws4auth import AWS4Auth
import os
import json
import datetime

region = 'us-east-1'
service = 'es'
credentials = boto3.Session().get_credentials()
awsauth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service, session_token=credentials.token)

index = 'lambda-s3-index'
type = 'lambda-type'
host = os.environ['ES_DOMAIN_URL']
url = host + '/' + index + '/' + type

headers = { "Content-Type": "application/json" }

s3 = boto3.client('s3')
bucket = os.environ['S3_BUCKET']

# Lambda execution starts here
def handler(event, context):
    sensorID = event['sensorID']
    timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
    temperature = event['temperature']

    document = { "sensorID": sensorID, "timestamp": timestamp, "temperature": temperature }
    print(document)
    # post to S3 for storage
    s3.put_object(Body=json.dumps(document).encode(), Bucket=bucket, Key=sensorID+"-"+timestamp+".json")
    # post to amazon elastic search for indexing and kibana use
    r = requests.post(url, auth=awsauth, json=document, headers=headers)
    print(r)
    response = "Data Uploaded"
    return {
        "Response" : response,
        "sensorID" : sensorID,
        "temperature": temperature
    }


问:
.loc into multindex pandas df on not-level zero with sorted order
say I have a multi index pandas data frame and I want to slice into the whole data frame on the not-zeroth level of the  data frame and get a dataframe back in the order of the sliced list.

this happens automatically using .loc on the zeroth level of the multi index, but apparently not-so for other levels.

here is what I mean:

```<code># create a multiindex dataframe
index = [('a',1), ('b',2), ('c', 3)]
index = pd.MultiIndex.from_tuples(index, names = ['letters', 'numbers'])
df = pd.DataFrame(index  = index, data = ['cat', 'dog', 'bird'],
                 columns = ['animal'])

# say I want to index on 'letters' level of df
lst_1 = ['c', 'a']
df2 = df.loc[lst_1 ] # this returns what I want in the order of lst

# now say I want to index on the 'numbers' level of df
lst_2 = [3, 2, 1]
df3 = df.loc(axis = 0)[:, lst_2] # PROBLEM: df3 is identical to df
</code>```

EXPECTED OUTPUT:

```<code>                animal
letters numbers
c       3         bird
b       2          dog
a       1          cat
</code>```

but what df3 returns is

```<code>                animal
letters numbers
a       1          cat
b       2          dog
c       3         bird
</code>```

I want something where df3 is sorted as df2 is.

I can cheat and do df.swaplevels() but I'm querying my dataframe with multiple different sources that sometimes require subsetting on "numbers" and sometimes on "letters" and I hate, hate copying and recopying my dataframe while adding unnecessary lines of code.

thank you!

Body:
say I have a multi index pandas data frame and I want to slice into the whole data frame on the not-zeroth level of the  data frame and get a dataframe back in the order of the sliced list.

this happens automatically using .loc on the zeroth level of the multi index, but apparently not-so for other levels.

here is what I mean:

# create a multiindex dataframe
index = [('a',1), ('b',2), ('c', 3)]
index = pd.MultiIndex.from_tuples(index, names = ['letters', 'numbers'])
df = pd.DataFrame(index  = index, data = ['cat', 'dog', 'bird'],
                 columns = ['animal'])

# say I want to index on 'letters' level of df
lst_1 = ['c', 'a']
df2 = df.loc[lst_1 ] # this returns what I want in the order of lst

# now say I want to index on the 'numbers' level of df
lst_2 = [3, 2, 1]
df3 = df.loc(axis = 0)[:, lst_2] # PROBLEM: df3 is identical to df

EXPECTED OUTPUT:

                animal
letters numbers
c       3         bird
b       2          dog
a       1          cat

but what df3 returns is

                animal
letters numbers
a       1          cat
b       2          dog
c       3         bird

I want something where df3 is sorted as df2 is.

I can cheat and do df.swaplevels() but I'm querying my dataframe with multiple different sources that sometimes require subsetting on "numbers" and sometimes on "letters" and I hate, hate copying and recopying my dataframe while adding unnecessary lines of code.

thank you!


问:
Sorting the data set in order for showing
I have some photos in my data directory, their names are as follows:

0.png, 10.png,20.png,30.png,40.png,50.png,60.png,70.png,80.png,90.png,100.png,
110.png,120.png,130.png,140.png,150.png,160.png,170.png,180.png,190.png,200.png,
210.png,220.png,230.png,240.png,250.png,260.png,270.png,280.png,290.png,300.png,
310.png,320.png,330.png,340.png,350.png,360.png
```
<p>for reading these files I use this command:</p>
```import glob

path = glob.glob("./data/*.png")
for file in path:
    print(path)
    img = cv2.imread(file)
    cv2.imshow('image', img)
```
<p>and the output is:</p>
```['./data\\0.png', './data\\10.png', './data\\100.png', './data\\110.png', './data\\120.png', './data\\130.png', './data\\140.png', './data\\150.png', './data\\160.png', './data\\170.png', './data\\180.png', './data\\190.png', './data\\20.png', './data\\200.png', './data\\210.png', './data\\220.png', './data\\230.png', './data\\240.png', './data\\250.png', './data\\260.png', './data\\270.png', './data\\280.png', './data\\290.png', './data\\30.png', './data\\300.png', './data\\310.png', './data\\320.png', './data\\330.png', './data\\340.png', './data\\350.png', './data\\360.png', './data\\40.png', './data\\50.png', './data\\60.png', './data\\70.png', './data\\80.png', './data\\90.png']
```

As you see, they are not shown by order.
How can one sort them in order?

I want to sort my data set in order to show.

Body:
I have some photos in my data directory, their names are as follows:

0.png, 10.png,20.png,30.png,40.png,50.png,60.png,70.png,80.png,90.png,100.png,
110.png,120.png,130.png,140.png,150.png,160.png,170.png,180.png,190.png,200.png,
210.png,220.png,230.png,240.png,250.png,260.png,270.png,280.png,290.png,300.png,
310.png,320.png,330.png,340.png,350.png,360.png

for reading these files I use this command:

import glob

path = glob.glob("./data/*.png")
for file in path:
    print(path)
    img = cv2.imread(file)
    cv2.imshow('image', img)

and the output is:

['./data\\0.png', './data\\10.png', './data\\100.png', './data\\110.png', './data\\120.png', './data\\130.png', './data\\140.png', './data\\150.png', './data\\160.png', './data\\170.png', './data\\180.png', './data\\190.png', './data\\20.png', './data\\200.png', './data\\210.png', './data\\220.png', './data\\230.png', './data\\240.png', './data\\250.png', './data\\260.png', './data\\270.png', './data\\280.png', './data\\290.png', './data\\30.png', './data\\300.png', './data\\310.png', './data\\320.png', './data\\330.png', './data\\340.png', './data\\350.png', './data\\360.png', './data\\40.png', './data\\50.png', './data\\60.png', './data\\70.png', './data\\80.png', './data\\90.png']

As you see, they are not shown by order.
How can one sort them in order?

I want to sort my data set in order to show.


问:
Firebase signInWithRedirect() not preserving Vue route params
I have a Pricing page which has a pricing table and does the following to redirect to a Sign Up page with a route param which determines which price (product) the user picked:

```<code>methods: {
    subscribe(price) {
      this.loading = true;
      if (!this.loggedIn) {
        this.$router.push({ name: "Sign Up", params: { price: price } });
      }
    },
  },
</code>```

In the Sign Up component, it will console log the correct price from the route param in mounted , but after the signIn with google happens and it redirects to the Checkout component, the route param price is lost:

```<code>mounted: function () {
    const googleAuth = new firebase.auth.GoogleAuthProvider();
    if (!this.loggedIn) {
      firebase.auth().signInWithRedirect(googleAuth);
      firebase
        .auth()
        .getRedirectResult()
        .then((result) => {
          this.$router.push({ name: "Checkout", params: { price: this.$route.params.price } });
          console.log(result);
        })
        .catch((error) => {
          console.log(error);
        });
      firebase.auth().onAuthStateChanged((user) => {
        if (user) {
          this.loggedIn = true;
        } else {
          // Show sign in screen with button above.
        }
      });
    }
  },
</code>```

Body:
I have a Pricing page which has a pricing table and does the following to redirect to a Sign Up page with a route param which determines which price (product) the user picked:

methods: {
    subscribe(price) {
      this.loading = true;
      if (!this.loggedIn) {
        this.$router.push({ name: "Sign Up", params: { price: price } });
      }
    },
  },

In the Sign Up component, it will console log the correct price from the route param in mounted , but after the signIn with google happens and it redirects to the Checkout component, the route param price is lost:

mounted: function () {
    const googleAuth = new firebase.auth.GoogleAuthProvider();
    if (!this.loggedIn) {
      firebase.auth().signInWithRedirect(googleAuth);
      firebase
        .auth()
        .getRedirectResult()
        .then((result) => {
          this.$router.push({ name: "Checkout", params: { price: this.$route.params.price } });
          console.log(result);
        })
        .catch((error) => {
          console.log(error);
        });
      firebase.auth().onAuthStateChanged((user) => {
        if (user) {
          this.loggedIn = true;
        } else {
          // Show sign in screen with button above.
        }
      });
    }
  },


问:
Player jumps a second time by itself after hitting the ground
I'm trying to make a First Person Controller and after I jump, right as the player is about to hit the ground, it jumps a second time by itself. This doesn't seem to be the case when the player lands on ground higher or lower than the ground it originally jumped on.

This is my Player code:
`

```<code>using System;
using UnityEngine;
using UnityEngine.InputSystem;

public class Player : MonoBehaviour
{
    [SerializeField] float mouseSensitivity = 3f;
    [SerializeField] float walkingSpeed = 10f;
    [SerializeField] float flyingSpeed = 15;
    [SerializeField] float climbingSpeed = 5f;
    [SerializeField] float mass = 1f;
    [SerializeField] float acceleration = 20f;

    [SerializeField] float worldBottomBoundary = -100f;

    public Transform cameraTransform;

    public bool IsGrounded => controller.isGrounded;

    public float Height
    {
        get => controller.height;
        set => controller.height = value;
    }

    public event Action OnBeforeMove;
    public event Action<bool> OnGroundStateChange;

    internal float movementSpeedMultiplier;

    State _state;

    public State CurrentState
    {
        get => _state;
        set
        {
            _state = value;
            velocity = Vector3.zero;
        }
    }

    public enum State
    {
        Walking,
        Flying,
        Climbing
    }

    CharacterController controller;
    internal Vector3 velocity;
    Vector2 look;

    (Vector3, Quaternion) initialPositionAndRotation;

    bool wasGrounded;

    PlayerInput playerInput;
    InputAction moveAction;
    InputAction lookAction;
    InputAction flyUpDownAction;

    void Awake()
    {
        controller = GetComponent<CharacterController>();
        playerInput = GetComponent<PlayerInput>();
        moveAction = playerInput.actions["move"];
        lookAction = playerInput.actions["look"];
        flyUpDownAction = playerInput.actions["flyUpDown"];
    }

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        initialPositionAndRotation = (transform.position, transform.rotation);
    }

    public void Teleport(Vector3 position, Quaternion rotation)
    {
        transform.position = position;
        Physics.SyncTransforms();
        look.x = rotation.eulerAngles.y;
        look.y = rotation.eulerAngles.z;
        velocity = Vector3.zero;
    }

    void Update()
    {
        movementSpeedMultiplier = 1f;
        switch (CurrentState)
        {
            case State.Walking:
                UpdateGround();
                UpdateGravity();
                UpdateMovement();
                UpdateLook();
                CheckBounds();
                break;
            case State.Flying:
                UpdateMovementFlying();
                UpdateLook();
                break;
            case State.Climbing:
                UpdateMovementClimbing();
                UpdateLook();
                break;
        }
    }

    void CheckBounds()
    {
        if (transform.position.y < worldBottomBoundary)
        {
            var (position, rotation) = initialPositionAndRotation;
            Teleport(position, rotation);
        }
    }

    void UpdateGround()
    {
        if (wasGrounded != IsGrounded)
        {
            OnGroundStateChange?.Invoke(IsGrounded);
            wasGrounded = IsGrounded;
        }
    }

    void UpdateGravity()
    {
        var gravity = Physics.gravity * mass * Time.deltaTime;
        velocity.y = IsGrounded ? -1f : velocity.y + gravity.y;
    }

    Vector3 GetMovementInput(float speed, bool horizontal = true)
    {
        var moveInput = moveAction.ReadValue<Vector2>();
        var flyUpDownInput = flyUpDownAction.ReadValue<float>();
        var input = new Vector3();
        var referenceTransform = horizontal ? transform : cameraTransform;
        input += referenceTransform.forward * moveInput.y;
        input += referenceTransform.right * moveInput.x;
        if (!horizontal)
        {
            input += transform.up * flyUpDownInput;
        }
        input = Vector3.ClampMagnitude(input, 1f);
        input *= speed * movementSpeedMultiplier;
        return input;
    }

    void UpdateMovement()
    {
        OnBeforeMove?.Invoke();

        var input = GetMovementInput(walkingSpeed);

        var factor = acceleration * Time.deltaTime;
        velocity.x = Mathf.Lerp(velocity.x, input.x, factor);
        velocity.z = Mathf.Lerp(velocity.z, input.z, factor);

        controller.Move(velocity * Time.deltaTime);
    }

    void UpdateMovementFlying()
    {
        var input = GetMovementInput(flyingSpeed, false);

        var factor = acceleration * Time.deltaTime;
        velocity = Vector3.Lerp(velocity, input, factor);

        controller.Move(velocity * Time.deltaTime);
    }

    void UpdateMovementClimbing()
    {
        var input = GetMovementInput(climbingSpeed, false);
        var forwardInputFactor = Vector3.Dot(transform.forward, input.normalized);

        if (forwardInputFactor > 0)
        {
            input.x = input.x * .5f;
            input.z = input.z * .5f;

            if (Mathf.Abs(input.y) > .2f)
            {
                input.y = Mathf.Sign(input.y) * climbingSpeed;
            }
        }
        else
        {
            input.y = 0;
            input.x = input.x * 3f;
            input.z = input.z * 3f;
        }

        var factor = acceleration * Time.deltaTime;
        velocity = Vector3.Lerp(velocity, input, factor);

        controller.Move(velocity * Time.deltaTime);
    }

    void UpdateLook()
    {
        var lookInput = lookAction.ReadValue<Vector2>();
        look.x += lookInput.x * mouseSensitivity;
        look.y += lookInput.y * mouseSensitivity;

        look.y = Mathf.Clamp(look.y, -90, 90f);

        cameraTransform.localRotation = Quaternion.Euler(-look.y, 0, 0);
        transform.localRotation = Quaternion.Euler(0, look.x, 0);
    }

    void OnToggleFlying()
    {
        CurrentState = CurrentState == State.Flying ? State.Walking : State.Flying;
    }
}
</code>```

`

And this is my PlayerJumping code:
`

```<code>using UnityEngine;

[RequireComponent(typeof(Player))]
public class PlayerJumping : MonoBehaviour
{
    [SerializeField] float jumpSpeed = 5f;
    [SerializeField] float jumpPressBufferTime = .05f;
    [SerializeField] float jumpGroundGraceTime = .2f;
    [SerializeField] int maxJumps = 1;

    Player player;

    bool tryingToJump;
    float lastJumpPressTime;
    float lastGroundedTime;
    int jumps;

    void Awake()
    {
        player = GetComponent<Player>();
    }

    void OnEnable()
    {
        player.OnBeforeMove += OnBeforeMove;
        player.OnGroundStateChange += OnGroundStateChange;
    }

    void OnDisable()
    {
        player.OnBeforeMove -= OnBeforeMove;
        player.OnGroundStateChange -= OnGroundStateChange;
    }

    void OnJump()
    {
        tryingToJump = true;
        lastJumpPressTime = Time.time;
    }

    void OnBeforeMove()
    {
        if (player.IsGrounded) jumps = 0;

        var wasTryingToJump = Time.time - lastJumpPressTime < jumpPressBufferTime;
        var wasGrounded = Time.time - lastGroundedTime < jumpGroundGraceTime;

        var isOrWasTryingToJump = tryingToJump || (wasTryingToJump && player.IsGrounded);
        var isOrWasGrounded = player.IsGrounded || wasGrounded;
        var jumpAllowed = jumps < maxJumps;

        if (
            jumpAllowed && isOrWasTryingToJump && isOrWasGrounded
            || jumpAllowed && tryingToJump
        )
        {
            player.velocity.y += jumpSpeed;
            jumps++;
        }

        tryingToJump = false;
    }

    void OnGroundStateChange(bool isGrounded)
    {
        if (!isGrounded) lastGroundedTime = Time.time;
    }
}
</code>```

`

Although to be honest, I've checked a million times and I'm starting to believe the problem isn't in the code but in the inspector, but don't let that cloud your judgement because I can be pretty stupid at times. Do you have any ideas?

Body:
I'm trying to make a First Person Controller and after I jump, right as the player is about to hit the ground, it jumps a second time by itself. This doesn't seem to be the case when the player lands on ground higher or lower than the ground it originally jumped on.

This is my Player code:
`

using System;
using UnityEngine;
using UnityEngine.InputSystem;

public class Player : MonoBehaviour
{
    [SerializeField] float mouseSensitivity = 3f;
    [SerializeField] float walkingSpeed = 10f;
    [SerializeField] float flyingSpeed = 15;
    [SerializeField] float climbingSpeed = 5f;
    [SerializeField] float mass = 1f;
    [SerializeField] float acceleration = 20f;

    [SerializeField] float worldBottomBoundary = -100f;

    public Transform cameraTransform;

    public bool IsGrounded => controller.isGrounded;

    public float Height
    {
        get => controller.height;
        set => controller.height = value;
    }

    public event Action OnBeforeMove;
    public event Action<bool> OnGroundStateChange;

    internal float movementSpeedMultiplier;

    State _state;

    public State CurrentState
    {
        get => _state;
        set
        {
            _state = value;
            velocity = Vector3.zero;
        }
    }

    public enum State
    {
        Walking,
        Flying,
        Climbing
    }

    CharacterController controller;
    internal Vector3 velocity;
    Vector2 look;

    (Vector3, Quaternion) initialPositionAndRotation;

    bool wasGrounded;

    PlayerInput playerInput;
    InputAction moveAction;
    InputAction lookAction;
    InputAction flyUpDownAction;

    void Awake()
    {
        controller = GetComponent<CharacterController>();
        playerInput = GetComponent<PlayerInput>();
        moveAction = playerInput.actions["move"];
        lookAction = playerInput.actions["look"];
        flyUpDownAction = playerInput.actions["flyUpDown"];
    }

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;
        initialPositionAndRotation = (transform.position, transform.rotation);
    }

    public void Teleport(Vector3 position, Quaternion rotation)
    {
        transform.position = position;
        Physics.SyncTransforms();
        look.x = rotation.eulerAngles.y;
        look.y = rotation.eulerAngles.z;
        velocity = Vector3.zero;
    }

    void Update()
    {
        movementSpeedMultiplier = 1f;
        switch (CurrentState)
        {
            case State.Walking:
                UpdateGround();
                UpdateGravity();
                UpdateMovement();
                UpdateLook();
                CheckBounds();
                break;
            case State.Flying:
                UpdateMovementFlying();
                UpdateLook();
                break;
            case State.Climbing:
                UpdateMovementClimbing();
                UpdateLook();
                break;
        }
    }

    void CheckBounds()
    {
        if (transform.position.y < worldBottomBoundary)
        {
            var (position, rotation) = initialPositionAndRotation;
            Teleport(position, rotation);
        }
    }

    void UpdateGround()
    {
        if (wasGrounded != IsGrounded)
        {
            OnGroundStateChange?.Invoke(IsGrounded);
            wasGrounded = IsGrounded;
        }
    }

    void UpdateGravity()
    {
        var gravity = Physics.gravity * mass * Time.deltaTime;
        velocity.y = IsGrounded ? -1f : velocity.y + gravity.y;
    }

    Vector3 GetMovementInput(float speed, bool horizontal = true)
    {
        var moveInput = moveAction.ReadValue<Vector2>();
        var flyUpDownInput = flyUpDownAction.ReadValue<float>();
        var input = new Vector3();
        var referenceTransform = horizontal ? transform : cameraTransform;
        input += referenceTransform.forward * moveInput.y;
        input += referenceTransform.right * moveInput.x;
        if (!horizontal)
        {
            input += transform.up * flyUpDownInput;
        }
        input = Vector3.ClampMagnitude(input, 1f);
        input *= speed * movementSpeedMultiplier;
        return input;
    }

    void UpdateMovement()
    {
        OnBeforeMove?.Invoke();

        var input = GetMovementInput(walkingSpeed);

        var factor = acceleration * Time.deltaTime;
        velocity.x = Mathf.Lerp(velocity.x, input.x, factor);
        velocity.z = Mathf.Lerp(velocity.z, input.z, factor);

        controller.Move(velocity * Time.deltaTime);
    }

    void UpdateMovementFlying()
    {
        var input = GetMovementInput(flyingSpeed, false);

        var factor = acceleration * Time.deltaTime;
        velocity = Vector3.Lerp(velocity, input, factor);

        controller.Move(velocity * Time.deltaTime);
    }

    void UpdateMovementClimbing()
    {
        var input = GetMovementInput(climbingSpeed, false);
        var forwardInputFactor = Vector3.Dot(transform.forward, input.normalized);

        if (forwardInputFactor > 0)
        {
            input.x = input.x * .5f;
            input.z = input.z * .5f;

            if (Mathf.Abs(input.y) > .2f)
            {
                input.y = Mathf.Sign(input.y) * climbingSpeed;
            }
        }
        else
        {
            input.y = 0;
            input.x = input.x * 3f;
            input.z = input.z * 3f;
        }

        var factor = acceleration * Time.deltaTime;
        velocity = Vector3.Lerp(velocity, input, factor);

        controller.Move(velocity * Time.deltaTime);
    }

    void UpdateLook()
    {
        var lookInput = lookAction.ReadValue<Vector2>();
        look.x += lookInput.x * mouseSensitivity;
        look.y += lookInput.y * mouseSensitivity;

        look.y = Mathf.Clamp(look.y, -90, 90f);

        cameraTransform.localRotation = Quaternion.Euler(-look.y, 0, 0);
        transform.localRotation = Quaternion.Euler(0, look.x, 0);
    }

    void OnToggleFlying()
    {
        CurrentState = CurrentState == State.Flying ? State.Walking : State.Flying;
    }
}

`

And this is my PlayerJumping code:
`

using UnityEngine;

[RequireComponent(typeof(Player))]
public class PlayerJumping : MonoBehaviour
{
    [SerializeField] float jumpSpeed = 5f;
    [SerializeField] float jumpPressBufferTime = .05f;
    [SerializeField] float jumpGroundGraceTime = .2f;
    [SerializeField] int maxJumps = 1;

    Player player;

    bool tryingToJump;
    float lastJumpPressTime;
    float lastGroundedTime;
    int jumps;

    void Awake()
    {
        player = GetComponent<Player>();
    }

    void OnEnable()
    {
        player.OnBeforeMove += OnBeforeMove;
        player.OnGroundStateChange += OnGroundStateChange;
    }

    void OnDisable()
    {
        player.OnBeforeMove -= OnBeforeMove;
        player.OnGroundStateChange -= OnGroundStateChange;
    }

    void OnJump()
    {
        tryingToJump = true;
        lastJumpPressTime = Time.time;
    }

    void OnBeforeMove()
    {
        if (player.IsGrounded) jumps = 0;

        var wasTryingToJump = Time.time - lastJumpPressTime < jumpPressBufferTime;
        var wasGrounded = Time.time - lastGroundedTime < jumpGroundGraceTime;

        var isOrWasTryingToJump = tryingToJump || (wasTryingToJump && player.IsGrounded);
        var isOrWasGrounded = player.IsGrounded || wasGrounded;
        var jumpAllowed = jumps < maxJumps;

        if (
            jumpAllowed && isOrWasTryingToJump && isOrWasGrounded
            || jumpAllowed && tryingToJump
        )
        {
            player.velocity.y += jumpSpeed;
            jumps++;
        }

        tryingToJump = false;
    }

    void OnGroundStateChange(bool isGrounded)
    {
        if (!isGrounded) lastGroundedTime = Time.time;
    }
}

`

Although to be honest, I've checked a million times and I'm starting to believe the problem isn't in the code but in the inspector, but don't let that cloud your judgement because I can be pretty stupid at times. Do you have any ideas?


问:
How to sort multiple columns on DataTables Server Side Processing?
I have a problem with multiple sort columns DataTables server side processing. When I'm hold Shift key and click the column, there is nothing change with my table. I'm not using SSP Class. And my code is something like this:

`

```<code>if (isset($_POST['order'])) {
    $order = $columns[$_POST['order']['0']['column']];
    $dir = $_POST['order']['0']['dir'];
}else{
    $order = "bukti_transfer.tgl_transfer DESC, bukti_transfer.nama_usaha ASC";
    $dir ="";
}

$query=mysql_query("SELECT * FROM my_table ORDER BY $order $dir LIMIT $limit OFFSET $start  ");
</code>```

`

Can anyone help me to solve this?

Body:
I have a problem with multiple sort columns DataTables server side processing. When I'm hold Shift key and click the column, there is nothing change with my table. I'm not using SSP Class. And my code is something like this:

`

if (isset($_POST['order'])) {
    $order = $columns[$_POST['order']['0']['column']];
    $dir = $_POST['order']['0']['dir'];
}else{
    $order = "bukti_transfer.tgl_transfer DESC, bukti_transfer.nama_usaha ASC";
    $dir ="";
}

$query=mysql_query("SELECT * FROM my_table ORDER BY $order $dir LIMIT $limit OFFSET $start  ");

`

Can anyone help me to solve this?


问:
How do I get React Router DOM to work from a CDN link?
I want to use React Router DOM using this CDN.

In my App.jsx file, I have the following:

```<code>const Link = ReactRouterDOM.Link;
const BrowserRouter = ReactRouterDOM.BrowserRouter;
const Route = ReactRouterDOM.Route;

...

<div>
    <BrowserRouter>
        <Navbar/>
        <div className="row mt-3">
            <div className="col-2">
            {folders.map((x, folderId) => { return (
                <div key={folderId}>
                    <Link to={`folder/${x.name}`}>{x.name}</Link>
                </div>
                ); })}
            </div>
            <div className="col-2"></div>
            <div className="col-8"></div>
        </div>

        <Route path="/folder/:name" element={<Folder/>}/>
    </BrowserRouter>
</div>
</code>```

When rendering, I get the error:

index.tsx:1219 Uncaught TypeError: Cannot read properties of undefined (reading 'Route')

Is there something I forgot to import? Am I using the wrong React Router DOM version? Thanks in advance

Body:
I want to use React Router DOM using this CDN.

In my App.jsx file, I have the following:

const Link = ReactRouterDOM.Link;
const BrowserRouter = ReactRouterDOM.BrowserRouter;
const Route = ReactRouterDOM.Route;

...

    <BrowserRouter>
        <Navbar/>

            {folders.map((x, folderId) => { return (

                    <Link to={`folder/${x.name}`}>{x.name}</Link>

                ); })}

        <Route path="/folder/:name" element={<Folder/>}/>
    </BrowserRouter>

When rendering, I get the error:

index.tsx:1219 Uncaught TypeError: Cannot read properties of undefined (reading 'Route')

Is there something I forgot to import? Am I using the wrong React Router DOM version? Thanks in advance


问:
How to connect websocket server running on minikube to the client?
I have a 2-way board game server and a client. I dockerized the client and now running it on minikube locally. I am not sure how to connect it to the clients.

Before this I was just doing npm start for the server and client (2 instances of client) and running the game.

I am not sure if I have to make some changes to the client as well, or can I just put a simple link (like localhost:// 8080) as i was doing earlier (running client not on minikube)


问:
How to validate a patch file for patch-package?
I have a made a patch file for patch-package npm module: https://github.com/ds300/patch-package

Problem is, when I try to run the patch, it results in this error:

ERROR Failed to apply patch for package react-native
This happened because the patch file patches/react-native+0.59.10.patch could not be parsed.

How can I validate and locate the error where the patch file parsing went wrong?

Patch-package version: "patch-package": "^6.4.5",


问:
Ionic importing ScreenOrientation makes the app blank
I have a simple problem. Whenever I import ScreenOrientation from Ionic, my app turns into a blank white screen on my emulator:

```<code>import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';

  constructor(
    //private screenOrientation: ScreenOrientation,
    private platform: Platform
  ) { }
</code>```

Whenever I uncomment that first import and try to build and run, my Ionic app goes blank. I've sequentially commented out every other element in the component and narrowed it down to this issue. Can anyone answer why it does this?

EDIT: package.json below

```<code>{
  "dependencies": {
    "@angular-devkit/build-angular": "^15.0.4",
    "@angular/common": "^15.0.4",
    "@angular/core": "^15.0.4",
    "@angular/material": "^15.0.3",
    "@angular/platform-browser-dynamic": "^15.0.4",
    "@angular/router": "^15.0.4",
    "@capacitor/android": "^4.6.1",
    "@capacitor/core": "^4.6.1",
    "@capacitor/ios": "^4.6.1",
    "@ionic-native/screen-orientation": "^5.36.0",
    "@ionic/angular": "^6.4.1",
    "@types/d3": "^7.4.0",
    "rxjs": "^6.6.7"
  },
  "devDependencies": {
    "@capacitor/cli": "^4.6.1",
    "@types/jest": "^29.2.5"
  }
}
</code>```

Providers in app.module.ts:

```<code>  providers: [
    { provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptorService,
      multi: true},
    ScreenOrientation,
    {
      provide: RouteReuseStrategy,
      useClass: IonicRouteStrategy
    }
    ]
</code>```

Body:
I have a simple problem. Whenever I import ScreenOrientation from Ionic, my app turns into a blank white screen on my emulator:

import { ScreenOrientation } from '@ionic-native/screen-orientation/ngx';

  constructor(
    //private screenOrientation: ScreenOrientation,
    private platform: Platform
  ) { }

Whenever I uncomment that first import and try to build and run, my Ionic app goes blank. I've sequentially commented out every other element in the component and narrowed it down to this issue. Can anyone answer why it does this?

EDIT: package.json below

{
  "dependencies": {
    "@angular-devkit/build-angular": "^15.0.4",
    "@angular/common": "^15.0.4",
    "@angular/core": "^15.0.4",
    "@angular/material": "^15.0.3",
    "@angular/platform-browser-dynamic": "^15.0.4",
    "@angular/router": "^15.0.4",
    "@capacitor/android": "^4.6.1",
    "@capacitor/core": "^4.6.1",
    "@capacitor/ios": "^4.6.1",
    "@ionic-native/screen-orientation": "^5.36.0",
    "@ionic/angular": "^6.4.1",
    "@types/d3": "^7.4.0",
    "rxjs": "^6.6.7"
  },
  "devDependencies": {
    "@capacitor/cli": "^4.6.1",
    "@types/jest": "^29.2.5"
  }
}

Providers in app.module.ts:

  providers: [
    { provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptorService,
      multi: true},
    ScreenOrientation,
    {
      provide: RouteReuseStrategy,
      useClass: IonicRouteStrategy
    }
    ]


问:
After upgrading to Angular 14 and after prod build, polyfills.js attempts to load main.js.map
And this fails as I never enabled source mapping for my prod build. There is no main.js.map file that is produced by the build.

Prior to upgrading from Angular 13 this was never an issue.

What would cause polyfills.js to reference main.js.map?


问:
Use '#selector' instead of explicitly constructing a 'Selector' warning
I have this line in my code:

```<code>let argsort = (scores as NSDictionary?)?.keysSortedByValue(using: Selector("compare:"))
</code>```

but XCode gives me a Use '#selector' instead of explicitly constructing a 'Selector' warning. However, the proposed fix:

```<code>let argsort = (scores as NSDictionary?)?.keysSortedByValue(using: #selector(NSTextLocation.compare(_:)))
</code>```

requires iOS version 15.0, and therefore does not work for me (I am targetting iOS 13.0).

How can I either silence this warning or find a way out of this? Thanks

Body:
I have this line in my code:

let argsort = (scores as NSDictionary?)?.keysSortedByValue(using: Selector("compare:"))

but XCode gives me a Use '#selector' instead of explicitly constructing a 'Selector' warning. However, the proposed fix:

let argsort = (scores as NSDictionary?)?.keysSortedByValue(using: #selector(NSTextLocation.compare(_:)))

requires iOS version 15.0, and therefore does not work for me (I am targetting iOS 13.0).

How can I either silence this warning or find a way out of this? Thanks


问:
Keep JavaScript-Context on reload
On reloading the javascript-context keeps changing to 'top'.

Is there any way to keep the context or at least a console command to change the context?

Title: Keep JavaScript-Context on reload


问:
Make Razor fetch Views from another project
I'm trying to implement vertical slice architecture. I have my Program.cs in Web project and my Views are coupled with Controllers in Core project. Razor won't find them when they are placed like that, but easily locates them in Web/Views, for example (relative path)

I register my controllers with views like that:

```<code>builder.Services.AddRazorPages(); // I also temporarily have some Razor Pages in my system.
builder.Services.AddControllersWithViews()
    .AddApplicationPart(typeof(Faction).Assembly); // Add controllers from another assembly
</code>```
```<code>app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllers();

app.MapRazorPages();
</code>```
```<code>return View("/Features/Statistics/GetLast5GamesStatsGlobal/GetLast5GamesStatsGlobal.cshtml", viewModel);
</code>```

Produces

InvalidOperationException: The view '/Features/Statistics/GetLast5GamesStatsGlobal/GetLast5GamesStatsGlobal.cshtml' was not found. The following locations were searched:
/Features/Statistics/GetLast5GamesStatsGlobal/GetLast5GamesStatsGlobal.cshtml*

File is located on this location, but in another project

How do I make them visible to the engine?

I have tried respecifying paths in different formats, using absolute path.

Body:
I'm trying to implement vertical slice architecture. I have my Program.cs in Web project and my Views are coupled with Controllers in Core project. Razor won't find them when they are placed like that, but easily locates them in Web/Views, for example (relative path)

I register my controllers with views like that:

builder.Services.AddRazorPages(); // I also temporarily have some Razor Pages in my system.
builder.Services.AddControllersWithViews()
    .AddApplicationPart(typeof(Faction).Assembly); // Add controllers from another assembly

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllers();

app.MapRazorPages();

return View("/Features/Statistics/GetLast5GamesStatsGlobal/GetLast5GamesStatsGlobal.cshtml", viewModel);

Produces

InvalidOperationException: The view '/Features/Statistics/GetLast5GamesStatsGlobal/GetLast5GamesStatsGlobal.cshtml' was not found. The following locations were searched:
/Features/Statistics/GetLast5GamesStatsGlobal/GetLast5GamesStatsGlobal.cshtml*

File is located on this location, but in another project

How do I make them visible to the engine?

I have tried respecifying paths in different formats, using absolute path.


问:
TypeError: Cannot read properties of undefined (reading 'state')
I tried console.log(this.state.bike). It gave me an array that basically contains everything I need. But when I try to access them I get undefined. How do I access the bikeLocation and bikeDescription? I have added 3 files. BikeServices, ListBikes and ViewBike Components.

```<code>import React, { Component } from 'react';
import BikeServices from '../services/BikeServices';

class viewBike extends Component {
    constructor(props){

        super(props)

        this.state = {
            bikeId: this.props.match.params.bikeId,
            bike: {}

        }

    }

    componentDidMount(){
        BikeServices.getBikesById(this.state.bikeId).then( (res) => {
            this.setState({bike: res.data});
            //console.log(this.state.bike);
            console.log(this.state.bike.bikeLocation);
        });
    }

    render() {

        return (
            <div>

               <br></br>
                    {this.state.bikeId}

                    <br></br>
                    {this.state.bike.bikeLocation}
            </div>
        );
    }
}

export default viewBike;

//BikeServices

import axios from 'axios';

const BIKE_URL = `http://localhost:8090/api/v1/bikes`;

class BikeService{

    getBikes(){
        return axios.get(BIKE_URL);
    }

    getBikesById(bikeId){

        return axios.get(BIKE_URL+ '/' +bikeId);

    }

}

export default new BikeService();

//ListBikes component

import React, { Component } from 'react';
import BikeService from '../services/BikeServices'

class ListBikes extends Component {

    constructor(props) {
        super(props)
        this.state = {
            bikes : [],
        }

        this.viewBike = this.viewBike.bind(this);
    }
    // bikes=[]

    componentDidMount(){
        BikeService.getBikes().then((res) => {
            this.setState({ bikes: res.data});

        });
    }

    viewBike(bikeId){
        console.log(this.props)
        this.props.history.push(`/bike/${bikeId}`);
    }

    render() {

        return (

                <div className='container'>

                {

                    this.state.bikes.map(
                        bike=>

                                    <div className="card">
                                        <div className="card-header">
                                        <img src="https://c0.wallpaperflare.com/preview/483/210/436/car-green-4x4-jeep.jpg" alt="rover" />
                                        </div>
                                        <div className="card-body">
                                        <span className="tag tag-teal">{bike.bikeStatus}</span>
                                        <h4>
                                        Bike Category: {bike.bikeCategory}
                                        </h4>
                                        <p>
                                        Bike Description: {bike.bikeDescription}
                                        <br></br>
                                        Location:
                                        {bike.location.address}, {bike.location.city}, {bike.location.state}, {bike.location.zip}
                                        </p>

                                        <button style={{marginLeft: "10px"}} onClick={() => this.viewBike(bike.bikeId)} className='btn btn-primary'>View</button>
                                         <button>Rent</button>

                                        </div>
                                    </div>

                    )

                }

                </div>

        );
    }
}

export default ListBikes;

</code>```

I tried console.log(this.state.bike). It gave me an array that basically contains everything I need. But when I try to access them I get undefined. How do I access the bikeLocation and bikeDescription? I have added 3 files. BikeServices, ListBikes and ViewBike Components.

Body:
I tried console.log(this.state.bike). It gave me an array that basically contains everything I need. But when I try to access them I get undefined. How do I access the bikeLocation and bikeDescription? I have added 3 files. BikeServices, ListBikes and ViewBike Components.

import React, { Component } from 'react';
import BikeServices from '../services/BikeServices';

class viewBike extends Component {
    constructor(props){

        super(props)

        this.state = {
            bikeId: this.props.match.params.bikeId,
            bike: {}

        }

    }

    componentDidMount(){
        BikeServices.getBikesById(this.state.bikeId).then( (res) => {
            this.setState({bike: res.data});
            //console.log(this.state.bike);
            console.log(this.state.bike.bikeLocation);
        });
    }

    render() {

        return (

                    {this.state.bikeId}

                    {this.state.bike.bikeLocation}

        );
    }
}

export default viewBike;

//BikeServices

import axios from 'axios';

const BIKE_URL = `http://localhost:8090/api/v1/bikes`;

class BikeService{

    getBikes(){
        return axios.get(BIKE_URL);
    }

    getBikesById(bikeId){

        return axios.get(BIKE_URL+ '/' +bikeId);

    }

}

export default new BikeService();

//ListBikes component

import React, { Component } from 'react';
import BikeService from '../services/BikeServices'

class ListBikes extends Component {

    constructor(props) {
        super(props)
        this.state = {
            bikes : [],
        }

        this.viewBike = this.viewBike.bind(this);
    }
    // bikes=[]

    componentDidMount(){
        BikeService.getBikes().then((res) => {
            this.setState({ bikes: res.data});

        });
    }

    viewBike(bikeId){
        console.log(this.props)
        this.props.history.push(`/bike/${bikeId}`);
    }

    render() {

        return (

                {

                    this.state.bikes.map(
                        bike=>

                                        {bike.bikeStatus}

                                        Bike Category: {bike.bikeCategory}

                                        Bike Description: {bike.bikeDescription}

                                        Location:
                                        {bike.location.address}, {bike.location.city}, {bike.location.state}, {bike.location.zip}

                                        <button style={{marginLeft: "10px"}} onClick={() => this.viewBike(bike.bikeId)} className='btn btn-primary'>View</button>
                                         <button>Rent</button>

                    )

                }

        );
    }
}

export default ListBikes;

I tried console.log(this.state.bike). It gave me an array that basically contains everything I need. But when I try to access them I get undefined. How do I access the bikeLocation and bikeDescription? I have added 3 files. BikeServices, ListBikes and ViewBike Components.


问:
Can I increase a number by a macro in LibreOffice Impress?
I want to make a counter with Libreoffice Impress.

Each Time I click on a rectangle, the number inside increases.

```<code>Dim Doc As Object
Dim Page As Object
Dim Rect As Object

Doc = ThisComponent
Page = Doc.drawPages.getByName("Test")
Rect = Page.getByIndex(0)

Rect.String = CInt(Rect.String) + 1
</code>```

It works everywhere except in presentation mode.

Is it possible to make it work in presentation mode ?

Body:
I want to make a counter with Libreoffice Impress.

Each Time I click on a rectangle, the number inside increases.

Dim Doc As Object
Dim Page As Object
Dim Rect As Object

Doc = ThisComponent
Page = Doc.drawPages.getByName("Test")
Rect = Page.getByIndex(0)

Rect.String = CInt(Rect.String) + 1

It works everywhere except in presentation mode.

Is it possible to make it work in presentation mode ?