问:
Animated background with canvas
How to implement animated background with html5 canvas? I want to add mouse events for this animation. I have issues with text over background because it vanishes during painting on canvas. Handling with z-coordinate doesn't work correctly.</p>

答:
Animated background with canvas

Okay, so by sounds of it, you might want to check out MDN by finding a page that interests you (like the canvasRenderingContext2d page), and start reading from there (you'll learn ALOT really fast). But, getting back to the point of this post, what I would recommend (judging from the issues you listed there) is:

Check the cursor position via the window's cursor events.

Clear the canvas every time you draw if drawing aliases are an issue due to canvas transparency.

Use requestAnimationFrame to help the browser with scheduling canvas redrawing.

An demo example of such an implementation is shown below. In the below example, coordinates of your cursor are displayed at your cursors location, with a yellow dot background relative to your cursors position to the center of the page. Enjoy!

var bgcanvas = document.getElementById('backgroundCanvas'),
    bgcontext = bgcanvas.getContext('2d'),
    mouseX = 0,
    mouseY = 0,
    mouseChanged = false;

window.addEventListener('mousemove', function(evt){
  if (mouseX !== evt.clientX)
    mouseX = evt.clientX, mouseChanged = true;
  if (mouseY !== evt.clientY)
    mouseY = evt.clientY, mouseChanged = true;
});

var repaintBGcanvasCUR = 0;
var repaintBGcanvas = function(){
  requestAnimationFrame(repaintBGcanvas);
  if ((++repaintBGcanvasCUR%2) // only modify the canvas half the time to reduce the CPU strain
      && mouseChanged){ // if the mouse has changed
    mouseChanged = false;
    bgcontext.clearRect(
      0,0,bgcanvas.width,bgcanvas.height);
    bgcontext.beginPath();
    // create the yellow circle path:
    bgcontext.arc(mouseX, mouseY,
      // pythagorean theorem:
      Math.hypot(mouseX-bgcanvas.width/2, mouseY-bgcanvas.height/2)/4,
      0, 2 * Math.PI);
    bgcontext.closePath();
    bgcontext.fillStyle = "rgba(255,255,0,.5)";
    // fill in the yellow circle
    bgcontext.fill();
    bgcontext.textAlign = 'center'; // horozontally center the text
    bgcontext.textBaseline = 'middle'; // vertically center the text
    bgcontext.font = '48px monospace'; // make the text fancy
    bgcontext.fillStyle = 'red'; // make the text fancy
    bgcontext.fillText( mouseX + ' X ' + mouseY, mouseX, mouseY);
  }
}
window.addEventListener(
  'load', repaintBGcanvas );

var resizeBackgroundCanvas = function(){
  bgcanvas.width = window.innerWidth;
  bgcanvas.height = window.innerHeight;
}
window.addEventListener(
  'resize', resizeBackgroundCanvas );
window.addEventListener(
  'load', resizeBackgroundCanvas );

// speed up canvas:
bgcontext.imageSmoothingEnabled = false;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html, body, #backgroundCanvas {
  width: 100%;
  height: 100%;
  margin: 0;
  cursor: none;
}
#backgroundCanvas {
  z-index: -2147483647; /*maximum far back*/
  position: fixed;
  top: 0; left: 0;
}
p {
  margin: 3em 2em;
}</code>```

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

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu felis eros. Donec tellus risus, dapibus luctus velit nec, molestie pulvinar tellus. Nulla cursus placerat risus in fermentum. Vestibulum rutrum rhoncus leo in sagittis. Morbi blandit, nibh et ornare faucibus, lectus massa vestibulum nulla, et pellentesque augue nunc ut tellus. Cras interdum, diam nec tincidunt rhoncus, dolor tortor lobortis ante, quis pretium lectus enim at lectus. Suspendisse consectetur, neque sed vulputate cursus, ex erat tempor magna, eu efficitur purus odio id libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pellentesque suscipit justo ut tristique. Ut finibus congue nisi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin feugiat eget nulla rhoncus semper. Proin placerat efficitur tortor, id porta est maximus ut. Phasellus tincidunt nisi sagittis consectetur laoreet. Cras eget consectetur mauris. Maecenas ornare, neque ac finibus sagittis, quam orci finibus nunc, vel cursus enim orci a arcu.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu felis eros. Donec tellus risus, dapibus luctus velit nec, molestie pulvinar tellus. Nulla cursus placerat risus in fermentum. Vestibulum rutrum rhoncus leo in sagittis. Morbi blandit, nibh et ornare faucibus, lectus massa vestibulum nulla, et pellentesque augue nunc ut tellus. Cras interdum, diam nec tincidunt rhoncus, dolor tortor lobortis ante, quis pretium lectus enim at lectus. Suspendisse consectetur, neque sed vulputate cursus, ex erat tempor magna, eu efficitur purus odio id libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pellentesque suscipit justo ut tristique. Ut finibus congue nisi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin feugiat eget nulla rhoncus semper. Proin placerat efficitur tortor, id porta est maximus ut. Phasellus tincidunt nisi sagittis consectetur laoreet. Cras eget consectetur mauris. Maecenas ornare, neque ac finibus sagittis, quam orci finibus nunc, vel cursus enim orci a arcu.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu felis eros. Donec tellus risus, dapibus luctus velit nec, molestie pulvinar tellus. Nulla cursus placerat risus in fermentum. Vestibulum rutrum rhoncus leo in sagittis. Morbi blandit, nibh et ornare faucibus, lectus massa vestibulum nulla, et pellentesque augue nunc ut tellus. Cras interdum, diam nec tincidunt rhoncus, dolor tortor lobortis ante, quis pretium lectus enim at lectus. Suspendisse consectetur, neque sed vulputate cursus, ex erat tempor magna, eu efficitur purus odio id libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pellentesque suscipit justo ut tristique. Ut finibus congue nisi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin feugiat eget nulla rhoncus semper. Proin placerat efficitur tortor, id porta est maximus ut. Phasellus tincidunt nisi sagittis consectetur laoreet. Cras eget consectetur mauris. Maecenas ornare, neque ac finibus sagittis, quam orci finibus nunc, vel cursus enim orci a arcu.
```

Title: Animated background with canvas

Body:
Animated background with canvas

Okay, so by sounds of it, you might want to check out MDN by finding a page that interests you (like the canvasRenderingContext2d page), and start reading from there (you'll learn ALOT really fast). But, getting back to the point of this post, what I would recommend (judging from the issues you listed there) is:

Check the cursor position via the window's cursor events.

Clear the canvas every time you draw if drawing aliases are an issue due to canvas transparency.

Use requestAnimationFrame to help the browser with scheduling canvas redrawing.

An demo example of such an implementation is shown below. In the below example, coordinates of your cursor are displayed at your cursors location, with a yellow dot background relative to your cursors position to the center of the page. Enjoy!

var bgcanvas = document.getElementById('backgroundCanvas'),
    bgcontext = bgcanvas.getContext('2d'),
    mouseX = 0,
    mouseY = 0,
    mouseChanged = false;

window.addEventListener('mousemove', function(evt){
  if (mouseX !== evt.clientX)
    mouseX = evt.clientX, mouseChanged = true;
  if (mouseY !== evt.clientY)
    mouseY = evt.clientY, mouseChanged = true;
});

var repaintBGcanvasCUR = 0;
var repaintBGcanvas = function(){
  requestAnimationFrame(repaintBGcanvas);
  if ((++repaintBGcanvasCUR%2) // only modify the canvas half the time to reduce the CPU strain
      && mouseChanged){ // if the mouse has changed
    mouseChanged = false;
    bgcontext.clearRect(
      0,0,bgcanvas.width,bgcanvas.height);
    bgcontext.beginPath();
    // create the yellow circle path:
    bgcontext.arc(mouseX, mouseY,
      // pythagorean theorem:
      Math.hypot(mouseX-bgcanvas.width/2, mouseY-bgcanvas.height/2)/4,
      0, 2 * Math.PI);
    bgcontext.closePath();
    bgcontext.fillStyle = "rgba(255,255,0,.5)";
    // fill in the yellow circle
    bgcontext.fill();
    bgcontext.textAlign = 'center'; // horozontally center the text
    bgcontext.textBaseline = 'middle'; // vertically center the text
    bgcontext.font = '48px monospace'; // make the text fancy
    bgcontext.fillStyle = 'red'; // make the text fancy
    bgcontext.fillText( mouseX + ' X ' + mouseY, mouseX, mouseY);
  }
}
window.addEventListener(
  'load', repaintBGcanvas );

var resizeBackgroundCanvas = function(){
  bgcanvas.width = window.innerWidth;
  bgcanvas.height = window.innerHeight;
}
window.addEventListener(
  'resize', resizeBackgroundCanvas );
window.addEventListener(
  'load', resizeBackgroundCanvas );

// speed up canvas:
bgcontext.imageSmoothingEnabled = false;

html, body, #backgroundCanvas {
  width: 100%;
  height: 100%;
  margin: 0;
  cursor: none;
}
#backgroundCanvas {
  z-index: -2147483647; /*maximum far back*/
  position: fixed;
  top: 0; left: 0;
}
p {
  margin: 3em 2em;
}

<canvas id="backgroundCanvas"></canvas>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu felis eros. Donec tellus risus, dapibus luctus velit nec, molestie pulvinar tellus. Nulla cursus placerat risus in fermentum. Vestibulum rutrum rhoncus leo in sagittis. Morbi blandit, nibh et ornare faucibus, lectus massa vestibulum nulla, et pellentesque augue nunc ut tellus. Cras interdum, diam nec tincidunt rhoncus, dolor tortor lobortis ante, quis pretium lectus enim at lectus. Suspendisse consectetur, neque sed vulputate cursus, ex erat tempor magna, eu efficitur purus odio id libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pellentesque suscipit justo ut tristique. Ut finibus congue nisi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin feugiat eget nulla rhoncus semper. Proin placerat efficitur tortor, id porta est maximus ut. Phasellus tincidunt nisi sagittis consectetur laoreet. Cras eget consectetur mauris. Maecenas ornare, neque ac finibus sagittis, quam orci finibus nunc, vel cursus enim orci a arcu.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu felis eros. Donec tellus risus, dapibus luctus velit nec, molestie pulvinar tellus. Nulla cursus placerat risus in fermentum. Vestibulum rutrum rhoncus leo in sagittis. Morbi blandit, nibh et ornare faucibus, lectus massa vestibulum nulla, et pellentesque augue nunc ut tellus. Cras interdum, diam nec tincidunt rhoncus, dolor tortor lobortis ante, quis pretium lectus enim at lectus. Suspendisse consectetur, neque sed vulputate cursus, ex erat tempor magna, eu efficitur purus odio id libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pellentesque suscipit justo ut tristique. Ut finibus congue nisi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin feugiat eget nulla rhoncus semper. Proin placerat efficitur tortor, id porta est maximus ut. Phasellus tincidunt nisi sagittis consectetur laoreet. Cras eget consectetur mauris. Maecenas ornare, neque ac finibus sagittis, quam orci finibus nunc, vel cursus enim orci a arcu.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut eu felis eros. Donec tellus risus, dapibus luctus velit nec, molestie pulvinar tellus. Nulla cursus placerat risus in fermentum. Vestibulum rutrum rhoncus leo in sagittis. Morbi blandit, nibh et ornare faucibus, lectus massa vestibulum nulla, et pellentesque augue nunc ut tellus. Cras interdum, diam nec tincidunt rhoncus, dolor tortor lobortis ante, quis pretium lectus enim at lectus. Suspendisse consectetur, neque sed vulputate cursus, ex erat tempor magna, eu efficitur purus odio id libero. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas pellentesque suscipit justo ut tristique. Ut finibus congue nisi. Interdum et malesuada fames ac ante ipsum primis in faucibus. Proin feugiat eget nulla rhoncus semper. Proin placerat efficitur tortor, id porta est maximus ut. Phasellus tincidunt nisi sagittis consectetur laoreet. Cras eget consectetur mauris. Maecenas ornare, neque ac finibus sagittis, quam orci finibus nunc, vel cursus enim orci a arcu.</p>


来源: stackexchange

问:
Default value for each type in typescript
Where can I find the default value of each type in typescript? For example, where is mentioned the default value for number type is null or 0.? Or about the string?

The default value means the value of a variable that is defined, but not assigned. Like let a : number;. This happens a lot in object definitions. For example:

```<code> class A{
     let a: number;
     let b: string;
 }
 let obj: A;
</code>```

Therefore, the question is on the values of a and b for obj.

答:
The default value of every type is undefined

From: MDN - 'undefined'

A variable that has not been assigned a value is of type undefined.

For example, invoking the following will alert the value 'undefined', even though greeting is of type String

```<code>let greeting: string;
alert(greeting);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Where can I find the default value of each type in typescript? For example, where is mentioned the default value for number type is null or 0.? Or about the string?

The default value means the value of a variable that is defined, but not assigned. Like let a : number;. This happens a lot in object definitions. For example:

 class A{
     let a: number;
     let b: string;
 }
 let obj: A;

Therefore, the question is on the values of a and b for obj.

Body:
The default value of every type is undefined

From: MDN - 'undefined'

A variable that has not been assigned a value is of type undefined.

For example, invoking the following will alert the value 'undefined', even though greeting is of type String

let greeting: string;
alert(greeting);

ContentLicense: CC BY-SA 3.0


问:
What is the particular implementation of Probabilistic Hough Transform in OpenCV?
Does anyone know the particular algorithm for Probabilistic Hough Transform in the OpenCV's implementation? I mean, is there a reference paper or documentation about the algorithm?

To get the idea, I can certainly look into the source code, but I wonder if there is any documentation about it. -- it's not in the source code's comments (OpenCV 1.0).

Thank you!

-Jin

答:
Here's an article about the Randomized Hough Transform which i believe to be the same as the "probabilistic Hough transform" used in OpenCV
http://en.wikipedia.org/wiki/Randomized_Hough_Transform

basically, you dont fill up the accumulator for all points but choose a set of points with a certain criteria to fill up the Hough transform.

The consequence is that sometimes, you could miss the actual line if there wasnt eenough points ot start with. I guess you'd want to use this if you have somewhat linear structures so that most points would be redundant.
reference no 2: L. Xu, E. Oja, and P. Kultanan, "A new curve detection method: Randomized Hough transform (RHT)", Pattern Recog. Lett. 11, 1990, 331-338.

I also read about some pretty different approaches where the algorithms would take two points and compute the point in the middle of those two points. if the point is an edge point, then we'd accumulate the bin for that line. This is apparently extremely fast but you'd assume a somewhat non-sparse matrix as you could easily miss lines if there wasnt enough edge points to start with.

ContentLicense: CC BY-SA 2.5


问:
In GNU Octave, how to solve libpng warning: iCCP: Not recognizing known sRGB profile that has been edited
I am doing math using GNU Octave, but no matter what version of GNU Octave I install, this warning appears every time I want to plot something, and then the program has no response.

libpng warning: iCCP: Not recognizing known sRGB profile that has been edited

My question has nothing to do with Android Studio.
I know it is not the problem of GNU Octave, but I do not know how to fix.

OS: Windows 8.1 x64

GNU Octave 4.2.0 installed by octave-4.2.0-w64-installer

this is the warning

答:
All these warnings can be removed by using a command tool called "pngcrush" in git bash on Windows. And then Octave will work well.

follow this answer


问:
The reset button of my JQUERY is making my TIC TAC TOE code go crazy
I have problem with my code, I've been trying to see whats wrong with it but with no sucess and I really need help. The problem here is that the code works well for two players (haven't done the one player part yet which is the AI), but when I hit the reset button it doesn't work, all the variables seem to reset and I'm guessing its some conceptual error. Here is the code, the problem is on line 108 I believe, when I do the first game it works fine, but then it starts going crazy like if something didn't reset well, I'm sorry if its a noob error I'm making but I'm quite new to this.

The code is this if you don't want to check codepen link:

```<code>$(document).ready(function(){
            //Lets work on the variables and what they do
            var set=0; //I'll use this to control the 3x3 grids
            var tempx=0; //I'll use this to control player X
            var temp0=0; //I'll use this to control player O
            var myturn='X'; //This is what I'll actually put out in the grid and is the human player
            var AI='O'; //But it will change according on who's the first player to move and is the Computer
            var contador=0;
            //I declare the winning conditions for player vs player
            var onex=0;
            var onexx=0;
            var twox=0;
            var twoxx=0;
            var threex=0;
            var threexx=0;
            var one0=0;
            var one00=0;
            var two0=0;
            var two00=0;
            var three0=0;
            var three00=0;
            //This is especifically for AI vs player
            //Going to set the original state of everything
            $('.reset').hide();
            $('.player').hide();
            $('.turns').hide();
            $('.whichplay').hide();
            //First lets work on each button function
            //Reset button!
            function reset(){
                $('.rows').prop("disabled",true);
                $('.reset').hide();
                $('.player').hide();
                $('.turns').hide();
                $('.whichplay').hide();
                $('.two-players').show();
                $('.one-player').show();
                $('.text').show();
                $('#playo').prop('disabled', false);
                $('#playx').prop('disabled', false);
                $('.rows').empty();
                set=0;
                temp0=0;
                tempx=0;
                contador=0;
                onex=0;
                onexx=0;
                twox=0;
                twoxx=0;
                threex=0;
                threexx=0;
                one0=0;
                one00=0;
                two0=0;
                two00=0;
                three0=0;
                three00=0;
                console.log('tempx after reset is '+tempx);
                console.log('temp0 after reset is '+temp0);
            }
            $('.reset').click(function(){
                reset();
            });
            function start(){
                console.log('IM STARTING LOOOOK')
                $('.one-player').hide();
                $('.reset').show();
                $('.player').show();
                $('.two-players').hide();
                $('.text').hide();
                $('.whichplay').show();
                //set=2;
                //console.log('set is '+set);
                $('.rows').removeAttr('disabled');
                //Player X function
                $('#playx').click(function(){
                    $('.whichplay').hide();
                    $('.turns').show();
                    $('#playo').prop('disabled', true);
                    $('#playx').prop('disabled', true);
                    $('.rows').prop("disabled",false);
                    tempx=1;
                    console.log('tempx after start is '+tempx);
                    console.log('tempO after start is '+temp0);
                });
                //Player O function
                $('#playo').click(function(){
                    $('.whichplay').hide();
                    $('.turns').show();
                    $('#playo').prop('disabled', true);
                    $('#playx').prop('disabled', true);
                    $('.rows').prop("disabled",false);
                    temp0=1;
                    console.log('tempx after start is '+tempx);
                    console.log('tempO after start is '+temp0);
                });
            };
            //When I hit one of these two options I will go into GAME MODE
            //LETS ENTER GAME MODE!
            $('.one-player').click(function(){
                //start();
                console.log('ERROR');
            });
            $('.two-players').click(function(){
                 start();
                 $('.rows').click(function(){
                    //I will create a variable that will store the ID's from the grid I click
                    var idstore=$(this).attr('id');
                    $(this).prop("disabled",true);
                    contador++;
                    //Now I got to control the turns X and O
                    if(tempx===1){
                        $(this).text('X');
                        console.log('This is the letter '+$(this).text('X'));
                        var s=$(this).get(0).id; //With this I extract the ID value into a string
                        tempx=0; //I close PX turn
                        temp0=1; //I start PY turn
                        var checker0=s.charAt(0); //I check the first letter of the id
                        var checker1=s.charAt(1); //I check the second letter of the id
                        $('#playo').show(); //I show its PO turn
                        $('#playx').hide();
                        if(checker0==='1'){
                           onex++; //Everytime this gets up to 3 PX win because it means a full row
                           //console.log('onex is '+onex);
                        }else if(checker0==='2'){
                            twox++; //Same here because it means a full row
                            //console.log('twox is '+twox);
                        }else if(checker0==='3'){
                            threex++; //Aaaaand same
                            //console.log('threex is '+threex);
                        }
                        if(checker1==='1'){
                            onexx++; //This means a full column
                            //console.log('onexx is '+onexx);
                        }else if(checker1==='2'){
                            twoxx++; //This means another full column
                            //console.log('twoxx is '+twoxx);
                        }else if(checker1==='3'){
                            threexx++; //Same
                            //console.log('threexx is '+threexx);
                        }
                        if(onexx===3||onex===3||twoxx===3||twox===3||threex===3||threexx===3){
                            alert('Player X win!'); //This checks full rows and columns
                            $('.rows').prop("disabled",true);

                        }else if(onexx===1&&onex===1&&twoxx===1&&twox===1&&threex===1&&threexx===1){
                            alert('Player X win!'); //This is for diagonals
                            $('.rows').prop("disabled",true);

                        }else if(contador===9){
                            alert('draw..');
                            $('.rows').prop("disabled",true);

                        }
                    }else if(temp0===1){
                        $(this).text('O');
                        var ss=$(this).get(0).id;
                        tempx=1;
                        temp0=0;
                        var checker00=ss.charAt(0);
                        var checker11=ss.charAt(1);
                        $('#playo').hide();
                        $('#playx').show();
                        //We're going to check the winner
                        if(checker00==='1'){
                           one0++;
                           //console.log('one0 is '+one0);
                        }else if(checker00==='2'){
                            two0++;
                            //console.log('two0 is '+two0);
                        }else if(checker00==='3'){
                            three0++;
                            //console.log('three0 is '+three0);
                        }
                        if(checker11==='1'){
                            one00++;
                            //console.log('one00 is '+one00);
                        }else if(checker11==='2'){
                            two00++;
                            //console.log('two00 is '+two00);
                        }else if(checker11==='3'){
                            three00++;
                            //console.log('three00 is '+three00);
                        }
                        if(one00===3||one0===3||two00===3||two0===3||three0===3||three00===3){
                            alert('Player O win!');
                            $('.rows').prop("disabled",true);

                        }else if(one00===1&&one0===1&&two00===1&&two0===1&&three0===1&&three00===1){
                            alert('Player O win!');
                            $('.rows').prop("disabled",true);

                        }else if(contador===9){
                            alert('draw..');
                            $('.rows').prop("disabled",true);

                        }
                    }

                });

            });
        });
</code>```

答:
its happening because you when you use your start function, its add a binding click function into your .rows. then after you reset, you didnt remove the binding, but you re-add another binding to your .rows click function.

this can be avoided by using .on .off click function. which when you want to attach the click function, you use .on, and when you reset or remove it, you use off

```<code>$( ".rows" ).off( "click");
$('.rows').on("click", function(){
});
</code>```

demo : https://jsfiddle.net/tvabhzxn/2/

Body:
I have problem with my code, I've been trying to see whats wrong with it but with no sucess and I really need help. The problem here is that the code works well for two players (haven't done the one player part yet which is the AI), but when I hit the reset button it doesn't work, all the variables seem to reset and I'm guessing its some conceptual error. Here is the code, the problem is on line 108 I believe, when I do the first game it works fine, but then it starts going crazy like if something didn't reset well, I'm sorry if its a noob error I'm making but I'm quite new to this.

The code is this if you don't want to check codepen link:

$(document).ready(function(){
            //Lets work on the variables and what they do
            var set=0; //I'll use this to control the 3x3 grids
            var tempx=0; //I'll use this to control player X
            var temp0=0; //I'll use this to control player O
            var myturn='X'; //This is what I'll actually put out in the grid and is the human player
            var AI='O'; //But it will change according on who's the first player to move and is the Computer
            var contador=0;
            //I declare the winning conditions for player vs player
            var onex=0;
            var onexx=0;
            var twox=0;
            var twoxx=0;
            var threex=0;
            var threexx=0;
            var one0=0;
            var one00=0;
            var two0=0;
            var two00=0;
            var three0=0;
            var three00=0;
            //This is especifically for AI vs player
            //Going to set the original state of everything
            $('.reset').hide();
            $('.player').hide();
            $('.turns').hide();
            $('.whichplay').hide();
            //First lets work on each button function
            //Reset button!
            function reset(){
                $('.rows').prop("disabled",true);
                $('.reset').hide();
                $('.player').hide();
                $('.turns').hide();
                $('.whichplay').hide();
                $('.two-players').show();
                $('.one-player').show();
                $('.text').show();
                $('#playo').prop('disabled', false);
                $('#playx').prop('disabled', false);
                $('.rows').empty();
                set=0;
                temp0=0;
                tempx=0;
                contador=0;
                onex=0;
                onexx=0;
                twox=0;
                twoxx=0;
                threex=0;
                threexx=0;
                one0=0;
                one00=0;
                two0=0;
                two00=0;
                three0=0;
                three00=0;
                console.log('tempx after reset is '+tempx);
                console.log('temp0 after reset is '+temp0);
            }
            $('.reset').click(function(){
                reset();
            });
            function start(){
                console.log('IM STARTING LOOOOK')
                $('.one-player').hide();
                $('.reset').show();
                $('.player').show();
                $('.two-players').hide();
                $('.text').hide();
                $('.whichplay').show();
                //set=2;
                //console.log('set is '+set);
                $('.rows').removeAttr('disabled');
                //Player X function
                $('#playx').click(function(){
                    $('.whichplay').hide();
                    $('.turns').show();
                    $('#playo').prop('disabled', true);
                    $('#playx').prop('disabled', true);
                    $('.rows').prop("disabled",false);
                    tempx=1;
                    console.log('tempx after start is '+tempx);
                    console.log('tempO after start is '+temp0);
                });
                //Player O function
                $('#playo').click(function(){
                    $('.whichplay').hide();
                    $('.turns').show();
                    $('#playo').prop('disabled', true);
                    $('#playx').prop('disabled', true);
                    $('.rows').prop("disabled",false);
                    temp0=1;
                    console.log('tempx after start is '+tempx);
                    console.log('tempO after start is '+temp0);
                });
            };
            //When I hit one of these two options I will go into GAME MODE
            //LETS ENTER GAME MODE!
            $('.one-player').click(function(){
                //start();
                console.log('ERROR');
            });
            $('.two-players').click(function(){
                 start();
                 $('.rows').click(function(){
                    //I will create a variable that will store the ID's from the grid I click
                    var idstore=$(this).attr('id');
                    $(this).prop("disabled",true);
                    contador++;
                    //Now I got to control the turns X and O
                    if(tempx===1){
                        $(this).text('X');
                        console.log('This is the letter '+$(this).text('X'));
                        var s=$(this).get(0).id; //With this I extract the ID value into a string
                        tempx=0; //I close PX turn
                        temp0=1; //I start PY turn
                        var checker0=s.charAt(0); //I check the first letter of the id
                        var checker1=s.charAt(1); //I check the second letter of the id
                        $('#playo').show(); //I show its PO turn
                        $('#playx').hide();
                        if(checker0==='1'){
                           onex++; //Everytime this gets up to 3 PX win because it means a full row
                           //console.log('onex is '+onex);
                        }else if(checker0==='2'){
                            twox++; //Same here because it means a full row
                            //console.log('twox is '+twox);
                        }else if(checker0==='3'){
                            threex++; //Aaaaand same
                            //console.log('threex is '+threex);
                        }
                        if(checker1==='1'){
                            onexx++; //This means a full column
                            //console.log('onexx is '+onexx);
                        }else if(checker1==='2'){
                            twoxx++; //This means another full column
                            //console.log('twoxx is '+twoxx);
                        }else if(checker1==='3'){
                            threexx++; //Same
                            //console.log('threexx is '+threexx);
                        }
                        if(onexx===3||onex===3||twoxx===3||twox===3||threex===3||threexx===3){
                            alert('Player X win!'); //This checks full rows and columns
                            $('.rows').prop("disabled",true);

                        }else if(onexx===1&&onex===1&&twoxx===1&&twox===1&&threex===1&&threexx===1){
                            alert('Player X win!'); //This is for diagonals
                            $('.rows').prop("disabled",true);

                        }else if(contador===9){
                            alert('draw..');
                            $('.rows').prop("disabled",true);

                        }
                    }else if(temp0===1){
                        $(this).text('O');
                        var ss=$(this).get(0).id;
                        tempx=1;
                        temp0=0;
                        var checker00=ss.charAt(0);
                        var checker11=ss.charAt(1);
                        $('#playo').hide();
                        $('#playx').show();
                        //We're going to check the winner
                        if(checker00==='1'){
                           one0++;
                           //console.log('one0 is '+one0);
                        }else if(checker00==='2'){
                            two0++;
                            //console.log('two0 is '+two0);
                        }else if(checker00==='3'){
                            three0++;
                            //console.log('three0 is '+three0);
                        }
                        if(checker11==='1'){
                            one00++;
                            //console.log('one00 is '+one00);
                        }else if(checker11==='2'){
                            two00++;
                            //console.log('two00 is '+two00);
                        }else if(checker11==='3'){
                            three00++;
                            //console.log('three00 is '+three00);
                        }
                        if(one00===3||one0===3||two00===3||two0===3||three0===3||three00===3){
                            alert('Player O win!');
                            $('.rows').prop("disabled",true);

                        }else if(one00===1&&one0===1&&two00===1&&two0===1&&three0===1&&three00===1){
                            alert('Player O win!');
                            $('.rows').prop("disabled",true);

                        }else if(contador===9){
                            alert('draw..');
                            $('.rows').prop("disabled",true);

                        }
                    }

                });

            });
        });

Body:
its happening because you when you use your start function, its add a binding click function into your .rows. then after you reset, you didnt remove the binding, but you re-add another binding to your .rows click function.

this can be avoided by using .on .off click function. which when you want to attach the click function, you use .on, and when you reset or remove it, you use off

$( ".rows" ).off( "click");
$('.rows').on("click", function(){
});

demo : https://jsfiddle.net/tvabhzxn/2/


问:
Table cell code causes error
The following code generates an error:

```<code><td> <asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>  </td>
</code>```

And the error is:

...does not contain a definition for 'TextBox1_TextChanged' and no extension method 'TextBox1_TextChanged' accepting a first argument of type  could be found

答: Remove attribute OnTextChanged="TextBox1_TextChanged" from textbox if you don't need. Or define one in codebehind with protected. or public access specifier.

Title: Table cell code causes error

Body:
The following code generates an error:

 <asp:TextBox ID="TextBox1" runat="server" OnTextChanged="TextBox1_TextChanged"></asp:TextBox>

And the error is:

...does not contain a definition for 'TextBox1_TextChanged' and no extension method 'TextBox1_TextChanged' accepting a first argument of type  could be found


问:
proportional line width ggplot2, in Gantt chart
I aim to plot line widths proportional to a variable in a data.frame, a topic which has, for example, been discussed here.
My application is (although the issue is probably not related to that) within a Gantt chart adapted from here as in:

```<code>library(reshape2)
library(ggplot2)

MA <- c("A", "B", "C")

dfr <- data.frame(
  name        = factor(MA, levels = MA),
  start.date  = as.Date(c("2012-09-01", "2013-01-01","2014-01-01")),
  end.date    = as.Date(c("2019-01-01", "2017-12-31","2019-06-30")),
  prozent     = c(1,0.5,0.75)*100
)
mdfr <- melt(dfr, measure.vars = c("start.date", "end.date"))

ggplot(mdfr, aes(value, name)) + geom_line(aes(size = prozent))
</code>```

This yields

where I do get different line widths, which however do not look proportional to prozent.

Is there a way to make the line widths proportional to prozent?

答:
just add + scale_size_area():

```<code>ggplot(mdfr, aes(value, name)) +
    geom_line(aes(size = prozent)) +
    scale_size_area()
</code>```

Body:
I aim to plot line widths proportional to a variable in a data.frame, a topic which has, for example, been discussed here.
My application is (although the issue is probably not related to that) within a Gantt chart adapted from here as in:

library(reshape2)
library(ggplot2)

MA <- c("A", "B", "C")

dfr <- data.frame(
  name        = factor(MA, levels = MA),
  start.date  = as.Date(c("2012-09-01", "2013-01-01","2014-01-01")),
  end.date    = as.Date(c("2019-01-01", "2017-12-31","2019-06-30")),
  prozent     = c(1,0.5,0.75)*100
)
mdfr <- melt(dfr, measure.vars = c("start.date", "end.date"))

ggplot(mdfr, aes(value, name)) + geom_line(aes(size = prozent))

This yields

where I do get different line widths, which however do not look proportional to prozent.

Is there a way to make the line widths proportional to prozent?

Body:
just add + scale_size_area():

ggplot(mdfr, aes(value, name)) +
    geom_line(aes(size = prozent)) +
    scale_size_area()


问:
Primefaces Drag&Drop drags and drops only one element from dataTable
So, I've used example from showcase of PrimeFaces https://www.primefaces.org/showcase/ui/dnd/dataTable.xhtml. That's my code:

```<code><div class="page_content">
        <div class="header">Очередь рассылок</div>
        <script type="text/javascript">
            function handleDrop(event, ui) {
                var droppedEmail = ui.draggable;

                droppedEmail.fadeOut('fast');
            }
        </script>
        <h:form>
            <p:fieldset id="availableEmailsField" legend="Доступные рассылки">
                <p:dataTable id="availableEmails" var="email" value="#{emailingQueueUI.customEmails}">
                    <p:column style="width: 20px;">
                        <h:outputText id="dragIcon" styleClass="ui-icon ui-icon-arrow-4"/>
                        <p:draggable for="dragIcon" revert="true" helper="clone"/>
                    </p:column>
                    <p:column headerText="ID">
                        <h:outputText value="#{email.id}"/>
                    </p:column>
                    <p:column headerText="Название">
                        <h:outputText value="#{email.name}"/>
                    </p:column>
                    <p:column headerText="Заголовок">
                        <h:outputText value="#{email.header}"/>
                    </p:column>
                    <p:column headerText="Количество порции">
                        <h:outputText value="#{email.chunkSize}"/>
                    </p:column>
                </p:dataTable>
            </p:fieldset>

            <p:outputPanel id="selectedEmailsField">
                <p:outputPanel id="dropArea">
                    <h:outputText value="Переместите сюда c доступных рассылок" rendered="#{empty emailingQueueUI.customEmailQueue}" style="font-size:16px;" />
                    <p:dataTable id="selectedEmails" var="email" value="#{emailingQueueUI.customEmailQueue}" rendered="#{not empty emailingQueueUI.customEmailQueue}"
                                 rowIndexVar="index">
                        <!--<p:ajax event="rowReorder" listener="#{emailingQueueUI.onQueueReorder}" update=":form" />-->
                        <p:column headerText="Номер в очереди">
                            <h:outputText value="#{index}"/>
                        </p:column>
                        <p:column headerText="Рассылка">
                            <h:outputText value="#{email.id}"/>
                        </p:column>
                        <p:column headerText="Название">
                            <h:outputText value="#{email.name}"/>
                        </p:column>
                        <p:column headerText="Заголовок">
                            <h:outputText value="#{email.header}"/>
                        </p:column>
                        <p:column headerText="Количество порции">
                            <h:outputText value="#{email.chunkSize}"/>
                        </p:column>
                    </p:dataTable>
                </p:outputPanel>
            </p:outputPanel>

            <p:droppable for="selectedEmailsField" tolerance="touch" activeStyleClass="ui-state-highlight" datasource="availableEmails" onDrop="handleDrop">
                <p:ajax listener="#{emailingQueueUI.onEmailDrop}" update="dropArea availableEmails" />
            </p:droppable>
        </h:form>

    </div>
</code>```

There is a problem with d&d, I can drag and drop only one element from "availableEmailsField". When I try to drop another element it removes previous element and adds the dropped one.

答:
I think the problem is in your bean.

Make sure that you initialize customEmailQueue inside @PostConstruct method and use the proper bean scope. In this case @ViewScoped.

Body:
So, I've used example from showcase of PrimeFaces https://www.primefaces.org/showcase/ui/dnd/dataTable.xhtml. That's my code:

Очередь рассылок

        <h:form>

                        <h:outputText id="dragIcon" styleClass="ui-icon ui-icon-arrow-4"/>

                        <h:outputText value="#{email.id}"/>

                        <h:outputText value="#{email.name}"/>

                        <h:outputText value="#{email.header}"/>

                        <h:outputText value="#{email.chunkSize}"/>

                    <h:outputText value="Переместите сюда c доступных рассылок" rendered="#{empty emailingQueueUI.customEmailQueue}" style="font-size:16px;" />

                            <h:outputText value="#{index}"/>

                            <h:outputText value="#{email.id}"/>

                            <h:outputText value="#{email.name}"/>

                            <h:outputText value="#{email.header}"/>

                            <h:outputText value="#{email.chunkSize}"/>

        </h:form>

There is a problem with d&d, I can drag and drop only one element from "availableEmailsField". When I try to drop another element it removes previous element and adds the dropped one.


问:
SQLiteAsyncConnection.QueryAsync not returning data from columns
I am using SQLite-net-PCL v.1.3.3 in a Xamarin Forms UWP project, and cannot understand this behaviour; don't know if it's a bug or something I haven't understood. I think I should be able to query columns from a table (FnImage, in the example below), and populate a collection of local objects (Test, below), with each instance in that collection of Test objects having the column values from a row in the FnImage table. I do not want to just create a local collection of rows from the FnImage table for memory management reasons; my result set should just include the data in the columns I am querying.

```<code>Task.Run(async () =>
{
var v = await mySQLiteAsyncConnection.QueryAsync<Test>("select 'Name', 'DbBytesThumbnail' from FnImage where 'Id' > ? ", 0);
...
});

public class Test {
public byte[] DbBytesThumbnail { get; set; }
public string Name { get; set; }
}
</code>```

The code does create a collection with a single instance of Test in it (there should be more, given the data in the FnImage table), and both properties in that single instance are null. I've tried mapping 'select 'Name' as Name, 'DbBytesThumbnail' as DbBytesThumbnail...', changing the name of the properties in the local Test object and the "as" clause in the query, changing bits of syntax in the query (";" at the end, with and without single quotes, etc...) and spent hours on this with no success.

The FnImage table exists, the type mappings are correct, and I am using these classes/tables elsewhere with no problems (with the myAsyncConnection.Table() syntax). The Task does not enter a Faulted state / no Exception is thrown. Is this an issue with SQLite-net-PCL, or what I am doing with it?

Thoughts and insights v welcome...

答:
I have tested your code and reproduced your issue .The problem is your
SQL statement is malformed. If you want to query columns from a table, please try to use the following SQL statement.</p>

```<code>"select Name, DbBytesThumbnail from FnImage where Id > ? "
</code>```

Body:
I am using SQLite-net-PCL v.1.3.3 in a Xamarin Forms UWP project, and cannot understand this behaviour; don't know if it's a bug or something I haven't understood. I think I should be able to query columns from a table (FnImage, in the example below), and populate a collection of local objects (Test, below), with each instance in that collection of Test objects having the column values from a row in the FnImage table. I do not want to just create a local collection of rows from the FnImage table for memory management reasons; my result set should just include the data in the columns I am querying.

Task.Run(async () =>
{
var v = await mySQLiteAsyncConnection.QueryAsync<Test>("select 'Name', 'DbBytesThumbnail' from FnImage where 'Id' > ? ", 0);
...
});

public class Test {
public byte[] DbBytesThumbnail { get; set; }
public string Name { get; set; }
}

The code does create a collection with a single instance of Test in it (there should be more, given the data in the FnImage table), and both properties in that single instance are null. I've tried mapping 'select 'Name' as Name, 'DbBytesThumbnail' as DbBytesThumbnail...', changing the name of the properties in the local Test object and the "as" clause in the query, changing bits of syntax in the query (";" at the end, with and without single quotes, etc...) and spent hours on this with no success.

The FnImage table exists, the type mappings are correct, and I am using these classes/tables elsewhere with no problems (with the myAsyncConnection.Table() syntax). The Task does not enter a Faulted state / no Exception is thrown. Is this an issue with SQLite-net-PCL, or what I am doing with it?

Thoughts and insights v welcome...

Body:
I have tested your code and reproduced your issue .The problem is your
SQL statement is malformed. If you want to query columns from a table, please try to use the following SQL statement.

"select Name, DbBytesThumbnail from FnImage where Id > ? "


问:
How to make all the attributions in the css selector into one line with vim?
Here is my css part of css file.

```<code>body{
    width:1100px;
    height:800px;
}
div.main{
    margin:20px auto 0 auto;
    background-color:#f7f7f7;
}
</code>```

I want to rewrite it as below.

```<code>body{width:1100px;height:800px;}
div.main{margin:20px auto 0 auto;background-color:#f7f7f7;}
</code>```

All attritutions and values rewritten as only one line,is there a smarty vim command to do the job?

答:
You could use the J or gJ (alternative that doesn't add spaces) commands. They can be run in visual mode to join all selected lines, or take a count.

Alternatively, the splitjoin.vim plugin provides specific support for css rules as you are asking. With the cursor over the first line of the css block, type gJ to join the whole block into a single line.

Either way, you may want/need to run a replace to remove leading spaces before joining - :s/^\s\+// before joining the lines.

EDIT: I guess a 'smarty' way to do this, and without using plugins, would be the following macro: vf}:s/^\s\+/^MgvgJ (the ^M means pressing the enter key - you may have to enter the macro manually to get this). Use it by putting the cursor at the beginning of the line at the top of the css rule you want to rewrite.

Body:
Here is my css part of css file.

body{
    width:1100px;
    height:800px;
}
div.main{
    margin:20px auto 0 auto;
    background-color:#f7f7f7;
}

I want to rewrite it as below.

body{width:1100px;height:800px;}
div.main{margin:20px auto 0 auto;background-color:#f7f7f7;}

All attritutions and values rewritten as only one line,is there a smarty vim command to do the job?


问:
wampserver load php_pgsql.dll error
wampserver load php_pgsql.dll error :

PHP Warning:  PHP Startup: Unable to load dynamic library 'd:/wamp/bin/php/php5.3.13/ext/php_pgsql.dll' -
  \xb2\xd9\xd7\xf7\xcf\xb5\xcd\xb3\xce\xde\xb7\xa8\xd4\xcb\xd0\xd0
  %1\xa1\xa3\r\n in Unknown on line 0

答:
Just copy the libpq.dll from your PHP directory to the Apache bin directory.

If it do not work out for you, you have to load libpq.dll in the httpd.conf like below

```<code>LoadFile "d:/wamp/bin/php/php5.3.13/libpq.dll"
</code>```

Title: wampserver load php_pgsql.dll error

Body:
Just copy the libpq.dll from your PHP directory to the Apache bin directory.

If it do not work out for you, you have to load libpq.dll in the httpd.conf like below

LoadFile "d:/wamp/bin/php/php5.3.13/libpq.dll"


问:
How can I convert an int number from decimal to binary?
How can I convert an int number from decimal to binary. For example:

```<code>int x=10; // radix 10
</code>```

How can I make another integer has the binary representation of x, such as:

```<code>int y=1010; // radix 2
</code>```

by using c only?

答: An integer is always stored in binary format internally -- saying that you want to convert int x = 10 base 10 to int y = 1010 base 2 doesn't make sense. Perhaps you want to convert it to a string representing the binary format of the integer, in which case you can use Integer.toBinaryString.

Body:
How can I convert an int number from decimal to binary. For example:

int x=10; // radix 10

How can I make another integer has the binary representation of x, such as:

int y=1010; // radix 2

by using c only?


问:
Views returned based on variable and existence
I have an asp.net-mvc website I am working on. The site is meant to as a basis for multiple clients all with their own unique business requirements. For any given controller method, I may or may not have a customized view for the client based on their ClientId.

Right now how I am handling this is through a ResourceSelectorObject like so:

```<code>public class ClientResourceSelector
{
    public ClientResourceSelector(int clientId)
    {
        this.ClientId = clientId;
    }

    public int ClientId { get; set; }

    public readonly List<ViewProfile> ViewProfiles = new List<ViewProfile>()
    {
        new ViewProfile { ClientId = 8, Controller = "Contact", Action = "NewContact", View = "C008/NewContact" }
    };

    public string ViewName(string controller, string action)
    {
        var Profile = ViewProfiles.FirstOrDefault(X => X.Controller.Equals(controller) && X.Action.Equals(action) && X.ClientId == ClientId);
        if (Profile == null) return string.Empty;
        return Profile.View;
    }
}
</code>```

Then in the code, I use that object in this manner:

```<code>// GET: Contact/NewContact
public ActionResult NewContact()
{
     var selector = new ClientResourceSelector(ClientId);
     string alternate_view = selector.ViewName("Contact", "NewContact");
     if (String.IsNullOrEmpty(alternate_view))
         return View(NewContactViewModel.Instance(ClientId));
     else
         return View(alternate_view, NewContactViewModel.Instance(ClientId));
}
</code>```

The problem, and this is definitely the programming equivalent of "First World Problems," but I would like to still be able to just call View(viewModel) and have it select the appropriate view to display programmatically without my having to remember to  register each view in the selector.

Obviously, I would then want to override the View() method in the abstract controller that all of my controllers are inheriting from. But I am unsure of how that code would look. Any suggestions would be helpful.

答:
Here is how I've created ones in the past.  Most of the Tenant systems I've built use some type of route/request parameter (could easily be updated to use DNS or wahtever, you have a lot of options) to determine the specific Tenant.  I use an action filter that executes before any controller (or routing) to populate the route data (useful for Tenant specific routes as well).

```<code>public class TenantActionFilterAttribute : ActionFilterAttribute
{
    internal const string _Tenant = "tenant";

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Do this how ever you want, right now I'm using querystring
        // Could be changed to use DNS name or whatever
        var tenant = filterContext.HttpContext.Request.QueryString[_Tenant] as string;

        if (tenant != null)
        {
            filterContext.RouteData.Values[Tenant] = tenant;
        }
    }
}
</code>```

Either globally register the action filter:

```<code>RegisterGlobalFilters(GlobalFilters.Filters);
</code>```

(Or using a Dependency Injection Framework)

Then a custom ViewEngine:

```<code>public class TenantViewEngine : RazorViewEngine
{

    private string GetPrefix(ControllerContext controllerContext)
    {
        var result = string.Empty;
        var tenant = controllerContext.RouteData.Values[TenantActionFilterAttribute.Tenant] as string;

        if (!string.IsNullOrEmpty(tenant))
        {
            result = "Tenants/" + tenant + "/";
        }

        return result;
    }
    protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
    {
        var prefix = GetPrefix(controllerContext);

        if (partialPath.StartsWith("~/"))
        {
            partialPath = partialPath.Insert(2, prefix);
        }
        else if (partialPath.StartsWith("~") || partialPath.StartsWith("/"))
        {
            partialPath = partialPath.Insert(1, prefix);
        }
        else if (string.IsNullOrEmpty(partialPath))
        {
            partialPath = prefix + partialPath;
        }

        return base.CreatePartialView(controllerContext, partialPath);
    }
    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        var prefix = GetPrefix(controllerContext);

        if (viewPath.StartsWith("~/"))
        {
            viewPath = viewPath.Insert(2, prefix);
        }
        else if (viewPath.StartsWith("~") || viewPath.StartsWith("/"))
        {
            viewPath = viewPath.Insert(1, prefix);
        }
        else if (!string.IsNullOrEmpty(viewPath))
        {
            viewPath = prefix + viewPath;
        }

        if (masterPath.StartsWith("~/"))
        {
            masterPath = masterPath.Insert(2, prefix);
        }
        else if (masterPath.StartsWith("~") || masterPath.StartsWith("/"))
        {
            masterPath = masterPath.Insert(1, prefix);
        }
        else if (!string.IsNullOrEmpty(masterPath))
        {
            masterPath = prefix + masterPath;
        }

        return base.CreateView(controllerContext, viewPath, masterPath);
    }
}
</code>```

I can't exactly remember how this works, but the search paths change from the default to something very close to:

```<code>"~/Tenants/<TenantName>/Areas/{3}/Views/{1}/{0}.cshtml",
"~/Areas/{3}/Views/{1}/{0}.cshtml",
"~/Tenants/<TenantName>//Views/{1}/{0}.cshtml",
"~/Views/{1}/{0}.cshtml",
"~/Tenants/<TenantName>//Views/Shared/{0}.cshtml",
"~/Views/Shared/{0}.cshtml",
</code>```

Where 1:Controller, 2:View/Action, 3:AreaName

Body:
I have an asp.net-mvc website I am working on. The site is meant to as a basis for multiple clients all with their own unique business requirements. For any given controller method, I may or may not have a customized view for the client based on their ClientId.

Right now how I am handling this is through a ResourceSelectorObject like so:

public class ClientResourceSelector
{
    public ClientResourceSelector(int clientId)
    {
        this.ClientId = clientId;
    }

    public int ClientId { get; set; }

    public readonly List<ViewProfile> ViewProfiles = new List<ViewProfile>()
    {
        new ViewProfile { ClientId = 8, Controller = "Contact", Action = "NewContact", View = "C008/NewContact" }
    };

    public string ViewName(string controller, string action)
    {
        var Profile = ViewProfiles.FirstOrDefault(X => X.Controller.Equals(controller) && X.Action.Equals(action) && X.ClientId == ClientId);
        if (Profile == null) return string.Empty;
        return Profile.View;
    }
}

Then in the code, I use that object in this manner:

// GET: Contact/NewContact
public ActionResult NewContact()
{
     var selector = new ClientResourceSelector(ClientId);
     string alternate_view = selector.ViewName("Contact", "NewContact");
     if (String.IsNullOrEmpty(alternate_view))
         return View(NewContactViewModel.Instance(ClientId));
     else
         return View(alternate_view, NewContactViewModel.Instance(ClientId));
}

The problem, and this is definitely the programming equivalent of "First World Problems," but I would like to still be able to just call View(viewModel) and have it select the appropriate view to display programmatically without my having to remember to  register each view in the selector.

Obviously, I would then want to override the View() method in the abstract controller that all of my controllers are inheriting from. But I am unsure of how that code would look. Any suggestions would be helpful.

Body:
Here is how I've created ones in the past.  Most of the Tenant systems I've built use some type of route/request parameter (could easily be updated to use DNS or wahtever, you have a lot of options) to determine the specific Tenant.  I use an action filter that executes before any controller (or routing) to populate the route data (useful for Tenant specific routes as well).

public class TenantActionFilterAttribute : ActionFilterAttribute
{
    internal const string _Tenant = "tenant";

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Do this how ever you want, right now I'm using querystring
        // Could be changed to use DNS name or whatever
        var tenant = filterContext.HttpContext.Request.QueryString[_Tenant] as string;

        if (tenant != null)
        {
            filterContext.RouteData.Values[Tenant] = tenant;
        }
    }
}

Either globally register the action filter:

RegisterGlobalFilters(GlobalFilters.Filters);

(Or using a Dependency Injection Framework)

Then a custom ViewEngine:

public class TenantViewEngine : RazorViewEngine
{

    private string GetPrefix(ControllerContext controllerContext)
    {
        var result = string.Empty;
        var tenant = controllerContext.RouteData.Values[TenantActionFilterAttribute.Tenant] as string;

        if (!string.IsNullOrEmpty(tenant))
        {
            result = "Tenants/" + tenant + "/";
        }

        return result;
    }
    protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
    {
        var prefix = GetPrefix(controllerContext);

        if (partialPath.StartsWith("~/"))
        {
            partialPath = partialPath.Insert(2, prefix);
        }
        else if (partialPath.StartsWith("~") || partialPath.StartsWith("/"))
        {
            partialPath = partialPath.Insert(1, prefix);
        }
        else if (string.IsNullOrEmpty(partialPath))
        {
            partialPath = prefix + partialPath;
        }

        return base.CreatePartialView(controllerContext, partialPath);
    }
    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        var prefix = GetPrefix(controllerContext);

        if (viewPath.StartsWith("~/"))
        {
            viewPath = viewPath.Insert(2, prefix);
        }
        else if (viewPath.StartsWith("~") || viewPath.StartsWith("/"))
        {
            viewPath = viewPath.Insert(1, prefix);
        }
        else if (!string.IsNullOrEmpty(viewPath))
        {
            viewPath = prefix + viewPath;
        }

        if (masterPath.StartsWith("~/"))
        {
            masterPath = masterPath.Insert(2, prefix);
        }
        else if (masterPath.StartsWith("~") || masterPath.StartsWith("/"))
        {
            masterPath = masterPath.Insert(1, prefix);
        }
        else if (!string.IsNullOrEmpty(masterPath))
        {
            masterPath = prefix + masterPath;
        }

        return base.CreateView(controllerContext, viewPath, masterPath);
    }
}

I can't exactly remember how this works, but the search paths change from the default to something very close to:

"~/Tenants/<TenantName>/Areas/{3}/Views/{1}/{0}.cshtml",
"~/Areas/{3}/Views/{1}/{0}.cshtml",
"~/Tenants/<TenantName>//Views/{1}/{0}.cshtml",
"~/Views/{1}/{0}.cshtml",
"~/Tenants/<TenantName>//Views/Shared/{0}.cshtml",
"~/Views/Shared/{0}.cshtml",

Where 1:Controller, 2:View/Action, 3:AreaName


问:
What is the error in following program in GW BASIC?
I was making a program which could tell if a given number is a prime number or not. No matter whether I enter a prime number or another number, it always shows "it is not a prime number". Is there any fault in it?</p>

```<code>10    input "what is the number";a
20    let b=1
30    let b=b+1
40    let k=a/b
50    let p=fix(k)
60    if p=k then goto 100
70    if b<a then goto 30
80    print "it is a prime number"
90    goto 110
100    print "it is not a prime number"
110    end
run
</code>```

答:
This code describes determining a prime number in basic:</p>

```<code>10 INPUT p
20 FOR l = 2 TO INT(SQR(p))
30 LET a = p / l
40 LET b = FIX(a)
50 IF a = b THEN GOTO 80
60 NEXT l
70 PRINT "prime"
80 END
</code>```

Body:
I was making a program which could tell if a given number is a prime number or not. No matter whether I enter a prime number or another number, it always shows "it is not a prime number". Is there any fault in it?

10    input "what is the number";a
20    let b=1
30    let b=b+1
40    let k=a/b
50    let p=fix(k)
60    if p=k then goto 100
70    if b<a then goto 30
80    print "it is a prime number"
90    goto 110
100    print "it is not a prime number"
110    end
run

Body:
This code describes determining a prime number in basic:

10 INPUT p
20 FOR l = 2 TO INT(SQR(p))
30 LET a = p / l
40 LET b = FIX(a)
50 IF a = b THEN GOTO 80
60 NEXT l
70 PRINT "prime"
80 END


问:
Button function call does not work?
I want a webpage that has something like this:

Welcome

[textbox] [textbox] [Multiply!]

Enter a value to multiply.

represented by this html code:

window.onload = function begin() {
  document.getElementById("demo").innerHTML = "Welcome";
}

function multiply(var1, var2) {
  document.getElementById('multiply').innerHTML = var1 * var2
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body onload="onload();">
  <p id='demo'> </p>

  <form>
    <input type='number' name=num1>
    <input type='number' name=num2>
    <button onclick=multiply(num1, num2)> Multiply! </button>
  </form>

  <p id='multiply'> Enter a value to multiply. </p>

</body></code>```

答:
```<code><!DOCTYPE html>
  <html>
    <head>
      <title> Test </title>
    </head>

    <body>
        <form>
          <input type='number' id='num1'>
          <input type='number' id='num2'>
          <button type='button' onclick="multiply()"> Multiply! </button>
        </form>

        <p id='multiply'> Enter a value to multiply. </p>

    <script src="01_using_javascript.js"> </script>
    </body>
</html>

function multiply() {
    var numberOne = document.getElementById('num1').value;
    var numberTwo = document.getElementById('num2').value;
    var multiply = document.getElementById('multiply');
    var multipliedResult = numberOne * numberTwo;
    multiply.innerHTML = multipliedResult;
}
</code>```

Title: Button function call does not work?

Body:
I want a webpage that has something like this:

Welcome

[textbox] [textbox] [Multiply!]

Enter a value to multiply.

represented by this html code:

window.onload = function begin() {
  document.getElementById("demo").innerHTML = "Welcome";
}

function multiply(var1, var2) {
  document.getElementById('multiply').innerHTML = var1 * var2
}

  <form>
    <input type='number' name=num1>
    <input type='number' name=num2>
    <button onclick=multiply(num1, num2)> Multiply! </button>
  </form>

 Enter a value to multiply.


问:
Remove the lines starting with a character in shell
I have dataset as:

```<code>file.txt
de
fds
fds
a
sa
1
2
3
1
}
</code>```

I would like to delete all the lines starting with characters or special characters. So my outfile is:

```<code>out.txt
1
2
3
1
</code>```

I could do it manually with 'sed', but I am looking for a suitable command for this.

my code:

```<code>sed -i '/d//g' file.txt
sed -i '/f//g' file.txt
sed -i '/a//g' file.txt
sed -i '/s//g' file.txt
sed -i '/}//g' file.txt
</code>```

答:
Use grep with -E option for regex (or egrep in short):

```<code>grep -E "^[0-9].*" file.txt
</code>```

Body:
I have dataset as:

file.txt
de
fds
fds
a
sa
1
2
3
1
}

I would like to delete all the lines starting with characters or special characters. So my outfile is:

out.txt
1
2
3
1

I could do it manually with 'sed', but I am looking for a suitable command for this.

my code:

sed -i '/d//g' file.txt
sed -i '/f//g' file.txt
sed -i '/a//g' file.txt
sed -i '/s//g' file.txt
sed -i '/}//g' file.txt

Body:
Use grep with -E option for regex (or egrep in short):

grep -E "^[0-9].*" file.txt


问:
Extension gd is missing from your system - laravel composer Update
I newly install Dompdf in Laravel Project via Composer (composer require barryvdh/laravel-dompdf). After enter the Command Terminal Reply Following Errors.

```<code>Problem 1
    - dompdf/dompdf v0.7.0 requires ext-gd * -> the requested PHP extension gd is missing from your system.
    - barryvdh/laravel-dompdf v0.7.0 requires dompdf/dompdf ^0.7 -> satisfiable by dompdf/dompdf[v0.7.0].
    - Installation request for barryvdh/laravel-dompdf ^0.7.0 -> satisfiable by barryvdh/laravel-dompdf[v0.7.0].

  To enable extensions, verify that they are enabled in those .ini files:
    - /etc/php/5.6/cli/php.ini
    - /etc/php/5.6/cli/conf.d/10-opcache.ini
    - /etc/php/5.6/cli/conf.d/10-pdo.ini
    - /etc/php/5.6/cli/conf.d/15-xml.ini
    - /etc/php/5.6/cli/conf.d/20-calendar.ini
    - /etc/php/5.6/cli/conf.d/20-ctype.ini
    - /etc/php/5.6/cli/conf.d/20-dom.ini
    - /etc/php/5.6/cli/conf.d/20-exif.ini
    - /etc/php/5.6/cli/conf.d/20-fileinfo.ini
    - /etc/php/5.6/cli/conf.d/20-ftp.ini
    - /etc/php/5.6/cli/conf.d/20-gettext.ini
    - /etc/php/5.6/cli/conf.d/20-iconv.ini
    - /etc/php/5.6/cli/conf.d/20-json.ini
    - /etc/php/5.6/cli/conf.d/20-mbstring.ini
    - /etc/php/5.6/cli/conf.d/20-phar.ini
    - /etc/php/5.6/cli/conf.d/20-posix.ini
    - /etc/php/5.6/cli/conf.d/20-readline.ini
    - /etc/php/5.6/cli/conf.d/20-shmop.ini
    - /etc/php/5.6/cli/conf.d/20-simplexml.ini
    - /etc/php/5.6/cli/conf.d/20-sockets.ini
    - /etc/php/5.6/cli/conf.d/20-sysvmsg.ini
    - /etc/php/5.6/cli/conf.d/20-sysvsem.ini
    - /etc/php/5.6/cli/conf.d/20-sysvshm.ini
    - /etc/php/5.6/cli/conf.d/20-tokenizer.ini
    - /etc/php/5.6/cli/conf.d/20-wddx.ini
    - /etc/php/5.6/cli/conf.d/20-xmlreader.ini
    - /etc/php/5.6/cli/conf.d/20-xmlwriter.ini
    - /etc/php/5.6/cli/conf.d/20-xsl.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.
</code>```

How to Solve this Error

I already Installed GD using Following comment. sudo apt-get install php5-gd and also Apache Server Restarted. My Laravel Version is 5.3 and Ubuntu Version is 14.04

答:
Open your php.ini and uncomment this line:

;extension=php_gd2.dll

Body:
I newly install Dompdf in Laravel Project via Composer (composer require barryvdh/laravel-dompdf). After enter the Command Terminal Reply Following Errors.

Problem 1
    - dompdf/dompdf v0.7.0 requires ext-gd * -> the requested PHP extension gd is missing from your system.
    - barryvdh/laravel-dompdf v0.7.0 requires dompdf/dompdf ^0.7 -> satisfiable by dompdf/dompdf[v0.7.0].
    - Installation request for barryvdh/laravel-dompdf ^0.7.0 -> satisfiable by barryvdh/laravel-dompdf[v0.7.0].

  To enable extensions, verify that they are enabled in those .ini files:
    - /etc/php/5.6/cli/php.ini
    - /etc/php/5.6/cli/conf.d/10-opcache.ini
    - /etc/php/5.6/cli/conf.d/10-pdo.ini
    - /etc/php/5.6/cli/conf.d/15-xml.ini
    - /etc/php/5.6/cli/conf.d/20-calendar.ini
    - /etc/php/5.6/cli/conf.d/20-ctype.ini
    - /etc/php/5.6/cli/conf.d/20-dom.ini
    - /etc/php/5.6/cli/conf.d/20-exif.ini
    - /etc/php/5.6/cli/conf.d/20-fileinfo.ini
    - /etc/php/5.6/cli/conf.d/20-ftp.ini
    - /etc/php/5.6/cli/conf.d/20-gettext.ini
    - /etc/php/5.6/cli/conf.d/20-iconv.ini
    - /etc/php/5.6/cli/conf.d/20-json.ini
    - /etc/php/5.6/cli/conf.d/20-mbstring.ini
    - /etc/php/5.6/cli/conf.d/20-phar.ini
    - /etc/php/5.6/cli/conf.d/20-posix.ini
    - /etc/php/5.6/cli/conf.d/20-readline.ini
    - /etc/php/5.6/cli/conf.d/20-shmop.ini
    - /etc/php/5.6/cli/conf.d/20-simplexml.ini
    - /etc/php/5.6/cli/conf.d/20-sockets.ini
    - /etc/php/5.6/cli/conf.d/20-sysvmsg.ini
    - /etc/php/5.6/cli/conf.d/20-sysvsem.ini
    - /etc/php/5.6/cli/conf.d/20-sysvshm.ini
    - /etc/php/5.6/cli/conf.d/20-tokenizer.ini
    - /etc/php/5.6/cli/conf.d/20-wddx.ini
    - /etc/php/5.6/cli/conf.d/20-xmlreader.ini
    - /etc/php/5.6/cli/conf.d/20-xmlwriter.ini
    - /etc/php/5.6/cli/conf.d/20-xsl.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

How to Solve this Error

I already Installed GD using Following comment. sudo apt-get install php5-gd and also Apache Server Restarted. My Laravel Version is 5.3 and Ubuntu Version is 14.04


问:
Why doesn't this SQL statement work?
```
SELECT * FROM table1, table2
WHERE table1.user_id = table2.id
AND table1.content = news
AND table1.content_id = 1
```

that wont work. cant u have two "AND" in a sql statement??

//Tomek

答:
let me rewrite that for you with a JOIN statement since it is not 1995 anymore, you also need quotes around news</p>

```<code>SELECT * FROM table1 t1
inner join table2 t2 on t1.user_id = t2.id
AND t1.content = 'news'
AND t1.content_id = 1
</code>```

OwnerDisplayName: Tomek

LastEditorDisplayName: Graeme Perrow

Title: Why doesn't this SQL statement work?

Body:
SELECT * FROM table1, table2
WHERE table1.user_id = table2.id
AND table1.content = news
AND table1.content_id = 1

that wont work. cant u have two "AND" in a sql statement??

//Tomek

Body:
let me rewrite that for you with a JOIN statement since it is not 1995 anymore, you also need quotes around news

SELECT * FROM table1 t1
inner join table2 t2 on t1.user_id = t2.id
AND t1.content = 'news'
AND t1.content_id = 1

OwnerDisplayName: SQLMenace


问:
Creating a file in Python. Beginner. How to format text in the created file
first post here...I'm learning about Python and I was able to learn how to create a .txt file from Python. However, in the tutorial I follow, once I run the code I am supposed to see these 4 lines in the .txt file

Hello World

This is our new text file

and this is another line.

Why? Because we can.

However what I see once I create the file is this:

Hello WorldThis is our new text fileand this is another line.Why? Because we can.

Basically instead of 4 different lines I see everything together in the same line. My question is, how can I make sure I am getting 4 lines and not everything together. Thank you, this is my code:

```<code>file = open("C:/Users/efacg/Desktop/OPENME/testfile.txt","w")

file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")

file.close()
</code>```

答:
welcome to Python!

You would need to tell python you want to end the line by adding '\n' to each of your write statements:

```<code>file = open("C:/Users/efacg/Desktop/OPENME/testfile.txt","w")

file.write("Hello World\n")
file.write("This is our new text file\n")
file.write("and this is another line.\n")
file.write("Why? Because we can.\n")

file.close()
</code>```

Body:
first post here...I'm learning about Python and I was able to learn how to create a .txt file from Python. However, in the tutorial I follow, once I run the code I am supposed to see these 4 lines in the .txt file

Hello World

This is our new text file

and this is another line.

Why? Because we can.

However what I see once I create the file is this:

Hello WorldThis is our new text fileand this is another line.Why? Because we can.

Basically instead of 4 different lines I see everything together in the same line. My question is, how can I make sure I am getting 4 lines and not everything together. Thank you, this is my code:

file = open("C:/Users/efacg/Desktop/OPENME/testfile.txt","w")

file.write("Hello World")
file.write("This is our new text file")
file.write("and this is another line.")
file.write("Why? Because we can.")

file.close()

Body:
welcome to Python!

You would need to tell python you want to end the line by adding '\n' to each of your write statements:

file = open("C:/Users/efacg/Desktop/OPENME/testfile.txt","w")

file.write("Hello World\n")
file.write("This is our new text file\n")
file.write("and this is another line.\n")
file.write("Why? Because we can.\n")

file.close()


问:
How to position HTML bordered box in the centre
I am trying to place a fully responsive text box in the centre of the page inside of an image. I haven't had any trouble placing the text box on the image but for some reason I am having trouble centring the box. I have tried reviewed and looked over multiple tutorials and stack overflow answers but nothing has been helpful. I have tried both width: 50% and margins but neither have worked. Attached below is my code. Again, I am fully aware that there are multiple answers to this question but none seem to work. Thanks a lot for the help it is highly appreciated!

Orillia, Ontario

        Welcome to Orillia!

```

Again, thank you very much!

答:
Add margin:0 auto to .square :

```<code>.square {
    position: relative;
    width: 50%;
    background-color: white;
    border: 8px solid #686868;
    height: 100px;
    text-align: center;
    margin-top: 225px;
    margin: 0 auto;/*/<-------------Added/*/
}
</code>```

Full Code:

.back {
    min-width: 100%;
}

.title {
    font-size: 90px;
    color: white;
    font-family: 'Oswald', sans-serif;
    text-align: center;
    margin-top: -483px;
}

.square {
    position: relative;
    width: 50%;
    background-color: white;
    border: 8px solid #686868;
    height: 100px;
    text-align: center;
    margin-top: 225px;
    margin: 0 auto;
}

.square:after {
    content: "";
    display: block;
    padding-bottom: 100%;
}

.content {
    position: absolute;
    width: 100%;
    height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="http://www.mrwallpaper.com/wallpapers/cute-bunny-1600x900.jpg" class="back" height=500 />

<div class="title">Orillia, Ontario</div>

<div class="square">
    <div class="content">
        Welcome to Orillia!
    </div>
</div></code>```

Body:
I am trying to place a fully responsive text box in the centre of the page inside of an image. I haven't had any trouble placing the text box on the image but for some reason I am having trouble centring the box. I have tried reviewed and looked over multiple tutorials and stack overflow answers but nothing has been helpful. I have tried both width: 50% and margins but neither have worked. Attached below is my code. Again, I am fully aware that there are multiple answers to this question but none seem to work. Thanks a lot for the help it is highly appreciated!

Orillia, Ontario

        Welcome to Orillia!

Again, thank you very much!

Body:
Add margin:0 auto to .square :

.square {
    position: relative;
    width: 50%;
    background-color: white;
    border: 8px solid #686868;
    height: 100px;
    text-align: center;
    margin-top: 225px;
    margin: 0 auto;/*/<-------------Added/*/
}

Full Code:

.back {
    min-width: 100%;
}

.title {
    font-size: 90px;
    color: white;
    font-family: 'Oswald', sans-serif;
    text-align: center;
    margin-top: -483px;
}

.square {
    position: relative;
    width: 50%;
    background-color: white;
    border: 8px solid #686868;
    height: 100px;
    text-align: center;
    margin-top: 225px;
    margin: 0 auto;
}

.square:after {
    content: "";
    display: block;
    padding-bottom: 100%;
}

.content {
    position: absolute;
    width: 100%;
    height: 100%;
}

<img src="http://www.mrwallpaper.com/wallpapers/cute-bunny-1600x900.jpg" class="back" height=500 />

<div class="title">Orillia, Ontario</div>

<div class="square">
    <div class="content">
        Welcome to Orillia!
    </div>
</div>


问:
My C# function will not work
I have made a function called "AddNumbers" but when I call it, I get an error that says "An object reference is needed". I have placed this function outside of the Main() entry point, but I am sure it has nothing to do with placement because I tried moving it and it would still not work.</p>

```<code>namespace FunctionPractice
{
     class Program
     {
        public int AddNumbers(int number1, int number2)
        {
            int result = number1 + number2;
            return result;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Enter 2 numbers: ");
            int firstNumber = Convert.ToInt16(Console.ReadLine());
            int secondNumber = Convert.ToInt16(Console.ReadLine());

            int result = AddNumbers(firstNumber, secondNumber);
            Console.WriteLine(result);
        }
    }
}
</code>```

答:
Hey your method works fine you just need to make your "AddNumbers" method static. You can't call a non-static method from a static one. Also you may want to add a read line to the end so the program doesn't just shut off once it writes to the screen. Here would be the fixed code.</p>

```<code>class Program
{
    public static int AddNumbers(int number1, int number2)
    {
        int result = number1 + number2;
        return result;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Enter 2 numbers: ");
        int firstNumber = Convert.ToInt16(Console.ReadLine());
        int secondNumber = Convert.ToInt16(Console.ReadLine());

        int result = AddNumbers(firstNumber, secondNumber);
        Console.WriteLine(result);
        Console.ReadLine();
    }
}
</code>```

Title: My C# function will not work

Body:
I have made a function called "AddNumbers" but when I call it, I get an error that says "An object reference is needed". I have placed this function outside of the Main() entry point, but I am sure it has nothing to do with placement because I tried moving it and it would still not work.

namespace FunctionPractice
{
     class Program
     {
        public int AddNumbers(int number1, int number2)
        {
            int result = number1 + number2;
            return result;
        }

        static void Main(string[] args)
        {
            Console.WriteLine("Enter 2 numbers: ");
            int firstNumber = Convert.ToInt16(Console.ReadLine());
            int secondNumber = Convert.ToInt16(Console.ReadLine());

            int result = AddNumbers(firstNumber, secondNumber);
            Console.WriteLine(result);
        }
    }
}

Body:
Hey your method works fine you just need to make your "AddNumbers" method static. You can't call a non-static method from a static one. Also you may want to add a read line to the end so the program doesn't just shut off once it writes to the screen. Here would be the fixed code.

class Program
{
    public static int AddNumbers(int number1, int number2)
    {
        int result = number1 + number2;
        return result;
    }

    static void Main(string[] args)
    {
        Console.WriteLine("Enter 2 numbers: ");
        int firstNumber = Convert.ToInt16(Console.ReadLine());
        int secondNumber = Convert.ToInt16(Console.ReadLine());

        int result = AddNumbers(firstNumber, secondNumber);
        Console.WriteLine(result);
        Console.ReadLine();
    }
}


问:
How to change variables in the .env file dynamically in Laravel?
I want to create a Laravel web app that allows an admin user to change some variables(such as database credentials) in the .env file using the web backend system. But how do I save the changes?</p>

答:
Yet another implementation, in case you have something like:

A = B #this is a valid entry

In your .env file

```<code>public function updateEnv($data = array())
{
    if (!count($data)) {
        return;
    }

    $pattern = '/([^\=]*)\=[^\n]*/';

    $envFile = base_path() . '/.env';
    $lines = file($envFile);
    $newLines = [];
    foreach ($lines as $line) {
        preg_match($pattern, $line, $matches);

        if (!count($matches)) {
            $newLines[] = $line;
            continue;
        }

        if (!key_exists(trim($matches[1]), $data)) {
            $newLines[] = $line;
            continue;
        }

        $line = trim($matches[1]) . "={$data[trim($matches[1])]}\n";
        $newLines[] = $line;
    }

    $newContent = implode('', $newLines);
    file_put_contents($envFile, $newContent);
}
</code>```

Body:
Yet another implementation, in case you have something like:

A = B #this is a valid entry

In your .env file

public function updateEnv($data = array())
{
    if (!count($data)) {
        return;
    }

    $pattern = '/([^\=]*)\=[^\n]*/';

    $envFile = base_path() . '/.env';
    $lines = file($envFile);
    $newLines = [];
    foreach ($lines as $line) {
        preg_match($pattern, $line, $matches);

        if (!count($matches)) {
            $newLines[] = $line;
            continue;
        }

        if (!key_exists(trim($matches[1]), $data)) {
            $newLines[] = $line;
            continue;
        }

        $line = trim($matches[1]) . "={$data[trim($matches[1])]}\n";
        $newLines[] = $line;
    }

    $newContent = implode('', $newLines);
    file_put_contents($envFile, $newContent);
}


问:
I don't understand the python callback function
This is my python callback function:

```<code>from time import sleep

def callback(sum):
    sleep(5)
    print("Sum = {}".format(sum))

def main(a, b, callback = None):
    print("adding {} + {}".format(a, b))
    if callback:
        callback(a+b)
    print('leaving u')

main(1, 2, callback)
</code>```

This is the output:

```<code>adding 1 + 2
Sum = 3
leaving u
</code>```

But I expected it to be:

```<code>adding 1 + 2
leaving u
Sum = 3
</code>```

I thought a callback function was suppose to be used in the case where there is a function that will take a lot of time. Therefore it made sense to me that it would run in the background and the next line in the main function would continue executing.

答:
sleep is synchronous (meaning, until its done, nothing else is being executed). For asynchronous tasks, consider using threading:

```<code>from multiprocessing.pool import ThreadPool

def callback (sum):
    print("Sum = {}".format(sum))

def main (a, b, callback = None):
    print("adding {} + {}".format(a, b))
    if callback:
        calling = ThreadPool(processes=1)
        registered_async = calling.apply_async(callback, args=(a+b,))
    print('leaving u')
    while not registered_async.ready(): pass

main(1, 2, callback=callback)
</code>```

Body:
This is my python callback function:

from time import sleep

def callback(sum):
    sleep(5)
    print("Sum = {}".format(sum))

def main(a, b, callback = None):
    print("adding {} + {}".format(a, b))
    if callback:
        callback(a+b)
    print('leaving u')

main(1, 2, callback)

This is the output:

adding 1 + 2
Sum = 3
leaving u

But I expected it to be:

adding 1 + 2
leaving u
Sum = 3

I thought a callback function was suppose to be used in the case where there is a function that will take a lot of time. Therefore it made sense to me that it would run in the background and the next line in the main function would continue executing.

Body:
sleep is synchronous (meaning, until its done, nothing else is being executed). For asynchronous tasks, consider using threading:

from multiprocessing.pool import ThreadPool

def callback (sum):
    print("Sum = {}".format(sum))

def main (a, b, callback = None):
    print("adding {} + {}".format(a, b))
    if callback:
        calling = ThreadPool(processes=1)
        registered_async = calling.apply_async(callback, args=(a+b,))
    print('leaving u')
    while not registered_async.ready(): pass

main(1, 2, callback=callback)


问:
Spring server: Timeout error
I am trying to run a cron-task using Rails schedule.rb file. The task invokes a function written in ruby. The function runs perfectly fine. However when trying to run as a cron I get this error.

```<code>Starting Spring server with `/home/ubuntu/.rvm/gems/ruby-2.4.0/gems/spring-2.0.2/bin/spring server --background` timed out after 20 seconds
</code>```

Spring(2.0.2) is installed and working perfectly.
Any idea how to solve this?

答:
If the command works outside of cron, but not in the crontab, the problem is almost certainly that the command isn't picking up some necessary environment variable setting. There are several ways to get around the problem, but the simplest and best is to wrap your command in a shell script.

For initial testing, you can simply source your login environment:

```<code>. ~/.bash_profile
</code>```

But eventually you'll want to just set the variables you need and not include anything extra. For more information, see Define your own job types.

Title: Spring server: Timeout error

Body:
I am trying to run a cron-task using Rails schedule.rb file. The task invokes a function written in ruby. The function runs perfectly fine. However when trying to run as a cron I get this error.

Starting Spring server with `/home/ubuntu/.rvm/gems/ruby-2.4.0/gems/spring-2.0.2/bin/spring server --background` timed out after 20 seconds

Spring(2.0.2) is installed and working perfectly.
Any idea how to solve this?

Body:
If the command works outside of cron, but not in the crontab, the problem is almost certainly that the command isn't picking up some necessary environment variable setting. There are several ways to get around the problem, but the simplest and best is to wrap your command in a shell script.

For initial testing, you can simply source your login environment:

. ~/.bash_profile

But eventually you'll want to just set the variables you need and not include anything extra. For more information, see Define your own job types.


问:
Execute Python file as linux command
I have a file named command1.py and it is available to the system path. That means i can type python command1.py from anywhere in the system and it will execute the file. but i want ti execute this file as a linux command.

eg, i want that file to execute when i type command1 in terminal

i have few lame solutions like creating an alias or creating a symlink but i do not want to do like that. Is there any way i can defind a unix command for that file and execute from the terminal.

Thank you in advance.

答:
Put the absolute path of python in your script, just like starting a bash script. Something like below:

```<code>       #!/usr/bin/python
</code>```

Depending on installation you path might be different. And make sure it's executable, chmod +x scriptname.py

Title: Execute Python file as linux command

Body:
Put the absolute path of python in your script, just like starting a bash script. Something like below:

       #!/usr/bin/python

Depending on installation you path might be different. And make sure it's executable, chmod +x scriptname.py


问:
Why is a negative index value taken while inserting a new element into an java array?
I was trying out a java code to insert a new element into an array, I understand most of the program except for a line of code: "int newindex = -index-1;". Why does a negative sign used in front of the index?

Here is the full program:

```<code>public class ArrayManipulation2 {

    public static void main(String[] args) {

        int[] array = {6,3,5,2,-9,-5,-1,0};
        Arrays.sort(array);
        printArray(array);

        int index= Arrays.binarySearch(array, 1);
        int newindex = -index-1;

        array = insertElement(array, 1, newindex);
        printArray(array);
    }

    public static void printArray(int[] array){

        for(int i=0; i<array.length; i++){
            if(i!=0){
                System.out.print(", ");
            }
            System.out.print(array[i]);
        }
        System.out.println();

    }

    public static int[] insertElement(int[] orginal, int element, int index){
        int length = orginal.length;
        int[] destination = new int[length+1];
        System.arraycopy(orginal, 0, destination, 0, index);
        destination[index]=element;
        System.arraycopy(orginal, index, destination, index+1, length-index);

        return destination;

    }
}
</code>```

I need to know why the new index is specified as "-index-1"?.

答:
Background:

The method Arrays.binarySearch() returns

the index of the search key, if it is contained in the array; otherwise, (-(insertion point) – 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.

So, this API suggested be used in a sorted array, otherwise it could return unexpected return value

Then ,let me clarify the code :
If can not find the element, the method will return value "(-(insertion point) – 1)" , then get its "opposite number",so the value could be insertion+1, and then minus 1， we can get its right insert position

Body:
I was trying out a java code to insert a new element into an array, I understand most of the program except for a line of code: "int newindex = -index-1;". Why does a negative sign used in front of the index?

Here is the full program:

public class ArrayManipulation2 {

    public static void main(String[] args) {

        int[] array = {6,3,5,2,-9,-5,-1,0};
        Arrays.sort(array);
        printArray(array);

        int index= Arrays.binarySearch(array, 1);
        int newindex = -index-1;

        array = insertElement(array, 1, newindex);
        printArray(array);
    }

    public static void printArray(int[] array){

        for(int i=0; i<array.length; i++){
            if(i!=0){
                System.out.print(", ");
            }
            System.out.print(array[i]);
        }
        System.out.println();

    }

    public static int[] insertElement(int[] orginal, int element, int index){
        int length = orginal.length;
        int[] destination = new int[length+1];
        System.arraycopy(orginal, 0, destination, 0, index);
        destination[index]=element;
        System.arraycopy(orginal, index, destination, index+1, length-index);

        return destination;

    }
}

I need to know why the new index is specified as "-index-1"?.


问:
Access to gl_InstanceID in WebGL 2 Instancing
I am trying to do instancing in WebGL 2. I want to use the built-in variable gl_InstanceID to index into a uniform float array.

I get the following error:

glDrawElementsInstancedANGLE: attempt to draw with all attributes having non-zero divisors

Is the only instancing allowed in WebGL 2 instancing with vertex attributes (instanced arrays)?

Also, is the spec the only definitive place to find out about these capabilities?

答:
Based on the bug report below it looks like this issue was fixed. Here's a small working example

function main() {
  const gl = document.querySelector('canvas').getContext('webgl2');
  if (!gl) {
    return alert('need webgl2');
  }
  const vs = `#version 300 es
  void main() {
    float angle = float(gl_InstanceID) / 10.0 * 2.0 * radians(180.0);
    float radius = float(gl_VertexID + 1) / 4.0 * 0.8;
    gl_Position = vec4(vec2(sin(angle), cos(angle)) * radius, 0, 1);
    gl_PointSize = mix(5.0, 20.0, float(gl_VertexID) / 3.0);
  }
  `;

  const fs = `#version 300 es
  precision highp float;
  out vec4 foo;
  void main() {
    foo = vec4(1, 0, 0, 1);
  }
  `;

  const prg = twgl.createProgram(gl, [vs, fs]);
  gl.useProgram(prg);
  gl.drawArraysInstanced(gl.POINTS, 0, 4, 10);
}

main();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas></canvas>
<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script></code>```

--- old answer ---

The spec says it's based on the OpenGL ES 3.0 spec

The remaining sections of this document are intended to be read in conjunction with the OpenGL ES 3.0 specification (3.0.4 at the time of this writing, available from the Khronos OpenGL ES API Registry). Unless otherwise specified, the behavior of each method is defined by the OpenGL ES 3.0 specification. This specification may diverge from OpenGL ES 3.0 in order to ensure interoperability or security, often defining areas that OpenGL ES 3.0 leaves implementation-defined. These differences are summarized in the Differences Between WebGL and OpenGL ES 3.0 section.

Unfortunately it looks like they forgot to specify that at least one attribute must have a non-zero divisor which is different from OpenGL ES 3.0. I filed a bug

The part that needs to be added is

INVALID_OPERATION is generated by DrawArraysInstanced or
  DrawElementsInstanced if there is not at least one enabled
  vertex attribute array that has a divisor of zero and is bound to an
  active generic attribute value in the program used for the draw command.

Body:
Based on the bug report below it looks like this issue was fixed. Here's a small working example

function main() {
  const gl = document.querySelector('canvas').getContext('webgl2');
  if (!gl) {
    return alert('need webgl2');
  }
  const vs = `#version 300 es
  void main() {
    float angle = float(gl_InstanceID) / 10.0 * 2.0 * radians(180.0);
    float radius = float(gl_VertexID + 1) / 4.0 * 0.8;
    gl_Position = vec4(vec2(sin(angle), cos(angle)) * radius, 0, 1);
    gl_PointSize = mix(5.0, 20.0, float(gl_VertexID) / 3.0);
  }
  `;

  const fs = `#version 300 es
  precision highp float;
  out vec4 foo;
  void main() {
    foo = vec4(1, 0, 0, 1);
  }
  `;

  const prg = twgl.createProgram(gl, [vs, fs]);
  gl.useProgram(prg);
  gl.drawArraysInstanced(gl.POINTS, 0, 4, 10);
}

main();

<canvas></canvas>
<script src="https://twgljs.org/dist/4.x/twgl.min.js"></script>

--- old answer ---

The spec says it's based on the OpenGL ES 3.0 spec

The remaining sections of this document are intended to be read in conjunction with the OpenGL ES 3.0 specification (3.0.4 at the time of this writing, available from the Khronos OpenGL ES API Registry). Unless otherwise specified, the behavior of each method is defined by the OpenGL ES 3.0 specification. This specification may diverge from OpenGL ES 3.0 in order to ensure interoperability or security, often defining areas that OpenGL ES 3.0 leaves implementation-defined. These differences are summarized in the Differences Between WebGL and OpenGL ES 3.0 section.

Unfortunately it looks like they forgot to specify that at least one attribute must have a non-zero divisor which is different from OpenGL ES 3.0. I filed a bug

The part that needs to be added is

INVALID_OPERATION is generated by DrawArraysInstanced or
  DrawElementsInstanced if there is not at least one enabled
  vertex attribute array that has a divisor of zero and is bound to an
  active generic attribute value in the program used for the draw command.


答:
Make your function as
public static int AddNumbers(int number1, int number2).

This is because, you are calling your function from a static function which belongs to the class itself. Your function belongs to the objects of the class. So when you call static function main(), it doesn't know of which instance's AddNumbers to call. Hence the error. Please read more about static keyword.

Title: My C# function will not work


答:
command1.py

in terminal, type "where python", you will get eg.
“/usr/bin/python” copy it

vi command1.py on the top type "#!/usr/bin/python" save it.

mv command1.py command1

you can type command1 in terminal and execute

Title: Execute Python file as linux command

Body:
I have a file named command1.py and it is available to the system path. That means i can type python command1.py from anywhere in the system and it will execute the file. but i want ti execute this file as a linux command.

eg, i want that file to execute when i type command1 in terminal

i have few lame solutions like creating an alias or creating a symlink but i do not want to do like that. Is there any way i can defind a unix command for that file and execute from the terminal.

Thank you in advance.