问:
unable to fetch the list values from the website
i fetch all the detail from the desire website but unable to get the some specific information please guide me for that.

targeted domain: https://shop.adidas.ae/en/messi-16-3-indoor-boots/BA9855.html

my code isresponse.xpath('//ul[@class="product-size"]//li/text()').extract()

need to fetch data!!!

Thanks!

答:
Often ecommerce websites have data in json format in page source and then have javscript unpack it on users end.

In this case you can open up the page source with javascript disabled and search for keywords (like specific size).

I found in this case it can be found with regular expressions:

```<code>import re
import json
data = re.findall('window.assets.sizesMap = (\{.+?\});', response.body_as_unicode())
json.loads(data[0])
Out:
{'16': {'uk': '0k', 'us': '0.5'},
 '17': {'uk': '1k', 'us': '1'},
 '18': {'uk': '2k', 'us': '2.5'},
 ...}
</code>```

Edit: More accurately you probably want to get different part of the json but nevertheless the answer is more or less the same:

```<code>data = re.findall('window.assets.sizes = (\{(?:.|\n)+?\});', response.body_as_unicode())
json.loads(data[0].replace("'", '"')) # replace single quotes to doubles
</code>```

Body:
Often ecommerce websites have data in json format in page source and then have javscript unpack it on users end.

In this case you can open up the page source with javascript disabled and search for keywords (like specific size).

I found in this case it can be found with regular expressions:

import re
import json
data = re.findall('window.assets.sizesMap = (\{.+?\});', response.body_as_unicode())
json.loads(data[0])
Out:
{'16': {'uk': '0k', 'us': '0.5'},
 '17': {'uk': '1k', 'us': '1'},
 '18': {'uk': '2k', 'us': '2.5'},
 ...}

Edit: More accurately you probably want to get different part of the json but nevertheless the answer is more or less the same:

data = re.findall('window.assets.sizes = (\{(?:.|\n)+?\});', response.body_as_unicode())
json.loads(data[0].replace("'", '"')) # replace single quotes to doubles


来源: stackexchange

问:
Array nested proxy
I have created an array, and my problem is in the operator square brackets "[]". The array is shared to reduce copying it every time, so when a write operation needs to take place a private copy of the array must be made before. When using the operator "[]", there is no way of knowing if the operation on the entry will be a read or write operation. For this purpose proxy is used, instead of returning a reference to the entry, a proxy is created with a reference to the array object and the required entry in the array.

The code for operator "[ ]":

```<code>inline typename BasicTypesArray< T >::BasicTypesArrayProxy BasicTypesArray< T >::operator[]( UnsignedInteger64bits entryIndex )
{
    return ( BasicTypesArrayProxy( *this, entryIndex ) );
}
</code>```

The code for the proxy constructor:

```<code>    inline BasicTypesArray< T >::BasicTypesArrayProxy::BasicTypesArrayProxy( BasicTypesArray< T >& basicTypesArray, UnsignedInteger64bits entryIndex ) :
    m_basicTypesArrayObject( basicTypesArray ),
    m_entryIndex( entryIndex )
    {}
</code>```

The problem is that when compiling this using g++ i get the following error:

In file included from BasicTypesArrayTest.cpp:4:0:
../Utilities/GeneralPurposeContainers/Array/BasicTypes/BasicTypesArray/BasicTypesArray.h: In instantiation of ‘Universe::GeneralPurposeContainers::BasicTypesArray::BasicTypesArrayProxy Universe::GeneralPurposeContainers::BasicTypesArray::operator [with T = int; Universe::UnsignedInteger64bits = long unsigned int]’:

BasicTypesArrayTest.cpp:31:13:   required from here
../Utilities/GeneralPurposeContainers/Array/BasicTypes/BasicTypesArray/BasicTypesArray.h:2311:64: error: no matching function for call to ‘Universe::GeneralPurposeContainers::BasicTypesArray::BasicTypesArrayProxy::BasicTypesArrayProxy(Universe::GeneralPurposeContainers::BasicTypesArray::BasicTypesArrayProxy)’

```<code>         return ( BasicTypesArrayProxy( *this, entryIndex ) );
</code>```

Sorry for the long error message.

Why does the compiler tries to call the proxy constructor with proxy and not with the reference to the class it is nested within??

答:
I think it ready run the constructor of your class BasicTypesArrayProxy( *this, entryIndex ). But for returning a value, it has to run the copy constructor to the calling code.
You can try this test: Set the return type of operator[] to reference (which will cause a crash in real run), to see whether your code can pass the compile stage.

ContentLicense: CC BY-SA 3.0

Title: Array nested proxy

Body:
I have created an array, and my problem is in the operator square brackets "[]". The array is shared to reduce copying it every time, so when a write operation needs to take place a private copy of the array must be made before. When using the operator "[]", there is no way of knowing if the operation on the entry will be a read or write operation. For this purpose proxy is used, instead of returning a reference to the entry, a proxy is created with a reference to the array object and the required entry in the array.

The code for operator "[ ]":

inline typename BasicTypesArray< T >::BasicTypesArrayProxy BasicTypesArray< T >::operator[]( UnsignedInteger64bits entryIndex )
{
    return ( BasicTypesArrayProxy( *this, entryIndex ) );
}

The code for the proxy constructor:

    inline BasicTypesArray< T >::BasicTypesArrayProxy::BasicTypesArrayProxy( BasicTypesArray< T >& basicTypesArray, UnsignedInteger64bits entryIndex ) :
    m_basicTypesArrayObject( basicTypesArray ),
    m_entryIndex( entryIndex )
    {}

The problem is that when compiling this using g++ i get the following error:

In file included from BasicTypesArrayTest.cpp:4:0:
../Utilities/GeneralPurposeContainers/Array/BasicTypes/BasicTypesArray/BasicTypesArray.h: In instantiation of ‘Universe::GeneralPurposeContainers::BasicTypesArray::BasicTypesArrayProxy Universe::GeneralPurposeContainers::BasicTypesArray::operator [with T = int; Universe::UnsignedInteger64bits = long unsigned int]’:

BasicTypesArrayTest.cpp:31:13:   required from here
../Utilities/GeneralPurposeContainers/Array/BasicTypes/BasicTypesArray/BasicTypesArray.h:2311:64: error: no matching function for call to ‘Universe::GeneralPurposeContainers::BasicTypesArray::BasicTypesArrayProxy::BasicTypesArrayProxy(Universe::GeneralPurposeContainers::BasicTypesArray::BasicTypesArrayProxy)’

         return ( BasicTypesArrayProxy( *this, entryIndex ) );

Sorry for the long error message.

Why does the compiler tries to call the proxy constructor with proxy and not with the reference to the class it is nested within??


问:
Qt - How to show a QLabel in fullscreen on my laptop?
I have a ui with a QButton and a QLabel. I would like the QLabel to be displayed on fullscreen on my laptop whenever I push that button.

I tried the following code:

```<code>void MainWindow::on_fullScreenBtn_clicked()
{
    // ui->myImage is a QLabel*
    ui->myImage->setText("going full screen");
    ui->myImage->showMaximized();
    ui->myImage->QWidget::showFullScreen();
}
</code>```

I can see this function gets executed, but this doesn't display my label in full screen. What am I doing incorrectly/ missing?

I am using QtCreator 3.5.1 and made my gui using the built-in graphical interface.

EDIT: The variable myImage is a QLabel containing an image

答:
The problem is that your QLabel is part of another widget and therefore displayed as a child widget instead due to the default Qt::Widget flag:

This is the default type for QWidget.
  Widgets of this type are child widgets if they have a parent, and
  independent windows if they have no parent. See also Qt::Window and Qt::SubWindow.

Therefore, the solution is to change the flag to Qt::Window manually as follows:

```<code>ui->myImage->setWindowFlag(Qt::Window);
</code>```

Pre Qt 5.9 users can use the following:

```<code>ui->myImage->setWindowFlags(ui->myImage->windowFlags() | Qt::Window);
</code>```

Note that you should call showFullScreen after you changed the window flags as documented by Qt:

Note: This function calls setParent() when changing the flags for a
  window, causing the widget to be hidden. You must call show() to make
  the widget visible again..

Undo maximisation

The window flag should be removed to undo the maximisation. This can be done as follows:

```<code>ui->myImage->setWindowFlag(Qt::Window, false);
ui->myImage->show();
</code>```

Pre Qt 5.9 users can use the following:

```<code>ui->myImage->setWindowFlags(ui->myImage->windowFlags() & ~Qt::Window);
ui->myImage->show();
</code>```

Note that the call to show is needed as pointed out above.

ContentLicense: CC BY-SA 4.0

Body:
I have a ui with a QButton and a QLabel. I would like the QLabel to be displayed on fullscreen on my laptop whenever I push that button.

I tried the following code:

void MainWindow::on_fullScreenBtn_clicked()
{
    // ui->myImage is a QLabel*
    ui->myImage->setText("going full screen");
    ui->myImage->showMaximized();
    ui->myImage->QWidget::showFullScreen();
}

I can see this function gets executed, but this doesn't display my label in full screen. What am I doing incorrectly/ missing?

I am using QtCreator 3.5.1 and made my gui using the built-in graphical interface.

EDIT: The variable myImage is a QLabel containing an image

Body:
The problem is that your QLabel is part of another widget and therefore displayed as a child widget instead due to the default Qt::Widget flag:

This is the default type for QWidget.
  Widgets of this type are child widgets if they have a parent, and
  independent windows if they have no parent. See also Qt::Window and Qt::SubWindow.

Therefore, the solution is to change the flag to Qt::Window manually as follows:

ui->myImage->setWindowFlag(Qt::Window);

Pre Qt 5.9 users can use the following:

ui->myImage->setWindowFlags(ui->myImage->windowFlags() | Qt::Window);

Note that you should call showFullScreen after you changed the window flags as documented by Qt:

Note: This function calls setParent() when changing the flags for a
  window, causing the widget to be hidden. You must call show() to make
  the widget visible again..

Undo maximisation

The window flag should be removed to undo the maximisation. This can be done as follows:

ui->myImage->setWindowFlag(Qt::Window, false);
ui->myImage->show();

Pre Qt 5.9 users can use the following:

ui->myImage->setWindowFlags(ui->myImage->windowFlags() & ~Qt::Window);
ui->myImage->show();

Note that the call to show is needed as pointed out above.


问:
My Python LinkedList implementation crashes after second addition to List
```<code>class Node:
  def __init__(self, data = None, next = None):
    self.data = data
    self.next = next

class LinkedList(Node):
  def __init__(self, l_size = 0, head = None, tail = None):
    Node.__init__(self)
    self.l_size = 0
    self.head = head
    self.tail = tail

  def add(self, data):
    n = Node(data, None)
    if(self.l_size == 0):
      self.head.next = n
      self.head.data = n.data
    else:
      self.tail.next = n
      self.tail.data = n.data
      n = n.next
      print(n)
    self.tail = n
    self.l_size += 1
    return True

l = LinkedList()
l.add(7)
l.add(8)
l.add(2)
</code>```

I'm just trying to achieve (h)-> 7 -> 8 -> 2 <- (l)
Where (h) and (l) are the head and tail pointers respectively. The way I'm implementing this the LL is basically the head and the tail pointers, the Nodes chain together on their own, that's why I made Node a super class.

答:
It should crash on the first addition - when you initialize your LinkedList you initialize it with self.head set to None (the default argument). Then when you call the add() method, since self.l_size is 0 you attempt to set self.head.next to the created node - but since it's set to None you'll get an AttributeError.

When your LinkedList is empty, you should set both its tail and head properties to the first added element, because in a list of length 1 both head and tail are the same element.

Body:
class Node:
  def __init__(self, data = None, next = None):
    self.data = data
    self.next = next

class LinkedList(Node):
  def __init__(self, l_size = 0, head = None, tail = None):
    Node.__init__(self)
    self.l_size = 0
    self.head = head
    self.tail = tail

  def add(self, data):
    n = Node(data, None)
    if(self.l_size == 0):
      self.head.next = n
      self.head.data = n.data
    else:
      self.tail.next = n
      self.tail.data = n.data
      n = n.next
      print(n)
    self.tail = n
    self.l_size += 1
    return True

l = LinkedList()
l.add(7)
l.add(8)
l.add(2)

I'm just trying to achieve (h)-> 7 -> 8 -> 2 <- (l)
Where (h) and (l) are the head and tail pointers respectively. The way I'm implementing this the LL is basically the head and the tail pointers, the Nodes chain together on their own, that's why I made Node a super class.


问:
Permission issues with popen within py2app
I am using py2app to bundle a python script, that uses the anaconda python distribution.

Since py2app doesn't play well with terminal scripts that need user input, I have a Tkinter file that py2app's setup.py launches, which then further launches my .py script using popen.

Locally, this works fine:

```<code>import subprocess as sub
command = "~/anaconda/bin/python -u myscript.py " + str(groups_count)
process = sub.Popen(command, shell=True, stdout=sub.PIPE, stderr=sub.PIPE, bufsize=1, universal_newlines=True)
</code>```

But when I want to distribute this, I need to replace hardcoded paths and run this using the distribution contained within

```<code>import subprocess as sub
command = sys.executable + " -u myscript.py " + str(groups_count)
process = sub.Popen(command, shell=True, stdout=sub.PIPE, stderr=sub.PIPE, bufsize=1, universal_newlines=True)
</code>```

This results in an error:

/bin/sh: /Users/username/projectname/appname/dist/MyOSXapp.app/Contents/MacOS/python: Permission denied

If I look at libpython2.7.dylib within /MyOSXapp.app/Contents/Frameworks it doesn't seem to be executable, but is readable by everyone. This is all assembled by py2app.

I need to run popen on my anaconda python distributed within pyapp. How do I do this?

答:
I worked around this by adding executable permission to the python file saved by py2app within the osx .app file.

```<code>$ chmod +x ./dist/MyOSXapp.app/Contents/MacOS/python
</code>```

Additionally, a fix for this was also added in py2app via issue 228.

Body:
I am using py2app to bundle a python script, that uses the anaconda python distribution.

Since py2app doesn't play well with terminal scripts that need user input, I have a Tkinter file that py2app's setup.py launches, which then further launches my .py script using popen.

Locally, this works fine:

import subprocess as sub
command = "~/anaconda/bin/python -u myscript.py " + str(groups_count)
process = sub.Popen(command, shell=True, stdout=sub.PIPE, stderr=sub.PIPE, bufsize=1, universal_newlines=True)

But when I want to distribute this, I need to replace hardcoded paths and run this using the distribution contained within

import subprocess as sub
command = sys.executable + " -u myscript.py " + str(groups_count)
process = sub.Popen(command, shell=True, stdout=sub.PIPE, stderr=sub.PIPE, bufsize=1, universal_newlines=True)

This results in an error:

/bin/sh: /Users/username/projectname/appname/dist/MyOSXapp.app/Contents/MacOS/python: Permission denied

If I look at libpython2.7.dylib within /MyOSXapp.app/Contents/Frameworks it doesn't seem to be executable, but is readable by everyone. This is all assembled by py2app.

I need to run popen on my anaconda python distributed within pyapp. How do I do this?

Body:
I worked around this by adding executable permission to the python file saved by py2app within the osx .app file.

$ chmod +x ./dist/MyOSXapp.app/Contents/MacOS/python

Additionally, a fix for this was also added in py2app via issue 228.


问:
Uploading/Saving videos not working in PHP
If a user inputs "0" in the "media_type" text box, it runs the image upload code and if you put "1" it runs the video upload code. The problem is with the video section because when i upload a video, it doesn't display anything. But when i input an image, and go to the image section, it works. Here is my code

PHP

```<code><?php

if(isset($_POST['submit'])){

    $media_type = addslashes($_POST['media_type']);

    if($media_type !=0 && $media_type !=1){

        die (json_encode([
        "Status" => " Failed",
        "Message" => " Error 404"
    ]));
        exit;
    }

    if(@getimagesize($_FILES["file"]["tmp_name"])==false){

        echo json_encode([

            "Status" => " Failed",
            "Message" => " No file selected..."
        ]);
        exit;
    }

    if(@getimagesize($_FILES['file']['tmp_name']) ==FALSE || $_POST['user_id'] == "" || $_POST['media_type'] =="" || $_POST['category1'] ==""){

        echo json_encode([
            "Status" => "Failed",
            "Message" => "There were values missing"

        ]);

    die("");
    }

function imageUpload(){
    $userid = addslashes($_POST['user_id']);
    $category1 = addslashes($_POST['category1']);
    $category2 = addslashes($_POST['category2']);
    $category3 = addslashes($_POST['category3']);

//if file is there

    $target = "images/";

    $target_file = addslashes($target . basename($_FILES["file"]["name"]));

    if(file_exists($target_file)){

        echo json_encode([
            "Status" => " Failed",
            "Message" => " Sorry, file already exists..."
        ]);
        exit;
    }
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file))
{

    $db = mysqli_connect("localhost", "root", "");
    mysqli_select_db($db, "magicsever");

    if(mysqli_connect_error()){

        die ("Database connection error");
    }

$image = addslashes($_FILES['file']['tmp_name']);
$name = addslashes($_FILES['file']['name']);

$sql = "INSERT INTO classified_images (`user_id`,`image`, `img_path`, `img_category_1`,`img_category_2`, `img_category_3`)VALUES('$userid','$image','$name','$category1','$category2','$category3')";
$final = mysqli_query($db, $sql);

echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK",
"userId" => $_POST["user_id"]
]);
}else{

echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error",
"userId" => $_POST["user_id"]
]);

}
}

function videoUpload(){
    $userid = addslashes($_POST['user_id']);
    $category1 = addslashes($_POST['category1']);
    $category2 = addslashes($_POST['category2']);
    $category3 = addslashes($_POST['category3']);
    // Check if file was submited

    $target = "videos/";

    $target_file = addslashes($target . basename($_FILES["file"]["name"]));

    // Check if file already exists
    if(file_exists($target_file)){

        echo json_encode([
            "Status" => " Failed",
            "Message" => " Sorry, file already exists..."
        ]);
        exit;
    }

    // Check file size not > 500Mb
    if($_FILES["file"]["size"] > 500000000){

        echo json_encode([

            "Status" => " Failed",
            "Message" => " Sorry, file is too large."
        ]);
        exit;
    }

        if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)){

            $db = mysqli_connect("localhost", "root", "");
    mysqli_select_db($db, "magicsever");

    if(mysqli_connect_error()){

        die ("Database connection error");
    }

    $video = addslashes($_FILES['file']['tmp_name']);
        $name = addslashes($_FILES['file']['name']);

    $sql = "INSERT INTO classified_videos (`user_id`, `vid_path`, `vid_category_1`, `vid_category_2`, `vid_category_3`, `video`)VALUES('$userid','$name','$category1','$category2','$category3','$video')";
    $final = mysqli_query($db, $sql);

            echo json_encode([

                "Status" => " Success",
                "Message" => " The file ". basename($_FILES["file"]["name"]). " has been uploaded.",
                "userId" => $_POST["user_id"]
            ]);
        }else{

            echo json_encode([

                "Status" => " Failed",
                "Message" => " Sorry, there was an error uploaded your file"
            ]);
            exit;
        }

    //Connect to database

}
    if($media_type ==0){

        imageUpload();
    }else if($media_type ==1){

        videoUpload();
    }
}
?>
</code>```

HTML

```<code>    <form method="post" enctype="multipart/form-data">

<input type="file" name="file">

<br></br>
<input type="text" name="user_id" placeholder="User id...">
<br></br>
<input type="text" name="media_type" placeholder="(0)Image...(1)Video">
<br></br>
<input type="text" name="category1" placeholder="MediaTag#1...">
<br></br>
<input type="text" name="category2" placeholder="MediaTag#2...">
<br></br>
<input type="text" name="category3" placeholder="MediaTag#3...">
    <br></br>
<input type="submit" name="submit" value="upload">

</form>
</code>```

答: The size of images cross 2MB upload size if you have upload more than 2MB data increase the size "File upload size "  from php.ini file</p>

Body:
If a user inputs "0" in the "media_type" text box, it runs the image upload code and if you put "1" it runs the video upload code. The problem is with the video section because when i upload a video, it doesn't display anything. But when i input an image, and go to the image section, it works. Here is my code

PHP

<?php

if(isset($_POST['submit'])){

    $media_type = addslashes($_POST['media_type']);

    if($media_type !=0 && $media_type !=1){

        die (json_encode([
        "Status" => " Failed",
        "Message" => " Error 404"
    ]));
        exit;
    }

    if(@getimagesize($_FILES["file"]["tmp_name"])==false){

        echo json_encode([

            "Status" => " Failed",
            "Message" => " No file selected..."
        ]);
        exit;
    }

    if(@getimagesize($_FILES['file']['tmp_name']) ==FALSE || $_POST['user_id'] == "" || $_POST['media_type'] =="" || $_POST['category1'] ==""){

        echo json_encode([
            "Status" => "Failed",
            "Message" => "There were values missing"

        ]);

    die("");
    }

function imageUpload(){
    $userid = addslashes($_POST['user_id']);
    $category1 = addslashes($_POST['category1']);
    $category2 = addslashes($_POST['category2']);
    $category3 = addslashes($_POST['category3']);

//if file is there

    $target = "images/";

    $target_file = addslashes($target . basename($_FILES["file"]["name"]));

    if(file_exists($target_file)){

        echo json_encode([
            "Status" => " Failed",
            "Message" => " Sorry, file already exists..."
        ]);
        exit;
    }
if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file))
{

    $db = mysqli_connect("localhost", "root", "");
    mysqli_select_db($db, "magicsever");

    if(mysqli_connect_error()){

        die ("Database connection error");
    }

$image = addslashes($_FILES['file']['tmp_name']);
$name = addslashes($_FILES['file']['name']);

$sql = "INSERT INTO classified_images (`user_id`,`image`, `img_path`, `img_category_1`,`img_category_2`, `img_category_3`)VALUES('$userid','$image','$name','$category1','$category2','$category3')";
$final = mysqli_query($db, $sql);

echo json_encode([
"Message" => "The file ". basename( $_FILES["file"]["name"]). " has been uploaded.",
"Status" => "OK",
"userId" => $_POST["user_id"]
]);
}else{

echo json_encode([
"Message" => "Sorry, there was an error uploading your file.",
"Status" => "Error",
"userId" => $_POST["user_id"]
]);

}
}

function videoUpload(){
    $userid = addslashes($_POST['user_id']);
    $category1 = addslashes($_POST['category1']);
    $category2 = addslashes($_POST['category2']);
    $category3 = addslashes($_POST['category3']);
    // Check if file was submited

    $target = "videos/";

    $target_file = addslashes($target . basename($_FILES["file"]["name"]));

    // Check if file already exists
    if(file_exists($target_file)){

        echo json_encode([
            "Status" => " Failed",
            "Message" => " Sorry, file already exists..."
        ]);
        exit;
    }

    // Check file size not > 500Mb
    if($_FILES["file"]["size"] > 500000000){

        echo json_encode([

            "Status" => " Failed",
            "Message" => " Sorry, file is too large."
        ]);
        exit;
    }

        if(move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)){

            $db = mysqli_connect("localhost", "root", "");
    mysqli_select_db($db, "magicsever");

    if(mysqli_connect_error()){

        die ("Database connection error");
    }

    $video = addslashes($_FILES['file']['tmp_name']);
        $name = addslashes($_FILES['file']['name']);

    $sql = "INSERT INTO classified_videos (`user_id`, `vid_path`, `vid_category_1`, `vid_category_2`, `vid_category_3`, `video`)VALUES('$userid','$name','$category1','$category2','$category3','$video')";
    $final = mysqli_query($db, $sql);

            echo json_encode([

                "Status" => " Success",
                "Message" => " The file ". basename($_FILES["file"]["name"]). " has been uploaded.",
                "userId" => $_POST["user_id"]
            ]);
        }else{

            echo json_encode([

                "Status" => " Failed",
                "Message" => " Sorry, there was an error uploaded your file"
            ]);
            exit;
        }

    //Connect to database

}
    if($media_type ==0){

        imageUpload();
    }else if($media_type ==1){

        videoUpload();
    }
}
?>

HTML

    <form method="post" enctype="multipart/form-data">

<input type="file" name="file">

<input type="text" name="user_id" placeholder="User id...">

<input type="text" name="media_type" placeholder="(0)Image...(1)Video">

<input type="text" name="category1" placeholder="MediaTag#1...">

<input type="text" name="category2" placeholder="MediaTag#2...">

<input type="text" name="category3" placeholder="MediaTag#3...">

<input type="submit" name="submit" value="upload">

</form>


问:
LINQ & Lambda Expressions equivalent of SQL In
Is there a lambda equivalent of IN?  I will like to select all the funds with ids either 4, 5 or 6.  One way of writing it is:

List fundHistoricalPrices = lionContext.FundHistoricalPrices.Where(fhp => fhp.Fund.FundId == 5 || fhp.Fund.FundId == 6 || fhp.Fund.FundId == 7).ToList();

However, that quickly becomes unmanageable if I need it to match say 100 different fundIds.  Can I do something like:

List
  fundHistoricalPrices =
  lionContext.FundHistoricalPrices.Where(fhp
  => fhp.Fund.FundId in(5,6,7)).ToList();

答:
It's somewhere along these lines, but I can't quite agree with the approach you have taken. But this will do if you really want to do this:

```<code>.Where(fhp => new List<int>{5,6,7}.Contains( fhp.Fund.FundId )).ToList();
</code>```

You may want to construct the List of ids before your LINQ query...

Body:
It's somewhere along these lines, but I can't quite agree with the approach you have taken. But this will do if you really want to do this:

.Where(fhp => new List<int>{5,6,7}.Contains( fhp.Fund.FundId )).ToList();

You may want to construct the List of ids before your LINQ query...

ContentLicense: CC BY-SA 2.5


问:
Azure function gives "The 'code' query parameter provided in the HTTP request did not match the expected value."
I am developing logic app in azure portal with azure function app.Logic app gives randomly code query parameter invalid error for function .
When ever error occurred i have to clone the logic app is there any permanent solution for this error.

Regards

答:
Goto yourfunction->manage->functionkey->default -click on the copy link under actions

Just appending code

https://{functionappName}.azurewebsites.net/api/{functionName}?code={defaultfunctionkey}


问:
es6 arrow function
I would test this in browser

```<code>let foo = () => ({ bar: 2 })
</code>```

But accidentally typed

```<code>let foo = () => { bar: 2}
</code>```

Why didn't throw an error?

答:
The two syntax are correct but they don't define the same function.</p>

```<code>function foo1() {
  return {bar: 2};
}

function foo2() {
  bar: 2;
}
</code>```

Title: es6 arrow function

Body:
I would test this in browser

let foo = () => ({ bar: 2 })

But accidentally typed

let foo = () => { bar: 2}

Why didn't throw an error?

Body:
The two syntax are correct but they don't define the same function.

function foo1() {
  return {bar: 2};
}

function foo2() {
  bar: 2;
}


问:
spring data @query 'cached' table?
App entity

```<code>@Entity
@Table(name = "app")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class App implements Serializable {
    @ManyToMany
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    @JoinTable(name = "app_alloweduser",
               joinColumns = @JoinColumn(name="apps_id", referencedColumnName="id"),
               inverseJoinColumns = @JoinColumn(name="allowedusers_id", referencedColumnName="id"))
    private Set<User> allowedusers = new HashSet<>();
}
</code>```

I try to write my own query as such.

```<code>@Query("SELECT app FROM App app WHERE (:department is null or app.department = :department) and "
        + "(:platform is null or app.platform = :platform) and "
        + "(:appName is null or lower(app.appName) LIKE CONCAT('%',lower(:appName),'%')) and "
        + "(app.id in (SELECT b.apps_id FROM allowedusers b where b.allowedusers_id = :loginid))")
Page<App> findAllAllowed(@Param("department") Department department,
                         @Param("platform") Platform platform,
                         @Param("appName") String appName,
                         @Param("loginid") Long loginid,
                         Pageable pageable);
</code>```

Error: org.hibernate.hql.internal.ast.QuerySyntaxException: allowedusers is not mapped

I have tried app_alloweduser also and it too throws the same error that it can't map. The table APP_ALLOWEDUSER, which is what I am interested in is verified to be there though. So I am wondering what is going on here.

Some background
The table app_alloweduser has 2 column, app_id & user_id. I will first have to retrieve a list of app_id given a user_id. Then return all app from this list of app_id.

答:
There is no alloweduser entity only App and User. Try to use join instead.

```<code>@Query("SELECT app FROM App app join User u WHERE (:department is null or app.department = :department) and "
        + "(:platform is null or app.platform = :platform) and "
        + "(:appName is null or lower(app.appName) LIKE CONCAT('%',lower(:appName),'%')) and "
        + "(u.allowedusers_id = :loginid))")
</code>```

UPDATE:
change u.allowedusers_id = :loginid to u.id = :loginid.
You don't have the table in HQL. Of course you can introduce a new entity if you need for the APP_ALLOWEDUSER

Title: spring data @query 'cached' table?

Body:
App entity

@Entity
@Table(name = "app")
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
public class App implements Serializable {
    @ManyToMany
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    @JoinTable(name = "app_alloweduser",
               joinColumns = @JoinColumn(name="apps_id", referencedColumnName="id"),
               inverseJoinColumns = @JoinColumn(name="allowedusers_id", referencedColumnName="id"))
    private Set<User> allowedusers = new HashSet<>();
}

I try to write my own query as such.

@Query("SELECT app FROM App app WHERE (:department is null or app.department = :department) and "
        + "(:platform is null or app.platform = :platform) and "
        + "(:appName is null or lower(app.appName) LIKE CONCAT('%',lower(:appName),'%')) and "
        + "(app.id in (SELECT b.apps_id FROM allowedusers b where b.allowedusers_id = :loginid))")
Page<App> findAllAllowed(@Param("department") Department department,
                         @Param("platform") Platform platform,
                         @Param("appName") String appName,
                         @Param("loginid") Long loginid,
                         Pageable pageable);

Error: org.hibernate.hql.internal.ast.QuerySyntaxException: allowedusers is not mapped

I have tried app_alloweduser also and it too throws the same error that it can't map. The table APP_ALLOWEDUSER, which is what I am interested in is verified to be there though. So I am wondering what is going on here.

Some background
The table app_alloweduser has 2 column, app_id & user_id. I will first have to retrieve a list of app_id given a user_id. Then return all app from this list of app_id.

Body:
There is no alloweduser entity only App and User. Try to use join instead.

@Query("SELECT app FROM App app join User u WHERE (:department is null or app.department = :department) and "
        + "(:platform is null or app.platform = :platform) and "
        + "(:appName is null or lower(app.appName) LIKE CONCAT('%',lower(:appName),'%')) and "
        + "(u.allowedusers_id = :loginid))")

UPDATE:
change u.allowedusers_id = :loginid to u.id = :loginid.
You don't have the table in HQL. Of course you can introduce a new entity if you need for the APP_ALLOWEDUSER


问:
SQL update all records except the last one with a value
I need to make a query where only the last line of each user that has a car gets a license plate number.

```<code>ID    UserId    LicensePlate    HasCar
1     1         ABC123          1
2     1         ABC123          1
3     2         NULL            0
4     3         UVW789          1
5     3         UVW789          1
</code>```

Should become:

```<code>ID    UserId    LicensePlate    HasCar
1     1         NULL            1
2     1         ABC123          1
3     2         NULL            0
4     3         NULL            1
5     3         UVW789          1
</code>```

So I basically need to find all users with a licenseplate and change all but the last one and make the LicensePlate NULL

答:
You can do it with a join on the table itself like that :

```<code>UPDATE car c
INNER JOIN car c2 ON c.userId = c2.userId AND c.id < c2.id AND c.HasCar = 1 AND c2.HasCar = 1
SET c.LicensePlate = NULL
</code>```

The condition c.id < c2.id will avoid to select the last line

Body:
I need to make a query where only the last line of each user that has a car gets a license plate number.

ID    UserId    LicensePlate    HasCar
1     1         ABC123          1
2     1         ABC123          1
3     2         NULL            0
4     3         UVW789          1
5     3         UVW789          1

Should become:

ID    UserId    LicensePlate    HasCar
1     1         NULL            1
2     1         ABC123          1
3     2         NULL            0
4     3         NULL            1
5     3         UVW789          1

So I basically need to find all users with a licenseplate and change all but the last one and make the LicensePlate NULL

Body:
You can do it with a join on the table itself like that :

UPDATE car c
INNER JOIN car c2 ON c.userId = c2.userId AND c.id < c2.id AND c.HasCar = 1 AND c2.HasCar = 1
SET c.LicensePlate = NULL

The condition c.id < c2.id will avoid to select the last line


问:
Is there a way to create your own html tag in HTML5?
I want to create something like

```<code><menu>
    <lunch>
        <dish>aaa</dish>
        <dish>bbb</dish>
    </lunch>
    <dinner>
        <dish>ccc</dish>
    </dinner>
</menu>
</code>```

Can it be done in HTML5?
I know I can do it with

```<code><ul id="menu">
    <li>
        <ul id="lunch">
            <li class="dish">aaa</li>
            <li class="dish">bbb</li>
        </ul>
    </li>
    <li>
        <ul id="dinner">
            <li class="dish">ccc</li>
        </ul>
    </li>
</ul>
</code>```

but it is so much less readable :(

答:
In some circumstances, it may look like creating your own tag names just works fine.

However, this is just your browser's error handling routines at work. And the problem is, different browsers have different error handling routines!

See this example.

The first line contains two made-up elements, what and ever, and they get treated differently by different browsers. The text comes out red in IE11 and Edge, but black in other browsers.

For comparison, the second line is similar, except it contains only valid HTML elements, and it will therefore look the same in all browsers.

body {color:black; background:white;} /* reset */

what, ever:nth-of-type(2) {color:red}
code, span:nth-of-type(2) {color:red}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p><what></what> <ever>test</ever></p>

<p><code></code> <span>test</span></p></code>```

Another problem with made-up elements is that you won't know what the future holds. If you created a website a couple of years ago with tag names like picture, dialog, details, slot, template etc, expecting them to behave like spans, are you in trouble now!

Body:
I want to create something like

<menu>
    <lunch>
        <dish>aaa</dish>
        <dish>bbb</dish>
    </lunch>
    <dinner>
        <dish>ccc</dish>
    </dinner>
</menu>

Can it be done in HTML5?
I know I can do it with

aaa

bbb

ccc

but it is so much less readable :(

Body:
In some circumstances, it may look like creating your own tag names just works fine.

However, this is just your browser's error handling routines at work. And the problem is, different browsers have different error handling routines!

See this example.

The first line contains two made-up elements, what and ever, and they get treated differently by different browsers. The text comes out red in IE11 and Edge, but black in other browsers.

For comparison, the second line is similar, except it contains only valid HTML elements, and it will therefore look the same in all browsers.

body {color:black; background:white;} /* reset */

what, ever:nth-of-type(2) {color:red}
code, span:nth-of-type(2) {color:red}

<p><what></what> <ever>test</ever></p>

<p><code></code> <span>test</span></p>

Another problem with made-up elements is that you won't know what the future holds. If you created a website a couple of years ago with tag names like picture, dialog, details, slot, template etc, expecting them to behave like spans, are you in trouble now!


问:
How to generate two versions of image on carrierwave after applying crop method? Rails 5 app
I have an avatar_uploader.rb that uses carrierwave to create multiple versions of the uploaded avatar and also has a crop method.

```<code>  version :thumb do
    process :crop
    resize_to_fill(100, 100)
  end

  version :miniature do
    resize_to_fill(25, 25)
  end

  version :large do
    resize_to_limit(600, 600)
  end

  def crop
    if model.crop_x.present?
      resize_to_limit(600, 600)
      manipulate! do |img|
        x = model.crop_x.to_i
        y = model.crop_y.to_i
        w = model.crop_w.to_i
        h = model.crop_h.to_i
        img.crop!(x, y, w, h)
      end
    end
  end
</code>```

The problem is that I need two versions after the crop method is applied. I want a miniature version that is just a smaller version of the thumb, which is a cropped version of the original file.

The crop method requires that the user crop the image and needs to be called through a view to get the x, y, w, h attributes. So it should only be done once. It wouldn't make sense for the user to crop the image twice for two versions.

Now, it would be convenient if I could define the version miniature to apply the resize_to_fill on the thumb version but I don't know what the syntax for that would be.

I want to write this:-

```<code>  version :miniature do
    thumb.resize_to_fill(25, 25)
  end
</code>```

But that just gives an error and says thumb is undefined.

Is there a way to achieve this?

Update:-

I don't think I explained this problem clearly.

The miniature version gets regenerated but the problem is that the crop doesn't alter the original file. It just creates the thumb version. When the miniature version is applied, it miniaturizes the original file, and not the thumb version. I want the same crop as the thumb version but in miniature dimensions. So ideally I want to apply the miniature version on the thumb version. I don't know how to achieve this. Hope this is clearer now.

答:
You need to call recreate_versions! on your image after the crop to do this. So you could do:

```<code>model.image.recreate_versions!(:miniature)
</code>```

UPDATE:

You seem to have a crop on :thumb, but for what you want, I would suggest a custom crop of the original, then recreate the versions after that. This Railscast from Ryan Bates explains it well.

Hope this helps!

Body:
I have an avatar_uploader.rb that uses carrierwave to create multiple versions of the uploaded avatar and also has a crop method.

  version :thumb do
    process :crop
    resize_to_fill(100, 100)
  end

  version :miniature do
    resize_to_fill(25, 25)
  end

  version :large do
    resize_to_limit(600, 600)
  end

  def crop
    if model.crop_x.present?
      resize_to_limit(600, 600)
      manipulate! do |img|
        x = model.crop_x.to_i
        y = model.crop_y.to_i
        w = model.crop_w.to_i
        h = model.crop_h.to_i
        img.crop!(x, y, w, h)
      end
    end
  end

The problem is that I need two versions after the crop method is applied. I want a miniature version that is just a smaller version of the thumb, which is a cropped version of the original file.

The crop method requires that the user crop the image and needs to be called through a view to get the x, y, w, h attributes. So it should only be done once. It wouldn't make sense for the user to crop the image twice for two versions.

Now, it would be convenient if I could define the version miniature to apply the resize_to_fill on the thumb version but I don't know what the syntax for that would be.

I want to write this:-

  version :miniature do
    thumb.resize_to_fill(25, 25)
  end

But that just gives an error and says thumb is undefined.

Is there a way to achieve this?

Update:-

I don't think I explained this problem clearly.

The miniature version gets regenerated but the problem is that the crop doesn't alter the original file. It just creates the thumb version. When the miniature version is applied, it miniaturizes the original file, and not the thumb version. I want the same crop as the thumb version but in miniature dimensions. So ideally I want to apply the miniature version on the thumb version. I don't know how to achieve this. Hope this is clearer now.

Body:
You need to call recreate_versions! on your image after the crop to do this. So you could do:

model.image.recreate_versions!(:miniature)

UPDATE:

You seem to have a crop on :thumb, but for what you want, I would suggest a custom crop of the original, then recreate the versions after that. This Railscast from Ryan Bates explains it well.

Hope this helps!


问:
Pass a list of string's in IN clause in DocumentDb Query
This query works when i try to fetch records using IN and multiple Email Id's:

```<code>var families = _client.CreateDocumentQuery<Restraunt>(_documentCollection.SelfLink,
"Select Restraunt.RestrauntId from Restraunt join Rest in Restraunt.Emails where Emails.Email IN ('abc@gmail.com','ab@gmail.com') ").AsEnumerable().ToList();
</code>```

I want to know how can i pass a list of Email id's as a string in the query?
I tried passing the list of strings directly but is unable to resolve that. Is there any way out to do that?

Let's say i have

```<code>List<string> elist=new List<string>{"abc@gmail.com","b@gmail.com"}
</code>```

How can i pass elist in the query?

答:
You can try this:</p>

```<code>List<string> elist=new List<string>{"abc@gmail.com","b@gmail.com"};

string emails = string.Empty;

if (eList!= null)
{
    emails = "'" + string.Join("','", eList.Select(x => x !=  String.Empty? x :"").Distinct().ToArray()) + "'";
    emails = emails.Replace("','','", "','");
}

var families = _client.CreateDocumentQuery<Restraunt>(_documentCollection.SelfLink,
    "Select Restraunt.RestrauntId FROM Restraunt join Rest in Restraunt.Emails
     WHERE Emails.Email IN (" + emails + ") ").AsEnumerable().ToList();
</code>```

Body:
This query works when i try to fetch records using IN and multiple Email Id's:

var families = _client.CreateDocumentQuery<Restraunt>(_documentCollection.SelfLink,
"Select Restraunt.RestrauntId from Restraunt join Rest in Restraunt.Emails where Emails.Email IN ('abc@gmail.com','ab@gmail.com') ").AsEnumerable().ToList();

I want to know how can i pass a list of Email id's as a string in the query?
I tried passing the list of strings directly but is unable to resolve that. Is there any way out to do that?

Let's say i have

List<string> elist=new List<string>{"abc@gmail.com","b@gmail.com"}

How can i pass elist in the query?

Body:
You can try this:

List<string> elist=new List<string>{"abc@gmail.com","b@gmail.com"};

string emails = string.Empty;

if (eList!= null)
{
    emails = "'" + string.Join("','", eList.Select(x => x !=  String.Empty? x :"").Distinct().ToArray()) + "'";
    emails = emails.Replace("','','", "','");
}

var families = _client.CreateDocumentQuery<Restraunt>(_documentCollection.SelfLink,
    "Select Restraunt.RestrauntId FROM Restraunt join Rest in Restraunt.Emails
     WHERE Emails.Email IN (" + emails + ") ").AsEnumerable().ToList();


问:
How can I disable TLSv1.0 with spring boot and embedded tomcat?
I want to de-activate TLSv1.0 with spring boot(release 1.3.3), but it doesn't work if application.yml as below:

ssl:
    protocol: TLSv1.2
    key-store: /E:/key/server.jks
    key-store-password: serverpkcs12

I still can access web page if only choose "USE TLS 1.0" in IE.
See this pic--not work.

However, if doesn't use embedded tomcat, and add these arguments for Connector located in server.xml, it works fine for me--web page blocked by IE. See this pic--worked for me

sslProtocols="TLSv1.2" sslEnabledProtocols="TLSv1.2"

And I also tried some VM arguments, for exmaple -Dhttps.protocols="TLSv1.2", all of them are useless.

So What can I do for this?

答:
The most transparent and readable way is to explicitly configure the valid TLS protocols in your application configuration file by excluding - of course - the unwanted ones.

e.g. in YAML

```<code>server.ssl.enabled-protocols=TLSv1.1,TLSv1.2
</code>```

You can then start your server and check whether TLSv1.0 is working by peforming the following

```<code>openssl s_client -connect localhost:443 -tls1
</code>```

The above connections should be rejected whereas the following two will be accepted and print the certificate's details

```<code>openssl s_client -connect localhost:443 -tls1_1
openssl s_client -connect localhost:443 -tls1_2
</code>```

Body:
The most transparent and readable way is to explicitly configure the valid TLS protocols in your application configuration file by excluding - of course - the unwanted ones.

e.g. in YAML

server.ssl.enabled-protocols=TLSv1.1,TLSv1.2

You can then start your server and check whether TLSv1.0 is working by peforming the following

openssl s_client -connect localhost:443 -tls1

The above connections should be rejected whereas the following two will be accepted and print the certificate's details

openssl s_client -connect localhost:443 -tls1_1
openssl s_client -connect localhost:443 -tls1_2


问:
Google BigQuery SQL: Prevent column prefix renaming after join
Say you have a table "table_with_100_columns."

And you want to add one more column with a simple join... without changing all of the column names. In other words, you wish to write something like

```<code>SELECT a.* as <a's columns without prefix>, additional_field
FROM [table_with_100_columns] a
JOIN [table_with_2_columns] b
ON a.col1 = b.key
</code>```

You should be able to do this to generate a new table with 101 columns, without having to rename every single column by hand. Right now the only way I know how to do this as follows:

```<code>SELECT
  a.col1 as col1,
  a.col2 as col2,
  a.col3 as col3,
  ...
  a.col100 as col100,
  b.additional_field as additional_field
FROM [table_with_100_columns] a
JOIN [table_with_2_columns] b
ON a.col1 = b.key
</code>```

Having to write 100 unnecessary lines of code simply to add one more column to a table is unbelievably inefficient - so I'm hoping there is a better way to preserve column names while joining?

UPDATE

It appears this is not yet possible in BigQuery. It is very easy to implement and I suggest the following to the Google BigQuery team:

```<code>if no fields share a name in SELECT clause:
  if no subtable reference names given:
    Do not rename fields after JOIN
</code>```

This will not break any current functionality and adds simple support for a very useful feature.

答:
Since i needed to stick with Legacy SQL (because Im integrating with another system that uses Legacy SQL and crashes due to column prefixes)

I managed to fix the problem by replacing the selection part of the SQL

```<code>SELECT *
FROM table1 t1
LEFT JOIN table2 t2
ON [some_condition]
GROUP BY [group_columns]
</code>```

To

```<code>SELECT
column1 as new_name1,
column2 as new_name2,
column3 as new_name3
FROM table1 t1
LEFT JOIN table2 t2
ON [some_condition]
GROUP BY [group_columns]
</code>```

Now column1 will be shown as new_name1 rather than t1_column1

Body:
Say you have a table "table_with_100_columns."

And you want to add one more column with a simple join... without changing all of the column names. In other words, you wish to write something like

SELECT a.* as , additional_field
FROM [table_with_100_columns] a
JOIN [table_with_2_columns] b
ON a.col1 = b.key

You should be able to do this to generate a new table with 101 columns, without having to rename every single column by hand. Right now the only way I know how to do this as follows:

SELECT
  a.col1 as col1,
  a.col2 as col2,
  a.col3 as col3,
  ...
  a.col100 as col100,
  b.additional_field as additional_field
FROM [table_with_100_columns] a
JOIN [table_with_2_columns] b
ON a.col1 = b.key

Having to write 100 unnecessary lines of code simply to add one more column to a table is unbelievably inefficient - so I'm hoping there is a better way to preserve column names while joining?

UPDATE

It appears this is not yet possible in BigQuery. It is very easy to implement and I suggest the following to the Google BigQuery team:

if no fields share a name in SELECT clause:
  if no subtable reference names given:
    Do not rename fields after JOIN

This will not break any current functionality and adds simple support for a very useful feature.

Body:
Since i needed to stick with Legacy SQL (because Im integrating with another system that uses Legacy SQL and crashes due to column prefixes)

I managed to fix the problem by replacing the selection part of the SQL

SELECT *
FROM table1 t1
LEFT JOIN table2 t2
ON [some_condition]
GROUP BY [group_columns]

To

SELECT
column1 as new_name1,
column2 as new_name2,
column3 as new_name3
FROM table1 t1
LEFT JOIN table2 t2
ON [some_condition]
GROUP BY [group_columns]

Now column1 will be shown as new_name1 rather than t1_column1


问:
Difference between init() and main() method in java
I want to know the difference between init and main method of java </p>

答:
init method is used when servlets or applets is initialize while main method is used for entry point of program....

If there is first time request for servlet then first of all servlet's init method is called and also some properties may be initialize at that time
While when you start your application main is entry point for that .......means main is first process for your application


问:
EditText Settext not working with Fragment
I have fragments for 3 states of a screen;  Add, Edit and View.
In Add, I create an entity and save it.
Next time I open it in View mode and set the entity name using

```<code>EditText entityName = (EditText) view.findViewById(R.id.entityName);
entityName.setText(entity.getEntityname());
</code>```

I click on the edit button from View mode to open the Edit mode. I change the entity name here and save it. This brings me back to the view screen. But I find the entity name is not updated.
I debug and found that entity.getEntityname()  is having correct value. I am not sure why the edit text does not take new value.

Any ideas?

Note: I am using android version 2.2

答:
There are some classes of View in Android should save their status when their container is detached.
Fragment.onViewCreated() should be called before View.onSaveInstanceState(). So if you set a value in the method Fragment.onViewCreated(). The value should be cleared in the method View.onRestoreInstanceState(Parcelable state).

For example,class TextView,RecyclerView and so on.You can read the code of TextView.java:

```<code>    public Parcelable onSaveInstanceState() {
    Parcelable superState = super.onSaveInstanceState();

    // Save state if we are forced to
    final boolean freezesText = getFreezesText();
    boolean hasSelection = false;
    int start = -1;
    int end = -1;
    ....
    if (freezesText || hasSelection) {
        SavedState ss = new SavedState(superState);
        ....
    }
    ....
   }
</code>```

There are to params to control whether to save the state: "freezesText" and "hasSelection".
TextView can't be selected,so hasSelection is false. the function ,getFreezesText(),return false in class TextView too.
So,TextView would not save the state.
the code of EditText.java:

```<code>    @Override
    public boolean getFreezesText() {
    return true;
    }
</code>```

EditText return true,so EditText should save the state.

There some method to fix this bug:

1.implement EditText.getFreezesText() and return false,and clear the state of select in EditText

2.implement onSaveInstanceState of EditText, return null.like this:

```<code> public Parcelable onSaveInstanceState() {
      super.onSaveInstanceState();
     return null;
 }
</code>```

3.use EditText.setSaveEnable(false);

4.add param in xml " saveEnable='false'"

Body:
I have fragments for 3 states of a screen;  Add, Edit and View.
In Add, I create an entity and save it.
Next time I open it in View mode and set the entity name using

EditText entityName = (EditText) view.findViewById(R.id.entityName);
entityName.setText(entity.getEntityname());

I click on the edit button from View mode to open the Edit mode. I change the entity name here and save it. This brings me back to the view screen. But I find the entity name is not updated.
I debug and found that entity.getEntityname()  is having correct value. I am not sure why the edit text does not take new value.

Any ideas?

Note: I am using android version 2.2

Body:
There are some classes of View in Android should save their status when their container is detached.
Fragment.onViewCreated() should be called before View.onSaveInstanceState(). So if you set a value in the method Fragment.onViewCreated(). The value should be cleared in the method View.onRestoreInstanceState(Parcelable state).

For example,class TextView,RecyclerView and so on.You can read the code of TextView.java:

    public Parcelable onSaveInstanceState() {
    Parcelable superState = super.onSaveInstanceState();

    // Save state if we are forced to
    final boolean freezesText = getFreezesText();
    boolean hasSelection = false;
    int start = -1;
    int end = -1;
    ....
    if (freezesText || hasSelection) {
        SavedState ss = new SavedState(superState);
        ....
    }
    ....
   }

There are to params to control whether to save the state: "freezesText" and "hasSelection".
TextView can't be selected,so hasSelection is false. the function ,getFreezesText(),return false in class TextView too.
So,TextView would not save the state.
the code of EditText.java:

    @Override
    public boolean getFreezesText() {
    return true;
    }

EditText return true,so EditText should save the state.

There some method to fix this bug:

1.implement EditText.getFreezesText() and return false,and clear the state of select in EditText

2.implement onSaveInstanceState of EditText, return null.like this:

 public Parcelable onSaveInstanceState() {
      super.onSaveInstanceState();
     return null;
 }

3.use EditText.setSaveEnable(false);

4.add param in xml " saveEnable='false'"


问:
Datatables iOS, Safari not showing at all
I tried the library, but I encountered error while testing in Safari. All the tables that work on Chrome, IE and Firefox refuse to work on Safari. Tried searching on the library website, but found no relevant information.
I got 2 variables:

```<code>var tabl1;
tabl1= $('#tabl1').DataTable(tabl1DataTableArguments);
</code>```

tabl1DataTableArguments holds all the arguments for the table:

```<code>var tabl1DataTableArguments = {
"dom": "<'row'<'#toolbar1.col-sm-12'>><'row'<'col-sm-4'B><'col-sm-4 text-center'l><'col-sm-4'f>>" +
"<'row'<'#top.col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
buttons: [
    {
        extend: 'excelHtml5',
        title: 'Data',
        exportOptions: {
            columns: [0]
        }
    },
    {
        extend: 'csvHtml5',
        title: 'Data',
        exportOptions: {
            columns: [0]
        }
    },
    {
        extend: 'pdfHtml5',
        title: 'Data',
        exportOptions: {
            columns: [0]
        }, customize: function (doc) {
            doc = CustomizeDataTables(doc);
        }
    },
],
"aLengthMenu": [[5, 10], [5, 10]],
"autoWidth": false,
ajax: {
    url: UrlData,
    method: "POST",
    dataSrc: 'Data'
},
columns: [
    {
        "title": "Title",
        data: 'Title', type: "String", width: "80%",
        render: function (data, type, full, meta) {
            return "<a href='"+full.id+"'>" + data + "</a> ";
        }

    }
]
}
</code>```

The thing I don't understand is why does it work everywhere else, but in Safari it just dies with no errors or anything. When I try to initialize it through the console it says that it is already initialized.

答: My issue was resolved with the latest version of the library.</p>

Body:
I tried the library, but I encountered error while testing in Safari. All the tables that work on Chrome, IE and Firefox refuse to work on Safari. Tried searching on the library website, but found no relevant information.
I got 2 variables:

var tabl1;
tabl1= $('#tabl1').DataTable(tabl1DataTableArguments);

tabl1DataTableArguments holds all the arguments for the table:

var tabl1DataTableArguments = {
"dom": "<'row'<'#toolbar1.col-sm-12'>><'row'<'col-sm-4'B><'col-sm-4 text-center'l><'col-sm-4'f>>" +
"<'row'<'#top.col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
buttons: [
    {
        extend: 'excelHtml5',
        title: 'Data',
        exportOptions: {
            columns: [0]
        }
    },
    {
        extend: 'csvHtml5',
        title: 'Data',
        exportOptions: {
            columns: [0]
        }
    },
    {
        extend: 'pdfHtml5',
        title: 'Data',
        exportOptions: {
            columns: [0]
        }, customize: function (doc) {
            doc = CustomizeDataTables(doc);
        }
    },
],
"aLengthMenu": [[5, 10], [5, 10]],
"autoWidth": false,
ajax: {
    url: UrlData,
    method: "POST",
    dataSrc: 'Data'
},
columns: [
    {
        "title": "Title",
        data: 'Title', type: "String", width: "80%",
        render: function (data, type, full, meta) {
            return "" + data + " ";
        }

    }
]
}

The thing I don't understand is why does it work everywhere else, but in Safari it just dies with no errors or anything. When I try to initialize it through the console it says that it is already initialized.


问:
Is there a reason for me to use Bintray if we are a node.js shop?
If I understand correctly, Bintray is a multi-faceted package management solution (e.g., it can manage not only npm packages, but also rubyGems and a lot of others) see this diagram from jfrog; and I understand npm server provide the same capability, but only for node.js package formats, see this blog from npmjs

My question is whether I my understanding toward Bintray is correct. i.e., if my goal is to build a private npm package manager service for my org, Bintray and npm server has no fundamental difference to achieve the goal from functionality perspective.

答:
I think the biggest reason to use Bintray, is its Universal solution.

I assume that on top of developing with node.js, you might also pack your apps as a Docker image, Vagrant box or an RPM package for distribution. Bintray will allow you to use it for Docker, Vagrant and RPM distributions too!

Of course, there are many other package types supported.

Look in https://www.jfrog.com/bintray/bintray-features/ for a long list of additional features that make Bintray a great solution for all your distribution needs.

I hope this helps.


问:
How to branch the whole repository including ignore files
I have a project, which is in the Mercurial repository. In the root folder there is a .hgignore file, which states, that the "Bin" folder should be ignored (and also some other files and folders).

Now I want to clone this repository but in a way, that ALL folders and files should be cloned, also the original ignored ones. If I just clone the repository, than I get only the files, which are included in the repository thus my bin folder is missing.

How can I get cloned repository with all files in it? I want to merge these two repositories together in a while...

PS - I am working on a legacy application which has a lot of external dll-s in the bin folder of the application. I know I should put them to a seperate folder, but that's another story.

答:
An ignored file is not in your repository, so it will not be cloned. You should copy these files by hand after you have cloned the repository.
When you copy those files, I think it won't be a problem if you overwrite other files that are in your repository (they're essentially the same files after all), so as long as you don't copy the .hg folder in the root of your checkout, you'll probably be fine.</p>


问:
check string valid or not in PHP
How to know which word has valid id card with criterion? If id card has 10 characters or more then id card is valid otherwise it is not valid.

example of sentences :

```<code>$String_1 = "i'm john and my id card 12334435345 my favorite team xxxxxxxx.";

$String_2 = "i'm ananda ramadina and my id card 9090909889 my favorite team YYYYYYYYYY.";

$String_3 = "i'm dinda rahayu and my id card 909 my favorite team RRRRRRRR.";
</code>```

答:
Try This:-</p>

```<code>$string_1 = "i'm john and my id card 125345 my favorite team xxxxxxxx.";

/* using regex to match string */
preg_match("/id card ([0-9]*)?/", $string_1, $output_array);

/* this will assign $getNumber the value of $output_array[1] if it exists, otherwise a blank value */
$getNumber = isset($output_array[1]) ? $output_array[1] : "";

if(strlen($getNumber) >= 10) {
    echo "valid";
} else {
    echo "invalid";
}
</code>```

Title: check string valid or not in PHP

Body:
How to know which word has valid id card with criterion? If id card has 10 characters or more then id card is valid otherwise it is not valid.

example of sentences :

$String_1 = "i'm john and my id card 12334435345 my favorite team xxxxxxxx.";

$String_2 = "i'm ananda ramadina and my id card 9090909889 my favorite team YYYYYYYYYY.";

$String_3 = "i'm dinda rahayu and my id card 909 my favorite team RRRRRRRR.";

Body:
Try This:-

$string_1 = "i'm john and my id card 125345 my favorite team xxxxxxxx.";

/* using regex to match string */
preg_match("/id card ([0-9]*)?/", $string_1, $output_array);

/* this will assign $getNumber the value of $output_array[1] if it exists, otherwise a blank value */
$getNumber = isset($output_array[1]) ? $output_array[1] : "";

if(strlen($getNumber) >= 10) {
    echo "valid";
} else {
    echo "invalid";
}


问:
How to show only date from DataGridView to label
I am working on C# and sql server. I saved date using DateTimePicker to sql. Now I am using DataGridView to show record then by selecting a row that data is shown on labels. Problem is I want to show only date but through the following method time is also coming along.

```<code> private void datagridpatient_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        lblgridpbirthday.Text = row.Cells["Birthday"].Value.ToString();
    }
</code>```

How to show only date?

答:
Try the below,</p>

```<code>lblgridpbirthday.Text = Convert.ToDateTime(row.Cells["Birthday"].Value).ToString("YourDateFormatHere");
</code>```

Body:
I am working on C# and sql server. I saved date using DateTimePicker to sql. Now I am using DataGridView to show record then by selecting a row that data is shown on labels. Problem is I want to show only date but through the following method time is also coming along.

 private void datagridpatient_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        lblgridpbirthday.Text = row.Cells["Birthday"].Value.ToString();
    }

How to show only date?

Body:
Try the below,

lblgridpbirthday.Text = Convert.ToDateTime(row.Cells["Birthday"].Value).ToString("YourDateFormatHere");


问:
Catch Unfortunately app has crashed in app level in Android
I want to know is there any option to catch the exception in application level to stop showing Unfortunately, (App Name) has stopped. instead I want to show my custom message to the user when it crashes.

Ex: If the app crashes in any of the screen in the app I need to capture that like Crashlytics and want to show my custom message. How to do it?

答:
I personnally do it like this :

```<code>Thread.currentThread().setUncaughtExceptionHandler(new  Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            //DO YOUR JOB HERE
        }
    });
</code>```

Put this in your oncreate of activity or application. The best is to save this on your application server, and advertise your user something happenned.

Body:
I personnally do it like this :

Thread.currentThread().setUncaughtExceptionHandler(new  Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            //DO YOUR JOB HERE
        }
    });

Put this in your oncreate of activity or application. The best is to save this on your application server, and advertise your user something happenned.


问:
Qt - How to show a QLabel in fullscreen on my laptop?
I have a ui with a QButton and a QLabel. I would like the QLabel to be displayed on fullscreen on my laptop whenever I push that button.

I tried the following code:

```<code>void MainWindow::on_fullScreenBtn_clicked()
{
    // ui->myImage is a QLabel*
    ui->myImage->setText("going full screen");
    ui->myImage->showMaximized();
    ui->myImage->QWidget::showFullScreen();
}
</code>```

I can see this function gets executed, but this doesn't display my label in full screen. What am I doing incorrectly/ missing?

I am using QtCreator 3.5.1 and made my gui using the built-in graphical interface.

EDIT: The variable myImage is a QLabel containing an image

答:
The showMaximized and showFullScreens work on a QWidget that dont have a parent (that are actual windows, not contained widgets). so you have a few different options there on your code.

1 - Create a QStackedLayout or QStackedWidget with only your QLabel, and when you trigger your slot, do this:

```<code>void MainWindow::on_fullScreenBtn_clicked()
{
    ui->stackedWidget->setCurrentIndex( indexOfTheLabel);
}
</code>```

this will make the Label take the whole screen.

2 - You can also remove the parent of the QLabel, but this will generate a complicated mess, so, don't.

```<code>void MainWindow::on_fullScreenBtn_clicked()
{
    ui->myImage->setParent(nullptr);
    ui->myImage->setText("going full screen");
    ui->myImage->showMaximized();
    ui->myImage->showFullScreen();
}
</code>```

Don't do this second one.

Body:
I have a ui with a QButton and a QLabel. I would like the QLabel to be displayed on fullscreen on my laptop whenever I push that button.

I tried the following code:

void MainWindow::on_fullScreenBtn_clicked()
{
    // ui->myImage is a QLabel*
    ui->myImage->setText("going full screen");
    ui->myImage->showMaximized();
    ui->myImage->QWidget::showFullScreen();
}

I can see this function gets executed, but this doesn't display my label in full screen. What am I doing incorrectly/ missing?

I am using QtCreator 3.5.1 and made my gui using the built-in graphical interface.

EDIT: The variable myImage is a QLabel containing an image

Body:
The showMaximized and showFullScreens work on a QWidget that dont have a parent (that are actual windows, not contained widgets). so you have a few different options there on your code.

1 - Create a QStackedLayout or QStackedWidget with only your QLabel, and when you trigger your slot, do this:

void MainWindow::on_fullScreenBtn_clicked()
{
    ui->stackedWidget->setCurrentIndex( indexOfTheLabel);
}

this will make the Label take the whole screen.

2 - You can also remove the parent of the QLabel, but this will generate a complicated mess, so, don't.

void MainWindow::on_fullScreenBtn_clicked()
{
    ui->myImage->setParent(nullptr);
    ui->myImage->setText("going full screen");
    ui->myImage->showMaximized();
    ui->myImage->showFullScreen();
}

Don't do this second one.


问:
Is there a way to have a single view not rotate?
I am trying to create a view that doesn't rotate with device orientation.  I want just this one view to not rotate because I have a UIToolbar that I don't want to rotate.  Is this possible?  If so, how do I implement it?  I am using Swift.  Also, is it possible to rotate the UIBarButtonItems with device orientation on the UIToolbar?  If so, how do I implement that?  Just to restate: I want the view and toolbar within it to not rotate with orientation; I want the buttons on the toolbar to rotate with orientation.  Thanks.</p>

答:
Straightforward. You should simply override the shouldRotate variable and set it to false for the VC you wish to prevent rotation in.

UPDATED - Swift 3

```<code>override var shouldAutorotate: Bool {
    return false
}
</code>```

Body:
Straightforward. You should simply override the shouldRotate variable and set it to false for the VC you wish to prevent rotation in.

UPDATED - Swift 3

override var shouldAutorotate: Bool {
    return false
}


问:
Storing actively updated fields in the database
I have a database with one of the table storing articles. For every article I need to store the number of times it was viewed. Now, my idea is to store this value in the database and update it every time someone visits the page with that article and I am considering two alternatives now:

Create a column views in the table articles and update it.

Create a separate table view_count with FK pointer to the article and the number views for that article.

My question is: is there any difference between these two approaches in terms of speed and why? Are there any better alternatives?

The database I use is PostgreSQL.

Note, that I am not considering the different ways of accumulating those values in separate files, outside of database and later inserting because i) we do not get as many hits ii) the feature in minor and if it would require such a hassle we would rather abandon it and use some other service for that.

答:
I have one more approach, where I do the update later in the day or when the traffic to the site is too less.
I would do the job in this way, when ever any user reads the articles, there user id will be stored in a new table, and later through script I can update How many times the article have been read by the users.</p>


答:
Try this</p>

```<code>$String_1 = "i'm john and my id card 12334435345 my favorite team xxxxxxxx.";
$intVal = filter_var($String_1, FILTER_SANITIZE_NUMBER_INT);
$count = strlen($intVal);
if ($count >= 10) {
// some logic
}
</code>```

Title: check string valid or not in PHP

Body:
Try this

$String_1 = "i'm john and my id card 12334435345 my favorite team xxxxxxxx.";
$intVal = filter_var($String_1, FILTER_SANITIZE_NUMBER_INT);
$count = strlen($intVal);
if ($count >= 10) {
// some logic
}


问:
Java - append excel
i need to append excel. I write code:

```<code>import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

    public class AppendExcel {

public static void main(String[] args) throws Exception {
    String excelFilePath = "append.xlsx";

    try {
        FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
        Workbook workbook = WorkbookFactory.create(inputStream);

        Sheet sheet = workbook.getSheetAt(0);

        DbManagerSQL test = new DbManagerSQL();
        String sql = "select distinct Code,Item,Description from MyTable";

        Statement stmt = test.dbConnect().createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        int rowCount = sheet.getLastRowNum();
        while (rs.next()) {

            Row row = sheet.createRow(++rowCount);

            int columnCount = 0;

            Cell cell = row.createCell(columnCount);
            cell.setCellValue(rowCount);

            cell = row.createCell(++columnCount);
            cell.setCellValue((String) rs.getString(1));
            cell.setCellValue((String) rs.getString(2));
            cell.setCellValue((String) rs.getString(3));

        }

        inputStream.close();

        FileOutputStream outputStream = new FileOutputStream("append.xlsx");
        workbook.write(outputStream);
        // workbook.close();
        outputStream.close();

    } catch (IOException | EncryptedDocumentException | InvalidFormatException ex) {
        ex.printStackTrace();
    }
}

}
</code>```

My Excel has the column

but when I append Excel I got next

It looks like remember only the last column. I think the prblem is in this line of code

cell = row.createCell(++columnCount);

but i don't now how to add data to get excel like this

Any idea???

答:
You increment your columnCount in the while:

```<code>int columnCount = 0;
cell = row.createCell(++columnCount);
</code>```

So you always write in the same cell. You must put the initialization out of the wile.

Title: Java - append excel

Body:
i need to append excel. I write code:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

    public class AppendExcel {

public static void main(String[] args) throws Exception {
    String excelFilePath = "append.xlsx";

    try {
        FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
        Workbook workbook = WorkbookFactory.create(inputStream);

        Sheet sheet = workbook.getSheetAt(0);

        DbManagerSQL test = new DbManagerSQL();
        String sql = "select distinct Code,Item,Description from MyTable";

        Statement stmt = test.dbConnect().createStatement();
        ResultSet rs = stmt.executeQuery(sql);

        int rowCount = sheet.getLastRowNum();
        while (rs.next()) {

            Row row = sheet.createRow(++rowCount);

            int columnCount = 0;

            Cell cell = row.createCell(columnCount);
            cell.setCellValue(rowCount);

            cell = row.createCell(++columnCount);
            cell.setCellValue((String) rs.getString(1));
            cell.setCellValue((String) rs.getString(2));
            cell.setCellValue((String) rs.getString(3));

        }

        inputStream.close();

        FileOutputStream outputStream = new FileOutputStream("append.xlsx");
        workbook.write(outputStream);
        // workbook.close();
        outputStream.close();

    } catch (IOException | EncryptedDocumentException | InvalidFormatException ex) {
        ex.printStackTrace();
    }
}

}

My Excel has the column

but when I append Excel I got next

It looks like remember only the last column. I think the prblem is in this line of code

cell = row.createCell(++columnCount);

but i don't now how to add data to get excel like this

Any idea???

Body:
You increment your columnCount in the while:

int columnCount = 0;
cell = row.createCell(++columnCount);

So you always write in the same cell. You must put the initialization out of the wile.


问:
How does HTTP error-handling work with observables?
I see a lot of tutorials doing something like this:

```<code>http.get("...").subscribe(
  success => console.log('hello success'),
  error => console.log('bye error')
);
</code>```

I don't know how this works, since there aren't any types or anything, however I tried to do that myself and I end up that the request always goes into success, even if I have an error. What is the problem?

Troublemaker:

```<code>this.memberService.create(this.currentMember)
      .subscribe(
        success => {
          let mem: Member = success.json() as Member;
          if (this.selectedOrganization) {
            this.addMemberToOrganization(mem);
          } else if (this.selectedServiceProvider) {
            this.addMemberToServiceProvider(mem);
          } else {
            this.toastsService.error("lbl_users_service_provider_and_organization_undefined");
          }
        },
        error => console.log(error)
      );
</code>```

Create-Method in the memberService:

```<code>  create(member: Member): Observable<any> {
    return this.http
      .post(this.RESOURCE_BASE_URL, member)
      .map(response => {
        if (response.status === 200) this.toastsSerivce.success(this.translateService.instant('lbl_users_member_created'));
        return response;
      })
      .catch(error => this.toastsSerivce.error(this.translateService.instant('lbl_users_member_create_failed')));
  }
</code>```

I even catch the error, but the subscribe part doesn't seem to care.
It fails at success.json(), because if there is an error, there is no json. But if there is an error, I want it to call the error =>... instead of the success. Any advice is highly appreciated.

答:
I think the issue is that you are not throwing the error with an Observable.throw(errMsg).

So, you may just use it like this:

```<code>.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
</code>```

In your example:

```<code>create(member: Member): Observable<any> {
    return this.http
      .post(this.RESOURCE_BASE_URL, member)
      .map(response => {
        if (response.status === 200) this.toastsSerivce.success(this.translateService.instant('lbl_users_member_created'));
        return response;
      })
      .catch((error:any) => Observable.throw(this.toastsSerivce.error(this.translateService.instant('lbl_users_member_create_failed'))));
  }
</code>```

But, you could use an error handler, like the one Angular proposes here:

```<code>private handleError (error: Response | any) {
    // In a real world app, you might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }
</code>```

And so, your method would look more like this:

```<code>create(member: Member): Observable<any> {
    return this.http
      .post(this.RESOURCE_BASE_URL, member)
      .map(response => {
        if (response.status === 200) this.toastsSerivce.success(this.translateService.instant('lbl_users_member_created'));
        return response;
      })
      .catch(this.handleError);
  }
</code>```

It's actually cleaner and more reusable for other methods that you may create within your service.

I would suggest to use also a response handler, like the one used by Angular's devs: this.extractData.

Obviusly, inside the error handle method you can put your own custom logic, depends on how you want to show or handle the error.

NOTE: I did not test your code nor the code I posted here. But I wanted to show/express the concept. You should throw the error in order to not going into success everytime. How you handle it depends on you and your App.

Body:
I see a lot of tutorials doing something like this:

http.get("...").subscribe(
  success => console.log('hello success'),
  error => console.log('bye error')
);

I don't know how this works, since there aren't any types or anything, however I tried to do that myself and I end up that the request always goes into success, even if I have an error. What is the problem?

Troublemaker:

this.memberService.create(this.currentMember)
      .subscribe(
        success => {
          let mem: Member = success.json() as Member;
          if (this.selectedOrganization) {
            this.addMemberToOrganization(mem);
          } else if (this.selectedServiceProvider) {
            this.addMemberToServiceProvider(mem);
          } else {
            this.toastsService.error("lbl_users_service_provider_and_organization_undefined");
          }
        },
        error => console.log(error)
      );

Create-Method in the memberService:

  create(member: Member): Observable<any> {
    return this.http
      .post(this.RESOURCE_BASE_URL, member)
      .map(response => {
        if (response.status === 200) this.toastsSerivce.success(this.translateService.instant('lbl_users_member_created'));
        return response;
      })
      .catch(error => this.toastsSerivce.error(this.translateService.instant('lbl_users_member_create_failed')));
  }

I even catch the error, but the subscribe part doesn't seem to care.
It fails at success.json(), because if there is an error, there is no json. But if there is an error, I want it to call the error =>... instead of the success. Any advice is highly appreciated.

Body:
I think the issue is that you are not throwing the error with an Observable.throw(errMsg).

So, you may just use it like this:

.catch((error:any) => Observable.throw(error.json().error || 'Server error'));

In your example:

create(member: Member): Observable<any> {
    return this.http
      .post(this.RESOURCE_BASE_URL, member)
      .map(response => {
        if (response.status === 200) this.toastsSerivce.success(this.translateService.instant('lbl_users_member_created'));
        return response;
      })
      .catch((error:any) => Observable.throw(this.toastsSerivce.error(this.translateService.instant('lbl_users_member_create_failed'))));
  }

But, you could use an error handler, like the one Angular proposes here:

private handleError (error: Response | any) {
    // In a real world app, you might use a remote logging infrastructure
    let errMsg: string;
    if (error instanceof Response) {
      const body = error.json() || '';
      const err = body.error || JSON.stringify(body);
      errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
    } else {
      errMsg = error.message ? error.message : error.toString();
    }
    console.error(errMsg);
    return Observable.throw(errMsg);
  }

And so, your method would look more like this:

create(member: Member): Observable<any> {
    return this.http
      .post(this.RESOURCE_BASE_URL, member)
      .map(response => {
        if (response.status === 200) this.toastsSerivce.success(this.translateService.instant('lbl_users_member_created'));
        return response;
      })
      .catch(this.handleError);
  }

It's actually cleaner and more reusable for other methods that you may create within your service.

I would suggest to use also a response handler, like the one used by Angular's devs: this.extractData.

Obviusly, inside the error handle method you can put your own custom logic, depends on how you want to show or handle the error.

NOTE: I did not test your code nor the code I posted here. But I wanted to show/express the concept. You should throw the error in order to not going into success everytime. How you handle it depends on you and your App.


问:
Can someone help me work out this error
This is my code, it is writen in python version 2.7.13:

```<code>import random
num=random.sample(range(1,9),4)
print(num)
thing=1
while thing==1:
    while thing==1:
        Usernum=str(input("Input a number of four DIFFRENT digits all of which are between 1 and 9 or exit"))
        if Usernum = "exit":
            print("Goodbye")
            break
        else:
            pass
        if len(set(Usernum)) == 4:
            pass
        else:
            print("You enterd a number that wasn't 4 digits, please try again!")
            thing==1
            pass

        if Usernum.isdigit:
            pass
        else:
            print("you entered something that isnt a number, please try again!")
            pass
        num1,num2,num3,num4 = Usernum.split()
        if num1 in (num2,num3,nub4) or num2 in (num3,num4) or num3==num4:
            print("you ented a number with duplicate digits, Please try again!")
        else:
            break
else:
pass
</code>```

Before i am getting a  error which I have never seen before. It says:

"ValueError: need more than 1 value to unpack"

答:
You need to double check your equalities. In python, and many other languages, double equals == is a logical test. A single = is an assignment. Double check this through your code.

Also on the last line you have not indented your pass properly, but as you have this right everywhere else I assume this is because you aren't finished yet. Hope this helps.

Title: Can someone help me work out this error

Body:
This is my code, it is writen in python version 2.7.13:

import random
num=random.sample(range(1,9),4)
print(num)
thing=1
while thing==1:
    while thing==1:
        Usernum=str(input("Input a number of four DIFFRENT digits all of which are between 1 and 9 or exit"))
        if Usernum = "exit":
            print("Goodbye")
            break
        else:
            pass
        if len(set(Usernum)) == 4:
            pass
        else:
            print("You enterd a number that wasn't 4 digits, please try again!")
            thing==1
            pass

        if Usernum.isdigit:
            pass
        else:
            print("you entered something that isnt a number, please try again!")
            pass
        num1,num2,num3,num4 = Usernum.split()
        if num1 in (num2,num3,nub4) or num2 in (num3,num4) or num3==num4:
            print("you ented a number with duplicate digits, Please try again!")
        else:
            break
else:
pass

Before i am getting a  error which I have never seen before. It says:

"ValueError: need more than 1 value to unpack"


问:
String was not recognized as a valid DateTime error when compare two datetime variable
```<code>string date1="06/06/2017";
string date2="06/05/2017";
</code>```

The dates are in format mm/dd/yyyy.I need to compare two dates

```<code>string test = DateTime.ParseExact(date1, "DD/M/yyyy", CultureInfo.InvariantCulture);
</code>```

I am unable to find out why I am getting error like String was not recognized as a valid DateTime.

答:
The dates are in format "mm/dd/yyyy"

If dates are in this format use "MM/dd/yyyy" in ParseExact():

```<code>var test = DateTime.ParseExact(date1, "MM/dd/yyyy", CultureInfo.InvariantCulture);
</code>```

Also, ParseExact() returns DateTime, not string. Use var or DateTime.

Body:
string date1="06/06/2017";
string date2="06/05/2017";

The dates are in format mm/dd/yyyy.I need to compare two dates

string test = DateTime.ParseExact(date1, "DD/M/yyyy", CultureInfo.InvariantCulture);

I am unable to find out why I am getting error like String was not recognized as a valid DateTime.

Body:
The dates are in format "mm/dd/yyyy"

If dates are in this format use "MM/dd/yyyy" in ParseExact():

var test = DateTime.ParseExact(date1, "MM/dd/yyyy", CultureInfo.InvariantCulture);

Also, ParseExact() returns DateTime, not string. Use var or DateTime.


问:
Use (write) SQL recursion to retrieve category level 2 in Hybris
I have a category organized by tree.
But the depth is not fixed.
When I have a child node.
So,How can I get category level 2 of the above node (also category).
Know that, Cat2CatRel (Category to Category Relation)is many to many.</p>

答:
May be you can use java API :</p>

```<code>List<CategoryModel> categories = category.getAllSubcategories();
categories.get(1);
</code>```

Body:
May be you can use java API :

List<CategoryModel> categories = category.getAllSubcategories();
categories.get(1);


问:
Automatically fill in the form based on input?
I've got a form
and in this form there is a "klasse", supposed to be a weight range lets say 975-1025. Now there are 20 weights to fill in.. is there a way to automatically fill in those number inputs based on the range of said range? (975 and 1025) auto fill 1000 on the inputs.

Thanks in advance!!

```<code><?php
     if(isset($_POST['update'])) {
        $dbhost = 'localhost';
        $dbuser = 'heijsdb_user';
        $dbpass = 'maus';

        $conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect($dbhost,  $dbuser,  $dbpass));

        if(! $conn ) {
           die('Could not connect: ' . mysqli_error($GLOBALS["___mysqli_ston"]));
        }
         $codering = 'RF-400.09';
         $revisie = '5';
         $controleur = $_POST['controleur'];

                        $sql = "INSERT INTO thermometer (Controleur, codering, revisie,)
                        VALUES ('$controleur', '$codering', '$revisie','$weeknr')"  ;
        mysqli_select_db($GLOBALS["___mysqli_ston"], heijsdb);

        $retval = mysqli_query( $conn ,  $sql);

        if(! $retval ) {
           die('Could not update data: ' . mysqli_error($GLOBALS["___mysqli_ston"]));
        }
        echo "Formulier verstuurd.";

        ((is_null($___mysqli_res = mysqli_close($conn))) ? false : $___mysqli_res);
     }else {
        ?>
           <form method = "post" action = "<?php $_PHP_SELF ?>" id="form1">
        <table border ="2" cellspacing = "5" cellpadding = "5" align="center">
            <tr><td ><b>Controleur:</b></td><td colspan="4"><input type = "text" name="controleur" value="<?php echo $_SESSION["username"]; ?>" readonly></td></tr>
            <tr>
                <td>Product</td>
                <td><input type="text" name="product"></td>
            </tr>
            <tr>
                <td>Afnemer:</td>
                <td><input type="text" name="afnemer"></td>
            </tr>
            <td>Tijd:</td>
                <td><input type="time" name="tijd"></td>
            </tr>
            <tr>
                <td>Netto gew</td>
                <td><input type="number" name="netto"></td>
            </tr>
            <tr>
                <td>Gewicht klasse</td>
                <td><input type="number" name="klasse">
                <input type="number" name="klasse1">
                </td>
            </tr>
            <tr>
                <td>Kuiken 1</td>
                <td><input type="number" name="gew1"></td>
            </tr>
            <tr>
                <td>Kuiken 2</td>
                <td><input type="number" name="gew2"></td>
            </tr>
            <tr>
                <td>Kuiken 3</td>
                <td><input type="number" name="gew3"></td>
            </tr>
            <tr>
                <td>Kuiken 4</td>
                <td><input type="number" name="gew4"></td>
            </tr>
            <tr>
                <td>Kuiken 5</td>
                <td><input type="number" name="gew5"></td>
            </tr>
            <tr>
                <td>Kuiken 6</td>
                <td><input type="number" name="gew6"></td>
            </tr>
            <tr>
                <td>Kuiken 7</td>
                <td><input type="number" name="gew7"></td>
            </tr>
            <tr>
                <td>Kuiken 8</td>
                <td><input type="number" name="gew8"></td>
            </tr>
            <tr>
                <td>Kuiken 9</td>
                <td><input type="number" name="gew9"></td>
            </tr>
            <tr>
                <td>Kuiken 10</td>
                <td><input type="number" name="gew10"></td>
            </tr>
            <tr>
                <td>Kuiken 11</td>
                <td><input type="number" name="gew11"></td>
            </tr>
            <tr>
                <td>Kuiken 12</td>
                <td><input type="number" name="gew12"></td>
            </tr>
            <tr>
                <td>Kuiken 13</td>
                <td><input type="number" name="gew13"></td>
            </tr>
            <tr>
                <td>Kuiken 14</td>
                <td><input type="number" name="gew14"></td>
            </tr>
            <tr>
                <td>Kuiken 15</td>
                <td><input type="number" name="gew15"></td>
            </tr>
            <tr>
                <td>Kuiken 16</td>
                <td><input type="number" name="gew16"></td>
            </tr>
            <tr>
                <td>Kuiken 17</td>
                <td><input type="number" name="gew17"></td>
            </tr>
            <tr>
                <td>Kuiken 18</td>
                <td><input type="number" name="gew18"></td>
            </tr>
            <tr>
                <td>Kuiken 19</td>
                <td><input type="number" name="gew19"></td>
            </tr>
            <tr>
                <td>Kuiken 20</td>
                <td><input type="number" name="gew20"></td>
            </tr>

        <table class="w3-centered w3-panel">
            <tr>

            </tr>
          </tfoot>
        </table>

<style>td {
  padding: 15px;
  border: 1px solid #ddd;

    }
</style>
<input type="submit" name="update" value="Formulier versturen" class="w3-bar w3-red" action="<?php echo $_SERVER['PHP_SELF']; ?>">
   </form>
</code>```

答:
I'm not sure I understand what you mean : do you want to autofill all of the 20 fields after a user has written in the first ?
if so, you could use javascript on input change  :

```<code>document.getElementById('klasse1').value //you should add an id to that input
</code>```

(see here for detecting the event Detecting input change in jQuery?)

Then you can populate the fields

```<code>document.getElementById('gew1').value = "the range";
</code>```

you can use a for loop to loop through the 20 fields

Body:
I've got a form
and in this form there is a "klasse", supposed to be a weight range lets say 975-1025. Now there are 20 weights to fill in.. is there a way to automatically fill in those number inputs based on the range of said range? (975 and 1025) auto fill 1000 on the inputs.

Thanks in advance!!

<?php
     if(isset($_POST['update'])) {
        $dbhost = 'localhost';
        $dbuser = 'heijsdb_user';
        $dbpass = 'maus';

        $conn = ($GLOBALS["___mysqli_ston"] = mysqli_connect($dbhost,  $dbuser,  $dbpass));

        if(! $conn ) {
           die('Could not connect: ' . mysqli_error($GLOBALS["___mysqli_ston"]));
        }
         $codering = 'RF-400.09';
         $revisie = '5';
         $controleur = $_POST['controleur'];

                        $sql = "INSERT INTO thermometer (Controleur, codering, revisie,)
                        VALUES ('$controleur', '$codering', '$revisie','$weeknr')"  ;
        mysqli_select_db($GLOBALS["___mysqli_ston"], heijsdb);

        $retval = mysqli_query( $conn ,  $sql);

        if(! $retval ) {
           die('Could not update data: ' . mysqli_error($GLOBALS["___mysqli_ston"]));
        }
        echo "Formulier verstuurd.";

        ((is_null($___mysqli_res = mysqli_close($conn))) ? false : $___mysqli_res);
     }else {
        ?>
           <form method = "post" action = "<?php $_PHP_SELF ?>" id="form1">

Controleur:	<input type = "text" name="controleur" value="<?php echo $_SESSION["username"]; ?>" readonly>

                Product
                <input type="text" name="product">

                Afnemer:
                <input type="text" name="afnemer">

            Tijd:
                <input type="time" name="tijd">

                Netto gew
                <input type="number" name="netto">

                Gewicht klasse
                <input type="number" name="klasse">
                <input type="number" name="klasse1">

                Kuiken 1
                <input type="number" name="gew1">

                Kuiken 2
                <input type="number" name="gew2">

                Kuiken 3
                <input type="number" name="gew3">

                Kuiken 4
                <input type="number" name="gew4">

                Kuiken 5
                <input type="number" name="gew5">

                Kuiken 6
                <input type="number" name="gew6">

                Kuiken 7
                <input type="number" name="gew7">

                Kuiken 8
                <input type="number" name="gew8">

                Kuiken 9
                <input type="number" name="gew9">

                Kuiken 10
                <input type="number" name="gew10">

                Kuiken 11
                <input type="number" name="gew11">

                Kuiken 12
                <input type="number" name="gew12">

                Kuiken 13
                <input type="number" name="gew13">

                Kuiken 14
                <input type="number" name="gew14">

                Kuiken 15
                <input type="number" name="gew15">

                Kuiken 16
                <input type="number" name="gew16">

                Kuiken 17
                <input type="number" name="gew17">

                Kuiken 18
                <input type="number" name="gew18">

                Kuiken 19
                <input type="number" name="gew19">

                Kuiken 20
                <input type="number" name="gew20">

<input type="submit" name="update" value="Formulier versturen" class="w3-bar w3-red" action="<?php echo $_SERVER['PHP_SELF']; ?>">
   </form>

Body:
I'm not sure I understand what you mean : do you want to autofill all of the 20 fields after a user has written in the first ?
if so, you could use javascript on input change  :

document.getElementById('klasse1').value //you should add an id to that input

(see here for detecting the event Detecting input change in jQuery?)

Then you can populate the fields

document.getElementById('gew1').value = "the range";

you can use a for loop to loop through the 20 fields