问:
How do I make fonts of different sizes vertically centered in html spans?
I'm making a pitch controller:

```<code><div id="pitchWrapper">
  <span id="pitchButtons">-</span>
  <span id="pitchValue">0</span>
  <span id="pitchButtons">+</span>
</div>
</code>```

I want the minus, plus, and pitch value all to be vertically centered. I want the plus and minus to be a bigger font-size than the pitch value.

It works reasonably well when I set the font sizes to all be the same...

...but when I try to make the pitch buttons bigger, they align below center:

Here's my css:

```<code>#pitchWrapper {
  display: flex;
  align-items: center;
  vertical-align: middle;
}

#pitchValue {
  font-size: 200%;
}

#pitchButtons {
  font-size: 300%;
}
</code>```

How can I increase the font size of the pitch buttons while keeping everything vertically centered please?

Thank you.

答:
You can use Hex code for Math Symbols.

#pitchWrapper {
  display: flex;
  align-items: center;
}

#pitchValue {
  font-size: 150%;
}

.pitchButtons {
  font-size: 300%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="pitchWrapper">
  <span class="pitchButtons">−</span>
  <span id="pitchValue">0</span>
  <span class="pitchButtons">+</span>
</div></code>```

Body:
I'm making a pitch controller:

  -
  0
  +

I want the minus, plus, and pitch value all to be vertically centered. I want the plus and minus to be a bigger font-size than the pitch value.

It works reasonably well when I set the font sizes to all be the same...

...but when I try to make the pitch buttons bigger, they align below center:

Here's my css:

#pitchWrapper {
  display: flex;
  align-items: center;
  vertical-align: middle;
}

#pitchValue {
  font-size: 200%;
}

#pitchButtons {
  font-size: 300%;
}

How can I increase the font size of the pitch buttons while keeping everything vertically centered please?

Thank you.

Body:
You can use Hex code for Math Symbols.

#pitchWrapper {
  display: flex;
  align-items: center;
}

#pitchValue {
  font-size: 150%;
}

.pitchButtons {
  font-size: 300%;
}

<div id="pitchWrapper">
  <span class="pitchButtons">&#8722;</span>
  <span id="pitchValue">0</span>
  <span class="pitchButtons">&#x2B;</span>
</div>


来源: stackexchange

问:
Python: Why am I receiving an AttributeError: __enter__
I am not reassigning the open keyword yet still receive this error. Any suggestions or direction to fix my error?

```<code> with tempfile.mkdtemp() as test_dir:
        print(test_dir)
</code>```

AttributeError: __enter__

I am also new to python and I am having a hard time understanding these concepts.

答:
Though I see some of you have answered the problem I would like to add my answer for better clarity.

correct approach:

```<code>       with open(fullname, "r") as file:
            content = file.read()
</code>```

incorrect approach:

```<code>       with open(fullname, "r").read() as file:

</code>```

Reason: when you add .read() then its string and not file handler and string is not having built in __enter__ and __exit__ methods and where as file handler has two built-in methods __enter__ and __exit__

ContentLicense: CC BY-SA 4.0

Body:
I am not reassigning the open keyword yet still receive this error. Any suggestions or direction to fix my error?

 with tempfile.mkdtemp() as test_dir:
        print(test_dir)

AttributeError: __enter__

I am also new to python and I am having a hard time understanding these concepts.

Body:
Though I see some of you have answered the problem I would like to add my answer for better clarity.

correct approach:

       with open(fullname, "r") as file:
            content = file.read()

incorrect approach:

       with open(fullname, "r").read() as file:

Reason: when you add .read() then its string and not file handler and string is not having built in __enter__ and __exit__ methods and where as file handler has two built-in methods __enter__ and __exit__


问:
.bashrc at ssh login
When I ssh into my ubuntu-box running Hardy 8.04, the environment variables in my .bashrc are not set.

If I do a source .bashrc, the variables are properly set, and all is well.

How come .bashrc isn't run at login?

答:
I had similar situation like Hobhouse. I wanted to use the command

```<code>ssh myhost.com 'some_command'
</code>```

where some_command exists in /var/some_location.

I tried to append /var/some_location to the PATH environment variable by editing $HOME/.bashrc but that wasn't working. Because per default, .bashrc (on Ubuntu 10.4 LTS) exits early due to this piece of code:

```<code># If not running interactively, don't do anything
[ -z "$PS1" ] && return
</code>```

Meaning if you want to change the environment for the ssh non-login shell, you should add code above that line.

Title: .bashrc at ssh login

Body:
I had similar situation like Hobhouse. I wanted to use the command

ssh myhost.com 'some_command'

where some_command exists in /var/some_location.

I tried to append /var/some_location to the PATH environment variable by editing $HOME/.bashrc but that wasn't working. Because per default, .bashrc (on Ubuntu 10.4 LTS) exits early due to this piece of code:

# If not running interactively, don't do anything
[ -z "$PS1" ] && return

Meaning if you want to change the environment for the ssh non-login shell, you should add code above that line.


问:
ToString("C") does not show expected result in VB
The input changes to $0.00 whenever i try this coding:

```<code>Private Sub btnEnt_Click(sender As Object, e As EventArgs) Handles btnEnt.Click

    Dim result As String

    Dim earn As Decimal

    txtEarning.Text = earn.ToString("C")

    result = txtFName.Text & " " & txtLName.Text & " Worked" & vbCrLf

    result &= nudHr.Value & " Hrs today"

    result &= " and his earning is " & txtEarning.Text

    txtRes.Text = result

End Sub
</code>```

instead of displaying input value, the value automatically converts to $0.00

答:
I think you might need this:

```<code>Dim earn as Decimal = nudHr.Value * 20
</code>```

If your person earns 20 dollars an hour

Body:
The input changes to $0.00 whenever i try this coding:

Private Sub btnEnt_Click(sender As Object, e As EventArgs) Handles btnEnt.Click

    Dim result As String

    Dim earn As Decimal

    txtEarning.Text = earn.ToString("C")

    result = txtFName.Text & " " & txtLName.Text & " Worked" & vbCrLf

    result &= nudHr.Value & " Hrs today"

    result &= " and his earning is " & txtEarning.Text

    txtRes.Text = result

End Sub

instead of displaying input value, the value automatically converts to $0.00

Body:
I think you might need this:

Dim earn as Decimal = nudHr.Value * 20

If your person earns 20 dollars an hour


问:
XCTest - Unable to understand / implement expectations in unit tests (to test aysnc code)
(NOTE - I'm developing for macOS, so please ... iOS-specific advice won't help me)

What I'm trying to do:
I have an app component that performs a short task on a background thread, and then, if certain conditions are met, asynchronously sends out a notification on the main thread.

NOTE - I am not using NSNotification in my app code. I am using my own custom notification mechanism. So, any solution related to NSNotification is not applicable to me.

I'm writing a unit test for the above mentioned app component, and simply want to check if that notification was indeed sent or not. My test has to be able to wait a second or so to give the notification time to reach its subscriber/observer, before performing an assertion.

I want to be able to test both possible cases in my tests: Both are normal scenarios.

Notification was sent.

Notification was not sent.

After hours of reading several docs and code samples, I don't understand how to achieve this with expectations.

I just want to wait one second in my test. Is it really this complicated ?

sleep() doesn't work

DispatchQueue.main.asyncAfter(time) doesn't work

Timer doesn't work

Here's the app component that needs to be tested, and its unit test:

In the below code, where do I put expectation.fulfill() ???

```<code>class ComponentBeingTested {

    func methodBeingTested() {

        doSomeWork()
        if certainConditionsAreMet {
             DispatchQueue.main.async {sendOutNotification()}
        }
    }
}

...

class UnitTestForComponentBeingTested: XCTestCase {

    let objectBeingTested = ComponentBeingTested()

    func testMethodBeingTested() {

          let expectation = self.expectation(description: "Notification was sent")

          // Call the code being tested
          objectBeingTested.methodBeingTested()

          // How do I do this with expectations ??? Where does expectation.fulfill() go ?
          waitForOneSecond()

          XCTAssertTrue(notificationSent)      // Assume the value of notificationSent is available

    }
}
</code>```

答:
Ok, after a lot of trial and error, this works great for me:

Description: I basically created a helper function in my test case class that contains all the boilerplate expectation/wait code. It does the following:

1 - Creates an expectation (i.e. XCTestExpectation) as a formality.

2 - Calls my (arbitrary) test case assertion code (passed in as a closure) on some global queue thread after the intended delay period. Once this assertion code has completed, the expectation is fulfilled (again, a formality).

3 - Waits on the expectation by calling XCTestCase.wait(timeout). This ensures that the main thread / run loop is kept alive while my assertion code completes on this other thread.

Then, in my test case, I simply invoke that helper function, providing it with a wait period and some code to execute (i.e. my assertions).

This way, I have a simple and expressive reusable function that hides all the excessive ugliness of expectations which I never thought necessary in the first place.

I can put this helper in a base class like MyAppTestCase: XCTestCase, so that it is available to all my test case classes.

NOTE - This solution can be enhanced and made even more generic/reusable, but as of now, this is quite sufficient for the purposes of the originally posted problem.

Solution:

```<code>class ComponentBeingTested {

    func methodBeingTested() {

        doSomeWork()
        if certainConditionsAreMet {
             DispatchQueue.main.async {sendOutNotification()}
        }
    }
}

...

class UnitTestForComponentBeingTested: XCTestCase {

    let objectBeingTested = ComponentBeingTested()

    // Helper function that uses expectation/wait to execute arbitrary
    // test code (passed in as a closure) after some delay period.
    func executeAfter(_ timeSeconds: Double, _ work: (@escaping () -> Void)) {

        let theExpectation = expectation(description: "some expectation")

        // Execute work() after timeSeconds seconds
        DispatchQueue.global(qos: .userInteractive).asyncAfter(deadline: .now() + timeSeconds) {

            // The call to work() will execute my test assertions
            work()

            // As a formality, fulfill the expectation
            theExpectation.fulfill()
        }

        // Wait for (timeSeconds + 1) seconds to give the work() call
        // some time to perform the assertions
        wait(for: [theExpectation], timeout: timeSeconds + 1)
    }

    func testMethodBeingTested() {

          // Call the code being tested
          objectBeingTested.methodBeingTested()

          // Call the helper function above, to do the waiting before executing
          // the assertions
          executeAfter(0.5) {

              // Assume the value of notificationSent is computed elsewhere
              // and is available to assert at this point
              XCTAssertTrue(notificationSent)
          }
    }
}
</code>```

Body:
(NOTE - I'm developing for macOS, so please ... iOS-specific advice won't help me)

What I'm trying to do:
I have an app component that performs a short task on a background thread, and then, if certain conditions are met, asynchronously sends out a notification on the main thread.

NOTE - I am not using NSNotification in my app code. I am using my own custom notification mechanism. So, any solution related to NSNotification is not applicable to me.

I'm writing a unit test for the above mentioned app component, and simply want to check if that notification was indeed sent or not. My test has to be able to wait a second or so to give the notification time to reach its subscriber/observer, before performing an assertion.

I want to be able to test both possible cases in my tests: Both are normal scenarios.

Notification was sent.

Notification was not sent.

After hours of reading several docs and code samples, I don't understand how to achieve this with expectations.

I just want to wait one second in my test. Is it really this complicated ?

sleep() doesn't work

DispatchQueue.main.asyncAfter(time) doesn't work

Timer doesn't work

Here's the app component that needs to be tested, and its unit test:

In the below code, where do I put expectation.fulfill() ???

class ComponentBeingTested {

    func methodBeingTested() {

        doSomeWork()
        if certainConditionsAreMet {
             DispatchQueue.main.async {sendOutNotification()}
        }
    }
}

...

class UnitTestForComponentBeingTested: XCTestCase {

    let objectBeingTested = ComponentBeingTested()

    func testMethodBeingTested() {

          let expectation = self.expectation(description: "Notification was sent")

          // Call the code being tested
          objectBeingTested.methodBeingTested()

          // How do I do this with expectations ??? Where does expectation.fulfill() go ?
          waitForOneSecond()

          XCTAssertTrue(notificationSent)      // Assume the value of notificationSent is available

    }
}

Body:
Ok, after a lot of trial and error, this works great for me:

Description: I basically created a helper function in my test case class that contains all the boilerplate expectation/wait code. It does the following:

1 - Creates an expectation (i.e. XCTestExpectation) as a formality.

2 - Calls my (arbitrary) test case assertion code (passed in as a closure) on some global queue thread after the intended delay period. Once this assertion code has completed, the expectation is fulfilled (again, a formality).

3 - Waits on the expectation by calling XCTestCase.wait(timeout). This ensures that the main thread / run loop is kept alive while my assertion code completes on this other thread.

Then, in my test case, I simply invoke that helper function, providing it with a wait period and some code to execute (i.e. my assertions).

This way, I have a simple and expressive reusable function that hides all the excessive ugliness of expectations which I never thought necessary in the first place.

I can put this helper in a base class like MyAppTestCase: XCTestCase, so that it is available to all my test case classes.

NOTE - This solution can be enhanced and made even more generic/reusable, but as of now, this is quite sufficient for the purposes of the originally posted problem.

Solution:

class ComponentBeingTested {

    func methodBeingTested() {

        doSomeWork()
        if certainConditionsAreMet {
             DispatchQueue.main.async {sendOutNotification()}
        }
    }
}

...

class UnitTestForComponentBeingTested: XCTestCase {

    let objectBeingTested = ComponentBeingTested()

    // Helper function that uses expectation/wait to execute arbitrary
    // test code (passed in as a closure) after some delay period.
    func executeAfter(_ timeSeconds: Double, _ work: (@escaping () -> Void)) {

        let theExpectation = expectation(description: "some expectation")

        // Execute work() after timeSeconds seconds
        DispatchQueue.global(qos: .userInteractive).asyncAfter(deadline: .now() + timeSeconds) {

            // The call to work() will execute my test assertions
            work()

            // As a formality, fulfill the expectation
            theExpectation.fulfill()
        }

        // Wait for (timeSeconds + 1) seconds to give the work() call
        // some time to perform the assertions
        wait(for: [theExpectation], timeout: timeSeconds + 1)
    }

    func testMethodBeingTested() {

          // Call the code being tested
          objectBeingTested.methodBeingTested()

          // Call the helper function above, to do the waiting before executing
          // the assertions
          executeAfter(0.5) {

              // Assume the value of notificationSent is computed elsewhere
              // and is available to assert at this point
              XCTAssertTrue(notificationSent)
          }
    }
}


问:
How to send back json data with status(204).send() without refreshing the page in nodejs?
I am working in nodejs project with handlebars. I am a beginner in nodejs. I just want to send back some data(it could be a json object) to handlebars template after POST request on the same page without refreshing the page. But I don't know how to do this.

This is the part of code but not the entire code:

```<code>router.post('/post/team', (req, res)=>{
    const newTeamPostQuery = newteampost({
        totalOvers: req.body.totalOvers,
        currentMatch: true,
        teamOne: [
            {
                name: req.body.teamOne,
                over: 0
            }
        ],
        teamTwo: [
            {
                name: req.body.teamTwo,
                over: 0
            }
        ]
    });

    newTeamPostQuery.save().then(savedPost=>{
        res.status(204).send({data: savedPost});
    }).catch(error=>{
        console.log(error);
    });
});
</code>```

I don't want to refresh the page. When I use this res.json({data: newTeamPostQuery}); then it refreshes the page to this /post/team route and show the json data on the page.

I am using handlebars to show data like this:
{{#if data.currentMatch}} data.totalOvers {{else}} Overs {{/if}}

I am using mongodb.

答:
Don't do form post request from handlebars template. Include JS file in your handlebars template and you need to call ajax post to that URI '/post/team' and you will get back the response in your ajax response. That's how your page won't refresh and you will get data without refreshing the page.

Using jQuery Ajax Post request.

```<code>//In your js code collect value of 'totalOvers','teamOne' and 'teamTwo' from HTML
//field using jquery with the help of HTML ID and call the ajax as following

$.ajax({
            url: '/post/team',
            type: 'post',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify({totalOvers: '5', teamOne: '2', teamTwo:'4'}),
            success: function (response) {
               //you will get server response here
               //do, what you need to do
            },
        });
</code>```

Body:
I am working in nodejs project with handlebars. I am a beginner in nodejs. I just want to send back some data(it could be a json object) to handlebars template after POST request on the same page without refreshing the page. But I don't know how to do this.

This is the part of code but not the entire code:

router.post('/post/team', (req, res)=>{
    const newTeamPostQuery = newteampost({
        totalOvers: req.body.totalOvers,
        currentMatch: true,
        teamOne: [
            {
                name: req.body.teamOne,
                over: 0
            }
        ],
        teamTwo: [
            {
                name: req.body.teamTwo,
                over: 0
            }
        ]
    });

    newTeamPostQuery.save().then(savedPost=>{
        res.status(204).send({data: savedPost});
    }).catch(error=>{
        console.log(error);
    });
});

I don't want to refresh the page. When I use this res.json({data: newTeamPostQuery}); then it refreshes the page to this /post/team route and show the json data on the page.

I am using handlebars to show data like this:
{{#if data.currentMatch}} data.totalOvers {{else}} Overs {{/if}}

I am using mongodb.

Body:
Don't do form post request from handlebars template. Include JS file in your handlebars template and you need to call ajax post to that URI '/post/team' and you will get back the response in your ajax response. That's how your page won't refresh and you will get data without refreshing the page.

Using jQuery Ajax Post request.

//In your js code collect value of 'totalOvers','teamOne' and 'teamTwo' from HTML
//field using jquery with the help of HTML ID and call the ajax as following

$.ajax({
            url: '/post/team',
            type: 'post',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify({totalOvers: '5', teamOne: '2', teamTwo:'4'}),
            success: function (response) {
               //you will get server response here
               //do, what you need to do
            },
        });


问:
Blank Screen on right scroll
On the right side you can a see few pixels of space:

Does anyone know how to remove it? I think it's because of animations I have added with "aos" library. I have already had this error without animations, but I fixed it with this code:

```<code>*, *::before, *::after {
    box-sizing: border-box;
}
</code>```

This is the link for the code so you can preview the page:

https://jsfiddle.net/5rq8grcL/

*,
*::before,
*::after {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  font-family: 'IBM Plex Sans Condensed', sans-serif;
  background-image: url("/assets/images/masaze.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  height: 100%;
  width: 100%;
  scroll-behavior: smooth;
  animation: fadeEffect 1s;
}

@keyframes fadeEffect {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

#navbar-list {
  list-style-type: none;
  text-align: center;
  margin: 0;
  overflow: hidden;
  background-color: #000;
  width: 100%;
  opacity: 0.9;
  position: fixed;
  z-index: 1;
}

#navbar-list li {
  text-align: justify;
  display: inline;
}

#navbar-list li a {
  color: white;
  text-decoration: none;
  display: inline-block;
}

#navbar-list li a:hover {
  color: #a0c2d5;
  transition: .5s;
}

.pocetna {
  font-size: 1.7rem;
  padding: 25px 20px;
  float: left;
}

.linkovi {
  padding: 35px 20px;
  position: relative;
  right: 180px;
}

.linkovi:active {
  color: black;
  background-color: white;
}

#main {
  text-align: center;
  padding-top: 15%;
}

#main h1 {
  font-size: 4.5em;
  text-shadow: 1px 1px 1px #000000;
}

#main h3 {
  font-size: 17pt;
}

hr {
  width: 615px;
  opacity: .2;
}

.button {
  height: 50px;
  font-size: 20px;
  margin-top: 20px;
  cursor: pointer;
  padding: 10px;
  outline: none;
  text-decoration: none;
  border: none;
  border-radius: 3%;
}

.button a {
  color: black;
  text-decoration: none;
}

.button:hover {
  background-color: #a0c2d5;
  transition: .5s;
}

section {
  position: relative;
  margin-top: -5px;
}

#video {
  background-color: rgba(20, 25, 25, 0.5);
  min-width: 100%;
  min-height: 100%;
  margin-top: 580px;
  z-index: 0;
  position: relative;
}

#section1 {
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
  color: #f1f1f1;
  width: 100%;
  padding: 200px;
  bottom: 0;
  left: 0;
}

#section1 h3 {
  font-size: 25pt;
}

#section1 p {
  font-size: 18pt;
  letter-spacing: 1px;
  text-shadow: 1px 1px gray;
}

#contact {
  background: rgba(0, 0, 0, 0.2);
  position: absolute;
  width: 100%;
  height: 500px;
  display: table;
  table-layout: fixed;
  border-spacing: 10px;
  margin-top: 50px;
}

#section2 {
  font-size: 25pt;
  text-align: center;
  background: rgba(0, 0, 0, 0.2);
  height: 100%;
  background-image: url("/assets/images/masaze.jpg");
}

#section2 h3 {
  margin: 0;
  padding: 20px 0;
}

.sectionc {
  display: table-cell;
}

.sectionc a {
  color: black;
  text-decoration: none;
  padding: 5px;
}

.sectionc a:hover {
  transition: 0.5s;
  color: #a0c2d5;
}

#map {
  width: 700px;
  height: 400px;
  margin: 50px auto;
}

#section3 {
  text-align: center;
  font-size: 25pt;
  background: rgba(0, 0, 0, 0.5);
  background-image: url("/assets/images/proba.jpg");
  height: 705px;
}

.kdn {
  margin: 0;
  padding: 20px;
  color: white;
}

#footer {
  background-color: black;
  color: white;
  height: 80px;
}

#footer p {
  margin: -5px;
  text-align: center;
  padding: 30px;
}

#footer p a {
  color: white;
  text-decoration: none;
  padding-left: 10px;
}

#footer p a:hover {
  color: #a0c2d5;
  transition: .5s;
}

span {
  color: black;
  transition: 1.5s;
}

span:hover {
  color: white;
  transition: 1.5s;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Masaže Gligorijević</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" media="screen" href="/stylesheets/main.css">
  <link rel="icon" href="/assets/images/logo.png">
  <link href="https://cdn.rawgit.com/michalsnik/aos/2.1.1/dist/aos.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:400,700" rel="stylesheet">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.9/css/all.css" integrity="sha384-5SOiIsAziJl6AWe0HWRKTXlfcSHKmYV4RBF18PPJ173Kzn7jzMyFuTtk8JA7QQG1" crossorigin="anonymous">
  <script src="/assets/js/main.js"></script>
</head>

<body>
  <nav>
    <div id="navbar">
      <ul id="navbar-list">
        <li>
          <img src="/assets/images/logo icon.ico" width="40" height="30" style="padding-right:10px;">Masaže Gligorijević
        </li>
        <li class="linkovil">Početna</li>
        <li class="linkovil">O nama</li>
        <li>Kontakt</li>
        <li>Kako do nas</li>
      </ul>
    </div>
  </nav>

  <header>
    <div id="main">
      <h1>Masaže Gligorijević</h1>
      <h3>Ulaganjem u svoje zdravlje, ulažete u kvalitet sopstvenog života.</h3>
      <hr>
      <button class="button"><i class="fas fa-play"></i> Rezervišite Odmah</button>
    </div>
  </header>

  <section>
    <video autoplay muted loop id="video">
            <source src="/assets/images/klip.mp4" type="video/mp4">
        </video>

    <div id="section1" data-aos="fade-right" data-aos-duration="1500" data-aos-easing="linear">
      <h3>O nama</h3>
      <p>
        Profesionalni maser i specijalno usavršeni fizioterapeut čija veština pokazuje odlične rezultate kod klijenata. <br><br> Naš salon je opremljen profesionalnom opremom. Masaže se obavljaju na stolovima za masažu.<br><br>Kompletnom uživanju doprinose
        prijatni zvuci muzike i mirisi aromatičnih ulja.<br> NAŠI klijenti odlaze uz pravilo: NAKON MASAŽE OPET IMAM OSMEH!
      </p>
    </div>
  </section>

  <section id="section2">
    <h3>Kontakt</h3>
    <div id="contact">
      <div id="sectionc" data-aos="fade-right" data-aos-duration="1500" data-aos-easing="linear">
        <h4>Zakažite vaš termin već sada!</h4>
        <p><i class="fas fa-location-arrow"></i> Adresa: Ljubiše Uroševića 6/21, Jagodina</p>
        <p><i class="fas fa-mobile"></i> Tel: 060 078 2880</p>
        <p><i class="fas fa-at"></i> Email: milosgliga92@gmail.com</a>
        </p>
      </div>

      <div class="sectionc" data-aos="fade-left" data-aos-duration="1500" data-aos-easing="linear">
        <h4>Pratite nas na društvenim mrežama!</h4>
        <p><i class="fab fa-facebook-f"></i> Facebook</p>
        <p><i class="fab fa-instagram"></i>Instagram</p>
      </div>
    </div>
  </section>

  <div id="section3" data-aos="fade-right" data-aos-duration="1000" data-aos-easing="linear">
    <h3 class="kdn">Kako do nas</h3>
    <div id="map">

    </div>
  </div>

  <footer>
    <div id="footer">
      <p>
        © 2018 <span>  Đorđe Gligorijević  </span> All Rights Reserved
        <i class="fab fa-facebook-f"></i>
        <i class="fab fa-twitter"></i>
        <i class="fab fa-instagram"></i>
        <i class="fab fa-linkedin-in"></i>
      </p>
    </div>
  </footer>

  <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAvHllMfDUDEVM_GtdkQ6_hyj4wMJ2vVxM&callback=initMap"></script>
  <script src="https://cdn.rawgit.com/michalsnik/aos/2.1.1/dist/aos.js"></script>
  <script>
    AOS.init();
  </script>

</body>

</html></code>```

答:
100% work. Try this</p>

```<code><script>$('[data-aos]').parent().addClass('hideOverflowOnMobile');</script>
<style>
@media (max-width: 768px) {
    .hideOverflowOnMobile {
        overflow: hidden;
    }
}
</style>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Blank Screen on right scroll

Body:
On the right side you can a see few pixels of space:

Does anyone know how to remove it? I think it's because of animations I have added with "aos" library. I have already had this error without animations, but I fixed it with this code:

*, *::before, *::after {
    box-sizing: border-box;
}

This is the link for the code so you can preview the page:

https://jsfiddle.net/5rq8grcL/

*,
*::before,
*::after {
  box-sizing: border-box;
}

html,
body {
  margin: 0;
  padding: 0;
  font-family: 'IBM Plex Sans Condensed', sans-serif;
  background-image: url("/assets/images/masaze.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  height: 100%;
  width: 100%;
  scroll-behavior: smooth;
  animation: fadeEffect 1s;
}

@keyframes fadeEffect {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

#navbar-list {
  list-style-type: none;
  text-align: center;
  margin: 0;
  overflow: hidden;
  background-color: #000;
  width: 100%;
  opacity: 0.9;
  position: fixed;
  z-index: 1;
}

#navbar-list li {
  text-align: justify;
  display: inline;
}

#navbar-list li a {
  color: white;
  text-decoration: none;
  display: inline-block;
}

#navbar-list li a:hover {
  color: #a0c2d5;
  transition: .5s;
}

.pocetna {
  font-size: 1.7rem;
  padding: 25px 20px;
  float: left;
}

.linkovi {
  padding: 35px 20px;
  position: relative;
  right: 180px;
}

.linkovi:active {
  color: black;
  background-color: white;
}

#main {
  text-align: center;
  padding-top: 15%;
}

#main h1 {
  font-size: 4.5em;
  text-shadow: 1px 1px 1px #000000;
}

#main h3 {
  font-size: 17pt;
}

hr {
  width: 615px;
  opacity: .2;
}

.button {
  height: 50px;
  font-size: 20px;
  margin-top: 20px;
  cursor: pointer;
  padding: 10px;
  outline: none;
  text-decoration: none;
  border: none;
  border-radius: 3%;
}

.button a {
  color: black;
  text-decoration: none;
}

.button:hover {
  background-color: #a0c2d5;
  transition: .5s;
}

section {
  position: relative;
  margin-top: -5px;
}

#video {
  background-color: rgba(20, 25, 25, 0.5);
  min-width: 100%;
  min-height: 100%;
  margin-top: 580px;
  z-index: 0;
  position: relative;
}

#section1 {
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
  color: #f1f1f1;
  width: 100%;
  padding: 200px;
  bottom: 0;
  left: 0;
}

#section1 h3 {
  font-size: 25pt;
}

#section1 p {
  font-size: 18pt;
  letter-spacing: 1px;
  text-shadow: 1px 1px gray;
}

#contact {
  background: rgba(0, 0, 0, 0.2);
  position: absolute;
  width: 100%;
  height: 500px;
  display: table;
  table-layout: fixed;
  border-spacing: 10px;
  margin-top: 50px;
}

#section2 {
  font-size: 25pt;
  text-align: center;
  background: rgba(0, 0, 0, 0.2);
  height: 100%;
  background-image: url("/assets/images/masaze.jpg");
}

#section2 h3 {
  margin: 0;
  padding: 20px 0;
}

.sectionc {
  display: table-cell;
}

.sectionc a {
  color: black;
  text-decoration: none;
  padding: 5px;
}

.sectionc a:hover {
  transition: 0.5s;
  color: #a0c2d5;
}

#map {
  width: 700px;
  height: 400px;
  margin: 50px auto;
}

#section3 {
  text-align: center;
  font-size: 25pt;
  background: rgba(0, 0, 0, 0.5);
  background-image: url("/assets/images/proba.jpg");
  height: 705px;
}

.kdn {
  margin: 0;
  padding: 20px;
  color: white;
}

#footer {
  background-color: black;
  color: white;
  height: 80px;
}

#footer p {
  margin: -5px;
  text-align: center;
  padding: 30px;
}

#footer p a {
  color: white;
  text-decoration: none;
  padding-left: 10px;
}

#footer p a:hover {
  color: #a0c2d5;
  transition: .5s;
}

span {
  color: black;
  transition: 1.5s;
}

span:hover {
  color: white;
  transition: 1.5s;
}

<!DOCTYPE html>

  <meta charset="utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Masaže Gligorijević</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" type="text/css" media="screen" href="/stylesheets/main.css">
  <link rel="icon" href="/assets/images/logo.png">
  <link href="https://cdn.rawgit.com/michalsnik/aos/2.1.1/dist/aos.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=IBM+Plex+Sans+Condensed:400,700" rel="stylesheet">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.9/css/all.css" integrity="sha384-5SOiIsAziJl6AWe0HWRKTXlfcSHKmYV4RBF18PPJ173Kzn7jzMyFuTtk8JA7QQG1" crossorigin="anonymous">

          Masaže Gligorijević

Početna

O nama

Kontakt

Kako do nas

Masaže Gligorijević

Ulaganjem u svoje zdravlje, ulažete u kvalitet sopstvenog života.

      <button class="button"> Rezervišite Odmah</button>

    <video autoplay muted loop id="video">
            <source src="/assets/images/klip.mp4" type="video/mp4">
        </video>

O nama

        Profesionalni maser i specijalno usavršeni fizioterapeut čija veština pokazuje odlične rezultate kod klijenata.

 Naš salon je opremljen profesionalnom opremom. Masaže se obavljaju na stolovima za masažu.

Kompletnom uživanju doprinose
        prijatni zvuci muzike i mirisi aromatičnih ulja.
 NAŠI klijenti odlaze uz pravilo: NAKON MASAŽE OPET IMAM OSMEH!

Kontakt

Zakažite vaš termin već sada!

 Adresa: Ljubiše Uroševića 6/21, Jagodina

 Tel: 060 078 2880

 Email: milosgliga92@gmail.com

Pratite nas na društvenim mrežama!

 Facebook

Instagram

Kako do nas

        © 2018   Đorđe Gligorijević   All Rights Reserved

Body:
100% work. Try this

<script>$('[data-aos]').parent().addClass('hideOverflowOnMobile');</script>
<style>
@media (max-width: 768px) {
    .hideOverflowOnMobile {
        overflow: hidden;
    }
}
</style>


问:
Android application Toast.makeText -error
I have problem due to the fact that my Android Studio
flags between  word

context and this -; expected
text and "Messages" ; expected
before .show ; expected and unexpected token I suppose .show

That does not make sense as the code is working perfectly in the tutorial but it is made in 2018 I wonder what could be issue or what more important what is the solutions?
Thanks you for all the answers :)

```<code>private void UserMenuSelector(MenuItem item)
    {
        switch (item.getItemId())
        {
            Context context;
            Object text;
            case R.id.nav_profile:
                Toast.makeText(context this, text "Profile",Toast.LENGTH_SHORT.show();
                break;

            case R.id.nav_home:
                Toast.makeText(context this, text "Home",Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_friends:
                Toast.makeText(context this, text "Friend List", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_find_friends:
                Toast.makeText(context this, text "Find Friends", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_messages:
                Toast.makeText(context this, text "Messages", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_settings:
                Toast.makeText(context this, text "Settings", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_Logout:
                Toast.makeText(context this, text "Logout", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private void show() {

    }
}
</code>```

答:
The Toast.makeText() required three parameters

Context: The context to use. Usually your Application or Activity object.

text: The text to show. Can be formatted text.

duration: How long to display the message. Either LENGTH_SHORT or LENGTH_LONG Value is LENGTH_SHORT, or LENGTH_LONG

Use this

```<code> Toast.makeText(YourActivity.this, "Profile",Toast.LENGTH_SHORT).show();

 // or this
 Toast.makeText(this, "Profile",Toast.LENGTH_SHORT).show();
</code>```

Instead of this

```<code> Toast.makeText(context this,text "Profile",Toast.LENGTH_SHORT.show();
</code>```

Body:
I have problem due to the fact that my Android Studio
flags between  word

context and this -; expected
text and "Messages" ; expected
before .show ; expected and unexpected token I suppose .show

That does not make sense as the code is working perfectly in the tutorial but it is made in 2018 I wonder what could be issue or what more important what is the solutions?
Thanks you for all the answers :)

private void UserMenuSelector(MenuItem item)
    {
        switch (item.getItemId())
        {
            Context context;
            Object text;
            case R.id.nav_profile:
                Toast.makeText(context this, text "Profile",Toast.LENGTH_SHORT.show();
                break;

            case R.id.nav_home:
                Toast.makeText(context this, text "Home",Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_friends:
                Toast.makeText(context this, text "Friend List", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_find_friends:
                Toast.makeText(context this, text "Find Friends", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_messages:
                Toast.makeText(context this, text "Messages", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_settings:
                Toast.makeText(context this, text "Settings", Toast.LENGTH_SHORT).show();
                break;

            case R.id.nav_Logout:
                Toast.makeText(context this, text "Logout", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    private void show() {

    }
}

Body:
The Toast.makeText() required three parameters

Context: The context to use. Usually your Application or Activity object.

text: The text to show. Can be formatted text.

duration: How long to display the message. Either LENGTH_SHORT or LENGTH_LONG Value is LENGTH_SHORT, or LENGTH_LONG

Use this

 Toast.makeText(YourActivity.this, "Profile",Toast.LENGTH_SHORT).show();

 // or this
 Toast.makeText(this, "Profile",Toast.LENGTH_SHORT).show();

Instead of this

 Toast.makeText(context this,text "Profile",Toast.LENGTH_SHORT.show();


问:
Assistance needed with join query
I have two very simple tables in Oracle 9G:

Customer

```<code>userid | firstName | lastName | email
-------+-----------+----------+---------------------
  1      user1       User1      user1@mail.in
  2      user2       User2      user2@mail.in
</code>```

Order

```<code>orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+-------
1          1          0         12/12/2009    1
2          1          1         13/12/2009    2
3          1          1         14/12/2009    3
4          2          0         12/12/2009    4
5          2          1         16/12/2009    2
6          1          0         14/12/2009    5
7          2          1         17/12/2009    4
8          2          0         10/12/2010    2
</code>```

I want to select all users which have orders of type 0

```<code>select *
from Customer c
inner join Order o on c.userid = o.userid
where o.orderType = '0'
</code>```

The result is:

```<code>orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+--------
1          1          0         12/12/2009    1
4          2          0         12/12/2009    4
6          1          0         14/12/2009    5
8          2          0         10/12/2010    2
</code>```

Now I need to modify this query to bring only last purchase date for each user id and get the result like this:

```<code>orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+--------
6          1          0         14/12/2009    5
8          2          0         10/12/2010    2
</code>```

How should I modify my query to get this result?

答:
Try this:</p>

```<code>select *
from   customer c
,      order o
where  c.userid = o.userid
and    o.orderType ='0'
and    o.order_date = (
    select max(o2.order_date)
    from   order o2
    where  o2.userid = o.userid
)
</code>```

Title: Assistance needed with join query

Body:
I have two very simple tables in Oracle 9G:

Customer

userid | firstName | lastName | email
-------+-----------+----------+---------------------
  1      user1       User1      user1@mail.in
  2      user2       User2      user2@mail.in

Order

orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+-------
1          1          0         12/12/2009    1
2          1          1         13/12/2009    2
3          1          1         14/12/2009    3
4          2          0         12/12/2009    4
5          2          1         16/12/2009    2
6          1          0         14/12/2009    5
7          2          1         17/12/2009    4
8          2          0         10/12/2010    2

I want to select all users which have orders of type 0

select *
from Customer c
inner join Order o on c.userid = o.userid
where o.orderType = '0'

The result is:

orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+--------
1          1          0         12/12/2009    1
4          2          0         12/12/2009    4
6          1          0         14/12/2009    5
8          2          0         10/12/2010    2

Now I need to modify this query to bring only last purchase date for each user id and get the result like this:

orderiD | userId | OrderType | Order_Date | Amount
--------+--------+-----------+------------+--------
6          1          0         14/12/2009    5
8          2          0         10/12/2010    2

How should I modify my query to get this result?

Body:
Try this:

select *
from   customer c
,      order o
where  c.userid = o.userid
and    o.orderType ='0'
and    o.order_date = (
    select max(o2.order_date)
    from   order o2
    where  o2.userid = o.userid
)


问:
Cannot resolve MultiDexApplication after updating android studio 4.0
After updating android studio to 4.0 and gradle to 6.1.1. There are some issues in my project which can't resolve.

```<code>import androidx.multidex.MultiDexApplication
</code>```

and

```<code>public class MyApplication extends MultiDexApplication
</code>```

I have this lib in my project and using it
works fine on previous version of Android studio.

答:
Try the following things.

Check whether your multidex dependency version in grade is updated one.

Delete your build folder in your project.

Clean project then Make Project.

If its still showing error then Invalidate cache and restart.

Hope this resolves your issue.

Body:
After updating android studio to 4.0 and gradle to 6.1.1. There are some issues in my project which can't resolve.

import androidx.multidex.MultiDexApplication

and

public class MyApplication extends MultiDexApplication

I have this lib in my project and using it
works fine on previous version of Android studio.


问:
How do I add rotation on centre axis for a 3d object in sparkAR?
I want to rotate the 3d object on its axis,  currently I'm using sparkar built in ide rotation, which is basically making it move in a circle like manner, its not spinning on it axis.</p>

答:
this might help

https://sparkar.facebook.com/ar-studio/learn/documentation/docs/3d-objects/

You can make 3D objects respond to other elements in your scene.
To do this, the 3D object should be a child of the element it should respond to


问:
Laravel 5.4 Passport Log user action (Optional auth:api)
I am using Laravel Passport (auth:api), all works well however I've came with the idea to log record user requests on a specific route.

When an GET request is made to /movie/65 I would like to store in movie_view the following data: user_id, movie_id (if the user is logged in)

However in my controller I am unable to call $request->user() without setting auth:api middleware.

What is the best practice you recommend to achieve this?

答: You can create a custom middleware as suggested here -- https://laracasts.com/discuss/channels/laravel/how-to-handle-route-with-optional-authentication. Then apply api guard to it. Let say you assign that custom middleware as auth.optional in Kernel.php, then you can use that middleware as auth.optional:api (with that api guard). Then you can access user thru $request->user() in your case above.


问:
Amazon RDS and Elastic Beanstalk connectivity
There are already several threads where this question is discussed, and I have already tried implementing suggestions discussed in
Elastic Beanstalk -> RDS connection error using Grails.

I have also opened ports to accept connections from "All" for ICMP, TCP and UDP in my EC2 instance.

I have made sure that my RDS and EC2 instances are in the same zone (Eastern)

I have also added the "elasticbeanstalk-default" security group in RDS default security group

I have added my local machine's IP address in RDS CIDR settings, and I am able to connect to RDS through SQLYog from my machine.

BUT when I try to connect my RDS instance from Elastic Beanstalk I am getting the following exception

```<code>Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:310)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:176)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:163)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
at java.net.Socket.connect(Socket.java:546)
at java.net.Socket.connect(Socket.java:495)
at java.net.Socket.<init>(Socket.java:392)
at java.net.Socket.<init>(Socket.java:235)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:293)
... 18 more

Jun 1, 2011 5:12:41 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Jun 1, 2011 5:12:41 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [] startup failed due to previous errors
Jun 1, 2011 5:12:41 AM org.apache.catalina.core.StandardContext listenerStop
SEVERE: Exception sending context destroyed event to listener instance of class         org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name.....
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:636)
</code>```

My DataSource.groovy parameters are as follows.

```<code>production {
    dataSource {
        pooled = true
        dbCreate = "update" // one of 'create', 'create-drop','update'
        url = "jdbc:mysql://[MyEndPoint]:3306/*****"
        username = "*****"
        password = "*****"
        dialect = org.hibernate.dialect.MySQL5InnoDBDialect
        properties {
            validationQuery = "SELECT 1"
            testOnBorrow = true
            testOnReturn = true
            testWhileIdle = true
            timeBetweenEvictionRunsMillis = 1000 * 60 * 30
            numTestsPerEvictionRun = 3
            minEvictableIdleTimeMillis = 1000 * 60 * 30
        }
    }
}
</code>```

答:
I solved it, pretty foolish answer though.

I always felt (thought) that when building a new WAR file for a Grails project in NetBeans it is created in a "production" environment, but that was not the case. I had to go to the project properties and change "Active grails environment" setting to "production" and this fixed it.

In a nutshell Amazon Web Services Elastic Beanstalk was trying to connect to my development environment database "localhost".

Body:
There are already several threads where this question is discussed, and I have already tried implementing suggestions discussed in
Elastic Beanstalk -> RDS connection error using Grails.

I have also opened ports to accept connections from "All" for ICMP, TCP and UDP in my EC2 instance.

I have made sure that my RDS and EC2 instances are in the same zone (Eastern)

I have also added the "elasticbeanstalk-default" security group in RDS default security group

I have added my local machine's IP address in RDS CIDR settings, and I am able to connect to RDS through SQLYog from my machine.

BUT when I try to connect my RDS instance from Elastic Beanstalk I am getting the following exception

Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:310)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:176)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:163)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
at java.net.Socket.connect(Socket.java:546)
at java.net.Socket.connect(Socket.java:495)
at java.net.Socket.<init>(Socket.java:392)
at java.net.Socket.<init>(Socket.java:235)
at com.mysql.jdbc.StandardSocketFactory.connect(StandardSocketFactory.java:256)
at com.mysql.jdbc.MysqlIO.<init>(MysqlIO.java:293)
... 18 more

Jun 1, 2011 5:12:41 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Jun 1, 2011 5:12:41 AM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [] startup failed due to previous errors
Jun 1, 2011 5:12:41 AM org.apache.catalina.core.StandardContext listenerStop
SEVERE: Exception sending context destroyed event to listener instance of class         org.codehaus.groovy.grails.web.context.GrailsContextLoaderListener
 org.springframework.beans.factory.BeanCreationException: Error creating bean with name.....
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:636)

My DataSource.groovy parameters are as follows.

production {
    dataSource {
        pooled = true
        dbCreate = "update" // one of 'create', 'create-drop','update'
        url = "jdbc:mysql://[MyEndPoint]:3306/*****"
        username = "*****"
        password = "*****"
        dialect = org.hibernate.dialect.MySQL5InnoDBDialect
        properties {
            validationQuery = "SELECT 1"
            testOnBorrow = true
            testOnReturn = true
            testWhileIdle = true
            timeBetweenEvictionRunsMillis = 1000 * 60 * 30
            numTestsPerEvictionRun = 3
            minEvictableIdleTimeMillis = 1000 * 60 * 30
        }
    }
}


问:
How to check if specified id does not exist in two tables in MySQL?
I have two relational tables.

table 1 staffs_items

```<code>item_id   int(11)
staff_id  int(11)
</code>```

table 2 entries_items

```<code>item_id   int(11)
entry_id  int(11)
</code>```

I want to check if an item_id does not exist in both tables.

like this:

```<code>SELECT EXISTS ( SELECT * FROM staffs_items AS si WHERE si.item_id = 1 ) AS exist;

+-------+
| exist |
+-------+
|     1 |
+-------+

SELECT EXISTS ( SELECT * FROM entries_items AS ei WHERE ei.item_id = 1 ) AS exist;

+-------+
| exist |
+-------+
|     0 |
+-------+
</code>```

I want to run those queries in a one liner.

If item_id does not exist in either table, I want to return 0 (false).

How can I do that?

答:
You could just place both exists subqueries into a single select:</p>

```<code>SELECT
    EXISTS (SELECT 1 FROM staffs_items WHERE item_id = 1) AS exists_staff_item,
    EXISTS (SELECT 1 FROM entries_items WHERE item_id = 1) AS exists_entries_item;
</code>```

Body:
I have two relational tables.

table 1 staffs_items

item_id   int(11)
staff_id  int(11)

table 2 entries_items

item_id   int(11)
entry_id  int(11)

I want to check if an item_id does not exist in both tables.

like this:

SELECT EXISTS ( SELECT * FROM staffs_items AS si WHERE si.item_id = 1 ) AS exist;

+-------+
| exist |
+-------+
|     1 |
+-------+

SELECT EXISTS ( SELECT * FROM entries_items AS ei WHERE ei.item_id = 1 ) AS exist;

+-------+
| exist |
+-------+
|     0 |
+-------+

I want to run those queries in a one liner.

If item_id does not exist in either table, I want to return 0 (false).

How can I do that?

Body:
You could just place both exists subqueries into a single select:

SELECT
    EXISTS (SELECT 1 FROM staffs_items WHERE item_id = 1) AS exists_staff_item,
    EXISTS (SELECT 1 FROM entries_items WHERE item_id = 1) AS exists_entries_item;


问:
Pass parameters from child to parent and viceversa
I want to create a StatefulWidget, so that child can use parameters of parent as well as they can change it also. </p>

<p>//need solution for problem like below.</p>

```<code>import "flutter/material.dart";
Toggle(
  builder: (value) => IconButton(
    icon: Icon(value ? Icons.add : Icons.minimize),
      onPressed: () => value = !value,
  ),
);

class Toggle extends StatefulWidget{
  final bool status;
  Widget Function(bool status) builder;
  Toggle({Key key, this.status = true, this.builder,}) : super(key: key);
  @override _ToggleState createState() => _ToggleState();
}

class _ToggleState extends State<Toggle> {
  @override Widget build(BuildContext context) => widget.builder(widget.status);
}
</code>```

答:
Usually, you create a function in the parent widget that changes the state of the parent, and pass that function to its child widget as a prop so that the child can execute it and mutate the state of the parent.

Here are an example snippet and CodePen url:

Snippet

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('demo')
        ),
        body: Center(
          child: Parent()
        )
      )
    ),
  );
}

class Parent extends StatefulWidget{
  _ParentState createState() => _ParentState();
}

class _ParentState extends State<Parent> {
  String _value = 'Hello';

  // This function will be passed down to the Child widget.
  void appendLetter(String letter) {
    setState(() {
      this._value += letter;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text('Parent: ' + this._value),
        new Child(
          param: this._value,
          callback: this.appendLetter // passing a function as a parameter
        )
      ]
    );
  }
}

class Child extends StatefulWidget{
  final String param;
  final void Function(String) callback;

  Child({
    Key key,
    this.param,
    this.callback,
  }) : super(key: key);

  _ChildState createState() => _ChildState();
}

class _ChildState extends State<Child> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Child: ' + widget.param),
        FlatButton(
          child: Text('Press Me'),
          onPressed: () => widget.callback('o') // invoking the function
        )
      ]
    );
  }
}

</code>```

CodePen

https://codepen.io/KenyoTheDeveloper/pen/xxZxdXg

Body:
I want to create a StatefulWidget, so that child can use parameters of parent as well as they can change it also.

//need solution for problem like below.

import "flutter/material.dart";
Toggle(
  builder: (value) => IconButton(
    icon: Icon(value ? Icons.add : Icons.minimize),
      onPressed: () => value = !value,
  ),
);

class Toggle extends StatefulWidget{
  final bool status;
  Widget Function(bool status) builder;
  Toggle({Key key, this.status = true, this.builder,}) : super(key: key);
  @override _ToggleState createState() => _ToggleState();
}

class _ToggleState extends State<Toggle> {
  @override Widget build(BuildContext context) => widget.builder(widget.status);
}

Body:
Usually, you create a function in the parent widget that changes the state of the parent, and pass that function to its child widget as a prop so that the child can execute it and mutate the state of the parent.

Here are an example snippet and CodePen url:

Snippet

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('demo')
        ),
        body: Center(
          child: Parent()
        )
      )
    ),
  );
}

class Parent extends StatefulWidget{
  _ParentState createState() => _ParentState();
}

class _ParentState extends State<Parent> {
  String _value = 'Hello';

  // This function will be passed down to the Child widget.
  void appendLetter(String letter) {
    setState(() {
      this._value += letter;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Text('Parent: ' + this._value),
        new Child(
          param: this._value,
          callback: this.appendLetter // passing a function as a parameter
        )
      ]
    );
  }
}

class Child extends StatefulWidget{
  final String param;
  final void Function(String) callback;

  Child({
    Key key,
    this.param,
    this.callback,
  }) : super(key: key);

  _ChildState createState() => _ChildState();
}

class _ChildState extends State<Child> {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Text('Child: ' + widget.param),
        FlatButton(
          child: Text('Press Me'),
          onPressed: () => widget.callback('o') // invoking the function
        )
      ]
    );
  }
}

CodePen

https://codepen.io/KenyoTheDeveloper/pen/xxZxdXg


问:
Input file with label not updating state
I want to make input type file with custom style, I hide input and styling the label using css. There are 2 problems:

I chose file, but coverFileState is undefinded (if I remove css style and choose file then everything is okay).

I want to set file name inside label, but it isn't working. I set text using setCoverUploadText inside handleCoverChange, but no effect.

If you help me with that problem I will really appreciate this, thanks!

```<code>const useStyles = makeStyles((theme) => ({
    fileInput: {
        marginBottom: '1em',
        width: '0.1px',
        height: '0.1px',
        opacity: '0',
        overflow: "hidden",
        position: "absolute"
    },
    uploadLabel: {
        fontSize: '1rem',
        cursor: 'pointer',
        color: "gray",
        border: "1px solid gray"
    }
}));

export default function AddingBook(props: ParamsProps) {

    const classes = useStyles();
    const coverFile = useRef(null);
    const [coverFileState, setCoverFile] = useState<string | Blob>();
    const [coverUploadText, setCoverUploadText] = useState("Upload cover photo *");

    const handleSubmit = () => {
        if (coverFileState === undefined) {
            setImageErrorMsg("*Please add cover photo.");
            return;
        }
        api.post('/image/add', JSON.stringify(REST))
            .then(res => {
                uploadCoverPhoto();
                props.close();
            }).catch(err => {
            const errorMsg = APIServices.onError(err);
            showErrorPopup(errorMsg);
        })
    };

    const handleCoverChange = () => {
        // @ts-ignore
        setCoverFile(coverFile.current.files[0]);
        // @ts-ignore
        setCoverUploadText(coverFile.current.files[0].name)
    };

    return (
        <>
            <div>
                <input
                    id="copy-file-upload"
                    type="file"
                    accept="image/*"
                    ref={coverFile}
                    onChange={handleCoverChange}
                    data-testid="inputFile"
                    className={classes.fileInput}
                />
                <label className={classes.uploadLabel} htmlFor="copy-file-upload">{coverUploadText}</label>
            </div>
        </>
    );
</code>```

答:
Try to replace "className" by "style" for the input file and for the label.
Hope it will helps you

EDIT:
it worked for me when i set the style as :

```<code>const useStyles = {
    fileInput: {
        marginBottom: '1em',
        width: '0.1px',
        height: '0.1px',
        opacity: '0',
        overflow: "hidden",
        position: "absolute"
    },
    uploadLabel: {
        fontSize: '1rem',
        cursor: 'pointer',
        color: "gray",
        border: "1px solid gray"
    }
};
</code>```

and use it in the return as :

```<code>....
<label style={useStyles.uploadLabel} htmlFor="copy-file-upload">{coverUploadText}</label>
....
</code>```

Body:
I want to make input type file with custom style, I hide input and styling the label using css. There are 2 problems:

I chose file, but coverFileState is undefinded (if I remove css style and choose file then everything is okay).

I want to set file name inside label, but it isn't working. I set text using setCoverUploadText inside handleCoverChange, but no effect.

If you help me with that problem I will really appreciate this, thanks!

const useStyles = makeStyles((theme) => ({
    fileInput: {
        marginBottom: '1em',
        width: '0.1px',
        height: '0.1px',
        opacity: '0',
        overflow: "hidden",
        position: "absolute"
    },
    uploadLabel: {
        fontSize: '1rem',
        cursor: 'pointer',
        color: "gray",
        border: "1px solid gray"
    }
}));

export default function AddingBook(props: ParamsProps) {

    const classes = useStyles();
    const coverFile = useRef(null);
    const [coverFileState, setCoverFile] = useState<string | Blob>();
    const [coverUploadText, setCoverUploadText] = useState("Upload cover photo *");

    const handleSubmit = () => {
        if (coverFileState === undefined) {
            setImageErrorMsg("*Please add cover photo.");
            return;
        }
        api.post('/image/add', JSON.stringify(REST))
            .then(res => {
                uploadCoverPhoto();
                props.close();
            }).catch(err => {
            const errorMsg = APIServices.onError(err);
            showErrorPopup(errorMsg);
        })
    };

    const handleCoverChange = () => {
        // @ts-ignore
        setCoverFile(coverFile.current.files[0]);
        // @ts-ignore
        setCoverUploadText(coverFile.current.files[0].name)
    };

    return (
        <>

                <input
                    id="copy-file-upload"
                    type="file"
                    accept="image/*"
                    ref={coverFile}
                    onChange={handleCoverChange}
                    data-testid="inputFile"
                    className={classes.fileInput}
                />
                {coverUploadText}

        </>
    );

Body:
Try to replace "className" by "style" for the input file and for the label.
Hope it will helps you

EDIT:
it worked for me when i set the style as :

const useStyles = {
    fileInput: {
        marginBottom: '1em',
        width: '0.1px',
        height: '0.1px',
        opacity: '0',
        overflow: "hidden",
        position: "absolute"
    },
    uploadLabel: {
        fontSize: '1rem',
        cursor: 'pointer',
        color: "gray",
        border: "1px solid gray"
    }
};

and use it in the return as :

....
<label style={useStyles.uploadLabel} htmlFor="copy-file-upload">{coverUploadText}</label>
....


问:
Kivy does not detect OpenGL 2.0
I have decided to do some programming in Kivy cross platform and installed Kivy on my computer successfully. The problem is that when I run my code, I get this error:

```<code>[INFO              ] [Kivy        ] v1.9.1
[INFO              ] [Python      ] v3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64 bit (AMD64)]
[INFO              ] [Factory     ] 179 symbols loaded
[INFO              ] [Image       ] Providers: img_tex, img_dds, img_gif, img_sdl2 (img_pil, img_ffpyplayer ignored)
[INFO              ] [OSC         ] using <thread> for socket
[INFO              ] [Window      ] Provider: sdl2
[INFO              ] [GL          ] GLEW initialization succeeded
[INFO              ] [GL          ] OpenGL version <b'1.1.0'>
[INFO              ] [GL          ] OpenGL vendor <b'Microsoft Corporation'>
[INFO              ] [GL          ] OpenGL renderer <b'GDI Generic'>
[INFO              ] [GL          ] OpenGL parsed version: 1, 1
[CRITICAL          ] [GL          ] Minimum required OpenGL version (2.0) NOT found!

OpenGL version detected: 1.1

Version: b'1.1.0'
Vendor: b'Microsoft Corporation'
Renderer: b'GDI Generic'

Try upgrading your graphics drivers and/or your graphics hardware in case of problems.

The application will leave now.
</code>```

And this error box pops out:

I have checked OpenGL version of my GPU via GPU Caps Viewer verifying me up to OpenGL Version 2.1, but Kivy somehow  doesn't detect OpenGL 2.1 and defaults to GDI Generic from Microsoft instead. I did some research on internet and found out that best way to resolve this problem is to update your graphical card's driver from your graphical card manufacturer, but this didn't work in my case.

I have updated my graphic drivers (I am running NVIDIA GeForce GT 435M on 64-bit Windows 8).

My question is: Is there a way to let Kivy switch from GDI Generic driver to NVIDIA driver? Or is there a problem somewhere else?

答:
As a quick workaround, try this.

# Keep these two lines until you find what the real solution is
import os
os.environ['KIVY_GL_BACKEND'] = 'angle_sdl2'

from kivy.app import App
App().run()
```

Title: Kivy does not detect OpenGL 2.0

Body:
I have decided to do some programming in Kivy cross platform and installed Kivy on my computer successfully. The problem is that when I run my code, I get this error:

[INFO              ] [Kivy        ] v1.9.1
[INFO              ] [Python      ] v3.4.4 (v3.4.4:737efcadf5a6, Dec 20 2015, 20:20:57) [MSC v.1600 64 bit (AMD64)]
[INFO              ] [Factory     ] 179 symbols loaded
[INFO              ] [Image       ] Providers: img_tex, img_dds, img_gif, img_sdl2 (img_pil, img_ffpyplayer ignored)
[INFO              ] [OSC         ] using <thread> for socket
[INFO              ] [Window      ] Provider: sdl2
[INFO              ] [GL          ] GLEW initialization succeeded
[INFO              ] [GL          ] OpenGL version
[INFO              ] [GL          ] OpenGL vendor
[INFO              ] [GL          ] OpenGL renderer
[INFO              ] [GL          ] OpenGL parsed version: 1, 1
[CRITICAL          ] [GL          ] Minimum required OpenGL version (2.0) NOT found!

OpenGL version detected: 1.1

Version: b'1.1.0'
Vendor: b'Microsoft Corporation'
Renderer: b'GDI Generic'

Try upgrading your graphics drivers and/or your graphics hardware in case of problems.

The application will leave now.

And this error box pops out:

I have checked OpenGL version of my GPU via GPU Caps Viewer verifying me up to OpenGL Version 2.1, but Kivy somehow  doesn't detect OpenGL 2.1 and defaults to GDI Generic from Microsoft instead. I did some research on internet and found out that best way to resolve this problem is to update your graphical card's driver from your graphical card manufacturer, but this didn't work in my case.

I have updated my graphic drivers (I am running NVIDIA GeForce GT 435M on 64-bit Windows 8).

My question is: Is there a way to let Kivy switch from GDI Generic driver to NVIDIA driver? Or is there a problem somewhere else?


问:
Command for loading postgres through docker?
Does anyone know the command for loading postgres through docker? Here is the recommended command on their documentation:

```<code>docker run -it --rm --network some-network postgres psql -h some-postgres -U postgres
</code>```

Forgive the naive question, how do you find what values for "some-network" are supposed to be and what values "some-postgres" is supposed to be?

答:
network in docker is used for interconnection between your containers which are needed to be communicated. If you only want postgres on docker you can ignore the network. some-network is the network name you want to use generally which can be listed by docker network ls command. some-postgres is the ip of the host server you want to run a container upon. You can run postgres on docker by following command

```<code>docker run -p 5432:5432 --name containername -e POSTGRES_PASSWORD=yourpassword -d postgres
</code>```

Here you can set the port, name password and -d is used for daemon mode and in the end, name of the image you want to use for postgres. This command will pull a postgres image from docker hub and set a running container for you. and more if you want to run psql inside the container you can connect to container ip which can be found by

```<code>docker inspect container_id
</code>```

then run the command

```<code>psql -h host_serverip -U postgres
</code>```

Body:
Does anyone know the command for loading postgres through docker? Here is the recommended command on their documentation:

docker run -it --rm --network some-network postgres psql -h some-postgres -U postgres

Forgive the naive question, how do you find what values for "some-network" are supposed to be and what values "some-postgres" is supposed to be?

Body:
network in docker is used for interconnection between your containers which are needed to be communicated. If you only want postgres on docker you can ignore the network. some-network is the network name you want to use generally which can be listed by docker network ls command. some-postgres is the ip of the host server you want to run a container upon. You can run postgres on docker by following command

docker run -p 5432:5432 --name containername -e POSTGRES_PASSWORD=yourpassword -d postgres

Here you can set the port, name password and -d is used for daemon mode and in the end, name of the image you want to use for postgres. This command will pull a postgres image from docker hub and set a running container for you. and more if you want to run psql inside the container you can connect to container ip which can be found by

docker inspect container_id

then run the command

psql -h host_serverip -U postgres


问:
How to authenticate async event messaging between services in microservice architecture
If my services communicate over Sync HTTP I would pass the JWT token to each service so each service an authenticate the request and ensure it is only providing data for the authenticated user.

However, if I change my communication mechanism to using async messaging (e.g. RabbitMQ), how would I now authenticate the event to the scope of the user who initiated the event.  Should the same JWT be passed as part of the event message.  I see an issue with this mechanism, in that the JWT may have expired by time the service processes the message which means the message will not get processed.

Is this the general approach and best practice, or should some sort of trusted policy be created and passed as a alias to the original JWT stating what that user could do and had access to, or is there a different approach?

答:
Once the user invokes the first microservice you should trust the communication among your services, so you dont need a jwt or standard token. You can pass in the event some sort of identification of the original user or its scopes to ensure that the reciever service filter the information accordingly.

This identification can be even a jwt token without expiration because it will be a token that only is used internally among your services so there is no risk that a malicious user tamper it.


问:
How to mock Java 8 Function in Spock Groovy
I want to mock Java 8 Function in spock groovy

below is my transformer interface

interface Transformer {
  String doSomething();
  Integer performTest();
  Function<List<Test>, String> findSuccess();
}
```

<p>want to mock this Function in service</p>

<pre class="lang-java prettyprint-override"><code>transformer.findSuccess().apply(tests);  // service class code
</code>```

Please help me on this

答:
I am using groovy 2.5 and I have added below in my test case. it's working

def function = {
  "1234"
} as Function<List<Test>, String>
1 * transformer.findSuccess() >> function
```

Body:
I want to mock Java 8 Function in spock groovy

below is my transformer interface

interface Transformer {
  String doSomething();
  Integer performTest();
  Function<List<Test>, String> findSuccess();
}

want to mock this Function in service

transformer.findSuccess().apply(tests);  // service class code

Please help me on this


问:
create new array from combination of elements in array _ JavaScript
suppose we have this array :

```<code>let a = ["a", "b", "c"]
</code>```

I need some combination like below:

```<code>[["a"], ["b"], ["c"], ["a", "b"], ["a", "c"], ["b", "c"], ["b", "a"], ["c", "a"], ["c","b"], ["a", "b", "c"], ...]
</code>```

const a = ["a", "b", "c"];

function perm(xs) {
  let ret = [];

  for (let i = 0; i < xs.length; i = i + 1) {
    let rest = perm(xs.slice(0, i).concat(xs.slice(i + 1)));

    if (!rest.length) {
      ret.push([xs[i]])
    } else {
      for (let j = 0; j < rest.length; j = j + 1) {
        ret.push([xs[i]].concat(rest[j]))
      }
    }
  }
  return ret;
}
console.log(perm(a));```

feel free to edit this question and if this is a similar question pls duplicate the question .strong text

答:
after searching a while, I foundout there is a function :

function combination(A, comb = [], result = [comb]) {
        for (var i = 0; i < A.length; i++)
            result = result.concat(combination(A.slice(0, i).concat(A.slice(i + 1)),            comb.concat(A[i])));
        return result;
    }

 console.log(combination(["q", "a", "w"]))```

and you can delete the first index with .slice(1, array.length)

Body:
suppose we have this array :

let a = ["a", "b", "c"]

I need some combination like below:

[["a"], ["b"], ["c"], ["a", "b"], ["a", "c"], ["b", "c"], ["b", "a"], ["c", "a"], ["c","b"], ["a", "b", "c"], ...]

const a = ["a", "b", "c"];

function perm(xs) {
  let ret = [];

  for (let i = 0; i < xs.length; i = i + 1) {
    let rest = perm(xs.slice(0, i).concat(xs.slice(i + 1)));

    if (!rest.length) {
      ret.push([xs[i]])
    } else {
      for (let j = 0; j < rest.length; j = j + 1) {
        ret.push([xs[i]].concat(rest[j]))
      }
    }
  }
  return ret;
}
console.log(perm(a));

feel free to edit this question and if this is a similar question pls duplicate the question .strong text

Body:
after searching a while, I foundout there is a function :

function combination(A, comb = [], result = [comb]) {
        for (var i = 0; i < A.length; i++)
            result = result.concat(combination(A.slice(0, i).concat(A.slice(i + 1)),            comb.concat(A[i])));
        return result;
    }

 console.log(combination(["q", "a", "w"]))

and you can delete the first index with .slice(1, array.length)


问:
problem in finding a function of a toolbox in Matlab
Why I can not see any result for the function of a toolbox(like topoplot in EEGlab) when I type its name in the help window in Matlab(search result) but when I type it with help or doc command in command line I get the result(help result)? Why these search results are not same?</p>

答:
Well, as topoplot is not a MATLAB-native function, it is also not part of the official documentation. Which is why you won't see something in the docs (and MATLAB asks you if you have ment something else).

The information that you get when you call help topoplot is what is written as comments at the very beginning of the file or just after the keyword function in the definition.

```<code>% this is what you get
% this line too

% this not
function test()
end
</code>```

if you now call help test

This also works after the keyword

```<code>function test()
% this is what you get
% this is the second line

% you won't see this
end
</code>```

Body:
Well, as topoplot is not a MATLAB-native function, it is also not part of the official documentation. Which is why you won't see something in the docs (and MATLAB asks you if you have ment something else).

The information that you get when you call help topoplot is what is written as comments at the very beginning of the file or just after the keyword function in the definition.

% this is what you get
% this line too

% this not
function test()
end

if you now call help test

This also works after the keyword

function test()
% this is what you get
% this is the second line

% you won't see this
end


问:
How can I know android game is developed with Unity game engine?
I have an android apk which I have decompiled. All libraries used are known to me. This include image loading and cachine libraries, airbnb lootie and crashlytics among others. I am trying to figure out the game engine used for the android apk. I have come across com.unity3d.ads which am not sure confirms this was developed on Unity3D. Can I use this to confirm? How can I know if this was done on android or if a game engine was used?</p>

答:
You cannot infer through com.unity3d.ads that the app is developed with Unity. You can use Unity Ads SDK to add advertisement to any platform iOS, Android or Java.

Extract the apk and navigate to lib folder and search libunity.so or libmono.so. If any of the file exists means the App was developed with Unity otherwise it is not.


问:
XAML Hot Reload for IOS Device not starting on Windows or MacBook Visual Studio 2019
I have a Xamarin Forms project that I am opening in an IOS Simulator. My Windows 10 PC is connected on the same network to my MacBook. But after the IOS Simulator shows up this message appears in the Debug Console:

[HotReload] (2020-05-30 01:00:03.2): INFO: XAML Hot Reload encountered a problem and failed to start. Use Help -> Report a Problem if the issues persists.
  [HotReload] (2020-05-30 01:00:03.2): INFO: Stopping All Hot Reload sessions due to Failed ...
  [HotReload] (2020-05-30 01:00:03.2): INFO: (Xamarin Testing.iOS) Stopped Hot Reload session due to Failed ...
  [HotReload] (2020-05-30 01:00:03.2): INFO: Stopped Hot Reload session.

I have tried running Hot Reload on just the Mac to no avail. Additionally, all the setup should be right, as I've double-checked all the correct options are ticked.

Does anyone know why the Hot Reloader isn't running?

答:
Welcome to SO !

First , have a check with Tools -> Options... -> Xmarin ->Hot Reload -> Enable ...

Second , you need to check whether Xaml code contains error when debugging .


问:
DomainAccessGuard.Sessions is Always null
Hi I am having trouble Integrating the ability to kick users as the sessionCollection is always null.

```<code>public void KickStaleUsers()
    {
        foreach (DomainAccessGuard.Session ses in DomainAccessGuard.Sessions) //<--- This is null
        {
            if (DateTime.Now.Subtract(ses.LastRequest).Minutes >= 60)
            {
                DomainAccessGuard.Kick(ses.SessionID);
                Log.Info("Brugeren (" + ses.UserName + ") er logget ud grundet 60 min. inaktivitet!", this);
            }
        }
    }
</code>```

I am running this from an agent

Does anybody know why it is null?

答:
Here is some sitecore documentation which provides an example of how to reduce session timeout.

It runs as an agent, and also has an Assert.IsNotNull check on session.

Hope this helps

Body:
Hi I am having trouble Integrating the ability to kick users as the sessionCollection is always null.

public void KickStaleUsers()
    {
        foreach (DomainAccessGuard.Session ses in DomainAccessGuard.Sessions) //<--- This is null
        {
            if (DateTime.Now.Subtract(ses.LastRequest).Minutes >= 60)
            {
                DomainAccessGuard.Kick(ses.SessionID);
                Log.Info("Brugeren (" + ses.UserName + ") er logget ud grundet 60 min. inaktivitet!", this);
            }
        }
    }

I am running this from an agent

Does anybody know why it is null?


问:
Call Statements return Different result
In Python programming, which using Pytorch i got this error

4 and >5 are printing the type of x to check the type of tensor, but returning different results

why does this happen?My Code of Execution

```<code>x = x.type(torch.int64)
print(x.type())
type(X)
</code>```

答:
This is a known behavior of PyTorch since version 0.4, though the maintainers don't offer a justification.

Note also that the type() of a Tensor no longer reflects the data type. Use isinstance() or x.type() instead

```<code>x = torch.DoubleTensor([1, 1, 1])
print(type(x))  # was torch.DoubleTensor
# "<class 'torch.Tensor'>"
print(x.type())  # OK: 'torch.DoubleTensor'
# 'torch.DoubleTensor'
print(isinstance(x, torch.DoubleTensor))  # OK: True
# True
</code>```

Title: Call Statements return Different result

Body:
In Python programming, which using Pytorch i got this error

4 and >5 are printing the type of x to check the type of tensor, but returning different results

why does this happen?My Code of Execution

x = x.type(torch.int64)
print(x.type())
type(X)

Body:
This is a known behavior of PyTorch since version 0.4, though the maintainers don't offer a justification.

Note also that the type() of a Tensor no longer reflects the data type. Use isinstance() or x.type() instead

x = torch.DoubleTensor([1, 1, 1])
print(type(x))  # was torch.DoubleTensor
# "<class 'torch.Tensor'>"
print(x.type())  # OK: 'torch.DoubleTensor'
# 'torch.DoubleTensor'
print(isinstance(x, torch.DoubleTensor))  # OK: True
# True


问:
Running Unit-test with Maven
Now I am learning Junit5 framework, and I found out there is an option to run my unit-test not only with IDE (I am using IntelijIdea), but with Maven surefire plugin. A lot of articles in the Ethernet advice me to use Maven plugin to run my test. Perhaps, I am not understand something, but whats the point? Actually, I can use my default IDE options to run it, am I wrong? Thanks a lot!

答:
While inside IntelliJ, use that to run your unit tests. That's where you write your code, run the unit tests there too, while working on your code.

If you're just starting with this, that may be the only place where you ever run your unit tests. But in any kind of mature development project, particularly when collaborating on code, you want a way to build your project outside your editor or IDE. While an IDE is often tainted with personal preferences and such, a build (script) on the command-line is seen as more authoritative.

If you have a good build (script) on the command-line, you can also run it in a Continuous Integration environment ("build server"), and properly automate builds, testing, reporting and deployments.

In this age, do not make your own build script for Java projects. Maven is the gold standard.

At the bare minimum, Maven will offer you:

Dependency management: you are likely to bring in (external) dependencies into your project. Relying on an IDE for dependency management is another source of inconsistencies. Maven does this in a predictable, reproducible way. Along with other properties about your project, this is managed in Maven's POM (file), which is pom.xml.

A default build lifecycle: basic things you are likely to need in a build. In your case: dependency resolution, then compilation, then test execution. You can reconfigure in the POM (file) the plugins that are executed, but for your question the defaults should work fine.

This is some official documentation about dependency management, and this about the POM (file). But don't get overwhelmed by all the options. Instead, rather rely on Maven's sane defaults.

For example, if you are using IntelliJ, I recommend using it to create your first Maven project, since it will set up a few things in a working POM (file) without you having to immediately understand the format of the POM entirely. (Choose "New Project", select "Maven", skip over archetype selection, and so on.)

Important things to keep in mind here are the POM (file), in the root of the project, and Maven's Standard Directory Layout, most notably for your question src/main/java and src/test/java for your production code resp. test code.

Title: Running Unit-test with Maven


问:
Remove Java warnings in the VS Code PROBLEMS window
I'm using Java in VS Code and am getting warnings in the PROBLEMS tab.

```<code>'_' should not be used as an identifier, since it is a reserved keyword from source level 1.8 on
Type safety: The method put(Object, Object) belongs to the raw type Hashtable. References to generic type Hashtable<K,V> should be parameterized
</code>```

Other ones also.

How can I disable them?

There seems to be an integer identifier at the end of each message - seems to be associated with the message type.

Some people have suggested looking at the .settings file and add something like

org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore

But I haven't found something related to my warnings - is there a complete list somehwer of these eclipse problem strings.

答:
You'd better fix it, instead of suppress it.

The first warning: Through this doc, you'd better not use '_' as an identifier, otherwise you will get an warning even an error. You can also get more information from this page.

The second warning is because you haven't added 'generic parameters', like this one:

```<code>HashMap map =newHashMap();
map.put("showOppo", option.isShowOppo());
</code>```

And you can change like this to avoid it:

```<code>HashMap<String,String> map =newHashMap<>();
</code>```

Body:
I'm using Java in VS Code and am getting warnings in the PROBLEMS tab.

'_' should not be used as an identifier, since it is a reserved keyword from source level 1.8 on
Type safety: The method put(Object, Object) belongs to the raw type Hashtable. References to generic type Hashtable<K,V> should be parameterized

Other ones also.

How can I disable them?

There seems to be an integer identifier at the end of each message - seems to be associated with the message type.

Some people have suggested looking at the .settings file and add something like

org.eclipse.jdt.core.compiler.problem.missingSerialVersion=ignore

But I haven't found something related to my warnings - is there a complete list somehwer of these eclipse problem strings.

Body:
You'd better fix it, instead of suppress it.

The first warning: Through this doc, you'd better not use '_' as an identifier, otherwise you will get an warning even an error. You can also get more information from this page.

The second warning is because you haven't added 'generic parameters', like this one:

HashMap map =newHashMap();
map.put("showOppo", option.isShowOppo());

And you can change like this to avoid it:

HashMap<String,String> map =newHashMap<>();


问:
Setting up half-icons with a rating system
I built a component that is basically a rating system that allows you to add more icons depending on the dropdown.

I was wondering if there was a way to make half stars, I've looked through older code on the internet, but there isn't anything that has been updated. Any help with be appreciated

```<code>import React, { useState } from 'react'
import {FaStar} from "react-icons/all";
import './Rater.css'

const Rater = () => {
    const [rating, setRating] = useState(null)
    const [hover, setHover] = useState(null)
    const [value] = useState(100)
    const [iconValue, setIconValue] = useState(5)

    return (
        <div>
            <select onChange={(e) =>
            {setIconValue(Number(e.target.value))}}>
                { Array.from(new Array(value),(value, index) =>
                    index + 1).map(value => <option
                    key={value} value={value}>{value}</option>) }
            </select>
            <h1> Select Amount of Icons </h1>

            {[... Array(iconValue)].map((icon, i) => {
                const value = i + 1

                return (
                    <label>
                        <input type='radio'
                               name='rating'
                               value={value}
                               onClick={() => setRating(value)}
                        />
                        <FaStar classname='star'
                                color={value <= (hover || rating) ? '#ffc107' : '#e4e5e9'}
                                size={100}
                                onMouseEnter={() => setHover(value)}
                                onMouseLeave={() => setHover(null)}
                        />
                    </label>
                )
            })}
        </div>
    )
}

export default Rater
</code>```

Body:
I built a component that is basically a rating system that allows you to add more icons depending on the dropdown.

I was wondering if there was a way to make half stars, I've looked through older code on the internet, but there isn't anything that has been updated. Any help with be appreciated

import React, { useState } from 'react'
import {FaStar} from "react-icons/all";
import './Rater.css'

const Rater = () => {
    const [rating, setRating] = useState(null)
    const [hover, setHover] = useState(null)
    const [value] = useState(100)
    const [iconValue, setIconValue] = useState(5)

    return (

            <select onChange={(e) =>
            {setIconValue(Number(e.target.value))}}>
                { Array.from(new Array(value),(value, index) =>
                    index + 1).map(value => <option
                    key={value} value={value}>{value}</option>) }
            </select>

 Select Amount of Icons

            {[... Array(iconValue)].map((icon, i) => {
                const value = i + 1

                return (

                        <input type='radio'
                               name='rating'
                               value={value}
                               onClick={() => setRating(value)}
                        />
                        <FaStar classname='star'
                                color={value <= (hover || rating) ? '#ffc107' : '#e4e5e9'}
                                size={100}
                                onMouseEnter={() => setHover(value)}
                                onMouseLeave={() => setHover(null)}
                        />

                )
            })}

    )
}

export default Rater

Body:
I looked at your code, Your star icon is in SVG. You can write a gradient template and add fill: url(#id) to the star you want to change

.linear-gradient-template {
  width: 0;
  height: 0;
}

<svg class="linear-gradient-template">
    <linearGradient id="orange_grey" x1="0%" y1="0%" x2="100%" y2="0%">
        <stop offset="50%" style="stop-color: rgb(255, 193, 7)"></stop>
        <stop offset="50%" style="stop-color: rgb(228, 229, 233)"></stop>
    </linearGradient>
</svg>

<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 576 512" class="one,star" color="#ffc107" size="100" height="100" width="100" xmlns="http://www.w3.org/2000/svg" style="color: rgb(255, 193, 7);">
  <path style="fill: url(#orange_grey)" d="M259.3 17.8L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0z"></path>
 </svg>

<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 576 512" class="one,star" color="#ffc107" size="100" height="100" width="100" xmlns="http://www.w3.org/2000/svg" style="color: rgb(255, 193, 7);">
  <path style="fill: url(#orange_grey)" d="M259.3 17.8L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0z"></path>
 </svg>

<svg stroke="currentColor" fill="currentColor" stroke-width="0" viewBox="0 0 576 512" class="one,star" color="#ffc107" size="100" height="100" width="100" xmlns="http://www.w3.org/2000/svg" style="color: rgb(255, 193, 7);">
  <path style="fill: url(#orange_grey)" d="M259.3 17.8L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0z"></path>
 </svg>

    import React, { useState } from 'react'
import {FaStar} from "react-icons/all";
import './Rater.css'

const Rater = () => {
    const [rating, setRating] = useState(null)
    const [hover, setHover] = useState(null)
    const [value] = useState(100)
    const [iconValue, setIconValue] = useState(5)
    const size = 100

    return (
        <div id="start-wrap">
            <svg className="linear-gradient-template">
                <linearGradient id="orange_red" x1="0%" y1="0%" x2="100%" y2="0%">
                    <stop offset="50%" style={{stopColor: 'rgb(255, 193, 7)'}}></stop>
                    <stop offset="50%" style={{stopColor: 'rgb(228, 229, 233)'}}></stop>
                </linearGradient>
            </svg>
            <select onChange={(e) =>
            {setIconValue(Number(e.target.value))}}>
                { Array.from(new Array(value),(value, index) =>
                    index + 1).map(value => <option
                    key={value} value={value}>{value}</option>) }
            </select>
            <h1> Select Amount of Icons </h1>
            {[... Array(iconValue)].map((icon, i) => {
                const value = i + 1
                return (
                    <label>
                        <input type='radio'
                            name='rating'
                            value={value}
                            onClick={() => setRating(value)}
                        />
                        <FaStar
                            className='star'
                            color={value <= (hover || rating) ? '#ffc107' : '#e4e5e9'}
                            size={size}
                            onMouseEnter={(e) => setHover(value)}
                            onMouseLeave={() => {
                                let svgDom = document.getElementsByClassName('star')[i]
                                let pathDom = svgDom.children[0]
                                pathDom.style.fill = ''
                                setHover(null)
                            }}
                            onMouseMove={e => {
                                let svgDom = document.getElementsByClassName('star')[i]
                                let pathDom = svgDom.children[0]
                                if(e.pageX - svgDom.getBoundingClientRect().left <= size / 2){
                                    pathDom.style.fill = 'url(#orange_red)'
                                } else {
                                    pathDom.style.fill = ''
                                }
                            }}
                        />
                    </label>
                )
            })}
        </div>
    )
}

export default Rater

Above, I change your code, It is not perfect, you can modify it according to your needs.