问:
How can i make a form that saves text in database and uploads a file on server
Ok so I am trying to make a form for a prison visit. I must save in an oracle database the first name, last name, id, inmate code, relationship, purpose of visit, date, hour and the name of the image. Moreover I need to upload the image on the server. I have made 2 forms and 2 php files that process the 2 forms and a javascript button that send them both but the second PHP which works with the picture loads after the first one so the errors from the first one don't appear. I tried to put the code from the second in the first one but still nothing. Can you please tell me how can I do to solve this? Below there is my code. The name of the inputs are in romanian but if you look at the form and the php you will figure it out. Here is the code:

Html file:

```<code><!DOCTYPE html>
<html>
<head>
    <title>CerereVizita</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="cerereV.css">
    <meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0">
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
    <script src="jquery.min.js"></script>
    <script src="jquery-ui.min.js"></script>

    <script>
        $(document).ready(function() {
            $("#datepicker").datepicker();
        });
    </script>
</head>

<body>
<div class="Container">
    <img src="persoana2.png" alt="Avatar" class="avatar">
    <div class="Container2">

        <iframe name="votar" style="display:none;"></iframe>
        <form action="cerereVizita.php" method="POST" id="form1" target="votar">

            <label><b>Nume:</b></label>
            <input type="text" placeholder="Ex: Popescu" name="last name" required>

            <label><b>Prenume:</b></label>
            <input type="text" placeholder="Ex: Marius" name="prenume" required>

            <label><b>CNP:</b></label>
            <input type="text" placeholder="Ex: 1900101125356" name="cnp" required>

            <label><b>Cod Detinut:</b></label>
            <input type="text" placeholder="Ex: 1234" name="cod-detinut" required>

            <label><b>Tipul de relatie:</b></label>
            <input type="text" placeholder="Ex: Sot" name="relatie" required>

            <label><b>Natura vizitei:</b></label>
            <input type="text" placeholder="Ex: Discutie" name="natura-vizitei" required>

            <label><b>Data:</b></label>
            <input id="datepicker" name="data" required>

            <label for="myList"> <b>Ora:</b></label>
            <div>
                <select name="ora" id = "myList" form="form1" required>
                    <option value = "12:00">12:00</option>
                    <option value = "13:00">13:00</option>
                    <option value = "14:00">14:00</option>
                    <option value = "15:00">15:00</option>
                </select>
            </div>

        </form>

        <form action="testU.php" method="post" enctype="multipart/form-data" target="votar">

            <label> <b>Poza:</b>
                <input type="file" name="fileToUpload" id="fileToUpload">
            </label>

        </form>

        <button onclick="submitForms()">Submit!</button>
    </div>
    <div class="item">
        <h3> Va rugam completati toate spatiile si verificati de 2 ori inainte sa trimiteti! </h3>
    </div>

    <div class="Container3">
        <a href="faq.html">FAQ</a>
        <a href="contact.html">Contact</a>
    </div>
    <img class="Poza" src="asd.jpg" alt="Prison image">
</div>
</body>

</html>

<script language="javascript">
    function submitForms(){
        $('form').submit();
    }
</script>
</code>```

Php for form1:

```<code><?php
//Oracle DB user name
$username = 'TW';

// Oracle DB user password
$password = 'TW';

// Oracle DB connection string
$connection_string = 'localhost/xe';

//Connect to an Oracle database
$connection = oci_connect(
    $username,
    $password,
    $connection_string
);

$var1 = $_POST['nume'];
$var2 = $_POST['prenume'];
$var3 = $_POST['cnp'];
$var4 = $_POST['cod-detinut'];
$var5 = $_POST['relatie'];
$var6 = $_POST['natura-vizitei'];
$var7 = $_POST['data'];
$var8 = $_POST['ora'];

if(is_numeric($var4)==true) {
//stid4
    $stid4 = oci_parse($connection, 'SELECT COUNT(ID) as "count" FROM DETINUTI WHERE ID=:codD');

    if (!$stid4) {
        $e = oci_error($connection);
        trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
    }

    oci_bind_by_name($stid4, ':codD', $var4);
    $r4 = oci_execute($stid4);
    if (!$r4) {
        $e = oci_error($stid4);
        trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
    }
    $row4 = oci_fetch_array($stid4, OCI_ASSOC + OCI_RETURN_LOBS);
    $count2 = $row4['count'];

    if (is_numeric($var3) == true AND strlen($var3) == 13) {

//stid2
        $stid2 = oci_parse($connection, 'SELECT COUNT(*) AS "count" FROM CEREREVIZITE WHERE CNP = :cnp AND DATA_VIZITA = to_date(:data_vizita,\'MM/DD/YYYY\')');

        if (!$stid2) {
            $e = oci_error($connection);
            trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
        }
        oci_bind_by_name($stid2, ':cnp', $var3);
        oci_bind_by_name($stid2, ':data_vizita', $var7);

        $r2 = oci_execute($stid2);
        if (!$r2) {
            $e = oci_error($stid2);
            trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
        }
        $row2 = oci_fetch_array($stid2, OCI_ASSOC + OCI_RETURN_LOBS);
        $count = $row2['count'];

//stid3

        $stid3 = oci_parse($connection, 'SELECT MAX(ID) AS "ID" FROM CEREREVIZITE');

        if (!$stid3) {
            $e = oci_error($connection);
            trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
        }
        $r3 = oci_execute($stid3);
        if (!$r3) {
            $e = oci_error($stid3);
            trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
        }
        $row3 = oci_fetch_array($stid3, OCI_ASSOC + OCI_RETURN_LOBS);
        $max = $row3['ID'];

        if ($count2 == 0) {
            $message = "Detinutul cu id-ul " . $var4 . " nu exista.";
            echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
        } else {
            if ($count == 0) {

                //stid1

                $stid1 = oci_parse($connection, 'INSERT INTO CEREREVIZITE VALUES (:id+1,:nume,:prenume,:cnp,:cod_detinut,:relatie,:natura,to_date(:data_vizita,\'MM/DD/YYYY\'),:ora,\'poza\')');

                if (!$stid1) {
                    $e = oci_error($connection);
                    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
                }

                oci_bind_by_name($stid1, ':id', $max);
                oci_bind_by_name($stid1, ':nume', $var1);
                oci_bind_by_name($stid1, ':prenume', $var2);
                oci_bind_by_name($stid1, ':cnp', $var3);
                oci_bind_by_name($stid1, ':cod_detinut', $var4);
                oci_bind_by_name($stid1, ':relatie', $var5);
                oci_bind_by_name($stid1, ':natura', $var6);
                oci_bind_by_name($stid1, ':data_vizita', $var7);
                oci_bind_by_name($stid1, ':ora', $var8);

                $r1 = oci_execute($stid1);
                if (!$r1) {
                    $e = oci_error($stid1);
                    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
                }

                $message = "Datele au fost inregistrate cu succes. ";
                echo "<script type='text/javascript'>alert('$message'); window.location.href = \"guest.html\";</script>";
            } else {

                $message = "Aveti deja o vizita inregistrata in data de " . $var7;
                echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
            }
        }
    } else {
        $message = "CNP invalid.";
        echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
    }
}
else{
    $message = "Cod invalid! ";
    echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
}
oci_close($connection);
?>
</code>```

Php for form2 (aka picture upload form):

```<code><?php
$target_dir = "C:/Apache24/htdocs/dwnds/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        $message = "File is an image - " . $check["mime"] . ".";
        echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
        $uploadOk = 1;
    } else {
        $message = "File is not an image.";
        echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    $message = "Sorry, file already exists.";
    echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    $message = "Sorry, your file is too large.";
    echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
    $message = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    $message = "Sorry, your file was not uploaded.";
    echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $message = "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        echo "<script type='text/javascript'>alert('$message'); window.location.href = \"guest.html\";</script>";
    } else {
        $message = "Sorry, there was an error uploading your file.";
        echo "<script type='text/javascript'>alert('$message'); window.location.href = \"cerereV.html\";</script>";
    }
}
?>
</code>```

答:
There is no need to use two html forms and two php files. You can combine two forms. Just add enctype="multipart/form-data" when you are transmitting files using html form as you have done in the 2nd form. It will look like this -

<form action="cerereVizita.php" method="POST" id="form1" target="votar" enctype="multipart/form-data">

  Nume:
  <input type="text" placeholder="Ex: Popescu" name="last name" required>

  Prenume:
  <input type="text" placeholder="Ex: Marius" name="prenume" required>

  CNP:
  <input type="text" placeholder="Ex: 1900101125356" name="cnp" required>

  Cod Detinut:
  <input type="text" placeholder="Ex: 1234" name="cod-detinut" required>

  Tipul de relatie:
  <input type="text" placeholder="Ex: Sot" name="relatie" required>

  Natura vizitei:
  <input type="text" placeholder="Ex: Discutie" name="natura-vizitei" required>

  Data:
  <input id="datepicker" name="data" required>

   Ora:

    <select name="ora" id="myList" form="form1" required>
        <option value = "12:00">12:00</option>
        <option value = "13:00">13:00</option>
        <option value = "14:00">14:00</option>
        <option value = "15:00">15:00</option>
    </select>

   Poza:
  <input type="file" name="fileToUpload" id="fileToUpload">
</form>
```

After this combine your PHP logic in one file.

Body:
Ok so I am trying to make a form for a prison visit. I must save in an oracle database the first name, last name, id, inmate code, relationship, purpose of visit, date, hour and the name of the image. Moreover I need to upload the image on the server. I have made 2 forms and 2 php files that process the 2 forms and a javascript button that send them both but the second PHP which works with the picture loads after the first one so the errors from the first one don't appear. I tried to put the code from the second in the first one but still nothing. Can you please tell me how can I do to solve this? Below there is my code. The name of the inputs are in romanian but if you look at the form and the php you will figure it out. Here is the code:

Html file:

<!DOCTYPE html>

    <title>CerereVizita</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="cerereV.css">
    <meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0">
    <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">

        <form action="cerereVizita.php" method="POST" id="form1" target="votar">

            Nume:
            <input type="text" placeholder="Ex: Popescu" name="last name" required>

            Prenume:
            <input type="text" placeholder="Ex: Marius" name="prenume" required>

            CNP:
            <input type="text" placeholder="Ex: 1900101125356" name="cnp" required>

            Cod Detinut:
            <input type="text" placeholder="Ex: 1234" name="cod-detinut" required>

            Tipul de relatie:
            <input type="text" placeholder="Ex: Sot" name="relatie" required>

            Natura vizitei:
            <input type="text" placeholder="Ex: Discutie" name="natura-vizitei" required>

            Data:
            <input id="datepicker" name="data" required>

             Ora:

                <select name="ora" id = "myList" form="form1" required>
                    <option value = "12:00">12:00</option>
                    <option value = "13:00">13:00</option>
                    <option value = "14:00">14:00</option>
                    <option value = "15:00">15:00</option>
                </select>

        </form>

        <form action="testU.php" method="post" enctype="multipart/form-data" target="votar">

             Poza:
                <input type="file" name="fileToUpload" id="fileToUpload">

        </form>

        <button onclick="submitForms()">Submit!</button>

 Va rugam completati toate spatiile si verificati de 2 ori inainte sa trimiteti!

        FAQ
        Contact

Php for form1:

<?php
//Oracle DB user name
$username = 'TW';

// Oracle DB user password
$password = 'TW';

// Oracle DB connection string
$connection_string = 'localhost/xe';

//Connect to an Oracle database
$connection = oci_connect(
    $username,
    $password,
    $connection_string
);

$var1 = $_POST['nume'];
$var2 = $_POST['prenume'];
$var3 = $_POST['cnp'];
$var4 = $_POST['cod-detinut'];
$var5 = $_POST['relatie'];
$var6 = $_POST['natura-vizitei'];
$var7 = $_POST['data'];
$var8 = $_POST['ora'];

if(is_numeric($var4)==true) {
//stid4
    $stid4 = oci_parse($connection, 'SELECT COUNT(ID) as "count" FROM DETINUTI WHERE ID=:codD');

    if (!$stid4) {
        $e = oci_error($connection);
        trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
    }

    oci_bind_by_name($stid4, ':codD', $var4);
    $r4 = oci_execute($stid4);
    if (!$r4) {
        $e = oci_error($stid4);
        trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
    }
    $row4 = oci_fetch_array($stid4, OCI_ASSOC + OCI_RETURN_LOBS);
    $count2 = $row4['count'];

    if (is_numeric($var3) == true AND strlen($var3) == 13) {

//stid2
        $stid2 = oci_parse($connection, 'SELECT COUNT(*) AS "count" FROM CEREREVIZITE WHERE CNP = :cnp AND DATA_VIZITA = to_date(:data_vizita,\'MM/DD/YYYY\')');

        if (!$stid2) {
            $e = oci_error($connection);
            trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
        }
        oci_bind_by_name($stid2, ':cnp', $var3);
        oci_bind_by_name($stid2, ':data_vizita', $var7);

        $r2 = oci_execute($stid2);
        if (!$r2) {
            $e = oci_error($stid2);
            trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
        }
        $row2 = oci_fetch_array($stid2, OCI_ASSOC + OCI_RETURN_LOBS);
        $count = $row2['count'];

//stid3

        $stid3 = oci_parse($connection, 'SELECT MAX(ID) AS "ID" FROM CEREREVIZITE');

        if (!$stid3) {
            $e = oci_error($connection);
            trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
        }
        $r3 = oci_execute($stid3);
        if (!$r3) {
            $e = oci_error($stid3);
            trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
        }
        $row3 = oci_fetch_array($stid3, OCI_ASSOC + OCI_RETURN_LOBS);
        $max = $row3['ID'];

        if ($count2 == 0) {
            $message = "Detinutul cu id-ul " . $var4 . " nu exista.";
            echo "";
        } else {
            if ($count == 0) {

                //stid1

                $stid1 = oci_parse($connection, 'INSERT INTO CEREREVIZITE VALUES (:id+1,:nume,:prenume,:cnp,:cod_detinut,:relatie,:natura,to_date(:data_vizita,\'MM/DD/YYYY\'),:ora,\'poza\')');

                if (!$stid1) {
                    $e = oci_error($connection);
                    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
                }

                oci_bind_by_name($stid1, ':id', $max);
                oci_bind_by_name($stid1, ':nume', $var1);
                oci_bind_by_name($stid1, ':prenume', $var2);
                oci_bind_by_name($stid1, ':cnp', $var3);
                oci_bind_by_name($stid1, ':cod_detinut', $var4);
                oci_bind_by_name($stid1, ':relatie', $var5);
                oci_bind_by_name($stid1, ':natura', $var6);
                oci_bind_by_name($stid1, ':data_vizita', $var7);
                oci_bind_by_name($stid1, ':ora', $var8);

                $r1 = oci_execute($stid1);
                if (!$r1) {
                    $e = oci_error($stid1);
                    trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
                }

                $message = "Datele au fost inregistrate cu succes. ";
                echo "";
            } else {

                $message = "Aveti deja o vizita inregistrata in data de " . $var7;
                echo "";
            }
        }
    } else {
        $message = "CNP invalid.";
        echo "";
    }
}
else{
    $message = "Cod invalid! ";
    echo "";
}
oci_close($connection);
?>

Php for form2 (aka picture upload form):

<?php
$target_dir = "C:/Apache24/htdocs/dwnds/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        $message = "File is an image - " . $check["mime"] . ".";
        echo "";
        $uploadOk = 1;
    } else {
        $message = "File is not an image.";
        echo "";
        $uploadOk = 0;
    }
}
// Check if file already exists
if (file_exists($target_file)) {
    $message = "Sorry, file already exists.";
    echo "";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    $message = "Sorry, your file is too large.";
    echo "";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
    $message = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    echo "";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    $message = "Sorry, your file was not uploaded.";
    echo "";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        $message = "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
        echo "";
    } else {
        $message = "Sorry, there was an error uploading your file.";
        echo "";
    }
}
?>

Body:
There is no need to use two html forms and two php files. You can combine two forms. Just add enctype="multipart/form-data" when you are transmitting files using html form as you have done in the 2nd form. It will look like this -

<form action="cerereVizita.php" method="POST" id="form1" target="votar" enctype="multipart/form-data">

  <label><b>Nume:</b></label>
  <input type="text" placeholder="Ex: Popescu" name="last name" required>

  <label><b>Prenume:</b></label>
  <input type="text" placeholder="Ex: Marius" name="prenume" required>

  <label><b>CNP:</b></label>
  <input type="text" placeholder="Ex: 1900101125356" name="cnp" required>

  <label><b>Cod Detinut:</b></label>
  <input type="text" placeholder="Ex: 1234" name="cod-detinut" required>

  <label><b>Tipul de relatie:</b></label>
  <input type="text" placeholder="Ex: Sot" name="relatie" required>

  <label><b>Natura vizitei:</b></label>
  <input type="text" placeholder="Ex: Discutie" name="natura-vizitei" required>

  <label><b>Data:</b></label>
  <input id="datepicker" name="data" required>

  <label for="myList"> <b>Ora:</b></label>
  <div>
    <select name="ora" id="myList" form="form1" required>
        <option value = "12:00">12:00</option>
        <option value = "13:00">13:00</option>
        <option value = "14:00">14:00</option>
        <option value = "15:00">15:00</option>
    </select>
  </div>

  <label> <b>Poza:</b></label>
  <input type="file" name="fileToUpload" id="fileToUpload">
</form>

After this combine your PHP logic in one file.


来源: stackexchange

问:
Unable to prevent automatic horizontal scrolling on TreeView in base class when selecting an item in Silverlight
I'm trying to prevent the automatic horizontal scrolling on a tree view item when you select it in Silverlight.  And I'm trying to do it in a base class.

So far I haven't been able to manage it.  I have tried the following code, but it executes and then the thing just scrolls anyway when I select it.

```<code>using System.Windows;
using System.Windows.Controls;

namespace MyControls
{
    public class CustomTreeView : TreeView
    {
        private ScrollViewer _scrollViewer;

        protected override void OnSelectedItemChanged(RoutedPropertyChangedEventArgs<object> e)
        {
            base.OnSelectedItemChanged(e);
            _scrollViewer.ScrollToHorizontalOffset(0);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            _scrollViewer = GetTemplateChild("ScrollViewer") as ScrollViewer;
        }
    }
}
</code>```

I don't actually want to disable scrolling entirely -- if an item flies off the edge of the tree view I want the user to be able to scroll to it.  What I am trying to do is to keep the tree where it is when I select a child node that may be longer than the width of the screen.

I've tried RequestBringIntoView on a WrapPanel, but that's WPF-only, it seems.  I've also tried doing this on UpdateLayout as well as SelectedItemChanged.  All to no avail.  I can't seem to find a general solution that I can have another class inherit from and use.

Anyone have any ideas?

Thanks!

-Ari

EDIT: The bounty states that I need to be able to do it in XAML.  That was a typo on my part.  I'll take code solutions as well.  Thanks!

答:
A late answer for those not satisfied with solutions above:

As explained on this MSDN dev blog, the tree view is scrolled because TreeViewItem calls its BringIntoView method on selection.
The event may be canceled by overriding its handler and marking it as Handled, as follows:

XAML:

```<code><TreeView>
  <TreeView.Resources>
    <Style TargetType="TreeViewItem">
      <EventSetter Event="RequestBringIntoView" Handler="TreeViewItem_RequestBringIntoView"/>
    </Style>
  </TreeView.Resources>
</TreeView>
</code>```

the handler:

```<code>void TreeViewItem_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) {
  e.Handled = true;
}
</code>```

The approach has drawback yet: direct calls to tvi.BringIntoView() stop working either, but it may be bypassed by setting a boolean flag before calling BringIntoView, checking it in the handler and resetting it after the call.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to prevent the automatic horizontal scrolling on a tree view item when you select it in Silverlight.  And I'm trying to do it in a base class.

So far I haven't been able to manage it.  I have tried the following code, but it executes and then the thing just scrolls anyway when I select it.

using System.Windows;
using System.Windows.Controls;

namespace MyControls
{
    public class CustomTreeView : TreeView
    {
        private ScrollViewer _scrollViewer;

        protected override void OnSelectedItemChanged(RoutedPropertyChangedEventArgs<object> e)
        {
            base.OnSelectedItemChanged(e);
            _scrollViewer.ScrollToHorizontalOffset(0);
        }

        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            _scrollViewer = GetTemplateChild("ScrollViewer") as ScrollViewer;
        }
    }
}

I don't actually want to disable scrolling entirely -- if an item flies off the edge of the tree view I want the user to be able to scroll to it.  What I am trying to do is to keep the tree where it is when I select a child node that may be longer than the width of the screen.

I've tried RequestBringIntoView on a WrapPanel, but that's WPF-only, it seems.  I've also tried doing this on UpdateLayout as well as SelectedItemChanged.  All to no avail.  I can't seem to find a general solution that I can have another class inherit from and use.

Anyone have any ideas?

Thanks!

-Ari

EDIT: The bounty states that I need to be able to do it in XAML.  That was a typo on my part.  I'll take code solutions as well.  Thanks!

Body:
A late answer for those not satisfied with solutions above:

As explained on this MSDN dev blog, the tree view is scrolled because TreeViewItem calls its BringIntoView method on selection.
The event may be canceled by overriding its handler and marking it as Handled, as follows:

XAML:

<TreeView>
  <TreeView.Resources>
    <Style TargetType="TreeViewItem">
      <EventSetter Event="RequestBringIntoView" Handler="TreeViewItem_RequestBringIntoView"/>
    </Style>
  </TreeView.Resources>
</TreeView>

the handler:

void TreeViewItem_RequestBringIntoView(object sender, RequestBringIntoViewEventArgs e) {
  e.Handled = true;
}

The approach has drawback yet: direct calls to tvi.BringIntoView() stop working either, but it may be bypassed by setting a boolean flag before calling BringIntoView, checking it in the handler and resetting it after the call.


问:
How to have an Ionic >=2 scrollable ion-list under fixed search bar
I have an Ionic >=2 application where I would like to have 2 or 3 fixed rows at the top of the page, and then have the rest of the page as a scrollable list (and later I want it to be virtual, but just want to get the simple list working forst).

As a simplified example, I have the following plunk. The markup repeated here is..

```<code>    <ion-header>
          <ion-navbar>
            <ion-title>{{ appName }}</ion-title>
           </ion-navbar>
    </ion-header>

    <ion-content scroll=false>
       <ion-grid>
         <!-- Row 1 fixed at top -->
         <ion-row>
           <ion-col>
             <ion-searchbar></ion-searchbar>
           </ion-col>
           <!-- Other cols -->
         </ion-row>

        <!-- Row 2 Scrollable list -->
        <ion-row>
          <ion-col>
            <ion-list>
              <ion-item *ngFor="let item of data">
                <div>{{item}}</div>
              </ion-item>
            </ion-list >
          </ion-col>
       </ion-row>

       </ion-grid>
    </ion-content>
</code>```

The problem is the search bar also scrolls with the list, whereas I would like this to always remain visible at the top of the page.

Does anyone know why I have the search bar also scrolling when this is in a completely separate row to the ion-list? Should I be using an ion-grid in this way?

Thanks in advance for any help!

答:
This is how I managed to have a list at the bottom of the page scroll without scrolling the whole page:

HTML

```<code><ion-content>
    <div class="table">
        <div class="table-row">
            <ion-searchbar></ion-searchbar>
        </div>
        <div class="table-row last-row">
            <div class="table-cell cell-content-outer-wrapper">
                <div class="cell-content-inner-wrapper">
                    <div class="cell-content">
                        <ion-list>
                            <ion-item *ngFor="let item of data">
                                <div>{{item}}</div>
                            </ion-item>
                        </ion-list>
                    </div>
                </div>
            </div>
        </div>
    </div>
</ion-content>
</code>```

CSS

```<code>.table {
    display: table;
    width: 100%;
    height: 100%;
}
.table-row {
   display: table-row;
}
.table-cell {
   display: table-cell;
}
.last-row {
   height: 100%;
}
.cell-content-outer-wrapper {
   height: 100%;
}
.cell-content-inner-wrapper {
   height: 100%;
   position: relative;
   overflow: auto;
}
.cell-content {
   position: absolute;
   top: 0;
   bottom: 0;
   left: 0;
   right: 0;
}
</code>```

Makes use of lots of divs but it worked for me in ionic 2 and in onsen-ui as well when I was facing the same problem.

Body:
I have an Ionic >=2 application where I would like to have 2 or 3 fixed rows at the top of the page, and then have the rest of the page as a scrollable list (and later I want it to be virtual, but just want to get the simple list working forst).

As a simplified example, I have the following plunk. The markup repeated here is..

    <ion-header>
          <ion-navbar>
            <ion-title>{{ appName }}</ion-title>
           </ion-navbar>
    </ion-header>

    <ion-content scroll=false>
       <ion-grid>

         <ion-row>
           <ion-col>
             <ion-searchbar></ion-searchbar>
           </ion-col>

         </ion-row>

        <ion-row>
          <ion-col>
            <ion-list>
              <ion-item *ngFor="let item of data">

{{item}}

              </ion-item>
            </ion-list >
          </ion-col>
       </ion-row>

       </ion-grid>
    </ion-content>

The problem is the search bar also scrolls with the list, whereas I would like this to always remain visible at the top of the page.

Does anyone know why I have the search bar also scrolling when this is in a completely separate row to the ion-list? Should I be using an ion-grid in this way?

Thanks in advance for any help!

Body:
This is how I managed to have a list at the bottom of the page scroll without scrolling the whole page:

HTML

<ion-content>
    <div class="table">
        <div class="table-row">
            <ion-searchbar></ion-searchbar>
        </div>
        <div class="table-row last-row">
            <div class="table-cell cell-content-outer-wrapper">
                <div class="cell-content-inner-wrapper">
                    <div class="cell-content">
                        <ion-list>
                            <ion-item *ngFor="let item of data">
                                <div>{{item}}</div>
                            </ion-item>
                        </ion-list>
                    </div>
                </div>
            </div>
        </div>
    </div>
</ion-content>

CSS

.table {
    display: table;
    width: 100%;
    height: 100%;
}
.table-row {
   display: table-row;
}
.table-cell {
   display: table-cell;
}
.last-row {
   height: 100%;
}
.cell-content-outer-wrapper {
   height: 100%;
}
.cell-content-inner-wrapper {
   height: 100%;
   position: relative;
   overflow: auto;
}
.cell-content {
   position: absolute;
   top: 0;
   bottom: 0;
   left: 0;
   right: 0;
}

Makes use of lots of divs but it worked for me in ionic 2 and in onsen-ui as well when I was facing the same problem.


问:
Making a variable constant without using a final keyword
I came across this question in interview, that how to make a variable constant without final keyword in java</p>

答:
You can force such a variable to be effectively final. For example, use it in a stream.</p>

```<code>int a = 1;
Stream.of(1, 2, 3, 4, 5).map(e -> e + a).forEach(System.out::println);

a = 12; // this line leads to a compile error
</code>```

Body:
You can force such a variable to be effectively final. For example, use it in a stream.

int a = 1;
Stream.of(1, 2, 3, 4, 5).map(e -> e + a).forEach(System.out::println);

a = 12; // this line leads to a compile error


问:
Neo4j Cypher RegExp ignore case query doesn't work on non-Latin characters
Sometimes I have to search nodes by RegExp ignore case query and it doesn't work on non-Latin characters.

For example I have a node.name property = ЖК Львівський маєток

If I search by

```<code>name =~ (?i).*ЖК Львівський маєток.*
</code>```

everything is working fine

but in case of

```<code>name =~ (?i).*жк Львівський маєток.*
</code>```

it doesn't search the node.

By the way - on Latin characters everything is working fine.

What am I doing wrong and how to fix it ?

答:
You need add an 'u' in your regex to transform it in a case-insensitive unicode regex. Like this:</p>

```<code>name =~ (?ui).*ЖК Львівський маєток.*
</code>```

Body:
Sometimes I have to search nodes by RegExp ignore case query and it doesn't work on non-Latin characters.

For example I have a node.name property = ЖК Львівський маєток

If I search by

name =~ (?i).*ЖК Львівський маєток.*

everything is working fine

but in case of

name =~ (?i).*жк Львівський маєток.*

it doesn't search the node.

By the way - on Latin characters everything is working fine.

What am I doing wrong and how to fix it ?

Body:
You need add an 'u' in your regex to transform it in a case-insensitive unicode regex. Like this:

name =~ (?ui).*ЖК Львівський маєток.*


问:
Mock bottle.request object in python
I am using bottle framework. I have code like

```<code>from bottle import request

def abc():
    x = request.get_header('x')
    ...
    ...
    data = request.json()
    ...
    ...
</code>```

I am writing UTs for this function, I want to mock get_header and json of bottle.request, and return my mock data from that.

I tried.

```<code>from mock import patch

@patch('bottle.request.headers', return_value={'x': 'x'})
@patch('bottle.request.json', return_value=...)
def test_abc(self, _, __):
    ...
    ...
</code>```

But it gives error for request.headers is read-only. I also have to mock request.json.

Thanks for help in advance :).

答:
Check the source code of bottle, headers and json are like:

```<code>    @DictProperty('environ', 'bottle.request.headers', read_only=True)
    def headers(self):
        ''' A :class:`WSGIHeaderDict` that provides case-insensitive access to
            HTTP request headers. '''
        return WSGIHeaderDict(self.environ)
</code>```

So in my pytest cases, I patched request.environ like below:

```<code>def test_xxx(monkeypatch):
    monkeypatch.setitem(request.environ, 'bottle.request.json', {'name': 'xxx', 'version': '0.1'})
    add_xxx()
    assert
</code>```

Title: Mock bottle.request object in python

Body:
I am using bottle framework. I have code like

from bottle import request

def abc():
    x = request.get_header('x')
    ...
    ...
    data = request.json()
    ...
    ...

I am writing UTs for this function, I want to mock get_header and json of bottle.request, and return my mock data from that.

I tried.

from mock import patch

@patch('bottle.request.headers', return_value={'x': 'x'})
@patch('bottle.request.json', return_value=...)
def test_abc(self, _, __):
    ...
    ...

But it gives error for request.headers is read-only. I also have to mock request.json.

Thanks for help in advance :).

Body:
Check the source code of bottle, headers and json are like:

    @DictProperty('environ', 'bottle.request.headers', read_only=True)
    def headers(self):
        ''' A :class:`WSGIHeaderDict` that provides case-insensitive access to
            HTTP request headers. '''
        return WSGIHeaderDict(self.environ)

So in my pytest cases, I patched request.environ like below:

def test_xxx(monkeypatch):
    monkeypatch.setitem(request.environ, 'bottle.request.json', {'name': 'xxx', 'version': '0.1'})
    add_xxx()
    assert


问:
"OutputPath property is not set" error occurs only when calling MSBuild in CCNET
I've made an MSBuild project that simply does an msbuild task with our solution file as parameter. I've defined a BeforeBuild target where I set some properties, and a Build target that executes the msbuild task.

I've confirmed that no errors occured when building the msbuild script in the command line console. However, when I use it in the msbuild task in my CCNET project, I keep getting the following error:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets
  (483,9): error: The OutputPath
  property is not set for project
  'MyProject.msbuild'.  Please check to
  make sure that you have specified a
  valid combination of Configuration and
  Platform for this project.
  Configuration='Debug'
  Platform='AnyCPU'.  You may be seeing
  this message because you are trying to
  build a project without a solution
  file, and have specified a non-default
  Configuration or Platform that doesn't
  exist for this project.

I checked the build log and it seems that the error occurs during _CheckForInvalidConfigurationAndPlatform. It wasn't even able to continue to my Build task! Since the script is only intended to build the solution under Debug/Release and AnyCPU as platform, I tried to add the following lines to my msbuild project:

```<code><PropertyGroup Condition=" '$(Configuration)|$(Platform)' ==  'Debug|AnyCPU' ">
  <OutputPath>.\bin\Debug\</OutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' ==  'Release|AnyCPU' ">
  <OutputPath>.\bin\Release\</OutputPath>
</PropertyGroup>
</code>```

I could still build the project without errors in the command line, but CCNET is returning the same error mentioned above.

I don't understand why CCNET keeps getting the error, and I don't know what else to try.

Please help.

答:
I found I had a similar situation (but using TeamCity as my CI environment).  In my particular case, the project was a Command Line application.  To solve it, I had to manually edit my project file.

Find these lines:

```<code><Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
</code>```

Change the second line to:

```<code><Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
</code>```

The find the other platform-specific lines in the project file and change them.  Example:

```<code>  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">
</code>```

becomes:

```<code>  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
</code>```

My suspicion is our build servers are 64-bit and the Console Application project type in Studio won't let you make the project fit an AnyCPU platform...

After these changes, TeamCity had no problem with my build script.

ContentLicense: CC BY-SA 2.5

Body:
I've made an MSBuild project that simply does an msbuild task with our solution file as parameter. I've defined a BeforeBuild target where I set some properties, and a Build target that executes the msbuild task.

I've confirmed that no errors occured when building the msbuild script in the command line console. However, when I use it in the msbuild task in my CCNET project, I keep getting the following error:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets
  (483,9): error: The OutputPath
  property is not set for project
  'MyProject.msbuild'.  Please check to
  make sure that you have specified a
  valid combination of Configuration and
  Platform for this project.
  Configuration='Debug'
  Platform='AnyCPU'.  You may be seeing
  this message because you are trying to
  build a project without a solution
  file, and have specified a non-default
  Configuration or Platform that doesn't
  exist for this project.

I checked the build log and it seems that the error occurs during _CheckForInvalidConfigurationAndPlatform. It wasn't even able to continue to my Build task! Since the script is only intended to build the solution under Debug/Release and AnyCPU as platform, I tried to add the following lines to my msbuild project:

<PropertyGroup Condition=" '$(Configuration)|$(Platform)' ==  'Debug|AnyCPU' ">
  <OutputPath>.\bin\Debug\</OutputPath>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' ==  'Release|AnyCPU' ">
  <OutputPath>.\bin\Release\</OutputPath>
</PropertyGroup>

I could still build the project without errors in the command line, but CCNET is returning the same error mentioned above.

I don't understand why CCNET keeps getting the error, and I don't know what else to try.

Please help.

Body:
I found I had a similar situation (but using TeamCity as my CI environment).  In my particular case, the project was a Command Line application.  To solve it, I had to manually edit my project file.

Find these lines:

<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>

Change the second line to:

<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>

The find the other platform-specific lines in the project file and change them.  Example:

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|x86' ">

becomes:

  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">

My suspicion is our build servers are 64-bit and the Console Application project type in Studio won't let you make the project fit an AnyCPU platform...

After these changes, TeamCity had no problem with my build script.


问:
Foxpro replace with "" not in
I hereby seek for a solution. I have one dbf for january and february each. There are two columns named A and B in each dbf, A is a series of number and B is vlookup, and I want to replace the columnB in february with "new" if its values in columnA do not appear in the column A in january, and "old" for vice versa. My code is the following:

```<code>REPLACE ALL B WITH "Old"
REPLACE ALL B WITH "New" FOR A NOT IN (sele A FROM &filejanuary)
</code>```

Thanks.

答:
```<code>update February set February.B = 'Old'
update February set February.B = 'New' ;
   where not exists (select * from January where January.A = February.A)
</code>```

Title: Foxpro replace with "" not in

Body:
I hereby seek for a solution. I have one dbf for january and february each. There are two columns named A and B in each dbf, A is a series of number and B is vlookup, and I want to replace the columnB in february with "new" if its values in columnA do not appear in the column A in january, and "old" for vice versa. My code is the following:

REPLACE ALL B WITH "Old"
REPLACE ALL B WITH "New" FOR A NOT IN (sele A FROM &filejanuary)

Thanks.


问:
Laravel Envoy Permissions?
Ok, so I am trying to call Envoy from a controller function but running into permissions problems that nobody else seems to be getting?

I have installed envoy globally and done a symlink to /usr/local/bin so that my site can see it. But I cannot figure out why it doesn't have permission.

I am running from Ubuntu 16.04, Nginx, PHP 7.0

Any help is appreciated:

```<code>$result = [];
         $live = false;

         $process = new \Symfony\Component\Process\Process('envoy run deploy --domain="test"');
         $process->setTimeout(3600);
         $process->setIdleTimeout(300);
         $process->setWorkingDirectory(base_path());
         $process->run(
             function ($type, $buffer) use ($live, &$result) {
                 $buffer = str_replace('[127.0.0.1]: ', '', $buffer);

                 if ($live) {
                     echo $buffer . '</br />';
                 }

                 $result[] = $buffer;
             }
         );

         dd($result);
</code>```

But getting:

```<code>0 => "sh: 1: "
  1 => "envoy: Permission denied"
  2 => "\n"
</code>```

答:
I believe it is the permission for the laravel app user. You should take into acccount that laravel process is owned by a different user (presumably www-data) who does not have permission to execute envoy.

To fix this, you have to tweak the permissions of the envoy which could lead to security weaknesses and time consuming on different deployments.

sudo chown www-data:www-data ~/.composer/vendor/laravel/envoy/envoy

However, I recommend that you use composer require laravel/envoy in your project and execute it from vendor/bin/envoy.

Title: Laravel Envoy Permissions?

Body:
Ok, so I am trying to call Envoy from a controller function but running into permissions problems that nobody else seems to be getting?

I have installed envoy globally and done a symlink to /usr/local/bin so that my site can see it. But I cannot figure out why it doesn't have permission.

I am running from Ubuntu 16.04, Nginx, PHP 7.0

Any help is appreciated:

$result = [];
         $live = false;

         $process = new \Symfony\Component\Process\Process('envoy run deploy --domain="test"');
         $process->setTimeout(3600);
         $process->setIdleTimeout(300);
         $process->setWorkingDirectory(base_path());
         $process->run(
             function ($type, $buffer) use ($live, &$result) {
                 $buffer = str_replace('[127.0.0.1]: ', '', $buffer);

                 if ($live) {
                     echo $buffer . '
';
                 }

                 $result[] = $buffer;
             }
         );

         dd($result);

But getting:

0 => "sh: 1: "
  1 => "envoy: Permission denied"
  2 => "\n"


问:
file_get_contents gives error in codeigniter
```<code>$scope.formatfilename = response.fileformat[0].FileName;
</code>```

// it contains filename = abcd

```<code> $filename1 ='{{formatfilename}}'; // now I have taken into phpvariable
 $siteaddr = "http://localhost:8080/demoproject/document/".$filename1.".html";
echo file_get_contents($siteaddressAPI);
</code>```

it gives me Failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
if I assign full url static to $siteaddressAPI then it gives the result.

how to solve in codeigniter ??

答:
Option 1:
change in php.ini

```<code>allow_url_fopen = On
</code>```

Option 2: use cURL
You might want to try using curl to retrieve the data instead of file_get_contents. curl has better support for error handling:

```<code> $filename1 ='{{formatfilename}}'; // now I have taken into phpvariable
 $siteaddr = "http://localhost:8080/demoproject/document/".$filename1.".html";
// make request
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $siteaddr);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);

    // convert response
    $output = json_decode($output);

    // handle error; error output
    if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {

      var_dump($output);
    }

    curl_close($ch);
</code>```

Working Example

```<code><?php

$siteaddr = "https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY";
// make request
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $siteaddr);
// Execute
$output = curl_exec($ch);

// convert response
$output = json_decode($output);

// handle error; error output
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
    var_dump($output);
}

curl_close($ch);
echo "```", print_r($output), "```";
die();
?>
</code>```

Output

```<code>stdClass Object
(
    [error_message] => The provided API key is invalid.
    [results] => Array
        (
        )

    [status] => REQUEST_DENIED
)
</code>```

Body:
$scope.formatfilename = response.fileformat[0].FileName;

// it contains filename = abcd

 $filename1 ='{{formatfilename}}'; // now I have taken into phpvariable
 $siteaddr = "http://localhost:8080/demoproject/document/".$filename1.".html";
echo file_get_contents($siteaddressAPI);

it gives me Failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
if I assign full url static to $siteaddressAPI then it gives the result.

how to solve in codeigniter ??

Body:
Option 1:
change in php.ini

allow_url_fopen = On

Option 2: use cURL
You might want to try using curl to retrieve the data instead of file_get_contents. curl has better support for error handling:

 $filename1 ='{{formatfilename}}'; // now I have taken into phpvariable
 $siteaddr = "http://localhost:8080/demoproject/document/".$filename1.".html";
// make request
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $siteaddr);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($ch);

    // convert response
    $output = json_decode($output);

    // handle error; error output
    if(curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {

      var_dump($output);
    }

    curl_close($ch);

Working Example

<?php

$siteaddr = "https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&key=YOUR_API_KEY";
// make request
$ch = curl_init();
// Disable SSL verification
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL, $siteaddr);
// Execute
$output = curl_exec($ch);

// convert response
$output = json_decode($output);

// handle error; error output
if (curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200) {
    var_dump($output);
}

curl_close($ch);
echo "<pre>", print_r($output), "</pre>";
die();
?>

Output

stdClass Object
(
    [error_message] => The provided API key is invalid.
    [results] => Array
        (
        )

    [status] => REQUEST_DENIED
)


问:
Twilio SMS Physical Phone Integration
In a perfect world, the solution I'm looking for would be an api resource tied to my physical phone, e.g. I could POST an sms message to https://url.com/api/sms, and this api would have the end result of sending an sms from my physical phone.  This means that the sms conversation would appear natively in my phone; if the recipient replies to the sms, it would appear just as a normal conversation as if I had physically typed the original sms via my phone.

I understand that I could set the replyto/callback/caller-id via Twilio's api.  This would mean that the sms gets sent out by the api, and if the recipient replies to it, I could have the reply forwarded to my phone.  But what would be missing in this scenario is the original message sent via the api, that the recipient is replying to.

Is there a streamlined way to achieve this, perhaps with Zapier?

One arduous solution I have in mind is to write an on-phone-app to intermediate the sms transmission so that I essentially have an sms-controlled api on the physical phone vs. a traditional http api.  (On android, the api would "listen" via DATA_SMS_RECEIVED_ACTION and then send via sendTextMessage).  But this seems cumbersome and would also require updating the app code when/if android changes the underlying SmsManager library.  The advantage of this is that I could avoid Twilio altogether, by using my service provider's email-to-sms to send to the on-phone-makeshift-sms-api.

答:
Twilio developer evangelist here.

I think you are looking for a feature that we just announced in preview. This is known as Hosted SMS and allows you to add SMS powered by Twilio to your existing phone number.

You need to apply to get access to Hosted SMS as it is newly in testing. You can do so with the form here: https://www.twilio.com/sms/hosted

Title: Twilio SMS Physical Phone Integration


问:
Sublime Text 2 - BeautifyRuby don't work
i've installed BeautifyRuby in my Sublime Text 2 (running OS X Yosemite 10.10), but is not working, I receive this message when I try to cmd + ctrl + k:

Error: invalid output. Check your ruby interpreter settings

I've changed, as suggested https://github.com/CraigWilliams/BeautifyRuby , the sublime-settings file with:

```<code>"ruby": "/Users/alessiogastaldo/.rbenv/bin/ruby"
</code>```

and also using the specific version:

```<code>"ruby": "/Users/alessiogastaldo/.rbenv/versions/1.8.7-p371/bin/ruby"
</code>```

but with no success.

I've read the different solutions proposed (like https://github.com/CraigWilliams/BeautifyRuby/issues/52) but nothing works.

Anyone do know how to solve this?

答:
I had the same problem too.
I solved with this:

In terminal, run the command: which ruby.

Copy the result. In my case was: "/home/user/.rbenv/shims/ruby"

Open your package settings. In my case: Preferences > Package Settings > BeautyfyRuby > Settings Default.

Add this line in the file: "ruby": "/home/user/.rbenv/shims/ruby",

You will need to install the htmlbeautifier gem.

Run the commmand in terminal: gem install htmlbeautifier

It works for me.

Body:
i've installed BeautifyRuby in my Sublime Text 2 (running OS X Yosemite 10.10), but is not working, I receive this message when I try to cmd + ctrl + k:

Error: invalid output. Check your ruby interpreter settings

I've changed, as suggested https://github.com/CraigWilliams/BeautifyRuby , the sublime-settings file with:

"ruby": "/Users/alessiogastaldo/.rbenv/bin/ruby"

and also using the specific version:

"ruby": "/Users/alessiogastaldo/.rbenv/versions/1.8.7-p371/bin/ruby"

but with no success.

I've read the different solutions proposed (like https://github.com/CraigWilliams/BeautifyRuby/issues/52) but nothing works.

Anyone do know how to solve this?


问:
How to write a simple testing case using XUnit?
Totally new to testing, I have a controller like this:

```<code>public class CheckRegController : Controller
{
    private readonly ApplicationDbContext _context;
    private readonly AppSettings _appSettings;

    public CheckRegController(ApplicationDbContext context, IOptions<AppSettings> appSettings)
    {
        _context = context;
        _appSettings = appSettings.Value;
    }

    [HttpGet]
    public IActionResult Get(string var1, int numberusers)
    {
        //...
    }
}
</code>```

Now I have added a test project in which I am trying to use XUnit and Moq. I just wanted to create an object of controller like I have done in a very simple project, but it doesn't work in this.When I tried:

```<code>CheckRegController cr = new CheckRegController();
</code>```

It says:

There is no argument given that corresponds to the required formal
  parameter 'context' of
  'CheckRegController.CheckRegController(ApplicationDbContext,
  IOptions)'   XUnitTestProjectOA

Then I tried:

```<code>var moqHome = new Mock<ApplicationDbContext>();
</code>```

but I don't know is it right or not OR what I need to do ahead?
How to pass _context and _appsettings ??

答:
You were on the right track. Mock the dependencies and inject them into the subject under test.

```<code>//Arrange
var dbmock = new Mock<ApplicationDbContext>();
//...setup dbmock as needed to exercise test
var options = new Mock<IOption<AppSetting>();
var appSetting = new AppSetting {
    //...populate appSetting as needed to exercise test
};
options.Setup(_ => _.Value).Returns(appSetting);

var sut = new CheckRegController(dbMock.Object, options.Object);
var var1 = "testing";
var numberusers = 2;

//Act
var actual = sut.Get(var1,numberusers)

//Assert
//...assert expected behavior to actual.
</code>```

I would also suggest abstracting away the context to also make the controller more maintainable.

Body:
Totally new to testing, I have a controller like this:

public class CheckRegController : Controller
{
    private readonly ApplicationDbContext _context;
    private readonly AppSettings _appSettings;

    public CheckRegController(ApplicationDbContext context, IOptions<AppSettings> appSettings)
    {
        _context = context;
        _appSettings = appSettings.Value;
    }

    [HttpGet]
    public IActionResult Get(string var1, int numberusers)
    {
        //...
    }
}

Now I have added a test project in which I am trying to use XUnit and Moq. I just wanted to create an object of controller like I have done in a very simple project, but it doesn't work in this.When I tried:

CheckRegController cr = new CheckRegController();

It says:

There is no argument given that corresponds to the required formal
  parameter 'context' of
  'CheckRegController.CheckRegController(ApplicationDbContext,
  IOptions)'   XUnitTestProjectOA

Then I tried:

var moqHome = new Mock<ApplicationDbContext>();

but I don't know is it right or not OR what I need to do ahead?
How to pass _context and _appsettings ??

Body:
You were on the right track. Mock the dependencies and inject them into the subject under test.

//Arrange
var dbmock = new Mock<ApplicationDbContext>();
//...setup dbmock as needed to exercise test
var options = new Mock<IOption<AppSetting>();
var appSetting = new AppSetting {
    //...populate appSetting as needed to exercise test
};
options.Setup(_ => _.Value).Returns(appSetting);

var sut = new CheckRegController(dbMock.Object, options.Object);
var var1 = "testing";
var numberusers = 2;

//Act
var actual = sut.Get(var1,numberusers)

//Assert
//...assert expected behavior to actual.

I would also suggest abstracting away the context to also make the controller more maintainable.


问:
Make a tree from a matrix
I have a matrix of numbers like this one

enter image description here

And I want to create a tree like
enter image description here

In the tree, if you do 1+2 (chimp - human) you get the distance in the matrix, which is 3.

My question is: How could I make the tree from the matrix? Which algorithm should I follow?

答:
You can't. The matrix doesn't contain enough information to reconstruct the tree.

As an example, consider just a matrix containing Human and Chimp. We know he total distance of both branches of the tree needs to be 3, but there's nothing telling us whether it should be 3+0 or 2+1 or 1+2 or 0+3.

Title: Make a tree from a matrix


问:
How to install tkinter on windows 10, python 3.6.1
I've encountered similar errors while using several different packages like matplotlib and pymc3, error message said:

```<code>    Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python36\lib\site-packages\matplotlib\pyplot.py", line 115, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "C:\Python36\lib\site-packages\matplotlib\backends\__init__.py", line 32, in pylab_setup
    globals(),locals(),[backend_name],0)
  File "C:\Python36\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 6, in <module>
    from six.moves import tkinter as Tk
  File "C:\Python36\lib\site-packages\six.py", line 92, in __get__
    result = self._resolve()
  File "C:\Python36\lib\site-packages\six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "C:\Python36\lib\site-packages\six.py", line 82, in _import_module
    __import__(name)
ModuleNotFoundError: No module named 'tkinter'
</code>```

I'm totally new to python, have no idea what tkinter is. After some googles, I tried to install ActiveTcl 8.6.4 into default path, but it doesn't work.

What should I do?

答: Finally, I figured out what happened. I unchecked tcl/tk option before installation, that may be the problem. I modified my python installation just now, hope it could help.</p>

Body:
I've encountered similar errors while using several different packages like matplotlib and pymc3, error message said:

    Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python36\lib\site-packages\matplotlib\pyplot.py", line 115, in <module>
    _backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
  File "C:\Python36\lib\site-packages\matplotlib\backends\__init__.py", line 32, in pylab_setup
    globals(),locals(),[backend_name],0)
  File "C:\Python36\lib\site-packages\matplotlib\backends\backend_tkagg.py", line 6, in <module>
    from six.moves import tkinter as Tk
  File "C:\Python36\lib\site-packages\six.py", line 92, in __get__
    result = self._resolve()
  File "C:\Python36\lib\site-packages\six.py", line 115, in _resolve
    return _import_module(self.mod)
  File "C:\Python36\lib\site-packages\six.py", line 82, in _import_module
    __import__(name)
ModuleNotFoundError: No module named 'tkinter'

I'm totally new to python, have no idea what tkinter is. After some googles, I tried to install ActiveTcl 8.6.4 into default path, but it doesn't work.

What should I do?


问:
Numpy tutorial - Boolean indexing
Reading Numpy quick tutorial, I cannot understand this sentence.

```<code>a = np.arange(12).reshape(3,4)
b1 = np.array([False,True,True])
b2 = np.array([True,False,True,False])
>>> a[b1,b2]
array([ 4, 10])
</code>```

Why a[b1,b2] is array([4,10]) instead of array([[4,6],[8,10]])?

答:
It's because you are performing integer array indexing there.

Internally, the indices are computed from the boolean arrays -

```<code>In [72]: idx1 = np.flatnonzero(b1)

In [73]: idx2 = np.flatnonzero(b2)

In [75]: idx1
Out[75]: array([1, 2])

In [76]: idx2
Out[76]: array([0, 2])
</code>```

Then, the integer array indexing is performed on each group of indices using each element from the indexing arrays -

```<code>In [77]: a[1,0] # 1 from idx1[0], 0 from idx2[0]
Out[77]: 4

In [78]: a[2,2] # 2 from idx1[1], 2 from idx2[1]
Out[78]: 10
</code>```

To achieve that MATLAB styled block extraction, we need to use open arrays and index into each of those axes/dims. To create such open arrays in NumPy, we have np.ix_ -

```<code>In [89]: np.ix_(b1,b2)
Out[89]:
(array([[1],
        [2]]), array([[0, 2]]))

In [90]: a[np.ix_(b1,b2)]
Out[90]:
array([[ 4,  6],
       [ 8, 10]])
</code>```

Title: Numpy tutorial - Boolean indexing

Body:
Reading Numpy quick tutorial, I cannot understand this sentence.

a = np.arange(12).reshape(3,4)
b1 = np.array([False,True,True])
b2 = np.array([True,False,True,False])
>>> a[b1,b2]
array([ 4, 10])

Why a[b1,b2] is array([4,10]) instead of array([[4,6],[8,10]])?

Body:
It's because you are performing integer array indexing there.

Internally, the indices are computed from the boolean arrays -

In [72]: idx1 = np.flatnonzero(b1)

In [73]: idx2 = np.flatnonzero(b2)

In [75]: idx1
Out[75]: array([1, 2])

In [76]: idx2
Out[76]: array([0, 2])

Then, the integer array indexing is performed on each group of indices using each element from the indexing arrays -

In [77]: a[1,0] # 1 from idx1[0], 0 from idx2[0]
Out[77]: 4

In [78]: a[2,2] # 2 from idx1[1], 2 from idx2[1]
Out[78]: 10

To achieve that MATLAB styled block extraction, we need to use open arrays and index into each of those axes/dims. To create such open arrays in NumPy, we have np.ix_ -

In [89]: np.ix_(b1,b2)
Out[89]:
(array([[1],
        [2]]), array([[0, 2]]))

In [90]: a[np.ix_(b1,b2)]
Out[90]:
array([[ 4,  6],
       [ 8, 10]])


问:
:eq() selector returns undefined
I'm learning jQuery and I get this 'undefined' error when using :eq() selector. Here is the HTML:

```<code><!DOCTYPE html>
<html>
<head>
    <title>:eq() selector example</title>
</head>
<body>
    <div>
        <button>Button #1</button>
        <button>Button #2</button>
        <button>Button #3</button>
        <button>Button #4</button>
        <button>Button #5</button>
        <button>Button #6</button>
    </div>

    <script src="jquery-2.1.4.min.js"></script>
    <script src="script.js"></script>
</body>
</html>
</code>```

And the script:

```<code>var myButton = $('button:eq(5)');
console.log(myButton.textContent);
</code>```

When I use var myButton = $('button')[5]; everything is fine though.

答:
Do with jquery object text().selector$('button:eq(5)'); return a jquery Object .And textContent is a Dom Object. is not acceptable one .

var myButton = $('button:eq(5)');
console.log(myButton.text());```
<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>
<div>
  <button>Button #1</button>
  <button>Button #2</button>
  <button>Button #3</button>
  <button>Button #4</button>
  <button>Button #5</button>
  <button>Button #6</button>
</div></code>```

OR

If you need combination of both try like this

```<code>$('button:eq(5)')[0].textContent
</code>```

Title: :eq() selector returns undefined

Body:
I'm learning jQuery and I get this 'undefined' error when using :eq() selector. Here is the HTML:

<!DOCTYPE html>

    <title>:eq() selector example</title>

        <button>Button #1</button>
        <button>Button #2</button>
        <button>Button #3</button>
        <button>Button #4</button>
        <button>Button #5</button>
        <button>Button #6</button>

And the script:

var myButton = $('button:eq(5)');
console.log(myButton.textContent);

When I use var myButton = $('button')[5]; everything is fine though.

Body:
Do with jquery object text().selector$('button:eq(5)'); return a jquery Object .And textContent is a Dom Object. is not acceptable one .

var myButton = $('button:eq(5)');
console.log(myButton.text());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button>Button #1</button>
  <button>Button #2</button>
  <button>Button #3</button>
  <button>Button #4</button>
  <button>Button #5</button>
  <button>Button #6</button>
</div>

OR

If you need combination of both try like this

$('button:eq(5)')[0].textContent


问:
How can I add this lengthy command as alias on git?
I sometimes use this command on git.

```<code>$ git filter-branch --commit-filter '
    if [ "$GIT_AUTHOR_EMAIL" = "wrong@address.local" ];
    then
            GIT_AUTHOR_NAME="myname";
            GIT_AUTHOR_EMAIL="right@address.com";
            git commit-tree "$@";
    else
            git commit-tree "$@";
    fi' HEAD
</code>```

I want to add that as alias.
And then I tried as below, it doesn't work...

```<code>git config --global alias.rewritelog '!f(){ \
    git filter-branch --commit-filter \' \
    if [ "$GIT_AUTHOR_EMAIL" = "wrong@address.local" ]; \
    then \
        GIT_AUTHOR_NAME="myname"; \
        GIT_AUTHOR_EMAIL="right@address.com"; \
        git commit-tree "$@"; \
    else \
        git commit-tree "$@"; \
    fi\' HEAD \
};f'
</code>```

After this command, error occurred.

```<code>zsh: parse error near `then'
</code>```

答:
You cannot escape single-quotes within single-quotes.
Luckily you can escape double-quotes within double-quotes.
Surround with double-quotes instead of single-quotes:

```<code>git config --global alias.rewritelog "!f(){ \
    git filter-branch --commit-filter ' \
    if [ \"$GIT_AUTHOR_EMAIL\" = wrong@address.local ]; \
    then \
        GIT_AUTHOR_NAME=myname; \
        GIT_AUTHOR_EMAIL=right@address.com; \
    fi; \
    git commit-tree \"$@\"' HEAD; };f"
</code>```

I also simplified your original code and removed some unnecessary double-quotes.

Body:
I sometimes use this command on git.

$ git filter-branch --commit-filter '
    if [ "$GIT_AUTHOR_EMAIL" = "wrong@address.local" ];
    then
            GIT_AUTHOR_NAME="myname";
            GIT_AUTHOR_EMAIL="right@address.com";
            git commit-tree "$@";
    else
            git commit-tree "$@";
    fi' HEAD

I want to add that as alias.
And then I tried as below, it doesn't work...

git config --global alias.rewritelog '!f(){ \
    git filter-branch --commit-filter \' \
    if [ "$GIT_AUTHOR_EMAIL" = "wrong@address.local" ]; \
    then \
        GIT_AUTHOR_NAME="myname"; \
        GIT_AUTHOR_EMAIL="right@address.com"; \
        git commit-tree "$@"; \
    else \
        git commit-tree "$@"; \
    fi\' HEAD \
};f'

After this command, error occurred.

zsh: parse error near `then'

Body:
You cannot escape single-quotes within single-quotes.
Luckily you can escape double-quotes within double-quotes.
Surround with double-quotes instead of single-quotes:

git config --global alias.rewritelog "!f(){ \
    git filter-branch --commit-filter ' \
    if [ \"$GIT_AUTHOR_EMAIL\" = wrong@address.local ]; \
    then \
        GIT_AUTHOR_NAME=myname; \
        GIT_AUTHOR_EMAIL=right@address.com; \
    fi; \
    git commit-tree \"$@\"' HEAD; };f"

I also simplified your original code and removed some unnecessary double-quotes.


问:
Column name with dot spark
I am trying to take columns from a DataFrame and convert it to an RDD[Vector].

The problem is that I have columns with a "dot" in their name as the following dataset :

```<code>"col0.1","col1.2","col2.3","col3.4"
1,2,3,4
10,12,15,3
1,12,10,5
</code>```

This is what I'm doing :

```<code>val df = spark.read.format("csv").options(Map("header" -> "true", "inferSchema" -> "true")).load("C:/Users/mhattabi/Desktop/donnee/test.txt")
val column=df.columns.map(c=>s"`${c}`")
val rows = new VectorAssembler().setInputCols(column).setOutputCol("vs")
  .transform(df)
  .select("vs")
  .rdd
val data =rows.map(_.getAs[org.apache.spark.ml.linalg.Vector](0))
  .map(org.apache.spark.mllib.linalg.Vectors.fromML)

val mat: RowMatrix = new RowMatrix(data)
//// Compute the top 5 singular values and corresponding singular vectors.
val svd: SingularValueDecomposition[RowMatrix, Matrix] = mat.computeSVD(mat.numCols().toInt, computeU = true)
val U: RowMatrix = svd.U  // The U factor is a RowMatrix.
val s: Vector = svd.s  // The singular values are stored in a local dense vector.
val V: Matrix = svd.V  // The V factor is a local dense matrix.

println(V)
</code>```

Please any help to get me consider columns with dot in their names.Thanks

答:
The problem here is VectorAssembler implementation, not the columns per se. You can for example skip the header:

```<code>val df = spark.read.format("csv")
  .options(Map("inferSchema" -> "true", "comment" -> "\""))
  .load(path)

new VectorAssembler()
  .setInputCols(df.columns)
  .setOutputCol("vs")
  .transform(df)
</code>```

or rename columns before passing to VectorAssembler:

```<code>val renamed =  df.toDF(df.columns.map(_.replace(".", "_")): _*)

new VectorAssembler()
  .setInputCols(renamed.columns)
  .setOutputCol("vs")
  .transform(renamed)
</code>```

Finally the best approach is to provide schema explicitly:

```<code>import org.apache.spark.sql.types._

val schema = StructType((0 until 4).map(i => StructField(s"_$i", DoubleType)))

val dfExplicit = spark.read.format("csv")
  .options(Map("header" -> "true"))
  .schema(schema)
  .load(path)

new VectorAssembler()
  .setInputCols(dfExplicit.columns)
  .setOutputCol("vs")
  .transform(dfExplicit)
</code>```

Title: Column name with dot spark

Body:
I am trying to take columns from a DataFrame and convert it to an RDD[Vector].

The problem is that I have columns with a "dot" in their name as the following dataset :

"col0.1","col1.2","col2.3","col3.4"
1,2,3,4
10,12,15,3
1,12,10,5

This is what I'm doing :

val df = spark.read.format("csv").options(Map("header" -> "true", "inferSchema" -> "true")).load("C:/Users/mhattabi/Desktop/donnee/test.txt")
val column=df.columns.map(c=>s"`${c}`")
val rows = new VectorAssembler().setInputCols(column).setOutputCol("vs")
  .transform(df)
  .select("vs")
  .rdd
val data =rows.map(_.getAs[org.apache.spark.ml.linalg.Vector](0))
  .map(org.apache.spark.mllib.linalg.Vectors.fromML)

val mat: RowMatrix = new RowMatrix(data)
//// Compute the top 5 singular values and corresponding singular vectors.
val svd: SingularValueDecomposition[RowMatrix, Matrix] = mat.computeSVD(mat.numCols().toInt, computeU = true)
val U: RowMatrix = svd.U  // The U factor is a RowMatrix.
val s: Vector = svd.s  // The singular values are stored in a local dense vector.
val V: Matrix = svd.V  // The V factor is a local dense matrix.

println(V)

Please any help to get me consider columns with dot in their names.Thanks

Body:
The problem here is VectorAssembler implementation, not the columns per se. You can for example skip the header:

val df = spark.read.format("csv")
  .options(Map("inferSchema" -> "true", "comment" -> "\""))
  .load(path)

new VectorAssembler()
  .setInputCols(df.columns)
  .setOutputCol("vs")
  .transform(df)

or rename columns before passing to VectorAssembler:

val renamed =  df.toDF(df.columns.map(_.replace(".", "_")): _*)

new VectorAssembler()
  .setInputCols(renamed.columns)
  .setOutputCol("vs")
  .transform(renamed)

Finally the best approach is to provide schema explicitly:

import org.apache.spark.sql.types._

val schema = StructType((0 until 4).map(i => StructField(s"_$i", DoubleType)))

val dfExplicit = spark.read.format("csv")
  .options(Map("header" -> "true"))
  .schema(schema)
  .load(path)

new VectorAssembler()
  .setInputCols(dfExplicit.columns)
  .setOutputCol("vs")
  .transform(dfExplicit)


答:
$('button:eq(5)') return jQuery object that doesn't have textContent property so you should use text() instead to get the element text :

```<code>var myButton = $('button:eq(5)');
console.log(myButton.text());
</code>```

When $('button')[5]; return DOM object that why you could access the property textContent on it :

```<code>var myButton = $('button')[5];
console.log(myButton.textContent);
</code>```

Hope this helps.

Title: :eq() selector returns undefined

Body:
$('button:eq(5)') return jQuery object that doesn't have textContent property so you should use text() instead to get the element text :

var myButton = $('button:eq(5)');
console.log(myButton.text());

When $('button')[5]; return DOM object that why you could access the property textContent on it :

var myButton = $('button')[5];
console.log(myButton.textContent);

Hope this helps.


问:
Passing multi parameters (radio) from view to controller using array
I would like to post between 55 and 100 items which could be false or true from view to my controller without using Model. This is my code in Razor View:

```<code>@using(Html.BeginForm("User","User",FormMethod.Post,new{enctype="multipart/form-data"}))
    {

        <input type="radio" name="answer1">Choice one</input>
        <input type="radio" name="answer1">Choice two</input>
        <input type="radio" name="answer2">Choice three</input>
        <input type="radio" name="answer2">Choice four</input>

    ....

    <input type="radio" name="answer55">Choice fifty five</input>
    <input type="radio" name="answer55">Choice fifty six</input>

    <button type="submit">Send</button>
                                   }
</code>```

Controller:

```<code>[HttpPost]
public async Task<ActionResult> User(Array....)
{
return view();}
</code>```

How can I send all of parameters (radio buttons) using an array to my controller. I appreciate all your solutions.

答:
Maybe create a view model class that contains an array of size bool elements, and then bind each of element to the radio button in Razor page.

```<code>public class BooleanViewModel
{
   public BooleanViewModel(int size)
   {
      BoolArray = new bool [size];
   }

   public bool [] BoolArray {get; set;}
}
</code>```

Set your Razor page model: @model BooleanViewModel

Then, in Razor you could use @Html.RadioButtonFor(model => model.BoolArray[0], "textForButton") etc.
You could also make some foreach loop and go through all items within model.BoolArray.

Body:
I would like to post between 55 and 100 items which could be false or true from view to my controller without using Model. This is my code in Razor View:

@using(Html.BeginForm("User","User",FormMethod.Post,new{enctype="multipart/form-data"}))
    {

        <input type="radio" name="answer1">Choice one</input>
        <input type="radio" name="answer1">Choice two</input>
        <input type="radio" name="answer2">Choice three</input>
        <input type="radio" name="answer2">Choice four</input>

    ....

    <input type="radio" name="answer55">Choice fifty five</input>
    <input type="radio" name="answer55">Choice fifty six</input>

    <button type="submit">Send</button>
                                   }

Controller:

[HttpPost]
public async Task<ActionResult> User(Array....)
{
return view();}

How can I send all of parameters (radio buttons) using an array to my controller. I appreciate all your solutions.

Body:
Maybe create a view model class that contains an array of size bool elements, and then bind each of element to the radio button in Razor page.

public class BooleanViewModel
{
   public BooleanViewModel(int size)
   {
      BoolArray = new bool [size];
   }

   public bool [] BoolArray {get; set;}
}

Set your Razor page model: @model BooleanViewModel

Then, in Razor you could use @Html.RadioButtonFor(model => model.BoolArray[0], "textForButton") etc.
You could also make some foreach loop and go through all items within model.BoolArray.


问:
JOSE4J: How to create a RsaJsonWebKey object from a JSON representation of RsaJsonWebKey
I want to save with JOSE4J the JSON representation of a RsaJsonWebKey object in JSON format and then recreate a RsaJsonWebKey  object from it again. I have the marshalling part:

RsaJsonWebKey rsaJsonWebKey = RsaJwkGenerator.generateJwk(2048);

String jwkjson = rsaJsonWebKey.toJson(JsonWebKey.OutputControlLevel.INCLUDE_PRIVATE);

but how to unmarshall it and recreate RsaJsonWebKey. That is where I'm stuck as I don't see a constructor of RsaJsonWebKey allowing that.

The question is related to this question

JWT becomes invalid after restarting the server

but it doesn't explain how to unmarshall.

答: The bottom half of the example in JWT becomes invalid after restarting the server does show how to get to a JsonWebKey/PublicJsonWebKey object from a JSON string.  Using PublicJsonWebKey publicJsonWebKey = PublicJsonWebKey.Factory.newPublicJwk(jwkJson); will do the parsing/unmarshalling and can be cast to RsaJsonWebKey if need be.

ContentLicense: CC BY-SA 4.0


问:
Python: Document results and figures into tex document
I currently have written a script that produces several figures. I was wondering if there is a way to publish these figures directly into a tex file, say in eps format without including all of the python code verbatim. I also want to include the values of some variables. I looked at the module pweave (http://mpastell.com/pweave/) but I couldn't figure out a way to exclude code chunks. I'm new to python so any help would be much appreciated!</p>

答:
Set echo to false before very code chunk, following the documentation:
http://mpastell.com/pweave/defaults.html</p>


问:
request-promise : downloading/checking a file's MIME type?
Using the standard request module, we can run the following script to check a file's MIME type;

```<code>var request = require('request');
var url = "http://www.somedomain.com/somepicture.jpg";
var magic = {
    jpg: 'ffd8ffe0',
    png: '89504e47',
    gif: '47494638'
};
var options = {
    method: 'GET',
    url: url,
    encoding: null // keeps the body as buffer
};

request(options, function (err, response, body) {
    if(!err && response.statusCode == 200){
        var magicNumberInBody = body.toString('hex',0,4);
        if (magicNumberInBody == magic.jpg ||
            magicNumberInBody == magic.png ||
            magicNumberInBody == magic.gif) {
            console.log("It's an image!");
            return true;
        }
    }
});
</code>```

Which is pretty self-explanatory. However, when working with node.js and relying on Promises, how can we carry out the above? I've attempted to install and use request-promise, and wrote up the following script;

```<code>return rp("http://www.somedomain.com/somepicture.jpg")
            .then((response) => {
                var magicNumberInBody = response.toString('hex',0,4);
                console.log(magicNumberInBody);
                if (magicNumberInBody == magic.jpg ||
                    magicNumberInBody == magic.png ||
                    magicNumberInBody == magic.gif) {
                    console.log("It's an image!");
                    return true;
                }
</code>```

However, for anything that's not html/txt based, request-promise seems to just return with the raw binary.

Would anyone know how I can change the above data into something meaningful, which I can easily use to identify if the MIME type is jpg/png/gif?

答:
I do a head request first

```<code>      // Download
      return Image._head($, $(image).attr('src'))
        .then((filename) => {
          return Image._download($, filename)
        })
        .then((code) => {
          return $
        })

  // Request
  Request.head(options)
    .then((data) => {
      console.log(data)
      // Get the content type
      // const type = data['content-type']
      // let ext = ''

      // // Extract extension
      // if (type === 'image/jpeg' || type === 'image/pjpeg') {
      //   ext = 'jpg'
      // } else if (type === 'image/png') {
      //   ext = 'png'
      // } else if (type === 'image/gif') {
      //   ext = 'gif'
      // }

      // Get filename
      let filename = null
      const disposition = data['content-disposition']

      if (disposition && disposition.indexOf('inline') !== -1) {
        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
        var matches = filenameRegex.exec(disposition)
        if (matches != null && matches[1]) {
          filename = matches[1].replace(/['"]/g, '')
        }
      }

      // Path
      // const path = Path.join('./resources/images', `${filename}`)

      // console.log('content-type:', data.headers['content-type'])
      // console.log('content-length:', data.headers['content-length'])
      // console.log('content-disposition:', data.headers['content-disposition'])
      console.log('filename:', filename)

      // resolve(data.html)
      resolve(filename)
    })
    .catch((error) => {
      resolve(new Error(`${error} - Instagram - ${src}`))
    })
</code>```

Then another request to actually download the file.

Hope this helps in some way

Body:
Using the standard request module, we can run the following script to check a file's MIME type;

var request = require('request');
var url = "http://www.somedomain.com/somepicture.jpg";
var magic = {
    jpg: 'ffd8ffe0',
    png: '89504e47',
    gif: '47494638'
};
var options = {
    method: 'GET',
    url: url,
    encoding: null // keeps the body as buffer
};

request(options, function (err, response, body) {
    if(!err && response.statusCode == 200){
        var magicNumberInBody = body.toString('hex',0,4);
        if (magicNumberInBody == magic.jpg ||
            magicNumberInBody == magic.png ||
            magicNumberInBody == magic.gif) {
            console.log("It's an image!");
            return true;
        }
    }
});

Which is pretty self-explanatory. However, when working with node.js and relying on Promises, how can we carry out the above? I've attempted to install and use request-promise, and wrote up the following script;

return rp("http://www.somedomain.com/somepicture.jpg")
            .then((response) => {
                var magicNumberInBody = response.toString('hex',0,4);
                console.log(magicNumberInBody);
                if (magicNumberInBody == magic.jpg ||
                    magicNumberInBody == magic.png ||
                    magicNumberInBody == magic.gif) {
                    console.log("It's an image!");
                    return true;
                }

However, for anything that's not html/txt based, request-promise seems to just return with the raw binary.

Would anyone know how I can change the above data into something meaningful, which I can easily use to identify if the MIME type is jpg/png/gif?

Body:
I do a head request first

      // Download
      return Image._head($, $(image).attr('src'))
        .then((filename) => {
          return Image._download($, filename)
        })
        .then((code) => {
          return $
        })

  // Request
  Request.head(options)
    .then((data) => {
      console.log(data)
      // Get the content type
      // const type = data['content-type']
      // let ext = ''

      // // Extract extension
      // if (type === 'image/jpeg' || type === 'image/pjpeg') {
      //   ext = 'jpg'
      // } else if (type === 'image/png') {
      //   ext = 'png'
      // } else if (type === 'image/gif') {
      //   ext = 'gif'
      // }

      // Get filename
      let filename = null
      const disposition = data['content-disposition']

      if (disposition && disposition.indexOf('inline') !== -1) {
        var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/
        var matches = filenameRegex.exec(disposition)
        if (matches != null && matches[1]) {
          filename = matches[1].replace(/['"]/g, '')
        }
      }

      // Path
      // const path = Path.join('./resources/images', `${filename}`)

      // console.log('content-type:', data.headers['content-type'])
      // console.log('content-length:', data.headers['content-length'])
      // console.log('content-disposition:', data.headers['content-disposition'])
      console.log('filename:', filename)

      // resolve(data.html)
      resolve(filename)
    })
    .catch((error) => {
      resolve(new Error(`${error} - Instagram - ${src}`))
    })

Then another request to actually download the file.

Hope this helps in some way


问:
Assign value to rows inside a for loop python
I can't figure out why my below code won't assign a new value to the nth row inside the for loop. As far as I know, the way I index the b matrix should be correct but it seems like the count variable won't update for each iteration.
The print statements serve only as a way of checking what is going on.

I assume that it's pretty simple, so I would highly appreciate if one could point out were I'm wrong.

```<code>#!/usr/bin/python
import sys
#from string import maketrans
#import re
import numpy as np

lines = sum(1 for line in sys.stdin)
b = np.zeros((lines,2))

count = 0
for line in sys.stdin:

    line = line.strip()
    myline = line.split(",")

    Depart = myline[3]
    DepartDelay = float(myline[6])

    if DepartDelay<0:

        DepartDelay=0

    b[count,0] = Depart
    b[count, 1] = DepartDelay

    count = count + 1
    print(count)
print(b)
print(count)
</code>```

I use the following command to execute the code within the terminal of Ubuntu.

```<code>cat sample.txt | mapper.py
</code>```

which is why there as such aren't specified any data/text file.

In advance, thank you!

答:
The core problem seems to be that you're reading from sys.stdin twice. Once in the argument to sum, which will read the entire input, then again in the for loop. Because files have a current position, the usual result is that the for loop gets nothing to process. stdin is also likely to be a stream, so cannot be rewound. You must load the data only once.

A second question is if you can load the data using a higher abstraction level. It looks like you're reading a CSV, for which csv.reader might be useful, but it's collected in a numpy array, which makes numpy.loadtxt even more appealing. It even has a usecols field to read specific columns.

The count variable can also be handled a little more easily, using for count, line in enumerate(sys.stdin):. This will increment it along with the reading of lines.

I think a decent starting point is something like:

```<code>b = np.loadtxt(sys.stdin, delimiter=',', usecols=(3,6))
b[:,1] = np.maximum(b[:,1], 0)   # Set no lower than 0
</code>```

Body:
I can't figure out why my below code won't assign a new value to the nth row inside the for loop. As far as I know, the way I index the b matrix should be correct but it seems like the count variable won't update for each iteration.
The print statements serve only as a way of checking what is going on.

I assume that it's pretty simple, so I would highly appreciate if one could point out were I'm wrong.

#!/usr/bin/python
import sys
#from string import maketrans
#import re
import numpy as np

lines = sum(1 for line in sys.stdin)
b = np.zeros((lines,2))

count = 0
for line in sys.stdin:

    line = line.strip()
    myline = line.split(",")

    Depart = myline[3]
    DepartDelay = float(myline[6])

    if DepartDelay<0:

        DepartDelay=0

    b[count,0] = Depart
    b[count, 1] = DepartDelay

    count = count + 1
    print(count)
print(b)
print(count)

I use the following command to execute the code within the terminal of Ubuntu.

cat sample.txt | mapper.py

which is why there as such aren't specified any data/text file.

In advance, thank you!

Body:
The core problem seems to be that you're reading from sys.stdin twice. Once in the argument to sum, which will read the entire input, then again in the for loop. Because files have a current position, the usual result is that the for loop gets nothing to process. stdin is also likely to be a stream, so cannot be rewound. You must load the data only once.

A second question is if you can load the data using a higher abstraction level. It looks like you're reading a CSV, for which csv.reader might be useful, but it's collected in a numpy array, which makes numpy.loadtxt even more appealing. It even has a usecols field to read specific columns.

The count variable can also be handled a little more easily, using for count, line in enumerate(sys.stdin):. This will increment it along with the reading of lines.

I think a decent starting point is something like:

b = np.loadtxt(sys.stdin, delimiter=',', usecols=(3,6))
b[:,1] = np.maximum(b[:,1], 0)   # Set no lower than 0


问:
Signing HTTP request in Volley
Is there a way to sign http request in Volley?

As far as I understand SSL connection.

client opens connection

server responds with cert that contains public key

client stores server's public key

client creates request and signs it with server's public key

server verifies request using own private key

If server sends the response, client verifies response with server's public key?

How does ssl pinning fits in this process?

答:
I think you got the gist of it as far I as I know. SSL pinning is just verification of the CA certificate provided by the server response.

I think this url got it right. Maybe it might help you

SSL Pinning with Volley network library on Android

Title: Signing HTTP request in Volley


问:
iOS Filter NSFetchedResultsController Efficiently
I'm attempting to add search support to a Core Data backed UITableView and started to hit some performance issues. I currently have associations to two NSFetchedResultsController (one for regular and one for searching). In my UISearchDisplayDelegate methods I release and recreate my NSFetchedResultsController after each call. However, this causes lag while typing! Is there a more efficient way to filter an NSFetchedResultsController? I've setup my batch size to around 50 items and my database has a few thousand records if that makes a difference. Thanks!

答:
Yes you can:

Create the NSFetchRequest instance and change its sort descriptor each time:

```<code> let shortDescriptor = NSSortDescriptor(key: key, ascending: ascending)
    request.sortDescriptors = [shortDescriptor]

    do {
        try fetchedResultViewController?.performFetch()
    } catch let error as NSError {
        print("Error in fetch \(error)")
    }
</code>```

Read the apple document: https://developer.apple.com/reference/coredata/nsfetchedresultscontroller

Body:
Yes you can:

Create the NSFetchRequest instance and change its sort descriptor each time:

 let shortDescriptor = NSSortDescriptor(key: key, ascending: ascending)
    request.sortDescriptors = [shortDescriptor]

    do {
        try fetchedResultViewController?.performFetch()
    } catch let error as NSError {
        print("Error in fetch \(error)")
    }

Read the apple document: https://developer.apple.com/reference/coredata/nsfetchedresultscontroller


问:
How to format high charts?
I am using highchart  (jquery chart library). I am indicating the axis with tooltip. now i need to display y axis value on top of respective bar. How can i do that

My example graph

Question: To display yaxis values on top of respective bar in highchart.

答:
The settings you are looking for live in series.dataLabels:

```<code>var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'column'
    },
    title: {
        text: 'Category View'
    },
    xAxis: {
        categories: ['Category 1', 'Category 2', 'Category 3', 'Category 4', 'Category 5']
    },
    yAxis: {
        title: {
            text: 'Views'
        }
    },
    series: [{
        name: 'Number of Visits',
        data: [5, 3, 4, 7, 2],
        dataLabels: {
            enabled: true,
            formatter: function() {
               return this.y;
            }
         }
    }]
});
</code>```

Title: How to format high charts?

Body:
The settings you are looking for live in series.dataLabels:

var chart = new Highcharts.Chart({
    chart: {
        renderTo: 'container',
        defaultSeriesType: 'column'
    },
    title: {
        text: 'Category View'
    },
    xAxis: {
        categories: ['Category 1', 'Category 2', 'Category 3', 'Category 4', 'Category 5']
    },
    yAxis: {
        title: {
            text: 'Views'
        }
    },
    series: [{
        name: 'Number of Visits',
        data: [5, 3, 4, 7, 2],
        dataLabels: {
            enabled: true,
            formatter: function() {
               return this.y;
            }
         }
    }]
});


问:
NPM Scripts Post Hook not Firing
I am testing using npm scripts to eventually remove my reliance on Gulp. I am starting simply with one main custom script called watch. This script will ultimately run all scripts prefaced with the watch name; for example watch:styles. My watch:styles script will use node-sass to compile my sass files down into CSS. This works. However, my next step is creating a postwatch:styles script that runs the newly created .css files through PostCSS and Autoprefixer.

The Problem, though, is my postwatch:styles hook is never triggered to run.

package.json

```<code>{
  "name": "npm-scripts-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "watch": "npm-run-all --parallel watch:*",
    "watch:styles": "node-sass -w ./src/styles/main.scss ./dist/assets/styles/app.css",
    "postwatch:styles": "postcss -u autoprefixer --no-map ./dist/assets/styles/app.css -o ./dist/assets/styles/app.css"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {},
  "dependencies": {
    "autoprefixer": "^7.1.1",
    "node-sass": "^4.5.3",
    "postcss-cli": "^4.0.0",
    "yarn-run-all": "^3.1.1"
  },
  "browserslist": [
    "last 3 versions"
  ]
}
</code>```

Any advice or suggestions as to why my post hook isn't firing? The initial watch:styles runs just fine. If I run yarn postwatch:styles manually the script runs correctly. Could there be a silent error on my watch:styles that is preventing the hook from firing?

Any advice will be greatly appreciated.

答:
Since watch:styles calls node-sass in watch mode, the command never returns but remains in an active state waiting for your files to change.

And since there is no positive return, postwatch:styles will never be called.

You should try another approach maybe watching your files with watch or nodemon.

Title: NPM Scripts Post Hook not Firing

Body:
I am testing using npm scripts to eventually remove my reliance on Gulp. I am starting simply with one main custom script called watch. This script will ultimately run all scripts prefaced with the watch name; for example watch:styles. My watch:styles script will use node-sass to compile my sass files down into CSS. This works. However, my next step is creating a postwatch:styles script that runs the newly created .css files through PostCSS and Autoprefixer.

The Problem, though, is my postwatch:styles hook is never triggered to run.

package.json

{
  "name": "npm-scripts-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "watch": "npm-run-all --parallel watch:*",
    "watch:styles": "node-sass -w ./src/styles/main.scss ./dist/assets/styles/app.css",
    "postwatch:styles": "postcss -u autoprefixer --no-map ./dist/assets/styles/app.css -o ./dist/assets/styles/app.css"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {},
  "dependencies": {
    "autoprefixer": "^7.1.1",
    "node-sass": "^4.5.3",
    "postcss-cli": "^4.0.0",
    "yarn-run-all": "^3.1.1"
  },
  "browserslist": [
    "last 3 versions"
  ]
}

Any advice or suggestions as to why my post hook isn't firing? The initial watch:styles runs just fine. If I run yarn postwatch:styles manually the script runs correctly. Could there be a silent error on my watch:styles that is preventing the hook from firing?

Any advice will be greatly appreciated.