问:
Using array_combine in a foreach loop to convert multiple arrays into a single array
I am trying array_combine to convert all these arrays into a single array with the unique value.

```<code>$arr_ch_no = array();
        $arr_ch_no[] = "'***0***'";
        $sql = mysql_query("SELECT ship_name,voy_no from tb_veh_data_entry WHERE (ETAQ > '".date("Y-m-d")."' or (ETAQ <> '0000-00-00' and stock = 0 and stock_sale_date = '0000-00-00')) and (user_id = 'UI08-00000063' or user_id = 'UI09-00000111') and stock_country = 58 and ((buyer in ('6371','2509','2535') and arica = 0 ) or arica=4)  group by ship_name,voy_no  ");
        while($row_no = mysql_fetch_array($sql))
        {
            $str_no_ch = selFieldCon("tb_veh_data_entry","GROUP_CONCAT(frame_no)"," ship_name = '".$row_no['ship_name']."' and voy_no = '".$row_no['voy_no']."'   and (user_id = 'UI08-00000063' or user_id = 'UI09-00000111') and stock_country = 58   and ((buyer in ('6371','2509','2535') and arica = 0 ) or arica=4) and ETAQ <> '0000-00-00' ".$this->condition."");
            $arr_no_ch = array();
            $arr_no_ch = explode(",",$str_no_ch);
            if($str_no_ch != '')
            foreach($arr_no_ch as $val)
                $arr_ch_no[] = "'".$val."'";
        }
</code>```

This query use for foreach loop

```<code>$sql    =    "SELECT * FROM tb_veh_data_entry WHERE 1 ".$this->condition." ";
</code>```

I am trying this inside foreach.

```<code>foreach loop //start

array_unique(array_combine($arr_ch_no));
</code>```

How can I convert it into a single array inside foreach.

```<code>Array
    (
        [0] => '***0***'
        [1] => 'NCP100-0027131'
    )
    Array
    (
        [0] => '***0***'
        [1] => 'NCP100-0027131'
    )
    Array
    (
        [0] => '***0***'
        [1] => 'NCP100-0027131'
    )
</code>```

But I do not get anything.

答:
this is not good solution. hope it can help you.</p>

```<code>$data1 = array_column($array, 0, 1);
$data2 = array_column($array, 1, 0);

$data1Length = count($data1);
$data2Length = count($data2);

$result = [];
if($data1Length > $data2Length) {
    foreach($data1Length as $k => $v) {
        $result[] = [$v, $k];
    }
} else {
    foreach($data1Length as $k => $v) {
        $result[] = [$k, $v];
    }
}
</code>```

Body:
I am trying array_combine to convert all these arrays into a single array with the unique value.

$arr_ch_no = array();
        $arr_ch_no[] = "'***0***'";
        $sql = mysql_query("SELECT ship_name,voy_no from tb_veh_data_entry WHERE (ETAQ > '".date("Y-m-d")."' or (ETAQ <> '0000-00-00' and stock = 0 and stock_sale_date = '0000-00-00')) and (user_id = 'UI08-00000063' or user_id = 'UI09-00000111') and stock_country = 58 and ((buyer in ('6371','2509','2535') and arica = 0 ) or arica=4)  group by ship_name,voy_no  ");
        while($row_no = mysql_fetch_array($sql))
        {
            $str_no_ch = selFieldCon("tb_veh_data_entry","GROUP_CONCAT(frame_no)"," ship_name = '".$row_no['ship_name']."' and voy_no = '".$row_no['voy_no']."'   and (user_id = 'UI08-00000063' or user_id = 'UI09-00000111') and stock_country = 58   and ((buyer in ('6371','2509','2535') and arica = 0 ) or arica=4) and ETAQ <> '0000-00-00' ".$this->condition."");
            $arr_no_ch = array();
            $arr_no_ch = explode(",",$str_no_ch);
            if($str_no_ch != '')
            foreach($arr_no_ch as $val)
                $arr_ch_no[] = "'".$val."'";
        }

This query use for foreach loop

$sql    =    "SELECT * FROM tb_veh_data_entry WHERE 1 ".$this->condition." ";

I am trying this inside foreach.

foreach loop //start

array_unique(array_combine($arr_ch_no));

How can I convert it into a single array inside foreach.

Array
    (
        [0] => '***0***'
        [1] => 'NCP100-0027131'
    )
    Array
    (
        [0] => '***0***'
        [1] => 'NCP100-0027131'
    )
    Array
    (
        [0] => '***0***'
        [1] => 'NCP100-0027131'
    )

But I do not get anything.

Body:
this is not good solution. hope it can help you.

$data1 = array_column($array, 0, 1);
$data2 = array_column($array, 1, 0);

$data1Length = count($data1);
$data2Length = count($data2);

$result = [];
if($data1Length > $data2Length) {
    foreach($data1Length as $k => $v) {
        $result[] = [$v, $k];
    }
} else {
    foreach($data1Length as $k => $v) {
        $result[] = [$k, $v];
    }
}


来源: stackexchange

问:
how to calculate p-value for 48 columns and save the results
I have two 18-by-48 datasets. One for died people and the other for survived. Both have the same column names(CNP1,CNP2,...,CNP48). I would like to calculate the P-value of each CNP.
The function that I am using is the following:

t.test(died_CNP$CNP1,survived_CNP$CNP1)[3]
  - How can I use this function for the 48 columns at one go and save the results in variables ( p1,p2,...,p48)?

答:
This is too long for a comment, but extends Gregor's answer. The key difference is it constructs the for loop without growing the object.

```<code>pVals  <- vector ("numeric", length = ncol (died_CNP))
for (i in seq_along (pVals)){
  pVals[i] <- t.test(died_CNP[[i]], survived_CNP[[i]])$p.value
}
</code>```

Or you can vectorize it

```<code>pVals <- vapply (seq_along (died_CNP),
          function (i){
            t.test(died_CNP[,i],survived_CNP[,i])$p.value
          },
          numeric(1))
</code>```

(Typed on a phone, code untested)

ContentLicense: CC BY-SA 3.0

Body:
This is too long for a comment, but extends Gregor's answer. The key difference is it constructs the for loop without growing the object.

pVals  <- vector ("numeric", length = ncol (died_CNP))
for (i in seq_along (pVals)){
  pVals[i] <- t.test(died_CNP[[i]], survived_CNP[[i]])$p.value
}

Or you can vectorize it

pVals <- vapply (seq_along (died_CNP),
          function (i){
            t.test(died_CNP[,i],survived_CNP[,i])$p.value
          },
          numeric(1))

(Typed on a phone, code untested)


问:
How to get the value of a loop text field using post method in php
I created all the text field by loop and when I click button of the text field, I can post it to another page. But now I cannot retrieve value of the text field. How can I retrieve the value of the loop text field?

This is my code.

```<code><?php
                $MYSQLQuery1=mysql_query("select id,ccode,pdesc,cost from product2")or die(mysql_error());
                $i=1;
                while($row=mysql_fetch_array($MYSQLQuery1)){
                ?>
                    <tr>
                    <td><?php echo"<img src='img/".$row['ccode'].".jpg' width='150' height='200'/>","<br/>";
                              echo $row['pdesc'],"<br/>";
                              echo $row['cost']; ?>
                    </td>
                    <td><?php echo "<input type='text' name='product".$i."'>";  ?></td>
                    <td>
                        <form action="addvehicle.php" role="form" method="POST" class="form-inline">
                            <input type="hidden" name="ID" value="<?php echo $row['id']; ?>">
                            <input type="submit" name="SUBMITEDITVEHICLE"  value="Edit" class="btn btn-success">
                        </form>
                    </td>
                    </tr>
                <?php
                    $i++;
                }
                ?>
</code>```

This is where I post the value.

```<code>if(isset($_POST['SUBMITEDITVEHICLE']))
{
    if($_POST['SUBMITEDITVEHICLE']=='Edit')
    {
            $i=0;
            $E_1 = clean($_POST['ID']);
            $gt = clean($_POST['product. $i']);
            echo $gt,"<br/>";
            $query_editvehicle=mysql_query("SELECT ccode,pdesc,cost FROM product2 WHERE ID='$E_1' ")or die(mysql_error());
            while($roweditvehicle=mysql_fetch_array($query_editvehicle))
            {
                $txtid = $roweditvehicle['id'];
                $txtvehicleregno = $roweditvehicle['ccode'];
                $txtmakemodel = $roweditvehicle['pdesc'];
                $txtcost = $roweditvehicle['cost'];
            }
        echo txtvehivleregno;
        echo txtmakemodel;
        echo txtcost;
        $i++;
    }
}
</code>```

答:
<?php echo "<input type='text' name='product".$i."'>"; // ?>

Its a text box right, so you have to assign the value by

```<code><td><?php echo "<input type='text' name='product".$i."' value=$row['cost']>"; // ?></td>
</code>```

Body:
I created all the text field by loop and when I click button of the text field, I can post it to another page. But now I cannot retrieve value of the text field. How can I retrieve the value of the loop text field?

This is my code.

<?php
                $MYSQLQuery1=mysql_query("select id,ccode,pdesc,cost from product2")or die(mysql_error());
                $i=1;
                while($row=mysql_fetch_array($MYSQLQuery1)){
                ?>

                    <?php echo"","
";
                              echo $row['pdesc'],"
";
                              echo $row['cost']; ?>

                    <?php echo "<input type='text' name='product".$i."'>";  ?>

                        <form action="addvehicle.php" role="form" method="POST" class="form-inline">
                            <input type="hidden" name="ID" value="<?php echo $row['id']; ?>">
                            <input type="submit" name="SUBMITEDITVEHICLE"  value="Edit" class="btn btn-success">
                        </form>

                <?php
                    $i++;
                }
                ?>

This is where I post the value.

if(isset($_POST['SUBMITEDITVEHICLE']))
{
    if($_POST['SUBMITEDITVEHICLE']=='Edit')
    {
            $i=0;
            $E_1 = clean($_POST['ID']);
            $gt = clean($_POST['product. $i']);
            echo $gt,"
";
            $query_editvehicle=mysql_query("SELECT ccode,pdesc,cost FROM product2 WHERE ID='$E_1' ")or die(mysql_error());
            while($roweditvehicle=mysql_fetch_array($query_editvehicle))
            {
                $txtid = $roweditvehicle['id'];
                $txtvehicleregno = $roweditvehicle['ccode'];
                $txtmakemodel = $roweditvehicle['pdesc'];
                $txtcost = $roweditvehicle['cost'];
            }
        echo txtvehivleregno;
        echo txtmakemodel;
        echo txtcost;
        $i++;
    }
}

Body:
<td><?php echo "<input type='text' name='product".$i."'>"; // ?></td>

Its a text box right, so you have to assign the value by

<td><?php echo "<input type='text' name='product".$i."' value=$row['cost']>"; // ?></td>


问:
Is browserify calling my function?
Weird situation

I have a function named THREE.Vector3.prototype.changeBasis that isn't called by me, but still returns a type error... Apparently it is called by Browserify!

The stack trace points straight to line 1, column 246. This line is generated by Browserify.

This is how line 1 looks in my bundle file:

```<code>(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
</code>```

And this is how it looks from column 246 and onwards:

```<code>t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
</code>```

The question is: why is line 1 calling my function..? It shouldn't.

This is how the stack trace looks in full:

```<code>TypeError: transformMatrix is undefined[Learn More]  tb.js:16065:27
    changeBasis file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:16065:27
    [90]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:16063:48
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    s/< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:305
    [86]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:15220:1
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    s/< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:305
    [85]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:14689:20
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    s/< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:305
    [5]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:878:17
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    s/< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:305
    [17]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:4528:15
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    s/< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:305
    [61]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:11972:24
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    s/< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:305
    [40]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:5947:33
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    s/< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:305
    [35]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:5109:20
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    e file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:425
    <anonymous> file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:11
</code>```

The two first lines points inside the function definition and then the stack trace jumps straight to line 1 of my bundle file (named tb.js).

This is how I define my function:

```<code>THREE.Vector3.prototype.changeBasis = function changeBasis( transformMatrix, lb0, lb1, lb2, local_to_global ) {  // line 163063 in the bundle

        if (!local_to_global) { transformMatrix.getInverse( transformMatrix ) }  // line 163065 in the bundle

        return this.applyMatrix3(transformMatrix);

}();
</code>```

This is the file in which my function is defined:

```<code>"use strict";

var THREE = require('three');

var loadTexture_promise = ( texture_path, texture_loader ) => {
    var texture_promise;

    if (       loadTexture_promise.texturePromises_cache[texture_path] !== undefined ) {
        return loadTexture_promise.texturePromises_cache[texture_path]
    }

    texture_promise = new Promise(
        function( resolve, reject )
        {
            texture_loader.load(
                texture_path,
                function (texture) {
                    // Success callback of TextureLoader
                    // We're done, so tell the promise it is complete
                    resolve(texture);
                },
                function (XmlHttpRequest_instance) {
                    // Progress callback of TextureLoader
                },
                function (unknown_parameter) {
                    // Failure callback of TextureLoader
                    // Reject the promise with the failure
                    reject(new Error('Could not load texture ' + texture_path));
                }
            );
        }
    );

    // add texture_promise to cache:
    loadTexture_promise.texturePromises_cache[texture_path] = texture_promise;

    return texture_promise;
};
// establish cache object on the loadTexture_promise function:
loadTexture_promise.texturePromises_cache = [];

THREE.PointHelper = function ( position = {x:0,y:0,z:0}, size = 20 ) {

    var geometry = new THREE.Geometry();
    var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );

    this.colorX_origo = new THREE.Color( 1,   0, 0 );
    this.colorX_end   = new THREE.Color( 1, 0.6, 0 );
    this.colorY_origo = new THREE.Color( 0,   1, 0 );
    this.colorY_end   = new THREE.Color( 0.6, 1, 0 );
    this.colorZ_origo = new THREE.Color( 0,   0, 1 );
    this.colorZ_end   = new THREE.Color( 0, 0.6, 1 );

    geometry.vertices.push(
        new THREE.Vector3( -size, 0, 0 ), new THREE.Vector3( 0, 0, 0 ),
        new THREE.Vector3(  size, 0, 0 ), new THREE.Vector3( 0, 0, 0 ),
        new THREE.Vector3( 0, -size, 0 ), new THREE.Vector3( 0, 0, 0 ),
        new THREE.Vector3( 0,  size, 0 ), new THREE.Vector3( 0, 0, 0 ),
        new THREE.Vector3( 0, 0, -size ), new THREE.Vector3( 0, 0, 0 ),
        new THREE.Vector3( 0, 0,  size ), new THREE.Vector3( 0, 0, 0 )
    );

    geometry.colors.push(
        this.colorX_end, this.colorX_origo, this.colorX_end, this.colorX_origo,
        this.colorY_end, this.colorY_origo, this.colorY_end, this.colorY_origo,
        this.colorZ_end, this.colorZ_origo, this.colorZ_end, this.colorZ_origo );

    THREE.Line.call( this, geometry, material );

    this.position.set( position.x, position.y, position.z );

};

THREE.PointHelper.prototype = Object.create( THREE.LineSegments.prototype );
THREE.PointHelper.prototype.constructor = THREE.PointHelper;

var origo = new THREE.Vector3();
THREE.VectorHelper = function ( end, color ) {

    var geometry = new THREE.Geometry();
    var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );

    geometry.vertices.push( origo, end );

    if ( typeof color !== "undefined" ) { this.color = new THREE.Color( color    ); }
    else                                { this.color = new THREE.Color( 0xffffff ); }
    geometry.colors.push( this.color, this.color );

    THREE.Line.call( this, geometry, material );
};

THREE.VectorHelper.prototype = Object.create( THREE.Line.prototype );
THREE.VectorHelper.prototype.constructor = THREE.VectorHelper;

THREE.VectorHelper.prototype.setColor = function( color ) {
    this.color.set( color );
    this.geometry.colorsNeedUpdate = true;
    return this
};

THREE.LineHelper = function ( start, end, color ) {

    var geometry = new THREE.Geometry();
    var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );

    geometry.vertices.push( start, end );

    if ( typeof color !== "undefined" ) { this.color = new THREE.Color( color    ); }
    else                                { this.color = new THREE.Color( 0xffffff ); }
    geometry.colors.push( this.color, this.color );

    THREE.Line.call( this, geometry, material );

};

THREE.LineHelper.prototype = Object.create( THREE.Line.prototype );
THREE.LineHelper.prototype.constructor = THREE.LineHelper;

THREE.LineHelper.prototype.setColor = function( color ) {
    this.color.set( color );
    this.geometry.colorsNeedUpdate = true;
    return this
};

// fixme: consider having it take a THREE.Plane as argument:
THREE.PlaneHelper = function ( planeNormal, planeCenter, size, step, colorCenterLine, colorGrid, debug ) {

    if ( typeof colorGrid === "undefined" ) { colorGrid = colorCenterLine; }

    THREE.GridHelper.call( this, size, step, colorCenterLine, colorGrid );

    if ( debug ) { console.log( "this.rotation before quaternion: ", this.rotation.clone() ); }

    this.position.set(planeCenter.x, planeCenter.y, planeCenter.z);

    var standardPlaneNormal = new THREE.Vector3(0, 1, 0);
    var quaternion  = new THREE.Quaternion().setFromUnitVectors(standardPlaneNormal, planeNormal);
    this.rotation.setFromQuaternion(quaternion);

    if ( debug ) {
        console.log( "quaternion after setFromUnitVectors: ", quaternion.clone() );
        console.log( "this.rotation after quaternion: ", this.rotation.clone() ); }
};

THREE.PlaneHelper.prototype = Object.create( THREE.GridHelper.prototype );
THREE.PlaneHelper.prototype.constructor = THREE.PlaneHelper;

THREE.Vector3.prototype.rejectOnVector = function () {

    var v1;

    return function rejectOnVector( planeNormal ) {

        if ( v1 === undefined ) v1 = new THREE.Vector3();

        v1.copy( this ).projectOnVector( planeNormal );

        return this.sub( v1 );

    };

}();

THREE.Vector3.prototype.changeBasis = function changeBasis( transformMatrix, lb0, lb1, lb2, local_to_global ) {  // lb = local basis

        if (!local_to_global) { transformMatrix.getInverse( transformMatrix ) }

        return this.applyMatrix3(transformMatrix);

}();

module.exports = {
    loadTexture_promise
};
</code>```

答: I hadn't seen my function was executing itself right after being defined.</p>

Title: Is browserify calling my function?

Body:
Weird situation

I have a function named THREE.Vector3.prototype.changeBasis that isn't called by me, but still returns a type error... Apparently it is called by Browserify!

The stack trace points straight to line 1, column 246. This line is generated by Browserify.

This is how line 1 looks in my bundle file:

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

And this is how it looks from column 246 and onwards:

t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){

The question is: why is line 1 calling my function..? It shouldn't.

This is how the stack trace looks in full:

TypeError: transformMatrix is undefined[Learn More]  tb.js:16065:27
    changeBasis file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:16065:27
    [90]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:16063:48
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    s/< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:305
    [86]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:15220:1
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    s/< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:305
    [85]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:14689:20
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    s/< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:305
    [5]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:878:17
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    s/< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:305
    [17]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:4528:15
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    s/< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:305
    [61]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:11972:24
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    s/< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:305
    [40]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:5947:33
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    s/< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:305
    [35]< file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:5109:20
    s file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:246
    e file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:425
    <anonymous> file:///C:/Users/Jon/Auchitect/frontend/js/tb.js:1:11

The two first lines points inside the function definition and then the stack trace jumps straight to line 1 of my bundle file (named tb.js).

This is how I define my function:

THREE.Vector3.prototype.changeBasis = function changeBasis( transformMatrix, lb0, lb1, lb2, local_to_global ) {  // line 163063 in the bundle

        if (!local_to_global) { transformMatrix.getInverse( transformMatrix ) }  // line 163065 in the bundle

        return this.applyMatrix3(transformMatrix);

}();

This is the file in which my function is defined:

"use strict";

var THREE = require('three');

var loadTexture_promise = ( texture_path, texture_loader ) => {
    var texture_promise;

    if (       loadTexture_promise.texturePromises_cache[texture_path] !== undefined ) {
        return loadTexture_promise.texturePromises_cache[texture_path]
    }

    texture_promise = new Promise(
        function( resolve, reject )
        {
            texture_loader.load(
                texture_path,
                function (texture) {
                    // Success callback of TextureLoader
                    // We're done, so tell the promise it is complete
                    resolve(texture);
                },
                function (XmlHttpRequest_instance) {
                    // Progress callback of TextureLoader
                },
                function (unknown_parameter) {
                    // Failure callback of TextureLoader
                    // Reject the promise with the failure
                    reject(new Error('Could not load texture ' + texture_path));
                }
            );
        }
    );

    // add texture_promise to cache:
    loadTexture_promise.texturePromises_cache[texture_path] = texture_promise;

    return texture_promise;
};
// establish cache object on the loadTexture_promise function:
loadTexture_promise.texturePromises_cache = [];

THREE.PointHelper = function ( position = {x:0,y:0,z:0}, size = 20 ) {

    var geometry = new THREE.Geometry();
    var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );

    this.colorX_origo = new THREE.Color( 1,   0, 0 );
    this.colorX_end   = new THREE.Color( 1, 0.6, 0 );
    this.colorY_origo = new THREE.Color( 0,   1, 0 );
    this.colorY_end   = new THREE.Color( 0.6, 1, 0 );
    this.colorZ_origo = new THREE.Color( 0,   0, 1 );
    this.colorZ_end   = new THREE.Color( 0, 0.6, 1 );

    geometry.vertices.push(
        new THREE.Vector3( -size, 0, 0 ), new THREE.Vector3( 0, 0, 0 ),
        new THREE.Vector3(  size, 0, 0 ), new THREE.Vector3( 0, 0, 0 ),
        new THREE.Vector3( 0, -size, 0 ), new THREE.Vector3( 0, 0, 0 ),
        new THREE.Vector3( 0,  size, 0 ), new THREE.Vector3( 0, 0, 0 ),
        new THREE.Vector3( 0, 0, -size ), new THREE.Vector3( 0, 0, 0 ),
        new THREE.Vector3( 0, 0,  size ), new THREE.Vector3( 0, 0, 0 )
    );

    geometry.colors.push(
        this.colorX_end, this.colorX_origo, this.colorX_end, this.colorX_origo,
        this.colorY_end, this.colorY_origo, this.colorY_end, this.colorY_origo,
        this.colorZ_end, this.colorZ_origo, this.colorZ_end, this.colorZ_origo );

    THREE.Line.call( this, geometry, material );

    this.position.set( position.x, position.y, position.z );

};

THREE.PointHelper.prototype = Object.create( THREE.LineSegments.prototype );
THREE.PointHelper.prototype.constructor = THREE.PointHelper;

var origo = new THREE.Vector3();
THREE.VectorHelper = function ( end, color ) {

    var geometry = new THREE.Geometry();
    var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );

    geometry.vertices.push( origo, end );

    if ( typeof color !== "undefined" ) { this.color = new THREE.Color( color    ); }
    else                                { this.color = new THREE.Color( 0xffffff ); }
    geometry.colors.push( this.color, this.color );

    THREE.Line.call( this, geometry, material );
};

THREE.VectorHelper.prototype = Object.create( THREE.Line.prototype );
THREE.VectorHelper.prototype.constructor = THREE.VectorHelper;

THREE.VectorHelper.prototype.setColor = function( color ) {
    this.color.set( color );
    this.geometry.colorsNeedUpdate = true;
    return this
};

THREE.LineHelper = function ( start, end, color ) {

    var geometry = new THREE.Geometry();
    var material = new THREE.LineBasicMaterial( { vertexColors: THREE.VertexColors } );

    geometry.vertices.push( start, end );

    if ( typeof color !== "undefined" ) { this.color = new THREE.Color( color    ); }
    else                                { this.color = new THREE.Color( 0xffffff ); }
    geometry.colors.push( this.color, this.color );

    THREE.Line.call( this, geometry, material );

};

THREE.LineHelper.prototype = Object.create( THREE.Line.prototype );
THREE.LineHelper.prototype.constructor = THREE.LineHelper;

THREE.LineHelper.prototype.setColor = function( color ) {
    this.color.set( color );
    this.geometry.colorsNeedUpdate = true;
    return this
};

// fixme: consider having it take a THREE.Plane as argument:
THREE.PlaneHelper = function ( planeNormal, planeCenter, size, step, colorCenterLine, colorGrid, debug ) {

    if ( typeof colorGrid === "undefined" ) { colorGrid = colorCenterLine; }

    THREE.GridHelper.call( this, size, step, colorCenterLine, colorGrid );

    if ( debug ) { console.log( "this.rotation before quaternion: ", this.rotation.clone() ); }

    this.position.set(planeCenter.x, planeCenter.y, planeCenter.z);

    var standardPlaneNormal = new THREE.Vector3(0, 1, 0);
    var quaternion  = new THREE.Quaternion().setFromUnitVectors(standardPlaneNormal, planeNormal);
    this.rotation.setFromQuaternion(quaternion);

    if ( debug ) {
        console.log( "quaternion after setFromUnitVectors: ", quaternion.clone() );
        console.log( "this.rotation after quaternion: ", this.rotation.clone() ); }
};

THREE.PlaneHelper.prototype = Object.create( THREE.GridHelper.prototype );
THREE.PlaneHelper.prototype.constructor = THREE.PlaneHelper;

THREE.Vector3.prototype.rejectOnVector = function () {

    var v1;

    return function rejectOnVector( planeNormal ) {

        if ( v1 === undefined ) v1 = new THREE.Vector3();

        v1.copy( this ).projectOnVector( planeNormal );

        return this.sub( v1 );

    };

}();

THREE.Vector3.prototype.changeBasis = function changeBasis( transformMatrix, lb0, lb1, lb2, local_to_global ) {  // lb = local basis

        if (!local_to_global) { transformMatrix.getInverse( transformMatrix ) }

        return this.applyMatrix3(transformMatrix);

}();

module.exports = {
    loadTexture_promise
};


问:
Determine if a character appears before first occurrence of another character
I want to be able to input a list of letters (there are only four options for letters in the list), however the list can be up to ten or so items long, for example:

```<code>letter_options = ['A', 'B', 'C', 'D']

s = ['B', 'C', 'A', 'C', 'D', 'A']
s = ['C', 'A', 'D', 'C', 'A']
s = ['A', 'B', 'A', 'A', 'D', 'B', 'B']
</code>```

My question is how would I go about determining if 'B' occurs before a 'D' or an 'A' occurs? If 'B' does not exist in the list, then the code would output 0. If 'B' does occur before an 'A' or 'D', then the code would output 1.

Here is what I have, but it does not work for the case where 'B' does not occur.

```<code>letters = ['A', 'A', 'A', 'A']
fkt = []

check = ' '.join(letters).split('B')[0].split()
if letters!=[] and letters[0]=='B':
    fkt.append(1)
elif letters!=[] and any(idx in check for idx in ['A', 'D']):
    fkt.append(0)
else:
    fkt.append(1)
</code>```

答:
If ['B', 'C', 'A', 'C', 'D', 'A'] is your list and you want to find out whether 'B' precedes 'D', you can convert your list to a string and then use str.find:

```<code>In [141]: l = ''.join(['B', 'C', 'A', 'C', 'D', 'A'])

In [148]: l[:max(0, l.find('D'))].find('A') > -1
Out[148]: True
</code>```

In general,

```<code>In [153]: def foo(l, c1, c2): # is c2 before c1?
     ...:     return l[:max(0, l.find(c1))].find(c2) > -1
     ...:

In [154]: foo(l, 'B', 'D')
Out[154]: False

In [155]: foo(l, 'D', 'B')
Out[155]: True
</code>```

str.find returns -1, so you can handle no-matches gracefully, since a splice to 0 ([:0]) returns an empty list.

An even simpler alternative is 0 <= l.find('X') < l.find('Y') as suggested by VPfB:

```<code>def foo(l, c1, c2): # is c2 before c1?
    return `0 <= l.find('c2') < l.find('c1')`
</code>```

Body:
I want to be able to input a list of letters (there are only four options for letters in the list), however the list can be up to ten or so items long, for example:

letter_options = ['A', 'B', 'C', 'D']

s = ['B', 'C', 'A', 'C', 'D', 'A']
s = ['C', 'A', 'D', 'C', 'A']
s = ['A', 'B', 'A', 'A', 'D', 'B', 'B']

My question is how would I go about determining if 'B' occurs before a 'D' or an 'A' occurs? If 'B' does not exist in the list, then the code would output 0. If 'B' does occur before an 'A' or 'D', then the code would output 1.

Here is what I have, but it does not work for the case where 'B' does not occur.

letters = ['A', 'A', 'A', 'A']
fkt = []

check = ' '.join(letters).split('B')[0].split()
if letters!=[] and letters[0]=='B':
    fkt.append(1)
elif letters!=[] and any(idx in check for idx in ['A', 'D']):
    fkt.append(0)
else:
    fkt.append(1)

Body:
If ['B', 'C', 'A', 'C', 'D', 'A'] is your list and you want to find out whether 'B' precedes 'D', you can convert your list to a string and then use str.find:

In [141]: l = ''.join(['B', 'C', 'A', 'C', 'D', 'A'])

In [148]: l[:max(0, l.find('D'))].find('A') > -1
Out[148]: True

In general,

In [153]: def foo(l, c1, c2): # is c2 before c1?
     ...:     return l[:max(0, l.find(c1))].find(c2) > -1
     ...:

In [154]: foo(l, 'B', 'D')
Out[154]: False

In [155]: foo(l, 'D', 'B')
Out[155]: True

str.find returns -1, so you can handle no-matches gracefully, since a splice to 0 ([:0]) returns an empty list.

An even simpler alternative is 0 <= l.find('X') < l.find('Y') as suggested by VPfB:

def foo(l, c1, c2): # is c2 before c1?
    return `0 <= l.find('c2') < l.find('c1')`


问:
Serialize into native memory buffer from C# using flatbuffers
Is it possible with flatbuffers in C# to serialize objects to native (unmanaged) memory buffer?
So I want to do these steps:

Allocate a native memory buffer from native memory

Create objects in C# and serialize them into the allocated buffer

Send this memory buffer to C++ for deserialization

I'm thinking either of some custom memory buffer allocator in C#, or of some way of transferring ownership of a memory buffer form C# to C++.

In general I want to avoid copying memory when sending data from C# to C++ and vice versa. I want this memory buffer to be shared between C# and C++.

How do I do that?

答:
No, the current FlatBuffers implementation is hard-coded to write to a regular byte array. You could copy this array to native memory afterwards, or like @pm100 says, pin it.

All serialization in FlatBuffers goes through an abstraction called the ByteBuffer, so if you made an implementation of that for native memory, it could be used directly relatively easily.


问:
Get value from select box and add to total with jQuery
I have managed to get this code up and running, which in short calculates the total price of cleaning a house based on it's size. Now i want to add an second option: choosing desired time of day, but i'm not sure how to proceed and connect the two different form elements.

This is how my code looks like now:

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

    $("#order").on('input', function(){
        var kvm2 = parseInt($('#kvm2').val()) || 0;
        var min_price = 299;
        var kvm2_price;
        if(kvm2 > 100) {
            kvm2_price = 6;
        }
        if(kvm2 > 200) {
            kvm2_price = 4;
        }
        if(kvm2 <= 100) {
            kvm2_price = 7;
        }
        var total = (kvm2_price * kvm2).toFixed(2);
        if(total < min_price) {
            $('#total').html(min_price);
        }
        else {
            $('#total').html(total);
        }
    });
});
</code>```

This is the select box I want to add:

```<code> <select name="timeslot" class="form-control form-control-lg">
    <option value="1">Dagtid (08 - 15) 0kr</option>
    <option value="2">Formiddag (12 - 15) 39kr</option>
    <option value="3">Ettermiddag (16 - 18) 39kr</option>
    <option value="4">Kveld (19 - 24) 129kr</option>
  </select>
</code>```

Based on the option you choose, either 0kr, 39kr or 129kr should be added on top of the total sales price.

答:
Declare total as a global, then add to it in the second function, and update the value in the element.  For simplicity, the code below just gives total an initial value, as though your first function had run.  Then, select a time slot, and the additional fee is added and is displayed in the total element.  Note - you need to keep the total variable as the output of the first function, or the total will keep increasing if the user changes the time option several times.

var total = 100;
  /*$("#order").on('input', function() {
    var kvm2 = parseInt($('#kvm2').val()) || 0;
    var min_price = 299;
    var kvm2_price;
    if (kvm2 > 100) {
      kvm2_price = 6;
    }
    if (kvm2 > 200) {
      kvm2_price = 4;
    }
    if (kvm2 <= 100) {
      kvm2_price = 7;
    }
    total = (kvm2_price * kvm2).toFixed(2);
    if (total < min_price) {
      $('#total').html(min_price);
    } else {
      $('#total').html(total);
    }
  });*/

  $('#timeslot').on('change', function() {
    extra = $(this).val();
    switch (extra) {
      case '1':
        add = 0;
        break;
      case '2':
      case '3':
        add = 39;
        break;
      case '4':
        add = 129;
        break;
    }
    total2 = total + add;
    console.log(total2);
    $('#total').html(total2);
  })```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="timeslot" class="form-control form-control-lg">
    <option disabled selected>Select Time</option>
    <option value="1">Dagtid (08 - 15) 0kr</option>
    <option value="2">Formiddag (12 - 15) 39kr</option>
    <option value="3">Ettermiddag (16 - 18) 39kr</option>
    <option value="4">Kveld (19 - 24) 129kr</option>
  </select>
<br>
<div id="total">100</div></code>```

Body:
I have managed to get this code up and running, which in short calculates the total price of cleaning a house based on it's size. Now i want to add an second option: choosing desired time of day, but i'm not sure how to proceed and connect the two different form elements.

This is how my code looks like now:

$(document).ready(function(){

    $("#order").on('input', function(){
        var kvm2 = parseInt($('#kvm2').val()) || 0;
        var min_price = 299;
        var kvm2_price;
        if(kvm2 > 100) {
            kvm2_price = 6;
        }
        if(kvm2 > 200) {
            kvm2_price = 4;
        }
        if(kvm2 <= 100) {
            kvm2_price = 7;
        }
        var total = (kvm2_price * kvm2).toFixed(2);
        if(total < min_price) {
            $('#total').html(min_price);
        }
        else {
            $('#total').html(total);
        }
    });
});

This is the select box I want to add:

 <select name="timeslot" class="form-control form-control-lg">
    <option value="1">Dagtid (08 - 15) 0kr</option>
    <option value="2">Formiddag (12 - 15) 39kr</option>
    <option value="3">Ettermiddag (16 - 18) 39kr</option>
    <option value="4">Kveld (19 - 24) 129kr</option>
  </select>

Based on the option you choose, either 0kr, 39kr or 129kr should be added on top of the total sales price.

Body:
Declare total as a global, then add to it in the second function, and update the value in the element.  For simplicity, the code below just gives total an initial value, as though your first function had run.  Then, select a time slot, and the additional fee is added and is displayed in the total element.  Note - you need to keep the total variable as the output of the first function, or the total will keep increasing if the user changes the time option several times.

var total = 100;
  /*$("#order").on('input', function() {
    var kvm2 = parseInt($('#kvm2').val()) || 0;
    var min_price = 299;
    var kvm2_price;
    if (kvm2 > 100) {
      kvm2_price = 6;
    }
    if (kvm2 > 200) {
      kvm2_price = 4;
    }
    if (kvm2 <= 100) {
      kvm2_price = 7;
    }
    total = (kvm2_price * kvm2).toFixed(2);
    if (total < min_price) {
      $('#total').html(min_price);
    } else {
      $('#total').html(total);
    }
  });*/

  $('#timeslot').on('change', function() {
    extra = $(this).val();
    switch (extra) {
      case '1':
        add = 0;
        break;
      case '2':
      case '3':
        add = 39;
        break;
      case '4':
        add = 129;
        break;
    }
    total2 = total + add;
    console.log(total2);
    $('#total').html(total2);
  })

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="timeslot" class="form-control form-control-lg">
    <option disabled selected>Select Time</option>
    <option value="1">Dagtid (08 - 15) 0kr</option>
    <option value="2">Formiddag (12 - 15) 39kr</option>
    <option value="3">Ettermiddag (16 - 18) 39kr</option>
    <option value="4">Kveld (19 - 24) 129kr</option>
  </select>
<br>
<div id="total">100</div>


问:
Connecting to MySQL outside of Vagrant box
I tried to sudo netstat -natp | grep mysql to see what port mysql was listening on and I see that it is actually listening on what is below. I also did an ifconfig to see what ip I was on within the vagrant box. I am trying to find out this info so that I can connect to a mysql database through a vagrant virtual machine, but use that information in an .env inside of a laravel application that is outside of the box. Can anyone help?

tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LIST

答:
In /etc/my.cnf, make ensure you have the following configuration:

1) Comment out this line if it's present, as it prevents external access

```<code>#skip-networking
</code>```

2) Set bind-address to as follows, if set to locahost, only local connections will be possible:

```<code>bind-address=0.0.0.0
</code>```

3) Restart MySQL with:

```<code>sudo service mysql restart
</code>```

This should do it.

If it doesn't then you may have a firewall consideration to take care of. If you're on the default iptables, then run:

```<code>iptables -A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT
</code>```

To verify the port is open, from your external host (not the VM) you can run:

```<code>nmap <vm-ip-address-here>
</code>```

If you don't see 3306 open, you have other uncommon networking issues.

Body:
In /etc/my.cnf, make ensure you have the following configuration:

1) Comment out this line if it's present, as it prevents external access

#skip-networking

2) Set bind-address to as follows, if set to locahost, only local connections will be possible:

bind-address=0.0.0.0

3) Restart MySQL with:

sudo service mysql restart

This should do it.

If it doesn't then you may have a firewall consideration to take care of. If you're on the default iptables, then run:

iptables -A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT

To verify the port is open, from your external host (not the VM) you can run:

nmap <vm-ip-address-here>

If you don't see 3306 open, you have other uncommon networking issues.


问:
ThreeJS texture problems
I have a basic scene in threejs that loads a .stl file, it loads normally, but it automatically changes color and I also want it to have its original color What do I have to do to fix it?

```<code>var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 60, window.innerWidth/window.innerHeight, 1, 500 );

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild(renderer.domElement);

controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.center =  new THREE.Vector3();

// var geometry = new THREE.BoxGeometry( 3, 1, 1 );
// var material = new THREE.MeshBasicMaterial( { color: 'skyblue' } );
// var cube = new THREE.Mesh( geometry, material );
// scene.add( cube );

var loader = new THREE.STLLoader();
loader.load( 'js/novo/undefined.stl', function ( geometry ) {
    console.log(geometry);

    var mesh = new THREE.Mesh(geometry);
    mesh.scale.set( 0.1, 0.1, 0.1 );
    // mesh.rotation.set( - Math.PI / 2, Math.PI / 2, 0 );
    // mesh.scale.set( 0.3, 0.3, 0.3 );
    // mesh.receiveShadow = true;
    scene.add( mesh );
});

camera.position.z = 300;

var animate = function () {
    requestAnimationFrame( animate );
    renderer.render(scene, camera);
};

animate();
</code>```

How should be:

How are you doing:

答:
You are not applying a material to your Mesh.

var mesh = new THREE.Mesh(geometry);

When a mesh is created, if you do not specify a material, a random colored BasicMaterial is applied which can be seen if you look at the THREE.Mesh source.

```<code>function Mesh( geometry, material ) {

    Object3D.call( this );

    this.type = 'Mesh';

    this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
    this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );

    this.drawMode = TrianglesDrawMode;

    this.updateMorphTargets();

}
</code>```

So, to fix your problem, create some sort of material, and send it to the Mesh constructor as the second parameter.

eg.

```<code>// create a red material.
var myMaterial = new THREE.MeshBasicMaterial({color: 0xff0000})
// create mesh with red material applied
var mesh = new THREE.Mesh(geometry, myMaterial);
</code>```

Title: ThreeJS texture problems

Body:
I have a basic scene in threejs that loads a .stl file, it loads normally, but it automatically changes color and I also want it to have its original color What do I have to do to fix it?

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 60, window.innerWidth/window.innerHeight, 1, 500 );

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild(renderer.domElement);

controls = new THREE.OrbitControls(camera, renderer.domElement);
controls.center =  new THREE.Vector3();

// var geometry = new THREE.BoxGeometry( 3, 1, 1 );
// var material = new THREE.MeshBasicMaterial( { color: 'skyblue' } );
// var cube = new THREE.Mesh( geometry, material );
// scene.add( cube );

var loader = new THREE.STLLoader();
loader.load( 'js/novo/undefined.stl', function ( geometry ) {
    console.log(geometry);

    var mesh = new THREE.Mesh(geometry);
    mesh.scale.set( 0.1, 0.1, 0.1 );
    // mesh.rotation.set( - Math.PI / 2, Math.PI / 2, 0 );
    // mesh.scale.set( 0.3, 0.3, 0.3 );
    // mesh.receiveShadow = true;
    scene.add( mesh );
});

camera.position.z = 300;

var animate = function () {
    requestAnimationFrame( animate );
    renderer.render(scene, camera);
};

animate();

How should be:

How are you doing:

Body:
You are not applying a material to your Mesh.

var mesh = new THREE.Mesh(geometry);

When a mesh is created, if you do not specify a material, a random colored BasicMaterial is applied which can be seen if you look at the THREE.Mesh source.

function Mesh( geometry, material ) {

    Object3D.call( this );

    this.type = 'Mesh';

    this.geometry = geometry !== undefined ? geometry : new BufferGeometry();
    this.material = material !== undefined ? material : new MeshBasicMaterial( { color: Math.random() * 0xffffff } );

    this.drawMode = TrianglesDrawMode;

    this.updateMorphTargets();

}

So, to fix your problem, create some sort of material, and send it to the Mesh constructor as the second parameter.

eg.

// create a red material.
var myMaterial = new THREE.MeshBasicMaterial({color: 0xff0000})
// create mesh with red material applied
var mesh = new THREE.Mesh(geometry, myMaterial);


问:
How to get a redirected address in C#
I can download a page from a website using </p>

```<code>sString = new System.Net.WebClient().DownloadString(Page);
</code>```

<p>But if the page redirects, how can I capture the new address.  For example, if I fetch google.com website, I would like to grab the page it redirects to so I can get the ei code.  </p>

答:
Here's how it's done using HttpClient

```<code>        string Page = "https://stackoverflow.com/questions/44980231/";
        HttpClientHandler ClientHandler = new HttpClientHandler();
        ClientHandler.AllowAutoRedirect = false;
        HttpClient client = new HttpClient(ClientHandler);
        HttpResponseMessage response = await client.GetAsync(Page);
        try
        {
            string location = response.Headers.GetValues("Location").FirstOrDefault();
            if (!Uri.IsWellFormedUriString(location, UriKind.Absolute))
            {
                Uri PageUri = new Uri(Page);
                location = PageUri.Scheme + "://" + PageUri.Host + location;
            }
            MessageBox.Show(location);
        }
        catch
        {
            MessageBox.Show("No redirect!");
        }
</code>```

Result:

Title: How to get a redirected address in C#

Body:
I can download a page from a website using

sString = new System.Net.WebClient().DownloadString(Page);

But if the page redirects, how can I capture the new address.  For example, if I fetch google.com website, I would like to grab the page it redirects to so I can get the ei code.

Body:
Here's how it's done using HttpClient

        string Page = "https://stackoverflow.com/questions/44980231/";
        HttpClientHandler ClientHandler = new HttpClientHandler();
        ClientHandler.AllowAutoRedirect = false;
        HttpClient client = new HttpClient(ClientHandler);
        HttpResponseMessage response = await client.GetAsync(Page);
        try
        {
            string location = response.Headers.GetValues("Location").FirstOrDefault();
            if (!Uri.IsWellFormedUriString(location, UriKind.Absolute))
            {
                Uri PageUri = new Uri(Page);
                location = PageUri.Scheme + "://" + PageUri.Host + location;
            }
            MessageBox.Show(location);
        }
        catch
        {
            MessageBox.Show("No redirect!");
        }

Result:


答:
As far as I know, you can echo it inside the while like this:

```<code><input type='text' name='product[]'> //don't forget the []
</code>```

then it if you post it you can have an array value,

```<code>$products = $_POST['product'];
print_r($products);//to print array
</code>```

try this code:

```<code><?php
            $MYSQLQuery1=mysql_query("select id,ccode,pdesc,cost from product2")or die(mysql_error());
            $i=1;
            echo '<form action="addvehicle.php" role="form" method="POST" class="form-inline">';
            while($row=mysql_fetch_array($MYSQLQuery1))
              {
                echo "
                     <tr>
                        <td>
                           <img src='img/".$row['ccode'].".jpg' width='150' height='200'/>
                           <br/>
                          ".$row['pdesc']."<br/>"
                           .$row['cost'].
                      "</td>
                        <td>
                          <input type='text' name='product[]'>
                       </td>
                      <td>
                        <input type='hidden' name='ID' value='".$row['id']."'>
                        <input type='submit' name='SUBMITEDITVEHICLE'  value='Edit' class='btn btn-success'>

                     </td>
                    </tr>"; //end of one echo and end of tr
               }//end of while

 echo "</form>"; //end of form
            ?>
</code>```

Title: How to get the value of a loop text field using post method in php

Body:
As far as I know, you can echo it inside the while like this:

<input type='text' name='product[]'> //don't forget the []

then it if you post it you can have an array value,

$products = $_POST['product'];
print_r($products);//to print array

try this code:

<?php
            $MYSQLQuery1=mysql_query("select id,ccode,pdesc,cost from product2")or die(mysql_error());
            $i=1;
            echo '<form action="addvehicle.php" role="form" method="POST" class="form-inline">';
            while($row=mysql_fetch_array($MYSQLQuery1))
              {
                echo "
                     <tr>
                        <td>
                           <img src='img/".$row['ccode'].".jpg' width='150' height='200'/>
                           <br/>
                          ".$row['pdesc']."<br/>"
                           .$row['cost'].
                      "</td>
                        <td>
                          <input type='text' name='product[]'>
                       </td>
                      <td>
                        <input type='hidden' name='ID' value='".$row['id']."'>
                        <input type='submit' name='SUBMITEDITVEHICLE'  value='Edit' class='btn btn-success'>

                     </td>
                    </tr>"; //end of one echo and end of tr
               }//end of while

 echo "</form>"; //end of form
            ?>


问:
Get a specific product by id in WooCommerce
I want to know how I can get access to a product by id in WooCommerce? I'd like to display the product attributes for the specific product on my homepage however I can only find shortcode example of this.

Is their any way to display the product by a certain id like so:

```<code>$product = PRODUCT WITH ID OF 10;
$product->get_attribute('pa_location');
</code>```

Any idea how I can achieve this? Thanks.

答:
You can use  Class WC_Product</p>

```<code>$product = new WC_Product(10);
$product->get_attribute('pa_location');
</code>```

Body:
I want to know how I can get access to a product by id in WooCommerce? I'd like to display the product attributes for the specific product on my homepage however I can only find shortcode example of this.

Is their any way to display the product by a certain id like so:

$product = PRODUCT WITH ID OF 10;
$product->get_attribute('pa_location');

Any idea how I can achieve this? Thanks.

Body:
You can use  Class WC_Product

$product = new WC_Product(10);
$product->get_attribute('pa_location');


问:
Handling quoting and escaped spaces in Bash command arguments
I am writing a bash script that uses other inputs to build a set of complicated arguments for a command. So far, the script runs perfectly with this technique:

```<code>whatIwant="command \"$filename-with-spaces-maybe\" -opt1 \"$some_words\" -opt2 $a_number  -opt3 \"$a_file_reference\" -opt4 \"$several_sentences\" "
eval $whatIwant
</code>```

Although it works, I am wary of using eval because of the risk of a bad filename doing damage. I would like to be able to skip assigning the variable and then eval'ing it, in favor of just putting the command at the beginning of the line and having all the arguments be set by the appropriate variables I have built previously in the script.

When I try this, however, the filenames don't seem to be treated as single variables, and instead are passed to the command as multiple arguments. I have tried several forms of double escaping but haven't managed to find something that is correctly evaluated. It's frustrating because when I echo back my variable into which I build the command, it copies and pastes perfectly to the command line and does what I want.

What is the best practice for doing this in a bash script?

答:
It's really this simple:

```<code>your_command "$filename_with_spaces_maybe" -opt1 "$some_words" -opt2 "$a_number" -opt3 "$a_file_reference" -opt4 "$several_sentences"
</code>```

That is to say:

Put every parameter expansion (where a variable name is replaced with its value) in double quotes -- even if you think the value will only be numeric.

Don't bother with any kind of eval, or assignment, etc.

The only quotes required are syntactic, not literal -- "nested" or "escaped" quotes are literal characters without syntactic meaning, so they have no effect on parsing (without an additional parse step, as generated by eval, which is indeed bad practice when at all avoidable), and just add extra unwanted content to the command actually being run.

For cases when you think you need to store a command in a variable for other reasons (to add arguments only conditionally, or to be able to reuse it), see BashFAQ #50.

If you weren't already convinced that eval is a Bad Idea, you'd want to read BashFAQ #48.

The Wooledge page on Quotes is an excellent resource for this question in general.

Body:
I am writing a bash script that uses other inputs to build a set of complicated arguments for a command. So far, the script runs perfectly with this technique:

whatIwant="command \"$filename-with-spaces-maybe\" -opt1 \"$some_words\" -opt2 $a_number  -opt3 \"$a_file_reference\" -opt4 \"$several_sentences\" "
eval $whatIwant

Although it works, I am wary of using eval because of the risk of a bad filename doing damage. I would like to be able to skip assigning the variable and then eval'ing it, in favor of just putting the command at the beginning of the line and having all the arguments be set by the appropriate variables I have built previously in the script.

When I try this, however, the filenames don't seem to be treated as single variables, and instead are passed to the command as multiple arguments. I have tried several forms of double escaping but haven't managed to find something that is correctly evaluated. It's frustrating because when I echo back my variable into which I build the command, it copies and pastes perfectly to the command line and does what I want.

What is the best practice for doing this in a bash script?

Body:
It's really this simple:

your_command "$filename_with_spaces_maybe" -opt1 "$some_words" -opt2 "$a_number" -opt3 "$a_file_reference" -opt4 "$several_sentences"

That is to say:

Put every parameter expansion (where a variable name is replaced with its value) in double quotes -- even if you think the value will only be numeric.

Don't bother with any kind of eval, or assignment, etc.

The only quotes required are syntactic, not literal -- "nested" or "escaped" quotes are literal characters without syntactic meaning, so they have no effect on parsing (without an additional parse step, as generated by eval, which is indeed bad practice when at all avoidable), and just add extra unwanted content to the command actually being run.

For cases when you think you need to store a command in a variable for other reasons (to add arguments only conditionally, or to be able to reuse it), see BashFAQ #50.

If you weren't already convinced that eval is a Bad Idea, you'd want to read BashFAQ #48.

The Wooledge page on Quotes is an excellent resource for this question in general.


问:
Pushing subfolders of a repository in Git?
I have just started using Git, but I'm a little confused. I've just about gotten my head around pushing the whole local directory to GitHub using this command when in the working directory of my choice:

git push -u origin master

Now, my repository is called /websites. I will have numerous subfolders on my Mac, like /websites/website1, /websites/website2, etc.

What if I want to only push a specific subfolder in my main repository? Is that possible? Also how would I pull back from only a subfolder too?

答:
That's not how git works. The behavior you're describing is how something like rsync or scp works. Git works by commits as opposed to individual files or directories. That being said, when you push with git, it only pushes changed files, as opposed to everything.

A better workflow for you would be to make each individual website its own repository. If you don't want to deal with that, you may find that keeping each website in its own branch helpful.


问:
How to draw makers overlaying axis with Matplotlib?
This is the effect I want.

But I get the figure below, in which the marker is covered by the axis. If the left yaxis is set to invisible, only half the marker is displayed.

答: You have to turn the clipping off, set clip_on = False, refer to official doc.


问:
Searching through table entries by column order based on lookup table
Contrary to what someone has voted, I have researched this, but I am only 9 and am trying to learn how to do a search across columns in a table.  I want to build a simple website for my school that lets the year R children select two sounds from a list of phonics and then it searches for the top three or five words that contain those phonic sounds.  I have built a table that has over 500 words in it (and I will keep adding to the words over time).  I have listed the phonics of every word in the table in columns to the right of each word (there are up to 12 phonic columns so far) and I have a table of all the phonics used in alphabetical order.  The website needs to have a page that has two selection boxes that allows the user to select from my list of phonics (I can do this part).  Then the first phonic searches through my table of words searching for matches in the first column of the phonics of each word.  For all words where there is a match the second phonic is then searched in columns 2 then 3 and so on to see if 3 or more matches can be found.  If there are more than 5 matches the matches are selected at random up to 5 matches and returned on the results screen.  Can anyone help.  I have worked hard on this and my teacher says it is too advanced for her, but I think it should be possible - I can do it in Excel - I filter and for the first phonic I select that phonic in the first phonics column, then for phonic 2 I filter it in the second phonics column (and so on - if there is no match in 2 then I deselect column 2 filter and then filter on column 3).  Can I build a hidden HTML table and do this in HTML or JavaScript or similar?  I am learning JavaScript, but have only learnt a little so far. I am in year 5.</p>

答:
Sorry about the delay in answering - down with the flu.
First off you need to work out some sort of data structure to be held in JavaScript (forget about HTML tables as they will only hinder you).
I would use something like:

```<code>var Phonics = {
   "tiger"    : "| t | ig | g | er |",
   "elephant" : "| e | ......"
};
</code>```

Here you are using a JavaScript Object followed by a string value. To return the possible values you would use var value = Phonic['tiger'] then use string search to apply your 'filters'. Another concern is the conflict, that may arise, when 2 or more objects have similar values.

Hope this puts you on the right track.

Body:
Sorry about the delay in answering - down with the flu.
First off you need to work out some sort of data structure to be held in JavaScript (forget about HTML tables as they will only hinder you).
I would use something like:

var Phonics = {
   "tiger"    : "| t | ig | g | er |",
   "elephant" : "| e | ......"
};

Here you are using a JavaScript Object followed by a string value. To return the possible values you would use var value = Phonic['tiger'] then use string search to apply your 'filters'. Another concern is the conflict, that may arise, when 2 or more objects have similar values.

Hope this puts you on the right track.


问:
Getting byte value for numbers between 0 and 255?
I need to get the byte / 8 bit representation for numbers between 0 and 255. Is there any comfortable way to do this in Java? Seems like most methods are intended to be work with 4 byte long integers? My final goal is to write several 8 bit values to a file.

Thanks for any hint on this!

答:
1 byte = 8 bits = 00000000~11111111 (binary) = 0~255 (unsigned byte)
  = 0x00~0xFF (hex decimal)

C#:

1 byte value is: 0~255

Java:

1 byte value is: -128~127

If you want get 0~255 (unsigned byte) value in java:

byte b = (byte) value;

example: byte b = (byte) 200;

int b = value & 0xFF;

example: int b = 200 & 0xFF;


问:
Scope of variable with out parameter
Example:

I have the following code block:

```<code>if (!int.TryParse("123", out var parsedNumber))
{
    return;
}

Console.WriteLine(parsedNumber);
</code>```

The output in console is: 123

Question:

How is it possible, that the line Console.WriteLine(parsedNumber); knows about parsedNumber?

According to my understanding, parsedNumber should only available in the if-block, shouldn't it?

If I try this:

```<code>foreach (var data in dataList)
{
   data += "something";
}

Console.WriteLine(data);
</code>```

Console.WriteLine(data); can't find data.

I think, that the solution is the out parameter, but I'm not sure. Can someone explain this?

答:
Yes, as you suspect the difference is that "out" modifier.

It is a feature added in C# 7 that allows you to declare the variable at the point where you want to use it as an argument.

That might be convenient as otherwise you'd have to declare parsedNumber before the method call.

You can read more about it here, under "Out variables".

https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/

EDIT

As for why the variable is still in scope outside of the if, that can certainly be confusing, but it was a design choice when implementing this, specifically for the "if" case and precisely so that it could be used in "try" methods.

You can refer to this comment (actually you can take a look at the whole discussion to see the different points of view there were on how to implement this).

https://github.com/dotnet/roslyn/issues/12939#issuecomment-255650834

Title: Scope of variable with out parameter

Body:
Example:

I have the following code block:

if (!int.TryParse("123", out var parsedNumber))
{
    return;
}

Console.WriteLine(parsedNumber);

The output in console is: 123

Question:

How is it possible, that the line Console.WriteLine(parsedNumber); knows about parsedNumber?

According to my understanding, parsedNumber should only available in the if-block, shouldn't it?

If I try this:

foreach (var data in dataList)
{
   data += "something";
}

Console.WriteLine(data);

Console.WriteLine(data); can't find data.

I think, that the solution is the out parameter, but I'm not sure. Can someone explain this?


问:
How to write to multiple files on different disks simultaneously in one thread with DMA?
I use aio to write multiple files on different disk in one thread. When I use buffered writing, IO processing is concurrent. But cpu loads is very high. When I open files with DIRECT flag, IO processing isn't concurrent.

How to write to multiple files on different disks simultaneously in one thread with DMA?

```<code>#include <malloc.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include <inttypes.h>

#include <unistd.h>
#include <fcntl.h>
#include <sys/syscall.h>
#include <linux/aio_abi.h>

using namespace std;

long double timeDiff(timespec start, timespec end) {
const long double s = start.tv_sec + start.tv_nsec * 1.0e-9;
const long double e = end.tv_sec   + end.tv_nsec   * 1.0e-9;
return e - s;
}

// nr: maximum number of requests that can simultaneously reside in the context.
inline int io_setup(unsigned nr, aio_context_t *ctxp) {
return syscall(__NR_io_setup, nr, ctxp);
}

inline int io_destroy(aio_context_t ctx) {
return syscall(__NR_io_destroy, ctx);
}

// Every I/O request that is submitted to
inline int io_submit(aio_context_t ctx, long nr, struct iocb **iocbpp) {
return syscall(__NR_io_submit, ctx, nr, iocbpp);
}

// For every completed I/O request kernel creates an io_event structure.
// minimal number of events one wants to get.
// maximum number of events one wants to get.
inline int io_getevents(aio_context_t ctx, long min_nr, long max_nr,
    struct io_event *events, struct timespec *timeout) {
return syscall(__NR_io_getevents, ctx, min_nr, max_nr, events, timeout);
}

int main(int argc, char *argv[]) {

// prepare data
const unsigned int kAlignment = 4096;
const long data_size = 1600 * 1024 * 12 / 8;
//const long data_size = 2448 * 1344 * 12 / 8;
void * data = memalign(kAlignment, data_size);
memset(data, 0, data_size);
//for (int i = 0; i < data_size; ++i)
//   data[i] = 'A';

// prepare fd
//const int file_num = 3;
const int file_num = 2;
int fd_arr[file_num];
for (int i = 0; i < file_num; ++i) {
    ostringstream filename;
    if (i == 0) {
        //filename << "/data/test";
        filename << "/test";
    } else {
        filename << "/data" << i << "/test";
    }
    //filename << "/data/test" << i;
    int fd = open(filename.str().c_str(), O_WRONLY | O_NONBLOCK | O_CREAT | O_DIRECT | O_APPEND, 0644);
    //int fd = open(filename.str().c_str(), O_WRONLY | O_NONBLOCK | O_CREAT | O_DIRECT, 0644);
    //int fd = open(filename.str().c_str(), O_WRONLY | O_NONBLOCK | O_CREAT, 0644);
    if (fd < 0) {
        perror("open");
        return -1;
    }
    fd_arr[i] = fd;
}

aio_context_t ctx;
struct io_event events[file_num];
int ret;
ctx = 0;

ret = io_setup(1000, &ctx);
if (ret < 0) {
    perror("io_setup");
    return -1;
}

struct iocb cbs[file_num];
for (int i = 0; i < file_num; ++i) {
    memset(&cbs[i], 0, sizeof(cbs[i]));
}
struct iocb * cbs_pointer[file_num];
for (int i = 0; i < file_num; ++i) {
    /* setup I/O control block */
    cbs_pointer[i] = &cbs[i];
    cbs[i].aio_fildes = fd_arr[i];
    cbs[i].aio_lio_opcode = IOCB_CMD_PWRITE; // IOCV_CMD
    cbs[i].aio_nbytes = data_size;
}

timespec tStart, tCurr;
clock_gettime(CLOCK_REALTIME, &tStart);

const int frame_num = 10000;
for (int k = 0; k < frame_num; ++k) {

    for (int i = 0; i < file_num; ++i) {
        /* setup I/O control block */
        cbs[i].aio_buf = (uint64_t)data;
        //cbs[i].aio_offset = k * data_size;
    }

    ret = io_submit(ctx, file_num, cbs_pointer);
    if (ret < 0) {
        perror("io_submit");
        return -1;
    }

    /* get reply */
    ret = io_getevents(ctx, file_num, file_num, events, NULL);
    //printf("events: %d, k: %d\n", ret, k);
}

clock_gettime(CLOCK_REALTIME, &tCurr);
cout << "frame: " << frame_num << " time: " << timeDiff(tStart, tCurr) << endl;

ret = io_destroy(ctx);
if (ret < 0) {
    perror("io_destroy");
    return -1;
}

// close fd
for (int i = 0; i < file_num; ++i) {
    fsync(fd_arr[i]);
    close(fd_arr[i]);
}
return 0;
}
</code>```

答:
Linux can make writes actually async if and only if the physical extents being written are allocated on the disc already. Otherwise it has to take a mutex and do the allocation first, thus everything becomes synchronous.

Note that truncating the file to a new length usually doesn't actually allocate the underlying extents. You need to prewrite the contents first. Thereafter, rewriting the same extents will now be done async and thus become concurrent.

As you might be gathering, async file i/o on Linux is not great, though it keeps on getting better over time. Windows or FreeBSD have far superior implementations. Even OS X is not terrible. Use any of those instead.

Body:
I use aio to write multiple files on different disk in one thread. When I use buffered writing, IO processing is concurrent. But cpu loads is very high. When I open files with DIRECT flag, IO processing isn't concurrent.

How to write to multiple files on different disks simultaneously in one thread with DMA?

#include <malloc.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include <inttypes.h>

#include <unistd.h>
#include <fcntl.h>
#include <sys/syscall.h>
#include <linux/aio_abi.h>

using namespace std;

long double timeDiff(timespec start, timespec end) {
const long double s = start.tv_sec + start.tv_nsec * 1.0e-9;
const long double e = end.tv_sec   + end.tv_nsec   * 1.0e-9;
return e - s;
}

// nr: maximum number of requests that can simultaneously reside in the context.
inline int io_setup(unsigned nr, aio_context_t *ctxp) {
return syscall(__NR_io_setup, nr, ctxp);
}

inline int io_destroy(aio_context_t ctx) {
return syscall(__NR_io_destroy, ctx);
}

// Every I/O request that is submitted to
inline int io_submit(aio_context_t ctx, long nr, struct iocb **iocbpp) {
return syscall(__NR_io_submit, ctx, nr, iocbpp);
}

// For every completed I/O request kernel creates an io_event structure.
// minimal number of events one wants to get.
// maximum number of events one wants to get.
inline int io_getevents(aio_context_t ctx, long min_nr, long max_nr,
    struct io_event *events, struct timespec *timeout) {
return syscall(__NR_io_getevents, ctx, min_nr, max_nr, events, timeout);
}

int main(int argc, char *argv[]) {

// prepare data
const unsigned int kAlignment = 4096;
const long data_size = 1600 * 1024 * 12 / 8;
//const long data_size = 2448 * 1344 * 12 / 8;
void * data = memalign(kAlignment, data_size);
memset(data, 0, data_size);
//for (int i = 0; i < data_size; ++i)
//   data[i] = 'A';

// prepare fd
//const int file_num = 3;
const int file_num = 2;
int fd_arr[file_num];
for (int i = 0; i < file_num; ++i) {
    ostringstream filename;
    if (i == 0) {
        //filename << "/data/test";
        filename << "/test";
    } else {
        filename << "/data" << i << "/test";
    }
    //filename << "/data/test" << i;
    int fd = open(filename.str().c_str(), O_WRONLY | O_NONBLOCK | O_CREAT | O_DIRECT | O_APPEND, 0644);
    //int fd = open(filename.str().c_str(), O_WRONLY | O_NONBLOCK | O_CREAT | O_DIRECT, 0644);
    //int fd = open(filename.str().c_str(), O_WRONLY | O_NONBLOCK | O_CREAT, 0644);
    if (fd < 0) {
        perror("open");
        return -1;
    }
    fd_arr[i] = fd;
}

aio_context_t ctx;
struct io_event events[file_num];
int ret;
ctx = 0;

ret = io_setup(1000, &ctx);
if (ret < 0) {
    perror("io_setup");
    return -1;
}

struct iocb cbs[file_num];
for (int i = 0; i < file_num; ++i) {
    memset(&cbs[i], 0, sizeof(cbs[i]));
}
struct iocb * cbs_pointer[file_num];
for (int i = 0; i < file_num; ++i) {
    /* setup I/O control block */
    cbs_pointer[i] = &cbs[i];
    cbs[i].aio_fildes = fd_arr[i];
    cbs[i].aio_lio_opcode = IOCB_CMD_PWRITE; // IOCV_CMD
    cbs[i].aio_nbytes = data_size;
}

timespec tStart, tCurr;
clock_gettime(CLOCK_REALTIME, &tStart);

const int frame_num = 10000;
for (int k = 0; k < frame_num; ++k) {

    for (int i = 0; i < file_num; ++i) {
        /* setup I/O control block */
        cbs[i].aio_buf = (uint64_t)data;
        //cbs[i].aio_offset = k * data_size;
    }

    ret = io_submit(ctx, file_num, cbs_pointer);
    if (ret < 0) {
        perror("io_submit");
        return -1;
    }

    /* get reply */
    ret = io_getevents(ctx, file_num, file_num, events, NULL);
    //printf("events: %d, k: %d\n", ret, k);
}

clock_gettime(CLOCK_REALTIME, &tCurr);
cout << "frame: " << frame_num << " time: " << timeDiff(tStart, tCurr) << endl;

ret = io_destroy(ctx);
if (ret < 0) {
    perror("io_destroy");
    return -1;
}

// close fd
for (int i = 0; i < file_num; ++i) {
    fsync(fd_arr[i]);
    close(fd_arr[i]);
}
return 0;
}


问:
Coding a Gaussian log-likelihood in R
I am trying to learn R by coding a Gaussian log-likelihood to solve with optim(), but after hours of sweat I am still way off the mark. (This is self-study, not homework.)

I am following the convention in many user-written functions that write a function like loglik <- function(theta, y, x) where theta is a vector of weights beta and variance sigma, y is the outcome and x is the data.

My full code with simulated data is below. Running it, you will see that my function is way off the mark compared to lm(). Can anyone give me an idea as to where I am going wrong?

```<code># random data
set.seed(111)
y = sample(1:100,100)
x1 = sample(1:100,100)*rnorm(1,0)
x2 = sample(x1)*rnorm(1,0)
x3 = sample(x2)*rnorm(1,0)
dat = data.frame(x1,x2,x3)

# define gaussian log-likelihood
logLik <- function(theta, Y, X){
  X           <- as.matrix(X) # convert data to matrix
  k           <- ncol(X) # get the number of columns (independent vars)
  beta        <- theta[1:k] # vector of weights intialized with starting values
  expected_y  <- X %*% beta  # X is dimension (n x k) and beta is dimension (k x 1)
  sigma2      <- theta[k+1] # should be pulled from the last of the starting values vector
  LL          <- sum(dnorm(Y, mean = expected_y, sd = sigma2, log = T)) # sum of the PDF over each observation
  return(-LL)
}
</code>```

Here is the output:

```<code>> optim(logLik, par=starting_values, method="Nelder-Mead", Y=y, X=dat, hessian = T)$par
[1]   0.4832514  -0.2276684  -0.3860800  32.7168490 -38.9030319
> coefficients(lm(y~x1+x2+x3))
(Intercept)          x1          x2          x3
58.17347451 -0.06587320  0.13001865 -0.03624233
</code>```

答:
The basics of your approach are sound but some of the details are wrong. First, it makes sense to construct the data according to a Gaussian linear model; for example

```<code>set.seed(111)
X <- cbind(1, matrix(rnorm(100*3), 100, 3))
y <- X %*% rep(1, 4) + rnorm(100, 0, 2)

starting.values <- c(1, 1, 1, 1, 2) # actual parameters

# define gaussian log-likelihood
logLik <- function(theta, y, X){
  k           <- ncol(X) # get the number of columns (independent vars)
  beta        <- theta[1:k] # vector of weights intialized with starting values
  expected_y  <- X %*% beta  # X is dimension (n x k) and beta is dimension (k x 1)
  sigma      <- theta[k+1] # should be pulled from the last of the starting values vector
  LL          <- sum(dnorm(y, mean = expected_y, sd = sigma, log = TRUE)) # sum of the PDF over each observation
  return(-LL)
}
</code>```

By the way, the *norm() functions are parametrized in terms of the SD, not the variance.

Then

```<code>> optim(logLik, par=starting.values, y=y, X=X, method="BFGS")$par
[1] 1.0471420 1.1411523 0.8167656 0.9840397 1.8910201
Warning message:
In dnorm(y, mean = expected_y, sd = sigma, log = TRUE) : NaNs produced

> summary(lm(y ~ X - 1))

Call:
lm(formula = y ~ X - 1)

Residuals:
    Min      1Q  Median      3Q     Max
-4.5062 -1.3293  0.1371  1.2057  5.8116

Coefficients:
   Estimate Std. Error t value Pr(>|t|)
X1   1.0471     0.1952   5.365 5.61e-07 ***
X2   1.1412     0.1818   6.275 1.00e-08 ***
X3   0.8168     0.1907   4.282 4.39e-05 ***
X4   0.9840     0.2122   4.638 1.11e-05 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 1.93 on 96 degrees of freedom
Multiple R-squared:  0.5333,    Adjusted R-squared:  0.5138
F-statistic: 27.42 on 4 and 96 DF,  p-value: 3.468e-15
</code>```

Notice that method="BFGS" issues a warning but produces the right answer; method="Nelder-Mead" is slightly less accurate. Also notice that the usual estimate of the SD of the errors differs from the ML estimate.

I hope this helps

Title: Coding a Gaussian log-likelihood in R

Body:
I am trying to learn R by coding a Gaussian log-likelihood to solve with optim(), but after hours of sweat I am still way off the mark. (This is self-study, not homework.)

I am following the convention in many user-written functions that write a function like loglik <- function(theta, y, x) where theta is a vector of weights beta and variance sigma, y is the outcome and x is the data.

My full code with simulated data is below. Running it, you will see that my function is way off the mark compared to lm(). Can anyone give me an idea as to where I am going wrong?

# random data
set.seed(111)
y = sample(1:100,100)
x1 = sample(1:100,100)*rnorm(1,0)
x2 = sample(x1)*rnorm(1,0)
x3 = sample(x2)*rnorm(1,0)
dat = data.frame(x1,x2,x3)

# define gaussian log-likelihood
logLik <- function(theta, Y, X){
  X           <- as.matrix(X) # convert data to matrix
  k           <- ncol(X) # get the number of columns (independent vars)
  beta        <- theta[1:k] # vector of weights intialized with starting values
  expected_y  <- X %*% beta  # X is dimension (n x k) and beta is dimension (k x 1)
  sigma2      <- theta[k+1] # should be pulled from the last of the starting values vector
  LL          <- sum(dnorm(Y, mean = expected_y, sd = sigma2, log = T)) # sum of the PDF over each observation
  return(-LL)
}

Here is the output:

> optim(logLik, par=starting_values, method="Nelder-Mead", Y=y, X=dat, hessian = T)$par
[1]   0.4832514  -0.2276684  -0.3860800  32.7168490 -38.9030319
> coefficients(lm(y~x1+x2+x3))
(Intercept)          x1          x2          x3
58.17347451 -0.06587320  0.13001865 -0.03624233

Body:
The basics of your approach are sound but some of the details are wrong. First, it makes sense to construct the data according to a Gaussian linear model; for example

set.seed(111)
X <- cbind(1, matrix(rnorm(100*3), 100, 3))
y <- X %*% rep(1, 4) + rnorm(100, 0, 2)

starting.values <- c(1, 1, 1, 1, 2) # actual parameters

# define gaussian log-likelihood
logLik <- function(theta, y, X){
  k           <- ncol(X) # get the number of columns (independent vars)
  beta        <- theta[1:k] # vector of weights intialized with starting values
  expected_y  <- X %*% beta  # X is dimension (n x k) and beta is dimension (k x 1)
  sigma      <- theta[k+1] # should be pulled from the last of the starting values vector
  LL          <- sum(dnorm(y, mean = expected_y, sd = sigma, log = TRUE)) # sum of the PDF over each observation
  return(-LL)
}

By the way, the *norm() functions are parametrized in terms of the SD, not the variance.

Then

> optim(logLik, par=starting.values, y=y, X=X, method="BFGS")$par
[1] 1.0471420 1.1411523 0.8167656 0.9840397 1.8910201
Warning message:
In dnorm(y, mean = expected_y, sd = sigma, log = TRUE) : NaNs produced

> summary(lm(y ~ X - 1))

Call:
lm(formula = y ~ X - 1)

Residuals:
    Min      1Q  Median      3Q     Max
-4.5062 -1.3293  0.1371  1.2057  5.8116

Coefficients:
   Estimate Std. Error t value Pr(>|t|)
X1   1.0471     0.1952   5.365 5.61e-07 ***
X2   1.1412     0.1818   6.275 1.00e-08 ***
X3   0.8168     0.1907   4.282 4.39e-05 ***
X4   0.9840     0.2122   4.638 1.11e-05 ***
---
Signif. codes:  0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 1.93 on 96 degrees of freedom
Multiple R-squared:  0.5333,    Adjusted R-squared:  0.5138
F-statistic: 27.42 on 4 and 96 DF,  p-value: 3.468e-15

Notice that method="BFGS" issues a warning but produces the right answer; method="Nelder-Mead" is slightly less accurate. Also notice that the usual estimate of the SD of the errors differs from the ML estimate.

I hope this helps


问:
Update unique table SQL
Hello i have this table.

```<code>ADDR      | STATE  |  ID
CRA.20 15 |  REP   |  (null)
CRA.20 15 |  REP   |  (null)
CRA.20 15 |  REP   |   (null)
CRA.20 15 |  PRI   |   RR_88_JK
</code>```

I need transform this table ..

```<code>ADDR      | STATE |   ID
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  PRI  |   RR_88_JK
</code>```

I have this QRY but not function. You have a one idea?.

```<code>UPDATE TABLE_A A
   SET a.ID = b.ID
 WHERE EXISTS
           (SELECT b.ID
              FROM TABLE_A B
             WHERE a.ADDR = B.ADDR  AND b.STATE = 'PRI')
 and  A.STATE = 'REP';
</code>```

Thanks.

答:
The following will do what you want:

```<code>UPDATE TABLE_A A
   SET a.ID = (SELECT MIN(ID)
                 FROM TABLE_A
                 WHERE ID IS NOT NULL AND
                       STATE = 'PRI')
   WHERE ID IS NULL AND
         STATE = 'REP'
</code>```

Best of luck.

Title: Update unique table SQL

Body:
Hello i have this table.

ADDR      | STATE  |  ID
CRA.20 15 |  REP   |  (null)
CRA.20 15 |  REP   |  (null)
CRA.20 15 |  REP   |   (null)
CRA.20 15 |  PRI   |   RR_88_JK

I need transform this table ..

ADDR      | STATE |   ID
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  REP  |   RR_88_JK
CRA.20 15 |  PRI  |   RR_88_JK

I have this QRY but not function. You have a one idea?.

UPDATE TABLE_A A
   SET a.ID = b.ID
 WHERE EXISTS
           (SELECT b.ID
              FROM TABLE_A B
             WHERE a.ADDR = B.ADDR  AND b.STATE = 'PRI')
 and  A.STATE = 'REP';

Thanks.

Body:
The following will do what you want:

UPDATE TABLE_A A
   SET a.ID = (SELECT MIN(ID)
                 FROM TABLE_A
                 WHERE ID IS NOT NULL AND
                       STATE = 'PRI')
   WHERE ID IS NULL AND
         STATE = 'REP'

Best of luck.


问:
Sanitizing GET input with PHP. Is it too late and do I even need to?
I am trying to sanitize the user input in a search through an array. I am wondering if I am sanitizing the input in the right way and if I even need it in a function like this. You'll get it:

Main questions #1: Am I "sanitizing" the input the right way at the right place or is it too late.

The HTML ->

```<code><div >
    <form class="theform">
    Jeg vil gerne have: <input class="theinputbox" type="text" onkeyup="showHint(this.value)">
    </form>
</div>
<div id="theHint"><span id="txtHint"></span></div>
</code>```

The javascript with showHint(); ->

```<code>function showHint(str) {

    if (str.length === 0) {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState === 4 && this.status === 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET", "ToostGetHint.php?q=" + str, true);
        xmlhttp.send();
    }
}
</code>```

The PHP with the array and result ->

```<code>    <?php
    $a[] = "Anna";
    $a[] = "Brittany";
    $a[] = "Cinderella";

    $q = test_input($_REQUEST["q"]);

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

    $hint = "";

    // lookup all hints from array if $q is different from ""
    if ($q !== "") {
        $q = strtolower($q);
        $len=strlen($q);
        foreach($a as $name) {
            if (stristr($q, substr($name, 0, $len))) {
                if ($hint === "") {
                    $hint =  '<p class="txtHint">' . $name . '</p>';
                } else {
                    $hint .= '<p class="txtHint">' . $name . '</p>';
                }
            }
        }
    }

    // Output "no suggestion" if no hint was found or output correct values
    echo $hint === "" ? "no suggestion" : $hint;
    ?>
</code>```

答:
In your specific case, you do not need to sanitize. You never output the input so there is no chance of XSS, and you never use the input in a SQL statement so there is no chance of SQL injection.

If you wanted to sanitize, for this specific case, you should whitelist the characters that you wish to allow. Since you are matching names, you really only need to allow upper and lower case letters. You can implement a white list through the use of a regex.

Body:
I am trying to sanitize the user input in a search through an array. I am wondering if I am sanitizing the input in the right way and if I even need it in a function like this. You'll get it:

Main questions #1: Am I "sanitizing" the input the right way at the right place or is it too late.

The HTML ->

    <form class="theform">
    Jeg vil gerne have: <input class="theinputbox" type="text" onkeyup="showHint(this.value)">
    </form>

The javascript with showHint(); ->

function showHint(str) {

    if (str.length === 0) {
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState === 4 && this.status === 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET", "ToostGetHint.php?q=" + str, true);
        xmlhttp.send();
    }
}

The PHP with the array and result ->

    <?php
    $a[] = "Anna";
    $a[] = "Brittany";
    $a[] = "Cinderella";

    $q = test_input($_REQUEST["q"]);

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

    $hint = "";

    // lookup all hints from array if $q is different from ""
    if ($q !== "") {
        $q = strtolower($q);
        $len=strlen($q);
        foreach($a as $name) {
            if (stristr($q, substr($name, 0, $len))) {
                if ($hint === "") {
                    $hint =  '
' . $name . '
';
                } else {
                    $hint .= '
' . $name . '
';
                }
            }
        }
    }

    // Output "no suggestion" if no hint was found or output correct values
    echo $hint === "" ? "no suggestion" : $hint;
    ?>


问:
Inspect object with JS
Is there any way to inspect an element with JavaScript as it does a FireBug or DevTool? Something like this:

答:
You can simulate that using javascript, with the exception of inspecting pseudo-elements created from pseudo-classes like :after.

All that is showing is the element's tagName, id, classList, and dimensions, which are all available through the element's properties and computed style properties;

```<code>var tag = element.tagName.toLowerCase();
var id = element.id;
var classes = element.classList.toString();
var width = window.getComputedStyle( element ).width;
var height = window.getComputedStyle( element ).height;
</code>```

Demo, not the best but illustrates its use

document.addEventListener("mouseover", function(e) {
  var element = e.target;
  var tag = element.tagName.toLowerCase();
  var id = element.id ? "#"+element.id:"";
  var classes = element.classList.toString().replace(/\s/, ".");
  classes = classes ? "."+classes:"";
  var width = window.getComputedStyle(element).width;
  var height = window.getComputedStyle(element).height;
  element.setAttribute("data-tooltip", `${tag}${id}${classes} ${width} x ${height}`);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  position: relative;
}

*:not(body):not(html):hover:after {
  content: attr(data-tooltip);
  display: block;
  position: absolute;
  top: -20px;
  left: 0px;
  background: black;
  color: white;
  font-size: 10px;
  padding:6px;
  white-space: nowrap;
}</code>```

  This is some text

      Column 1
      Column 2

      Data 1
      Data 2

      Data 3
      Data 4

      Data 6
      Data 5

Item 1

Item 2

Item 3

Item 4

```

Title: Inspect object with JS

Body:
You can simulate that using javascript, with the exception of inspecting pseudo-elements created from pseudo-classes like :after.

All that is showing is the element's tagName, id, classList, and dimensions, which are all available through the element's properties and computed style properties;

var tag = element.tagName.toLowerCase();
var id = element.id;
var classes = element.classList.toString();
var width = window.getComputedStyle( element ).width;
var height = window.getComputedStyle( element ).height;

Demo, not the best but illustrates its use

document.addEventListener("mouseover", function(e) {
  var element = e.target;
  var tag = element.tagName.toLowerCase();
  var id = element.id ? "#"+element.id:"";
  var classes = element.classList.toString().replace(/\s/, ".");
  classes = classes ? "."+classes:"";
  var width = window.getComputedStyle(element).width;
  var height = window.getComputedStyle(element).height;
  element.setAttribute("data-tooltip", `${tag}${id}${classes} ${width} x ${height}`);
});

* {
  position: relative;
}

*:not(body):not(html):hover:after {
  content: attr(data-tooltip);
  display: block;
  position: absolute;
  top: -20px;
  left: 0px;
  background: black;
  color: white;
  font-size: 10px;
  padding:6px;
  white-space: nowrap;
}

<div class="class1 class2">
  This is some text
  <table id="table" class="someclass">
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
    </tr>
    <tr>
      <td id="cell1">Data 1</td>
      <td>Data 2</td>
    </tr>
    <tr>
      <td>Data 3</td>
      <td>Data 4</td>
    </tr>
    <tr>
      <td>Data 6</td>
      <td>Data 5</td>
    </tr>
  </table>
</div>
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
</ul>


问:
How to change href url upon change of a dropdown?
This is my code

```<code><tbody>
<tr>
  <td>$id</td>
  <td>
    <div class='form-group'>
    <div class='col-sm-10'>
      <select id='form-control' class='form-control' onchange='leaveChange()'>
        <option value='$prices'>price</option>
        <option value='$Sale'>Sale</option>
        <option value='$payment'>payment</option>
      </select>";
      ?>
      <script>
      function leaveChange() {
        if (document.getElementById("form-control").value == ""){
          document.getElementById("enableordisable").innerHTML = "Enable";
          document.getElementById("status").innerHTML = "Disabled";
        }
        if(document.getElementById("form-control").value == 1){
          document.getElementById("enableordisable").innerHTML = "Disable";
          document.getElementById("status").innerHTML = "Enabled";
        }
      }
      </script>
  <?php echo "</div></td>
  <td><p id='status'>---</p></td>
  <td> <a id='enableordisable' type='addToTable' class='btn waves- effect waves-light btn-custom' href='function/enabledisable.php?stuff=$id&price=$price'>price</a></td>
</code>```

What I want to do is when a value is selected from the dropdown, I want this href URL in the button

```<code>href='function/enabledisable.php?stuff=$id&price=$price&item'
</code>```

to be updated so that item will point to the option chosen from the dropdown.

How can I do this?

Any help will be appreciated!

note: I cannot use the value inside of the options

答:
```<code>document.getElementById("enableordisable").href = 'function/enabledisable.php?stuff=$id&price=$price&item';
</code>```

this can change the URL of a

Body:
This is my code

  $id

      <select id='form-control' class='form-control' onchange='leaveChange()'>
        <option value='$prices'>price</option>
        <option value='$Sale'>Sale</option>
        <option value='$payment'>payment</option>
      </select>";
      ?>

  <?php echo "

---

   price

What I want to do is when a value is selected from the dropdown, I want this href URL in the button

href='function/enabledisable.php?stuff=$id&price=$price&item'

to be updated so that item will point to the option chosen from the dropdown.

How can I do this?

Any help will be appreciated!

note: I cannot use the value inside of the options

Body:
document.getElementById("enableordisable").href = 'function/enabledisable.php?stuff=$id&price=$price&item';

this can change the URL of a <a>


问:
Can't spawn `gcloud app deploy` from a Node.js script on Windows
I'm building an Electron application (Node.js)  which needs to spawn gcloud app deploy from the application with realtime feedback (stdin/stdout/stderr).

I rapidly switched from child_process to execa because I had some issues on Mac OS X with the child_process buffer which is limited to 200kb (and gcloud app deploy sends some big chunk of string > 200kb which crash the command).

Now, with execa everything seems to work normally on OSX but not on Windows.

The code looks something like this:

```<code>let bin = `gcloud${/^win/.test(process.platform) ? '.cmd' : ''}`

//which: https://github.com/npm/node-which
which(bin, (err, fullpath) => {
  let proc = execa(fullpath, ['app', 'deploy'], {
    cwd: appPath
  })
  proc.stdout.on('data', data => {
    parseDeploy(data.toString())
  })
  proc.stderr.on('data', data => {
    parseDeploy(data.toString())
  })
  proc.then(() => {
    ...
  }).catch(e => {
    ...
  })
})
</code>```

This code works perfectly on Mac OS X while I haven't the same result on Windows

I have tried lots of thing:

execa()

execa.shell()

options shell:true

I tried maxBuffer to 1GB (just in case)

It works with detached:true BUT I can't read stdout / stderr in realtime in the application as it prompts a new cmd.exe without interaction with the Node.js application

Lots of child_process variant.

I have made a GIST to show the responses I get for some tests I have done on Windows with basic Child Process scripts:
https://gist.github.com/thyb/9b53b65c25cd964bbe962d8a9754e31f

I also opened an issue on execa repository: https://github.com/sindresorhus/execa/issues/97

Does someone already got this issue ? I've searched around and found nothing promising except this reddit thread which doesn't solve this issue.

答:
Behind the scene, gcloud.cmd is running a python script. After reading tons of Node.js issue with ChildProcess / Python and Windows, I fell on this thread: https://github.com/nodejs/node-v0.x-archive/issues/8298

There is some known issue about running Python scripts from a Node.js Child Process.
They talk in this comment about an unbuffered option for python. After updating the shell script in gcloud.cmd by adding the -u option, I noticed everything was working as expected

This comment explains how to set this option as an environment variable (to not modify the windows shell script directly): https://docs.python.org/2/using/cmdline.html#envvar-PYTHONUNBUFFERED

So adding PYTHONUNBUFFERED to the environment variable fix this issue !

```<code>execa(fullpath, ['app', 'deploy'], {
  cwd: appPath,
  env: Object.assign({}, process.env, {
    PYTHONUNBUFFERED: true
  })
})
</code>```

Body:
I'm building an Electron application (Node.js)  which needs to spawn gcloud app deploy from the application with realtime feedback (stdin/stdout/stderr).

I rapidly switched from child_process to execa because I had some issues on Mac OS X with the child_process buffer which is limited to 200kb (and gcloud app deploy sends some big chunk of string > 200kb which crash the command).

Now, with execa everything seems to work normally on OSX but not on Windows.

The code looks something like this:

let bin = `gcloud${/^win/.test(process.platform) ? '.cmd' : ''}`

//which: https://github.com/npm/node-which
which(bin, (err, fullpath) => {
  let proc = execa(fullpath, ['app', 'deploy'], {
    cwd: appPath
  })
  proc.stdout.on('data', data => {
    parseDeploy(data.toString())
  })
  proc.stderr.on('data', data => {
    parseDeploy(data.toString())
  })
  proc.then(() => {
    ...
  }).catch(e => {
    ...
  })
})

This code works perfectly on Mac OS X while I haven't the same result on Windows

I have tried lots of thing:

execa()

execa.shell()

options shell:true

I tried maxBuffer to 1GB (just in case)

It works with detached:true BUT I can't read stdout / stderr in realtime in the application as it prompts a new cmd.exe without interaction with the Node.js application

Lots of child_process variant.

I have made a GIST to show the responses I get for some tests I have done on Windows with basic Child Process scripts:
https://gist.github.com/thyb/9b53b65c25cd964bbe962d8a9754e31f

I also opened an issue on execa repository: https://github.com/sindresorhus/execa/issues/97

Does someone already got this issue ? I've searched around and found nothing promising except this reddit thread which doesn't solve this issue.

Body:
Behind the scene, gcloud.cmd is running a python script. After reading tons of Node.js issue with ChildProcess / Python and Windows, I fell on this thread: https://github.com/nodejs/node-v0.x-archive/issues/8298

There is some known issue about running Python scripts from a Node.js Child Process.
They talk in this comment about an unbuffered option for python. After updating the shell script in gcloud.cmd by adding the -u option, I noticed everything was working as expected

This comment explains how to set this option as an environment variable (to not modify the windows shell script directly): https://docs.python.org/2/using/cmdline.html#envvar-PYTHONUNBUFFERED

So adding PYTHONUNBUFFERED to the environment variable fix this issue !

execa(fullpath, ['app', 'deploy'], {
  cwd: appPath,
  env: Object.assign({}, process.env, {
    PYTHONUNBUFFERED: true
  })
})