问:
Objective-c how to convert NSURL into NSString?
Total objective-c noob here with a question.
Is there a way to convert NSURL into NSString in one line?
I need to retrieve URL from sqlite database abd then save it into string.

Currently the line i want to convert looks like this ->

```<code>MyString.url = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 1)];
</code>```

so ofcourse im getting 'Incompatible pointer types assigning to 'NSURL *' from 'NSString *''

:)

答:
You can use any one

```<code>NSString *string=[NSString stringWithFormat:@"%@",url1];

or

NSString *str=[url1 absoluteString];

NSLog(@"string :: %@",string);
</code>```

string :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAAA1F7476071FE/DuplicateMedia.app/loading_circle_animation.gif

```<code>    NSLog(@"str :: %@", str);
</code>```

str :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAA-A1F7476071FE/DuplicateMedia.app/loading_circle_animation.gif

Body:
Total objective-c noob here with a question.
Is there a way to convert NSURL into NSString in one line?
I need to retrieve URL from sqlite database abd then save it into string.

Currently the line i want to convert looks like this ->

MyString.url = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 1)];

so ofcourse im getting 'Incompatible pointer types assigning to 'NSURL *' from 'NSString *''

:)

Body:
You can use any one

NSString *string=[NSString stringWithFormat:@"%@",url1];

or

NSString *str=[url1 absoluteString];

NSLog(@"string :: %@",string);

string :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAAA1F7476071FE/DuplicateMedia.app/loading_circle_animation.gif

    NSLog(@"str :: %@", str);

str :: file:///var/containers/Bundle/Application/E2D7570B-D5A6-45A0-8EAA-A1F7476071FE/DuplicateMedia.app/loading_circle_animation.gif


来源: stackexchange

问:
jQuery get meta content in div
I need to get some data stored in a div and in a meta tag.

Here the div:

```<code><div id="qtip-0" class="qtip simcal-default-calendar simcal-event-bubble qtip-pos-tc qtip-fixed qtip-focus" tracking="false" role="alert" aria-live="polite" aria-atomic="false" aria-describedby="qtip-0-content" aria-hidden="false" data-qtip-id="0" >
<div class="qtip-tip">
    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>
</div>
<div class="qtip-content" id="qtip-0-content" aria-atomic="true">
    <div class="simcal-event-details simcal-tooltip-content" style="display: block; visibility: visible;">
        <div class="col-xs-12 title-event-container">
            <span class="simcal-event-title" itemprop="name">Riunione intenra Scali ferroviari</span>
        </div>
        <p><label>Luogo:</label><br>
        <span class="simcal-event-address simcal-event-start-location" itemprop="location" itemscope="" itemtype="http://schema.org/Place"><meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia</span></p>
        <div id="map">Mappa</div>
        <p>
            <a href="//maps.google.com?q=Palazzo+Marino+-+Comune+di+MilanoPiazza+della+Scala+2%2C+20121+Milano%2C+Italia" target="_blank">Vedi mappa ingrandita</a>
        </p>
    </div>
</div>
</code>```

I need to access to:

```<code><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">
</code>```

to get the content attribute.

Here what I have tried:

```<code>var currentEventAddress = $('#qtip-0 span').find('meta[itemprop="address"]').attr('content');

console.log(currentEventAddress);
</code>```

But I get undefined

答:
This simple thing make this work.</p>

```<code><script type="text/javascript">
  $(document).ready(function() {
    console.log($("meta[itemprop='address']").attr("content"));
  });
</script>
</code>```

ContentLicense: CC BY-SA 3.0

Title: jQuery get meta content in div

Body:
I need to get some data stored in a div and in a meta tag.

Here the div:

    <canvas width="16" height="16" style="background-color: transparent !important; border: 0px !important; width: 8px; height: 8px;"></canvas>

            Riunione intenra Scali ferroviari

Luogo:

        <meta itemprop="name" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia"><meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia

Mappa

            Vedi mappa ingrandita

I need to access to:

<meta itemprop="address" content="Palazzo Marino - Comune di Milano
Piazza della Scala 2, 20121 Milano, Italia">

to get the content attribute.

Here what I have tried:

var currentEventAddress = $('#qtip-0 span').find('meta[itemprop="address"]').attr('content');

console.log(currentEventAddress);

But I get undefined

Body:
This simple thing make this work.

<script type="text/javascript">
  $(document).ready(function() {
    console.log($("meta[itemprop='address']").attr("content"));
  });
</script>


问:
Generate relations between tables Oracle with sqlplus
I Have a database that was handed to me in my job, in ".dmp" format, i imported it to my work space, and my mission is to understand it and  make some changes in it, my problem is it contains a lot of tables and i want to understand the relation between each table.

My question is, is there a way to show the relations between all the tables?  is there a way to generate a model that shows them all? something i need to install?

I'm using Oracle 10g Enterprise Edition.

答:
Yes. It's possible using tool.

SQL DEVELOPER is oracle provided free tool using which you can generate model which will show you relations between tables graphically.
Details procedure you may find it int the below link.

http://www.oracle.com/technetwork/issue-archive/2014/14-may/o34sqldev-2193423.html


问:
How to print all the substrings from a file using python
I have the text file like this

```<code>Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.106
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.107
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.108
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.109
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1
</code>```

I want to print all the IPv4 Addresses from this file using python script.
Currently I am able to print only first IPv4 (10.0.6.106) address only with the below python script.

ip =  open("ip.txt").read().split("IPv4 ")[1].split(":")[1].split("\n")[0].strip()
print ip

please help me to print all the IPv4 adresses.

答:
This should do it:</p>

```<code>with open('ip.txt') as ip:
    for line in ip:
        if line.startswith('IPv4 Address'):
            line = line.split(':')
            print line[1].strip()
</code>```

Body:
I have the text file like this

Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.106
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.107
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.108
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix  . : example.com
IPv6 Address. . . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Temporary IPv6 Address. . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
Link-local IPv6 Address . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx
IPv4 Address. . . . . . . . . . . : 10.0.6.109
Subnet Mask . . . . . . . . . . . : 255.255.0.0
Default Gateway . . . . . . . . . : xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
                                   10.0.0.1

I want to print all the IPv4 Addresses from this file using python script.
Currently I am able to print only first IPv4 (10.0.6.106) address only with the below python script.

ip =  open("ip.txt").read().split("IPv4 ")[1].split(":")[1].split("\n")[0].strip()
print ip

please help me to print all the IPv4 adresses.

Body:
This should do it:

with open('ip.txt') as ip:
    for line in ip:
        if line.startswith('IPv4 Address'):
            line = line.split(':')
            print line[1].strip()


问:
How to link to internal pages using changePage?
I currently have one index.html file with 3 pages in (with separate IDs). I also have 3 buttons which are displayed on all 3 pages, which I would like to link to each page when clicked. However, the link only works from the index.html page and once on another page, the events are no longer handled.

Basically when I'm on page 2 or 3, the click events aren't handled. (Tested with console.log)

html:

```<code><div data-role="page" id="article1">
    <div data-role="header" data-theme="a" data-position="fixed">
         <h1>Notes</h1>
    </div>

<div id="global-footer" data-role="footer" data-position="fixed" data-theme="a" data-id="main-footer" class="ui-bar">
     <div id="footer-container">
          <button id="notespagebtn" class="notespagebtn" data-role="none">Notes</button>
          <button id="reminderspagebtn" class="reminderspagebtn" data-role="none">Reminders</button>
          <button id="listspagebtn" class="listspagebtn" data-role="none">Lists</button>
      </div>
    </div>

</div>

<div data-role="page" id="article2">
     <div data-role="header" data-theme="a" data-position="fixed">
         <h1>Reminders</h1>
     </div>

<div id="global-footer" data-role="footer" data-position="fixed" data-theme="a" data-id="main-footer" class="ui-bar">
    <div id="footer-container">
        <button id="notespagebtn" class="notespagebtn" data-role="none">Notes</button>
        <button id="reminderspagebtn" class="reminderspagebtn" data-role="none">Reminders</button>
        <button id="listspagebtn" class="listspagebtn" data-role="none">Lists</button>
     </div>
  </div>

</div>

<div data-role="page" id="article3">
    <div data-role="header" data-theme="a" data-position="fixed">
        <h1>Lists</h1>
    </div>

   <div id="global-footer" data-role="footer" data-position="fixed" data-theme="a" data-id="main-footer" class="ui-bar">
        <div id="footer-container">
             <button id="notespagebtn" class="notespagebtn" data-role="none">Notes</button>
             <button id="reminderspagebtn" class="reminderspagebtn" data-role="none">Reminders</button>
             <button id="listspagebtn" class="listspagebtn" data-role="none">Lists</button>
   </div>
</div>
</code>```

JS:

```<code>$("#notespagebtn").click(function() {
        $.mobile.changePage("#article1");
    });

    $("#reminderspagebtn").click(function() {
        console.log("test");
        $.mobile.changePage("#article2");
    });

    $("#listspagebtn").click(function() {
        console.log("test");
        $.mobile.changePage("#article3");
    });
</code>```

答:
Buttons have same ID for all 3 pages. give them different Ids or use class to bind the event.

Jsfiddle

```<code>$(".notespagebtn").click(function() {
    $.mobile.changePage("#article1");
});

$(".reminderspagebtn").click(function() {
    console.log("test");
    $.mobile.changePage("#article2");
});

$(".listspagebtn").click(function() {
    console.log("test");
    $.mobile.changePage("#article3");
});
</code>```

Body:
I currently have one index.html file with 3 pages in (with separate IDs). I also have 3 buttons which are displayed on all 3 pages, which I would like to link to each page when clicked. However, the link only works from the index.html page and once on another page, the events are no longer handled.

Basically when I'm on page 2 or 3, the click events aren't handled. (Tested with console.log)

html:

Notes

          <button id="notespagebtn" class="notespagebtn" data-role="none">Notes</button>
          <button id="reminderspagebtn" class="reminderspagebtn" data-role="none">Reminders</button>
          <button id="listspagebtn" class="listspagebtn" data-role="none">Lists</button>

Reminders

        <button id="notespagebtn" class="notespagebtn" data-role="none">Notes</button>
        <button id="reminderspagebtn" class="reminderspagebtn" data-role="none">Reminders</button>
        <button id="listspagebtn" class="listspagebtn" data-role="none">Lists</button>

Lists

             <button id="notespagebtn" class="notespagebtn" data-role="none">Notes</button>
             <button id="reminderspagebtn" class="reminderspagebtn" data-role="none">Reminders</button>
             <button id="listspagebtn" class="listspagebtn" data-role="none">Lists</button>

JS:

$("#notespagebtn").click(function() {
        $.mobile.changePage("#article1");
    });

    $("#reminderspagebtn").click(function() {
        console.log("test");
        $.mobile.changePage("#article2");
    });

    $("#listspagebtn").click(function() {
        console.log("test");
        $.mobile.changePage("#article3");
    });

Body:
Buttons have same ID for all 3 pages. give them different Ids or use class to bind the event.

Jsfiddle

$(".notespagebtn").click(function() {
    $.mobile.changePage("#article1");
});

$(".reminderspagebtn").click(function() {
    console.log("test");
    $.mobile.changePage("#article2");
});

$(".listspagebtn").click(function() {
    console.log("test");
    $.mobile.changePage("#article3");
});


问:
exists pagination in material angular or alternative?
In ng-bootstrap exists pagination, I looked at material.angular.io and in github. But I have not seen anything similar, exists, any componente or alternative that is not documented?

Update:

With alternative I mean that inside MD, use another component and modify its behavior, by some simple adjustment ect. or used another name instead of
pagination

答:
Why don't you use Materialise Pagination

http://materializecss.com/pagination.html


问:
Sorl-thumbnail generates black lines and undesired crops
I'm using Sorl Thumbnail 12.4a1, Pillow 4.0.0 in a django project

It works fine for most images but for some of them I run into unexpected behaviour.

The original image is portrait jpg 765x1110

After running this code: get_thumbnail('/media/ryzsUIKZVUc.jpg', '464', upscale=False)

I receive a 464x320 image with black background on it's left and right and cropped on top and bottom

this is the original:
https://www.dropbox.com/s/ia7906ec19xjhro/ryzsUIKZVUc.jpg?dl=0

and this is the result: https://www.dropbox.com/s/adgut5zkw4xln6e/62b2439654a00312defafddb862eda9b.jpg?dl=0

p.s.
tried to upload the original here as an image but it was automatically converted to portrait.. could it mean something?

答:
The frame appears because of the exif tag. The size of the image is not correctly determined.

You can see this using exiftool:

```<code>$ exiftool ryzsUIKZVUc.jpg
ExifTool Version Number         : 10.10
File Name                       : ryzsUIKZVUc.jpg
Directory                       : .
File Size                       : 210 kB
File Modification Date/Time     : 2017:03:30 12:33:51+03:00
File Access Date/Time           : 2017:03:30 12:33:55+03:00
File Inode Change Date/Time     : 2017:03:30 12:33:51+03:00
File Permissions                : rw-rw-r--
File Type                       : JPEG
File Type Extension             : jpg
MIME Type                       : image/jpeg
JFIF Version                    : 1.01
Comment                         : CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 99.
Exif Byte Order                 : Big-endian (Motorola, MM)
Processing Software             : Windows Photo Editor 10.0.10011.16384
Orientation                     : Rotate 270 CW
Software                        : Windows Photo Editor 10.0.10011.16384
Modify Date                     : 2017:03:07 09:28:15
Date/Time Original              : 2017:03:07 09:27:46
Create Date                     : 2017:03:07 09:27:46
Sub Sec Time Original           : 00
Sub Sec Time Digitized          : 00
Color Space                     : sRGB
Padding                         : (Binary data 2060 bytes, use -b option to extract)
Compression                     : JPEG (old-style)
X Resolution                    : 96
Y Resolution                    : 96
Resolution Unit                 : inches
Thumbnail Offset                : 4608
Thumbnail Length                : 8169
About                           : uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1b
Creator Tool                    : Windows Photo Editor 10.0.10011.16384
Image Width                     : 1110
Image Height                    : 765
Encoding Process                : Baseline DCT, Huffman coding
Bits Per Sample                 : 8
Color Components                : 3
Y Cb Cr Sub Sampling            : YCbCr4:2:0 (2 2)
Image Size                      : 1110x765
Megapixels                      : 0.849
Create Date                     : 2017:03:07 09:27:46.00
Date/Time Original              : 2017:03:07 09:27:46.00
Thumbnail Image                 : (Binary data 8169 bytes, use -b option to extract)
</code>```

Or use PIL

```<code>>>> from PIL import Image
>>> from PIL.ExifTags import TAGS
>>>
>>> im = Image.open('ryzsUIKZVUc.jpg')
>>> exif = im._getexif()
>>> data = {}
>>>
>>> for tag, value in exif.items():
...     decoded = TAGS.get(tag, tag)
...     data[decoded] = value
...
>>>
>>> data['Orientation']
8
</code>```

To fix this, you can before generating a preview, (rotate image) save the picture without this tag.

For example,

```<code>def orient(image_path):
    """ Check are this img oriented """
    img = Image.open(image_path)
    # check is has exif data
    if not hasattr(img, '_getexif') or img._getexif() is None:
        return
    # if has information - try rotate img
    orientation = img._getexif().get(0x112)
    rotate_values = {3: 180, 6: 270, 8: 90}
    if orientation in rotate_values:
        img = img.rotate(rotate_values[orientation], expand=True)
    img.save(image_path, quality=100)
</code>```

Or easier, change the settings THUMBNAIL_ORIENTATION = False. In this case, the image simply stops rotating. And no more black lines are created.

Body:
The frame appears because of the exif tag. The size of the image is not correctly determined.

You can see this using exiftool:

$ exiftool ryzsUIKZVUc.jpg
ExifTool Version Number         : 10.10
File Name                       : ryzsUIKZVUc.jpg
Directory                       : .
File Size                       : 210 kB
File Modification Date/Time     : 2017:03:30 12:33:51+03:00
File Access Date/Time           : 2017:03:30 12:33:55+03:00
File Inode Change Date/Time     : 2017:03:30 12:33:51+03:00
File Permissions                : rw-rw-r--
File Type                       : JPEG
File Type Extension             : jpg
MIME Type                       : image/jpeg
JFIF Version                    : 1.01
Comment                         : CREATOR: gd-jpeg v1.0 (using IJG JPEG v62), quality = 99.
Exif Byte Order                 : Big-endian (Motorola, MM)
Processing Software             : Windows Photo Editor 10.0.10011.16384
Orientation                     : Rotate 270 CW
Software                        : Windows Photo Editor 10.0.10011.16384
Modify Date                     : 2017:03:07 09:28:15
Date/Time Original              : 2017:03:07 09:27:46
Create Date                     : 2017:03:07 09:27:46
Sub Sec Time Original           : 00
Sub Sec Time Digitized          : 00
Color Space                     : sRGB
Padding                         : (Binary data 2060 bytes, use -b option to extract)
Compression                     : JPEG (old-style)
X Resolution                    : 96
Y Resolution                    : 96
Resolution Unit                 : inches
Thumbnail Offset                : 4608
Thumbnail Length                : 8169
About                           : uuid:faf5bdd5-ba3d-11da-ad31-d33d75182f1b
Creator Tool                    : Windows Photo Editor 10.0.10011.16384
Image Width                     : 1110
Image Height                    : 765
Encoding Process                : Baseline DCT, Huffman coding
Bits Per Sample                 : 8
Color Components                : 3
Y Cb Cr Sub Sampling            : YCbCr4:2:0 (2 2)
Image Size                      : 1110x765
Megapixels                      : 0.849
Create Date                     : 2017:03:07 09:27:46.00
Date/Time Original              : 2017:03:07 09:27:46.00
Thumbnail Image                 : (Binary data 8169 bytes, use -b option to extract)

Or use PIL

>>> from PIL import Image
>>> from PIL.ExifTags import TAGS
>>>
>>> im = Image.open('ryzsUIKZVUc.jpg')
>>> exif = im._getexif()
>>> data = {}
>>>
>>> for tag, value in exif.items():
...     decoded = TAGS.get(tag, tag)
...     data[decoded] = value
...
>>>
>>> data['Orientation']
8

To fix this, you can before generating a preview, (rotate image) save the picture without this tag.

For example,

def orient(image_path):
    """ Check are this img oriented """
    img = Image.open(image_path)
    # check is has exif data
    if not hasattr(img, '_getexif') or img._getexif() is None:
        return
    # if has information - try rotate img
    orientation = img._getexif().get(0x112)
    rotate_values = {3: 180, 6: 270, 8: 90}
    if orientation in rotate_values:
        img = img.rotate(rotate_values[orientation], expand=True)
    img.save(image_path, quality=100)

Or easier, change the settings THUMBNAIL_ORIENTATION = False. In this case, the image simply stops rotating. And no more black lines are created.


问:
Spring boot with Zuul proxy crashes on Maven, while Gradle works
I have a Spring boot project which is built with Gradle.

I need to migrate it to Maven, which I thought would be easy (should be), but I've encountered an issue in the Zuul depedency, or to be exact: spring-cloud-starter-zuul.

When I run the Spring boot application with the annotation @EnableZuulProxy it produces the following error:

```<code>2017-03-30 00:02:57.521  WARN 11380 --- [ost-startStop-1] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2017-03-30 00:02:57.521  INFO 11380 --- [ost-startStop-1] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2017-03-30 00:02:57.532  INFO 11380 --- [ost-startStop-1] c.netflix.config.DynamicPropertyFactory  : DynamicPropertyFactory is initialized with configuration sources: com.netflix.config.ConcurrentCompositeConfiguration@df85e3e
2017-03-30 00:02:57.556 ERROR 11380 --- [ost-startStop-1] o.s.b.c.embedded.tomcat.TomcatStarter    : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'org.springframework.cloud.netflix.zuul.ZuulConfiguration$ZuulFilterConfiguration': Unsatisfied dependency expressed through field 'filters'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'simpleHostRoutingFilter' defined in org.springframework.cloud.netflix.zuul.ZuulProxyConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter]: Factory method 'simpleHostRoutingFilter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/http/conn/HttpClientConnectionManager
2017-03-30 00:02:57.588  WARN 11380 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
2017-03-30 00:02:57.588 ERROR 11380 --- [           main] o.s.boot.SpringApplication               : Application startup failed
</code>```

The error only occurs on the Maven build, which narrow the problem to the pom.xml file vs build.gradle which does run.

After tinkering with the working build.gradle file, I've managed to produce the error when commenting out this part:

```<code>buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE")
    }
}
apply plugin: 'org.springframework.boot'
</code>```

So the issue is I don't use the plugin in my maven file?

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>aaa</groupId>
    <artifactId>helloZuul</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.4.3.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.4.3.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-io -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-zuul -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
            <version>1.2.6.RELEASE</version>
        </dependency>
    </dependencies>
</project>
</code>```

build.gradle

```<code>group 'aaa'
version '1.0-SNAPSHOT'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'

sourceCompatibility = 1.8

jar {
    baseName = 'gs-rest-service'
    version = '0.1.0'
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile "org.springframework.boot:spring-boot-starter-web:1.4.3.RELEASE"
    compile group: 'org.apache.commons', name: 'commons-io', version: '1.3.2'
    compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-zuul', version: '1.2.6.RELEASE'
}
</code>```

How can I make my maven project run? Or more specifically, what is the purpose of the spring boot gradle plugin?

Any help will be greatly appreciated!

答:
I managed to get it working after a lot of trial and error.

pom.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>aaa</groupId>
    <artifactId>client</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-io -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Brixton.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>
</code>```

Body:
I have a Spring boot project which is built with Gradle.

I need to migrate it to Maven, which I thought would be easy (should be), but I've encountered an issue in the Zuul depedency, or to be exact: spring-cloud-starter-zuul.

When I run the Spring boot application with the annotation @EnableZuulProxy it produces the following error:

2017-03-30 00:02:57.521  WARN 11380 --- [ost-startStop-1] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2017-03-30 00:02:57.521  INFO 11380 --- [ost-startStop-1] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2017-03-30 00:02:57.532  INFO 11380 --- [ost-startStop-1] c.netflix.config.DynamicPropertyFactory  : DynamicPropertyFactory is initialized with configuration sources: com.netflix.config.ConcurrentCompositeConfiguration@df85e3e
2017-03-30 00:02:57.556 ERROR 11380 --- [ost-startStop-1] o.s.b.c.embedded.tomcat.TomcatStarter    : Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message: Error creating bean with name 'org.springframework.cloud.netflix.zuul.ZuulConfiguration$ZuulFilterConfiguration': Unsatisfied dependency expressed through field 'filters'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'simpleHostRoutingFilter' defined in org.springframework.cloud.netflix.zuul.ZuulProxyConfiguration: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter]: Factory method 'simpleHostRoutingFilter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/apache/http/conn/HttpClientConnectionManager
2017-03-30 00:02:57.588  WARN 11380 --- [           main] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.boot.context.embedded.EmbeddedServletContainerException: Unable to start embedded Tomcat
2017-03-30 00:02:57.588 ERROR 11380 --- [           main] o.s.boot.SpringApplication               : Application startup failed

The error only occurs on the Maven build, which narrow the problem to the pom.xml file vs build.gradle which does run.

After tinkering with the working build.gradle file, I've managed to produce the error when commenting out this part:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE")
    }
}
apply plugin: 'org.springframework.boot'

So the issue is I don't use the plugin in my maven file?

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>aaa</groupId>
    <artifactId>helloZuul</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.4.3.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>1.4.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
            <version>1.2.6.RELEASE</version>
        </dependency>
    </dependencies>
</project>

build.gradle

group 'aaa'
version '1.0-SNAPSHOT'

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.3.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'

sourceCompatibility = 1.8

jar {
    baseName = 'gs-rest-service'
    version = '0.1.0'
}

repositories {
    mavenCentral()
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile "org.springframework.boot:spring-boot-starter-web:1.4.3.RELEASE"
    compile group: 'org.apache.commons', name: 'commons-io', version: '1.3.2'
    compile group: 'org.springframework.cloud', name: 'spring-cloud-starter-zuul', version: '1.2.6.RELEASE'
}

How can I make my maven project run? Or more specifically, what is the purpose of the spring boot gradle plugin?

Any help will be greatly appreciated!

Body:
I managed to get it working after a lot of trial and error.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>aaa</groupId>
    <artifactId>client</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-io -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Brixton.SR5</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>


问:
How to get google static map images with QT (C++)
I am trying to use QT to implement an application which download google static map images and show the map on a GUI application. In this way the local saved images can be used when there is no internet access.

I have checked a lot of example using QNetworkAccessManager, QNetworkRequest, QNetworkReply, but it will give back some information like "SSL handshake failed" and I am not able to download the image.

The url to download images is:

```<code>    urlbase = "https://maps.googleapis.com/maps/api/staticmap?center=%f,%f&zoom=%d&maptype=%s&size=%dx%d&format=jpg"
</code>```

Previous I used Python to do the work:

```<code>    result = urllib.urlopen(url).read()
    tile = PIL.Image.open(cStringIO.StringIO(result))
</code>```

which was very easy and convenient.

But when comes to QT and C++, it seems like all need a lot of self-built functions. So is there any easy way to do the job with C++ and QT?

答:
You can implement your gui with QML module and use Map QML type for map.

It supports caching for "offline" features:

For "online" Map plugins, network bandwidth and latency can be major
  contributors to the user's perception of performance. Extensive
  caching is performed to mitigate this, but such mitigation is not
  always perfect. For "offline" plugins, the time spent retrieving the
  stored geographic data and rendering the basic map features can often
  play a dominant role. Some offline plugins may use hardware
  acceleration themselves to (partially) avert this.

Example of map in qml:

Body:
I am trying to use QT to implement an application which download google static map images and show the map on a GUI application. In this way the local saved images can be used when there is no internet access.

I have checked a lot of example using QNetworkAccessManager, QNetworkRequest, QNetworkReply, but it will give back some information like "SSL handshake failed" and I am not able to download the image.

The url to download images is:

    urlbase = "https://maps.googleapis.com/maps/api/staticmap?center=%f,%f&zoom=%d&maptype=%s&size=%dx%d&format=jpg"

Previous I used Python to do the work:

    result = urllib.urlopen(url).read()
    tile = PIL.Image.open(cStringIO.StringIO(result))

which was very easy and convenient.

But when comes to QT and C++, it seems like all need a lot of self-built functions. So is there any easy way to do the job with C++ and QT?


问:
how to set cookie expiration time in angularJs 1.3?
In my application I am using angularJS 1.3, when I using $cookies to store some values I need to set 1 min expiration time of cookie. The angularJs 1.3 $cookies service has not put method to supply expiration time.
this is the code I tried so far.

```<code>var x = new Date();
x.setMinutes(x.getMinutes() + 1);

$cookies['showStartUpScreen'] = value + ';expires=' + x.toGMTString();
</code>```

答:
The ability to set expiration time for cookies was added in 1.4, along with an overhaul of how Angular works with cookies generally. In 1.3 however, you could use plain JS to set the cookie with expiration, as Angular polls for cookie changes.

```<code>  var date = new Date();
  var expireTime = date.getTime() + 5000 // 5 seconds
  date.setTime(expireTime);
  console.log(date)
  document.cookie = 'myFavorite=ok;expires='+date.toGMTString()+';path=/';

  // Retrieve cookie using both vanilla and Angular
  console.log(document.cookie)
  var theCookie = $cookies.myFavorite
  console.log(theCookie)
</code>```

I've set up a proof of concept on CodePen, with a button you can press after 5 seconds to show the cookie does expire as expected.

References:

SO - javascript set cookie with expire time

AngularJS 1.4 API documentation for $cookies

Body:
In my application I am using angularJS 1.3, when I using $cookies to store some values I need to set 1 min expiration time of cookie. The angularJs 1.3 $cookies service has not put method to supply expiration time.
this is the code I tried so far.

var x = new Date();
x.setMinutes(x.getMinutes() + 1);

$cookies['showStartUpScreen'] = value + ';expires=' + x.toGMTString();

Body:
The ability to set expiration time for cookies was added in 1.4, along with an overhaul of how Angular works with cookies generally. In 1.3 however, you could use plain JS to set the cookie with expiration, as Angular polls for cookie changes.

  var date = new Date();
  var expireTime = date.getTime() + 5000 // 5 seconds
  date.setTime(expireTime);
  console.log(date)
  document.cookie = 'myFavorite=ok;expires='+date.toGMTString()+';path=/';

  // Retrieve cookie using both vanilla and Angular
  console.log(document.cookie)
  var theCookie = $cookies.myFavorite
  console.log(theCookie)

I've set up a proof of concept on CodePen, with a button you can press after 5 seconds to show the cookie does expire as expected.

References:

SO - javascript set cookie with expire time

AngularJS 1.4 API documentation for $cookies


问:
Getting image path in public folder in laravel
I'm making direction using this method to upload my image

```<code> mkdir(public_path().'/website/'.$path,0777, true);
</code>```

It's supposed to create it on the root folder (Public_html) , but i found it created on new folder with name (public ) , so now i can't get the path of the image using this code

```<code> <img src="{{url('public/website/'.$file->path.$file->file)}}"  />
</code>```

how to get the correct path of the image or even create the folder on the public_html root path ?

答:
You try this to get your image content

```<code>  <img src="<?php echo asset('/').'public/'.$path.$file->file;  ?>"  />
</code>```

Body:
I'm making direction using this method to upload my image

 mkdir(public_path().'/website/'.$path,0777, true);

It's supposed to create it on the root folder (Public_html) , but i found it created on new folder with name (public ) , so now i can't get the path of the image using this code

 path.$file->file)}}"  />

how to get the correct path of the image or even create the folder on the public_html root path ?

Body:
You try this to get your image content

  <img src="<?php echo asset('/').'public/'.$path.$file->file;  ?>"  />


问:
Silverstripe SQLUpdate multiple rows
I have the following code (edited for simplicity's sake but my goal is to update the AccountID of multiple devices) :

```<code>$devices = Device::get();
if ($devices && $devices->count())
{
    foreach ($devices as $device)
    {
        $device->AccountID = 5;
        $device->write();
    }
}
</code>```

My problem is the above code can take a lot of time before execution is done especially if there are 30 or more devices. I was thinking of just having a single query and not having to call the write() function all the time. Let's say I have the array below where ID is the ID of the device to be updated and the AccountID is the field to be updated. Is it possible to have only one query with SQLUpdate? And how?

```<code>$values = array(
    array("ID" => 1, "AccountID" => 2),
    array("ID" => 2, "AccountID" => 12),
    array("ID" => 3, "AccountID" => 22),
    array("ID" => 4, "AccountID" => 32),
)
</code>```

From https://docs.silverstripe.org/en/3/developer_guides/model/sql_query/ I can see that inserting multiple rows is possible with SQLInsert but how about for SQLUpdate? If not possible, do you have any suggestions on how can I implement this without calling write() for every device?

Thanks a lot!

答:
No, you can't update multiple rows using SQLUpdate. You could write a raw query, something similar to this answer and run it using DB::query.

Calling write on a DataObject is quite different from just performing an SQL update. write will write to the current stage (for versioning), perform validation and also trigger onBeforeWrite and onAfterWrite hooks.

If you really just need the DB update, it will be faster to run SQLUpdate queries instead of the write. So that could gain you some performance.

And for extra performance, I suggest you also use a raw SQLSelect instead of Devices::get() to get the values you need instead of running through the ORM.

Title: Silverstripe SQLUpdate multiple rows

Body:
I have the following code (edited for simplicity's sake but my goal is to update the AccountID of multiple devices) :

$devices = Device::get();
if ($devices && $devices->count())
{
    foreach ($devices as $device)
    {
        $device->AccountID = 5;
        $device->write();
    }
}

My problem is the above code can take a lot of time before execution is done especially if there are 30 or more devices. I was thinking of just having a single query and not having to call the write() function all the time. Let's say I have the array below where ID is the ID of the device to be updated and the AccountID is the field to be updated. Is it possible to have only one query with SQLUpdate? And how?

$values = array(
    array("ID" => 1, "AccountID" => 2),
    array("ID" => 2, "AccountID" => 12),
    array("ID" => 3, "AccountID" => 22),
    array("ID" => 4, "AccountID" => 32),
)

From https://docs.silverstripe.org/en/3/developer_guides/model/sql_query/ I can see that inserting multiple rows is possible with SQLInsert but how about for SQLUpdate? If not possible, do you have any suggestions on how can I implement this without calling write() for every device?

Thanks a lot!


问:
Using regex in SQL
I've run into a problem where I cannot go any longer on my own.
I currently have a database which basically lists my cellphone with different applications on it.

The applications are listed with the status within the same database column which means that i separate the application from the status with a ";" and i separate the different applications with a ",".

Example :

```<code>ipboard,4.83->6.3,Running;testAcap,6.9-0,Stopped;
ipboard,2.3333->5.366,Stopped;Videostream,1.2,Stopped;
</code>```

Now, how would i go about finding all the ipboards that currently as an app is stopped? As you see, the string before the status can vary in lenght due to the different versions. And I do not want a list of everything that is stopped, just the ipboard in this case.

My crappy query so far that selects all strings with ipboard in them at all(All of them doesnt have it) :

```<code>select *
  from acaps
  where acaps like '%ipb%'
</code>```

For me the next logical thing to do would be something like :

```<code>select *
  from acaps
  where acaps like '%ipb%'
  and subshitblabla where "Stopped" after the "," after the ipboard string.
</code>```

Anyone knows how to get this working?

答:
Assuming thar col_name is the coumn taht you wnat use for filter If i remeber correctly you can do it in the same like</p>

```<code> select *
  from acaps
  where acaps.col_name like 'ipb%Stopped'
</code>```

Title: Using regex in SQL

Body:
I've run into a problem where I cannot go any longer on my own.
I currently have a database which basically lists my cellphone with different applications on it.

The applications are listed with the status within the same database column which means that i separate the application from the status with a ";" and i separate the different applications with a ",".

Example :

ipboard,4.83->6.3,Running;testAcap,6.9-0,Stopped;
ipboard,2.3333->5.366,Stopped;Videostream,1.2,Stopped;

Now, how would i go about finding all the ipboards that currently as an app is stopped? As you see, the string before the status can vary in lenght due to the different versions. And I do not want a list of everything that is stopped, just the ipboard in this case.

My crappy query so far that selects all strings with ipboard in them at all(All of them doesnt have it) :

select *
  from acaps
  where acaps like '%ipb%'

For me the next logical thing to do would be something like :

select *
  from acaps
  where acaps like '%ipb%'
  and subshitblabla where "Stopped" after the "," after the ipboard string.

Anyone knows how to get this working?

Body:
Assuming thar col_name is the coumn taht you wnat use for filter If i remeber correctly you can do it in the same like

 select *
  from acaps
  where acaps.col_name like 'ipb%Stopped'


问:
json Deserialization changes date
Hey I'm getting diffrent date after deserialization.
before the date is 30.03.2017, and after the date is 29.03.2017.

before

after

Json string (stam value):

```<code>[{"a_id":1,"auctionname":"computer","deadLine":"\/Date(1490821200000)\/"},{"a_id":2,"auctionname":"keyboard","deadLine":"\/Date(1490821200000)\/"},{"a_id":3,"auctionname":"mouse","deadLine":"\/Date(1490821200000)\/"}]
</code>```

my code:

```<code>[Test]
    public void GetAuctionsByJson_works()
    {
        Mock<IAuctionRespository> mockAuction = new Mock<IAuctionRespository>();
        mockAuction.Setup(m => m.Auctions).Returns(new Auction[]
            {
                new Auction { a_id=1, auctionname="computer", deadLine=DateTime.Today},
                new Auction { a_id=2, auctionname="keyboard", deadLine=DateTime.Today},
                new Auction { a_id=3, auctionname="mouse", deadLine=DateTime.Today}
            }.AsQueryable());
        CustomerController controller = new CustomerController(mockAuction.Object);
        var actual = controller.GetAuctionsByJson() as JsonResult;
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string stam = serializer.Serialize(actual.Data);
        List<Auction> result = serializer.Deserialize<List<Auction>>(serializer.Serialize(actual.Data));

        //List<Auction> result = ser.ReadObject(actual);// as List<Auction>; //null --> decirialized
    }
</code>```

答:
There are multiple issues.

First, the format \/Date(1490821200000)\/ isn't used anymore. It was used in the early 2000s when there was no defacto standard to represen time in AJAX calls. The number is an escaped number of ticks in UTC. The defacto standard is ISO8601, 2017-03-30T00:00:00Z.

Second JavascriptSerializer isn't used anymore. It's been replaced by Json.NET even in ASP.NET Web API. I'm not sure if it understands ISO8601 or not. It isn't used anyway, except in legacy code.

Finally, DateTime.Today returns the local time. DateTime.Today in a +3 timezone is 30/3/2017 12:00:00 am but 29/3/2017 09:00:00 pmin UTC. Its .Kind property is Local. Even Json.NET would serialize this as 2017-03-30T00:00:00+03:00

To get the current date in UTC, one should use DateTime.UtcNow.Date. This has a Kind value of Utc. Json.NET will serialize this as 2017-03-30T00:00:00Z

Try changind all calls to

```<code>DateTime.Today
</code>```

with

```<code>DateTime.UtcNow.Date
</code>```

Title: json Deserialization changes date

Body:
Hey I'm getting diffrent date after deserialization.
before the date is 30.03.2017, and after the date is 29.03.2017.

before

after

Json string (stam value):

[{"a_id":1,"auctionname":"computer","deadLine":"\/Date(1490821200000)\/"},{"a_id":2,"auctionname":"keyboard","deadLine":"\/Date(1490821200000)\/"},{"a_id":3,"auctionname":"mouse","deadLine":"\/Date(1490821200000)\/"}]

my code:

[Test]
    public void GetAuctionsByJson_works()
    {
        Mock<IAuctionRespository> mockAuction = new Mock<IAuctionRespository>();
        mockAuction.Setup(m => m.Auctions).Returns(new Auction[]
            {
                new Auction { a_id=1, auctionname="computer", deadLine=DateTime.Today},
                new Auction { a_id=2, auctionname="keyboard", deadLine=DateTime.Today},
                new Auction { a_id=3, auctionname="mouse", deadLine=DateTime.Today}
            }.AsQueryable());
        CustomerController controller = new CustomerController(mockAuction.Object);
        var actual = controller.GetAuctionsByJson() as JsonResult;
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        string stam = serializer.Serialize(actual.Data);
        List<Auction> result = serializer.Deserialize<List<Auction>>(serializer.Serialize(actual.Data));

        //List<Auction> result = ser.ReadObject(actual);// as List<Auction>; //null --> decirialized
    }

Body:
There are multiple issues.

First, the format \/Date(1490821200000)\/ isn't used anymore. It was used in the early 2000s when there was no defacto standard to represen time in AJAX calls. The number is an escaped number of ticks in UTC. The defacto standard is ISO8601, 2017-03-30T00:00:00Z.

Second JavascriptSerializer isn't used anymore. It's been replaced by Json.NET even in ASP.NET Web API. I'm not sure if it understands ISO8601 or not. It isn't used anyway, except in legacy code.

Finally, DateTime.Today returns the local time. DateTime.Today in a +3 timezone is 30/3/2017 12:00:00 am but 29/3/2017 09:00:00 pmin UTC. Its .Kind property is Local. Even Json.NET would serialize this as 2017-03-30T00:00:00+03:00

To get the current date in UTC, one should use DateTime.UtcNow.Date. This has a Kind value of Utc. Json.NET will serialize this as 2017-03-30T00:00:00Z

Try changind all calls to

DateTime.Today

with

DateTime.UtcNow.Date


问:
Elixir's module attributes in Phoenix production
As far as I know module attributes evaluated during compilation time. I was trying to follow this post about mocking API in Elixir:

```<code>defmodule Example.User do

  @github_api Application.get_env(:example, :github_api)

  def get(username) when is_binary(username) do
    @github_api.make_request(:get, "/users/#{username}")
  end
end
</code>```

And I'm wondering if that's gonna work in production at all. As far as I understand when this module is compiled there's no access to the Application. So my question is: can I use module attributes to store some config values that come from Application.get_env?

答:
You absolutely can. As long as the application was compiled using MIX_ENV specified to environment you want the application running under, and as long as that call evaluates to what you expect for that environment, it'll all work fine.

For a deeper look at how module attributes are affected by compilation for an almost identical case as what you've described, take a look at this blog post here.

Body:
As far as I know module attributes evaluated during compilation time. I was trying to follow this post about mocking API in Elixir:

defmodule Example.User do

  @github_api Application.get_env(:example, :github_api)

  def get(username) when is_binary(username) do
    @github_api.make_request(:get, "/users/#{username}")
  end
end

And I'm wondering if that's gonna work in production at all. As far as I understand when this module is compiled there's no access to the Application. So my question is: can I use module attributes to store some config values that come from Application.get_env?


问:
How to separate letters and digits from a string in JavaScript
I have a string which is combination of letters and digits. For my application I have to separate a string with letters and digits: ex:If my string is "12jan" i hav to get "12" "jan" seperately..</p>

答:
You can always do this if str is your string:

```<code>var digits = str.replace(/\D/g, ""),
    letters = str.replace(/[^a-z]/gi, "");
</code>```

Essentially, what this code does is replace all of the characters that you do not want with the empty string.

\D and [^a-z] are character classes that represent, respectively, all the non-digits and all the non-letters. The g at the end of the two expressions makes them replace all occurrences of the pattern. The i make it case-insensitive, keeping both lower and upper case letters.

ContentLicense: CC BY-SA 2.5

Body:
You can always do this if str is your string:

var digits = str.replace(/\D/g, ""),
    letters = str.replace(/[^a-z]/gi, "");

Essentially, what this code does is replace all of the characters that you do not want with the empty string.

\D and [^a-z] are character classes that represent, respectively, all the non-digits and all the non-letters. The g at the end of the two expressions makes them replace all occurrences of the pattern. The i make it case-insensitive, keeping both lower and upper case letters.


问:
Angularjs show and hide result based on radio button selection
I am trying to show and hide a value based on the radio button selection. I am doing this on ng-click of radio button. It is not working for me

Here is the HTML and Angular js code

```<code>**HTML Code:**
<div ng-app="ssbApp" ng-controller="ssbCtrl">
    <input type="radio" name="showHideExample" ng-model="showHideExample" value="single" ng-click="showHideTest=true">Show
    <input type="radio" name="showHideExample" ng-model="showHideExample" value="multi" ng-click="showHideTest=false">hide
    <div ng-snow="showHideTest" ng-model="showHideTest">Test hide and show</div>
</div>

**Angular JS Code:**
var ssbApp = angular.module("ssbApp", []);
ssbApp.controller('ssbCtrl', function ($scope, $http) {
   $scope.showHideTest = false;
});
</code>```

答:
HTML Code Code:

Try this example, it will work.

```<code><div ng-app="ssbApp" ng-controller="ssbCtrl">
    <input type="radio" name="showHideExample" ng-model="showHideExample"   ng-value="true">Show
    <input type="radio" name="showHideExample" ng-model="showHideExample" ng-value="">hide
    <div ng-snow="(showHideExample ==true)?true:false">Test hide and show</div>
</div>
</code>```

Angular JS Code:

```<code>var ssbApp = angular.module("ssbApp", []);
ssbApp.controller('ssbCtrl', function ($scope, $http) {
  // $scope.showHideTest = false;
});
</code>```

Body:
I am trying to show and hide a value based on the radio button selection. I am doing this on ng-click of radio button. It is not working for me

Here is the HTML and Angular js code

**HTML Code:**

    <input type="radio" name="showHideExample" ng-model="showHideExample" value="single" ng-click="showHideTest=true">Show
    <input type="radio" name="showHideExample" ng-model="showHideExample" value="multi" ng-click="showHideTest=false">hide

Test hide and show

**Angular JS Code:**
var ssbApp = angular.module("ssbApp", []);
ssbApp.controller('ssbCtrl', function ($scope, $http) {
   $scope.showHideTest = false;
});

Body:
HTML Code Code:

Try this example, it will work.

<div ng-app="ssbApp" ng-controller="ssbCtrl">
    <input type="radio" name="showHideExample" ng-model="showHideExample"   ng-value="true">Show
    <input type="radio" name="showHideExample" ng-model="showHideExample" ng-value="">hide
    <div ng-snow="(showHideExample ==true)?true:false">Test hide and show</div>
</div>

Angular JS Code:

var ssbApp = angular.module("ssbApp", []);
ssbApp.controller('ssbCtrl', function ($scope, $http) {
  // $scope.showHideTest = false;
});


问:
How to manipulate Bitbucket repository with token?
I followed this documentation to get a token value and a token secret from bitbucket:

https://confluence.atlassian.com/display/BITBUCKET/OAuth+on+Bitbucket

After that I want to push/pull to a given repo by using that token.

At Github I can use the token like this way:
https://help.github.com/articles/git-automation-with-oauth-tokens#step-2-clone-a-repository

My question is how can I use this kind of http authorization at bitbucket (mercurial/git)?

答:
To manipulate Bitbucket repository with token:

First you create an "Oauth" in access management section of your bitbucket account setting. This gives you a "Key" and a "Secret". You have done this bit.

Now using these Key and Secret you ask Bitbucket for a token. In my case I made a http request to https://bitbucket.org/site/oauth2/access_token. I could do it with Curl or some Ajax library like this:

```<code>curl -X POST -u "yourKeyHere:yourSecretHere"  https://bitbucket.org/site/oauth2/access_token -d  grant_type=client_credentials
</code>```

alternatively, my http request was like this (using superagent in node) with my Content-Type set to application/x-www-form-urlencoded you can use postman:

```<code>request.post("https://yourKeyHere:yourSecretHere@bitbucket.org/site/oauth2/      access_token").send('grant_type=client_credentials');`
</code>```

the result is like this:

```<code>{
   "access_token": "blah blah blah HXAhrfr8YeIqGTpkyFio=",
   "scopes": "pipeline snippet issue pullrequest project team account",
   "expires_in": 3600,
   "refresh_token": "hsadgsadvkQ",
   "token_type": "bearer"
}
</code>```

Now that you have the "access_token", clone a private repo with it. But the url to your repo should be like this (keep the bracket around token):

```<code>https://x-token-auth:{tokenHere}@bitbucket.org/yourRepoOwnerHere/RepoNameHere.git
</code>```

Body:
To manipulate Bitbucket repository with token:

First you create an "Oauth" in access management section of your bitbucket account setting. This gives you a "Key" and a "Secret". You have done this bit.

Now using these Key and Secret you ask Bitbucket for a token. In my case I made a http request to https://bitbucket.org/site/oauth2/access_token. I could do it with Curl or some Ajax library like this:

curl -X POST -u "yourKeyHere:yourSecretHere"  https://bitbucket.org/site/oauth2/access_token -d  grant_type=client_credentials

alternatively, my http request was like this (using superagent in node) with my Content-Type set to application/x-www-form-urlencoded you can use postman:

request.post("https://yourKeyHere:yourSecretHere@bitbucket.org/site/oauth2/      access_token").send('grant_type=client_credentials');`

the result is like this:

{
   "access_token": "blah blah blah HXAhrfr8YeIqGTpkyFio=",
   "scopes": "pipeline snippet issue pullrequest project team account",
   "expires_in": 3600,
   "refresh_token": "hsadgsadvkQ",
   "token_type": "bearer"
}

Now that you have the "access_token", clone a private repo with it. But the url to your repo should be like this (keep the bracket around token):

https://x-token-auth:{tokenHere}@bitbucket.org/yourRepoOwnerHere/RepoNameHere.git


问:
How to separate letters and digits from a string in php
I have a string which is combination of letters and digits. For my application i have to separate a string with letters and digits:  ex:If my string is "12jan" i hav to get "12" "jan" separately..</p>

答:
You can make use of preg_split to split your string at the point which is preceded by digit and is followed by letters as:

```<code>$arr = preg_split('/(?<=[0-9])(?=[a-z]+)/i',$str);
</code>```

Code in Action

```<code><?php
$str = '12jan';
$arr = preg_split('/(?<=[0-9])(?=[a-z]+)/i',$str);
print_r($arr);
</code>```

Result:

```<code>Array
(
    [0] => 12
    [1] => jan
)
</code>```

Body:
You can make use of preg_split to split your string at the point which is preceded by digit and is followed by letters as:

$arr = preg_split('/(?<=[0-9])(?=[a-z]+)/i',$str);

Code in Action

<?php
$str = '12jan';
$arr = preg_split('/(?<=[0-9])(?=[a-z]+)/i',$str);
print_r($arr);

Result:

Array
(
    [0] => 12
    [1] => jan
)


问:
How to change the value of array element in list of arrays? (C#)
I have list of arrays of labels and I want to change visibility of some label in some array in list by index. Tell me, please, how can I do that?</p>

答:
is this what you want:

```<code>    foreach (var l in list)
        if (l.Name.Equals("test", StringComparison.OrdinalIgnoreCase))
            l.Visible = false;
</code>```

or:

```<code>    foreach (var l in list)
        if (l.TabIndex == 1)
            l.Visible = false;
</code>```

Body:
is this what you want:

    foreach (var l in list)
        if (l.Name.Equals("test", StringComparison.OrdinalIgnoreCase))
            l.Visible = false;

or:

    foreach (var l in list)
        if (l.TabIndex == 1)
            l.Visible = false;


问:
modprobe: ERROR: could not insert 'tun': Unknown symbol in module, or unknown parameter (see dmesg)
My server runs openvpn client, it was working fine.
But after a server reboot, I couldn't startup the openvpn client.

openvpn log says:

```<code>ERROR: Cannot open TUN/TAP dev /dev/net/tun: No such device (errno=19)
</code>```

but

```<code>lyq@server:~$ ls /dev/net/tun -l
crw-rw-rw- 1 root root 10, 200 Feb 27 13:44 /dev/net/tun
</code>```

After some searching, I found this command:

```<code>lyq@server:~$ sudo modprobe tun
modprobe: ERROR: could not insert 'tun': Unknown symbol in module, or unknown parameter (see dmesg)
</code>```

and the 'dmesg' says:

```<code>[  991.073261] tun: Unknown symbol __sk_attach_filter (err 0)
[  991.073347] tun: Unknown symbol __sk_detach_filter (err 0)
</code>```

I need help, thank you very much.

答:
The "No such device" message means that no device driver with the major and minor numbers of the device node (10 and 100 in your case) exists. The reason for that is most likely that the "tun" driver failed to load, and the reason for that appears to be that the __sk_attach_filter and __sk_detach_filter symbols do not exist in the kernel you're running.

Since you say this happened after a reboot, it is likely that the kernel image was upgraded some time before that reboot, and this is the first time the system boots with the new kernel. Missing symbol errors tend to be due to the module versions not matching the kernel version.

Did you build the kernel yourself, or did you install it from som package manager? If you installed it by yourself, try again and make sure to run "make modules_install" (see e.g. https://unix.stackexchange.com/questions/20864/what-happens-in-each-step-of-the-linux-kernel-building-process for information about the kernel build targets). If you installed via a package manager, check if there some kernel modules package or tun driver package that needs to be upgraded.

Body:
My server runs openvpn client, it was working fine.
But after a server reboot, I couldn't startup the openvpn client.

openvpn log says:

ERROR: Cannot open TUN/TAP dev /dev/net/tun: No such device (errno=19)

but

lyq@server:~$ ls /dev/net/tun -l
crw-rw-rw- 1 root root 10, 200 Feb 27 13:44 /dev/net/tun

After some searching, I found this command:

lyq@server:~$ sudo modprobe tun
modprobe: ERROR: could not insert 'tun': Unknown symbol in module, or unknown parameter (see dmesg)

and the 'dmesg' says:

[  991.073261] tun: Unknown symbol __sk_attach_filter (err 0)
[  991.073347] tun: Unknown symbol __sk_detach_filter (err 0)

I need help, thank you very much.


问:
how to stretch listviewitem in listview
developers.

I try to stretch listview item in horizontal orientation.
I do reset ItemContainerStyle ,and the horizentalalignment is strech.
Here is all code in the MainPage.xaml.

```<code><Grid x:Name="rootGrid"
      HorizontalAlignment="Stretch"
      MinWidth="320"
      MaxWidth="480"
      Width="Auto">
    <ListView x:Name="infoFlowListView"
              MinWidth="320"
              MaxWidth="480"
              Width="Auto"
              HorizontalAlignment="Stretch">
        <ListView.ItemTemplate>
            <DataTemplate>
                <local:MyUserControl1 MinWidth="300" HorizontalAlignment="Stretch"></local:MyUserControl1>
            </DataTemplate>
        </ListView.ItemTemplate>
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                <Setter Property="HorizontalAlignment" Value="Stretch"></Setter>
            </Style>
        </ListView.ItemContainerStyle>
    </ListView>
</Grid>
</code>```

Here is all code in MainPage.xaml.cs

```<code>public MainPage()
    {
        var items = new List<MyUserControl1>();
        for (int i = 0; i < 50; i++)
        {
            items.Add(new MyUserControl1());
        }
        this.InitializeComponent();
        infoFlowListView.ItemsSource = items;
    }
</code>```

Here is all code in MyUserControl.xaml

```<code><Grid>
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"></ColumnDefinition>
    <ColumnDefinition Width="4*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="*"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="8"></RowDefinition>
</Grid.RowDefinitions>

<Ellipse Width="60" Height="60"
         Grid.Column="0" Grid.Row="0" Grid.RowSpan="3"
         VerticalAlignment="Center"
         HorizontalAlignment="Center"
         Stretch="Uniform">
    <Ellipse.Fill>
        <ImageBrush ImageSource="Assets/1.png"></ImageBrush>
    </Ellipse.Fill>
</Ellipse>

<RelativePanel x:Name="topRelativePanel"
               Grid.Column="1" Grid.Row="0"
               HorizontalAlignment="Stretch">
    <TextBlock Text="TestName"
               VerticalAlignment="Bottom"
               RelativePanel.AlignLeftWithPanel="True"
               FontSize="12"
               HorizontalAlignment="Stretch"></TextBlock>
    <TextBlock Text="Author"
               VerticalAlignment="Bottom"
               RelativePanel.AlignRightWithPanel="True"
               FontSize="12"
               HorizontalAlignment="Stretch"
               Margin="0,0,8,0"></TextBlock>
</RelativePanel>

<TextBlock x:Name="nameTextBlock"
           Grid.Column="1" Grid.Row="1"
           Text="Name"
           TextTrimming="WordEllipsis"
           VerticalAlignment="Stretch"
           HorizontalAlignment="Stretch"
           FontSize="18" >
</TextBlock>

<Grid x:Name="bottomGrid"
      Grid.Column="1" Grid.Row="2"
      VerticalAlignment="Top"
      HorizontalAlignment="Stretch">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="3*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Column="0"
               HorizontalAlignment="Stretch"
               Text="90"></TextBlock>
    <TextBlock Grid.Column="1"
               HorizontalAlignment="Stretch"
               Text="48"></TextBlock>
    <TextBlock Grid.Column="2"
               HorizontalAlignment="Stretch"
               Text="20170330 08:33"
               Margin="0,0,0,0"></TextBlock>
</Grid>

<Border Background="LightGray"
        VerticalAlignment="Stretch"
        HorizontalAlignment="Stretch"
        Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2"></Border>
</code>```

I test these code on 6inch emulator, and I add a screenshot of this example.

And the mobile emulators don't have the same result.
Here are different emulator screenshots.
4inch
screen shot of example
The right side of these screenshots are different.

答:
I try to stretch listview item in horizontal orientation.

You need to set the HorizontalContentAlignment property for the ListViewItem, not the HorizontalAlignment. With the following code the content of ListViewItem will stretch.

```<code><ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <Setter Property="HorizontalContentAlignment"  Value="Stretch"></Setter>
    </Style>
</ListView.ItemContainerStyle>
</code>```

The default ListViewItem style and template doesn't open the HorizontalAlignment setter  but HorizontalContentAlignment.

Title: how to stretch listviewitem in listview

Body:
developers.

I try to stretch listview item in horizontal orientation.
I do reset ItemContainerStyle ,and the horizentalalignment is strech.
Here is all code in the MainPage.xaml.

<Grid x:Name="rootGrid"
      HorizontalAlignment="Stretch"
      MinWidth="320"
      MaxWidth="480"
      Width="Auto">
    <ListView x:Name="infoFlowListView"
              MinWidth="320"
              MaxWidth="480"
              Width="Auto"
              HorizontalAlignment="Stretch">
        <ListView.ItemTemplate>
            <DataTemplate>
                <local:MyUserControl1 MinWidth="300" HorizontalAlignment="Stretch"></local:MyUserControl1>
            </DataTemplate>
        </ListView.ItemTemplate>
        <ListView.ItemContainerStyle>

        </ListView.ItemContainerStyle>
    </ListView>
</Grid>

Here is all code in MainPage.xaml.cs

public MainPage()
    {
        var items = new List<MyUserControl1>();
        for (int i = 0; i < 50; i++)
        {
            items.Add(new MyUserControl1());
        }
        this.InitializeComponent();
        infoFlowListView.ItemsSource = items;
    }

Here is all code in MyUserControl.xaml

<Grid>
<Grid.ColumnDefinitions>
    <ColumnDefinition Width="*"></ColumnDefinition>
    <ColumnDefinition Width="4*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="*"></RowDefinition>
    <RowDefinition Height="Auto"></RowDefinition>
    <RowDefinition Height="8"></RowDefinition>
</Grid.RowDefinitions>

<Ellipse Width="60" Height="60"
         Grid.Column="0" Grid.Row="0" Grid.RowSpan="3"
         VerticalAlignment="Center"
         HorizontalAlignment="Center"
         Stretch="Uniform">
    <Ellipse.Fill>
        <ImageBrush ImageSource="Assets/1.png"></ImageBrush>
    </Ellipse.Fill>
</Ellipse>

<RelativePanel x:Name="topRelativePanel"
               Grid.Column="1" Grid.Row="0"
               HorizontalAlignment="Stretch">
    <TextBlock Text="TestName"
               VerticalAlignment="Bottom"
               RelativePanel.AlignLeftWithPanel="True"
               FontSize="12"
               HorizontalAlignment="Stretch"></TextBlock>
    <TextBlock Text="Author"
               VerticalAlignment="Bottom"
               RelativePanel.AlignRightWithPanel="True"
               FontSize="12"
               HorizontalAlignment="Stretch"
               Margin="0,0,8,0"></TextBlock>
</RelativePanel>

<TextBlock x:Name="nameTextBlock"
           Grid.Column="1" Grid.Row="1"
           Text="Name"
           TextTrimming="WordEllipsis"
           VerticalAlignment="Stretch"
           HorizontalAlignment="Stretch"
           FontSize="18" >
</TextBlock>

<Grid x:Name="bottomGrid"
      Grid.Column="1" Grid.Row="2"
      VerticalAlignment="Top"
      HorizontalAlignment="Stretch">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="*"></ColumnDefinition>
        <ColumnDefinition Width="3*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <TextBlock Grid.Column="0"
               HorizontalAlignment="Stretch"
               Text="90"></TextBlock>
    <TextBlock Grid.Column="1"
               HorizontalAlignment="Stretch"
               Text="48"></TextBlock>
    <TextBlock Grid.Column="2"
               HorizontalAlignment="Stretch"
               Text="20170330 08:33"
               Margin="0,0,0,0"></TextBlock>
</Grid>

<Border Background="LightGray"
        VerticalAlignment="Stretch"
        HorizontalAlignment="Stretch"
        Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2"></Border>

I test these code on 6inch emulator, and I add a screenshot of this example.

And the mobile emulators don't have the same result.
Here are different emulator screenshots.
4inch
screen shot of example
The right side of these screenshots are different.

Body:
I try to stretch listview item in horizontal orientation.

You need to set the HorizontalContentAlignment property for the ListViewItem, not the HorizontalAlignment. With the following code the content of ListViewItem will stretch.

<ListView.ItemContainerStyle>
    <Style TargetType="ListViewItem">
        <Setter Property="HorizontalContentAlignment"  Value="Stretch"></Setter>
    </Style>
</ListView.ItemContainerStyle>

The default ListViewItem style and template doesn't open the HorizontalAlignment setter  but HorizontalContentAlignment.


问:
MongoDB insert \u0000 after each character in string field?
I am just started mongodb and facing issue when saving XML in string field. it add '\u0000' with each character in xml file. like

"\u0000?\u0000x\u0000m\u0000l\u0000 \u0000v\u0000e\u0000r\u0000s\u0000i\u0000o\u0000n

I need to save this XML as it is without JSON 0r BSON conversion in string field.

答:
Till the time, I found a query to get xml back in correct format.</p>

```<code>db.Test.find({"data":"XYZ"}).forEach(function(doc){
         var xml = doc.data.replace(/\u0000/g,"");
         print(xml);
})
</code>```

Body:
Till the time, I found a query to get xml back in correct format.

db.Test.find({"data":"XYZ"}).forEach(function(doc){
         var xml = doc.data.replace(/\u0000/g,"");
         print(xml);
})


问:
Deleting a table row from button click
The following code that I typed is used to add or delete rows in an html table. When I click the add button without any problem, but when I click the delete button though I want to delete a particular row I am unable to. I get an alert message stating:

"can not read property `onclick` of null "

How can I rectify this issue?

```<code><HTML>
  <HEAD>
    <TITLE> Add/Remove dynamic rows in HTML table </TITLE>
    <SCRIPT language="javascript">
      function addRow(tableID) {

        var table = document.getElementById(tableID);

        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);

        var colCount = table.rows[0].cells.length;

        for (var i = 0; i < colCount; i++) {

          var newcell = row.insertCell(i);

          newcell.innerHTML = table.rows[0].cells[i].innerHTML;
          //alert(newcell.childNodes);
          switch (newcell.childNodes[0].type) {
            case "text":
              newcell.childNodes[0].value = "";
              break;
            case "checkbox":
              newcell.childNodes[0].checked = false;
              break;
            case "select-one":
              newcell.childNodes[0].selectedIndex = 0;
              break;
          }
        }
      }

      function deleteRow(tableID) {
        try {
          var table = document.getElementById(tableID);
          var rowCount = table.rows.length;

          for (var i = 0; i < rowCount; i++) {
            var row = table.rows[i];
            var chkbox = row.cells[0].childNodes[0];
            if (document.getElementById('button').onclick == true) {
              if (rowCount <= 1) {
                alert("Cannot delete all the rows.");
                break;
              }
              table.deleteRow(i);
              rowCount--;
              i--;
            }

          }
        } catch (e) {
          alert(e);
        }
      }
    </SCRIPT>
  </HEAD>

  <BODY>
    <INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

    <TABLE id="dataTable" width="350px" border="1">
      <TR>

        <TD>
          <INPUT type="button" name="button" value=delete id=delete onclick="deleteRow('dataTable')">
        </TD>

      </TR>
    </TABLE>
  </BODY>
</HTML>
</code>```

答:
```<code> <div class="table-responsive">
                                      <table class="table" id="testTable">
                                        <thead>
                                          <tr>
                                            <th>Col1</th>
                                            <th>Col2</th>
                                            <th>Type</th>
                                            <th>Remove</th>
                                          </tr>
                                        </thead>
                                        <tbody>
                                          <tr>
                                            <td><input type="text" id="mainScript"  name="mainScript"></td>
                                            <td><input type="text" id="rollBackScript"  name="rollBackScript"></td>
                                            <td><select name="type" id ="type" >
                                                      <option value="Automated" selected >Automated</option>
                                                      <option value="Manual" >Manual</option>
                                                </select>
                                            </td>
                                            <td><input type="button" class="btn btn-danger" value="Delete" onclick="deleteRow(this);"></td>
                                          </tr>
                                        </tbody>
                                      </table>
                                      </div>
                    </div>

                    <div class="row" align="left">
                    <input type="button"  class="btn btn-success"  value="Add Row" onclick="addRow('scriptsTable')" />
                    </div>
</code>```

JavaScript functions

```<code><script>

    function addRow(tableId) {
    var table = document.getElementById(tableId);
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);
        var colCount = table.rows[1].cells.length;
        for(var i=0; i<colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.innerHTML = table.rows[1].cells[i].innerHTML;
            //alert(newcell.childNodes);
            switch(newcell.childNodes[0].type) {
                case "text":
                        newcell.childNodes[0].value = "";
                        break;
                case "checkbox":
                        newcell.childNodes[0].checked = false;
                        break;
                case "select-one":
                        newcell.childNodes[0].selectedIndex = 0;
                        break;
                case "button":
                    newcell.childNodes[0].value = "Delete";
                    break;
            }
        }
    }

    function deleteRow(deleteBtn) {

        var table = document.getElementById('scriptsTable');

         if(table.rows.length <= 2){
                alert("Cannot delete all the rows.");
                return;
            }
        if (typeof(deleteBtn) == "object") {
            $(deleteBtn).closest("tr").remove();
        } else {
            return false;
        }
        }
</script>
</code>```

Title: Deleting a table row from button click

Body:
The following code that I typed is used to add or delete rows in an html table. When I click the add button without any problem, but when I click the delete button though I want to delete a particular row I am unable to. I get an alert message stating:

"can not read property `onclick` of null "

How can I rectify this issue?

    <TITLE> Add/Remove dynamic rows in HTML table </TITLE>

    <INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />

          <INPUT type="button" name="button" value=delete id=delete onclick="deleteRow('dataTable')">

Body:
 <div class="table-responsive">
                                      <table class="table" id="testTable">
                                        <thead>
                                          <tr>
                                            <th>Col1</th>
                                            <th>Col2</th>
                                            <th>Type</th>
                                            <th>Remove</th>
                                          </tr>
                                        </thead>
                                        <tbody>
                                          <tr>
                                            <td><input type="text" id="mainScript"  name="mainScript"></td>
                                            <td><input type="text" id="rollBackScript"  name="rollBackScript"></td>
                                            <td><select name="type" id ="type" >
                                                      <option value="Automated" selected >Automated</option>
                                                      <option value="Manual" >Manual</option>
                                                </select>
                                            </td>
                                            <td><input type="button" class="btn btn-danger" value="Delete" onclick="deleteRow(this);"></td>
                                          </tr>
                                        </tbody>
                                      </table>
                                      </div>
                    </div>

                    <div class="row" align="left">
                    <input type="button"  class="btn btn-success"  value="Add Row" onclick="addRow('scriptsTable')" />
                    </div>

JavaScript functions

<script>

    function addRow(tableId) {
    var table = document.getElementById(tableId);
        var rowCount = table.rows.length;
        var row = table.insertRow(rowCount);
        var colCount = table.rows[1].cells.length;
        for(var i=0; i<colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.innerHTML = table.rows[1].cells[i].innerHTML;
            //alert(newcell.childNodes);
            switch(newcell.childNodes[0].type) {
                case "text":
                        newcell.childNodes[0].value = "";
                        break;
                case "checkbox":
                        newcell.childNodes[0].checked = false;
                        break;
                case "select-one":
                        newcell.childNodes[0].selectedIndex = 0;
                        break;
                case "button":
                    newcell.childNodes[0].value = "Delete";
                    break;
            }
        }
    }

    function deleteRow(deleteBtn) {

        var table = document.getElementById('scriptsTable');

         if(table.rows.length <= 2){
                alert("Cannot delete all the rows.");
                return;
            }
        if (typeof(deleteBtn) == "object") {
            $(deleteBtn).closest("tr").remove();
        } else {
            return false;
        }
        }
</script>


问:
Json response parser for Array or Object
I am writing a library to consume a Json API and I am facing a design problem when using Gson as the parsing library.

One of the endpoints returns an array of objects if everything goes well like so:

```<code>[
  {
   "name": "John",
   "age" : 21
  },
  {
   "name": "Sarah",
   "age" : 32
  },
]
</code>```

However, the error schema for all the endpoints in the API is an json object instead of an array.

```<code>{
  "errors": [
     {
       "code": 1001,
       "message": "Something blew up"
     }
  ]
}
</code>```

The problem arises when modeling this in POJOs. Because the error schema is common for all the API endpoints, I decided to have an abstract ApiResponse class which will only map the errors attribute

```<code>public abstract class ApiResponse{

  @SerializedName("errors")
  List<ApiResponseError> errors;
}

public class ApiResponseError {

  @SerializedName("code")
  public Integer code;

  @SerializedName("message")
  public String message;
}
</code>```

Now I would like to inherit from ApiResponse to have the error mapping "for free" and a POJO per API endpoint response. However, the top level json object for this response is an array (if the server succeeds to execute the request), so I can not create a new class to map it like I would like it.

I decided to still create a class extending ApiResponse:

```<code>public class ApiResponsePerson extends ApiResponse {

  List<Person> persons;
}
</code>```

And implemented a custom deserializer to correctly parse the json depending on the type of the top level object, and setting it to the correct field on the following class:

```<code>public class DeserializerApiResponsePerson implements JsonDeserializer<ApiResponsePerson> {

  @Override
  public ApiResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

    ApiResponsePerson response = new ApiResponsePerson();
    if (json.isJsonArray()) {
      Type personType = new TypeToken<List<Person>>() {}.getType();
      response.persons = context.deserialize(json, personType);
      return response;
    }
    if (json.isJsonObject()) {
      JsonElement errorJson = json.getAsJsonObject().get("errors");
      Type errorsType = new TypeToken<List<ApiResponseError>>() {}.getType();
      response.errors = context.deserialize(errorJson, errorsType);
      return response;
    }
    throw new JsonParseException("Unexpected Json for 'ApiResponse'");
  }
}
</code>```

Which I will then add to the Gson

```<code>Gson gson = new GsonBuilder()
    .registerTypeAdapter(ApiResponsePerson.class, new DeserializerApiResponsePerson())
    .create();
</code>```

Is there any way to model this POJOs and have Gson recognize this structure without having to manually handle this scenario?
Is there any better way to accomplish this?
Am I missing any scenario where the deserializer might fail or not work as expected?

Thanks

答:
This solution is almost very good for this scenario. But I would like to define the response more general, is there should be a status to identify success or failure for the request? So I prefer the json format to be like this:

for success:

```<code>{
  "status": "success",
  "results": [
    {
      "name": "John",
      "age" : 21
    }
  ]
}
</code>```

for failure:

```<code>{
  "status": "failure",
  "errors": [
     {
       "code": 1001,
       "message": "Something blew up"
     }
  ]
}
</code>```

Body:
I am writing a library to consume a Json API and I am facing a design problem when using Gson as the parsing library.

One of the endpoints returns an array of objects if everything goes well like so:

[
  {
   "name": "John",
   "age" : 21
  },
  {
   "name": "Sarah",
   "age" : 32
  },
]

However, the error schema for all the endpoints in the API is an json object instead of an array.

{
  "errors": [
     {
       "code": 1001,
       "message": "Something blew up"
     }
  ]
}

The problem arises when modeling this in POJOs. Because the error schema is common for all the API endpoints, I decided to have an abstract ApiResponse class which will only map the errors attribute

public abstract class ApiResponse{

  @SerializedName("errors")
  List<ApiResponseError> errors;
}

public class ApiResponseError {

  @SerializedName("code")
  public Integer code;

  @SerializedName("message")
  public String message;
}

Now I would like to inherit from ApiResponse to have the error mapping "for free" and a POJO per API endpoint response. However, the top level json object for this response is an array (if the server succeeds to execute the request), so I can not create a new class to map it like I would like it.

I decided to still create a class extending ApiResponse:

public class ApiResponsePerson extends ApiResponse {

  List<Person> persons;
}

And implemented a custom deserializer to correctly parse the json depending on the type of the top level object, and setting it to the correct field on the following class:

public class DeserializerApiResponsePerson implements JsonDeserializer<ApiResponsePerson> {

  @Override
  public ApiResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {

    ApiResponsePerson response = new ApiResponsePerson();
    if (json.isJsonArray()) {
      Type personType = new TypeToken<List<Person>>() {}.getType();
      response.persons = context.deserialize(json, personType);
      return response;
    }
    if (json.isJsonObject()) {
      JsonElement errorJson = json.getAsJsonObject().get("errors");
      Type errorsType = new TypeToken<List<ApiResponseError>>() {}.getType();
      response.errors = context.deserialize(errorJson, errorsType);
      return response;
    }
    throw new JsonParseException("Unexpected Json for 'ApiResponse'");
  }
}

Which I will then add to the Gson

Gson gson = new GsonBuilder()
    .registerTypeAdapter(ApiResponsePerson.class, new DeserializerApiResponsePerson())
    .create();

Is there any way to model this POJOs and have Gson recognize this structure without having to manually handle this scenario?
Is there any better way to accomplish this?
Am I missing any scenario where the deserializer might fail or not work as expected?

Thanks

Body:
This solution is almost very good for this scenario. But I would like to define the response more general, is there should be a status to identify success or failure for the request? So I prefer the json format to be like this:

for success:

{
  "status": "success",
  "results": [
    {
      "name": "John",
      "age" : 21
    }
  ]
}

for failure:

{
  "status": "failure",
  "errors": [
     {
       "code": 1001,
       "message": "Something blew up"
     }
  ]
}