问:
JQuery on Clicks add class
Hello people I've created a simple cars animations but there are many problems that when the user clicks on the more than button in the same time, this problem in the video will appears so How to prevent this problem, The reason is that we will not be able to predict what the user will do

Youtube Video

Here my code:

$(document).ready(function () {
    var $cars = $('.car');
    var temp = 1;
    $('.car-model').on('click', function () {
        /*=========================
         * Add Class Active
         */
        $(this).addClass('activeModel').parent().siblings().find('.car-model').removeClass('activeModel');
        var index = $(this).data('index');
        if (temp == index) {

        } else {
            var $current = $cars.find('.current');
            var $next = $('[data-car-index="' + index + '"]').parent();
            $current.addClass('car--trans-out');
            setTimeout(function () {
                $('.car-image-container').removeClass('whelrotateClick');
                $current.removeClass('current').removeClass('car--trans-out');
                $next.addClass('current').addClass('car--trans-in');
                setTimeout(function () {
                    $next.removeClass('car--trans-in');
                }, 1000)
            }, 1000);
        }
        temp = index;
    });
    $('.selectContainer').on('change', function () {
        var index = $(this).find('option:selected').data('index');
        var $current = $cars.find('.current');
        var $next = $('[data-car-index="' + index + '"]').parent();

        $current.addClass('car--trans-out');
        setTimeout(function () {
            $current.removeClass('current').removeClass('car--trans-out');
            $next.addClass('current').addClass('car--trans-in');
            setTimeout(function () {
                $next.removeClass('car--trans-in');
            }, 1000)
        }, 1000);
    });

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.car{
    padding:40px 0;
}
.car .changeCarSelect{
    display:none;
    text-align:left;
}
.car .changeCarSelect span{
    display:inline-block;
    margin-right:4px;
    font-size:14px;
}
.car .selectContainer {
    width: 200px;
    padding: 10px 5px;
    display:inline-block;
    margin-bottom:30px;
    font-size: 14px;
    border:1px solid rgba(246, 246, 246, 0.89);
    outline:none;
    cursor:pointer;
}
.car .car-button .car-model{
    width:100%;
    margin-bottom:30px;
    cursor:pointer;
}
.car .car-button .car-model h3 {
    margin: 0;
    padding: 15px 10px;
    border: 2px solid #e9e9e9;
    color: #333;
    font-family: "Raleway", Arial, Tahoma;
    font-weight: 700;
    font-size: 18px;
    text-align: center;
    -moz-transition: all .4s ease-in-out;
    -o-transition: all .4s ease-in-out;
    -webkit-transition: all .4s ease-in-out;
    transition: all .4s ease-in-out;
}
.car .car-button .car-model.activeModel h3{
    background-color:#333;
    color:#ffffff;
}
.car div[class^='col']{
    padding:4px;
}
.car .car-relative{
    position:relative;
    width:100%;
    margin: 0 0 20px;
    overflow: hidden;
}
.car-image-container{
    position: absolute;
    left: 100%;
    overflow: hidden;
}

.car .car-image{
    display: none;
}
.car .car-image img{
    margin:auto;
}
.car .current{
    position: relative;
    left: 0;
}
.car .current .car-image{
    display: block;
}
.car--trans-in .car-image {
    -moz-animation: trans-in 1s ease-out;
    -o-animation: trans-in 1s ease-out;
    -webkit-animation: trans-in 1s ease-out;
    animation: trans-in 1s ease-out;
    -moz-animation-fill-mode: forwards;
    -o-animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
    -moz-animation-timing-function: cubic-bezier(0.165, 0.84, 0.44, 1);
    -o-animation-timing-function: cubic-bezier(0.165, 0.84, 0.44, 1);
    -webkit-animation-timing-function: cubic-bezier(0.165, 0.84, 0.44, 1);
    animation-timing-function: cubic-bezier(0.165, 0.84, 0.44, 1);
}
.car--trans-out .car-image {
    -moz-animation: trans-out 1s ease-in;
    -o-animation: trans-out 1s ease-in;
    -webkit-animation: trans-out 1s ease-in;
    animation: trans-out 1s ease-in;
    -moz-animation-fill-mode: forwards;
    -o-animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
    -moz-animation-timing-function: cubic-bezier(0.895, 0.03, 0.685, 0.22);
    -o-animation-timing-function: cubic-bezier(0.895, 0.03, 0.685, 0.22);
    -webkit-animation-timing-function: cubic-bezier(0.895, 0.03, 0.685, 0.22);
    animation-timing-function: cubic-bezier(0.895, 0.03, 0.685, 0.22);
}
@-moz-keyframes trans-in {
    0% {
        -moz-transform: translateX(150%);
        -ms-transform: translateX(150%);
        -o-transform: translateX(150%);
        -webkit-transform: translateX(150%);
        transform: translateX(150%);
    }
    80% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    100% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
}

@-webkit-keyframes trans-in {
    0% {
        -moz-transform: translateX(150%);
        -ms-transform: translateX(150%);
        -o-transform: translateX(150%);
        -webkit-transform: translateX(150%);
        transform: translateX(150%);
    }
    80% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    100% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
}

@keyframes trans-in {
    0% {
        -moz-transform: translateX(150%);
        -ms-transform: translateX(150%);
        -o-transform: translateX(150%);
        -webkit-transform: translateX(150%);
        transform: translateX(150%);
    }
    80% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    100% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
}
@-moz-keyframes trans-out {
    0% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    10% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    80% {
        -moz-transform: translateX(-100%);
        -ms-transform: translateX(-100%);
        -o-transform: translateX(-100%);
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }
    100% {
        -moz-transform: translateX(-100%);
        -ms-transform: translateX(-100%);
        -o-transform: translateX(-100%);
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }
}
@-webkit-keyframes trans-out {
    0% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    10% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    80% {
        -moz-transform: translateX(-100%);
        -ms-transform: translateX(-100%);
        -o-transform: translateX(-100%);
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }
    100% {
        -moz-transform: translateX(-100%);
        -ms-transform: translateX(-100%);
        -o-transform: translateX(-100%);
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }
}
@keyframes trans-out {
    0% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    10% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    80% {
        -moz-transform: translateX(-100%);
        -ms-transform: translateX(-100%);
        -o-transform: translateX(-100%);
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }
    100% {
        -moz-transform: translateX(-100%);
        -ms-transform: translateX(-100%);
        -o-transform: translateX(-100%);
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }
}
@media only screen and (max-width: 768px)  {
    .car .changeCarSelect{
        display:block;
    }
    .car .car-button .car-model {
        display:none;
    }
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

                Change Car
                <select class="selectContainer">
                    <option class="selectCar" data-index="1">
                        Car model
                    </option>
                    <option class="selectCar" data-index="2">
                        Car model
                    </option>
                    <option class="selectCar" data-index="3">
                        Car model
                    </option>
                    <option class="selectCar" data-index="4">
                        Car model
                    </option>
                    <option class="selectCar" data-index="5">
                        Car model
                    </option>
                </select>

Car Model 1

Car Model 2

Car Model 3

Car Model 4

Car Model 5

```

Please run code snippet in fullscreen

答:
If you animate using CSS3 than you can check for a transition is finished using:

```<code>// if you use CSS3 transition
$("selector").on("transitionend", function(){
   // do something ... like make buttons clickable again...
});
</code>```

or if you use CSS3 animation

```<code>$("selector").on("animationend", function(){
   // do something
});
</code>```

EXAMPLE

here's an example on how to use .one() and .off() jQuery's methods:

as you can see, the button is not clickable while the car animates

var $btn = $(".btn");
var $car = $(".car");

function initStates() {
  // Make button clickable
  $btn.one("click", moveCar);
  // Remove the animation class
  $car.removeClass("moveCar");
}

function moveCar() {
  console.log("BUTTON CLICK!!");

  // Remove Click handler
  $btn.off("click");

  // Move car using CSS3 animation
  // and call initStates on animationend (event callback)
  $car.addClass("moveCar").one("animationend", initStates);
}

// INITIALIZE default states
initStates();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.car {
  position: relative;
  background: red;
  width: 20px;
  height: 20px;
}

.moveCar /* CLASS ADDED BY JQUERY */ {
  animation: move 2s ease-out;
  background: green;
}

@keyframes move {
  0% {
    left: 0;
  }
  100% {
    left: 80%;
  }
}</code>```

<button class="btn">CLICK TO MOVE CAR</button>

```
</div>
</div>
</p>

<p>If you use jQuery's <code>.animate()</code> than you can check if an item is animated using</p>

```if( $("selector").is(":animated") ) return;
// If a selector is animated the code below will not execute
alert("Animate next car!");
```

<p>than, eventually, in order to memorize the clicked button while one car was animated - you could create a variable to store the value of the car to animate next once the current animated one triggers an <code>.animate</code> callback - Than remember to reset / null the variable after you've used it.</p>

<p>If instead - you <strong>want</strong> actually to have multiple cars running on screen - than you need to position your cars using </p>

```position: absolute;
```

Title: JQuery on Clicks add class

Body:
Hello people I've created a simple cars animations but there are many problems that when the user clicks on the more than button in the same time, this problem in the video will appears so How to prevent this problem, The reason is that we will not be able to predict what the user will do

Youtube Video

Here my code:

$(document).ready(function () {
    var $cars = $('.car');
    var temp = 1;
    $('.car-model').on('click', function () {
        /*=========================
         * Add Class Active
         */
        $(this).addClass('activeModel').parent().siblings().find('.car-model').removeClass('activeModel');
        var index = $(this).data('index');
        if (temp == index) {

        } else {
            var $current = $cars.find('.current');
            var $next = $('[data-car-index="' + index + '"]').parent();
            $current.addClass('car--trans-out');
            setTimeout(function () {
                $('.car-image-container').removeClass('whelrotateClick');
                $current.removeClass('current').removeClass('car--trans-out');
                $next.addClass('current').addClass('car--trans-in');
                setTimeout(function () {
                    $next.removeClass('car--trans-in');
                }, 1000)
            }, 1000);
        }
        temp = index;
    });
    $('.selectContainer').on('change', function () {
        var index = $(this).find('option:selected').data('index');
        var $current = $cars.find('.current');
        var $next = $('[data-car-index="' + index + '"]').parent();

        $current.addClass('car--trans-out');
        setTimeout(function () {
            $current.removeClass('current').removeClass('car--trans-out');
            $next.addClass('current').addClass('car--trans-in');
            setTimeout(function () {
                $next.removeClass('car--trans-in');
            }, 1000)
        }, 1000);
    });

});

.car{
    padding:40px 0;
}
.car .changeCarSelect{
    display:none;
    text-align:left;
}
.car .changeCarSelect span{
    display:inline-block;
    margin-right:4px;
    font-size:14px;
}
.car .selectContainer {
    width: 200px;
    padding: 10px 5px;
    display:inline-block;
    margin-bottom:30px;
    font-size: 14px;
    border:1px solid rgba(246, 246, 246, 0.89);
    outline:none;
    cursor:pointer;
}
.car .car-button .car-model{
    width:100%;
    margin-bottom:30px;
    cursor:pointer;
}
.car .car-button .car-model h3 {
    margin: 0;
    padding: 15px 10px;
    border: 2px solid #e9e9e9;
    color: #333;
    font-family: "Raleway", Arial, Tahoma;
    font-weight: 700;
    font-size: 18px;
    text-align: center;
    -moz-transition: all .4s ease-in-out;
    -o-transition: all .4s ease-in-out;
    -webkit-transition: all .4s ease-in-out;
    transition: all .4s ease-in-out;
}
.car .car-button .car-model.activeModel h3{
    background-color:#333;
    color:#ffffff;
}
.car div[class^='col']{
    padding:4px;
}
.car .car-relative{
    position:relative;
    width:100%;
    margin: 0 0 20px;
    overflow: hidden;
}
.car-image-container{
    position: absolute;
    left: 100%;
    overflow: hidden;
}

.car .car-image{
    display: none;
}
.car .car-image img{
    margin:auto;
}
.car .current{
    position: relative;
    left: 0;
}
.car .current .car-image{
    display: block;
}
.car--trans-in .car-image {
    -moz-animation: trans-in 1s ease-out;
    -o-animation: trans-in 1s ease-out;
    -webkit-animation: trans-in 1s ease-out;
    animation: trans-in 1s ease-out;
    -moz-animation-fill-mode: forwards;
    -o-animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
    -moz-animation-timing-function: cubic-bezier(0.165, 0.84, 0.44, 1);
    -o-animation-timing-function: cubic-bezier(0.165, 0.84, 0.44, 1);
    -webkit-animation-timing-function: cubic-bezier(0.165, 0.84, 0.44, 1);
    animation-timing-function: cubic-bezier(0.165, 0.84, 0.44, 1);
}
.car--trans-out .car-image {
    -moz-animation: trans-out 1s ease-in;
    -o-animation: trans-out 1s ease-in;
    -webkit-animation: trans-out 1s ease-in;
    animation: trans-out 1s ease-in;
    -moz-animation-fill-mode: forwards;
    -o-animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
    -moz-animation-timing-function: cubic-bezier(0.895, 0.03, 0.685, 0.22);
    -o-animation-timing-function: cubic-bezier(0.895, 0.03, 0.685, 0.22);
    -webkit-animation-timing-function: cubic-bezier(0.895, 0.03, 0.685, 0.22);
    animation-timing-function: cubic-bezier(0.895, 0.03, 0.685, 0.22);
}
@-moz-keyframes trans-in {
    0% {
        -moz-transform: translateX(150%);
        -ms-transform: translateX(150%);
        -o-transform: translateX(150%);
        -webkit-transform: translateX(150%);
        transform: translateX(150%);
    }
    80% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    100% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
}

@-webkit-keyframes trans-in {
    0% {
        -moz-transform: translateX(150%);
        -ms-transform: translateX(150%);
        -o-transform: translateX(150%);
        -webkit-transform: translateX(150%);
        transform: translateX(150%);
    }
    80% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    100% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
}

@keyframes trans-in {
    0% {
        -moz-transform: translateX(150%);
        -ms-transform: translateX(150%);
        -o-transform: translateX(150%);
        -webkit-transform: translateX(150%);
        transform: translateX(150%);
    }
    80% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    100% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
}
@-moz-keyframes trans-out {
    0% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    10% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    80% {
        -moz-transform: translateX(-100%);
        -ms-transform: translateX(-100%);
        -o-transform: translateX(-100%);
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }
    100% {
        -moz-transform: translateX(-100%);
        -ms-transform: translateX(-100%);
        -o-transform: translateX(-100%);
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }
}
@-webkit-keyframes trans-out {
    0% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    10% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    80% {
        -moz-transform: translateX(-100%);
        -ms-transform: translateX(-100%);
        -o-transform: translateX(-100%);
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }
    100% {
        -moz-transform: translateX(-100%);
        -ms-transform: translateX(-100%);
        -o-transform: translateX(-100%);
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }
}
@keyframes trans-out {
    0% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    10% {
        -moz-transform: translateX(0%);
        -ms-transform: translateX(0%);
        -o-transform: translateX(0%);
        -webkit-transform: translateX(0%);
        transform: translateX(0%);
    }
    80% {
        -moz-transform: translateX(-100%);
        -ms-transform: translateX(-100%);
        -o-transform: translateX(-100%);
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }
    100% {
        -moz-transform: translateX(-100%);
        -ms-transform: translateX(-100%);
        -o-transform: translateX(-100%);
        -webkit-transform: translateX(-100%);
        transform: translateX(-100%);
    }
}
@media only screen and (max-width: 768px)  {
    .car .changeCarSelect{
        display:block;
    }
    .car .car-button .car-model {
        display:none;
    }
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

                Change Car
                <select class="selectContainer">
                    <option class="selectCar" data-index="1">
                        Car model
                    </option>
                    <option class="selectCar" data-index="2">
                        Car model
                    </option>
                    <option class="selectCar" data-index="3">
                        Car model
                    </option>
                    <option class="selectCar" data-index="4">
                        Car model
                    </option>
                    <option class="selectCar" data-index="5">
                        Car model
                    </option>
                </select>

Car Model 1

Car Model 2

Car Model 3

Car Model 4

Car Model 5

Please run code snippet in fullscreen

Body:
If you animate using CSS3 than you can check for a transition is finished using:

// if you use CSS3 transition
$("selector").on("transitionend", function(){
   // do something ... like make buttons clickable again...
});

or if you use CSS3 animation

$("selector").on("animationend", function(){
   // do something
});

EXAMPLE

here's an example on how to use .one() and .off() jQuery's methods:

as you can see, the button is not clickable while the car animates

var $btn = $(".btn");
var $car = $(".car");

function initStates() {
  // Make button clickable
  $btn.one("click", moveCar);
  // Remove the animation class
  $car.removeClass("moveCar");
}

function moveCar() {
  console.log("BUTTON CLICK!!");

  // Remove Click handler
  $btn.off("click");

  // Move car using CSS3 animation
  // and call initStates on animationend (event callback)
  $car.addClass("moveCar").one("animationend", initStates);
}

// INITIALIZE default states
initStates();

.car {
  position: relative;
  background: red;
  width: 20px;
  height: 20px;
}

.moveCar /* CLASS ADDED BY JQUERY */ {
  animation: move 2s ease-out;
  background: green;
}

@keyframes move {
  0% {
    left: 0;
  }
  100% {
    left: 80%;
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button class="btn">CLICK TO MOVE CAR</button>
<div class="car"></div>

If you use jQuery's .animate() than you can check if an item is animated using

if( $("selector").is(":animated") ) return;
// If a selector is animated the code below will not execute
alert("Animate next car!");

than, eventually, in order to memorize the clicked button while one car was animated - you could create a variable to store the value of the car to animate next once the current animated one triggers an .animate callback - Than remember to reset / null the variable after you've used it.

If instead - you want actually to have multiple cars running on screen - than you need to position your cars using

position: absolute;


来源: stackexchange

问:
Is there a free (LGPL< BSD, etc. ) RDF editor component for swing?
I look for a JComponenet based RDF editor which I could embed in my application?

It does'n need to be fancy .

Thanks in advance.

答: I don't know whether it's embeddable (or whether it even works), but take a look at http://sourceforge.net/projects/rdfeditor/.</p>

OwnerDisplayName: lbownik

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Steve McLeod

OwnerDisplayName: Brian Clapper


问:
How to block access to the .svn/entries on my webserver?
I setup an NGINX webserver and use svn to manage project folder. Nessus found the weakness:

Configure permissions for the affected

  web server to deny access to the

  '.svn' directory.

How do I block access to the .svn directory? It seems that svn export is the more preferable way to checkout on the webserver, but it easier to me to use svn up.

答:
Put the following in a file called ".htaccess" (if you're running Apache):</p>

```<code><FilesMatch "^\.svn">
  Deny from all
</FilesMatch>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Put the following in a file called ".htaccess" (if you're running Apache):

<FilesMatch "^\.svn">
  Deny from all
</FilesMatch>


问:
Apache drill losing unicode in TSVs
I'm using the text/tsv storage plugin with Apache drill and the output tsv files have ? for unicode characters. If I use the JSON storage plugin, the unicode is fine.

Something like:

URL: http://localhost:8047/query.json

Payload:

```<code>{
  "queryType":"SQL",
  "query": "CREATE TABLE st.`repo`.`test` AS SELECT * FROM st.`repo`.`unicode_data`"
}
</code>```

答:
Set the JVM file encoding and this is fixed.

JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF8

Title: Apache drill losing unicode in TSVs

Body:
I'm using the text/tsv storage plugin with Apache drill and the output tsv files have ? for unicode characters. If I use the JSON storage plugin, the unicode is fine.

Something like:

URL: http://localhost:8047/query.json

Payload:

{
  "queryType":"SQL",
  "query": "CREATE TABLE st.`repo`.`test` AS SELECT * FROM st.`repo`.`unicode_data`"
}


问:
How to store information from a file into variables?
This is a part of an assignment that I have been having some trouble on.From my googling, I think I have to split the array and I have gotten to the point where I am now.

The program reads over a text file and outputs the text in it to the console. It then asks the user to input a name relating to the text file.
It then reads the file over again and what is suppose to happen next is for the variable power to store a number from a text file based on their input.

When I run my code, the text file outputs and it asks for the input. Then nothing happens; what should happen is that my variable power should output the value in index 2 of my array named g which should be 10 based on my text file.

My text file is organized like this:

Giant

Power

10

I want my int power to store 10 and I think that would be in index 2.
and Character (variable) is what the name that they enter in when being asked, in this case, Giant.

Am a beginner to java and any help is appreciated.

Edit: for now this problem is solved, dont know if it works or not because as I 'fixed' this problem an ArrayIndexOutofBoundsException: 2 has occurred. Any ideas why?? This error is at line 46 which is int power = Integer.parseInt(g[2]);

```<code>while ((line = creatureRead.readLine()) != null)
{
  String[] g = line.split(" ");
  for (int index = 0; index < g.length; index++)
  {

    if (character.equals("Giant"))
    {
    int power = Integer.parseInt(g[2]);
    System.out.println(power);
    }
  }
      creatureRead.close();
}
}

catch (IOException e)
{
 e.printStackTrace();
}
</code>```

答:
From what I understand this is how your program works:

Read the file and display its content to the console in form of

[Creature] Power [Power value]

User inputs [Creature]

Program is supposed to display [Power value] for that creature

My guess is that you got to end of file that's why you can't read from it. After 1) close your file and open it in 3). Let me know if that's not the case.

Body:
This is a part of an assignment that I have been having some trouble on.From my googling, I think I have to split the array and I have gotten to the point where I am now.

The program reads over a text file and outputs the text in it to the console. It then asks the user to input a name relating to the text file.
It then reads the file over again and what is suppose to happen next is for the variable power to store a number from a text file based on their input.

When I run my code, the text file outputs and it asks for the input. Then nothing happens; what should happen is that my variable power should output the value in index 2 of my array named g which should be 10 based on my text file.

My text file is organized like this:

Giant

Power

10

I want my int power to store 10 and I think that would be in index 2.
and Character (variable) is what the name that they enter in when being asked, in this case, Giant.

Am a beginner to java and any help is appreciated.

Edit: for now this problem is solved, dont know if it works or not because as I 'fixed' this problem an ArrayIndexOutofBoundsException: 2 has occurred. Any ideas why?? This error is at line 46 which is int power = Integer.parseInt(g[2]);

while ((line = creatureRead.readLine()) != null)
{
  String[] g = line.split(" ");
  for (int index = 0; index < g.length; index++)
  {

    if (character.equals("Giant"))
    {
    int power = Integer.parseInt(g[2]);
    System.out.println(power);
    }
  }
      creatureRead.close();
}
}

catch (IOException e)
{
 e.printStackTrace();
}


问:
Error in Turtle recursion
I'm attempting to use Turtle Graphics to make a fractal via recursion, but for some reason my code seems to not return the Turtle back to the origin.
My code is as follows

```<code>public static void sun(Turtle t, double radius) {
for ( int i = 0; i < 360; i++ ) {
    t.forward( radius * .0174 );
    t.left( 1 );
}
    t.penup();
    t.left(90);
    t.forward(radius);
    //t.fill();
    t.pendown();
for (int i = 0; i < 8; i++) {
    t.forward(2*radius);
    t.backward(2*radius);
    t.left(45);
}
t.penup();
t.backward(radius);
t.right(90);
t.pendown();
}

public static void fractalSun(Turtle t, double r, int level) {
int color;
if (level == 0) {
  t.color(255, 0, 0);
  sun(t, r);
}
else {
  sun(t, r);
  t.left(90);
  t.forward(r);
  t.right(90);
  t.forward(r * 2);
  t.right(90);
  fractalSun(t, r/4, level -1);
  t.left(90);
  t.backward(r * 2);
 }
}
</code>```

The code compiles successfully, but produces this image:
Screenshot

My goal would be for the turtle to return to the center of each 'sun' but something isn't working.

答:
Your 8-spoke loop leaves the pen at the center of the figure after each spoke.  At the end of the loop, starting at the center, you execute this sequence:

```<code>t.penup();
t.backward(radius);
t.right(90);
t.pendown();
</code>```

In particular, you back up one radius; I think that's where you're getting off your intended point.  Drop that line, double-check your desired direction, and I think you'll be okay.

Title: Error in Turtle recursion

Body:
I'm attempting to use Turtle Graphics to make a fractal via recursion, but for some reason my code seems to not return the Turtle back to the origin.
My code is as follows

public static void sun(Turtle t, double radius) {
for ( int i = 0; i < 360; i++ ) {
    t.forward( radius * .0174 );
    t.left( 1 );
}
    t.penup();
    t.left(90);
    t.forward(radius);
    //t.fill();
    t.pendown();
for (int i = 0; i < 8; i++) {
    t.forward(2*radius);
    t.backward(2*radius);
    t.left(45);
}
t.penup();
t.backward(radius);
t.right(90);
t.pendown();
}

public static void fractalSun(Turtle t, double r, int level) {
int color;
if (level == 0) {
  t.color(255, 0, 0);
  sun(t, r);
}
else {
  sun(t, r);
  t.left(90);
  t.forward(r);
  t.right(90);
  t.forward(r * 2);
  t.right(90);
  fractalSun(t, r/4, level -1);
  t.left(90);
  t.backward(r * 2);
 }
}

The code compiles successfully, but produces this image:
Screenshot

My goal would be for the turtle to return to the center of each 'sun' but something isn't working.

Body:
Your 8-spoke loop leaves the pen at the center of the figure after each spoke.  At the end of the loop, starting at the center, you execute this sequence:

t.penup();
t.backward(radius);
t.right(90);
t.pendown();

In particular, you back up one radius; I think that's where you're getting off your intended point.  Drop that line, double-check your desired direction, and I think you'll be okay.


问:
How to transition resource just has been copied into onto copy queue to a state which copy queue doesn't support?
I copy data to my D3D12_HEAP_TYPE_DEFAULT buffers from my D3D12_HEAP_TYPE_UPLOAD intermediate buffers using D3D12_COMMAND_LIST_TYPE_COPY queue. After copy has been made, i need to transition resource back to D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER. But copy queue doesn't support transition to this state. How can i do it properly?

Should i insert fence right after copying, then wait for this fence on graphics queue and perform transition there, that is not really comfortable option. Any other possibilities?

答:
If you use a copy command list on the copy queue, your resource will decay back to common as describe in the quote. You can then either transition from common to vertex and constant buffer at the usage site explicitely, or do nothing because common will promote itself to anyway.

The following resources will decay when an ExecuteCommandLists
  operation is completed on the GPU: Resources being accessed on a Copy
  queue, or Buffer resources on any queue type, or Texture resources on
  any queue type that have the
  D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS flag set.


问:
Windows USB Device Location
I am looking for the proper WMI Win32 or CIM Class property to find the location of a USB device. In device manager, shown below, the Location is known as "Port_#0002.Hub_#0009". Any ideas on the class and property that this is in the Windows API or if it is an arbitrary value Device Manager gives another property which is more cryptic. If the latter, what is the "more cryptic" class and property?

Image: http://i.stack.imgur.com/7Miwp.png

答:
Use API SetupDiGetDeviceRegistryProperty
and const parameter SPDRP_LOCATION_INFORMATION.

Title: Windows USB Device Location


问:
how to to fit an image on a trapezium html canvas which I drew using path
[I want to add another image over the laptop screen`var ctx = myCanvas.getContext('2d');

```<code>                ctx.beginPath();
                ctx.moveTo(13,28);
                ctx.lineTo(237,7);
                ctx.lineTo(285,105);
                ctx.lineTo(73,151);
                ctx.closePath();
                   ctx.lineWidth = 0.5;
            ctx.strokeStyle = 'blue';
                ctx.stroke();
                //ctx.clip();
                //ctx.rotate(-20*Math.PI/180);
                var img = new Image;
                img.onload = function()
                {

                    var width = img.width;
                      var  height = img.height;
                    ctx.drawImage(img, 0, 0, img.width,    img.height,
                           0, 0, myCanvas.width, myCanvas.height);

                    }
                };
                img.src = reader.result;
               `][1]
</code>```

how do I skew the image to fit in the trapezium ctx that i have created

答:
Why 2D API is 2D

The canvas 2D API is called a 2D API for a very good reason. It can only do 2D transformations.

Not 2D

The shape you have...

The above image annotates your shape. Lines A,C are not parallel.

2D best fit

The canvas 2D transformation can not fit a rectangle to that shape as it does not carry enough information to deal with the converging lines and how to scale the pixels as they converge.

The best you can do is an approximation

The next image bisects the shape using two lines. These lines will be used to create the transform that will best fit the shape using the 2D transformation.

We use the bisecting lines to define the x and y axis of the transform and use the length of each to determine the scale. The center point of the image is the center of one of the bisecting lines.

const ctx = canvas.getContext("2d");
const path = [13, 28, 237, 7, 285, 105, 73, 151];
const imageURL = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Sarcoramphus_papa_%28K%C3%B6nigsgeier_-_King_Vulture%29_-_Weltvogelpark_Walsrode_2013-01.jpg/675px-Sarcoramphus_papa_%28K%C3%B6nigsgeier_-_King_Vulture%29_-_Weltvogelpark_Walsrode_2013-01.jpg";
function setStyle(style){
    Object.keys(style).forEach(key => ctx[key] = style[key]);
}
function drawPath(path, style) {
    var i = 0;
    setStyle(style);
    ctx.beginPath();
    ctx.moveTo(path[i++], path[i++]);
    while (i < path.length) {
        ctx.lineTo(path[i++], path[i++]);
    }
    ctx.closePath();
    ctx.stroke();
}
function markPath(path, style, marks) {
    var i = 0;
    var len = path.length;
    setStyle(style);
    while (i < len) {
        ctx.fillText(
            marks[i >> 1],
            (path[i] + path[((i++) + 2) % len]) / 2,
            (path[i] + path[((i++) + 2) % len]) / 2
        );
    }
}
function bisectPath(path, modulo, style) {
    var i = 0;
    var len = path.length;
    setStyle(style);
    ctx.beginPath();
    while (i < len) {
        ctx.moveTo(
            (path[i] + path[((i++) + 2) % len]) / 2,
            (path[i] + path[((i++) + 2) % len]) / 2
        );
        i += modulo;
        ctx.lineTo(
            (path[i] + path[((i++) + 2) % len]) / 2,
            (path[i] + path[((i++) + 2) % len]) / 2
        );
        i -= modulo + 2;
    }
    ctx.stroke();

}

// functions to create lines, get vectors, length and normals
function getLine(x1,y1,x2,y2){
   return {
      p1 : { x : x1 , y : y1 },
      p2 : { x : x2 , y : y2 }
   };
}
function getVec(line){
   line.vec = {
       x : line.p2.x - line.p1.x,
       y : line.p2.y - line.p1.y
   };
   return line;
}
function getNormal(line){
   line.len = Math.hypot(line.vec.x, line.vec.y);
   line.norm = {
       x : line.vec.x / line.len,
       y : line.vec.y / line.len,
   };
   return line;
}
// create the 2 bisecting lines
var line1 = getNormal( getVec( getLine(
     (path[0] + path[2]) / 2,
     (path[1] + path[3]) / 2,
     (path[4] + path[6]) / 2,
     (path[5] + path[7]) / 2
)));
var line2 = getNormal( getVec( getLine(
     (path[6] + path[0]) / 2,
     (path[7] + path[1]) / 2,
     (path[2] + path[4]) / 2,
     (path[3] + path[5]) / 2
)));

// create an image to fit
var image = new Image;
image.src = imageURL;
image.onload = function(){
    var w, h, sx, sy, cx, cy;
    w = this.width;
    h = this.height;
    // calculate the image scales
    sx = line2.len / w;
    sy = line1.len / h;
    // calculate the center
    cx = (line1.p1.x + line1.p2.x) / 2;
    cy = (line1.p1.y + line1.p2.y) / 2;

    // now we have all the information needed to create the transformation
    ctx.setTransform(
       line2.norm.x * sx,  // scale and direction of x axis
       line2.norm.y * sx,
       line1.norm.x * sy,  // scale and direction of y axis
       line1.norm.y * sy,
       cx, cy,             // the origin coordinate (0,0)
    );
    // Draw the image offset from its center by half its width and heigth
    ctx.drawImage(this, -w / 2, -h / 2);
    // reset the transformation
    ctx.setTransform(1,0,0,1,0,0);

    // draw the guides
    drawPath(path, {
        lineWidth : 0.5,
        strokeStyle : "blue"
    });
    bisectPath(path, 2, {
        lineWidth : 1,
        strokeStyle : "white"
    });
    markPath(path, {
        font : "18px arial",
        textAlign : "center",
        textBaseline : "middle",
        fillStyle : "black"
    }, ["A", "B", "C", "D"]);

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id=canvas height=160></canvas></code>```

That is the best you can do with the canvas 2D API. You could render each pixel calculating the 3D transform to fit the shape you have. Depending on the image size that can take some time (CPU) to do and the result will be OK.

WebGL for 3D

If you really need the 3D transform you should use webGL. There are plenty of examples on SO and the web on how to do that

Body:
[I want to add another image over the laptop screen`var ctx = myCanvas.getContext('2d');

                ctx.beginPath();
                ctx.moveTo(13,28);
                ctx.lineTo(237,7);
                ctx.lineTo(285,105);
                ctx.lineTo(73,151);
                ctx.closePath();
                   ctx.lineWidth = 0.5;
            ctx.strokeStyle = 'blue';
                ctx.stroke();
                //ctx.clip();
                //ctx.rotate(-20*Math.PI/180);
                var img = new Image;
                img.onload = function()
                {

                    var width = img.width;
                      var  height = img.height;
                    ctx.drawImage(img, 0, 0, img.width,    img.height,
                           0, 0, myCanvas.width, myCanvas.height);

                    }
                };
                img.src = reader.result;
               `][1]

how do I skew the image to fit in the trapezium ctx that i have created

Body:
Why 2D API is 2D

The canvas 2D API is called a 2D API for a very good reason. It can only do 2D transformations.

Not 2D

The shape you have...

The above image annotates your shape. Lines A,C are not parallel.

2D best fit

The canvas 2D transformation can not fit a rectangle to that shape as it does not carry enough information to deal with the converging lines and how to scale the pixels as they converge.

The best you can do is an approximation

The next image bisects the shape using two lines. These lines will be used to create the transform that will best fit the shape using the 2D transformation.

We use the bisecting lines to define the x and y axis of the transform and use the length of each to determine the scale. The center point of the image is the center of one of the bisecting lines.

const ctx = canvas.getContext("2d");
const path = [13, 28, 237, 7, 285, 105, 73, 151];
const imageURL = "https://upload.wikimedia.org/wikipedia/commons/thumb/5/55/Sarcoramphus_papa_%28K%C3%B6nigsgeier_-_King_Vulture%29_-_Weltvogelpark_Walsrode_2013-01.jpg/675px-Sarcoramphus_papa_%28K%C3%B6nigsgeier_-_King_Vulture%29_-_Weltvogelpark_Walsrode_2013-01.jpg";
function setStyle(style){
    Object.keys(style).forEach(key => ctx[key] = style[key]);
}
function drawPath(path, style) {
    var i = 0;
    setStyle(style);
    ctx.beginPath();
    ctx.moveTo(path[i++], path[i++]);
    while (i < path.length) {
        ctx.lineTo(path[i++], path[i++]);
    }
    ctx.closePath();
    ctx.stroke();
}
function markPath(path, style, marks) {
    var i = 0;
    var len = path.length;
    setStyle(style);
    while (i < len) {
        ctx.fillText(
            marks[i >> 1],
            (path[i] + path[((i++) + 2) % len]) / 2,
            (path[i] + path[((i++) + 2) % len]) / 2
        );
    }
}
function bisectPath(path, modulo, style) {
    var i = 0;
    var len = path.length;
    setStyle(style);
    ctx.beginPath();
    while (i < len) {
        ctx.moveTo(
            (path[i] + path[((i++) + 2) % len]) / 2,
            (path[i] + path[((i++) + 2) % len]) / 2
        );
        i += modulo;
        ctx.lineTo(
            (path[i] + path[((i++) + 2) % len]) / 2,
            (path[i] + path[((i++) + 2) % len]) / 2
        );
        i -= modulo + 2;
    }
    ctx.stroke();

}

// functions to create lines, get vectors, length and normals
function getLine(x1,y1,x2,y2){
   return {
      p1 : { x : x1 , y : y1 },
      p2 : { x : x2 , y : y2 }
   };
}
function getVec(line){
   line.vec = {
       x : line.p2.x - line.p1.x,
       y : line.p2.y - line.p1.y
   };
   return line;
}
function getNormal(line){
   line.len = Math.hypot(line.vec.x, line.vec.y);
   line.norm = {
       x : line.vec.x / line.len,
       y : line.vec.y / line.len,
   };
   return line;
}
// create the 2 bisecting lines
var line1 = getNormal( getVec( getLine(
     (path[0] + path[2]) / 2,
     (path[1] + path[3]) / 2,
     (path[4] + path[6]) / 2,
     (path[5] + path[7]) / 2
)));
var line2 = getNormal( getVec( getLine(
     (path[6] + path[0]) / 2,
     (path[7] + path[1]) / 2,
     (path[2] + path[4]) / 2,
     (path[3] + path[5]) / 2
)));

// create an image to fit
var image = new Image;
image.src = imageURL;
image.onload = function(){
    var w, h, sx, sy, cx, cy;
    w = this.width;
    h = this.height;
    // calculate the image scales
    sx = line2.len / w;
    sy = line1.len / h;
    // calculate the center
    cx = (line1.p1.x + line1.p2.x) / 2;
    cy = (line1.p1.y + line1.p2.y) / 2;

    // now we have all the information needed to create the transformation
    ctx.setTransform(
       line2.norm.x * sx,  // scale and direction of x axis
       line2.norm.y * sx,
       line1.norm.x * sy,  // scale and direction of y axis
       line1.norm.y * sy,
       cx, cy,             // the origin coordinate (0,0)
    );
    // Draw the image offset from its center by half its width and heigth
    ctx.drawImage(this, -w / 2, -h / 2);
    // reset the transformation
    ctx.setTransform(1,0,0,1,0,0);

    // draw the guides
    drawPath(path, {
        lineWidth : 0.5,
        strokeStyle : "blue"
    });
    bisectPath(path, 2, {
        lineWidth : 1,
        strokeStyle : "white"
    });
    markPath(path, {
        font : "18px arial",
        textAlign : "center",
        textBaseline : "middle",
        fillStyle : "black"
    }, ["A", "B", "C", "D"]);

}

<canvas id=canvas height=160></canvas>

That is the best you can do with the canvas 2D API. You could render each pixel calculating the 3D transform to fit the shape you have. Depending on the image size that can take some time (CPU) to do and the result will be OK.

WebGL for 3D

If you really need the 3D transform you should use webGL. There are plenty of examples on SO and the web on how to do that


问:
Python While loop inside a for loop that keeps on repeating while value is invalid
This is my code:

```<code>for i in range(1, 5):
    try:
        grade = int(input("Please enter {}'s grade for practical assessment {}: ".format(name, i)))
        while (grade < 0 and grade > 40):
            print("That is not a valid grade.")
            continue
    except ValueError:
        print("That is not a valid value.")
        continue
</code>```

My question is that how to check if the grade is in range and to make the loop repeat if a false input is entered. When I tried to run the program, and enter an over range input, it goes to the next assessment number instead of trying again until it's true.

答:
You could use something like this which uses a while True loop as well as a try statement and except clause to determine whether the user entered a valid grade:

```<code>names = ["Adam", "Bob", "Chloe"] # Example list of names

for name in names:
  for i in range(1, 5):
    while True:
      try:
        grade = int(input("Please enter {}'s grade for practical assessment {}: ".format(name, i)))
        if not (0 <= grade <= 40):
          raise ValueError()
      except ValueError:
        print("Error: Please enter a grade between 0 and 40")
      else:
        break
</code>```

Example Usage:

```<code>Please enter Adam's grade for practical assessment 1:  a
Error: Please enter a grade between 0 and 40
Please enter Adam's grade for practical assessment 1:  -1
Error: Please enter a grade between 0 and 40
Please enter Adam's grade for practical assessment 1:  10
Please enter Adam's grade for practical assessment 2:  4
Please enter Adam's grade for practical assessment 3:
...
</code>```

Try it here!

Body:
This is my code:

for i in range(1, 5):
    try:
        grade = int(input("Please enter {}'s grade for practical assessment {}: ".format(name, i)))
        while (grade < 0 and grade > 40):
            print("That is not a valid grade.")
            continue
    except ValueError:
        print("That is not a valid value.")
        continue

My question is that how to check if the grade is in range and to make the loop repeat if a false input is entered. When I tried to run the program, and enter an over range input, it goes to the next assessment number instead of trying again until it's true.

Body:
You could use something like this which uses a while True loop as well as a try statement and except clause to determine whether the user entered a valid grade:

names = ["Adam", "Bob", "Chloe"] # Example list of names

for name in names:
  for i in range(1, 5):
    while True:
      try:
        grade = int(input("Please enter {}'s grade for practical assessment {}: ".format(name, i)))
        if not (0 <= grade <= 40):
          raise ValueError()
      except ValueError:
        print("Error: Please enter a grade between 0 and 40")
      else:
        break

Example Usage:

Please enter Adam's grade for practical assessment 1:  a
Error: Please enter a grade between 0 and 40
Please enter Adam's grade for practical assessment 1:  -1
Error: Please enter a grade between 0 and 40
Please enter Adam's grade for practical assessment 1:  10
Please enter Adam's grade for practical assessment 2:  4
Please enter Adam's grade for practical assessment 3:
...

Try it here!


问:
Car Class Python Program
Here is my code. I keep getting a Name Error as my result. How should I fix this problem?

Car Class

```<code>class Car:
    def __init__(self, year, make, speed):
        self.__year_model = year
        self.__make = make
        self.__speed = 0

    def set_year_model(self, year):
        self.__year_model = year

    def set_make(self, make):
        self.__make = make

    def set_speed(self, speed):
        self.__speed = 0

    def get_year_model(self):
        return self.__year_model

    def get_make(self):
        return self.__make

    def get_speed(self):
        return self.__speed

    #methods
    def accelerate(self):
        self.speed +=5

    def brake(self):
        self.speed -=5

    def get_speed(self):
        return self.speed
</code>```

Program

```<code>import Lab9_prob2

def main():

    year = input('Enter the car year: ')
    make = input('Enter the car make: ')
    speed = 0

    #Accelerate 5 times
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())

    #Brake 5 times
    mycar.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    my_car.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    my_car.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    my_car.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    my_car.brake()
    print('The current speed after brake is: ', mycar.get_speed())

#Call the main function
main()
</code>```

答:
Your code has several problems:

You have not created an instance: mycar = Car(year, make, speed)

You have renamed mycar to my_car: ie my_car.brake()

The class attribute is called self.__speed, it is not called self.speed.(accelerate, brake and get_speed methods)

```<code>class Car:
    def __init__(self, year, make, speed):
        self.__year_model = year
        self.__make = make
        self.__speed = 0

    def set_year_model(self, year):
        self.__year_model = year

    def set_make(self, make):
        self.__make = make

    def set_speed(self, speed):
        self.__speed = 0

    def get_year_model(self):
        return self.__year_model

    def get_make(self):
        return self.__make

    def get_speed(self):
        return self.__speed

    #methods
    def accelerate(self):
        self.__speed +=5

    def brake(self):
        self.__speed -=5

    def get_speed(self):
        return self.__speed

def main():

    year = input('Enter the car year: ')
    make = input('Enter the car make: ')
    speed = 0

    mycar = Car(year, make, speed)

    #Accelerate 5 times
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())

    #Brake 5 times
    mycar.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    mycar.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    mycar.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    mycar.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    mycar.brake()
    print('The current speed after brake is: ', mycar.get_speed())

#Call the main function
main()
</code>```

Title: Car Class Python Program

Body:
Here is my code. I keep getting a Name Error as my result. How should I fix this problem?

Car Class

class Car:
    def __init__(self, year, make, speed):
        self.__year_model = year
        self.__make = make
        self.__speed = 0

    def set_year_model(self, year):
        self.__year_model = year

    def set_make(self, make):
        self.__make = make

    def set_speed(self, speed):
        self.__speed = 0

    def get_year_model(self):
        return self.__year_model

    def get_make(self):
        return self.__make

    def get_speed(self):
        return self.__speed

    #methods
    def accelerate(self):
        self.speed +=5

    def brake(self):
        self.speed -=5

    def get_speed(self):
        return self.speed

Program

import Lab9_prob2

def main():

    year = input('Enter the car year: ')
    make = input('Enter the car make: ')
    speed = 0

    #Accelerate 5 times
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())

    #Brake 5 times
    mycar.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    my_car.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    my_car.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    my_car.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    my_car.brake()
    print('The current speed after brake is: ', mycar.get_speed())

#Call the main function
main()

Body:
Your code has several problems:

You have not created an instance: mycar = Car(year, make, speed)

You have renamed mycar to my_car: ie my_car.brake()

The class attribute is called self.__speed, it is not called self.speed.(accelerate, brake and get_speed methods)

class Car:
    def __init__(self, year, make, speed):
        self.__year_model = year
        self.__make = make
        self.__speed = 0

    def set_year_model(self, year):
        self.__year_model = year

    def set_make(self, make):
        self.__make = make

    def set_speed(self, speed):
        self.__speed = 0

    def get_year_model(self):
        return self.__year_model

    def get_make(self):
        return self.__make

    def get_speed(self):
        return self.__speed

    #methods
    def accelerate(self):
        self.__speed +=5

    def brake(self):
        self.__speed -=5

    def get_speed(self):
        return self.__speed

def main():

    year = input('Enter the car year: ')
    make = input('Enter the car make: ')
    speed = 0

    mycar = Car(year, make, speed)

    #Accelerate 5 times
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())
    mycar.accelerate()
    print('The current speed is: ', mycar.get_speed())

    #Brake 5 times
    mycar.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    mycar.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    mycar.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    mycar.brake()
    print('The current speed after brake is: ', mycar.get_speed())
    mycar.brake()
    print('The current speed after brake is: ', mycar.get_speed())

#Call the main function
main()


问:
Default behaviour when starting up Intern tests with Selenium Tunnel
I was just wondering if this was the default behaviour when starting up Intern with a Selenium Tunnel. At the moment, before running any tests, random pages that appear to look like the Intern-tutorial, which I used to learn how to run tests with Intern, seem to come up before attempting to run any of my own tests.

I have set up a vanilla install with no tests set up to demonstrate this behaviour. Please see the video link given below as reference if I have been unclear.

https://www.youtube.com/watch?v=vC15PbjSxVw

答: Leadfoot, which is the WebDriver implementation used by Intern, performs feature and defect tests on the browser before testing starts. These tests tell intern about features that a particular browser might not support, or might implement incorrectly, giving Intern (well, Leadfoot) a chance to work around them.</p>


问:
modal is not displaying data separately
I want to update my table using bootstrap dialog , but I when I retrieve my datatable from server side and embed php code into my modal to show the table data into the modal, and choose what the user wants to update in that form. it is showing the data from every row of my table into the modal , how can I fix it?

form_modal

```<code><form id="product_update">
   <div class="row">
   <div class="form-group">
   <?php foreach ($product as $value): ?>
   <div class="col-xs-12">
      <label for="description">Name: </label>
      <input type="text" class="form-control" id="description" name="description" title="product description" value="<?php echo $value['descripcion']; ?>" required>
      <div>
      </div>
   </div>
   <div class="row">
      <div class="form-group">
         <div class="col-xs-8 col-sm-6">
            <label for="cost_price">Cost Price:</label>
            <div class="input-group"> <span class="input-group-addon">$</span>
               <input type="text" class="form-control input-group-lg reg_name" id="cost_price" name="cost_price" title="cost_price"  placeholder="Last name" value="<?php echo $value['precio_compra']; ?>" required>
            </div>
         </div>
         <div class="col-xs-8 col-sm-6">
            <label for="selling_price">Selling price: </label>
            <input type="text" class="form-control input-group-lg reg_name" id="selling_price" name="selling_price" title="selling_price" placeholder="Last name" value="<?php echo $value['precio_venta']; ?>" required>
         </div>
      </div>
   </div>
   <div class="row">
      <div class="form-group">
         <div class="col-xs-8 col-sm-6">
            <label for="wprice">Wholeprice: </label>
            <input type="text" class="form-control" id="wprice" name="wprice" title="wprice" value="<?php echo $value['precio_mayoreo']; ?>" required>
         </div>
         <div class="col-xs-8 col-sm-6">
            <label for="min_stock">Min stock: </label>
            <input type="text" class="form-control" id="min_stock" name="min_stock" title="min_stock" value="<?php echo $value['existencia_minima']; ?>" required>
         </div>
      </div>
   </div>
   <div class="row">
      <div class="form-group">
         <div class="col-xs-8 col-sm-6">
            <label for="stock">Stock: </label>
            <input type="text" class="form-control" id="stock" name="stock" title="stock" value="<?php echo $value['existencia']; ?>" required>
         </div>
         <div class="col-xs-8 col-sm-6">
            <label for="max_stock">Max stock: </label>
            <input type="text" class="form-control" id="max_stock" name="max_stock" title="max_stock" value="<?php echo $value['existencia_maxima']; ?>" required>
         </div>
      </div>
   </div>
  <?php endforeach ?>
   <div class="row">
      <div class="form-group">
         <div class="col-xs-8 col-sm-6">
            <label for="provider">Provider: </label>
            <select name="select-provider" id="select-provider">
                <option value="0">Select a provider</option>
                <?php foreach ($data as $value): ?>
                   <option value="<?php echo $value['id']; ?>"><?php echo $value['first_name'].' '.$value['last_name'] ?></option>
                <?php endforeach ?>
            </select>
         </div>
      </div>
   </div>
</form>
</code>```

modal js

```<code>$('#example tbody').on('click', 'a', function(event) {
    event.preventDefault();
    var data = table.row($(this).parents('tr')).data();
    hash = data[0];
    $("#product_update").validate();
    BootstrapDialog.show({
        type: BootstrapDialog.TYPE_WARNING,
        message: function(dialog) {
            var $message = $('<div></div>');
            var pageToLoad = dialog.getData('pageToLoad');
            $message.load(pageToLoad);

            return $message;
        },
        data: {
            'pageToLoad': URL_GET_VIEW_PRODUCT_UPDATE
        },
        closable: false,
        buttons: [{
            id: 'btn-ok',
            cssClass: 'btn-primary',
            icon: 'glyphicon glyphicon-send',
            label: ' Save',
            action: function(e) {
                var description = $('#description').val();
                var description = $('#description').val();
                var cost_price = $('#cost_price').val();
                var selling_price = $('#selling_price').val();
                var wprice = $('#wprice').val();
                var min_stock = $('#min_stock').val();
                var stock = $('#stock').val();
                var max_stock = $('#max_stock').val();
                var provider_id = $('#select_provider').val();
                if ($("#product_update").valid()) {
                    $.ajax({
                        url: URL_GET_UPDATE_PRODUCT,
                        type: 'POST',
                        data: { hash: hash, provider_id: provider_id, description: description, cost_price: cost_price,  selling_price: selling_price, wprice: wprice, min_stock: min_stock,   stock: stock, max_stock: max_stock },
                        success: function(data) {
                            console.log(data);
                            if (data.msg == 'successfully updated') {
                                $('#product_update')[0].reset();
                                table.ajax.reload();
                            } else if (data.min_stock == 'el stock no puede ser mayor al min') {
                                BootstrapDialog.show({
                                    type: BootstrapDialog.TYPE_DANGER,
                                    message: 'el stock no puede ser mayor al min'
                                });
                            }
                        }
                    });
                }
            }
        },{
            id: 'btn-cancel',
            cssClass: 'btn-danger',
            icon: 'glyphicon glyphicon-remove',
            label: ' Cancel',
            action: function(e) {
                e.close();
            }
        }]
    });
});
</code>```

model product

```<code>public function datatable(){
        $this->db->select('hash_id,codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,existencia_maxima,storelte_articulos.status');
        $this->db->from('storelte_articulos');
        $query = $this->db->get();
        return $query->result_array();
    }
    public function isExistsProduct($data){
        $this->db->select('descripcion');
        $this->db->from('storelte_articulos');
        $this->db->where('descripcion',$data['descripcion']);
        $query = $this->db->get();
        return $query->num_rows() == 0 ? false : true;
    }

    public function addProduct($data){
        $query = 'UPDATE storelte_articulos SET hash_id = MD5(id) WHERE id = LAST_INSERT_ID()';
        $this->db->insert('storelte_articulos',$data);
        $this->db->query($query);
    }

    public function updateProduct($data) {
        $this->db->where('md5(id)',$this->input->post('hash'));
        $this->db->update('storelte_articulos',$data);
    }

     public function get_product() {
    $this->db->select('codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia_maxima,existencia');
    $this->db->from('storelte_articulos');
    $this->db->where('md5(id)', $this->input->post('hash'));
    $query = $this->db->get();
    return $query->result_array();
}
</code>```

modal img

答:
I suspect your query is not targeting the single row that you intend to access.
If you are not querying on your table Primary/Unique Key, you should add LIMIT 1 --but really you should be using the PK.

Also, you seem to be looping through all of the results from the query.

You'll need to post more of your code, because I can only make assumptions from what you've provided.

Why are you putting the Warning element at the top?

Where did you copy/paste your scripts from?

```<code>public function datatable(){
    $this->db->select('hash_id,codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,existencia_maxima,storelte_articulos.status');
</code>```

You will need some sort of $this->db->where() statement here that references the appropriate row id.

like:  $this->db->where('id',$this->input->post('id'));

```<code>    $this->db->from('storelte_articulos');
    $query = $this->db->get();
    return $query->result_array();
}
</code>```

Title: modal is not displaying data separately

Body:
I want to update my table using bootstrap dialog , but I when I retrieve my datatable from server side and embed php code into my modal to show the table data into the modal, and choose what the user wants to update in that form. it is showing the data from every row of my table into the modal , how can I fix it?

form_modal

<form id="product_update">

   <?php foreach ($product as $value): ?>

      Name:
      <input type="text" class="form-control" id="description" name="description" title="product description" value="<?php echo $value['descripcion']; ?>" required>

            Cost Price:

 $
               <input type="text" class="form-control input-group-lg reg_name" id="cost_price" name="cost_price" title="cost_price"  placeholder="Last name" value="<?php echo $value['precio_compra']; ?>" required>

            Selling price:
            <input type="text" class="form-control input-group-lg reg_name" id="selling_price" name="selling_price" title="selling_price" placeholder="Last name" value="<?php echo $value['precio_venta']; ?>" required>

            Wholeprice:
            <input type="text" class="form-control" id="wprice" name="wprice" title="wprice" value="<?php echo $value['precio_mayoreo']; ?>" required>

            Min stock:
            <input type="text" class="form-control" id="min_stock" name="min_stock" title="min_stock" value="<?php echo $value['existencia_minima']; ?>" required>

            Stock:
            <input type="text" class="form-control" id="stock" name="stock" title="stock" value="<?php echo $value['existencia']; ?>" required>

            Max stock:
            <input type="text" class="form-control" id="max_stock" name="max_stock" title="max_stock" value="<?php echo $value['existencia_maxima']; ?>" required>

  <?php endforeach ?>

            Provider:
            <select name="select-provider" id="select-provider">
                <option value="0">Select a provider</option>
                <?php foreach ($data as $value): ?>
                   <option value="<?php echo $value['id']; ?>"><?php echo $value['first_name'].' '.$value['last_name'] ?></option>
                <?php endforeach ?>
            </select>

</form>

modal js

$('#example tbody').on('click', 'a', function(event) {
    event.preventDefault();
    var data = table.row($(this).parents('tr')).data();
    hash = data[0];
    $("#product_update").validate();
    BootstrapDialog.show({
        type: BootstrapDialog.TYPE_WARNING,
        message: function(dialog) {
            var $message = $('

');
            var pageToLoad = dialog.getData('pageToLoad');
            $message.load(pageToLoad);

            return $message;
        },
        data: {
            'pageToLoad': URL_GET_VIEW_PRODUCT_UPDATE
        },
        closable: false,
        buttons: [{
            id: 'btn-ok',
            cssClass: 'btn-primary',
            icon: 'glyphicon glyphicon-send',
            label: ' Save',
            action: function(e) {
                var description = $('#description').val();
                var description = $('#description').val();
                var cost_price = $('#cost_price').val();
                var selling_price = $('#selling_price').val();
                var wprice = $('#wprice').val();
                var min_stock = $('#min_stock').val();
                var stock = $('#stock').val();
                var max_stock = $('#max_stock').val();
                var provider_id = $('#select_provider').val();
                if ($("#product_update").valid()) {
                    $.ajax({
                        url: URL_GET_UPDATE_PRODUCT,
                        type: 'POST',
                        data: { hash: hash, provider_id: provider_id, description: description, cost_price: cost_price,  selling_price: selling_price, wprice: wprice, min_stock: min_stock,   stock: stock, max_stock: max_stock },
                        success: function(data) {
                            console.log(data);
                            if (data.msg == 'successfully updated') {
                                $('#product_update')[0].reset();
                                table.ajax.reload();
                            } else if (data.min_stock == 'el stock no puede ser mayor al min') {
                                BootstrapDialog.show({
                                    type: BootstrapDialog.TYPE_DANGER,
                                    message: 'el stock no puede ser mayor al min'
                                });
                            }
                        }
                    });
                }
            }
        },{
            id: 'btn-cancel',
            cssClass: 'btn-danger',
            icon: 'glyphicon glyphicon-remove',
            label: ' Cancel',
            action: function(e) {
                e.close();
            }
        }]
    });
});

model product

public function datatable(){
        $this->db->select('hash_id,codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,existencia_maxima,storelte_articulos.status');
        $this->db->from('storelte_articulos');
        $query = $this->db->get();
        return $query->result_array();
    }
    public function isExistsProduct($data){
        $this->db->select('descripcion');
        $this->db->from('storelte_articulos');
        $this->db->where('descripcion',$data['descripcion']);
        $query = $this->db->get();
        return $query->num_rows() == 0 ? false : true;
    }

    public function addProduct($data){
        $query = 'UPDATE storelte_articulos SET hash_id = MD5(id) WHERE id = LAST_INSERT_ID()';
        $this->db->insert('storelte_articulos',$data);
        $this->db->query($query);
    }

    public function updateProduct($data) {
        $this->db->where('md5(id)',$this->input->post('hash'));
        $this->db->update('storelte_articulos',$data);
    }

     public function get_product() {
    $this->db->select('codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia_maxima,existencia');
    $this->db->from('storelte_articulos');
    $this->db->where('md5(id)', $this->input->post('hash'));
    $query = $this->db->get();
    return $query->result_array();
}

modal img

Body:
I suspect your query is not targeting the single row that you intend to access.
If you are not querying on your table Primary/Unique Key, you should add LIMIT 1 --but really you should be using the PK.

Also, you seem to be looping through all of the results from the query.

You'll need to post more of your code, because I can only make assumptions from what you've provided.

Why are you putting the Warning element at the top?

Where did you copy/paste your scripts from?

public function datatable(){
    $this->db->select('hash_id,codigo,descripcion,precio_compra,precio_venta,precio_mayoreo,existencia_minima,existencia,existencia_maxima,storelte_articulos.status');

You will need some sort of $this->db->where() statement here that references the appropriate row id.

like:  $this->db->where('id',$this->input->post('id'));

    $this->db->from('storelte_articulos');
    $query = $this->db->get();
    return $query->result_array();
}


问:
A quickie: python, terminal "print command not found"
Been using terminal to run python scripts written in textwrangler for about 18 months. Decided to look at possibility of moving to an IDE so downloaded a couple of trial versions. Just downloaded BBEedit and suddenly having problems executing script, either from BBedit or Textwrangler. The following code:

```<code>print "Please work"

for i in range(50):
    print i
</code>```

yields the following error message:

```<code>/Users/paulpatterson/Documents/Python/Scripts/t.py: line 1: print: command not found
/Users/paulpatterson/Documents/Python/Scripts/t.py: line 3: syntax error near unexpected token `('
/Users/paulpatterson/Documents/Python/Scripts/t.py: line 3: `for i in range(50):'
</code>```

Some files still work okay, but I'm struggling to figure out why others now aren't -
not even sure if BBedit download has caused the problem.
Can anyone help?

答: It's running the script as a shell script, not a Python script.</p>

Body:
Been using terminal to run python scripts written in textwrangler for about 18 months. Decided to look at possibility of moving to an IDE so downloaded a couple of trial versions. Just downloaded BBEedit and suddenly having problems executing script, either from BBedit or Textwrangler. The following code:

print "Please work"

for i in range(50):
    print i

yields the following error message:

/Users/paulpatterson/Documents/Python/Scripts/t.py: line 1: print: command not found
/Users/paulpatterson/Documents/Python/Scripts/t.py: line 3: syntax error near unexpected token `('
/Users/paulpatterson/Documents/Python/Scripts/t.py: line 3: `for i in range(50):'

Some files still work okay, but I'm struggling to figure out why others now aren't -
not even sure if BBedit download has caused the problem.
Can anyone help?


问:
PyQt timer in GUI to update info
I am creating a GUI in python to display info from some sensors.

This way, i want that after pressing a linking pushbutton, the GUI periodically updates info. Here is the code:

```<code>def linkage(self, Form):
    self.s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
    self.label_communication.setText("aaaa")
    try:
        ip=self.lineEdit_ip.text()
        port=self.lineEdit_2.text()
        self.s.connect((ip,int(port)));
        self.label_communication.setText("connected")
        #self.timer = QtCore.QTimer()
        #self.timer.timeout.connect(updatefunc)
        #self.timer.start(1000)
    except:
        self.label_communication.setText("not connected")
</code>```

When i press the button with the timer lines commented, the label shows "connected". But when the timer is not commented, it shows "not connected".

How should i solve this?

Thanks

答:
you are using try/except so you are suppressing the original error.  So in your case either remove tr/except or use a print or traceback, I prefer traceback

```<code>import traceback
try:
   your_code
except:
   print traceback.format_exc()
   self.label_communication.setText("not connected")
</code>```

this will show what exactly happening without erroring out

Title: PyQt timer in GUI to update info

Body:
I am creating a GUI in python to display info from some sensors.

This way, i want that after pressing a linking pushbutton, the GUI periodically updates info. Here is the code:

def linkage(self, Form):
    self.s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);
    self.label_communication.setText("aaaa")
    try:
        ip=self.lineEdit_ip.text()
        port=self.lineEdit_2.text()
        self.s.connect((ip,int(port)));
        self.label_communication.setText("connected")
        #self.timer = QtCore.QTimer()
        #self.timer.timeout.connect(updatefunc)
        #self.timer.start(1000)
    except:
        self.label_communication.setText("not connected")

When i press the button with the timer lines commented, the label shows "connected". But when the timer is not commented, it shows "not connected".

How should i solve this?

Thanks

Body:
you are using try/except so you are suppressing the original error.  So in your case either remove tr/except or use a print or traceback, I prefer traceback

import traceback
try:
   your_code
except:
   print traceback.format_exc()
   self.label_communication.setText("not connected")

this will show what exactly happening without erroring out


问:
(C#) Unity2D - Animation Fighting my Character's Movement?
I'd like to thank you in advance for helping me with this issue.

I have a player that consists of three part:
The body
The head
and the Arm

All three of these are individual sprites.

I have grouped them all under one Empty GameObject that I named "Player"

I have then added an animation on the "Player" GameObject that changes the Y position from 0 to 0.022, and then from 0.022 back to 0.
This create a nice little hover animation where the character bounces up and down.

The animation works perfectly fine!

However, I also have a script attached to the "Player" object, this script is called "PlayerController".

In PlayerController I change the player's x Position if they hold down A (for leftwards movement) or D (for rightwards movement).

```<code>protected bool facingRight = true;
float xPos = 0;

void Update()
{
    if (Input.GetKey(KeyCode.D))
    {
        xPos += 0.01f;
        if (!facingRight)
        {
            Flip();
        }
    }
    else if (Input.GetKey(KeyCode.A))
    {
        xPos -= 0.01f;

        if (facingRight)
        {
            Flip();
        }
    }

    gameObject.transform.position = new Vector2(xPos, transform.position.y);

}

protected void Flip()
{
    facingRight = !facingRight;
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
}
</code>```

When I hold A or D, the character refuses to move. However he does flip correctly.

I personally think my animation is fighting the script, and that the animation has a higher priority than the script...?

Here's a video of me explaining my issue

(Not sure if videos are generally accepted in this community or not. If not, then I apologize)

If you guys could please help me understand what is happening and how to correct it I would be extremely grateful.

Thank you! :)

答:
Solved the problem after hours of tinkering.

Turns out the solution was simple:

All I had to do was structure my player like this:

Player (Empty GameObject)

PlayerAssembly (Body, Head, and Arm's parent)

Body Parts (Body, Head, Arm)

and then put the script, rigidBody2D, and collider on "Player".

Then put the animator on "PlayerAssembly".

Body:
I'd like to thank you in advance for helping me with this issue.

I have a player that consists of three part:
The body
The head
and the Arm

All three of these are individual sprites.

I have grouped them all under one Empty GameObject that I named "Player"

I have then added an animation on the "Player" GameObject that changes the Y position from 0 to 0.022, and then from 0.022 back to 0.
This create a nice little hover animation where the character bounces up and down.

The animation works perfectly fine!

However, I also have a script attached to the "Player" object, this script is called "PlayerController".

In PlayerController I change the player's x Position if they hold down A (for leftwards movement) or D (for rightwards movement).

protected bool facingRight = true;
float xPos = 0;

void Update()
{
    if (Input.GetKey(KeyCode.D))
    {
        xPos += 0.01f;
        if (!facingRight)
        {
            Flip();
        }
    }
    else if (Input.GetKey(KeyCode.A))
    {
        xPos -= 0.01f;

        if (facingRight)
        {
            Flip();
        }
    }

    gameObject.transform.position = new Vector2(xPos, transform.position.y);

}

protected void Flip()
{
    facingRight = !facingRight;
    Vector3 theScale = transform.localScale;
    theScale.x *= -1;
    transform.localScale = theScale;
}

When I hold A or D, the character refuses to move. However he does flip correctly.

I personally think my animation is fighting the script, and that the animation has a higher priority than the script...?

Here's a video of me explaining my issue

(Not sure if videos are generally accepted in this community or not. If not, then I apologize)

If you guys could please help me understand what is happening and how to correct it I would be extremely grateful.

Thank you! :)


问:
Scale text label by screen size
Is there a way to scale text so that it takes up close to the same screen real estate no matter what the device size is? I've found that the text on an iPad sized device is too small in relation to the screen size when compared to the iPhone. Below is an example of what I'm looking for. Notice the text percentage size is similar in relation to the device screen size.

Example

答:
I was having the same issue where I needed the text to be scaled proportionally along with the screen size increase.

Adaptive sizing is quite limited as you can only set the font sizing for size classes. Having the font sizes for two width options, compact and regular was not a solution for me.

I have written a small lib which handles automatic font scaling for UILabel and UITextView for different screen sizes.

You can set the scaling globally or for a specific instance of UILabel and UITextView.

Find it here: AMXFontAutoScale

Title: Scale text label by screen size


问:
how to convert string to date (HHMMMDD) (hour, month, day-of-month)
I try to convert a string into date type. This is the whole what I did.

```<code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHMMMDD");

String date = "23Mar25";

System.out.println(date);

LocalDate localDate = LocalDate.parse(date, formatter);

System.out.println(localDate);
</code>```

And I got the error information as

```<code>Text '23Mar25' could not be parsed:
Unable to obtain LocalDate from TemporalAccessor:
{MonthOfYear=3, DayOfYear=25},ISO resolved to 23:00 of type
java.time.format.Parsed at
java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
</code>```

Anyone can help me to solve it?

答:
```<code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHMMMDD");
</code>```

It is using a pattern for:

```<code>HH: 2 spaces for hour
MMM: 3 spaces for month
DD: 2 spaces for day
</code>```

I think you want a format like: `ddmmmyy

```<code>dd: 2 spaces for day
mmm: 3 spaces for month
yy: 2 spaces for year
</code>```

Body:
I try to convert a string into date type. This is the whole what I did.

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHMMMDD");

String date = "23Mar25";

System.out.println(date);

LocalDate localDate = LocalDate.parse(date, formatter);

System.out.println(localDate);

And I got the error information as

Text '23Mar25' could not be parsed:
Unable to obtain LocalDate from TemporalAccessor:
{MonthOfYear=3, DayOfYear=25},ISO resolved to 23:00 of type
java.time.format.Parsed at
java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)

Anyone can help me to solve it?

Body:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HHMMMDD");

It is using a pattern for:

HH: 2 spaces for hour
MMM: 3 spaces for month
DD: 2 spaces for day

I think you want a format like: `ddmmmyy

dd: 2 spaces for day
mmm: 3 spaces for month
yy: 2 spaces for year


问:
Mysql - select several rows with same value
I've got a table called 'data', and some columns:

user,unit,price,discount,description.

```<code> -----   -----  ------  ---------   -----------
| user | unit |  price | discount | description |
 -----   -----  ------  ---------   -----------
| test | unit |  100   |    50    |     des     |
-----   -----  -------   --------   -----------
| test2| unit2 |  200  |    20    |     des     |
 -----   -----  -----    --------   -----------
</code>```

```<code><?php
 if($_SERVER['REQUEST_METHOD']=='GET'){
 $id  = $_GET['id'];
 require_once('dbConnect.php');
 $sql = "SELECT * FROM data WHERE description='".$id."'";
 $r = mysqli_query($con,$sql);
 $res = mysqli_fetch_array($r);
 $result = array();
 array_push($result,array(
     "user"=>$res['user'],
     "unit"=>$res['unit'],
     "price"=>$res['price'],
     "discount"=>$res['discount']
 )
 );
 echo json_encode(array("result"=>$result));
 mysqli_close($con);
 }
</code>```

From this code, I get:

```<code>{"result":[{"user":"test","unit":"unit","price":"100","discount":"50"}]}
</code>```

so it's just the first row. I want to get both of them like this:

```<code>{"result":[{"user":"test","unit":"unit","price":"100","discount":"50"}]}
{"result2":[{"user":"test2","unit":"unit2","price":"200","discount":"20"}]}
</code>```

so there will be 2 arrays.

答:
You will need to write a loop containing calls of mysqli_fetch_assoc().  As you iterate, store the rows of data.

```<code>while($row = mysqli_fetch_assoc($r)){
    array_push($result, array(
         "user" => $row['user'],
         "unit" => $row['unit'],
         "price" => $row['price'],
         "discount" => $row['discount']
         )
     );
}
</code>```

Or if you replace the * in your SELECT clause to nominate your desired rows, you can use the top-voted comment on the mysqli_fetch_assoc() manual page...

```<code>for ($result = []; $row = mysqli_fetch_assoc($r); $result[] = $row);
</code>```

This compact one-liner will convert your resultset into a multidimensional array with the same structure as the previous code block without the iterated array_push() function calls.

Body:
I've got a table called 'data', and some columns:

user,unit,price,discount,description.

 -----   -----  ------  ---------   -----------
| user | unit |  price | discount | description |
 -----   -----  ------  ---------   -----------
| test | unit |  100   |    50    |     des     |
-----   -----  -------   --------   -----------
| test2| unit2 |  200  |    20    |     des     |
 -----   -----  -----    --------   -----------

<?php
 if($_SERVER['REQUEST_METHOD']=='GET'){
 $id  = $_GET['id'];
 require_once('dbConnect.php');
 $sql = "SELECT * FROM data WHERE description='".$id."'";
 $r = mysqli_query($con,$sql);
 $res = mysqli_fetch_array($r);
 $result = array();
 array_push($result,array(
     "user"=>$res['user'],
     "unit"=>$res['unit'],
     "price"=>$res['price'],
     "discount"=>$res['discount']
 )
 );
 echo json_encode(array("result"=>$result));
 mysqli_close($con);
 }

From this code, I get:

{"result":[{"user":"test","unit":"unit","price":"100","discount":"50"}]}

so it's just the first row. I want to get both of them like this:

{"result":[{"user":"test","unit":"unit","price":"100","discount":"50"}]}
{"result2":[{"user":"test2","unit":"unit2","price":"200","discount":"20"}]}

so there will be 2 arrays.

Body:
You will need to write a loop containing calls of mysqli_fetch_assoc().  As you iterate, store the rows of data.

while($row = mysqli_fetch_assoc($r)){
    array_push($result, array(
         "user" => $row['user'],
         "unit" => $row['unit'],
         "price" => $row['price'],
         "discount" => $row['discount']
         )
     );
}

Or if you replace the * in your SELECT clause to nominate your desired rows, you can use the top-voted comment on the mysqli_fetch_assoc() manual page...

for ($result = []; $row = mysqli_fetch_assoc($r); $result[] = $row);

This compact one-liner will convert your resultset into a multidimensional array with the same structure as the previous code block without the iterated array_push() function calls.

ContentLicense: CC BY-SA 4.0


答:
```<code><?php
 if($_SERVER['REQUEST_METHOD']=='GET'){
 $id  = $_GET['id'];
 require_once('dbConnect.php');
 $sql = "SELECT * FROM data WHERE description='".$id."'";
 $r = mysqli_query($con,$sql);
 $result = array();
 while ($res = mysqli_fetch_assoc($r)){
    $aRaw["user"] = $res['user'];
    $aRaw["unit"] = $res['unit'];
    $aRaw["price"] = $res['price'];
    $aRaw["discount"] = $res['discount'];
    $result[] = $aRaw;
 }
 );
 echo json_encode(array("result"=>$result));
 mysqli_close($con);
 }
</code>```

Warning: code is vulnerable to SQL injection attacks

Title: Mysql - select several rows with same value

Body:
<?php
 if($_SERVER['REQUEST_METHOD']=='GET'){
 $id  = $_GET['id'];
 require_once('dbConnect.php');
 $sql = "SELECT * FROM data WHERE description='".$id."'";
 $r = mysqli_query($con,$sql);
 $result = array();
 while ($res = mysqli_fetch_assoc($r)){
    $aRaw["user"] = $res['user'];
    $aRaw["unit"] = $res['unit'];
    $aRaw["price"] = $res['price'];
    $aRaw["discount"] = $res['discount'];
    $result[] = $aRaw;
 }
 );
 echo json_encode(array("result"=>$result));
 mysqli_close($con);
 }

Warning: code is vulnerable to SQL injection attacks


问:
How to do HTTP-request/call with JSON payload from command-line?
What's the easiest way to do a JSON call from the command-line? I have a website that does a JSON call to retrieve additional data.

The Request Payload as shown in Google Chrome looks like this:

```<code>{"version": "1.1", "method":"progr","id":2,"params":{"call":...} }
</code>```

It's about doing the call from (preferably) linux command line and retrieving the JSON content, not about parsing the incoming JSON data.

答:
Use curl, assuming the data is POST'ed, something like

```<code>curl -X POST http://example.com/some/path -d '{"version": "1.1", "method":"progr","id":2,"params":{"call":...} }'
</code>```

If you're just retrieving the data with a GET , and don't need to send anything bar URL parameters,
you'd just run curl http://example.com/some/path

Body:
What's the easiest way to do a JSON call from the command-line? I have a website that does a JSON call to retrieve additional data.

The Request Payload as shown in Google Chrome looks like this:

{"version": "1.1", "method":"progr","id":2,"params":{"call":...} }

It's about doing the call from (preferably) linux command line and retrieving the JSON content, not about parsing the incoming JSON data.

Body:
Use curl, assuming the data is POST'ed, something like

curl -X POST http://example.com/some/path -d '{"version": "1.1", "method":"progr","id":2,"params":{"call":...} }'

If you're just retrieving the data with a GET , and don't need to send anything bar URL parameters,
you'd just run curl http://example.com/some/path