问:
ERROR 404 popping up when navigating from my contacts page to my home page
I have four pages home, about, projects and contacts, all links work fine except when i navigate from the contacts page back to the home page, ERROR 404 pops up and i have no idea why, here is my webpage to
check it out here,

https://chrisalta94.github.io/Christopher-Personal-Portfolio/index.html

Any idea why?

答:
That is because you are linking Home to home.html instead of to index.html at the Contacts page.

Use this Home instead of this Home

Body:
That is because you are linking Home to home.html instead of to index.html at the Contacts page.

Use this <a href="index.html">Home</a> instead of this <a href="home.html">Home</a>


来源: stackexchange

问:
Updating AutoLayout Constraints When UIView Height Changes
I currently have a UIView (we'll call this viewB) added to a parent UIScrollView, which we'll call scrollView.  This functions as expected, with viewB being added like so;

```<code>viewB.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
viewB.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
viewB.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
viewB.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true
</code>```

viewB is taller than scrollView, hence its ability to scroll vertically.

At some point in my app, the user may tap a button, which adds more content to viewB, hence changing viewB's height.  On that button tap, scrollView does not seem to know to update any of its constraints, and viewB ends up changing positions and does not appear as expected.

What methods would I call (and on which views) to force AutoLayout to tell scrollView that viewB has changed sizes?  Or would it be more efficient to remove viewB from scrollView and then re-add with new constraints?

答:
Subviews inside a view that's inside a scrollview should be hooked properly from top to bottom at any time , so when you add a new subview to viewB you need to insert it properly inside that chain then call

```<code>self.view.layoutIfNeeded()
</code>```

if for e.x you add it at the bottom then you should remove most bottom subview's bottom constraint with viewB and hook it to the top of the new view and re-hook that new's subview's bottom to viewB's bottom plus giving height & width & x constraint finally refresh the layout again which is a tedious problem so you either go with it or with this Tip

Tip : instead of managing constraints manually with UIScrollView you can use a UITableView or replace viewB with a UIStackView that has easily remove/add/insert functions

ContentLicense: CC BY-SA 4.0

Body:
I currently have a UIView (we'll call this viewB) added to a parent UIScrollView, which we'll call scrollView.  This functions as expected, with viewB being added like so;

viewB.topAnchor.constraint(equalTo: scrollView.topAnchor).isActive = true
viewB.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor).isActive = true
viewB.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor).isActive = true
viewB.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor).isActive = true

viewB is taller than scrollView, hence its ability to scroll vertically.

At some point in my app, the user may tap a button, which adds more content to viewB, hence changing viewB's height.  On that button tap, scrollView does not seem to know to update any of its constraints, and viewB ends up changing positions and does not appear as expected.

What methods would I call (and on which views) to force AutoLayout to tell scrollView that viewB has changed sizes?  Or would it be more efficient to remove viewB from scrollView and then re-add with new constraints?

Body:
Subviews inside a view that's inside a scrollview should be hooked properly from top to bottom at any time , so when you add a new subview to viewB you need to insert it properly inside that chain then call

self.view.layoutIfNeeded()

if for e.x you add it at the bottom then you should remove most bottom subview's bottom constraint with viewB and hook it to the top of the new view and re-hook that new's subview's bottom to viewB's bottom plus giving height & width & x constraint finally refresh the layout again which is a tedious problem so you either go with it or with this Tip

Tip : instead of managing constraints manually with UIScrollView you can use a UITableView or replace viewB with a UIStackView that has easily remove/add/insert functions


问:
How to stop code from running until $.get returns value?
I am trying to read in data from a file and save it into an array using jquery's get function. However, because the get function is asynchronous, the code after the $.get function call runs and the data is undefined. How can I run the code following the $.get function call only after the call is completed and data has been returned?

I have tried setting async to false, but the console log gives the error that it is deprecated.

```<code>    class CharacterDatabase{
      constructor(fName){
        this.fileText = readFile(fName);
        this.fileText = this.fileText.split(/[\r\n]+/);
      }
    }

    function readFile(fName){
      console.log(fName);
      $.get(fName, function(data){
        return data;
      }, "text");
    }

    var cd = new CharacterDatabase("text.txt");
</code>```

The error:

```<code>main.js:32 Uncaught TypeError: Cannot read property 'split' of undefined at new CharacterDatabase (main.js:32) at main.js:85
</code>```

is thrown in the console.

Line 32 is:

```<code>this.fileText = this.fileText.split(/[\r\n]+/);
</code>```

When setting async to false the error states that synchronous XMLHTTPRequests are deprecated.

答:
A simple solution would be to wrap the call in a Promise and use async/await:

```<code>class CharacterDatabase{
  constructor(fName){
    this.init();
  }
}

async function init() {
    this.fileText = await readFile(fName);
    this.fileText = this.fileText.split(/[\r\n]+/);
}

async function readFile(fName){
  console.log(fName);
  await new Promise((resolve) => {$.get(fName, function(data){
    resolve(data);
  }, "text")});;
}

var cd = new CharacterDatabase("text.txt");
</code>```

As a sidenote, I would generally not advise to put any I/O operations in a constructor.

Body:
I am trying to read in data from a file and save it into an array using jquery's get function. However, because the get function is asynchronous, the code after the $.get function call runs and the data is undefined. How can I run the code following the $.get function call only after the call is completed and data has been returned?

I have tried setting async to false, but the console log gives the error that it is deprecated.

    class CharacterDatabase{
      constructor(fName){
        this.fileText = readFile(fName);
        this.fileText = this.fileText.split(/[\r\n]+/);
      }
    }

    function readFile(fName){
      console.log(fName);
      $.get(fName, function(data){
        return data;
      }, "text");
    }

    var cd = new CharacterDatabase("text.txt");

The error:

main.js:32 Uncaught TypeError: Cannot read property 'split' of undefined at new CharacterDatabase (main.js:32) at main.js:85

is thrown in the console.

Line 32 is:

this.fileText = this.fileText.split(/[\r\n]+/);

When setting async to false the error states that synchronous XMLHTTPRequests are deprecated.

Body:
A simple solution would be to wrap the call in a Promise and use async/await:

class CharacterDatabase{
  constructor(fName){
    this.init();
  }
}

async function init() {
    this.fileText = await readFile(fName);
    this.fileText = this.fileText.split(/[\r\n]+/);
}

async function readFile(fName){
  console.log(fName);
  await new Promise((resolve) => {$.get(fName, function(data){
    resolve(data);
  }, "text")});;
}

var cd = new CharacterDatabase("text.txt");

As a sidenote, I would generally not advise to put any I/O operations in a constructor.


问:
Bug problem : Failed prop type: The prop `onClick` is marked as required in `Letter`, but its value is `undefined`
I'm new to React, so for educational purposes I'm building a hangman game. But I incurr in a problem, from the snippet below the onclick event is unrecognized as a function. I am supposing the problem could stem by a not proper use of this, but is only an assumption.

definition

```<code>const Letter = ({ index, letter, onClick }) => (
  <div className={`letter`} onClick={() => onClick(index)}>
    <button >
      {letter}
    </button>
  </div>
)
</code>```

render part

```<code>ALPHABET.map((letter, index) => (
    <Letter
      letter={letter}
      index={index}
      key={index}
      onClick={this.addLetter(letter,usedLetters)}
    />
</code>```

答:
The problem is here:

```<code>onClick={this.addLetter(letter,usedLetters}
</code>```

You are invoking the function as soon as the component renders.

Assuming you are defining a class-component and addLetter is an arrow function inside it like so:

```<code>addLetter = (letter, usedLetters) => {
  ...
}
</code>```

You can rework the onClick property to this and it will still require the arguments your defined by default.

```<code>onClick={this.addLetter}
</code>```

Also, you never passed in usedLetters as a property to Letter

```<code><Letter
  letter={letter}
  usedLetters={usedLetters}
  index={index}
  key={index}
  onClick={this.addLetter(letter,usedLetters)}
/>
</code>```

Body:
I'm new to React, so for educational purposes I'm building a hangman game. But I incurr in a problem, from the snippet below the onclick event is unrecognized as a function. I am supposing the problem could stem by a not proper use of this, but is only an assumption.

definition

const Letter = ({ index, letter, onClick }) => (
  <div className={`letter`} onClick={() => onClick(index)}>
    <button >
      {letter}
    </button>

)

render part

ALPHABET.map((letter, index) => (
    <Letter
      letter={letter}
      index={index}
      key={index}
      onClick={this.addLetter(letter,usedLetters)}
    />

Body:
The problem is here:

onClick={this.addLetter(letter,usedLetters}

You are invoking the function as soon as the component renders.

Assuming you are defining a class-component and addLetter is an arrow function inside it like so:

addLetter = (letter, usedLetters) => {
  ...
}

You can rework the onClick property to this and it will still require the arguments your defined by default.

onClick={this.addLetter}

Also, you never passed in usedLetters as a property to Letter

<Letter
  letter={letter}
  usedLetters={usedLetters}
  index={index}
  key={index}
  onClick={this.addLetter(letter,usedLetters)}
/>


问:
accept POST from only own server
i have developed a project in PHP now i need to process those POST DATA which have been sent from my own server !

how to do it ?

REFERRER is not a solution, as it can be blocked/removed or changed easily !

is there code to stop it in .htaccess ?

答:
You could try to use cryptographic nonce : Typical client-server communication during a nonce-based authentication process including both a server nonce and a client nonce ( this client nonce could be built using the nonce recived from the server ) .

Now this doesn't make you super secure ( as there will be people who would be able to bypass this rather easy ) it will be harder for most floks to make a post to you're website .

( this image shows you how to use nonces in an authetification process , however you could use it for non authentification purposes )

ContentLicense: CC BY-SA 3.0

Title: accept POST from only own server


问:
Problem with finding the closest intersection
The rays keep casting on the wrong "wall", but only if the lamp is more in the bottom right. If the lamp is in the left up corner everything is working fine.

I have tried a lot of things, but last time I had a problem I wrote I checked the formulars many times and in the end it was a problem with the formular so I am not even gonne try

(https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection)

function for finding the closest wall:

    def draw(self):
        bestdist = 1000000000000000000
        for obs in run.Obs:
            x1, y1 = obs.startp
            x2, y2 = obs.endp
            x3, y3 = run.lamp
            x4, y4 = self.maxendpoint

            d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
            if d != 0:
                t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / d
                u = ((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / d
                if 0 < t < 1 and u > 0:
                    px = round(x1 + t * (x2 - x1))
                    py = round(y1 + t * (y2 - y1))
                    dist = px**2+py**2
                    if dist < bestdist:
                        bestdist = dist
                        self.endpoint= [px, py]
                    # pygame.draw.circle(run.screen, pygame.Color('green'), (px, py), 3)
        if len(self.endpoint) == 2:
            pygame.draw.line(run.screen, pygame.Color('white'), run.lamp, self.endpoint)
```

<p>the whole code:</p>

<pre class="lang-py prettyprint-override"><code>import pygame
import sys
import math
import random as rd
import numpy as np

class Obs(object):
    def __init__(self, startp, endp):
        self.startp = startp
        self.endp = endp

    def drawww(self):
        pygame.draw.line(run.screen, pygame.Color('red'), (self.startp), (self.endp))

class rays(object):
    def __init__(self, maxendpoint):
        self.maxendpoint = maxendpoint
        self.endpoint = []

    def draw(self):
        bestdist = 1000000000000000000
        for obs in run.Obs:
            x1, y1 = obs.startp
            x2, y2 = obs.endp
            x3, y3 = run.lamp
            x4, y4 = self.maxendpoint

            d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
            if d != 0:
                t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / d
                u = ((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / d
                if 0 < t < 1 and u > 0:
                    px = round(x1 + t * (x2 - x1))
                    py = round(y1 + t * (y2 - y1))
                    dist = px**2+py**2
                    if dist < bestdist:
                        bestdist = dist
                        self.endpoint= [px, py]
                    # pygame.draw.circle(run.screen, pygame.Color('green'), (px, py), 3)
        if len(self.endpoint) == 2:
            pygame.draw.line(run.screen, pygame.Color('white'), run.lamp, self.endpoint)

class Control(object):
    def __init__(self):
        self.winw = 800
        self.winh = 800
        self.screen = pygame.display.set_mode((self.winw, self.winh))
        self.fps = 60
        self.clock = pygame.time.Clock()
        self.lamp = [round(self.winw/2), round(self.winh/2)]
        self.lampr = 13
        self.lines = []
        self.r = 5
        self.Obs = []
        self.angel = 0
        self.fov = 360
        self.scene = np.ones(self.fov)
        self.done = False
        self.makeobs()

    def event_loop(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.done = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_F5:
                    self.__init__()
                elif event.key == pygame.K_LEFT:
                    if self.angel <= 0:
                        self.angel = 360
                    else:
                        self.angel -= 5
                elif event.key == pygame.K_RIGHT:
                    if self.angel >= 360:
                        self.angel = 0
                    else:
                        self.angel += 5
                elif event.key == pygame.K_w:
                    self.lamp[1] -= 10
                elif event.key == pygame.K_a:
                    self.lamp[0] -= 10
                elif event.key == pygame.K_s:
                    self.lamp[1] += 10
                elif event.key == pygame.K_d:
                    self.lamp[0] += 10
                elif event.key == pygame.K_y:
                    pass

        if pygame.mouse.get_pressed() == (1, 0, 0):
            if pygame.mouse.get_pos()[0] > 800:
                self.lamp = [799, pygame.mouse.get_pos()[1]]
            else:
                self.lamp[0] = pygame.mouse.get_pos()[0]
                self.lamp[1] = pygame.mouse.get_pos()[1]

    def draw(self):
        self.screen.fill((pygame.Color('black')))
        pygame.draw.circle(self.screen, pygame.Color('white'), self.lamp, self.lampr)
        for obs in self.Obs:
            obs.drawww()
        for line in self.lines:
            line.draw()

    def makeobs(self):
        for i in range(2):
            self.Obs.append(Obs((rd.randint(0, self.winw), rd.randint(0, self.winh)),
                                (rd.randint(0, self.winw), rd.randint(0, self.winh))))
        # self.Obs.append(Obs((0, 0), (self.winw, 0)))
        # self.Obs.append(Obs((0, 0), (0, self.winh)))
        # self.Obs.append(Obs((self.winw, 0), (self.winw, self.winh)))
        # self.Obs.append(Obs((0, self.winh), (self.winw, self.winh)))

    def createlines(self):
        self.lines.clear()
        for angle in range(self.angel, self.angel+self.fov):
            angle = math.radians(angle)
            self.lines.append(rays([self.lamp[0] + math.cos(angle), self.lamp[1] + math.sin(angle)]))

    def main_loop(self):
        while not self.done:
            self.event_loop()
            self.createlines()
            self.draw()
            pygame.display.update()
            self.clock.tick(self.fps)
            pygame.display.set_caption(f"Draw  FPS: {self.clock.get_fps()}")

if __name__ == '__main__':
    run = Control()
    run.main_loop()
    pygame.quit()
    sys.exit()

</code>```

Expected it to work no matter where the lamp is.

答:
The code

```<code>px = round(x1 + t * (x2 - x1))
py = round(y1 + t * (y2 - y1))
dist = px**2+py**2
</code>```

doesn't make any sense, because (py, py) is a point, and so dist = px**2+py**2 is the squared Euclidean distance from the origin (0, 0) to (py, py).

You've to calculate the distance from (x3, x4) to the intersection point:

vx = u * (x4 - x3)
vy = u * (y4 - y3)
dist = vx**2+vy**2
```
<p>Further there is an issue when in the calculation of <code>u</code>:</p>
<p><s><code>u = ((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / d</code></s><br />
<code>u = ((x1 - x3) * (y1 - y2) - (y1 - y3) * (x1 - x2)) / d</code></p>
<p>Method class <code>rays</code>:</p>
<pre class="lang-py prettyprint-override"><code>class rays(object):
    def __init__(self, maxendpoint):
        self.maxendpoint = maxendpoint
        self.endpoint = []

    def draw(self):
        bestdist = 1000000000000000000
        for obs in run.Obs:
            x1, y1 = obs.startp
            x2, y2 = obs.endp
            x3, y3 = run.lamp
            x4, y4 = self.maxendpoint

            d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
            if d != 0:
                t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / d
                u = ((x1 - x3) * (y1 - y2) - (y1 - y3) * (x1 - x2)) / d
                if 0 < t < 1 and u > 0:
                    vx = u * (x4 - x3)
                    vy = u * (y4 - y3)
                    dist = vx**2+vy**2
                    if dist < bestdist:
                        px = round(x3 + u * (x4 - x3))
                        py = round(y3 + u * (y4 - y3))
                        bestdist = dist
                        self.endpoint= [px, py]
                    # pygame.draw.circle(run.screen, pygame.Color('green'), (px, py), 3)
        if len(self.endpoint) == 2:
            pygame.draw.line(run.screen, pygame.Color('white'), run.lamp, self.endpoint)
</code>```

Minimal example:  repl.it/@Rabbid76/PyGame-IntersectAndCutLines

import pygame
import math
import random

def intersect(obstacles, P0, P1):
    bestdist = 1000000000000000000
    endpoint = P1
    for Q0, Q1 in obstacles:
        d = (P1[0]-P0[0]) * (Q1[1]-Q0[1]) + (P1[1]-P0[1]) * (Q0[0]-Q1[0])
        if d != 0:
            t = ((Q0[0]-P0[0]) * (Q1[1]-Q0[1]) + (Q0[1]-P0[1]) * (Q0[0]-Q1[0])) / d
            u = ((Q0[0]-P0[0]) * (P1[1]-P0[1]) + (Q0[1]-P0[1]) * (P0[0]-P1[0])) / d
            if 0 <= t <= 1 and 0 <= u <= 1:
                vx, vy = (P1[0]-P0[0]) * t, (P1[1]-P0[1]) * t
                dist = vx*vx + vy*vy
                if dist < bestdist:
                    px, py = round(Q1[0] * u + Q0[0] * (1-u)), round(Q1[1] * u + Q0[1] * (1-u))
                    bestdist = dist
                    endpoint = (px, py)
    return endpoint

def createRays(center):
    return [(center[0] + 1200 * math.cos(angle), center[1] + 1200 * math.sin(angle)) for angle in range(0, 360, 10)]

def createObstacles(surface):
    w, h = surface.get_size()
    return [((random.randrange(w), random.randrange(h)), (random.randrange(w), random.randrange(h))) for _ in range(5)]

window = pygame.display.set_mode((800, 800))
clock = pygame.time.Clock()

origin = window.get_rect().center
rays = createRays(origin)
obstacles = createObstacles(window)

move_center = True
run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            obstacles = createObstacles(window)
        if event.type == pygame.KEYDOWN:
            move_center = not move_center

    if move_center:
        origin = pygame.mouse.get_pos()
        rays = createRays(origin)

    window.fill(0)
    for endpoint in rays:
        endpoint = intersect(obstacles, origin, endpoint)
        pygame.draw.line(window, (128, 128, 128), origin, endpoint)
    pygame.draw.circle(window, (255, 255, 255), origin, 10)
    for start, end in obstacles:
        pygame.draw.line(window, (255, 0, 0), start, end)
    pygame.display.flip()

pygame.quit()
exit()
```

Body:
The rays keep casting on the wrong "wall", but only if the lamp is more in the bottom right. If the lamp is in the left up corner everything is working fine.

I have tried a lot of things, but last time I had a problem I wrote I checked the formulars many times and in the end it was a problem with the formular so I am not even gonne try

(https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection)

function for finding the closest wall:

    def draw(self):
        bestdist = 1000000000000000000
        for obs in run.Obs:
            x1, y1 = obs.startp
            x2, y2 = obs.endp
            x3, y3 = run.lamp
            x4, y4 = self.maxendpoint

            d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
            if d != 0:
                t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / d
                u = ((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / d
                if 0 < t < 1 and u > 0:
                    px = round(x1 + t * (x2 - x1))
                    py = round(y1 + t * (y2 - y1))
                    dist = px**2+py**2
                    if dist < bestdist:
                        bestdist = dist
                        self.endpoint= [px, py]
                    # pygame.draw.circle(run.screen, pygame.Color('green'), (px, py), 3)
        if len(self.endpoint) == 2:
            pygame.draw.line(run.screen, pygame.Color('white'), run.lamp, self.endpoint)

the whole code:

import pygame
import sys
import math
import random as rd
import numpy as np

class Obs(object):
    def __init__(self, startp, endp):
        self.startp = startp
        self.endp = endp

    def drawww(self):
        pygame.draw.line(run.screen, pygame.Color('red'), (self.startp), (self.endp))

class rays(object):
    def __init__(self, maxendpoint):
        self.maxendpoint = maxendpoint
        self.endpoint = []

    def draw(self):
        bestdist = 1000000000000000000
        for obs in run.Obs:
            x1, y1 = obs.startp
            x2, y2 = obs.endp
            x3, y3 = run.lamp
            x4, y4 = self.maxendpoint

            d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
            if d != 0:
                t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / d
                u = ((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / d
                if 0 < t < 1 and u > 0:
                    px = round(x1 + t * (x2 - x1))
                    py = round(y1 + t * (y2 - y1))
                    dist = px**2+py**2
                    if dist < bestdist:
                        bestdist = dist
                        self.endpoint= [px, py]
                    # pygame.draw.circle(run.screen, pygame.Color('green'), (px, py), 3)
        if len(self.endpoint) == 2:
            pygame.draw.line(run.screen, pygame.Color('white'), run.lamp, self.endpoint)

class Control(object):
    def __init__(self):
        self.winw = 800
        self.winh = 800
        self.screen = pygame.display.set_mode((self.winw, self.winh))
        self.fps = 60
        self.clock = pygame.time.Clock()
        self.lamp = [round(self.winw/2), round(self.winh/2)]
        self.lampr = 13
        self.lines = []
        self.r = 5
        self.Obs = []
        self.angel = 0
        self.fov = 360
        self.scene = np.ones(self.fov)
        self.done = False
        self.makeobs()

    def event_loop(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                self.done = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_F5:
                    self.__init__()
                elif event.key == pygame.K_LEFT:
                    if self.angel <= 0:
                        self.angel = 360
                    else:
                        self.angel -= 5
                elif event.key == pygame.K_RIGHT:
                    if self.angel >= 360:
                        self.angel = 0
                    else:
                        self.angel += 5
                elif event.key == pygame.K_w:
                    self.lamp[1] -= 10
                elif event.key == pygame.K_a:
                    self.lamp[0] -= 10
                elif event.key == pygame.K_s:
                    self.lamp[1] += 10
                elif event.key == pygame.K_d:
                    self.lamp[0] += 10
                elif event.key == pygame.K_y:
                    pass

        if pygame.mouse.get_pressed() == (1, 0, 0):
            if pygame.mouse.get_pos()[0] > 800:
                self.lamp = [799, pygame.mouse.get_pos()[1]]
            else:
                self.lamp[0] = pygame.mouse.get_pos()[0]
                self.lamp[1] = pygame.mouse.get_pos()[1]

    def draw(self):
        self.screen.fill((pygame.Color('black')))
        pygame.draw.circle(self.screen, pygame.Color('white'), self.lamp, self.lampr)
        for obs in self.Obs:
            obs.drawww()
        for line in self.lines:
            line.draw()

    def makeobs(self):
        for i in range(2):
            self.Obs.append(Obs((rd.randint(0, self.winw), rd.randint(0, self.winh)),
                                (rd.randint(0, self.winw), rd.randint(0, self.winh))))
        # self.Obs.append(Obs((0, 0), (self.winw, 0)))
        # self.Obs.append(Obs((0, 0), (0, self.winh)))
        # self.Obs.append(Obs((self.winw, 0), (self.winw, self.winh)))
        # self.Obs.append(Obs((0, self.winh), (self.winw, self.winh)))

    def createlines(self):
        self.lines.clear()
        for angle in range(self.angel, self.angel+self.fov):
            angle = math.radians(angle)
            self.lines.append(rays([self.lamp[0] + math.cos(angle), self.lamp[1] + math.sin(angle)]))

    def main_loop(self):
        while not self.done:
            self.event_loop()
            self.createlines()
            self.draw()
            pygame.display.update()
            self.clock.tick(self.fps)
            pygame.display.set_caption(f"Draw  FPS: {self.clock.get_fps()}")

if __name__ == '__main__':
    run = Control()
    run.main_loop()
    pygame.quit()
    sys.exit()

Expected it to work no matter where the lamp is.

Body:
The code

px = round(x1 + t * (x2 - x1))
py = round(y1 + t * (y2 - y1))
dist = px**2+py**2

doesn't make any sense, because (py, py) is a point, and so dist = px**2+py**2 is the squared Euclidean distance from the origin (0, 0) to (py, py).

You've to calculate the distance from (x3, x4) to the intersection point:

vx = u * (x4 - x3)
vy = u * (y4 - y3)
dist = vx**2+vy**2

Further there is an issue when in the calculation of u:

<s>u = ((x1 - x2) * (y1 - y3) - (y1 - y2) * (x1 - x3)) / d</s>

u = ((x1 - x3) * (y1 - y2) - (y1 - y3) * (x1 - x2)) / d

Method class rays:

class rays(object):
    def __init__(self, maxendpoint):
        self.maxendpoint = maxendpoint
        self.endpoint = []

    def draw(self):
        bestdist = 1000000000000000000
        for obs in run.Obs:
            x1, y1 = obs.startp
            x2, y2 = obs.endp
            x3, y3 = run.lamp
            x4, y4 = self.maxendpoint

            d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4)
            if d != 0:
                t = ((x1 - x3) * (y3 - y4) - (y1 - y3) * (x3 - x4)) / d
                u = ((x1 - x3) * (y1 - y2) - (y1 - y3) * (x1 - x2)) / d
                if 0 < t < 1 and u > 0:
                    vx = u * (x4 - x3)
                    vy = u * (y4 - y3)
                    dist = vx**2+vy**2
                    if dist < bestdist:
                        px = round(x3 + u * (x4 - x3))
                        py = round(y3 + u * (y4 - y3))
                        bestdist = dist
                        self.endpoint= [px, py]
                    # pygame.draw.circle(run.screen, pygame.Color('green'), (px, py), 3)
        if len(self.endpoint) == 2:
            pygame.draw.line(run.screen, pygame.Color('white'), run.lamp, self.endpoint)

Minimal example:  repl.it/@Rabbid76/PyGame-IntersectAndCutLines

import pygame
import math
import random

def intersect(obstacles, P0, P1):
    bestdist = 1000000000000000000
    endpoint = P1
    for Q0, Q1 in obstacles:
        d = (P1[0]-P0[0]) * (Q1[1]-Q0[1]) + (P1[1]-P0[1]) * (Q0[0]-Q1[0])
        if d != 0:
            t = ((Q0[0]-P0[0]) * (Q1[1]-Q0[1]) + (Q0[1]-P0[1]) * (Q0[0]-Q1[0])) / d
            u = ((Q0[0]-P0[0]) * (P1[1]-P0[1]) + (Q0[1]-P0[1]) * (P0[0]-P1[0])) / d
            if 0 <= t <= 1 and 0 <= u <= 1:
                vx, vy = (P1[0]-P0[0]) * t, (P1[1]-P0[1]) * t
                dist = vx*vx + vy*vy
                if dist < bestdist:
                    px, py = round(Q1[0] * u + Q0[0] * (1-u)), round(Q1[1] * u + Q0[1] * (1-u))
                    bestdist = dist
                    endpoint = (px, py)
    return endpoint

def createRays(center):
    return [(center[0] + 1200 * math.cos(angle), center[1] + 1200 * math.sin(angle)) for angle in range(0, 360, 10)]

def createObstacles(surface):
    w, h = surface.get_size()
    return [((random.randrange(w), random.randrange(h)), (random.randrange(w), random.randrange(h))) for _ in range(5)]

window = pygame.display.set_mode((800, 800))
clock = pygame.time.Clock()

origin = window.get_rect().center
rays = createRays(origin)
obstacles = createObstacles(window)

move_center = True
run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        if event.type == pygame.MOUSEBUTTONDOWN:
            obstacles = createObstacles(window)
        if event.type == pygame.KEYDOWN:
            move_center = not move_center

    if move_center:
        origin = pygame.mouse.get_pos()
        rays = createRays(origin)

    window.fill(0)
    for endpoint in rays:
        endpoint = intersect(obstacles, origin, endpoint)
        pygame.draw.line(window, (128, 128, 128), origin, endpoint)
    pygame.draw.circle(window, (255, 255, 255), origin, 10)
    for start, end in obstacles:
        pygame.draw.line(window, (255, 0, 0), start, end)
    pygame.display.flip()

pygame.quit()
exit()


问:
Using UIMA Ruta: How do I annotate the first token of a text and use that annotation further?
I would like to annotate the first token of a text and use that annotation in following rules. I have tried different patterns:

Token.begin == 0 (doesn't work, although there definitely is a token that begins at 0)

Token{STARTSWITH(DocumentMetaData)}; (also doesn't work)

The only pattern that works is:

Document{->MARKFIRST(First)};

But if I try to use that annotation e.g. in the following way:

First{->MARK(FirstAgain)};

it doesn't work again. This makes absolutely no sense to me. There seems to be a really weird behaviour with annotations that start at 0.

答:
This trivial task can be a bit tricky indeed, mainly because of the visibility settings. I do not know why your rules in the question do not work without having a look at the text that should be processed.

As for UIMA Ruta 2.7.0, I prefer a rule like:

```<code># Token{->First};
</code>```

Here some additional thoughts about the rules in the question:

```<code>Token.begin == 0;
</code>```

Normally, there is not token with begin at 0 since the document starts with some whitespaces or line breaks. If there is actually a token that starts at offset 0 and the rule does not match, then something invisible is covering the begin of the end of the token. This depends of course of the filtering settings, but in case that you did not change them, it could be a bom.

```<code>Token{STARTSWITH(DocumentMetaData)};
</code>```

Here, either the problem above applies, or the begin offset is not identical. If the DocumentMetaData covers the complete document, then I would bet on the leading whitespaces. Another reason could be that the internal indexing is broken, e.g., the tokens or the DocumentMetaData are created by an external analysis engine which was called with EXEC and no reindexing was configured in the action. This situation could also occur with unfortunate optimizations using the config params.

```<code>Document{->MARKFIRST(First)};
First{->MARK(FirstAgain)};
</code>```

MARKFIRST creates an annotation using the offset of the first RutaBasic in the matched context IIRC. If the document starts with something invisible, e.g., a line break, then the second rule cannot match.

As a general advice in situations like this when some obvious simple rules do not work correctly as expected, I recommend adding some additional rules and using the debugging config with the explanation view. As rule like Token; can directly highlight if the visibility setting are problematic for the given tokens.

DISCLAIMER: I am a developer of UIMA Ruta

Body:
This trivial task can be a bit tricky indeed, mainly because of the visibility settings. I do not know why your rules in the question do not work without having a look at the text that should be processed.

As for UIMA Ruta 2.7.0, I prefer a rule like:

# Token{->First};

Here some additional thoughts about the rules in the question:

Token.begin == 0;

Normally, there is not token with begin at 0 since the document starts with some whitespaces or line breaks. If there is actually a token that starts at offset 0 and the rule does not match, then something invisible is covering the begin of the end of the token. This depends of course of the filtering settings, but in case that you did not change them, it could be a bom.

Token{STARTSWITH(DocumentMetaData)};

Here, either the problem above applies, or the begin offset is not identical. If the DocumentMetaData covers the complete document, then I would bet on the leading whitespaces. Another reason could be that the internal indexing is broken, e.g., the tokens or the DocumentMetaData are created by an external analysis engine which was called with EXEC and no reindexing was configured in the action. This situation could also occur with unfortunate optimizations using the config params.

Document{->MARKFIRST(First)};
First{->MARK(FirstAgain)};

MARKFIRST creates an annotation using the offset of the first RutaBasic in the matched context IIRC. If the document starts with something invisible, e.g., a line break, then the second rule cannot match.

As a general advice in situations like this when some obvious simple rules do not work correctly as expected, I recommend adding some additional rules and using the debugging config with the explanation view. As rule like Token; can directly highlight if the visibility setting are problematic for the given tokens.

DISCLAIMER: I am a developer of UIMA Ruta


问:
javascript document.getElementById in other frames
I have two frames and want to access an element in one frame from another:

Frame 1:

```<code><div id='someId'>...</div>
</code>```

Frame 2:

```<code>var div=document.getElementById('someId');

div.innerHTML='something';
</code>```

This is somehow not functioning in Firefox so I want to be sure, can I access an element in another frame by its ID?

答:
For some reason

```<code>window.frames["framename"].document.getElementById ( "yourelementid" );
</code>```

was not working for me.

This other method did:

```<code>   document.getElementById('framename').contentWindow.document.getElementById('yourelementid');
</code>```

Body:
I have two frames and want to access an element in one frame from another:

Frame 1:

...

Frame 2:

var div=document.getElementById('someId');

div.innerHTML='something';

This is somehow not functioning in Firefox so I want to be sure, can I access an element in another frame by its ID?

Body:
For some reason

window.frames["framename"].document.getElementById ( "yourelementid" );

was not working for me.

This other method did:

   document.getElementById('framename').contentWindow.document.getElementById('yourelementid');


问:
How to validate only part of a value I'm getting through a get request?
I want to get two values from a get request, and then I'll use explode to retrieve each of them separately. However, this means that the value I'm getting before using explode isn't unique to the table (since it's a compound, and therefore it's not an existing value in the table). How can use validate to avoid duplicate of it ?

I tried making the column unique using an SQL constraint, however this means I get an exception page when a user enters a duplicate. I would like to use validation instead so I get an error message.

```<code>public function store(Request $request)
    {
        $this->validate($request, [
            'idProduit' => 'unique:stocks',
            'produit' => 'required|unique:stocks',
            'quantite' => 'required'
        ]);
        $produit = explode("|",$request->get('produit'));
        $stock = new Stock;
        $stock->idProduit = $produit[0];
        $stock->produit = $produit[1];
        $stock->quantite = $request->input('quantite');
        $stock->save();

        return redirect('/stocks/')->with('success', 'Entrée de stock ajoutée à la base de données');
    }
</code>```

I don't actually get any error message, but it is allowing me to add duplicates in the database, which I know why : the value is a compound that doesn't exist in the database, and so the unique validation I wrote cannot catch duplicate on just a part of it.

答:
You could create custom validation rule class or use Validator https://laravel.com/docs/5.8/validation#custom-validation-rules.

Something like that:

```<code>Validator::make($request->all(), [
    'quantite' => 'required',
    'produit' => [
        'required',
        function ($attribute, $value, $fail) {
            $parts = explode('|', $value);

            if (!Stock::where('idProduit', $parts[0])->exists()) {
                $fail('idProduit already exists.');
            }

            if (!Stock::where('produit', $parts[1])->exists()) {
                $fail('produit already exists.');
            }
        }
    ],
])->validate();
</code>```

Body:
I want to get two values from a get request, and then I'll use explode to retrieve each of them separately. However, this means that the value I'm getting before using explode isn't unique to the table (since it's a compound, and therefore it's not an existing value in the table). How can use validate to avoid duplicate of it ?

I tried making the column unique using an SQL constraint, however this means I get an exception page when a user enters a duplicate. I would like to use validation instead so I get an error message.

public function store(Request $request)
    {
        $this->validate($request, [
            'idProduit' => 'unique:stocks',
            'produit' => 'required|unique:stocks',
            'quantite' => 'required'
        ]);
        $produit = explode("|",$request->get('produit'));
        $stock = new Stock;
        $stock->idProduit = $produit[0];
        $stock->produit = $produit[1];
        $stock->quantite = $request->input('quantite');
        $stock->save();

        return redirect('/stocks/')->with('success', 'Entrée de stock ajoutée à la base de données');
    }

I don't actually get any error message, but it is allowing me to add duplicates in the database, which I know why : the value is a compound that doesn't exist in the database, and so the unique validation I wrote cannot catch duplicate on just a part of it.

Body:
You could create custom validation rule class or use Validator https://laravel.com/docs/5.8/validation#custom-validation-rules.

Something like that:

Validator::make($request->all(), [
    'quantite' => 'required',
    'produit' => [
        'required',
        function ($attribute, $value, $fail) {
            $parts = explode('|', $value);

            if (!Stock::where('idProduit', $parts[0])->exists()) {
                $fail('idProduit already exists.');
            }

            if (!Stock::where('produit', $parts[1])->exists()) {
                $fail('produit already exists.');
            }
        }
    ],
])->validate();


问:
Is CreateCompatibleDC() necessary working with windows on one display?
This example code manually reads a bitmap file, uses CreateDIBSection() to make GDI allocate memory for it, and create an hbitmap handle.  Then it uses a MemoryDC to draw the bitmap to a window DC:

ftp://ftp.oreilly.com/examples/9781572319950/cd_contents/Chap15/DibSect/DibSect.c

```<code>hdc = BeginPaint (hwnd, &ps) ;
...
hdcMem = CreateCompatibleDC (hdc) ;
</code>```

Why can't we use GetDC() with NULL or with hwndDesktop instead?  Why can't we cache the device context instead of repeatedly creating it?

If the machine has only one display device and we are only drawing to windows why do we need to constantly harmonize bitmaps and device contexts?  Once the pixeldata is copied to the buffer provided by GDI, does GDI update it when that HBITMAP is loaded into a DC and drawn on?  If the user also wishes to draw on it is it necessary to synchronize access?  (By calling GDIFlush() first?)

It's hard to figure this out when most all of the object properties are opaque and abstracted.  I've read almost all of the related MSDN, a lot of Petzold's book, and some articles:

Display Device Contexts

CreateCompatibleDC()

CreateDIBSection()

Memory Device Contexts

Guide to Win32 Memory DC

Guide to WIN32 Paint for Intermediates

Programming Windows®, Fifth Edition

Edit:

I think my question boils down to this:

Is a device context a TYPE of display or is it an INSTANCE of graphical data that is able to be displayed.  A computer typically has only a handful of displays but it could have hundreds of things to display on them.

答:
GetDC(NULL) is the screen HDC and the screen is a shared resource, therefore you should only do read/query operations on this HDC. Writing to this HDC is not a good idea on Vista and higher because of the DWM.

Since a HDC can only contain one bitmap, one brush and one pen, Windows/applications obviously need more than one HDC provided by the graphics engine.

You can count on CreateCompatibleDC to be relatively cheap operation and I believe Windows has a cache of DCs it can hand out. If you are creating a game/animation type application you might want to cache some of these graphic objects on your own but a normal application should not.

You don't generally call GDIFlush unless you are sharing GDI objects across several threads. You can use SetDIBits if you want to mix raw pixel bytes access and GDI.

I don't really get the once screen argument, Windows has supported multiple monitors since Windows 98 and there is not much you can do to prevent the user from connecting another monitor.

Body:
This example code manually reads a bitmap file, uses CreateDIBSection() to make GDI allocate memory for it, and create an hbitmap handle.  Then it uses a MemoryDC to draw the bitmap to a window DC:

ftp://ftp.oreilly.com/examples/9781572319950/cd_contents/Chap15/DibSect/DibSect.c

hdc = BeginPaint (hwnd, &ps) ;
...
hdcMem = CreateCompatibleDC (hdc) ;

Why can't we use GetDC() with NULL or with hwndDesktop instead?  Why can't we cache the device context instead of repeatedly creating it?

If the machine has only one display device and we are only drawing to windows why do we need to constantly harmonize bitmaps and device contexts?  Once the pixeldata is copied to the buffer provided by GDI, does GDI update it when that HBITMAP is loaded into a DC and drawn on?  If the user also wishes to draw on it is it necessary to synchronize access?  (By calling GDIFlush() first?)

It's hard to figure this out when most all of the object properties are opaque and abstracted.  I've read almost all of the related MSDN, a lot of Petzold's book, and some articles:

Display Device Contexts

CreateCompatibleDC()

CreateDIBSection()

Memory Device Contexts

Guide to Win32 Memory DC

Guide to WIN32 Paint for Intermediates

Programming Windows®, Fifth Edition

Edit:

I think my question boils down to this:

Is a device context a TYPE of display or is it an INSTANCE of graphical data that is able to be displayed.  A computer typically has only a handful of displays but it could have hundreds of things to display on them.


问:
Problem with connect to postgresql with java and intellij
I have problem with my project. I'm trying start my application with postgresql and I have error. I can not call build gradle, always finish BUILD FAILED. I show you the code.
I do not understand why this error because I threw in a week without a problem and gradle build was also successful. I just changed the application properties file back to MySQL. When I again wanted to use postgresql, these errors pop up. I am asking for help and thank you for every answer

My application properties

```<code>spring.jpa.hibernate.ddl-auto=update
spring.jpa.database=postgresql
spring.datasource.url=${JDBC_DATABASE_URL}
spring.datasource.username=${JDBC_DATABASE_USERNAME}
spring.datasource.password=${JDBC_DATABASE_PASSWORD}
</code>```

my build.gradle

```<code>plugins {
    id 'org.springframework.boot' version '2.1.3.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'
</code>```

//apply plugin: 'war'

```<code>group = 'com.crud'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    compileOnly 'org.projectlombok:lombok:1.18.8'
    annotationProcessor 'org.projectlombok:lombok:1.18.8'
    implementation 'org.springframework.boot:spring-boot-starter-data-
   jpa'
    //runtimeOnly 'mysql:mysql-connector-java'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'io.springfox:springfox-swagger2:2.7.0'
    implementation 'io.springfox:springfox-swagger-ui:2.7.0'
    testImplementation 'org.springframework.boot:spring-boot-starter-
   test'
    runtimeOnly 'org.postgresql:postgresql'
    implementation 'org.springframework.boot:spring-boot-starter-
   mail:2.1.5.RELEASE'
    //providedRuntime 'org.springframework.boot:spring-boot-starter-
    tomcat'
}
</code>```

When I run application...

```<code>2019-05-26 19:19:36.139  INFO 14288 --- [           main]
o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-05-26 19:19:36.152  INFO 14288 --- [           main]
ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-
run your application with 'debug' enabled.
2019-05-26 19:19:36.162 ERROR 14288 --- [           main]
o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name
'org.springframework.boot.autoconfigure.
orm.jpa.HibernateJpaConfiguration':
Unsatisfied dependency expressed through constructor parameter 0; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dataSource' defined in class path resource

 [org/springframework/boot/autoconfigure
/jdbc/DataSourceConfiguration$Hikari.c
lass]: Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method
'dataSource' threw exception; nested exception is
 java.lang.IllegalArgumentException: URL must start with 'jdbc'
at

org.springframework.beans.factory.
support.ConstructorResolver.createArgumentA
rray(ConstructorResolver.java:769) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.ConstructorResolver.autowireConstru
ctor(ConstructorResolver.java:218) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
autowireConstructor(AbstractAutowireCapableBeanFactory.java:1325) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBeanInstance(AbstractAutowireCapableBeanFactory.java:1171) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
 support.AbstractAutowireCapableBeanFactory.
 createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-
 5.1.5.RELEASE.jar:5.1.5.RELEASE]
 at

org.springframework.beans.factory.
support.AbstractBeanFactory.lambda$doGetBea
n$0(AbstractBeanFactory.java:320) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultSingletonBeanRegistry.getSin
gleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.doGetBean(Abstr
actBeanFactory.java:318) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.getBean(Abstrac
tBeanFactory.java:199) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.ConstructorResolver.instantiateUsin
gFactoryMethod(ConstructorResolver.java:392) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory.

instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.
java:1305)
 ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory.
createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory.
doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.
lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultSingletonBeanRegistry.
getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractBeanFactory.
doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.context.support
.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105)
~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.context.support
.AbstractApplicationContext.
finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~
[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
 org.springframework.context.support
.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.boot.web.servlet.
context.ServletWebServerApplicationContext.
refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
org.springframework.boot.SpringApplication
.refresh(SpringApplication.java:775) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
 org.springframework.boot.SpringApplication
.refreshContext(SpringApplication.java:397) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
org.springframework.boot.SpringApplication
.run(SpringApplication.java:316) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.SpringApplication
.run(SpringApplication.java:1260) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
 org.springframework.boot.SpringApplication
.run(SpringApplication.java:1248) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
com.crud.tasks.TasksApplication.
main(TasksApplication.java:11) ~[classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'dataSource' defined in class path resource

[org/springframework/boot/autoconfigure
/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via
factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method
'dataSource' threw exception; nested exception is
java.lang.IllegalArgumentException: URL must start with 'jdbc'
at
org.springframework.beans.factory.
support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.ConstructorResolver.
instantiateUsingFactoryMethod(ConstructorResolver.java:607) ~[spring-
beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
instantiateUsingFactoryMethod
(AbstractAutowireCapableBeanFactory.java:1305) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractBeanFactory.
lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultSingletonBeanRegistry.
getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.
doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.
getBean(AbstractBeanFactory.java:199) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.config
.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultListableBeanFactory.
doResolveDependency(DefaultListableBeanFactory.java:1247) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
 support.DefaultListableBeanFactory.
 resolveDependency(DefaultListableBeanFactory.java:1167) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.support.
ConstructorResolver.
resolveAutowiredArgument(ConstructorResolver.java:857) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.ConstructorResolver.
createArgumentArray(ConstructorResolver.java:760) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 28 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed
to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method
'dataSource' threw exception; nested exception is
java.lang.IllegalArgumentException: URL must start with 'jdbc'
at

org.springframework.beans.factory.
support.SimpleInstantiationStrategy.
instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 42 common frames omitted
Caused by: java.lang.IllegalArgumentException: URL must start with 'jdbc'
at org.springframework.util.Assert.isTrue(Assert.java:118) ~[spring-core-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.boot.jdbc.DatabaseDriver.
fromJdbcUrl(DatabaseDriver.java:280) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.autoconfigure.
jdbc.DataSourceProperties.
determineDriverClassName(DataSourceProperties.java:230) ~[spring-boot-
autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
org.springframework.boot.autoconfigure
.jdbc.DataSourceProperties.
initializeDataSourceBuilder(DataSourceProperties.java:176) ~[spring-boot-
autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.autoconfigure.
jdbc.DataSourceConfiguration.
createDataSource(DataSourceConfiguration.java:43) ~[spring-boot-
autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.autoconfigure.
jdbc.DataSourceConfiguration$Hikari.
dataSource(DataSourceConfiguration.java:83) ~[spring-boot-autoconfigure-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) ~[na:na]
at
java.base/jdk.internal.reflect.
NativeMethodAccessorImpl.
invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at
java.base/jdk.internal.reflect.
DelegatingMethodAccessorImpl.
invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at
org.springframework.beans.
factory.support.SimpleInstantiationStrategy.
instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 43 common frames omitted
</code>```

and when I run gradle build...

```<code>Task :test

com.crud.tasks.TasksApplicationTests > contextLoads FAILED
java.lang.IllegalStateException
    Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException
        Caused by:
org.springframework.beans.factory.BeanCreationException
            Caused by:
org.springframework.beans.BeanInstantiationException
                Caused by: java.lang.IllegalArgumentException

7 tests completed, 1 failed
</code>```

答:
I think logs are saying what the problem is.

'dataSource' threw exception; nested exception is
  java.lang.IllegalArgumentException: URL must start with 'jdbc'
  at

It's not clear what the value of this variable ${JDBC_DATABASE_URL}

But it should be something like :

```<code>jdbc:postgresql://localhost:5432/dbname?currentSchema=dbschema
</code>```

Body:
I have problem with my project. I'm trying start my application with postgresql and I have error. I can not call build gradle, always finish BUILD FAILED. I show you the code.
I do not understand why this error because I threw in a week without a problem and gradle build was also successful. I just changed the application properties file back to MySQL. When I again wanted to use postgresql, these errors pop up. I am asking for help and thank you for every answer

My application properties

spring.jpa.hibernate.ddl-auto=update
spring.jpa.database=postgresql
spring.datasource.url=${JDBC_DATABASE_URL}
spring.datasource.username=${JDBC_DATABASE_USERNAME}
spring.datasource.password=${JDBC_DATABASE_PASSWORD}

my build.gradle

plugins {
    id 'org.springframework.boot' version '2.1.3.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'

//apply plugin: 'war'

group = 'com.crud'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    compileOnly 'org.projectlombok:lombok:1.18.8'
    annotationProcessor 'org.projectlombok:lombok:1.18.8'
    implementation 'org.springframework.boot:spring-boot-starter-data-
   jpa'
    //runtimeOnly 'mysql:mysql-connector-java'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'io.springfox:springfox-swagger2:2.7.0'
    implementation 'io.springfox:springfox-swagger-ui:2.7.0'
    testImplementation 'org.springframework.boot:spring-boot-starter-
   test'
    runtimeOnly 'org.postgresql:postgresql'
    implementation 'org.springframework.boot:spring-boot-starter-
   mail:2.1.5.RELEASE'
    //providedRuntime 'org.springframework.boot:spring-boot-starter-
    tomcat'
}

When I run application...

2019-05-26 19:19:36.139  INFO 14288 --- [           main]
o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
2019-05-26 19:19:36.152  INFO 14288 --- [           main]
ConditionEvaluationReportLoggingListener :

Error starting ApplicationContext. To display the conditions report re-
run your application with 'debug' enabled.
2019-05-26 19:19:36.162 ERROR 14288 --- [           main]
o.s.boot.SpringApplication               : Application run failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error
creating bean with name
'org.springframework.boot.autoconfigure.
orm.jpa.HibernateJpaConfiguration':
Unsatisfied dependency expressed through constructor parameter 0; nested
exception is org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'dataSource' defined in class path resource

 [org/springframework/boot/autoconfigure
/jdbc/DataSourceConfiguration$Hikari.c
lass]: Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method
'dataSource' threw exception; nested exception is
 java.lang.IllegalArgumentException: URL must start with 'jdbc'
at

org.springframework.beans.factory.
support.ConstructorResolver.createArgumentA
rray(ConstructorResolver.java:769) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.ConstructorResolver.autowireConstru
ctor(ConstructorResolver.java:218) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
autowireConstructor(AbstractAutowireCapableBeanFactory.java:1325) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBeanInstance(AbstractAutowireCapableBeanFactory.java:1171) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
 support.AbstractAutowireCapableBeanFactory.
 createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-
 5.1.5.RELEASE.jar:5.1.5.RELEASE]
 at

org.springframework.beans.factory.
support.AbstractBeanFactory.lambda$doGetBea
n$0(AbstractBeanFactory.java:320) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultSingletonBeanRegistry.getSin
gleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.doGetBean(Abstr
actBeanFactory.java:318) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.getBean(Abstrac
tBeanFactory.java:199) ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.ConstructorResolver.instantiateUsin
gFactoryMethod(ConstructorResolver.java:392) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory.

instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.
java:1305)
 ~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory.
createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.support.
AbstractAutowireCapableBeanFactory.
doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.
lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultSingletonBeanRegistry.
getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractBeanFactory.
doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
~[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.context.support
.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105)
~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.context.support
.AbstractApplicationContext.
finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~
[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
 org.springframework.context.support
.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
~[spring-context-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.boot.web.servlet.
context.ServletWebServerApplicationContext.
refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
org.springframework.boot.SpringApplication
.refresh(SpringApplication.java:775) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
 org.springframework.boot.SpringApplication
.refreshContext(SpringApplication.java:397) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
org.springframework.boot.SpringApplication
.run(SpringApplication.java:316) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.SpringApplication
.run(SpringApplication.java:1260) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
 org.springframework.boot.SpringApplication
.run(SpringApplication.java:1248) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
com.crud.tasks.TasksApplication.
main(TasksApplication.java:11) ~[classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'dataSource' defined in class path resource

[org/springframework/boot/autoconfigure
/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via
factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method
'dataSource' threw exception; nested exception is
java.lang.IllegalArgumentException: URL must start with 'jdbc'
at
org.springframework.beans.factory.
support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.ConstructorResolver.
instantiateUsingFactoryMethod(ConstructorResolver.java:607) ~[spring-
beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
instantiateUsingFactoryMethod
(AbstractAutowireCapableBeanFactory.java:1305) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBeanInstance(AbstractAutowireCapableBeanFactory.java:1144) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractAutowireCapableBeanFactory.
createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at
org.springframework.beans.factory.
support.AbstractBeanFactory.
lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultSingletonBeanRegistry.
getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.
doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.AbstractBeanFactory.
getBean(AbstractBeanFactory.java:199) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.config
.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.DefaultListableBeanFactory.
doResolveDependency(DefaultListableBeanFactory.java:1247) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

 org.springframework.beans.factory.
 support.DefaultListableBeanFactory.
 resolveDependency(DefaultListableBeanFactory.java:1167) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.support.
ConstructorResolver.
resolveAutowiredArgument(ConstructorResolver.java:857) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.ConstructorResolver.
createArgumentArray(ConstructorResolver.java:760) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 28 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed
to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method
'dataSource' threw exception; nested exception is
java.lang.IllegalArgumentException: URL must start with 'jdbc'
at

org.springframework.beans.factory.
support.SimpleInstantiationStrategy.
instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.beans.factory.
support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~
[spring-beans-5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 42 common frames omitted
Caused by: java.lang.IllegalArgumentException: URL must start with 'jdbc'
at org.springframework.util.Assert.isTrue(Assert.java:118) ~[spring-core-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
at

org.springframework.boot.jdbc.DatabaseDriver.
fromJdbcUrl(DatabaseDriver.java:280) ~[spring-boot-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.autoconfigure.
jdbc.DataSourceProperties.
determineDriverClassName(DataSourceProperties.java:230) ~[spring-boot-
autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at
org.springframework.boot.autoconfigure
.jdbc.DataSourceProperties.
initializeDataSourceBuilder(DataSourceProperties.java:176) ~[spring-boot-
autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.autoconfigure.
jdbc.DataSourceConfiguration.
createDataSource(DataSourceConfiguration.java:43) ~[spring-boot-
autoconfigure-2.1.3.RELEASE.jar:2.1.3.RELEASE]
at

org.springframework.boot.autoconfigure.
jdbc.DataSourceConfiguration$Hikari.
dataSource(DataSourceConfiguration.java:83) ~[spring-boot-autoconfigure-
2.1.3.RELEASE.jar:2.1.3.RELEASE]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native
Method) ~[na:na]
at
java.base/jdk.internal.reflect.
NativeMethodAccessorImpl.
invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at
java.base/jdk.internal.reflect.
DelegatingMethodAccessorImpl.
invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at
org.springframework.beans.
factory.support.SimpleInstantiationStrategy.
instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-
5.1.5.RELEASE.jar:5.1.5.RELEASE]
... 43 common frames omitted

and when I run gradle build...

Task :test

com.crud.tasks.TasksApplicationTests > contextLoads FAILED
java.lang.IllegalStateException
    Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException
        Caused by:
org.springframework.beans.factory.BeanCreationException
            Caused by:
org.springframework.beans.BeanInstantiationException
                Caused by: java.lang.IllegalArgumentException

7 tests completed, 1 failed

Body:
I think logs are saying what the problem is.

'dataSource' threw exception; nested exception is
  java.lang.IllegalArgumentException: URL must start with 'jdbc'
  at

It's not clear what the value of this variable ${JDBC_DATABASE_URL}

But it should be something like :

jdbc:postgresql://localhost:5432/dbname?currentSchema=dbschema


问:
Different behavior due to different "looping styles"
I have a simple problem. Navigate to a certain line in a fine, and delete everything after that. I use the suitable file.truncate() call. However, the two snippets of code below behave differently.

1)

```<code>with open(file, "a+b", 1) as f:
  #Navigate to the MARKER
  while True:
    line = f.readline()
    if MARKER in line:
      f.truncate()
      f.write(stuff)
      break
</code>```

2)

```<code>with open(file, "a+b", 1) as f:
  #Navigate to the MARKER
  for line in f:
    if MARKER in line:
      f.truncate()
      f.write(stuff)
      break
</code>```

(1) behaves as expected. However in case of (2), the file in truncated several lines after the MARKER is found. I speculate that there is some buffering going on, but as you can see, I explicitly define the buffering behavior as "line buffered" to the open() call.

Any thoughts? I would like to use the more intuitive "for line in file" syntax...

答:
From Python documentation, 5. Built-in Types / 5.9. File Objects:

In order to make a for loop the most
  efficient way of looping over the
  lines of a file (a very common
  operation), the next() method uses a
  hidden read-ahead buffer.

BTW: It is generally discouraged to use keywords (e.g. file) as variable names.

Body:
I have a simple problem. Navigate to a certain line in a fine, and delete everything after that. I use the suitable file.truncate() call. However, the two snippets of code below behave differently.

1)

with open(file, "a+b", 1) as f:
  #Navigate to the MARKER
  while True:
    line = f.readline()
    if MARKER in line:
      f.truncate()
      f.write(stuff)
      break

2)

with open(file, "a+b", 1) as f:
  #Navigate to the MARKER
  for line in f:
    if MARKER in line:
      f.truncate()
      f.write(stuff)
      break

(1) behaves as expected. However in case of (2), the file in truncated several lines after the MARKER is found. I speculate that there is some buffering going on, but as you can see, I explicitly define the buffering behavior as "line buffered" to the open() call.

Any thoughts? I would like to use the more intuitive "for line in file" syntax...


问:
How to make an inline-block element fill the remainder of the line?
Is such a thing possible using CSS and two inline-block (or whatever) DIV tags instead of using a table?

The table version is this (borders added so you can see it):

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head></head>
<body>
<table style="width:100%;">
<tr>
<td style="border:1px solid black;width:100px;height:10px;"></td>
<td style="border:1px solid black;height:10px;"></td>
</tr>
</table>
</body>
</html>
</code>```

It produces a left column with a FIXED WIDTH (not a percentage width), and a right column that expands to fill THE REMAINING SPACE on the line.  Sounds pretty simple, right?  Furthermore, since nothing is "floated", the parent container's height properly expands to encompass the height of the content.

--BEGIN RANT--

I've seen the "clear fix" and "holy grail" implementations for multi-column layouts with fixed-width side column, and they suck and they're complicated.  They reverse the order of elements, they use percentage widths, or they use floats, negative margins, and the relationship between the "left", "right", and "margin" attributes are complex.  Furthermore, the layouts are sub-pixel sensitive so that adding even a single pixel of borders, padding, or margins will break the whole layout, and send entire columns wrapping to the next line.  For example, rounding errors are a problem even if you try to do something simple, like put 4 elements on a line, with each one's width set to 25%.

--END RANT--

I've tried using "inline-block" and "white-space:nowrap;", but the problem is I just can't get the 2nd element to fill the remaining space on the line.  Setting the width to something like "width:100%-(LeftColumWidth)px" will work in some cases, but performing a calculation in a width property is not really supported.

答: I've used flex-grow property to achieve this goal. You'll have to set display: flex for parent container, then you need to set flex-grow: 1 for the block you want to fill remaining space, or just flex: 1 as tanius mentioned in the comments.

ContentLicense: CC BY-SA 2.5

Body:
Is such a thing possible using CSS and two inline-block (or whatever) DIV tags instead of using a table?

The table version is this (borders added so you can see it):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

It produces a left column with a FIXED WIDTH (not a percentage width), and a right column that expands to fill THE REMAINING SPACE on the line.  Sounds pretty simple, right?  Furthermore, since nothing is "floated", the parent container's height properly expands to encompass the height of the content.

--BEGIN RANT--

I've seen the "clear fix" and "holy grail" implementations for multi-column layouts with fixed-width side column, and they suck and they're complicated.  They reverse the order of elements, they use percentage widths, or they use floats, negative margins, and the relationship between the "left", "right", and "margin" attributes are complex.  Furthermore, the layouts are sub-pixel sensitive so that adding even a single pixel of borders, padding, or margins will break the whole layout, and send entire columns wrapping to the next line.  For example, rounding errors are a problem even if you try to do something simple, like put 4 elements on a line, with each one's width set to 25%.

--END RANT--

I've tried using "inline-block" and "white-space:nowrap;", but the problem is I just can't get the 2nd element to fill the remaining space on the line.  Setting the width to something like "width:100%-(LeftColumWidth)px" will work in some cases, but performing a calculation in a width property is not really supported.


问:
How to deserialize BIG JSON data into DataGridView
I´d like to deserialize a big JSON File (~600MB) into DataGridView without facing "maxJsonLength" Error.

My Code is working fine for small JSON files. But for bigger JSON files I get the "maxJsonLength" Error. Is there a workaround or an easy way to solve this problem since I am not the most experienced coder?

```<code>Private Sub BtnOpenFile_Click(sender As Object, e As EventArgs) Handles BtnOpenFileOld.Click
        OpenFileDialog1.InitialDirectory = "C:\"

        If OpenFileDialog1.ShowDialog = DialogResult.Cancel Then
        End If

        Dim JSonFilePath As String = File.ReadAllText(OpenFileDialog1.FileName)
        LblFilePath.Text = OpenFileDialog1.FileName

        DataGridView1.Rows.Clear()
        DataGridView1.Refresh()

        Dim dict As Object = New JavaScriptSerializer().Deserialize(Of List(Of Object))(JSonFilePath)

        For Each item As Object In dict
            DataGridView1.Rows.Add(item("EMail").ToString, item("Timestamp").ToString, item("Number").ToString)
        Next

    End Sub
</code>```

My JSON File looks like

```<code>[
  {
    "EMail": "one@mail.com",
    "Timestamp": "2019-05-25T21:24:06.799381+02:00",
    "Number": 206074,
    "randomtrash1": "notneeded",
    "randomtrash2": "notneeded",
    "randomtrash3": "notneeded",
    "randomtrash4": "notneeded",
    "randomtrash5": "notneeded",
    "randomtrash6": "notneeded",
    "randomtrash7": "notneeded",
    "randomtrash8": "notneeded",
    "randomtrash9": "notneeded"
  },
  {
    "EMail": "two@mail.com",
    "Timestamp": "2019-05-25T21:24:06.8273826+02:00",
    "Number": 7397,
    "randomtrash1": "notneeded",
    "randomtrash2": "notneeded",
    "randomtrash3": "notneeded",
    "randomtrash4": "notneeded",
    "randomtrash5": "notneeded",
    "randomtrash6": "notneeded",
    "randomtrash7": "notneeded",
    "randomtrash8": "notneeded",
    "randomtrash9": "notneeded",
    "randomtrash10": "notneeded",
    "randomtrash11": "notneeded",
    "randomtrash12": "notneeded",
    "randomtrash13": "notneeded",
    "randomtrash14": "notneeded",
    "randomtrash15": "notneeded",
    "randomtrash16": "notneeded",
    "randomtrash17": "notneeded",
    "randomtrash18": "notneeded",
    "randomtrash19": "notneeded",
    "randomtrash20": "notneeded",
    "randomtrash21": "notneeded"
  }
]

</code>```

答:
A minimal fix to avoid the maxJsonLength error is to set JavaScriptSerializer.MaxJsonLength = int.MaxValue as shown in this answer to The length of the string exceeds the value set on the maxJsonLength property by Taha Rehman Siddiqui:

```<code>Dim serializer As JavaScriptSerializer = New JavaScriptSerializer()
serializer.MaxJsonLength = Int32.MaxValue
Dim dict As Object = serializer.Deserialize(Of List(Of Object))(JSonFilePath)
</code>```

However, you are currently loading a 600MB file into a 600-1,200MB string which is approaching the .Net maximum string length.  If you file gets somewhat larger, you will start to get out-of-memory exceptions.  A better approach would be to deserialize directly from the file using a streaming solution, however JavaScriptSerializer does not support streaming.  Thus I'd recommend switching to json.net, which does.

First, install Json.NET as shown here.  Next, since you don't seem to want to define an explicit data model for your JSON, create the following static method:

```<code>Public Module JsonExtensions
    Public Function LoadAnonymousType(Of T)(ByVal path as String, ByVal anonymousTypeObject as T, Optional ByVal settings as JsonSerializerSettings = Nothing) as T
        Using streamReader As TextReader = File.OpenText(path)
            Dim serializer = JsonSerializer.CreateDefault(settings)
            return CType(serializer.Deserialize(streamreader, GetType(T)), T)
        End Using
    End Function
End Module
</code>```

What this does is to deserialize the contents of the file whose location is specified by the path argument into a data model of the type specified by the anonymousTypeObject argument.

Now you will be able to deserialize your JSON directly from the file to an array of of anonymous type objects as follows:

```<code>Dim array = JsonExtensions.LoadAnonymousType( _
    FileName, _
    { New With {.Email = CType(Nothing, String), .Timestamp = CType(Nothing, String), .Number = CType(Nothing, Long) }} _
)
For Each item In array
    ' DataGridView1.Rows.Add(item("EMail").ToString, item("Timestamp").ToString, item("Number").ToString)
    Console.WriteLine("Email = {0}, Timestamp = {1}, Number = {2}", item.Email, item.Timestamp, item.Number)
Next
</code>```

Alternatively, you could create an explicit data model as follows:

```<code>Public Class RootObject
    Public Property Email As String
    Public Property Timestamp As String
    Public Property Number As Long
End Class
</code>```

And deserialize as shown in Deserialize JSON from a file:

```<code>Dim list As List(Of RootObject) = Nothing
Using streamReader As TextReader = File.OpenText(FileName)
    list = CType(JsonSerializer.CreateDefault().Deserialize(streamReader, GetType(List(Of RootObject))), List(Of RootObject))
End Using
For Each item In list
    ' DataGridView1.Rows.Add(item("EMail").ToString, item("Timestamp").ToString, item("Number").ToString)
    Console.WriteLine("Email = {0}, Timestamp = {1}, Number = {2}", item.Email, item.Timestamp, item.Number)
Next
</code>```

Demo fiddle here.

Body:
I´d like to deserialize a big JSON File (~600MB) into DataGridView without facing "maxJsonLength" Error.

My Code is working fine for small JSON files. But for bigger JSON files I get the "maxJsonLength" Error. Is there a workaround or an easy way to solve this problem since I am not the most experienced coder?

Private Sub BtnOpenFile_Click(sender As Object, e As EventArgs) Handles BtnOpenFileOld.Click
        OpenFileDialog1.InitialDirectory = "C:\"

        If OpenFileDialog1.ShowDialog = DialogResult.Cancel Then
        End If

        Dim JSonFilePath As String = File.ReadAllText(OpenFileDialog1.FileName)
        LblFilePath.Text = OpenFileDialog1.FileName

        DataGridView1.Rows.Clear()
        DataGridView1.Refresh()

        Dim dict As Object = New JavaScriptSerializer().Deserialize(Of List(Of Object))(JSonFilePath)

        For Each item As Object In dict
            DataGridView1.Rows.Add(item("EMail").ToString, item("Timestamp").ToString, item("Number").ToString)
        Next

    End Sub

My JSON File looks like

[
  {
    "EMail": "one@mail.com",
    "Timestamp": "2019-05-25T21:24:06.799381+02:00",
    "Number": 206074,
    "randomtrash1": "notneeded",
    "randomtrash2": "notneeded",
    "randomtrash3": "notneeded",
    "randomtrash4": "notneeded",
    "randomtrash5": "notneeded",
    "randomtrash6": "notneeded",
    "randomtrash7": "notneeded",
    "randomtrash8": "notneeded",
    "randomtrash9": "notneeded"
  },
  {
    "EMail": "two@mail.com",
    "Timestamp": "2019-05-25T21:24:06.8273826+02:00",
    "Number": 7397,
    "randomtrash1": "notneeded",
    "randomtrash2": "notneeded",
    "randomtrash3": "notneeded",
    "randomtrash4": "notneeded",
    "randomtrash5": "notneeded",
    "randomtrash6": "notneeded",
    "randomtrash7": "notneeded",
    "randomtrash8": "notneeded",
    "randomtrash9": "notneeded",
    "randomtrash10": "notneeded",
    "randomtrash11": "notneeded",
    "randomtrash12": "notneeded",
    "randomtrash13": "notneeded",
    "randomtrash14": "notneeded",
    "randomtrash15": "notneeded",
    "randomtrash16": "notneeded",
    "randomtrash17": "notneeded",
    "randomtrash18": "notneeded",
    "randomtrash19": "notneeded",
    "randomtrash20": "notneeded",
    "randomtrash21": "notneeded"
  }
]

Body:
A minimal fix to avoid the maxJsonLength error is to set JavaScriptSerializer.MaxJsonLength = int.MaxValue as shown in this answer to The length of the string exceeds the value set on the maxJsonLength property by Taha Rehman Siddiqui:

Dim serializer As JavaScriptSerializer = New JavaScriptSerializer()
serializer.MaxJsonLength = Int32.MaxValue
Dim dict As Object = serializer.Deserialize(Of List(Of Object))(JSonFilePath)

However, you are currently loading a 600MB file into a 600-1,200MB string which is approaching the .Net maximum string length.  If you file gets somewhat larger, you will start to get out-of-memory exceptions.  A better approach would be to deserialize directly from the file using a streaming solution, however JavaScriptSerializer does not support streaming.  Thus I'd recommend switching to json.net, which does.

First, install Json.NET as shown here.  Next, since you don't seem to want to define an explicit data model for your JSON, create the following static method:

Public Module JsonExtensions
    Public Function LoadAnonymousType(Of T)(ByVal path as String, ByVal anonymousTypeObject as T, Optional ByVal settings as JsonSerializerSettings = Nothing) as T
        Using streamReader As TextReader = File.OpenText(path)
            Dim serializer = JsonSerializer.CreateDefault(settings)
            return CType(serializer.Deserialize(streamreader, GetType(T)), T)
        End Using
    End Function
End Module

What this does is to deserialize the contents of the file whose location is specified by the path argument into a data model of the type specified by the anonymousTypeObject argument.

Now you will be able to deserialize your JSON directly from the file to an array of of anonymous type objects as follows:

Dim array = JsonExtensions.LoadAnonymousType( _
    FileName, _
    { New With {.Email = CType(Nothing, String), .Timestamp = CType(Nothing, String), .Number = CType(Nothing, Long) }} _
)
For Each item In array
    ' DataGridView1.Rows.Add(item("EMail").ToString, item("Timestamp").ToString, item("Number").ToString)
    Console.WriteLine("Email = {0}, Timestamp = {1}, Number = {2}", item.Email, item.Timestamp, item.Number)
Next

Alternatively, you could create an explicit data model as follows:

Public Class RootObject
    Public Property Email As String
    Public Property Timestamp As String
    Public Property Number As Long
End Class

And deserialize as shown in Deserialize JSON from a file:

Dim list As List(Of RootObject) = Nothing
Using streamReader As TextReader = File.OpenText(FileName)
    list = CType(JsonSerializer.CreateDefault().Deserialize(streamReader, GetType(List(Of RootObject))), List(Of RootObject))
End Using
For Each item In list
    ' DataGridView1.Rows.Add(item("EMail").ToString, item("Timestamp").ToString, item("Number").ToString)
    Console.WriteLine("Email = {0}, Timestamp = {1}, Number = {2}", item.Email, item.Timestamp, item.Number)
Next

Demo fiddle here.


问:
Is it possible insert a file into the input (type file) from url?
Is it possible insert a file into the input (type file) from url or from url add to FileList?</p>

```<code><input type="file" id="image" hidden>
</code>```

答:
Not directly.

Windows does allow pasting in an URL in the Open File dialog, but it will download the file to a temporary directory on the client machine and then re-upload it onto your server.

You may want to look into something like https://uppy.io/ if you need both uploading and transloading.

Body:
Is it possible insert a file into the input (type file) from url or from url add to FileList?

<input type="file" id="image" hidden>


问:
Update row in TABLE1 using value from another row in TABLE1 to lookup value in TABLE2
I have a table as follows

TABLE1

```<code>Id   UserId  Type       Value
1    AAA     companyid  123
2    AAA     branchid
3    BBB     companyid  124
4    BBB     branchid
5    CCC     companyid  125
6    CCC     branchid
</code>```

and TABLE2

```<code>BranchId   CompanyId   Name
1          123         RedBranch
2          123         YellowBranch
3          123         GreenBranch
4          124         SouthBranch
5          125         NorthBranch
</code>```

I need to update Type in TABLE1 WHERE Type = 'branchid' using the value in Type = 'companyid' for the same UserId.  Once I have the correct 'companyid' I want to use the following SELECT to get the TOP BranchId from TABLE2

```<code>SELECT TOP 1 Id
FROM TABLE2
WHERE CompanyId = (correct companyid from TABLE1)
ORDER BY Id DESC
</code>```

How can I achieve this in one Update statement?

答:
Here's a stab at it:</p>

```<code>update T1
set Value = (select max(BranchId) from Table2 where CompanyId = T1a.value)
from Table1 T1
inner join Table1 T1a on T1a.UserId = T1.UserId and T1a.Type = 'companyid'
where T1.Type = 'branchid'
</code>```

Body:
I have a table as follows

TABLE1

Id   UserId  Type       Value
1    AAA     companyid  123
2    AAA     branchid
3    BBB     companyid  124
4    BBB     branchid
5    CCC     companyid  125
6    CCC     branchid

and TABLE2

BranchId   CompanyId   Name
1          123         RedBranch
2          123         YellowBranch
3          123         GreenBranch
4          124         SouthBranch
5          125         NorthBranch

I need to update Type in TABLE1 WHERE Type = 'branchid' using the value in Type = 'companyid' for the same UserId.  Once I have the correct 'companyid' I want to use the following SELECT to get the TOP BranchId from TABLE2

SELECT TOP 1 Id
FROM TABLE2
WHERE CompanyId = (correct companyid from TABLE1)
ORDER BY Id DESC

How can I achieve this in one Update statement?

Body:
Here's a stab at it:

update T1
set Value = (select max(BranchId) from Table2 where CompanyId = T1a.value)
from Table1 T1
inner join Table1 T1a on T1a.UserId = T1.UserId and T1a.Type = 'companyid'
where T1.Type = 'branchid'


问:
Are there situations when self-assignment is useful?
It is commonly known that when implementing an assignment operator one has to protect against self-assignment, at least when the class has non-POD members. Usually it is (or is equivalent to):

```<code>Foo& operator=(const Foo& other)
{
  if (&other == this)
     return *this;
  ... // Do copy
}
</code>```

What were the reasons for not inserting the self-assignment protection automatically? Are there use cases when self-assignment does something non-trivial and practically useful?

```<code>Foo& operator=(const Foo& other)
{
  if (&other == this)
  {
    // Do something non-trivial
  }
  else
  {
    // Do copy
  }
  return *this;
}
</code>```

To summarize the answers and discussion by now

Looks like non-trivial self-assignment can never be really useful. The only option proposed was to put an assert there in order to detect some logical errors. But there are quite legitimate self-assignment cases like a = std::min(a, b), so even this option is highly dubious.

But there are two possible implementations of a trivial self-assignment:

Do nothing if &other == this. Always work, though may have negative performance impact due to an extra branching. But in a user-defined assignment operator the test must be almost always explicitly made.

Copy each member to itself. This is what is done by default. If the members use default assignment operators as well, it may be faster, because doesn't requre an extra branching.

I still don't see why the C++ standard could not guarantee that in a user-defined assignment operator &other != this. If you want no branching, use the default operator. If you are redefining the operator, some test is needed anyway...

答:
Self-assignment protection is only necessary for types where the code being skipped is dangerous when applied to itself. Consider the case where you have a user-provided assignment operator because each individual object has some kind of identifier, which you don't want to copy. Well, you can "copy" the other values just fine in self-assignment cases. So inserting an invisible self-assignment test is just adding a pointless and potentially costly conditional branch.

So it's not about self-assignment being useful; it's about self-assignment not always needing protection.

Furthermore, C++ generally doesn't like adding code like that to your code without you explicitly asking for it. It's typically done in terms of whole functions, not part of functions. Even destructor calls at the end of blocks are something you asked for when you put the object to be destroyed on the stack.

Body:
It is commonly known that when implementing an assignment operator one has to protect against self-assignment, at least when the class has non-POD members. Usually it is (or is equivalent to):

Foo& operator=(const Foo& other)
{
  if (&other == this)
     return *this;
  ... // Do copy
}

What were the reasons for not inserting the self-assignment protection automatically? Are there use cases when self-assignment does something non-trivial and practically useful?

Foo& operator=(const Foo& other)
{
  if (&other == this)
  {
    // Do something non-trivial
  }
  else
  {
    // Do copy
  }
  return *this;
}

To summarize the answers and discussion by now

Looks like non-trivial self-assignment can never be really useful. The only option proposed was to put an assert there in order to detect some logical errors. But there are quite legitimate self-assignment cases like a = std::min(a, b), so even this option is highly dubious.

But there are two possible implementations of a trivial self-assignment:

Do nothing if &other == this. Always work, though may have negative performance impact due to an extra branching. But in a user-defined assignment operator the test must be almost always explicitly made.

Copy each member to itself. This is what is done by default. If the members use default assignment operators as well, it may be faster, because doesn't requre an extra branching.

I still don't see why the C++ standard could not guarantee that in a user-defined assignment operator &other != this. If you want no branching, use the default operator. If you are redefining the operator, some test is needed anyway...


问:
Executing unix shell commands using PHP
A text box will be used to capture the command. I've been told that I have to use the exec() function to execute UNIX shell commands.

Something like this, user types ls in the text box. The exec() function will execute the UNIX command and the command will be displayed on the web page.

What I want to know how will I get the output of the shell command and display in the web browser using PHP.

I don't know where to start since I'm very new to PHP.

I'm using Ubuntu.

答:
```<code>exec(escapeshellarg($userSuppliedInput), $output);

echo $output;
</code>```

Title: Executing unix shell commands using PHP


问:
Android Studio replacing my xml layout (bug)
I was previously working on a 1 month project using Android Studio. My xml layout was all well and good until I opened it up today and had the following as my xml code:

As you can see the preview is showing the correct data, but the code is not.

What happened, how can I retrieve my original code?

Some of the files were not backed up on a VCS.

答:
You can check the android studio local history if your files were not backed up:

Right click on your app folder - select "Local History" and "show history" to see your latest file that got changed