问:
Kotlin-Android First App Unresolved Reference TextView Button etc
I'm new to Android & Kotlin development.

I wanted to get started with a simple "Hello World", but am already running into problems.

I added a Textview to my MainActivity and want to set an onClick listener to change the text of a TextView I dragged into the activity.

The compiler is now complaining that 'TextView' is an unresolved reference (it does the same with Buttons etc.).

I then added a kotlinx import as suggested by a website, but this fails to solve anything. Code sample below, anything with an asterisk as a line comment was added by me.

```<code>package com.example.my.mynewapp

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.fragmentX.view.* // *

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val textView: TextView = findViewById(R.id.testView) as TextView  // *
        textView.setOnClickListener { // *
            textView.text = "You clicked me! You flipping clicked me!" // *
        } // *

    }
}
</code>```

Would anyone have any idea what's going on?

答:
It should have been automatically imported, but there should be

```<code>import android.widget.<WhateverIsMissing>
</code>```

Replace WhateverIsMissing with the reference that is unresolved

Body:
I'm new to Android & Kotlin development.

I wanted to get started with a simple "Hello World", but am already running into problems.

I added a Textview to my MainActivity and want to set an onClick listener to change the text of a TextView I dragged into the activity.

The compiler is now complaining that 'TextView' is an unresolved reference (it does the same with Buttons etc.).

I then added a kotlinx import as suggested by a website, but this fails to solve anything. Code sample below, anything with an asterisk as a line comment was added by me.

package com.example.my.mynewapp

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.fragmentX.view.* // *

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val textView: TextView = findViewById(R.id.testView) as TextView  // *
        textView.setOnClickListener { // *
            textView.text = "You clicked me! You flipping clicked me!" // *
        } // *

    }
}

Would anyone have any idea what's going on?

Body:
It should have been automatically imported, but there should be

import android.widget.<WhateverIsMissing>

Replace WhateverIsMissing with the reference that is unresolved


来源: stackexchange

问:
When i try to read file from s3 bucket error occurs, what is the problem?
```<code>Py4JJavaError: An error occurred while calling o40.csv.
: java.io.IOException: The s3n:// client to Amazon S3 is no longer available: please migrate to the s3a:// client
    at org.apache.hadoop.fs.s3native.NativeS3FileSystem.initialize(NativeS3FileSystem.java:82)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2669)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:94)
    at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2703)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2685)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:373)
    at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$org$apache$spark$sql$execution$datasources$DataSource$$checkAndGlobPathIfNecessary$1.apply(DataSource.scala:547)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$org$apache$spark$sql$execution$datasources$DataSource$$checkAndGlobPathIfNecessary$1.apply(DataSource.scala:545)
    at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
    at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
    at scala.collection.immutable.List.flatMap(List.scala:355)
    at org.apache.spark.sql.execution.datasources.DataSource.org$apache$spark$sql$execution$datasources$DataSource$$checkAndGlobPathIfNecessary(DataSource.scala:545)
    at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:359)
    at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:223)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:211)
    at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:619)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)
</code>```

Can anyone help me about this error type?
My codes like this:

```<code>spark._jsc.hadoopConfiguration().set("fs.s3a.awsAccessKeyId", accessKeyId)
spark._jsc.hadoopConfiguration().set("fs.s3a.awsSecretAccessKey", secretAccessKey)
</code>```

答: If you are using pr passing  AWS S3 bucket URL with prefix as s3:// or s3n:// then replace it with s3a:// because Spark uses org.apache.hadoop.fs.s3a.S3AFileSystem for S3 communications and you also might have to include hadoop-aws 2.7.1 JAR on to your classpath

ContentLicense: CC BY-SA 4.0

Body:
Py4JJavaError: An error occurred while calling o40.csv.
: java.io.IOException: The s3n:// client to Amazon S3 is no longer available: please migrate to the s3a:// client
    at org.apache.hadoop.fs.s3native.NativeS3FileSystem.initialize(NativeS3FileSystem.java:82)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2669)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:94)
    at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2703)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2685)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:373)
    at org.apache.hadoop.fs.Path.getFileSystem(Path.java:295)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$org$apache$spark$sql$execution$datasources$DataSource$$checkAndGlobPathIfNecessary$1.apply(DataSource.scala:547)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$org$apache$spark$sql$execution$datasources$DataSource$$checkAndGlobPathIfNecessary$1.apply(DataSource.scala:545)
    at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
    at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
    at scala.collection.immutable.List.foreach(List.scala:392)
    at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
    at scala.collection.immutable.List.flatMap(List.scala:355)
    at org.apache.spark.sql.execution.datasources.DataSource.org$apache$spark$sql$execution$datasources$DataSource$$checkAndGlobPathIfNecessary(DataSource.scala:545)
    at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:359)
    at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:223)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:211)
    at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:619)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:238)
    at java.lang.Thread.run(Thread.java:748)

Can anyone help me about this error type?
My codes like this:

spark._jsc.hadoopConfiguration().set("fs.s3a.awsAccessKeyId", accessKeyId)
spark._jsc.hadoopConfiguration().set("fs.s3a.awsSecretAccessKey", secretAccessKey)


问:
Setting Content Security Policy in Apache web server
We had a penetration testing and one of the findings were:

"Missing Content-Security-Policy HTTP response header"

We did a bit of research and found out how to set this in the web servers httpd.conf file. The problem is we don't know what to include exactly. Our web app doesn't really have any dependencies to external sites like googleapis or any CDN or external images on the net. So, we aren't really sure what to put.

Below is a sample but this has dependencies to some google links.

```<code><Location "/CompanyXYZ/">
Header always append X-Frame-Options deny
Header always set Content-Security-Policy "default-src 'self' data: blob: *.google.com *.gstatic.com; style-src 'self' 'unsafe-inline' *.google.com *.googleapis.com; script-src 'self' 'unsafe-inline' *.googleapis.com *.google.com;"
</Location>
</code>```

What if we have none of those dependencies? how should we set ours?

答:
One thing to clear up here is that policy doesn't "have dependencies" on the google links. It's a policy that is allowing the user's web browser to load content from those domain when they load your app. The CSP policy is denying the user's browser permission to load anything else.

A lack of a CSP policy should not be considered a vulnerability. I would hope that is rated as a 'note' or very low risk issue. Implementing CSP is something you do need to test since you can easily break functionality on your site/app. I would just be sure you're not rushed into this to satisfy a vendor.

CSP is something that should be done more carefully than this, you need to carefully evaluate all the content loaded/included by your app. Then it would be prudent to implement a policy in report-only mode where you can see violations that would have violated the policy. This way you can find problems without the risk of breaking functionality to users.

This is its own can of worms since you need a reporting listener (there are platforms available online for this).

If you do choose to wing it and just implement the policy

If you don't rely on the resources from those domains you safely omit them. They are left in there as examples since so many sites include content from those CDNs.

One last option is to just include a very minimal policy that basically does nothing. Most pentest vendors are just checking a box to see if exists.

You could try the following to check the box (warning this does nothing):

```<code>Content-Security-Policy: "default-src *"
</code>```

Body:
We had a penetration testing and one of the findings were:

"Missing Content-Security-Policy HTTP response header"

We did a bit of research and found out how to set this in the web servers httpd.conf file. The problem is we don't know what to include exactly. Our web app doesn't really have any dependencies to external sites like googleapis or any CDN or external images on the net. So, we aren't really sure what to put.

Below is a sample but this has dependencies to some google links.

<Location "/CompanyXYZ/">
Header always append X-Frame-Options deny
Header always set Content-Security-Policy "default-src 'self' data: blob: *.google.com *.gstatic.com; style-src 'self' 'unsafe-inline' *.google.com *.googleapis.com; script-src 'self' 'unsafe-inline' *.googleapis.com *.google.com;"
</Location>

What if we have none of those dependencies? how should we set ours?

Body:
One thing to clear up here is that policy doesn't "have dependencies" on the google links. It's a policy that is allowing the user's web browser to load content from those domain when they load your app. The CSP policy is denying the user's browser permission to load anything else.

A lack of a CSP policy should not be considered a vulnerability. I would hope that is rated as a 'note' or very low risk issue. Implementing CSP is something you do need to test since you can easily break functionality on your site/app. I would just be sure you're not rushed into this to satisfy a vendor.

CSP is something that should be done more carefully than this, you need to carefully evaluate all the content loaded/included by your app. Then it would be prudent to implement a policy in report-only mode where you can see violations that would have violated the policy. This way you can find problems without the risk of breaking functionality to users.

This is its own can of worms since you need a reporting listener (there are platforms available online for this).

If you do choose to wing it and just implement the policy

If you don't rely on the resources from those domains you safely omit them. They are left in there as examples since so many sites include content from those CDNs.

One last option is to just include a very minimal policy that basically does nothing. Most pentest vendors are just checking a box to see if exists.

You could try the following to check the box (warning this does nothing):

Content-Security-Policy: "default-src *"


问:
Why does my javascript object get faster and faster?
So, I'm trying to code a game where there is a ball that chases the player, and currently I'm coding the player physics. For some reason, as the player walks back and forth, it gets faster and faster, but I can't figure out why.  I think it might have something to do with me multiplying the physicsX variable by .85, but I can't figure out how that would affect it. Here is my code-

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var baseX = 100;
var baseY = 50;
var physicsY = 0;
var physicsX = 0;

function coronavirus() {
  ctx.beginPath();
  ctx.fillStyle = "blue";
  ctx.arc(50, 50, 5, 0, 2 * Math.PI, false);
  ctx.fill();
}

function ground() {
  ctx.beginPath();
  ctx.fillStyle = "green";
  ctx.rect(0, 140, screen.width, 10);
  ctx.fill();
}

function person() {
  ctx.beginPath();
  ctx.strokeStyle = "black";
  ctx.arc(baseX, baseY, 5, 0, 2 * Math.PI, false); //head
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 5); //body
  ctx.lineTo(baseX, baseY + 20);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //left leg
  ctx.lineTo(baseX - 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //right leg
  ctx.lineTo(baseX + 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX - 5, baseY + 10); //arms
  ctx.lineTo(baseX + 5, baseY + 10);
  ctx.stroke();
}

function personHitbox() {
  ctx.beginPath();
  ctx.strokeStyle = "black"
  ctx.rect(baseX - 5, baseY - 5, 10, 32);
  ctx.stroke();
}

function personTouchingGround() {
  var personHitbox = {y: baseY - 5, height: 32}
  var ground = {y: 140}
    if (personHitbox.y + personHitbox.height < ground.y) {
    touchingGround = false;
} else {
  touchingGround = true;
}
}

function personMoving() {
  if (touchingGround == false) {
    physicsY++;
    baseY = baseY + physicsY;
  }
  physicsX = 0;
  window.addEventListener('keydown', (e) => {
  if (e.key == "ArrowRight") {
    physicsX = physicsX + 0.001;
  }
  if (e.key == "ArrowLeft") {
    physicsX = physicsX - 0.001;
  }
  physicsX = physicsX * 0.85
  baseX = baseX + physicsX;
});

}
function gameloop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  new coronavirus();
  new person();
  new personHitbox();
  new personTouchingGround();
  new personMoving();
  new ground();
  requestAnimationFrame(gameloop);
}
gameloop();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>canvas {
  width: 100%;
  height: 100%;
  margin: 0%;
}</code>```

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />

    <canvas id="canvas"></canvas>

```

答:
Two issues:

You keep adding to physicsX, so the amount of distance it moves keeps increasing.  Just keep physicsX constant to move the same amount.  (Actually doesn't, because every animation frame you are setting PhysicsX = 0, but the logic is wrong.  When you fix the real error, this causes the unit not to move properly.)

Move the 'keydown' event binding outside personMoving() so it only executes once.  Your event listener binding is being executed every time you call personMoving(), so it is binding 'key' event over and over again, and then you get 'key' event triggered more and more over time.

So after 100 animation frames each keypress will trigger the baseX and PhysicsX adding code 100 times.

You should only bind the key event once.

I've also used Math.abs and *-1 for right left movement.

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var baseX = 100;
var baseY = 50;
var physicsY = 0;
var physicsX = 0;

function coronavirus() {
  ctx.beginPath();
  ctx.fillStyle = "blue";
  ctx.arc(50, 50, 5, 0, 2 * Math.PI, false);
  ctx.fill();
}

function ground() {
  ctx.beginPath();
  ctx.fillStyle = "green";
  ctx.rect(0, 140, screen.width, 10);
  ctx.fill();
}

function person() {
  ctx.beginPath();
  ctx.strokeStyle = "black";
  ctx.arc(baseX, baseY, 5, 0, 2 * Math.PI, false); //head
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 5); //body
  ctx.lineTo(baseX, baseY + 20);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //left leg
  ctx.lineTo(baseX - 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //right leg
  ctx.lineTo(baseX + 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX - 5, baseY + 10); //arms
  ctx.lineTo(baseX + 5, baseY + 10);
  ctx.stroke();
}

function personHitbox() {
  ctx.beginPath();
  ctx.strokeStyle = "black"
  ctx.rect(baseX - 5, baseY - 5, 10, 32);
  ctx.stroke();
}

function personTouchingGround() {
  var personHitbox = {
    y: baseY - 5,
    height: 32
  }
  var ground = {
    y: 140
  }
  if (personHitbox.y + personHitbox.height < ground.y) {
    touchingGround = false;
  } else {
    touchingGround = true;
  }
}

function personMoving() {
  if (touchingGround == false) {
    physicsY++;
    baseY = baseY + physicsY;
  }

}

  physicsX = 10;
  window.addEventListener('keydown', (e) => {
    if (e.key == "ArrowRight") {
      physicsX = Math.abs(physicsX);
    }
    if (e.key == "ArrowLeft") {
      physicsX = Math.abs(physicsX)*-1;
    }
//    physicsX = physicsX * 0.85
    baseX = baseX + physicsX;
//    put this console.log in your original code to see what I mean
//    console.log(baseX)
  });

function gameloop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  new coronavirus();
  new person();
  new personHitbox();
  new personTouchingGround();
  new personMoving();
  new ground();
  requestAnimationFrame(gameloop);
}
gameloop();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas"></canvas></code>```

Body:
So, I'm trying to code a game where there is a ball that chases the player, and currently I'm coding the player physics. For some reason, as the player walks back and forth, it gets faster and faster, but I can't figure out why.  I think it might have something to do with me multiplying the physicsX variable by .85, but I can't figure out how that would affect it. Here is my code-

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var baseX = 100;
var baseY = 50;
var physicsY = 0;
var physicsX = 0;

function coronavirus() {
  ctx.beginPath();
  ctx.fillStyle = "blue";
  ctx.arc(50, 50, 5, 0, 2 * Math.PI, false);
  ctx.fill();
}

function ground() {
  ctx.beginPath();
  ctx.fillStyle = "green";
  ctx.rect(0, 140, screen.width, 10);
  ctx.fill();
}

function person() {
  ctx.beginPath();
  ctx.strokeStyle = "black";
  ctx.arc(baseX, baseY, 5, 0, 2 * Math.PI, false); //head
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 5); //body
  ctx.lineTo(baseX, baseY + 20);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //left leg
  ctx.lineTo(baseX - 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //right leg
  ctx.lineTo(baseX + 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX - 5, baseY + 10); //arms
  ctx.lineTo(baseX + 5, baseY + 10);
  ctx.stroke();
}

function personHitbox() {
  ctx.beginPath();
  ctx.strokeStyle = "black"
  ctx.rect(baseX - 5, baseY - 5, 10, 32);
  ctx.stroke();
}

function personTouchingGround() {
  var personHitbox = {y: baseY - 5, height: 32}
  var ground = {y: 140}
    if (personHitbox.y + personHitbox.height < ground.y) {
    touchingGround = false;
} else {
  touchingGround = true;
}
}

function personMoving() {
  if (touchingGround == false) {
    physicsY++;
    baseY = baseY + physicsY;
  }
  physicsX = 0;
  window.addEventListener('keydown', (e) => {
  if (e.key == "ArrowRight") {
    physicsX = physicsX + 0.001;
  }
  if (e.key == "ArrowLeft") {
    physicsX = physicsX - 0.001;
  }
  physicsX = physicsX * 0.85
  baseX = baseX + physicsX;
});

}
function gameloop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  new coronavirus();
  new person();
  new personHitbox();
  new personTouchingGround();
  new personMoving();
  new ground();
  requestAnimationFrame(gameloop);
}
gameloop();

canvas {
  width: 100%;
  height: 100%;
  margin: 0%;
}

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />

    <canvas id="canvas"></canvas>

Body:
Two issues:

You keep adding to physicsX, so the amount of distance it moves keeps increasing.  Just keep physicsX constant to move the same amount.  (Actually doesn't, because every animation frame you are setting PhysicsX = 0, but the logic is wrong.  When you fix the real error, this causes the unit not to move properly.)

Move the 'keydown' event binding outside personMoving() so it only executes once.  Your event listener binding is being executed every time you call personMoving(), so it is binding 'key' event over and over again, and then you get 'key' event triggered more and more over time.

So after 100 animation frames each keypress will trigger the baseX and PhysicsX adding code 100 times.

You should only bind the key event once.

I've also used Math.abs and *-1 for right left movement.

var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
var baseX = 100;
var baseY = 50;
var physicsY = 0;
var physicsX = 0;

function coronavirus() {
  ctx.beginPath();
  ctx.fillStyle = "blue";
  ctx.arc(50, 50, 5, 0, 2 * Math.PI, false);
  ctx.fill();
}

function ground() {
  ctx.beginPath();
  ctx.fillStyle = "green";
  ctx.rect(0, 140, screen.width, 10);
  ctx.fill();
}

function person() {
  ctx.beginPath();
  ctx.strokeStyle = "black";
  ctx.arc(baseX, baseY, 5, 0, 2 * Math.PI, false); //head
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 5); //body
  ctx.lineTo(baseX, baseY + 20);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //left leg
  ctx.lineTo(baseX - 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX, baseY + 20); //right leg
  ctx.lineTo(baseX + 3, baseY + 27);
  ctx.stroke();
  ctx.moveTo(baseX - 5, baseY + 10); //arms
  ctx.lineTo(baseX + 5, baseY + 10);
  ctx.stroke();
}

function personHitbox() {
  ctx.beginPath();
  ctx.strokeStyle = "black"
  ctx.rect(baseX - 5, baseY - 5, 10, 32);
  ctx.stroke();
}

function personTouchingGround() {
  var personHitbox = {
    y: baseY - 5,
    height: 32
  }
  var ground = {
    y: 140
  }
  if (personHitbox.y + personHitbox.height < ground.y) {
    touchingGround = false;
  } else {
    touchingGround = true;
  }
}

function personMoving() {
  if (touchingGround == false) {
    physicsY++;
    baseY = baseY + physicsY;
  }

}

  physicsX = 10;
  window.addEventListener('keydown', (e) => {
    if (e.key == "ArrowRight") {
      physicsX = Math.abs(physicsX);
    }
    if (e.key == "ArrowLeft") {
      physicsX = Math.abs(physicsX)*-1;
    }
//    physicsX = physicsX * 0.85
    baseX = baseX + physicsX;
//    put this console.log in your original code to see what I mean
//    console.log(baseX)
  });

function gameloop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  new coronavirus();
  new person();
  new personHitbox();
  new personTouchingGround();
  new personMoving();
  new ground();
  requestAnimationFrame(gameloop);
}
gameloop();

<canvas id="canvas"></canvas>


问:
How to handle null while comparing maps using streams - Java?
I have 2 data structures with values like:

```<code>List<Map<String,String>> customerDirectory
</code>```

```<code>[{NAME=ALEX BENSON, PHONE=012-12342, ADDRESS=123 MAIN ST, CITY=QUEENS, STATE=NY},
 {NAME=ZOYE ABEL, PHONE=012-12445, ADDRESS=123 WATERSIDE, CITY=WINDSOR, STATE=CT}]
</code>```

and

```<code>Map<String,String> customerInfo
</code>```

```<code>{NAME=ALEX BENSON, PHONE=012-12342, ADDRESS=123 MAIN ST}
</code>```

I am trying to iterate through the customerDirectory to find if customerInfo has exact match in values for the keys - "NAME","PHONE","ADDRESS" so that I could find if the record is a duplicate.

So I have come up with:

```<code>List<String> compareKeys = Arrays.asList("NAME","PHONE","ADDRESS");

Function<Map<String,String>, String> getVal = mp -> compareKeys.stream().map(mp::get).map(String::trim).collect(Collectors.joining());

BiPredicate<Map<String,String>, Map<String,String>> checkDup = (mp1,mp2) -> getVal.apply(mp1).equals(getVal.apply(mp2));

boolean anyMatch = customerDirectory.stream().anyMatch(customer-> checkDup.test(customerInfo, customer));
</code>```

But the customerInfo map can have value for ADDRESS as null for which I have tried:

```<code>BiFunction<Map<String, String>, String, String> handleNull = (mp, key) -> mp.get(key) == null ? " " : mp.get(key);
</code>```

and I have used it in :

```<code>Function<Map<String,String>, String> getVal = mp -> compareKeys.stream().map(key->handleNull.apply(mp,key)).map(mp::get).map(String::trim).collect(Collectors.joining());
</code>```

But I still end up getting NullPointerException which means I am missing the exact flow probably.
Is there a better way to handle null values here?

答:
You can do it in a better way I think. </p>

```<code>boolean anyMatch = customerDirectory.stream()
         .anyMatch(m -> m.entrySet().stream()
           .filter(entry -> compareKeys.contains(entry.getKey()))
           .allMatch(entry -> entry.getValue().equals(customerInfo.get(entry.getKey()))));
</code>```

<p>or even more concise: </p>

```<code> boolean anyMatch =
            customerDirectory.stream()
                   .anyMatch(m -> compareKeys.stream()
                            .allMatch(key -> m.get(key).equals(customerInfo.get(key))));
</code>```

Body:
I have 2 data structures with values like:

List<Map<String,String>> customerDirectory

[{NAME=ALEX BENSON, PHONE=012-12342, ADDRESS=123 MAIN ST, CITY=QUEENS, STATE=NY},
 {NAME=ZOYE ABEL, PHONE=012-12445, ADDRESS=123 WATERSIDE, CITY=WINDSOR, STATE=CT}]

and

Map<String,String> customerInfo

{NAME=ALEX BENSON, PHONE=012-12342, ADDRESS=123 MAIN ST}

I am trying to iterate through the customerDirectory to find if customerInfo has exact match in values for the keys - "NAME","PHONE","ADDRESS" so that I could find if the record is a duplicate.

So I have come up with:

List<String> compareKeys = Arrays.asList("NAME","PHONE","ADDRESS");

Function<Map<String,String>, String> getVal = mp -> compareKeys.stream().map(mp::get).map(String::trim).collect(Collectors.joining());

BiPredicate<Map<String,String>, Map<String,String>> checkDup = (mp1,mp2) -> getVal.apply(mp1).equals(getVal.apply(mp2));

boolean anyMatch = customerDirectory.stream().anyMatch(customer-> checkDup.test(customerInfo, customer));

But the customerInfo map can have value for ADDRESS as null for which I have tried:

BiFunction<Map<String, String>, String, String> handleNull = (mp, key) -> mp.get(key) == null ? " " : mp.get(key);

and I have used it in :

Function<Map<String,String>, String> getVal = mp -> compareKeys.stream().map(key->handleNull.apply(mp,key)).map(mp::get).map(String::trim).collect(Collectors.joining());

But I still end up getting NullPointerException which means I am missing the exact flow probably.
Is there a better way to handle null values here?

Body:
You can do it in a better way I think.

boolean anyMatch = customerDirectory.stream()
         .anyMatch(m -> m.entrySet().stream()
           .filter(entry -> compareKeys.contains(entry.getKey()))
           .allMatch(entry -> entry.getValue().equals(customerInfo.get(entry.getKey()))));

or even more concise:

 boolean anyMatch =
            customerDirectory.stream()
                   .anyMatch(m -> compareKeys.stream()
                            .allMatch(key -> m.get(key).equals(customerInfo.get(key))));


问:
How to show \n \t characters on vscode
I'm debugging a laravel app and I need to know if any of these characters is present, before vs code did show them, now it does not:

is there any way to enable this again?

EDIT: I'm using XDebug + vscode

答:
It seems Visual studio code "delegated" this escape to the debugger, I have spoken to the developer of xDebug and they told me they aren't escaping anything on their side, it seems a problem of vs code and this should be an option for the end-user not the debugger.

there's no current way of doing this atm on this date

Title: How to show \n \t characters on vscode


问:
func<bool> events and a headache
I have a boolean event, and I am trying to call each subscriber individually so I can return false if even one subscriber returns false. So far, my attempts have left me with nothing but a brain that is tired, wants to cry, and eat a pop tart(then cry some more).

For the function that actually calls the event, I have been doing this:

```<code>foreach (Delegate sub in SomeBooleanEvent.GetInvocationList())
             {
                 someBool = sub;
                 //blah blah blah code blah blah blah
                 }
             }
</code>```

The error I get is:

CS0029: Cannot implicitly convert type 'System.Delegate' to 'bool'

I am so confused...help me...please...

Edit:
After finally managing to muster the willpower to tackle this, I have found using func<bool> instead of Delegate seems to partially work.

However, I now have a new problem. When I call the event, only one subscriber is present/called?

答:
I finally figured out what was going on.
For those that may find this useful, func<bool> should be used instead of Delegate(the code I made before my last edit didn't call subscriber because I had accidentally deleted a code block that would have called each method).

By simply doing

```<code>public event Func<bool> onAWildBooleanEvent;

public bool? AWildBooleanEVent(){
            bool? result = null;
            if(daBool!=null){
                foreach (Func<bool> sub in onAWildBooleanEvent.GetInvocationList())
                {
                    if(result == null){
                        result = sub();
                    }else{
                        if(sub()!=result){
                            result= false;
                        }
                    }

                }
                return AoNBool;
            }
            return null;
        }
</code>```

This should work for other types as well as long as you have no need for event handlers and event args. Just make sure you set the func to the appropriate type. Also, if you want all events to trigger, make sure to call them. Otherwise, they will not be notified of the event.

Title: func<bool> events and a headache

Body:
I have a boolean event, and I am trying to call each subscriber individually so I can return false if even one subscriber returns false. So far, my attempts have left me with nothing but a brain that is tired, wants to cry, and eat a pop tart(then cry some more).

For the function that actually calls the event, I have been doing this:

foreach (Delegate sub in SomeBooleanEvent.GetInvocationList())
             {
                 someBool = sub;
                 //blah blah blah code blah blah blah
                 }
             }

The error I get is:

CS0029: Cannot implicitly convert type 'System.Delegate' to 'bool'

I am so confused...help me...please...

Edit:
After finally managing to muster the willpower to tackle this, I have found using func<bool> instead of Delegate seems to partially work.

However, I now have a new problem. When I call the event, only one subscriber is present/called?

Body:
I finally figured out what was going on.
For those that may find this useful, func<bool> should be used instead of Delegate(the code I made before my last edit didn't call subscriber because I had accidentally deleted a code block that would have called each method).

By simply doing

public event Func<bool> onAWildBooleanEvent;

public bool? AWildBooleanEVent(){
            bool? result = null;
            if(daBool!=null){
                foreach (Func<bool> sub in onAWildBooleanEvent.GetInvocationList())
                {
                    if(result == null){
                        result = sub();
                    }else{
                        if(sub()!=result){
                            result= false;
                        }
                    }

                }
                return AoNBool;
            }
            return null;
        }

This should work for other types as well as long as you have no need for event handlers and event args. Just make sure you set the func to the appropriate type. Also, if you want all events to trigger, make sure to call them. Otherwise, they will not be notified of the event.


问:
I get duplicate results with foreach
I have this foreach so I want the visitagent value received for each element to check if it exists in the database, well then in block_viste_agent I have the function that blocks the visitagent value, the problem is that when I am going to block user via a value by checkbox then if there are others it adds them to me again there is also a detail that with characters like numbers I don't get them duplicates it work good, so I have the user agent and if I want to block a new one and there are 3 user agents already blocked, then it comes back and duplicates the ones that are blocked only what are blocked the user agent that I checkbox doesn't duplicates, what is wrong with my code?

foreach ($_POST['visitagent'] as $agent_id) {
    $checkagent = $wpdb->query(
        "SELECT *
        FROM {$wpdb->prefix}lcl_user_agent
        WHERE user_agent = '$agent_id'"
    );

    if ($checkagent <= 0) {
        $this->block_viste_agent(absint($agent_id), true);
    }
}
```

I looked for this question but I don't know my code is diferrent
Getting duplicated results in foreach loop

答:
Replace this code.

```<code>if ($checkagent <= 0) {
    $this->block_viste_agent(absint($agent_id), true);
}
</code>```

this one

```<code>if (!$checkagent->rowCount()) {
    $this->block_viste_agent(absint($agent_id), true);
}
</code>```

Title: I get duplicate results with foreach

Body:
I have this foreach so I want the visitagent value received for each element to check if it exists in the database, well then in block_viste_agent I have the function that blocks the visitagent value, the problem is that when I am going to block user via a value by checkbox then if there are others it adds them to me again there is also a detail that with characters like numbers I don't get them duplicates it work good, so I have the user agent and if I want to block a new one and there are 3 user agents already blocked, then it comes back and duplicates the ones that are blocked only what are blocked the user agent that I checkbox doesn't duplicates, what is wrong with my code?

foreach ($_POST['visitagent'] as $agent_id) {
    $checkagent = $wpdb->query(
        "SELECT *
        FROM {$wpdb->prefix}lcl_user_agent
        WHERE user_agent = '$agent_id'"
    );

    if ($checkagent <= 0) {
        $this->block_viste_agent(absint($agent_id), true);
    }
}

I looked for this question but I don't know my code is diferrent
Getting duplicated results in foreach loop

Body:
Replace this code.

if ($checkagent <= 0) {
    $this->block_viste_agent(absint($agent_id), true);
}

this one

if (!$checkagent->rowCount()) {
    $this->block_viste_agent(absint($agent_id), true);
}


问:
Oracle: Move column to new table, eliminate non-unique rows remaining in original table while maintaining foreign relationship between two tables
I have a table like the following:

Table 1: Person_Favorite_Food

```<code>id name   address          favorite_food
------------------------------------------
1  Dave   123 Cherry Ln    Pizza
2  Dave   123 Cherry Ln    Cheeseburger
3  Dave   456 Peachtree St Ice cream
4  Cindy  789 Grove Rd     Pizza
</code>```

id - primary key

unique key constraint on the following columns: name, address and food

Since each person can have more than one favorite food item I'd like to split Table 1 into two tables like the following:

Table 2: Person

```<code>id name   address
--------------------------
1  Dave   123 Cherry Ln
3  Dave   456 Peachtree St
4  Cindy  789 Grove Rd
</code>```

Table 3: Person_Favorite_Food

```<code>person_id  favorite_food
-----------------
1          Pizza
1          Cheeseburger
3          Ice cream
4          Pizza
</code>```

How would I go about doing this in Oracle?

Note: In the original table Rows 1 and 2 represent favorite food for the same person so the favorite food entries in the Person_Favorite_Food table will need to have the same identifier for both of those entries although the identifiers are different in the initial table.

答:
You can use:

```<code>create table new1 as
    select distinct id, name, address
    from t;

create table new2 as
    select id, favorite_food
    from t;
</code>```

I would recommend create two new tables and not trying to morph the existing table into one of the new ones.

Body:
I have a table like the following:

Table 1: Person_Favorite_Food

id name   address          favorite_food
------------------------------------------
1  Dave   123 Cherry Ln    Pizza
2  Dave   123 Cherry Ln    Cheeseburger
3  Dave   456 Peachtree St Ice cream
4  Cindy  789 Grove Rd     Pizza

id - primary key

unique key constraint on the following columns: name, address and food

Since each person can have more than one favorite food item I'd like to split Table 1 into two tables like the following:

Table 2: Person

id name   address
--------------------------
1  Dave   123 Cherry Ln
3  Dave   456 Peachtree St
4  Cindy  789 Grove Rd

Table 3: Person_Favorite_Food

person_id  favorite_food
-----------------
1          Pizza
1          Cheeseburger
3          Ice cream
4          Pizza

How would I go about doing this in Oracle?

Note: In the original table Rows 1 and 2 represent favorite food for the same person so the favorite food entries in the Person_Favorite_Food table will need to have the same identifier for both of those entries although the identifiers are different in the initial table.

Body:
You can use:

create table new1 as
    select distinct id, name, address
    from t;

create table new2 as
    select id, favorite_food
    from t;

I would recommend create two new tables and not trying to morph the existing table into one of the new ones.


问:
Drawing Bowling Pins (pyramid) with Recursion in Ada
I know this is pushing the good will of the community by presenting my least elaborate work expecting someone to come and save me but I simply have no choice with nothing to lose. I've gone through packets, files, types, flags and boxes the last few weeks but I haven't covered much of recursion. Especially not drawing with recursion. My exam is in roughly one week and I hope this is ample time to repeat and learn simple recursion tricks like that of drawing bowling pins or other patterns:

```<code>I I I I I
 I I I I
  I I I
   I I
    I
n = 5
</code>```

The problem I have with recursion is that I don't quite get it. How are you supposed to approach a problem like drawing pins like this using recursion?

The closest I've come is

```<code>I I I
I I
I
n = 3
</code>```

and that's using

THIS CODE NOW WORKS

```<code>with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure pyramidchaser is

   subtype X_Type is Integer range 0..30;
   X: X_Type;
   Indent : Integer := 0;

   procedure Numbergrabber (X : out Integer) is
   begin

      Put("Enter a number: ");
      Get(X);
      Skip_Line;
   end Numbergrabber;

   procedure PrintSpaces(I : in Integer) is
   begin
      if I in X_Type then
      Put(" ");
      else
     return;
      end if;

      PrintSpaces(I - 1);
   end Printspaces;

   procedure PrintPins(i, n: in Integer) is
   begin
      if i >= n then
     return;
      end if;

    Put('I');
    Put(' ');

    PrintPins(i + 1, n);
    end Printpins;

   function Pins (X, Indent: in Integer) return Integer is

      Printed : Integer;

   begin

      Printed:= 0;
      if X > 0 then
     PrintSpaces(Indent);
     PrintPins(0, X);
     New_Line;

     Printed := X + Pins(X - 1, Indent + 1);
      end if;
      return Printed;

   end Pins;

   Bowlingpins : Integer;

begin

   Numbergrabber(X);
   Bowlingpins:= Pins(X, Indent);

end pyramidchaser;

</code>```

but with that I throw in a sum I dont really need just to kick off the recursive part which I dont really know why I do except it seems to be needed to be there. I experimented with code from a completely different assignment, thats why it looks the way it does. I know mod 2 will grant me too many new lines but at least it was an approach to finding heights to the pyramid. I understand the real approach is something similar to N+1 as with each step of the growing pyramid a new line is needed, but I dont know how to implement it.

I don't expect anyone to present a complete code but I hope somebody can clue me in on how to think on the way towards finding a solution.

I can still pass the exam without knowing recursion as its typically 2 assignments where one is and one isnt recursion and you need to pass one or the other, but given that I have some time I thought Id give it a chance.

As always, immensely thankful for anyone fighting the good fight!

Seeing this post gathered some attention Id like to expand the pyramid to one a little more complex:

THE PYRAMID PROBLEM 2

hope someone looks at it. I didnt expect so many good answers, I thought why not throw all I have out there.

```<code>Level 1
|=|

Level 2
|===|
||=||
|===|

Level 3

|=====|
||===||
|||=|||
||===||
|=====|

it needs to be figured out recursively. so some way it has to build both upwards and downwards from the center.
</code>```

To clarify Im studying for an exam and surely so are many others whom would be thankful for code to sink their teeth in. Maybe theres an easy way to apply what Tama built in terms of bowling pin lines in pyramid walls?

答:
I don't program in Ada (it looks like a strange Pascal to me), but there is an obvious algorithmic problem in your Pins function.

Basically, if you want to print a pyramid whose base is N down to the very bottom where base is 1, you would need to do something like this (sorry for crude pascalization of the code).

```<code>procedure PrintPins(i, n: Integer)
begin
    if i >= n then return;

    Ada.Text_IO.Put('I'); // Print pin
    Ada.Text_IO.Put(' '); // Print space

    PrintPins(i + 1, n);  // Next iteration
end;

function Pins(x, indent: Integer): Integer
   printed: Integer;
begin
    printed := 0;
    if x > 0 then
       PrintSpaces(indent); // Print indentation pretty much using the same artificial approach as by printing pins
       PrintPins(0, x);
       (*Print new line here*)

       (*Now go down the next level and print another
       row*)
       printed := x + Pins(x - 1, indent + 1);
    end;
    return printed;
end
</code>```

P.S. You don't need a specific function to count the number of printed pins here. It's just a Gauss sequence sum of the range 1..N, which is given by N(N + 1)/2

Body:
I know this is pushing the good will of the community by presenting my least elaborate work expecting someone to come and save me but I simply have no choice with nothing to lose. I've gone through packets, files, types, flags and boxes the last few weeks but I haven't covered much of recursion. Especially not drawing with recursion. My exam is in roughly one week and I hope this is ample time to repeat and learn simple recursion tricks like that of drawing bowling pins or other patterns:

I I I I I
 I I I I
  I I I
   I I
    I
n = 5

The problem I have with recursion is that I don't quite get it. How are you supposed to approach a problem like drawing pins like this using recursion?

The closest I've come is

I I I
I I
I
n = 3

and that's using

THIS CODE NOW WORKS

with Ada.Text_IO; use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure pyramidchaser is

   subtype X_Type is Integer range 0..30;
   X: X_Type;
   Indent : Integer := 0;

   procedure Numbergrabber (X : out Integer) is
   begin

      Put("Enter a number: ");
      Get(X);
      Skip_Line;
   end Numbergrabber;

   procedure PrintSpaces(I : in Integer) is
   begin
      if I in X_Type then
      Put(" ");
      else
     return;
      end if;

      PrintSpaces(I - 1);
   end Printspaces;

   procedure PrintPins(i, n: in Integer) is
   begin
      if i >= n then
     return;
      end if;

    Put('I');
    Put(' ');

    PrintPins(i + 1, n);
    end Printpins;

   function Pins (X, Indent: in Integer) return Integer is

      Printed : Integer;

   begin

      Printed:= 0;
      if X > 0 then
     PrintSpaces(Indent);
     PrintPins(0, X);
     New_Line;

     Printed := X + Pins(X - 1, Indent + 1);
      end if;
      return Printed;

   end Pins;

   Bowlingpins : Integer;

begin

   Numbergrabber(X);
   Bowlingpins:= Pins(X, Indent);

end pyramidchaser;

but with that I throw in a sum I dont really need just to kick off the recursive part which I dont really know why I do except it seems to be needed to be there. I experimented with code from a completely different assignment, thats why it looks the way it does. I know mod 2 will grant me too many new lines but at least it was an approach to finding heights to the pyramid. I understand the real approach is something similar to N+1 as with each step of the growing pyramid a new line is needed, but I dont know how to implement it.

I don't expect anyone to present a complete code but I hope somebody can clue me in on how to think on the way towards finding a solution.

I can still pass the exam without knowing recursion as its typically 2 assignments where one is and one isnt recursion and you need to pass one or the other, but given that I have some time I thought Id give it a chance.

As always, immensely thankful for anyone fighting the good fight!

Seeing this post gathered some attention Id like to expand the pyramid to one a little more complex:

THE PYRAMID PROBLEM 2

hope someone looks at it. I didnt expect so many good answers, I thought why not throw all I have out there.

Level 1
|=|

Level 2
|===|
||=||
|===|

Level 3

|=====|
||===||
|||=|||
||===||
|=====|

it needs to be figured out recursively. so some way it has to build both upwards and downwards from the center.

To clarify Im studying for an exam and surely so are many others whom would be thankful for code to sink their teeth in. Maybe theres an easy way to apply what Tama built in terms of bowling pin lines in pyramid walls?

Body:
I don't program in Ada (it looks like a strange Pascal to me), but there is an obvious algorithmic problem in your Pins function.

Basically, if you want to print a pyramid whose base is N down to the very bottom where base is 1, you would need to do something like this (sorry for crude pascalization of the code).

procedure PrintPins(i, n: Integer)
begin
    if i >= n then return;

    Ada.Text_IO.Put('I'); // Print pin
    Ada.Text_IO.Put(' '); // Print space

    PrintPins(i + 1, n);  // Next iteration
end;

function Pins(x, indent: Integer): Integer
   printed: Integer;
begin
    printed := 0;
    if x > 0 then
       PrintSpaces(indent); // Print indentation pretty much using the same artificial approach as by printing pins
       PrintPins(0, x);
       (*Print new line here*)

       (*Now go down the next level and print another
       row*)
       printed := x + Pins(x - 1, indent + 1);
    end;
    return printed;
end

P.S. You don't need a specific function to count the number of printed pins here. It's just a Gauss sequence sum of the range 1..N, which is given by N(N + 1)/2


问:
How do i convert sympy matrix output into numpy array
Attached below is my code

```<code>import sympy as sym

k = [3,10,0.65,0.3]
x = [999, 1, 0]
SU, IN, IM= x[0], x[1], x[2]

def equation():
    dsdt = '(IM/k0) - ((IN/(IN+SU))*k1*k2*SU)'
    dindt = '((IN/(IN+SU))*k1*k2*SU) - (IN/k3)'
    dimdt = '(IN/k3) - (IM/k0)'
    return [dsdt, dindt, dimdt]

def Jacobian(v_str, f_list):
    vars = sym.symbols(v_str)
    f = sym.sympify(f_list)
    J = sym.zeros(len(f),len(vars))
    for i, fi in enumerate(f):
        for j, s in enumerate(vars):
            J[i,j] = sym.diff(fi, s)
    return J

Jacobian('k0 k1 k2 k3', equation())
</code>```

I need the return value to be in numpy.array for further processing... now im just hard coding it.
 Using jupyter notebook, python version 3.7.6

Sample output:

答:
If you want a numpy array then the following will work: flatten the matrix and pass it to array:</p>

```<code>from numpy import array
from sympy import flatten, Matrix
print(array(flatten(Matrix(equation()).jacobian(var('k0 k1 k2 k3')))))
</code>```

Body:
Attached below is my code

import sympy as sym

k = [3,10,0.65,0.3]
x = [999, 1, 0]
SU, IN, IM= x[0], x[1], x[2]

def equation():
    dsdt = '(IM/k0) - ((IN/(IN+SU))*k1*k2*SU)'
    dindt = '((IN/(IN+SU))*k1*k2*SU) - (IN/k3)'
    dimdt = '(IN/k3) - (IM/k0)'
    return [dsdt, dindt, dimdt]

def Jacobian(v_str, f_list):
    vars = sym.symbols(v_str)
    f = sym.sympify(f_list)
    J = sym.zeros(len(f),len(vars))
    for i, fi in enumerate(f):
        for j, s in enumerate(vars):
            J[i,j] = sym.diff(fi, s)
    return J

Jacobian('k0 k1 k2 k3', equation())

I need the return value to be in numpy.array for further processing... now im just hard coding it.
 Using jupyter notebook, python version 3.7.6

Sample output:

Body:
If you want a numpy array then the following will work: flatten the matrix and pass it to array:

from numpy import array
from sympy import flatten, Matrix
print(array(flatten(Matrix(equation()).jacobian(var('k0 k1 k2 k3')))))


问:
How to restrict user input to a prespecifed number of words?
My program first asks the user to specify the number of words they wish to enter and then takes them as input. Now I want the program to function correctly and restrict the user if he tries entering more words than previously specifed.

Here is my attempt:

```<code>if __name__ == '__main__':
    num_words = int(input('How many words would you like to turn backwards?  '))
    words = []
    for i in range(num_words):
        word = input('please enter string:')
        if len(word.split()) >= 2:
            print('Please only enter one word', end ='')
        else:
            words.append(word)
    print(words)
</code>```

答:
You could add a while-loop instead of your if statement, so you don't waste an iteration without receiving the right input. For example:

```<code>for i in range(num_words):
    word = input('pease enter string:')
    while len(word.split()) >= 2:
        word = input('Please only enter one word')
    words.append(word)
print(words)
</code>```

Body:
My program first asks the user to specify the number of words they wish to enter and then takes them as input. Now I want the program to function correctly and restrict the user if he tries entering more words than previously specifed.

Here is my attempt:

if __name__ == '__main__':
    num_words = int(input('How many words would you like to turn backwards?  '))
    words = []
    for i in range(num_words):
        word = input('please enter string:')
        if len(word.split()) >= 2:
            print('Please only enter one word', end ='')
        else:
            words.append(word)
    print(words)

Body:
You could add a while-loop instead of your if statement, so you don't waste an iteration without receiving the right input. For example:

for i in range(num_words):
    word = input('pease enter string:')
    while len(word.split()) >= 2:
        word = input('Please only enter one word')
    words.append(word)
print(words)


问:
SDL_LoadWAV not loading file
I want to load a wav file and play it with the following code:

```<code>if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
    std::cerr << "Could not init SDL:" << SDL_GetError() << '\n';
}
SDL_AudioSpec wavSpec;
Uint32 wavLength;
Uint8 *wavBuffer;

if(SDL_LoadWAV("sound.wav", &wavSpec, &wavBuffer, &wavLength) == NULL) {
    std::cerr << "Could not load wave:" << SDL_GetError() << '\n';
    return;
}

SDL_AudioDeviceID deviceId = SDL_OpenAudioDevice(NULL, 0, &wavSpec, NULL, 0);

int success = SDL_QueueAudio(deviceId, wavBuffer, wavLength);
SDL_PauseAudioDevice(deviceId, 0);

SDL_CloseAudioDevice(deviceId);
SDL_FreeWAV(wavBuffer);
SDL_Quit();
</code>```

However SDL_LoadWav returns NULL.
SDL_GetError just returns:

```<code>Couldn't open sounds.wav
</code>```

I already checked that the file exists but still no luck. Is there anything wrong with the code?

For debug purpose i also tryed to open the wav with ifstream like this:

```<code>std::ifstream ifs{"hitBrick.wav"};
if(!ifs) {
    std::cerr << "cannot open plattform fstream \n";
}
</code>```

and here it works no error.

What could be the issue?

EDIT:

I could find the reason for the wav not getting loaded by SDL_LoadWAV.

According to the docu of SDL_LoadWav only supported wave formats are
MS-ADPCM and IMA-ADPCM.

But my file is PCM format. So I converted the files under linux with the tool SOX: https://wiki.ubuntuusers.de/SoX/

Now I don't get any errors but also I don't hear any sounds. What could be that issue?

答:
I found the Issue while I don't hear sound.

```<code>SDL_PauseAudioDevice(deviceId, 0);
SDL_CloseAudioDevice(deviceId);
</code>```

Here I get ready to play the sound and close it directly.

With a delay in between the sound can be heared:

```<code>SDL_PauseAudioDevice(deviceId, 0);
SDL_Delay(1000);
SDL_CloseAudioDevice(deviceId);
</code>```

Title: SDL_LoadWAV not loading file

Body:
I want to load a wav file and play it with the following code:

if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO) < 0) {
    std::cerr << "Could not init SDL:" << SDL_GetError() << '\n';
}
SDL_AudioSpec wavSpec;
Uint32 wavLength;
Uint8 *wavBuffer;

if(SDL_LoadWAV("sound.wav", &wavSpec, &wavBuffer, &wavLength) == NULL) {
    std::cerr << "Could not load wave:" << SDL_GetError() << '\n';
    return;
}

SDL_AudioDeviceID deviceId = SDL_OpenAudioDevice(NULL, 0, &wavSpec, NULL, 0);

int success = SDL_QueueAudio(deviceId, wavBuffer, wavLength);
SDL_PauseAudioDevice(deviceId, 0);

SDL_CloseAudioDevice(deviceId);
SDL_FreeWAV(wavBuffer);
SDL_Quit();

However SDL_LoadWav returns NULL.
SDL_GetError just returns:

Couldn't open sounds.wav

I already checked that the file exists but still no luck. Is there anything wrong with the code?

For debug purpose i also tryed to open the wav with ifstream like this:

std::ifstream ifs{"hitBrick.wav"};
if(!ifs) {
    std::cerr << "cannot open plattform fstream \n";
}

and here it works no error.

What could be the issue?

EDIT:

I could find the reason for the wav not getting loaded by SDL_LoadWAV.

According to the docu of SDL_LoadWav only supported wave formats are
MS-ADPCM and IMA-ADPCM.

But my file is PCM format. So I converted the files under linux with the tool SOX: https://wiki.ubuntuusers.de/SoX/

Now I don't get any errors but also I don't hear any sounds. What could be that issue?

Body:
I found the Issue while I don't hear sound.

SDL_PauseAudioDevice(deviceId, 0);
SDL_CloseAudioDevice(deviceId);

Here I get ready to play the sound and close it directly.

With a delay in between the sound can be heared:

SDL_PauseAudioDevice(deviceId, 0);
SDL_Delay(1000);
SDL_CloseAudioDevice(deviceId);


问:
How to Retrieve data from selected ListBox?
In C#.Net ,I'm trying to retrieve data from selected ListBox.

Eg. First I displayed many data in ListBox that retrieved from MSSQL 2008 Database.
    When i select single data from that listbox , i want to show that selected data into textbox...
How can i do that?
I need yours answers because i'm just beginner ,
Please answer me if you know..
Thanks

答:
In ASP.NET use below code:</p>

```<code>var selectedValue = listBoxObj.SelectedItem.value;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
In ASP.NET use below code:

var selectedValue = listBoxObj.SelectedItem.value;


问:
Bubble Chart using R - x axis variables are not in numerical order + Scaling of axis
I have the following R code which contains some dummy data. I am trying to create a bubble chart where the size of the bubble is dependent on the amount and is positioned based on the profitability (as a % of the amount) on the x-axis and the volatility (as a % of the amount) on the y-axis. Code is as follows:

```<code> rio_csv <- import("~/Desktop/R/Dummy Data.csv")

# Select columns to go into df

df <- data.frame("Volpc" = rio_csv[,6],"Profitpc"= rio_csv[,5],"Amount"= rio_csv[,4])

#Plot Bubble Chart

plot <- ggplot(df, aes(x = Profitpc, y = Volpc, size = Amount)) +
geom_point(alpha = 0.2) + scale_size(range = c(5,15)) + xlab("Profitability %") +
ylab("Volatility %")

plot
</code>```

The profitability measure on the x-axis is a percentage and the volatility on the y-axis is a percentage. They both have the data type 'character'.

My first problem is when i run the code a bubble chart appears but the x-axis is not in numerical order, the y-axis is in numerical order.

I tried to use the code df$Profitpc <- as.numeric(df$Profitpc) but this causes all the values in the column to go NA with the warning 'NAs introduced by coercion'.

Is there a way of ordering the x-axis so it is in numerical order (increasing)?

My second problem is that the scaling of both axes are not suitably scaled. Ideally i would like a situation where both axes have appropriate scaling such as 0 to the max % value. Is there a way to do this also? I am sorry if this is obvious. I have attached a picture of the chart to illustrate the issues.

答:
You've given us your code but not your data, so this isn't a simple self-contained example or a reprex.  [See this post for more advice on how to give us what we need to help you.]

However, from the symptoms you describe, I'm guessing that df$Profitpc contains values such as 27.0%.  That's why as.numeric() fails: it doesn't know how to handle the %.  So your solution is to reformat your input data so that df$Profitpc truly is a numeric.  Then the graph will behave as you want.  As you haven't given us your input data, you're on your own when it comes to doing that...

Personally, I'd make the same change to df$Volpc as well.  As you've discovered, it's only luck that has presented the data in the order you want it.  Once you've got numeric data (and as a result, the order of display that you want), you can use features of ggplot to format its appearance the way you want.

The lesson here is that it is important to separate the derivation of your data from its presentation.

Body:
I have the following R code which contains some dummy data. I am trying to create a bubble chart where the size of the bubble is dependent on the amount and is positioned based on the profitability (as a % of the amount) on the x-axis and the volatility (as a % of the amount) on the y-axis. Code is as follows:

 rio_csv <- import("~/Desktop/R/Dummy Data.csv")

# Select columns to go into df

df <- data.frame("Volpc" = rio_csv[,6],"Profitpc"= rio_csv[,5],"Amount"= rio_csv[,4])

#Plot Bubble Chart

plot <- ggplot(df, aes(x = Profitpc, y = Volpc, size = Amount)) +
geom_point(alpha = 0.2) + scale_size(range = c(5,15)) + xlab("Profitability %") +
ylab("Volatility %")

plot

The profitability measure on the x-axis is a percentage and the volatility on the y-axis is a percentage. They both have the data type 'character'.

My first problem is when i run the code a bubble chart appears but the x-axis is not in numerical order, the y-axis is in numerical order.

I tried to use the code df$Profitpc <- as.numeric(df$Profitpc) but this causes all the values in the column to go NA with the warning 'NAs introduced by coercion'.

Is there a way of ordering the x-axis so it is in numerical order (increasing)?

My second problem is that the scaling of both axes are not suitably scaled. Ideally i would like a situation where both axes have appropriate scaling such as 0 to the max % value. Is there a way to do this also? I am sorry if this is obvious. I have attached a picture of the chart to illustrate the issues.


问:
Errors with freeze table header - HTML
I am trying to enter entries in table inputs for my inventory website. I want to freeze the headers of each column and tried doing it with this -> Freeze the top row for an html table only (Fixed Table Header Scrolling)

window.onload = function(){
  var to_show = '';
  for(var i = 1 ; i < 50 ; i++){
    to_show += '
<input type="text" autocomplete="off" id="product_name_'+ i +'" name="product_name_'+i+'" onkeyup="productSearch(this.value, '+i+')" tabindex="-1" style="font-size:larger;">	';
    to_show += '<input type="text" autocomplete="off" id="location_'+ i +'" name="location_'+ i +'" onkeyup="productSearch(this.value, '+ i +')" tabindex="-1" style="font-size:larger;">
';
  }
  document.getElementById('addInside_tr_20').innerHTML = to_show;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@import url("https://fonts.googleapis.com/css?family=Montserrat:300,400|Oswald:200,300,400&display=swap");
:root {
  --purple-theme: #091428;
  --lightpurple-theme: #0f3a41;
  --gray-bg-heading: #b8b8b8;
  --gray-bg-sidebar: #dee3e7;
  --lightgreen-theme: #65ffce;
  --green-theme: #46b692;
  --red-theme: #f75b54;
}
/* width */
::-webkit-scrollbar {
  width: 10px;
}
/* Track */
::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px grey;
  border-radius: 0px 0px 10px 10px;
  background: var(--lightpurple-theme);
}
/* Handle */
::-webkit-scrollbar-thumb {
  background: var(--green-theme);
  border-radius: 0 0 10px 10px;
}
/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
  background: var(--lightgreen-theme);
}
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
::-moz-selection {
  /* Code for Firefox */
  color: var(--purple-theme);
  background: var(--green-theme);
}
::selection {
  color: var(--purple-theme);
  background: var(--green-theme);
}
input:focus,
option:focus,
select:focus {
  outline-color: var(--lightgreen-theme);
}
body {
  height: 100%;
  background-repeat: no-repeat;
}
a {
  text-decoration: none;
}
table,
select,
input,
a {
  color: whitesmoke;
}
input {
  width: 100%;
  line-height: 5px;
  font-size: 10px;
}
input[type="text"],
input[type="url"],
input[type="number"] {
  height: 30px;
  border: 1px solid var(--green-theme);
  background-color: transparent;
  color: whitesmoke;
  font-size: 15px;
}
input[type="button"],
input[type="reset"],
input[type="submit"] {
  border: 1px solid var(--green-theme);
  background-color: var(--green-theme);
  color: var(--purple-theme);
  text-decoration-style: bold;
  font-size: 15px;
  border-radius: 0px 15px 15px 0px;
}

/* ------grid container------ */
input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ccc;
}
input[type="date"] {
  height: 100%;
}
.grid_container {
  display: grid;
  grid-template-columns: repeat(auto, 1fr);
  grid-gap: 10px;
  padding: 10px;
  margin: 0 auto;
  color: whitesmoke;
}
.grid {
  background-color: var(--purple-theme);
  border: 1px solid lightgrey;
  padding: 20px;
}
.inside > span {
  font-family: "Oswald", sans-serif;
  font-weight: 400;
  font-size: 18px;
}
.item1 {
  grid-column: 1 / 3;
}
.item2 {
  grid-column: 3 / 5;
}

.item3 {
  grid-column: 5 / 7;
}
.item4 {
  grid-column: 7 / 9;
}

.item5 {
  grid-column: 1 / 9;
}

.inside {
  padding: 0;
  padding-bottom: 10px;
  border: none;
}

.item2 {
  grid-column: 1 / 9;
  grid-row: 1 / 5;
}
.inside input[type="text"] {
  width: 200px;
}
.item2 select,
.item2 option {
  width: 100%;
  height: 30px;
  background-color: var(--purple-theme);
  border: 1px solid var(--green-theme);
  text-align: center;
}
.item2 select option {
  background: var(--purple-theme);
}
.item2 table {
  width: 100%;
  text-align: center;
  margin-top: 20px;
  font-size: 20px;
}
.details table:nth-child(1) {
  margin-top: -20px;
}
.details {
  margin-top: -20px;
}
.item2 th {
  background-color: var(--green-theme);
  color: var(--purple-theme);
  padding: 15px;
}
.item2 a {
  text-decoration: underline;
}

/* main edit here start */
                      #text-area td:nth-child(1) {
                        width: 80%;
                      }
                      #text-area td:nth-child(2) {
                        width: 20%;
                      }
                      #text-area thead th:nth-child(1) {
                        width: 80%;
                      }
                      #text-area thead th:nth-child(2) {
                        width: 20%;
                      }

                      #text-area thead {
                        display: block;
                      }
                      #text-area tbody {
                        height: 440px;
                        display: block;
                        overflow: auto;
                        width: 100%;
                      }
                      #text-area input {
                        width: 100%;
                      }

                      #text-area input {
                        border: none;
                      }
                      #text-area {
                        border: 1px solid var(--green-theme);
                      }
                      #text-area tr:nth-child(2n + 1) {
                        background: var(--lightpurple-theme);
                      }
                      #text-area td:nth-child(4) {
                        border-right: none;
                      }
                      #text-area td {
                        border-right: 1px solid var(--green-theme);
                      }
/* main edit here ends */
.item2 .inside table * {
  padding-bottom: 20px;
}

.suggestion {
  position: absolute;
  background-color: var(--purple-theme);
  font-size: smaller;
  cursor: pointer;
}
.suggestion_i:hover {
  color: var(--purple-theme);
  background-color: var(--green-theme);
}
.suggestion_i {
  cursor: pointer;
  text-align: center;
  text-justify: center;
  padding: 10px 10px -5px 10px;
}
#sorted_div {
  background-color: var(--purple-theme);
  /*position:absolute;*/
  top: 123px;
}
#sorted_div tr:nth-child(2n + 1) {
  background: var(--lightpurple-theme);
}</code>```

              <form action="php/invoiceFetch.php" method="post" enctype="multipart/form-data" id='myForm' onkeypress="return event.keyCode != 13;">

                    Location :
                    <input type="text" autocomplete="off" name="invoice_name" id="invoice_name" onchange="invoiceSpliter()" onkeyup="customerSearch(this.value)" style="width: 500;">
                    Product Suggestion :

                    Product Name
                    Current Locations

                  <input type="reset" value="Reset" tabindex="-1">
                  <input type="button" onclick="document.getElementById('myModal').style.display = 'block';" value="Submit">

              </form>

```

You can check the code on [codepen]{https://codepen.io/zaidi2293/pen/WNwmJrP} (Ignore most of the css as they are just to replicate what I had so that I don't miss something out)

(Sorry for the extensive code length) The Problem is the "thead" is not aligned with "tbody" as in column perspective because of overflow in vertical direction. I've asked this question before but that doesn't seem to work for me. Also, there will be some more columns added in the future. No custom size width answers please

答:
th {
  background-color: #fff;
}

th {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  z-index: 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="text-area">
  <thead>
    <tr>
      <th><label >Barcode</label></th>
      <th><label >Product Name</label></th>
      <th><label >Count</label></th>
      <th><label >QB-Price / Online Price</label></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="text" value="772696001844"></td>
      <td><input type="text" value="ACTIVATED CHARCOAL (COCONUT BASE) 114g" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696023815"></td>
      <td><input type="text" value="BILBERRY FRUIT POWDER" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696031100"></td>
      <td><input type="text" value="BLADDERWRACK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696031100"></td>
      <td><input type="text" value="BLADDERWRACK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696031100"></td>
      <td><input type="text" value="BLADDERWRACK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696037607"></td>
      <td><input type="text" value="BUCKTHORN BARK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696044803"></td>
      <td><input type="text" value="CASCARA BARK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696044803"></td>
      <td><input type="text" value="CASCARA BARK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696042007"></td>
      <td><input type="text" value="CHAMOMILE FLOWER WHOLE" ></td>
      <td><input type="text" value="6" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696066805"></td>
      <td><input type="text" value="DAMIANA LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696066805"></td>
      <td><input type="text" value="DAMIANA LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696067208"></td>
      <td><input type="text" value="DANDELION LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696067208"></td>
      <td><input type="text" value="DANDELION LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696084007"></td>
      <td><input type="text" value="FRANKINCENSE TEARS" ></td>
      <td><input type="text" value="4" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696087008"></td>
      <td><input type="text" value="GENTIAN ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696087008"></td>
      <td><input type="text" value="GENTIAN ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696108208"></td>
      <td><input type="text" value="HIBISCUS FLOWER WHOLE" ></td>
      <td><input type="text" value="6" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696112809"></td>
      <td><input type="text" value="HYSSOP HERB POWDER" ></td>
      <td><input type="text" value="2" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696124604"></td>
      <td><input type="text" value="LICORICE ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696124604"></td>
      <td><input type="text" value="LICORICE ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
  </tbody>
</table></code>```

Title: Errors with freeze table header - HTML

Body:
I am trying to enter entries in table inputs for my inventory website. I want to freeze the headers of each column and tried doing it with this -> Freeze the top row for an html table only (Fixed Table Header Scrolling)

window.onload = function(){
  var to_show = '';
  for(var i = 1 ; i < 50 ; i++){
    to_show += '
<input type="text" autocomplete="off" id="product_name_'+ i +'" name="product_name_'+i+'" onkeyup="productSearch(this.value, '+i+')" tabindex="-1" style="font-size:larger;">	';
    to_show += '<input type="text" autocomplete="off" id="location_'+ i +'" name="location_'+ i +'" onkeyup="productSearch(this.value, '+ i +')" tabindex="-1" style="font-size:larger;">
';
  }
  document.getElementById('addInside_tr_20').innerHTML = to_show;
}

@import url("https://fonts.googleapis.com/css?family=Montserrat:300,400|Oswald:200,300,400&display=swap");
:root {
  --purple-theme: #091428;
  --lightpurple-theme: #0f3a41;
  --gray-bg-heading: #b8b8b8;
  --gray-bg-sidebar: #dee3e7;
  --lightgreen-theme: #65ffce;
  --green-theme: #46b692;
  --red-theme: #f75b54;
}
/* width */
::-webkit-scrollbar {
  width: 10px;
}
/* Track */
::-webkit-scrollbar-track {
  box-shadow: inset 0 0 5px grey;
  border-radius: 0px 0px 10px 10px;
  background: var(--lightpurple-theme);
}
/* Handle */
::-webkit-scrollbar-thumb {
  background: var(--green-theme);
  border-radius: 0 0 10px 10px;
}
/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
  background: var(--lightgreen-theme);
}
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
::-moz-selection {
  /* Code for Firefox */
  color: var(--purple-theme);
  background: var(--green-theme);
}
::selection {
  color: var(--purple-theme);
  background: var(--green-theme);
}
input:focus,
option:focus,
select:focus {
  outline-color: var(--lightgreen-theme);
}
body {
  height: 100%;
  background-repeat: no-repeat;
}
a {
  text-decoration: none;
}
table,
select,
input,
a {
  color: whitesmoke;
}
input {
  width: 100%;
  line-height: 5px;
  font-size: 10px;
}
input[type="text"],
input[type="url"],
input[type="number"] {
  height: 30px;
  border: 1px solid var(--green-theme);
  background-color: transparent;
  color: whitesmoke;
  font-size: 15px;
}
input[type="button"],
input[type="reset"],
input[type="submit"] {
  border: 1px solid var(--green-theme);
  background-color: var(--green-theme);
  color: var(--purple-theme);
  text-decoration-style: bold;
  font-size: 15px;
  border-radius: 0px 15px 15px 0px;
}

/* ------grid container------ */
input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ccc;
}
input[type="date"] {
  height: 100%;
}
.grid_container {
  display: grid;
  grid-template-columns: repeat(auto, 1fr);
  grid-gap: 10px;
  padding: 10px;
  margin: 0 auto;
  color: whitesmoke;
}
.grid {
  background-color: var(--purple-theme);
  border: 1px solid lightgrey;
  padding: 20px;
}
.inside > span {
  font-family: "Oswald", sans-serif;
  font-weight: 400;
  font-size: 18px;
}
.item1 {
  grid-column: 1 / 3;
}
.item2 {
  grid-column: 3 / 5;
}

.item3 {
  grid-column: 5 / 7;
}
.item4 {
  grid-column: 7 / 9;
}

.item5 {
  grid-column: 1 / 9;
}

.inside {
  padding: 0;
  padding-bottom: 10px;
  border: none;
}

.item2 {
  grid-column: 1 / 9;
  grid-row: 1 / 5;
}
.inside input[type="text"] {
  width: 200px;
}
.item2 select,
.item2 option {
  width: 100%;
  height: 30px;
  background-color: var(--purple-theme);
  border: 1px solid var(--green-theme);
  text-align: center;
}
.item2 select option {
  background: var(--purple-theme);
}
.item2 table {
  width: 100%;
  text-align: center;
  margin-top: 20px;
  font-size: 20px;
}
.details table:nth-child(1) {
  margin-top: -20px;
}
.details {
  margin-top: -20px;
}
.item2 th {
  background-color: var(--green-theme);
  color: var(--purple-theme);
  padding: 15px;
}
.item2 a {
  text-decoration: underline;
}

/* main edit here start */
                      #text-area td:nth-child(1) {
                        width: 80%;
                      }
                      #text-area td:nth-child(2) {
                        width: 20%;
                      }
                      #text-area thead th:nth-child(1) {
                        width: 80%;
                      }
                      #text-area thead th:nth-child(2) {
                        width: 20%;
                      }

                      #text-area thead {
                        display: block;
                      }
                      #text-area tbody {
                        height: 440px;
                        display: block;
                        overflow: auto;
                        width: 100%;
                      }
                      #text-area input {
                        width: 100%;
                      }

                      #text-area input {
                        border: none;
                      }
                      #text-area {
                        border: 1px solid var(--green-theme);
                      }
                      #text-area tr:nth-child(2n + 1) {
                        background: var(--lightpurple-theme);
                      }
                      #text-area td:nth-child(4) {
                        border-right: none;
                      }
                      #text-area td {
                        border-right: 1px solid var(--green-theme);
                      }
/* main edit here ends */
.item2 .inside table * {
  padding-bottom: 20px;
}

.suggestion {
  position: absolute;
  background-color: var(--purple-theme);
  font-size: smaller;
  cursor: pointer;
}
.suggestion_i:hover {
  color: var(--purple-theme);
  background-color: var(--green-theme);
}
.suggestion_i {
  cursor: pointer;
  text-align: center;
  text-justify: center;
  padding: 10px 10px -5px 10px;
}
#sorted_div {
  background-color: var(--purple-theme);
  /*position:absolute;*/
  top: 123px;
}
#sorted_div tr:nth-child(2n + 1) {
  background: var(--lightpurple-theme);
}

              <form action="php/invoiceFetch.php" method="post" enctype="multipart/form-data" id='myForm' onkeypress="return event.keyCode != 13;">

                    Location :
                    <input type="text" autocomplete="off" name="invoice_name" id="invoice_name" onchange="invoiceSpliter()" onkeyup="customerSearch(this.value)" style="width: 500;">
                    Product Suggestion :

                    Product Name
                    Current Locations

                  <input type="reset" value="Reset" tabindex="-1">
                  <input type="button" onclick="document.getElementById('myModal').style.display = 'block';" value="Submit">

              </form>

You can check the code on [codepen]{https://codepen.io/zaidi2293/pen/WNwmJrP} (Ignore most of the css as they are just to replicate what I had so that I don't miss something out)

(Sorry for the extensive code length) The Problem is the "thead" is not aligned with "tbody" as in column perspective because of overflow in vertical direction. I've asked this question before but that doesn't seem to work for me. Also, there will be some more columns added in the future. No custom size width answers please

Body:
th {
  background-color: #fff;
}

th {
  position: -webkit-sticky;
  position: sticky;
  top: 0;
  z-index: 2;
}

<table id="text-area">
  <thead>
    <tr>
      <th><label >Barcode</label></th>
      <th><label >Product Name</label></th>
      <th><label >Count</label></th>
      <th><label >QB-Price / Online Price</label></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><input type="text" value="772696001844"></td>
      <td><input type="text" value="ACTIVATED CHARCOAL (COCONUT BASE) 114g" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696023815"></td>
      <td><input type="text" value="BILBERRY FRUIT POWDER" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696031100"></td>
      <td><input type="text" value="BLADDERWRACK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696031100"></td>
      <td><input type="text" value="BLADDERWRACK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696031100"></td>
      <td><input type="text" value="BLADDERWRACK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696037607"></td>
      <td><input type="text" value="BUCKTHORN BARK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696044803"></td>
      <td><input type="text" value="CASCARA BARK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696044803"></td>
      <td><input type="text" value="CASCARA BARK C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696042007"></td>
      <td><input type="text" value="CHAMOMILE FLOWER WHOLE" ></td>
      <td><input type="text" value="6" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696066805"></td>
      <td><input type="text" value="DAMIANA LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696066805"></td>
      <td><input type="text" value="DAMIANA LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696067208"></td>
      <td><input type="text" value="DANDELION LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696067208"></td>
      <td><input type="text" value="DANDELION LVS. C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696084007"></td>
      <td><input type="text" value="FRANKINCENSE TEARS" ></td>
      <td><input type="text" value="4" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696087008"></td>
      <td><input type="text" value="GENTIAN ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696087008"></td>
      <td><input type="text" value="GENTIAN ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696108208"></td>
      <td><input type="text" value="HIBISCUS FLOWER WHOLE" ></td>
      <td><input type="text" value="6" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696112809"></td>
      <td><input type="text" value="HYSSOP HERB POWDER" ></td>
      <td><input type="text" value="2" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696124604"></td>
      <td><input type="text" value="LICORICE ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
    <tr>
      <td><input type="text" value="772696124604"></td>
      <td><input type="text" value="LICORICE ROOT C/S" ></td>
      <td><input type="text" value="1" ></td>
      <td><input type="text" value="$19.25" ></td>
    </tr>
  </tbody>
</table>


问:
How do I display a csv or txt file on a python flask website
I would like to show information from a csv file on my flask app on a table but it only shows the first line of the csv file.     </p>

```<code>@app.route('/view/', methods=['GET', 'POST'])
def view():
    with open('/home/MakerofMarkers/mysite/container.csv', 'r') as csv_file:
        csv_reader = csv.reader(csv_file)
        next(csv_reader)

        for line in csv_reader:
            return str(line)

    return render_template('work.html')
</code>```

答:
If youre are using flask, in the render_template you send the data to the html in a variable

```<code>@app.route('/view/', methods=['GET', 'POST'])
    def view():
        with open('/home/MakerofMarkers/mysite/container.csv', 'r') as csv_file:
            csv_reader = csv.reader(csv_file)

        return render_template('work.html', data = csv_reader)
</code>```

This is a example of work.html

```<code><div class="card-body">
            <table class="table table-hover">
                <thead>
                    <tr>
                    <th scope="col">#</th>
                    <th scope="col">Data1</th>
                    <th scope="col">Data2</th>
                    <th scope="col">Data3</th>
                    <th scope="col">Data4</th>
                    <th scope="col">Data5</th>

                    </tr>
                </thead>
                <tbody>
                    {% for line in data %}
                    <tr>
                        <td>{{line.id}}</td>
                        <td>{{line.data1}}</td>
                        <td>{{line.data2}}</td>
                        <td>{{line.data3}}</td>
                        <td>{{line.data4}}</td>
                        <td>{{line.data5}}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
</code>```

Use jinja2, the data is used with {% %}
In this case i using line.data1, if your lines are list modify this to line[1] for example

Body:
I would like to show information from a csv file on my flask app on a table but it only shows the first line of the csv file.

@app.route('/view/', methods=['GET', 'POST'])
def view():
    with open('/home/MakerofMarkers/mysite/container.csv', 'r') as csv_file:
        csv_reader = csv.reader(csv_file)
        next(csv_reader)

        for line in csv_reader:
            return str(line)

    return render_template('work.html')

Body:
If youre are using flask, in the render_template you send the data to the html in a variable

@app.route('/view/', methods=['GET', 'POST'])
    def view():
        with open('/home/MakerofMarkers/mysite/container.csv', 'r') as csv_file:
            csv_reader = csv.reader(csv_file)

        return render_template('work.html', data = csv_reader)

This is a example of work.html

<div class="card-body">
            <table class="table table-hover">
                <thead>
                    <tr>
                    <th scope="col">#</th>
                    <th scope="col">Data1</th>
                    <th scope="col">Data2</th>
                    <th scope="col">Data3</th>
                    <th scope="col">Data4</th>
                    <th scope="col">Data5</th>

                    </tr>
                </thead>
                <tbody>
                    {% for line in data %}
                    <tr>
                        <td>{{line.id}}</td>
                        <td>{{line.data1}}</td>
                        <td>{{line.data2}}</td>
                        <td>{{line.data3}}</td>
                        <td>{{line.data4}}</td>
                        <td>{{line.data5}}</td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>

Use jinja2, the data is used with {% %}
In this case i using line.data1, if your lines are list modify this to line[1] for example


问:
How do I create links in Django such that other users can't access them?
I'm pretty confused about how do I prevent users' from accessing the data of other users.

The case at hand :

I'm creating a Notes + To-Do app in which a user logs in, creates their notes and tasks.

How to create links to those notes such that they aren't accessible by other users? As in the correct syntax for UserPassesTestMixin.

In the To-Do app, how do I keep the tasks of one user unique to them? Similarly for the note app, how do I achieve that?

答:
Not sure what you mean by "create links". For what you describe, the links don't change for people that have access or not. The difference if that a user that owns note 5 and goes to /note/5/, they should be able to see their note, but if another user goes to /note/5/ they should either 1) get a 404 error (Note not found) or 403 (Permission Denied) just be redirected to another page (say, the home page), maybe with a message.

Using Class based views, this is easy to do.

Prevent access to views

```<code>from django.core.exceptions import PermissionDenied
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

class LoginRequiredAccessMixin(object):
   # This will ensure the user is authenticated and should
   # likely be used for other views

   @method_decorator(login_required)
   def dispatch(self, request, *args, **kwargs):
      return super(LoginRequiredAccessMixin, self).dispatch(request, *args, **kwargs)

 class AccessMixin(LoginRequiredAccessMixin):

   def get_object(self, queryset=None):
      obj = get_object_or_404(Note, pk=self.kwargs['id'])

      # Assumes you have a notes.user, but change to created_by
      # or whatever is your user field name
      if obj.user == self.request.user:
          # User owns object
          return obj

      raise PermissionDenied("User has no access to this note")

class NoteView(AccessMixin, DetailView):
  # This is a regular DetilView, but with the Mixin,
  # you are overwriting the get_object() function.
  # If you don't want the Mixin, then you can just add
  # get get_object() function here. Except that with the
  # Mixin, you can reuse it for your UpdateView, DeleteView
  # and even across both your notes and task views
  model = Note
  template_name = 'note/details.html'

  def get_context_data(self, **kwargs):
     context = super(NoteView, self).get_context_data(**kwargs)
     # Add any special context for the template
     return context
</code>```

If instead you want to just direct users to another page, you would do something like:

```<code>from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.contrib import messages

class NoteView(DetailView):
  model = Note
  template_name = 'note/details.html'

  def get_context_data(self, **kwargs):
     context = super(NoteView, self).get_context_data(**kwargs)
     # Add any special context for the template
     return context

  @method_decorator(login_required)
  def dispatch(self, request, *args, **kwargs):
     note = self.get_objet()
     if note and not note.user == self.request.user:
        messages.error(
            self.request,
            'You are not allowed to access this Note'
        )
        return HttpResponseRedirect('/home')
    return super(NoteView, self).dispatch(request, *args, **kwargs)
</code>```

You didn't supply any code so I cannot be more specific, but hopefully you get an idea of the two techniques. The first is usually a cleaner solution, and the Mixin I show can be shared across both your Note views and ToDo Tasks records, assuming they use the same user/created_by field name.

Body:
Not sure what you mean by "create links". For what you describe, the links don't change for people that have access or not. The difference if that a user that owns note 5 and goes to /note/5/, they should be able to see their note, but if another user goes to /note/5/ they should either 1) get a 404 error (Note not found) or 403 (Permission Denied) just be redirected to another page (say, the home page), maybe with a message.

Using Class based views, this is easy to do.

Prevent access to views

from django.core.exceptions import PermissionDenied
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required

class LoginRequiredAccessMixin(object):
   # This will ensure the user is authenticated and should
   # likely be used for other views

   @method_decorator(login_required)
   def dispatch(self, request, *args, **kwargs):
      return super(LoginRequiredAccessMixin, self).dispatch(request, *args, **kwargs)

 class AccessMixin(LoginRequiredAccessMixin):

   def get_object(self, queryset=None):
      obj = get_object_or_404(Note, pk=self.kwargs['id'])

      # Assumes you have a notes.user, but change to created_by
      # or whatever is your user field name
      if obj.user == self.request.user:
          # User owns object
          return obj

      raise PermissionDenied("User has no access to this note")

class NoteView(AccessMixin, DetailView):
  # This is a regular DetilView, but with the Mixin,
  # you are overwriting the get_object() function.
  # If you don't want the Mixin, then you can just add
  # get get_object() function here. Except that with the
  # Mixin, you can reuse it for your UpdateView, DeleteView
  # and even across both your notes and task views
  model = Note
  template_name = 'note/details.html'

  def get_context_data(self, **kwargs):
     context = super(NoteView, self).get_context_data(**kwargs)
     # Add any special context for the template
     return context

If instead you want to just direct users to another page, you would do something like:

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.contrib import messages

class NoteView(DetailView):
  model = Note
  template_name = 'note/details.html'

  def get_context_data(self, **kwargs):
     context = super(NoteView, self).get_context_data(**kwargs)
     # Add any special context for the template
     return context

  @method_decorator(login_required)
  def dispatch(self, request, *args, **kwargs):
     note = self.get_objet()
     if note and not note.user == self.request.user:
        messages.error(
            self.request,
            'You are not allowed to access this Note'
        )
        return HttpResponseRedirect('/home')
    return super(NoteView, self).dispatch(request, *args, **kwargs)

You didn't supply any code so I cannot be more specific, but hopefully you get an idea of the two techniques. The first is usually a cleaner solution, and the Mixin I show can be shared across both your Note views and ToDo Tasks records, assuming they use the same user/created_by field name.