问:
HTML Canvas Full Screen
I'm playing with the following application using the HTML Canvas: http://driz.co.uk/particles/

At the moment it is set to 640x480 pixels, but I would like to make it full screen as it will be shown a projector. However as far as I can tell I cannot set the canvas size to be 100% as the variables only except numbers and not the %. Using CSS just stretches it rather than making it actual full screen.

Any ideas?

EDIT: Tried finding the height and width using jQuery but it breaks the canvas any ideas why?

```<code>var $j = jQuery.noConflict();

var canvas;
var ctx;
var canvasDiv;
var outerDiv;

var canvasW = $j('body').width();
var canvasH = $j('body').height();

//var canvasW     = 640;
//var canvasH     = 480;

var numMovers   = 550;
var movers      = [];
var friction    = .96;
var radCirc     = Math.PI * 2;

var mouseX, mouseY, mouseVX, mouseVY, prevMouseX = 0, prevMouseY = 0;
var isMouseDown = true;

function init()
{
    canvas = document.getElementById("mainCanvas");

    if( canvas.getContext )
    {
        setup();
        setInterval( run , 33 );
    }
}

function setup()
{
    outerDiv = document.getElementById("outer");
    canvasDiv = document.getElementById("canvasContainer");
    ctx = canvas.getContext("2d");

    var i = numMovers;
    while( i-- )
    {
        var m = new Mover();
        m.x  = canvasW * .5;
        m.y  = canvasH * .5;
        m.vX = Math.cos(i) * Math.random() * 25;
        m.vY = Math.sin(i) * Math.random() * 25;
        m.size = 2;
        movers[i] = m;
    }

    document.onmousedown = onDocMouseDown;
    document.onmouseup   = onDocMouseUp;
    document.onmousemove = onDocMouseMove;
}

function run()
{
    ctx.globalCompositeOperation = "source-over";
    ctx.fillStyle = "rgba(8,8,12,.65)";
    ctx.fillRect( 0 , 0 , canvasW , canvasH );
    ctx.globalCompositeOperation = "lighter";

    mouseVX    = mouseX - prevMouseX;
    mouseVY    = mouseY - prevMouseY;
    prevMouseX = mouseX;
    prevMouseY = mouseY;

    var toDist   = canvasW / 1.15;
    var stirDist = canvasW / 8;
    var blowDist = canvasW / 2;

    var Mrnd   = Math.random;
    var Mabs   = Math.abs;
    var Msqrt  = Math.sqrt;
    var Mcos   = Math.cos;
    var Msin   = Math.sin;
    var Matan2 = Math.atan2;
    var Mmax   = Math.max;
    var Mmin   = Math.min;

    var i = numMovers;
    while( i-- )
    {
        var m  = movers[i];
        var x  = m.x;
        var y  = m.y;
        var vX = m.vX;
        var vY = m.vY;

        var dX = x - mouseX;
        var dY = y - mouseY;
        var d = Msqrt( dX * dX + dY * dY );
        var a = Matan2( dY , dX );
        var cosA = Mcos( a );
        var sinA = Msin( a );

        if( isMouseDown )
        {
            if( d < blowDist )
            {
                var blowAcc = ( 1 - ( d / blowDist ) ) * 2;
                vX += cosA * blowAcc + .5 - Mrnd();
                vY += sinA * blowAcc + .5 - Mrnd();
            }
        }

        if( d < toDist )
        {
            var toAcc = ( 1 - ( d / toDist ) ) * canvasW * .0014;
            vX -= cosA * toAcc;
            vY -= sinA * toAcc;
        }

        if( d < stirDist )
        {
            var mAcc = ( 1 - ( d / stirDist ) ) * canvasW * .00022;
            vX += mouseVX * mAcc;
            vY += mouseVY * mAcc;
        }

        vX *= friction;
        vY *= friction;

        var avgVX = Mabs( vX );
        var avgVY = Mabs( vY );
        var avgV = ( avgVX + avgVY ) * .5;

        if( avgVX < .1 ) vX *= Mrnd() * 3;
        if( avgVY < .1 ) vY *= Mrnd() * 3;

        var sc = avgV * .45;
        sc = Mmax( Mmin( sc , 3.5 ) , .4 );

        var nextX = x + vX;
        var nextY = y + vY;

        if( nextX > canvasW )
        {
            nextX = canvasW;
            vX *= -1;
        }
        else if( nextX < 0 )
        {
            nextX = 0;
            vX *= -1;
        }

        if( nextY > canvasH )
        {
            nextY = canvasH;
            vY *= -1;
        }
        else if( nextY < 0 )
        {
            nextY = 0;
            vY *= -1;
        }

        m.vX = vX;
        m.vY = vY;
        m.x  = nextX;
        m.y  = nextY;

        ctx.fillStyle = m.color;
        ctx.beginPath();
        ctx.arc( nextX , nextY , sc , 0 , radCirc , true );
        ctx.closePath();
        ctx.fill();
    }

    //rect( ctx , mouseX - 3 , mouseY - 3 , 6 , 6 );
}

function onDocMouseMove( e )
{
    var ev = e ? e : window.event;
    mouseX = ev.clientX - outerDiv.offsetLeft - canvasDiv.offsetLeft;
    mouseY = ev.clientY - outerDiv.offsetTop  - canvasDiv.offsetTop;
}

function onDocMouseDown( e )
{
    isMouseDown = true;
    return false;
}

function onDocMouseUp( e )
{
    isMouseDown = true;
    return false;
}

// ==========================================================================================

function Mover()
{
    this.color = "rgb(" + Math.floor( Math.random()*255 ) + "," + Math.floor( Math.random()*255 ) + "," + Math.floor( Math.random()*255 ) + ")";
    this.y     = 0;
    this.x     = 0;
    this.vX    = 0;
    this.vY    = 0;
    this.size  = 0;
}

// ==========================================================================================

function rect( context , x , y , w , h )
{
    context.beginPath();
    context.rect( x , y , w , h );
    context.closePath();
    context.fill();
}

// ==========================================================================================
</code>```

答:
I hope it will be useful.</p>

```<code>// Get the canvas element
var canvas = document.getElementById('canvas');

var isInFullScreen = (document.fullscreenElement && document.fullscreenElement !== null) ||
    (document.webkitFullscreenElement && document.webkitFullscreenElement !== null) ||
    (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
    (document.msFullscreenElement && document.msFullscreenElement !== null);

// Enter fullscreen
function fullscreen(){
    if(canvas.RequestFullScreen){
        canvas.RequestFullScreen();
    }else if(canvas.webkitRequestFullScreen){
        canvas.webkitRequestFullScreen();
    }else if(canvas.mozRequestFullScreen){
        canvas.mozRequestFullScreen();
    }else if(canvas.msRequestFullscreen){
        canvas.msRequestFullscreen();
    }else{
        alert("This browser doesn't supporter fullscreen");
    }
}

// Exit fullscreen
function exitfullscreen(){
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
    }else{
        alert("Exit fullscreen doesn't work");
    }
}
</code>```

Title: HTML Canvas Full Screen

Body:
I'm playing with the following application using the HTML Canvas: http://driz.co.uk/particles/

At the moment it is set to 640x480 pixels, but I would like to make it full screen as it will be shown a projector. However as far as I can tell I cannot set the canvas size to be 100% as the variables only except numbers and not the %. Using CSS just stretches it rather than making it actual full screen.

Any ideas?

EDIT: Tried finding the height and width using jQuery but it breaks the canvas any ideas why?

var $j = jQuery.noConflict();

var canvas;
var ctx;
var canvasDiv;
var outerDiv;

var canvasW = $j('body').width();
var canvasH = $j('body').height();

//var canvasW     = 640;
//var canvasH     = 480;

var numMovers   = 550;
var movers      = [];
var friction    = .96;
var radCirc     = Math.PI * 2;

var mouseX, mouseY, mouseVX, mouseVY, prevMouseX = 0, prevMouseY = 0;
var isMouseDown = true;

function init()
{
    canvas = document.getElementById("mainCanvas");

    if( canvas.getContext )
    {
        setup();
        setInterval( run , 33 );
    }
}

function setup()
{
    outerDiv = document.getElementById("outer");
    canvasDiv = document.getElementById("canvasContainer");
    ctx = canvas.getContext("2d");

    var i = numMovers;
    while( i-- )
    {
        var m = new Mover();
        m.x  = canvasW * .5;
        m.y  = canvasH * .5;
        m.vX = Math.cos(i) * Math.random() * 25;
        m.vY = Math.sin(i) * Math.random() * 25;
        m.size = 2;
        movers[i] = m;
    }

    document.onmousedown = onDocMouseDown;
    document.onmouseup   = onDocMouseUp;
    document.onmousemove = onDocMouseMove;
}

function run()
{
    ctx.globalCompositeOperation = "source-over";
    ctx.fillStyle = "rgba(8,8,12,.65)";
    ctx.fillRect( 0 , 0 , canvasW , canvasH );
    ctx.globalCompositeOperation = "lighter";

    mouseVX    = mouseX - prevMouseX;
    mouseVY    = mouseY - prevMouseY;
    prevMouseX = mouseX;
    prevMouseY = mouseY;

    var toDist   = canvasW / 1.15;
    var stirDist = canvasW / 8;
    var blowDist = canvasW / 2;

    var Mrnd   = Math.random;
    var Mabs   = Math.abs;
    var Msqrt  = Math.sqrt;
    var Mcos   = Math.cos;
    var Msin   = Math.sin;
    var Matan2 = Math.atan2;
    var Mmax   = Math.max;
    var Mmin   = Math.min;

    var i = numMovers;
    while( i-- )
    {
        var m  = movers[i];
        var x  = m.x;
        var y  = m.y;
        var vX = m.vX;
        var vY = m.vY;

        var dX = x - mouseX;
        var dY = y - mouseY;
        var d = Msqrt( dX * dX + dY * dY );
        var a = Matan2( dY , dX );
        var cosA = Mcos( a );
        var sinA = Msin( a );

        if( isMouseDown )
        {
            if( d < blowDist )
            {
                var blowAcc = ( 1 - ( d / blowDist ) ) * 2;
                vX += cosA * blowAcc + .5 - Mrnd();
                vY += sinA * blowAcc + .5 - Mrnd();
            }
        }

        if( d < toDist )
        {
            var toAcc = ( 1 - ( d / toDist ) ) * canvasW * .0014;
            vX -= cosA * toAcc;
            vY -= sinA * toAcc;
        }

        if( d < stirDist )
        {
            var mAcc = ( 1 - ( d / stirDist ) ) * canvasW * .00022;
            vX += mouseVX * mAcc;
            vY += mouseVY * mAcc;
        }

        vX *= friction;
        vY *= friction;

        var avgVX = Mabs( vX );
        var avgVY = Mabs( vY );
        var avgV = ( avgVX + avgVY ) * .5;

        if( avgVX < .1 ) vX *= Mrnd() * 3;
        if( avgVY < .1 ) vY *= Mrnd() * 3;

        var sc = avgV * .45;
        sc = Mmax( Mmin( sc , 3.5 ) , .4 );

        var nextX = x + vX;
        var nextY = y + vY;

        if( nextX > canvasW )
        {
            nextX = canvasW;
            vX *= -1;
        }
        else if( nextX < 0 )
        {
            nextX = 0;
            vX *= -1;
        }

        if( nextY > canvasH )
        {
            nextY = canvasH;
            vY *= -1;
        }
        else if( nextY < 0 )
        {
            nextY = 0;
            vY *= -1;
        }

        m.vX = vX;
        m.vY = vY;
        m.x  = nextX;
        m.y  = nextY;

        ctx.fillStyle = m.color;
        ctx.beginPath();
        ctx.arc( nextX , nextY , sc , 0 , radCirc , true );
        ctx.closePath();
        ctx.fill();
    }

    //rect( ctx , mouseX - 3 , mouseY - 3 , 6 , 6 );
}

function onDocMouseMove( e )
{
    var ev = e ? e : window.event;
    mouseX = ev.clientX - outerDiv.offsetLeft - canvasDiv.offsetLeft;
    mouseY = ev.clientY - outerDiv.offsetTop  - canvasDiv.offsetTop;
}

function onDocMouseDown( e )
{
    isMouseDown = true;
    return false;
}

function onDocMouseUp( e )
{
    isMouseDown = true;
    return false;
}

// ==========================================================================================

function Mover()
{
    this.color = "rgb(" + Math.floor( Math.random()*255 ) + "," + Math.floor( Math.random()*255 ) + "," + Math.floor( Math.random()*255 ) + ")";
    this.y     = 0;
    this.x     = 0;
    this.vX    = 0;
    this.vY    = 0;
    this.size  = 0;
}

// ==========================================================================================

function rect( context , x , y , w , h )
{
    context.beginPath();
    context.rect( x , y , w , h );
    context.closePath();
    context.fill();
}

// ==========================================================================================

Body:
I hope it will be useful.

// Get the canvas element
var canvas = document.getElementById('canvas');

var isInFullScreen = (document.fullscreenElement && document.fullscreenElement !== null) ||
    (document.webkitFullscreenElement && document.webkitFullscreenElement !== null) ||
    (document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
    (document.msFullscreenElement && document.msFullscreenElement !== null);

// Enter fullscreen
function fullscreen(){
    if(canvas.RequestFullScreen){
        canvas.RequestFullScreen();
    }else if(canvas.webkitRequestFullScreen){
        canvas.webkitRequestFullScreen();
    }else if(canvas.mozRequestFullScreen){
        canvas.mozRequestFullScreen();
    }else if(canvas.msRequestFullscreen){
        canvas.msRequestFullscreen();
    }else{
        alert("This browser doesn't supporter fullscreen");
    }
}

// Exit fullscreen
function exitfullscreen(){
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
    }else{
        alert("Exit fullscreen doesn't work");
    }
}


来源: stackexchange

问:
How to add a file in the same repository having same folder name in github
I added a JSON file to my GitHub account and I need to access it in my android music player app and for the image, I need to put the image in the same folder but whenever I put it in the same repository it generates a different link.
The link for my JSON raw file is:

Link to my JSON file

I need an image in the same folder with the link:

I need the same link for my image just need 'album_art_3.jpg' at the end of the link instead of 'musiclibrary.JSON'

These are the files in my repository

答:
You are linking to your file with the raw git commit hash. If you added the image and json file in different commits, their raw git commit hash value in which they were added is different. The commit hash you're using to link to the json file didn't even have the image file at that commit point, so you're pointing to a non-existent file if you try to point to the image file with the same commit hash.

Instead of the commit hash, use the branch name on which both exist, in this case 'master', as in

https://raw.githubusercontent.com/zakharhabib/hello-world/master/musiclibrary.json

and

https://raw.githubusercontent.com/zakharhabib/hello-world/master/album_art_3.jpg

ContentLicense: CC BY-SA 3.0


问:
How do I change the orientation of the anchor on UMG (Unreal Engine)?
The anchor in UMG anchors the top left hook of a widget, and I think this is pretty unintuitive. Shouldn't the anchor be in the middle of a widget? Anyways, how do I make it so that the widget is anchored through the middle?</p>

答: In the details panel, open the slot menu and from there you can change the position of the anchor to the middle.</p>


问:
How to edit css for `<TH></TH>` headers in `HTMLTable`?
I want to change the border colors surrounding my header tables from the default grey given by the packageHTMLTable to black. I cannot figure this out for some reason. I've tried the following:

```<code>htmlTable(data, css.table = "margin-top: 0.5px; margin-bottom: 0.5px; border: 1.5px solid black;", css.cgroup="border-bottom: 1px solid black; border-top: 1.5px solid black; text-align: center;", file = "data.html")
</code>```

I've also changed css.cgroup to css.rgroup but nothing happens. Help would be much appreciated!

答:
There must be a better way to do this using the HTMLTable package, but this will do the trick:

```<code>mytableout <-htmlTable(data)

sink("data.html")
cat("<style>th {border-bottom: 1px solid black !important;border-top: 2px solid black !important;}</style>")
print(mytableout,type="html",useViewer=TRUE)
sink()
</code>```

Black:

Grey:

Body:
I want to change the border colors surrounding my header tables from the default grey given by the packageHTMLTable to black. I cannot figure this out for some reason. I've tried the following:

htmlTable(data, css.table = "margin-top: 0.5px; margin-bottom: 0.5px; border: 1.5px solid black;", css.cgroup="border-bottom: 1px solid black; border-top: 1.5px solid black; text-align: center;", file = "data.html")

I've also changed css.cgroup to css.rgroup but nothing happens. Help would be much appreciated!

Body:
There must be a better way to do this using the HTMLTable package, but this will do the trick:

mytableout <-htmlTable(data)

sink("data.html")
cat("<style>th {border-bottom: 1px solid black !important;border-top: 2px solid black !important;}</style>")
print(mytableout,type="html",useViewer=TRUE)
sink()

Black:

Grey:


问:
How put all extension of a datatables jquery in the dt-toolbar in spesific order?
I used the datatables jQuery plugin in my tables, and I add a button to the dt-toolbar. I want to add all extension of a datatables plugin like: Show and hide columns, filter, show number of rows in page.

I tried this code :

```<code>"sDom": "<'dt-toolbar'<'col-sm-6 col-xs-12  '<'toolbar1'f>> <'col-sm-6 col-xs-12 '<'toolbar'lC>>>"
</code>```

In the toolbar I add my button with this code:

```<code>$("div.toolbar").prepend('<button class=" btn btn-primary " data-toggle="modal" data-target="#myModal" > Ajouter fonction</button>');
$("div.toolbar").addClass('text-right');
</code>```

I have this result:

but I want the filter and show rows on the left, and the button and the show hide column on the right, how can I do this?

答:
So if I understand you right, you want the two buttons on the right  and the filter and page length control on the left.  I changed it from your button to a custom button and the col visibility button to make sure the had the same look and feel.

http://live.datatables.net/huwoyete/3/edit

I added the classes:

```<code>.movel {float:left}
.mover{float:right}
</code>```

then the code:

```<code>$(document).ready( function () {

    var table = $('#example').DataTable({

    dom: "<'movel'f><'movel'l><'mover'B>ti",
    buttons:[{"text":"Ajouter fonction", action:function(){
   // put your action here.

  // I did it this way so the buttons have the same look and feel.

    }}, "colvis" ]
  });

} );
</code>```

Body:
I used the datatables jQuery plugin in my tables, and I add a button to the dt-toolbar. I want to add all extension of a datatables plugin like: Show and hide columns, filter, show number of rows in page.

I tried this code :

"sDom": "<'dt-toolbar'<'col-sm-6 col-xs-12  '<'toolbar1'f>> <'col-sm-6 col-xs-12 '<'toolbar'lC>>>"

In the toolbar I add my button with this code:

$("div.toolbar").prepend('<button class=" btn btn-primary " data-toggle="modal" data-target="#myModal" > Ajouter fonction</button>');
$("div.toolbar").addClass('text-right');

I have this result:

but I want the filter and show rows on the left, and the button and the show hide column on the right, how can I do this?

Body:
So if I understand you right, you want the two buttons on the right  and the filter and page length control on the left.  I changed it from your button to a custom button and the col visibility button to make sure the had the same look and feel.

http://live.datatables.net/huwoyete/3/edit

I added the classes:

.movel {float:left}
.mover{float:right}

then the code:

$(document).ready( function () {

    var table = $('#example').DataTable({

    dom: "<'movel'f><'movel'l><'mover'B>ti",
    buttons:[{"text":"Ajouter fonction", action:function(){
   // put your action here.

  // I did it this way so the buttons have the same look and feel.

    }}, "colvis" ]
  });

} );


问:
What is this called in C#?
```<code>Book x = new Book(){
              Author = "Rowling",
              Title = "Harry Potter",
              Genre = Genres.Fantasy
              };
</code>```

I've tried googling for Inline declaration, but I guess thats not what it's officially called.

Thoughts?

答:
Have alook at
Object and Collection Initializers (C# Programming Guide)
</p>

OwnerDisplayName: delete

LastEditorDisplayName: delete

ContentLicense: CC BY-SA 2.5

Title: What is this called in C#?

Body:
Book x = new Book(){
              Author = "Rowling",
              Title = "Harry Potter",
              Genre = Genres.Fantasy
              };

I've tried googling for Inline declaration, but I guess thats not what it's officially called.

Thoughts?


问:
Neural Network to predict nth square
I am trying to use multi-layer neural network to predict nth square.

I have the following training data containing the first 99 squares

```<code>1    1
2    4
3    9
4    16
5    25
...
98   9604
99   9801
</code>```

This is the code:

```<code>import numpy as np
import neurolab as nl

# Load input data
text = np.loadtxt('data_sq.txt')

# Separate it into datapoints and labels
data = text[:, :1]
labels = text[:, 1:]

# Define a multilayer neural network with 2 hidden layers;
# First hidden layer consists of 10 neurons
# Second hidden layer consists of 6 neurons
# Output layer consists of 1 neuron
nn = nl.net.newff([[0, 99]], [10, 6, 1])

# Train the neural network
error_progress = nn.train(data, labels, epochs=2000, show=10, goal=0.01)

# Run the classifier on test datapoints
print('\nTest results:')
data_test = [[100], [101]]
for item in data_test:
    print(item, '-->', nn.sim([item])[0])
</code>```

Which prints 1 for both 100th and 101st squares:

```<code>Test results:
[100] --> [ 1.]
[101] --> [ 1.]
</code>```

What is the right way to do this?

答:
Following Filip Malczak's and Seanny123's suggestions and comments, I implemented a neural network in tensorflow to check what happens when we try to teach it to predict (and interpolate) the 2-nd square.

Training on continuous interval

I trained the network on the interval [-7,7] (taking 300 points inside this interval, to make it continuous), and then tested it on the interval [-30,30]. The activation functions are ReLu, and the network has 3 hidden layers, each one is of size 50. epochs=500. The result is depicted in the figure below.

So basically, inside (and also close to) the interval [-7,7], the fit is quite perfect, and then it continues more or less linearly outside. It is nice to see that at least initially, the slope of the network's output tries to "match" the slope of x^2. If we increase the test interval, the two graphs diverge quite a lot, as one can see in the figure below:

Training on even numbers

Finally, if instead I train the network on the set of all even integers in the interval [-100,100], and apply it on the set of all integers (even and odd) in this interval, I get:

When training the network to produce the image above, I increased the epochs to 2500 to get a better accuracy. The rest of the parameters stayed unchanged. So it seems that interpolating "inside" the training interval works quite well (maybe except of the area around 0, where the fit is a bit worse).

Here is the code that I used for the first figure:

```<code>import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.python.framework.ops import reset_default_graph

#preparing training data
train_x=np.linspace(-7,7,300).reshape(-1,1)
train_y=train_x**2

#setting network features
dimensions=[50,50,50,1]
epochs=500
batch_size=5

reset_default_graph()
X=tf.placeholder(tf.float32, shape=[None,1])
Y=tf.placeholder(tf.float32, shape=[None,1])

weights=[]
biases=[]
n_inputs=1

#initializing variables
for i,n_outputs in enumerate(dimensions):
    with tf.variable_scope("layer_{}".format(i)):
        w=tf.get_variable(name="W",shape=[n_inputs,n_outputs],initializer=tf.random_normal_initializer(mean=0.0,stddev=0.02,seed=42))
        b=tf.get_variable(name="b",initializer=tf.zeros_initializer(shape=[n_outputs]))
        weights.append(w)
        biases.append(b)
        n_inputs=n_outputs

def forward_pass(X,weights,biases):
    h=X
    for i in range(len(weights)):
        h=tf.add(tf.matmul(h,weights[i]),biases[i])
        h=tf.nn.relu(h)
    return h

output_layer=forward_pass(X,weights,biases)
cost=tf.reduce_mean(tf.squared_difference(output_layer,Y),1)
cost=tf.reduce_sum(cost)
optimizer=tf.train.AdamOptimizer(learning_rate=0.01).minimize(cost)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    #train the network
    for i in range(epochs):
        idx=np.arange(len(train_x))
        np.random.shuffle(idx)
        for j in range(len(train_x)//batch_size):
            cur_idx=idx[batch_size*j:batch_size*(j+1)]
            sess.run(optimizer,feed_dict={X:train_x[cur_idx],Y:train_y[cur_idx]})
        #current_cost=sess.run(cost,feed_dict={X:train_x,Y:train_y})
        #print(current_cost)
    #apply the network on the test data
    test_x=np.linspace(-30,30,300)
    network_output=sess.run(output_layer,feed_dict={X:test_x.reshape(-1,1)})

plt.plot(test_x,test_x**2,color='r',label='y=x^2')
plt.plot(test_x,network_output,color='b',label='network output')
plt.legend(loc='center')
plt.show()
</code>```

Title: Neural Network to predict nth square

Body:
I am trying to use multi-layer neural network to predict nth square.

I have the following training data containing the first 99 squares

1    1
2    4
3    9
4    16
5    25
...
98   9604
99   9801

This is the code:

import numpy as np
import neurolab as nl

# Load input data
text = np.loadtxt('data_sq.txt')

# Separate it into datapoints and labels
data = text[:, :1]
labels = text[:, 1:]

# Define a multilayer neural network with 2 hidden layers;
# First hidden layer consists of 10 neurons
# Second hidden layer consists of 6 neurons
# Output layer consists of 1 neuron
nn = nl.net.newff([[0, 99]], [10, 6, 1])

# Train the neural network
error_progress = nn.train(data, labels, epochs=2000, show=10, goal=0.01)

# Run the classifier on test datapoints
print('\nTest results:')
data_test = [[100], [101]]
for item in data_test:
    print(item, '-->', nn.sim([item])[0])

Which prints 1 for both 100th and 101st squares:

Test results:
[100] --> [ 1.]
[101] --> [ 1.]

What is the right way to do this?

Body:
Following Filip Malczak's and Seanny123's suggestions and comments, I implemented a neural network in tensorflow to check what happens when we try to teach it to predict (and interpolate) the 2-nd square.

Training on continuous interval

I trained the network on the interval [-7,7] (taking 300 points inside this interval, to make it continuous), and then tested it on the interval [-30,30]. The activation functions are ReLu, and the network has 3 hidden layers, each one is of size 50. epochs=500. The result is depicted in the figure below.

So basically, inside (and also close to) the interval [-7,7], the fit is quite perfect, and then it continues more or less linearly outside. It is nice to see that at least initially, the slope of the network's output tries to "match" the slope of x^2. If we increase the test interval, the two graphs diverge quite a lot, as one can see in the figure below:

Training on even numbers

Finally, if instead I train the network on the set of all even integers in the interval [-100,100], and apply it on the set of all integers (even and odd) in this interval, I get:

When training the network to produce the image above, I increased the epochs to 2500 to get a better accuracy. The rest of the parameters stayed unchanged. So it seems that interpolating "inside" the training interval works quite well (maybe except of the area around 0, where the fit is a bit worse).

Here is the code that I used for the first figure:

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.python.framework.ops import reset_default_graph

#preparing training data
train_x=np.linspace(-7,7,300).reshape(-1,1)
train_y=train_x**2

#setting network features
dimensions=[50,50,50,1]
epochs=500
batch_size=5

reset_default_graph()
X=tf.placeholder(tf.float32, shape=[None,1])
Y=tf.placeholder(tf.float32, shape=[None,1])

weights=[]
biases=[]
n_inputs=1

#initializing variables
for i,n_outputs in enumerate(dimensions):
    with tf.variable_scope("layer_{}".format(i)):
        w=tf.get_variable(name="W",shape=[n_inputs,n_outputs],initializer=tf.random_normal_initializer(mean=0.0,stddev=0.02,seed=42))
        b=tf.get_variable(name="b",initializer=tf.zeros_initializer(shape=[n_outputs]))
        weights.append(w)
        biases.append(b)
        n_inputs=n_outputs

def forward_pass(X,weights,biases):
    h=X
    for i in range(len(weights)):
        h=tf.add(tf.matmul(h,weights[i]),biases[i])
        h=tf.nn.relu(h)
    return h

output_layer=forward_pass(X,weights,biases)
cost=tf.reduce_mean(tf.squared_difference(output_layer,Y),1)
cost=tf.reduce_sum(cost)
optimizer=tf.train.AdamOptimizer(learning_rate=0.01).minimize(cost)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    #train the network
    for i in range(epochs):
        idx=np.arange(len(train_x))
        np.random.shuffle(idx)
        for j in range(len(train_x)//batch_size):
            cur_idx=idx[batch_size*j:batch_size*(j+1)]
            sess.run(optimizer,feed_dict={X:train_x[cur_idx],Y:train_y[cur_idx]})
        #current_cost=sess.run(cost,feed_dict={X:train_x,Y:train_y})
        #print(current_cost)
    #apply the network on the test data
    test_x=np.linspace(-30,30,300)
    network_output=sess.run(output_layer,feed_dict={X:test_x.reshape(-1,1)})

plt.plot(test_x,test_x**2,color='r',label='y=x^2')
plt.plot(test_x,network_output,color='b',label='network output')
plt.legend(loc='center')
plt.show()

ContentLicense: CC BY-SA 4.0


问:
Unexpected lifetime of lambda in pipeline
I'm using a pipeline of ranges views and I want to do a complete transformation of the output and keep the pipeline going. I understand that I can't return a copy of the new range because it wouldn't live anywhere. What I don't understand is why I can't keep the storage in the lambda's closure.

```<code>auto counter = []() {
    std::map<int, int> counts;
    return ranges::make_pipeable([=](auto &&rng) mutable -> std::map<int, int>& {
        // Do stuff that fills in the map
        return counts;
    });
};

auto steps = foo() | counter() | bar();
auto data = // stuff
ranges::for_each(data | steps, [](auto &&i) {
    std::cout << i << std::endl;
});
</code>```

When I do a release build this works, but when I do a debug build this segfaults. If I change the map in the counter lambda to be static and the capture to be by reference then this works of course (but is clearly ugly as anything).

What I don't really understand is why the lifetime of the lambda returned from counter (and it's attendant closure) isn't at least as long as the lifetime of the variable steps.

答:
That's because make_pipeable takes it argument by value. Here is the definition from the src code:

```<code>    struct make_pipeable_fn
    {
        template<typename Fun>
        detail::pipeable_binder<Fun> operator()(Fun fun) const
        {
            return {std::move(fun)};
        }
    };
</code>```

Since you are returning std::map<int, int> by reference, it is pointing to an address of an object which has been moved from. (std::move in the above call)

If this is not super clear, consider a simpler example. In the below code, Noisy is just a struct which emits out its calls.

```<code>#include <iostream>
#include <range/v3/utility/functional.hpp>

using namespace ranges;

struct Noisy
{
   Noisy() { local_ = ++cnt_; std::cout << "Noisy() ctor " << local_ << '\n'; }
   Noisy(const Noisy&) { local_= ++cnt_; std::cout << "Noisy(Noisy&) copy ctor " << local_ << '\n'; }
   Noisy(Noisy&&) { local_ = ++cnt_; std::cout << "Move constructor " << local_ << '\n'; }
   ~Noisy() { std::cout << "~Noisy() dtor with local " << local_ << '\n'; }

   // global object counter
   static int cnt_;

   // local count idx
   int local_ = 0;
};
int Noisy::cnt_ = 0;

auto counter = []()
{
   Noisy n;
   return make_pipeable([=](auto x) { return n; });
};

int main(int argc, char *argv[])
{
   auto steps = counter();
   std::cout << "Deleting" << '\n';
   return 0;
}
</code>```

The output of the above code is this:

```<code>Noisy() ctor 1
Noisy(Noisy&) copy ctor 2
Move constructor 3
Move constructor 4
~Noisy() dtor with local 3
~Noisy() dtor with local 2
~Noisy() dtor with local 1
Deleting
~Noisy() dtor with local 4
</code>```

As you can see, object 2 (which in your case is holding the std::map<int, int>) is destroyed before the line printing Deleting. steps is a pipeable_binder struct which extends from our passed lambda and is destroyed at the end.

Body:
I'm using a pipeline of ranges views and I want to do a complete transformation of the output and keep the pipeline going. I understand that I can't return a copy of the new range because it wouldn't live anywhere. What I don't understand is why I can't keep the storage in the lambda's closure.

auto counter = []() {
    std::map<int, int> counts;
    return ranges::make_pipeable([=](auto &&rng) mutable -> std::map<int, int>& {
        // Do stuff that fills in the map
        return counts;
    });
};

auto steps = foo() | counter() | bar();
auto data = // stuff
ranges::for_each(data | steps, [](auto &&i) {
    std::cout << i << std::endl;
});

When I do a release build this works, but when I do a debug build this segfaults. If I change the map in the counter lambda to be static and the capture to be by reference then this works of course (but is clearly ugly as anything).

What I don't really understand is why the lifetime of the lambda returned from counter (and it's attendant closure) isn't at least as long as the lifetime of the variable steps.

Body:
That's because make_pipeable takes it argument by value. Here is the definition from the src code:

    struct make_pipeable_fn
    {
        template<typename Fun>
        detail::pipeable_binder<Fun> operator()(Fun fun) const
        {
            return {std::move(fun)};
        }
    };

Since you are returning std::map<int, int> by reference, it is pointing to an address of an object which has been moved from. (std::move in the above call)

If this is not super clear, consider a simpler example. In the below code, Noisy is just a struct which emits out its calls.

#include <iostream>
#include <range/v3/utility/functional.hpp>

using namespace ranges;

struct Noisy
{
   Noisy() { local_ = ++cnt_; std::cout << "Noisy() ctor " << local_ << '\n'; }
   Noisy(const Noisy&) { local_= ++cnt_; std::cout << "Noisy(Noisy&) copy ctor " << local_ << '\n'; }
   Noisy(Noisy&&) { local_ = ++cnt_; std::cout << "Move constructor " << local_ << '\n'; }
   ~Noisy() { std::cout << "~Noisy() dtor with local " << local_ << '\n'; }

   // global object counter
   static int cnt_;

   // local count idx
   int local_ = 0;
};
int Noisy::cnt_ = 0;

auto counter = []()
{
   Noisy n;
   return make_pipeable([=](auto x) { return n; });
};

int main(int argc, char *argv[])
{
   auto steps = counter();
   std::cout << "Deleting" << '\n';
   return 0;
}

The output of the above code is this:

Noisy() ctor 1
Noisy(Noisy&) copy ctor 2
Move constructor 3
Move constructor 4
~Noisy() dtor with local 3
~Noisy() dtor with local 2
~Noisy() dtor with local 1
Deleting
~Noisy() dtor with local 4

As you can see, object 2 (which in your case is holding the std::map<int, int>) is destroyed before the line printing Deleting. steps is a pipeable_binder struct which extends from our passed lambda and is destroyed at the end.


问:
What's the difference between CSS UI framework and jQuery UI
I noticed that CSS Framework such as bootstrap and w3.css can create webpage ui widgets such as button.
But Javascript library jQuery-ui can also create button

What's the difference between these two approaches?

答:
Bootstrap (assuming v3):

Quoting directly from bootstrap's website:

Bootstrap is the most popular HTML, CSS, and JS framework for
  developing responsive, mobile first projects on the web.

Which means that it provides the following features:

Is a framework which allows you to create responsive web application which work across multiple devices like PC, Tablets and Mobile.

It provides a 12 column responsive grid system which works across devices.

Supports SASS Preprocessor, which make writing CSS much more efficient with concepts like variables, mixins, inheritance etc.

Also provides a wide variety of components which makes web development a breeze. These components are built using javascript and jQuery.

A lot of themes which you can use for your web app.

jQueryUI

Quoting directly from jQueryUI:

jQuery UI is a curated set of user interface interactions, effects,
  widgets, and themes built on top of the jQuery JavaScript Library.
  Whether you're building highly interactive web applications or you
  just need to add a date picker to a form control, jQuery UI is the
  perfect choice.

Which basically means that it provides:

A set of widgets/components like calendar, dropdowns etc which you can use with your web application.

Interactions like drag and drop.

Themes for creating custom look and feel for your components.

To sum it up, Bootstrap is a framework for building responsive web applications whereas jQueryUI is essentially a widget/interaction library. Note that you can use jQueryUI widgets inside your Bootstrap based application.


问:
Find 'average' with equal upper and lower distance to values of a given set
I recently encountered the following
problem:

Given a set of points with height yᵢ, find the height of the line for which the average distance to points above equals the average distance to points below the line:

More abstract definition: Given a set of real valued data points Y = {y1, ..., yn}, find ȳ which splits Y into two sets Y⁺ = {y ∊ Y : y > ȳ} and Y⁻ = {y ∊ Y : y < ȳ} so that the average distance between ȳ and elements of Y⁺ equals the average distance between ȳ and elements of Y⁻.

Naive solution: Initialize ȳ with the average of Y, compute average upper and lower distances and iteratively move up or down depending on whether the upper or lower average distance is greater.

Question: This problem is pretty basic, so there is probably a better solution (?) Even a non-iterative algebraic algorithm?

答:
As mentioned in the comment, if you know which points are above and below the line, then you can solve it like this:

a = number of points above the line

b = number of points below the line

sa = sum of all y above the line

sb = sum of all y below the line

Now we can create the following equation:

```<code>(sa - a * y) / a = (b * y - sb) / b              | * a * b
sa * b - a * b * y = a * b * y - a * sb          | + a * b * y + a * sb
sa * b + a * sb = 2 * a * b * y                  | / (2 * a * b)
==> y = (a * sb + b * sa) / (2 * a * b)
      = sa / (2 * a) + sb / (2 * b)
      = (sa / a + sb / b) / 2
</code>```

If we interprete the result then we could say it is the average between the averages of the points above and below the line.

Body:
As mentioned in the comment, if you know which points are above and below the line, then you can solve it like this:

a = number of points above the line

b = number of points below the line

sa = sum of all y above the line

sb = sum of all y below the line

Now we can create the following equation:

(sa - a * y) / a = (b * y - sb) / b              | * a * b
sa * b - a * b * y = a * b * y - a * sb          | + a * b * y + a * sb
sa * b + a * sb = 2 * a * b * y                  | / (2 * a * b)
==> y = (a * sb + b * sa) / (2 * a * b)
      = sa / (2 * a) + sb / (2 * b)
      = (sa / a + sb / b) / 2

If we interprete the result then we could say it is the average between the averages of the points above and below the line.


问:
Cannot start rails server
I tried to rails server

= Could not find rake-12.0.0 in any of the sources
    Run bundle install to install missing gems.

I tried to bundle update/ install
It goes to the error msg below .

答:
Follow this step:

gem install rack

Run bundle update rake for updating your Gemfile.lock file.

Delete the Gemfile.lock and again bundle install.

Title: Cannot start rails server


问:
Regex, That Matches No more Than n Occurrences
I'm trying to find a Regex, that matches no more than n consecutive, say three, for example, occurrences of a character; in the case of three and character is "a":

abbaa - matches;

ammaaa - doesn't match(three consecutive a's), there is one "a", but whole expression must be discarded because three "a's"

Thank you.

答:
You can specify a character, or you can generalize it to all characters.

Also, not sure if you're trying to test or match the whole string, but assume

it's the whole string.

Generalized

^(?:(\w)(?!\1{2})|\W)+$

Explained

```<code> ^                       # Beginning of string
 (?:                     # Cluster
      ( \w )                  # (1), a word character
      (?! \1{2} )             # Not 2 more of same in a sequence
   |                        # or,
      \W                      # Not a word character
 )+                      # End Cluster, 1 to many times
 $                       # End of string
</code>```

You could substitute specific characters instead of \w and \W

by replacing what you want.

Example for  character a it would be a and [^a].

^(?:(a)(?!\1{2})|[^a])+$

or more than one like  [abc] and [^abc]

^(?:([abc])(?!\1{2})|[^abc])+$

Body:
You can specify a character, or you can generalize it to all characters.

Also, not sure if you're trying to test or match the whole string, but assume

it's the whole string.

Generalized

^(?:(\w)(?!\1{2})|\W)+$

Explained

 ^                       # Beginning of string
 (?:                     # Cluster
      ( \w )                  # (1), a word character
      (?! \1{2} )             # Not 2 more of same in a sequence
   |                        # or,
      \W                      # Not a word character
 )+                      # End Cluster, 1 to many times
 $                       # End of string

You could substitute specific characters instead of \w and \W

by replacing what you want.

Example for  character a it would be a and [^a].

^(?:(a)(?!\1{2})|[^a])+$

or more than one like  [abc] and [^abc]

^(?:([abc])(?!\1{2})|[^abc])+$


问:
Symfony vichimage upload make two labels in formbuilder
Hi guys fro some reason the form builder make me two labels when i specified my own label.

Here is the config for the vich image bundle:

```<code>vich_uploader:
    db_driver: orm
    mappings:
        product_image:
            uri_prefix:         /images/products
            upload_destination: %kernel.root_dir%/../web/images/products
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true
        apartment_image:
            uri_prefix:         /images/apartment
            upload_destination: %kernel.root_dir%/../web/images/apartment
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true
        slide_image:
            uri_prefix:         /images/slider
            upload_destination: %kernel.root_dir%/../web/images/slider
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true
        point_image:
            uri_prefix:         /images/point
            upload_destination: %kernel.root_dir%/../web/images/point
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true
        object_image:
            uri_prefix:         /images/object
            upload_destination: %kernel.root_dir%/../web/images/object
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true
        gallery_image:
            uri_prefix:         /images/gallery
            upload_destination: %kernel.root_dir%/../web/images/gallery
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true
</code>```

Here is the buildForm:

```<code>public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('translations', 'a2lix_translations',array(
            'required_locales' => array('bg','en')
        ))
        ->add('canvas')
        ->add('mode','checkbox', array('label'=> 'In sell','required'=>false))
        ->add('lat','text',array('label'=>'Latitude'))
        ->add('longt','text',array('label'=>'Longitude '))
        ->add('imageLeadFile', 'vich_image', array(
            'label'=>'Lead image Home Page (720x534)',
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))
        ->add('imageLocationFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))
        ->add('imagePinFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))
        ->add('imageAligmentFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))
        ->add('imageAligmentIconFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))
        ->add('imageArchitectureIconFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))->add('imageStageIconFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))->add('imageLocationIconFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))->add('imageGalleryIconFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))->add('imageColumFirstFile', 'vich_image', array(
        'required' => false,
        'allow_delete' => true, // not mandatory, default is true
        'download_link' => true, // not mandatory, default is true
        ))->add('imageColumSecondFile', 'vich_image', array(
        'required' => false,
        'allow_delete' => true, // not mandatory, default is true
        'download_link' => true, // not mandatory, default is true
    ))->add('imageColumThirdFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
    ))->add('imageColumForthFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))
    ;
}
</code>```

So when i try to make different label like this (i want to include the dimensions of the image the admin to know what image need to be provided):

```<code>        ->add('imageLeadFile', 'vich_image', array(
            'label'=>'Lead image Home Page (720x534)',
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))
</code>```

I got second label on top...

I have seen the uploader template and there has no label:

```<code>{% block vich_file_widget %}
{% spaceless %}
    <div class="vich-file">
        {{ form_row(form.file) }}
        {% if form.delete is defined %}
        {{ form_row(form.delete) }}
        {% endif %}

        {% if download_uri is defined and download_uri %}
        <a href="{{ download_uri }}">{{ 'download'|trans({}, 'VichUploaderBundle') }}</a>
        {% endif %}
    </div>
{% endspaceless %}
{% endblock %}

{% block vich_image_widget %}
{% spaceless %}
    <div class="vich-image">
        {{ form_row(form.file) }}
        {% if form.delete is defined %}
        {{ form_row(form.delete) }}
        {% endif %}

        {% if download_uri is defined and download_uri %}
         <a href="{{ download_uri }}"><img src="{{ download_uri }}" alt="" /></a>
        {% endif %}
        {% if show_download_link and download_uri is defined and download_uri%}
        <a href="{{ download_uri }}">{{ 'download'|trans({}, 'VichUploaderBundle') }}</a>
        {% endif %}
    </div>
{% endspaceless %}
{% endblock %}
</code>```

The config to use the external twig files in the CoreBundle:

```<code>form_themes:
    # other form themes
    - 'CoreBundle:VichForm:fields.html.twig'
</code>```

What could possibly make this?

答:
It's an old question but it hasn't been answered properly, so, for future reference:

In VichUploaderBundle template file 'fields.html.twig', do this:

```<code><div class="vich-file">
    {{ form_widget(form.file) }}
    {% if form.delete is defined %}
    {{ form_row(form.delete, {'label': 'Delete'}) }}
    {% endif %}
</code>```

And the same thing below for the image widget.

```<code><div class="vich-image">
    {{ form_widget(form.file) }}
    {% if form.delete is defined %}
    {{ form_row(form.delete, {'label': 'Delete'}) }}
    {% endif %}
</code>```

(This is just basic Twig BTW)

Body:
Hi guys fro some reason the form builder make me two labels when i specified my own label.

Here is the config for the vich image bundle:

vich_uploader:
    db_driver: orm
    mappings:
        product_image:
            uri_prefix:         /images/products
            upload_destination: %kernel.root_dir%/../web/images/products
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true
        apartment_image:
            uri_prefix:         /images/apartment
            upload_destination: %kernel.root_dir%/../web/images/apartment
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true
        slide_image:
            uri_prefix:         /images/slider
            upload_destination: %kernel.root_dir%/../web/images/slider
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true
        point_image:
            uri_prefix:         /images/point
            upload_destination: %kernel.root_dir%/../web/images/point
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true
        object_image:
            uri_prefix:         /images/object
            upload_destination: %kernel.root_dir%/../web/images/object
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true
        gallery_image:
            uri_prefix:         /images/gallery
            upload_destination: %kernel.root_dir%/../web/images/gallery
            inject_on_load:     false
            delete_on_update:   true
            delete_on_remove:   true

Here is the buildForm:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('translations', 'a2lix_translations',array(
            'required_locales' => array('bg','en')
        ))
        ->add('canvas')
        ->add('mode','checkbox', array('label'=> 'In sell','required'=>false))
        ->add('lat','text',array('label'=>'Latitude'))
        ->add('longt','text',array('label'=>'Longitude '))
        ->add('imageLeadFile', 'vich_image', array(
            'label'=>'Lead image Home Page (720x534)',
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))
        ->add('imageLocationFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))
        ->add('imagePinFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))
        ->add('imageAligmentFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))
        ->add('imageAligmentIconFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))
        ->add('imageArchitectureIconFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))->add('imageStageIconFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))->add('imageLocationIconFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))->add('imageGalleryIconFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))->add('imageColumFirstFile', 'vich_image', array(
        'required' => false,
        'allow_delete' => true, // not mandatory, default is true
        'download_link' => true, // not mandatory, default is true
        ))->add('imageColumSecondFile', 'vich_image', array(
        'required' => false,
        'allow_delete' => true, // not mandatory, default is true
        'download_link' => true, // not mandatory, default is true
    ))->add('imageColumThirdFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
    ))->add('imageColumForthFile', 'vich_image', array(
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))
    ;
}

So when i try to make different label like this (i want to include the dimensions of the image the admin to know what image need to be provided):

        ->add('imageLeadFile', 'vich_image', array(
            'label'=>'Lead image Home Page (720x534)',
            'required' => false,
            'allow_delete' => true, // not mandatory, default is true
            'download_link' => true, // not mandatory, default is true
        ))

I got second label on top...

I have seen the uploader template and there has no label:

{% block vich_file_widget %}
{% spaceless %}

        {{ form_row(form.file) }}
        {% if form.delete is defined %}
        {{ form_row(form.delete) }}
        {% endif %}

        {% if download_uri is defined and download_uri %}
        {{ 'download'|trans({}, 'VichUploaderBundle') }}
        {% endif %}

{% endspaceless %}
{% endblock %}

{% block vich_image_widget %}
{% spaceless %}

        {{ form_row(form.file) }}
        {% if form.delete is defined %}
        {{ form_row(form.delete) }}
        {% endif %}

        {% if download_uri is defined and download_uri %}

        {% endif %}
        {% if show_download_link and download_uri is defined and download_uri%}
        {{ 'download'|trans({}, 'VichUploaderBundle') }}
        {% endif %}

{% endspaceless %}
{% endblock %}

The config to use the external twig files in the CoreBundle:

form_themes:
    # other form themes
    - 'CoreBundle:VichForm:fields.html.twig'

What could possibly make this?

Body:
It's an old question but it hasn't been answered properly, so, for future reference:

In VichUploaderBundle template file 'fields.html.twig', do this:

<div class="vich-file">
    {{ form_widget(form.file) }}
    {% if form.delete is defined %}
    {{ form_row(form.delete, {'label': 'Delete'}) }}
    {% endif %}

And the same thing below for the image widget.

<div class="vich-image">
    {{ form_widget(form.file) }}
    {% if form.delete is defined %}
    {{ form_row(form.delete, {'label': 'Delete'}) }}
    {% endif %}

(This is just basic Twig BTW)


问:
Unable to display category name of post
On my home page, I'm trying to loop through a set number of posts and display the category name of each post. The category that I'm trying to display the name for is a subcategory of a parent (if that makes any difference). Here's my code for it:

```<code>        <?php
            $args = array( 'numberposts' => '15' );
            $recent_posts = wp_get_recent_posts( $args );
            foreach ( $recent_posts as $recent ) {
                $category = get_the_category($recent['ID']);
                echo $category['cat-name'];
        }; ?>
</code>```

When I run that, nothing ends up displaying. That page displays as if the code wasn't there. But when I do a var_dump on $category:

```<code>        <?php
            $args = array( 'numberposts' => '15' );
            $recent_posts = wp_get_recent_posts( $args );
            foreach ( $recent_posts as $recent ) {
                $category = get_the_category($recent['ID']);
                echo var_dump($category);
        }; ?>
</code>```

I can see that everything is there that I need. Each post, with it's keys and values, but for some reason trying to display a specific property of a post (like 'cat-name', or even 'name') doesn't work. Any ideas?

答:
try this

```<code><?php get_cat_name( $cat_id ) ?>
</code>```

Example

```<code><?php echo get_cat_name(4);?>
</code>```

if you want to know more about category name display or other about category in wordpress you can visit https://codex.wordpress.org/Function_Reference/get_cat_name

Title: Unable to display category name of post

Body:
On my home page, I'm trying to loop through a set number of posts and display the category name of each post. The category that I'm trying to display the name for is a subcategory of a parent (if that makes any difference). Here's my code for it:

        <?php
            $args = array( 'numberposts' => '15' );
            $recent_posts = wp_get_recent_posts( $args );
            foreach ( $recent_posts as $recent ) {
                $category = get_the_category($recent['ID']);
                echo $category['cat-name'];
        }; ?>

When I run that, nothing ends up displaying. That page displays as if the code wasn't there. But when I do a var_dump on $category:

        <?php
            $args = array( 'numberposts' => '15' );
            $recent_posts = wp_get_recent_posts( $args );
            foreach ( $recent_posts as $recent ) {
                $category = get_the_category($recent['ID']);
                echo var_dump($category);
        }; ?>

I can see that everything is there that I need. Each post, with it's keys and values, but for some reason trying to display a specific property of a post (like 'cat-name', or even 'name') doesn't work. Any ideas?

Body:
try this

<?php get_cat_name( $cat_id ) ?>

Example

<?php echo get_cat_name(4);?>

if you want to know more about category name display or other about category in wordpress you can visit https://codex.wordpress.org/Function_Reference/get_cat_name


问:
Equivalent of shell 'cd' command to change the working directory?
cd is the shell command to change the working directory.

How do I change the current working directory in Python?

答:
If you're using a relatively new version of Python, you can also use a context manager, such as this one:

```<code>from __future__ import with_statement
from grizzled.os import working_directory

with working_directory(path_to_directory):
    # code in here occurs within the directory

# code here is in the original directory
</code>```

UPDATE

If you prefer to roll your own:

```<code>import os
from contextlib import contextmanager

@contextmanager
def working_directory(directory):
    owd = os.getcwd()
    try:
        os.chdir(directory)
        yield directory
    finally:
        os.chdir(owd)
</code>```

OwnerDisplayName: Peter

Body:
If you're using a relatively new version of Python, you can also use a context manager, such as this one:

from __future__ import with_statement
from grizzled.os import working_directory

with working_directory(path_to_directory):
    # code in here occurs within the directory

# code here is in the original directory

UPDATE

If you prefer to roll your own:

import os
from contextlib import contextmanager

@contextmanager
def working_directory(directory):
    owd = os.getcwd()
    try:
        os.chdir(directory)
        yield directory
    finally:
        os.chdir(owd)

OwnerDisplayName: Brian Clapper


问:
Changing reference types(strings) inside methods
I am passing a string variable to a method. I know strings are reference types but the value that I assign inside the method is lost. </p>

```<code>public static void TestMethod(string myString)
{
    myString = "world";
}

static void Main(string[] args)
{
    string s = "hello";
    Console.WriteLine(s); // output is "hello"
    TestMethod(s);
    Console.WriteLine(s); // output is also "hello" not "world" !?
}
</code>```

<p>Anyway this does not happen with an array for example. Can someone explain why might be the cause? </p>

答:
Strings are immutable, which means that you can't change it's value, like you do with the items in an array. You can only replace a string object with a different string object.

The same happens if you try to replace an array object. This will put a new array in the parameter variable, but it will not change the variable that you used to call the method, and thus does not replace the array that you passed in:

```<code>public static void TestMethod(string[] myArray) {
  myArray = new string[] { "world" };
}
</code>```

Parameters are always passed by value unless you use the ref or out keywords. For a reference type that means that you pass a copy of the reference.

Using the ref keyword you pass the variable, so that you can change it in the method:

```<code>public static void TestMethod(ref string myString) {
  myString = "world";
}
</code>```

Body:
I am passing a string variable to a method. I know strings are reference types but the value that I assign inside the method is lost.

public static void TestMethod(string myString)
{
    myString = "world";
}

static void Main(string[] args)
{
    string s = "hello";
    Console.WriteLine(s); // output is "hello"
    TestMethod(s);
    Console.WriteLine(s); // output is also "hello" not "world" !?
}

Anyway this does not happen with an array for example. Can someone explain why might be the cause?

Body:
Strings are immutable, which means that you can't change it's value, like you do with the items in an array. You can only replace a string object with a different string object.

The same happens if you try to replace an array object. This will put a new array in the parameter variable, but it will not change the variable that you used to call the method, and thus does not replace the array that you passed in:

public static void TestMethod(string[] myArray) {
  myArray = new string[] { "world" };
}

Parameters are always passed by value unless you use the ref or out keywords. For a reference type that means that you pass a copy of the reference.

Using the ref keyword you pass the variable, so that you can change it in the method:

public static void TestMethod(ref string myString) {
  myString = "world";
}


问:
How to stop more than one being removed from an integer?
I know the title may seem fairly confusing, was just unsure on how to ask this...
So, I'm working on a basic sample game (not going to be a complete game or anything), where you can move around and are chased by an enemy character that attacks you. The problem is that when the attack function is called, instead of only removing one heart/hitpoint, they continue to be 'spam removed'. Here's what I'm working with...

```<code>void Enemy::attackPlayer()
{
    if (distance < 50)
    {
        Player::health--;
        return;
    }
}
</code>```

Pretty simple, right? Well the problem is that I need some way of I guess 'sleeping' the single function so that instead of continuing to remove health, it stops after one, then after let's say, 3 seconds, allows another attack to occur.

答:
I guess, player won't get another attacked from any enemy for 3 seconds. However, enemy can attack to another player if exist. Thus, this timer variable is keep into Player class. If I am correct, I think this code will work.</p>

```<code>class Player
{
private:
    uint32_t last_attack_timer;
    ...
public:
    void set_last_attack_timer(uint32_t timer){this->last_attack_timer = timer;};
    uint32_t get_last_attack_timer(void){return last_attack_timer;};
    ...
}

void Enemy::attackPlayer()
{
    uint32_t timer = time(0);

    if (distance < 50 && timer-Player::get_last_attack_timer>3000)
    {
        Player::health--;
        Player::set_last_attack_timer(timer(0));
        return;
    }
}
</code>```

Body:
I know the title may seem fairly confusing, was just unsure on how to ask this...
So, I'm working on a basic sample game (not going to be a complete game or anything), where you can move around and are chased by an enemy character that attacks you. The problem is that when the attack function is called, instead of only removing one heart/hitpoint, they continue to be 'spam removed'. Here's what I'm working with...

void Enemy::attackPlayer()
{
    if (distance < 50)
    {
        Player::health--;
        return;
    }
}

Pretty simple, right? Well the problem is that I need some way of I guess 'sleeping' the single function so that instead of continuing to remove health, it stops after one, then after let's say, 3 seconds, allows another attack to occur.

Body:
I guess, player won't get another attacked from any enemy for 3 seconds. However, enemy can attack to another player if exist. Thus, this timer variable is keep into Player class. If I am correct, I think this code will work.

class Player
{
private:
    uint32_t last_attack_timer;
    ...
public:
    void set_last_attack_timer(uint32_t timer){this->last_attack_timer = timer;};
    uint32_t get_last_attack_timer(void){return last_attack_timer;};
    ...
}

void Enemy::attackPlayer()
{
    uint32_t timer = time(0);

    if (distance < 50 && timer-Player::get_last_attack_timer>3000)
    {
        Player::health--;
        Player::set_last_attack_timer(timer(0));
        return;
    }
}


问:
Page shows duplicate posts everytime i click on button
I am having a strange issue with Jquery Mobile. I had created a Page which displays posts and is displaying posts correctly.

Now the issue is, whenever i click on back button and click on the posts button again, it duplicates the posts and display. The number of times i click on back button and click on post button, Posts gets duplicated accordingly and shows in multiples.

For example, i have a post that is being displayed. Now i click on back button and then click on show posts button, this time, the same post displays twice. Now again if i click back button and then click on show posts button, it now the same post shows thrice and so on.

But if i refresh the page after every back button click, then it shows the posts correctly. Can anyone guide me where i am going wrong?

Here is the Code:

HTML PAGE:

```<code><div data-role="page" id="userpost">
    <div data-role="header" data-theme="b">
        <a class="back" class="button button-clear" data-rel="back" data-icon="back" href="#">back</a>
        <p style="text-align: center">Posts History</p>
    </div>
    <div data-role="content">
        <p id="username"></p>
        <div class="row cf" id="userPosts">
        </div>

        <div data-role="footer" data-position="fixed" data-theme="b">
            <h6>©</h6>
        </div>
    </div>
</div>
</code>```

JQuery Code:

```<code>function displayuserPosts() {
    if (localStorage.login = "true") {
        var username = localStorage.username;
        $('#username').append("<p style='font-size:10px; color:red; text-align:center;'>Welcome: " + username + "</p>");
        var userPosts = "username=" + username + "&upost";
        $.ajax({
            type: "GET",
            url: "../php-code2/uposts.php",
            data: userPosts,
            dataType: "json",
            success: function (data) {
                $.each(data, function (i, field) {
                    $("#userPosts").append('<p class="job cf">'+ field.title +'</p>');
                });
            }
        });
    } else {
        alert("Please login to post a Job");
        window.location.href = "#Main";
    }
}
</code>```

答:
On this line:

```<code>$("#userPosts").append('<p class="job cf">'+ field.title +'</p>');
</code>```

Change .append to .html.

"append" means add content to what is already in the element ( #userPosts in this case).

;)

EDIT

Okay. Let's try something else then.

You already use localstorage...

Why not set a boolean flag when posts are loaded?

And one date flag to know when it was loaded...

What I call a flag is a variable used only to remember a state... To be used in comparisons.

So this should work.

Notice you can use a more precise time to remember.

```<code>// It good to know todays date.
var today = new Date().getDate(); // day of the month

function displayuserPosts() {

  // Executes only if logged in AND the posts not already loaded today.
  if(    localStorage.login == "true"
      && localStorage.userpostsLoaded != "true"
      && localStorage.userpostsWhen != today ){

      var username = localStorage.username;
      $('#username').append("<p style='font-size:10px; color:red; text-align:center;'>Welcome: " + username + "</p>");
      var userPosts = "username=" + username + "&upost";

      $.ajax({
          type: "GET",
          url: "../php-code2/uposts.php",
          data: userPosts,
          dataType: "json",
          success: function (data) {
              $.each(data, function (i, field) {
                  $("#userPosts").append('<p class="job cf">'+ field.title +'</p>');
              });

              // Set some flags!
              localStorage.userpostsLoaded="true";
              localStorage.userpostsWhen=today;
          }
      });

  }else{

    // If the Ajax request was avoided because of the login
    if( localStorage.login != "true" ){
      alert("Please login to post a Job");
      window.location.href = "#Main";
    }
  }
}
</code>```

Body:
I am having a strange issue with Jquery Mobile. I had created a Page which displays posts and is displaying posts correctly.

Now the issue is, whenever i click on back button and click on the posts button again, it duplicates the posts and display. The number of times i click on back button and click on post button, Posts gets duplicated accordingly and shows in multiples.

For example, i have a post that is being displayed. Now i click on back button and then click on show posts button, this time, the same post displays twice. Now again if i click back button and then click on show posts button, it now the same post shows thrice and so on.

But if i refresh the page after every back button click, then it shows the posts correctly. Can anyone guide me where i am going wrong?

Here is the Code:

HTML PAGE:

        back

Posts History

©

JQuery Code:

function displayuserPosts() {
    if (localStorage.login = "true") {
        var username = localStorage.username;
        $('#username').append("
Welcome: " + username + "
");
        var userPosts = "username=" + username + "&upost";
        $.ajax({
            type: "GET",
            url: "../php-code2/uposts.php",
            data: userPosts,
            dataType: "json",
            success: function (data) {
                $.each(data, function (i, field) {
                    $("#userPosts").append('
'+ field.title +'
');
                });
            }
        });
    } else {
        alert("Please login to post a Job");
        window.location.href = "#Main";
    }
}

Body:
On this line:

$("#userPosts").append('<p class="job cf">'+ field.title +'</p>');

Change .append to .html.

"append" means add content to what is already in the element ( #userPosts in this case).

;)

EDIT

Okay. Let's try something else then.

You already use localstorage...

Why not set a boolean flag when posts are loaded?

And one date flag to know when it was loaded...

What I call a flag is a variable used only to remember a state... To be used in comparisons.

So this should work.

Notice you can use a more precise time to remember.

// It good to know todays date.
var today = new Date().getDate(); // day of the month

function displayuserPosts() {

  // Executes only if logged in AND the posts not already loaded today.
  if(    localStorage.login == "true"
      && localStorage.userpostsLoaded != "true"
      && localStorage.userpostsWhen != today ){

      var username = localStorage.username;
      $('#username').append("<p style='font-size:10px; color:red; text-align:center;'>Welcome: " + username + "</p>");
      var userPosts = "username=" + username + "&upost";

      $.ajax({
          type: "GET",
          url: "../php-code2/uposts.php",
          data: userPosts,
          dataType: "json",
          success: function (data) {
              $.each(data, function (i, field) {
                  $("#userPosts").append('<p class="job cf">'+ field.title +'</p>');
              });

              // Set some flags!
              localStorage.userpostsLoaded="true";
              localStorage.userpostsWhen=today;
          }
      });

  }else{

    // If the Ajax request was avoided because of the login
    if( localStorage.login != "true" ){
      alert("Please login to post a Job");
      window.location.href = "#Main";
    }
  }
}


问:
Pandas: count some value in all columns
I have a dataframe

```<code>graph   0       1       2       3       4
1       blue    blue    blue    blue    blue
2       blue    blue    blue    blue    blue
3       blue    red     blue    blue    red
4       red     blue    red     red     blue
5       red     red     blue    red     red
6       blue    blue    blue    blue    blue
</code>```

I need to get the count of the value 'blue' of every string/line.

The desired output:

```<code>graph   result
1       5
2       5
3       3
4       2
5       1
6       5
</code>```

I try to do it with

```<code>(df['0', '1', '2', '3', '4']).applymap(lambda x: str.count(x, 'blue'))
</code>```

But it returns

```<code>KeyError: ('0', '1', '2', '3', '4')
</code>```

答:
With a numpy bent.  Reconstruct from scratch if you reliably know where the graph column is, namely column 0.

```<code>v = df.values
pd.DataFrame(dict(graph=v[:, 0], result=(df.values[:, 1:] == 'blue').sum(1)))

  graph  result
0     1       5
1     2       5
2     3       3
3     4       2
4     5       1
5     6       5
</code>```

naive time test

Title: Pandas: count some value in all columns

Body:
I have a dataframe

graph   0       1       2       3       4
1       blue    blue    blue    blue    blue
2       blue    blue    blue    blue    blue
3       blue    red     blue    blue    red
4       red     blue    red     red     blue
5       red     red     blue    red     red
6       blue    blue    blue    blue    blue

I need to get the count of the value 'blue' of every string/line.

The desired output:

graph   result
1       5
2       5
3       3
4       2
5       1
6       5

I try to do it with

(df['0', '1', '2', '3', '4']).applymap(lambda x: str.count(x, 'blue'))

But it returns

KeyError: ('0', '1', '2', '3', '4')

Body:
With a numpy bent.  Reconstruct from scratch if you reliably know where the graph column is, namely column 0.

v = df.values
pd.DataFrame(dict(graph=v[:, 0], result=(df.values[:, 1:] == 'blue').sum(1)))

  graph  result
0     1       5
1     2       5
2     3       3
3     4       2
4     5       1
5     6       5

naive time test


问:
Mario CS50 in Python
so I tried coding the mario assignment from CS50 in python instead of C to challenge myself and I managed to get it to work! I don't quite understand how the loops are working, especially the math because I just played around to get the result I wanted.

The requirements of the assignment were as follows

Create a half pyramid using hashes

Make sure it's right aligned

It should correspond to the height given by the User

The first line should start with 2"#"s

Any clarification on my loops would be greatly appreciated :)

```<code>print('Height: ', end='');
h = int(input());

while(h<0 or h > 24):
  print("That is an invalid input")
  print('Height: ', end='');
  h = int(input());

for i in range(h):
    print(" "*(h-i)+"#"*(i+1));
</code>```

答:
Firstly, just wanted to point out, your code does not print out the entire pyramid; it only prints half of it out. Your output should something like (if we input height to be 3, for example):

```<code>  # #
 ## ##
### ###
</code>```

Your code only prints the left side:

```<code>  #
 ##
###
</code>```

Now, to your question. Here is how you got it to work:

```<code>for i in range(h):
     print(" " * (h - i) + "#" * (i + 1));
</code>```

To describe the conditional statement of the for-loop, i starts at 0, and it goes up till h.

To understand how your print() statement works, think of it as a line segment that consists of spaces and hashes. The length of this segment is h. So, in h - i, you print part of this "segment" as spaces, and in i + 1, you print the remainder of the loop.

Now, the reason you use i + 1, and not just i is because of the for-loop condition; i starts at zero. As a result, you must have realized that the first line has no hashes, as there is h - 0 spaces, and 0 hashes. That is why the i + 1 was required; you are printing an extra space at the start of every line, if you check closely with your current code.

A more easier-to-understand logic of your code, with the same results, is:

```<code>for i in range(1, h + 1): # The counter's range is toyed with here
    print(" " * (h - i) + "#" * i); # The "i + 1" is removed
</code>```

Here, the range of the loop is toyed with; now it starts at 1 (so that the first hash is printed, and the entire "segment" is not only spaces in the first line), and it ends at h + 1 (so that the range of the loop stays the same).

The i + 1 is removed; seeing the print() statement makes it easier to understand the "segment" logic discussed above.

*Just to clarify, the alternate code I provided above is not intended as a replacement to your code; I just included it to reinforce my "segment" idea. Your code is perfectly fine and works just as well as mine.

Title: Mario CS50 in Python

Body:
so I tried coding the mario assignment from CS50 in python instead of C to challenge myself and I managed to get it to work! I don't quite understand how the loops are working, especially the math because I just played around to get the result I wanted.

The requirements of the assignment were as follows

Create a half pyramid using hashes

Make sure it's right aligned

It should correspond to the height given by the User

The first line should start with 2"#"s

Any clarification on my loops would be greatly appreciated :)

print('Height: ', end='');
h = int(input());

while(h<0 or h > 24):
  print("That is an invalid input")
  print('Height: ', end='');
  h = int(input());

for i in range(h):
    print(" "*(h-i)+"#"*(i+1));

Body:
Firstly, just wanted to point out, your code does not print out the entire pyramid; it only prints half of it out. Your output should something like (if we input height to be 3, for example):

  # #
 ## ##
### ###

Your code only prints the left side:

  #
 ##
###

Now, to your question. Here is how you got it to work:

for i in range(h):
     print(" " * (h - i) + "#" * (i + 1));

To describe the conditional statement of the for-loop, i starts at 0, and it goes up till h.

To understand how your print() statement works, think of it as a line segment that consists of spaces and hashes. The length of this segment is h. So, in h - i, you print part of this "segment" as spaces, and in i + 1, you print the remainder of the loop.

Now, the reason you use i + 1, and not just i is because of the for-loop condition; i starts at zero. As a result, you must have realized that the first line has no hashes, as there is h - 0 spaces, and 0 hashes. That is why the i + 1 was required; you are printing an extra space at the start of every line, if you check closely with your current code.

A more easier-to-understand logic of your code, with the same results, is:

for i in range(1, h + 1): # The counter's range is toyed with here
    print(" " * (h - i) + "#" * i); # The "i + 1" is removed

Here, the range of the loop is toyed with; now it starts at 1 (so that the first hash is printed, and the entire "segment" is not only spaces in the first line), and it ends at h + 1 (so that the range of the loop stays the same).

The i + 1 is removed; seeing the print() statement makes it easier to understand the "segment" logic discussed above.

*Just to clarify, the alternate code I provided above is not intended as a replacement to your code; I just included it to reinforce my "segment" idea. Your code is perfectly fine and works just as well as mine.


问:
Concourse CI get userId
I was trying to get the last userId who committed and triggered a build in Concourse CI so that I can send it as part of slack notification. Can someone point me to the right direction?</p>

答: Concourse does not save that information in an easily accessible way... you should write a task that runs git log in the correct directory and grabs the name of the last committer.

Title: Concourse CI get userId


问:
Numpy Covariance Matrix numpy.cov
I am using numpy and want to compute the covariance matrix for an ndarray. I am trying to use numpy.cov() but am not getting the correct results. More details below.

My ndarray is 768x8 for where 8 is the numbers features in my data set.

When I use MATLAB to compute the covariance matrix, I get a 8x8 (which is what I require), but when I use np.cov(), I get a 768x768 which is incorrect. I tried changing the rowvar argument to true and this does not work.

What would be the correct call to numpy.cov()? In other words, how would I reproduce the cov() results from MATLAB using numpy.

答:
Amazingly, the documentation might tell you.  You should pass rowvar=False to indicate that columns represent variables.

```<code>>>> data.shape
(768, 8)
>>> numpy.cov(data, rowvar=False).shape
(8, 8)
</code>```

Title: Numpy Covariance Matrix numpy.cov

Body:
Amazingly, the documentation might tell you.  You should pass rowvar=False to indicate that columns represent variables.

>>> data.shape
(768, 8)
>>> numpy.cov(data, rowvar=False).shape
(8, 8)


问:
WxWidgets using wxString
I'm taking a computer sciences class and we have to make a calculator using a GUI. I have been banging my head into a wall trying to even get input though.
Understand how to use pointers and GetValue(), to take in the input as a wxString but that does me no good, If I can't get the string as a double or integer then I can't perform operations on it.
Does anyone know how to convert wxString to Double? or even int?

Thanks in Advance

答:
For this purpose, there are the two functions ToDouble and ToLong.

For details take a look at the offical documentation:

http://docs.wxwidgets.org/stable/wx_wxstring.html#wxstringtolong

http://docs.wxwidgets.org/stable/wx_wxstring.html#wxstringtodouble

EDIT: Example:

```<code>wxTextCtrl ctrl;
// user has entered a number
double number;
if( !ctrl.GetValue().ToDouble( &number ) )
    // handle error
else
    // continue...
</code>```

Please note: It will only work if you enter a number. If you enter a term like 2+3 the function should return false. In this case you have to split the string up and interpret all numbers seperately.

Title: WxWidgets using wxString

Body:
For this purpose, there are the two functions ToDouble and ToLong.

For details take a look at the offical documentation:

http://docs.wxwidgets.org/stable/wx_wxstring.html#wxstringtolong

http://docs.wxwidgets.org/stable/wx_wxstring.html#wxstringtodouble

EDIT: Example:

wxTextCtrl ctrl;
// user has entered a number
double number;
if( !ctrl.GetValue().ToDouble( &number ) )
    // handle error
else
    // continue...

Please note: It will only work if you enter a number. If you enter a term like 2+3 the function should return false. In this case you have to split the string up and interpret all numbers seperately.


问:
Image not aligning to the right on gmail,outlook and yahoo mail
I'm new to email template designs and I'm wondering why this is happening to my email template. The first screen shot is what I expect and the others are what is rendered in gmail, yahoo and outlook respectively. My concern is why is the logo not being aligned to the right as expected. I've also attached the corresponding code that shows the logo.

```

答:
You have a lot of align center on the td's which need to be align right as the logo is in a table that is supposed to be aligned right.

I have added an extra table and made it the same size as the logo and aligned it right.

```

Let me know if this fixes it. If this doesn't fix the issue then we will need more code to see if there is any conflicting class or ID that is causing teh template to go eider than the design.

Is this part of a hybrid or responsive email?

Cheers

Body:
You have a lot of align center on the td's which need to be align right as the logo is in a table that is supposed to be aligned right.

I have added an extra table and made it the same size as the logo and aligned it right.

 <tr>
 <td align="right" valign="top">
 <!-- CENTERING TABLE // -->
 <!--
 The centering table keeps the content
 tables centered in the emailBody table,
 in case its width is set to 100%.
 -->
 <table border="0" cellpadding="0" cellspacing="0" width="100%" style="color:#ffffff;" bgcolor="#E1E1E1">
 <tr>
 <td align="right" valign="top">
 <!-- FLEXIBLE CONTAINER // -->
 <!--
 The flexible container has a set width
 that gets overridden by the media query.
 Most content tables within can then be
 given 100% widths.
 -->
 <table border="0" cellpadding="0" cellspacing="0" width="600" class="flexibleContainer">
 <tr>
 <td align="right" valign="top" width="600" class="flexibleContainerCell">

 <!-- CONTENT TABLE // -->
 <!--
 The content table is the first element
 that's entirely separate from the structural
 framework of the email.
 -->
 <table border="0" cellpadding="30" cellspacing="0" width="100%">
 <tr>
 <td align="right" valign="top" class="textContent">

 <table width="152" border="0" align="right" cellpadding="0" cellspacing="0" style="width:100%; max-width: 152px;">
 <tbody>
 <tr>
 <td align="right"><img alt="accesbank-logo" src="http://oi65.tinypic.com/euel9v.jpg" /></td>
 </tr>
 </tbody>
 </table>
 </td>
 </tr>
 </table>
 <!-- // CONTENT TABLE -->
 </td>
 </tr>
 </table>
 <!-- // FLEXIBLE CONTAINER -->
 </td>
 </tr>
 </table>
 <!-- // CENTERING TABLE -->
 </td>
 </tr>

Let me know if this fixes it. If this doesn't fix the issue then we will need more code to see if there is any conflicting class or ID that is causing teh template to go eider than the design.

Is this part of a hybrid or responsive email?

Cheers