问:
Trying To Filter Only Rows That Meet Two Criteria
I promise I have read through the Query information page, but obviously I am missing/misunderstanding something.

I have a Table that has the statuses for multiple departments (the fields are Strings). When a user loads that table I want App Maker to hide jobs that have been finished.

The way we categorize a job as finishes is when:

The Inventory Status = Complete and when the The Delivery Status = Delivered.

Both these conditions need to be met.

Example:

Inventory (Complete) + Delivery (Delivered) = hide

Inventory (In Progress) + Delivery (Delivered) = don't hide

Inventory (Complete) + Delivery (Scheduled) = don't hide

I tried the following, however it hides all the example listed above, not just the first one.

```<code>var datasource = app.datasources.SystemOrders;
var inventory = ['Complete'];
var delivery = ['Delivered'];
    datasource.query.filters.InventoryStatus._notIn = inventory;
    datasource.query.filters.DeliveryStatus._notIn = delivery;
    datasource.load();
</code>```

I have also tried this:

```<code>var datasource = app.datasources.SystemOrders;
    datasource.query.filters.InventoryStatus._notIn = 'Complete';
    datasource.query.filters.DeliveryStatus._notIn = 'Delivered';
    datasource.load();
</code>```

But I get this error:

Type mismatch: Cannot set type String for property _notIn. Type List is expected. at SystemOrders.ToolBar.Button2.onClick:2:46

Any help would be greatly appreciated.

答:
Filters are using AND operator. Please consider switching the Datasource Query Builder and applying the following query:

"InventoryStatus != :CompleteStatus OR DeliveryStatus != :DeliveredStatus"

Set CompleteStatus variable to Complete
Set DeliveredStatus variable to Delivered

Explanation:
Filter you want to apply is "NOT(InventoryStatus = Complete AND DeliveryStatus = Delivered)" which is equivalent to "InventoryStatus != Complete OR DeliveryStatus != Delivered".

Body:
I promise I have read through the Query information page, but obviously I am missing/misunderstanding something.

I have a Table that has the statuses for multiple departments (the fields are Strings). When a user loads that table I want App Maker to hide jobs that have been finished.

The way we categorize a job as finishes is when:

The Inventory Status = Complete and when the The Delivery Status = Delivered.

Both these conditions need to be met.

Example:

Inventory (Complete) + Delivery (Delivered) = hide

Inventory (In Progress) + Delivery (Delivered) = don't hide

Inventory (Complete) + Delivery (Scheduled) = don't hide

I tried the following, however it hides all the example listed above, not just the first one.

var datasource = app.datasources.SystemOrders;
var inventory = ['Complete'];
var delivery = ['Delivered'];
    datasource.query.filters.InventoryStatus._notIn = inventory;
    datasource.query.filters.DeliveryStatus._notIn = delivery;
    datasource.load();

I have also tried this:

var datasource = app.datasources.SystemOrders;
    datasource.query.filters.InventoryStatus._notIn = 'Complete';
    datasource.query.filters.DeliveryStatus._notIn = 'Delivered';
    datasource.load();

But I get this error:

Type mismatch: Cannot set type String for property _notIn. Type List is expected. at SystemOrders.ToolBar.Button2.onClick:2:46

Any help would be greatly appreciated.


来源: stackexchange

问:
Matlab - Creating two arrays that consider all possible values for two objects
I have two physical "objects." I am representing their positions with two different arrays.

• Object 1 moves in the xy-plane only

• Object 2 moves in all three physical dimensions

Objective: Vectorize the four for loops without distorting the data. Also, the intent is to perform this operation for all possible values of object 1 to be compared with object 2.

Here is the code snippet:

```<code>Npos = 21;
Nsam = 200;

% dummy initialisation
AX = rand(1, Npos);
AY = zeros(1, Npos);
AZ = rand(1, Npos);
Bx = rand(Nsam);
By = rand(Nsam);
Bz = rand(Nsam);

for qx = 1 : Npos
    for yx = 1 : Npos
        for zx = 1 : Nsam
            for cx = 1 : Nsam
                Tx2Array( qx, yx, zx, cx ) = sqrt( ( AX( qx ) - Bx( zx, cx ) ).^2 + ( AY( yx ) - By( zx, cx ) ).^2 + ( AZ( yx ) - Bz( zx, cx ) ).^2 );
            end
        end
    end
end
% Result is a 21 x 21 x 200 x 200 matrix filled with all real numbers
</code>```

Legend

AX, AY, AZ are 1 x 21 arrays and represent the (x,y=0,z) of Object 1

AY is all zeros, but for readability is still included (hence no fifth loop!)

Bx, By, Bz are all 200 x 200 arrays and represent the (x,y,z) of Object 2

Npos = 21; Nsam = 200;

The formula used above is:

```<code>sqrt( (a1-b1)^2 + (a2-b2)^2 + (a3-b3)^2 )
</code>```

答:
You can avoid the to inner loops by replacing zx and cx with : as follows:

```<code>Tx2Array = zeros(Npos, Npos, Nsam, Nsam); % preallocate memory
for qx = 1 : Npos
    for yx = 1 : Npos
        Tx2Array( qx, yx, :, : ) = sqrt( ( AX( qx ) - Bx( :, : ) ).^2 + ( AY( yx ) - By( :, : ) ).^2 + ( AZ( yx ) - Bz( :, : ) ).^2 );
    end
end
</code>```

In this way, the largest dimensions are vectorised. So, the largest improvement is already done.

By converting your B* to 4D and generating a mesh for your A* matrices, you can even remove all the for loops as follows:

```<code>[AX_, AZ_] = meshgrid(AX, AZ);
AX_ = AX_';
AZ_ = AZ_';
AY_ = zeros(Npos);

Bx_(1, 1, :, :) = Bx;
By_(1, 1, :, :) = By;
Bz_(1, 1, :, :) = Bz;

Tx2Array2 = sqrt( ( AX_ - Bx_ ).^2 + ( AY_ - By_ ).^2 + ( AZ_ - Bz_ ).^2 );
</code>```

You can check the the results are the same using the following check:

```<code>max(max(max(max(abs(Tx2Array - Tx2Array2))))) < eps
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two physical "objects." I am representing their positions with two different arrays.

• Object 1 moves in the xy-plane only

• Object 2 moves in all three physical dimensions

Objective: Vectorize the four for loops without distorting the data. Also, the intent is to perform this operation for all possible values of object 1 to be compared with object 2.

Here is the code snippet:

Npos = 21;
Nsam = 200;

% dummy initialisation
AX = rand(1, Npos);
AY = zeros(1, Npos);
AZ = rand(1, Npos);
Bx = rand(Nsam);
By = rand(Nsam);
Bz = rand(Nsam);

for qx = 1 : Npos
    for yx = 1 : Npos
        for zx = 1 : Nsam
            for cx = 1 : Nsam
                Tx2Array( qx, yx, zx, cx ) = sqrt( ( AX( qx ) - Bx( zx, cx ) ).^2 + ( AY( yx ) - By( zx, cx ) ).^2 + ( AZ( yx ) - Bz( zx, cx ) ).^2 );
            end
        end
    end
end
% Result is a 21 x 21 x 200 x 200 matrix filled with all real numbers

Legend

AX, AY, AZ are 1 x 21 arrays and represent the (x,y=0,z) of Object 1

AY is all zeros, but for readability is still included (hence no fifth loop!)

Bx, By, Bz are all 200 x 200 arrays and represent the (x,y,z) of Object 2

Npos = 21; Nsam = 200;

The formula used above is:

sqrt( (a1-b1)^2 + (a2-b2)^2 + (a3-b3)^2 )

Body:
You can avoid the to inner loops by replacing zx and cx with : as follows:

Tx2Array = zeros(Npos, Npos, Nsam, Nsam); % preallocate memory
for qx = 1 : Npos
    for yx = 1 : Npos
        Tx2Array( qx, yx, :, : ) = sqrt( ( AX( qx ) - Bx( :, : ) ).^2 + ( AY( yx ) - By( :, : ) ).^2 + ( AZ( yx ) - Bz( :, : ) ).^2 );
    end
end

In this way, the largest dimensions are vectorised. So, the largest improvement is already done.

By converting your B* to 4D and generating a mesh for your A* matrices, you can even remove all the for loops as follows:

[AX_, AZ_] = meshgrid(AX, AZ);
AX_ = AX_';
AZ_ = AZ_';
AY_ = zeros(Npos);

Bx_(1, 1, :, :) = Bx;
By_(1, 1, :, :) = By;
Bz_(1, 1, :, :) = Bz;

Tx2Array2 = sqrt( ( AX_ - Bx_ ).^2 + ( AY_ - By_ ).^2 + ( AZ_ - Bz_ ).^2 );

You can check the the results are the same using the following check:

max(max(max(max(abs(Tx2Array - Tx2Array2))))) < eps


问:
Android: ImageView is under the layout
I have an imageview which has an animation. However, when the image moves, it goes behind its layout, as you can see in this image:

I want that this imageview is in front of the layout. I tried with yourView.bringToFront(); but in this way the imageview is in front of the other views, not the layout.

Here is the xml:

```<code>         <LinearLayout
            android:id="@+id/layoutComponentiNemico"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="vertical">

            <RelativeLayout
                android:id="@+id/layoutContenitoreImmagineNemico"
                android:layout_width="50dp"
                android:layout_height="0dp"
                android:layout_gravity="center"
                android:layout_weight="5">

                <ImageView
                    android:id="@+id/immagineNemico"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@drawable/anziano"/>
            </RelativeLayout>

            <ImageView
                android:id="@+id/immaginePiattaformaNemico"
                android:layout_width="150dp"
                android:layout_height="0dp"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:background="@drawable/piattaformaritagliata"/>

        </LinearLayout>
</code>```

So my imageview should "goes out" from the relative layout during the animation.

The animation:

```<code>    immagineNemico.clearAnimation();
    TranslateAnimation mAnimation = new TranslateAnimation(
            TranslateAnimation.RELATIVE_TO_PARENT, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, -0.4f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0.1f);
    mAnimation.setDuration(1000);
    mAnimation.setRepeatCount(1);
    mAnimation.setRepeatMode(Animation.REVERSE);
    mAnimation.setInterpolator(new DecelerateInterpolator());
    immagineNemico.setAnimation(mAnimation);
</code>```

答:
Could it be that you are applying the animation to @id/layoutContenitoreImmagineNemico instead of @id/immaginePiattaformaNemico?

Please show us your animation code.

Title: Android: ImageView is under the layout

Body:
I have an imageview which has an animation. However, when the image moves, it goes behind its layout, as you can see in this image:

I want that this imageview is in front of the layout. I tried with yourView.bringToFront(); but in this way the imageview is in front of the other views, not the layout.

Here is the xml:

         <LinearLayout
            android:id="@+id/layoutComponentiNemico"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:orientation="vertical">

            <RelativeLayout
                android:id="@+id/layoutContenitoreImmagineNemico"
                android:layout_width="50dp"
                android:layout_height="0dp"
                android:layout_gravity="center"
                android:layout_weight="5">

                <ImageView
                    android:id="@+id/immagineNemico"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@drawable/anziano"/>
            </RelativeLayout>

            <ImageView
                android:id="@+id/immaginePiattaformaNemico"
                android:layout_width="150dp"
                android:layout_height="0dp"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:background="@drawable/piattaformaritagliata"/>

        </LinearLayout>

So my imageview should "goes out" from the relative layout during the animation.

The animation:

    immagineNemico.clearAnimation();
    TranslateAnimation mAnimation = new TranslateAnimation(
            TranslateAnimation.RELATIVE_TO_PARENT, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, -0.4f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0f,
            TranslateAnimation.RELATIVE_TO_PARENT, 0.1f);
    mAnimation.setDuration(1000);
    mAnimation.setRepeatCount(1);
    mAnimation.setRepeatMode(Animation.REVERSE);
    mAnimation.setInterpolator(new DecelerateInterpolator());
    immagineNemico.setAnimation(mAnimation);


问:
How to get from AlexNet multiple image labels
So, I am doing my Master's Thesis on the influence of super-resolution algorithms on the accuracy rate of image labeling by AlexNet. I am using Matlab with the pre-trained version of AlexNet.

The problem is that, by using

```<code>[label, scores] = classify(net, 'image')
</code>```

I only get one label, whereas I would like to get multiple labels, e.g., five, and their corresponding scores by AlexNet.

I do not know how to do it and would really be very thankful if anyone could give me, at least, a hint.

答:
The scores matrix tells you how each class scored when classifying the data.  Specifically, each column i tells you how the score of the ith class faired when trying to classifying the input with class i.  Each row is one input into AlexNet.

If you want to get the top k scores for each input, you can sort - specifically look at the second output variable and sort each row individually.  After, you can extract out the first k columns of the result which tells you the top 5 classes or labels that were associated with the input.  If you're concerned about the actual classes, look at the first output.

```<code>% First classify the image(s) you would like
[label, scores] = classify(net, ...);

k = 5; % We want 5 classes
[scores_sorted, classes] = sort(scores, 2); % Sort each row individually
scores_sorted = scores_sorted(:, 1 : k);
classes = classes(:, 1 : k);
</code>```

scores_sorted and classes will now give you k column matrices where each row tells you the top k classes assigned for each input (stored in classes) as well as the scores provided by AlexNet (scores_sorted).

To finally determine what the actual classes are, when you create AlexNet, the final layer has the categories of classification. Assuming that you created the default net:

```<code>net = alexnet;
</code>```

... you can determine what the classes are for each label ID by:

```<code>c = net.Layers(end).ClassNames;
</code>```

This is a cell array of classes, and there should be 1000 elements in total. Therefore, given the classes variable from the code I wrote above, you can thus do:

```<code>out = net.Layers(end).ClassNames(classes);
</code>```

classes would thus be used to index into the cell array and it will thus will give you a N x k cell array where each row in this cell array tells you the labels assigned by AlexNet for the top k classes per input image.

Body:
So, I am doing my Master's Thesis on the influence of super-resolution algorithms on the accuracy rate of image labeling by AlexNet. I am using Matlab with the pre-trained version of AlexNet.

The problem is that, by using

[label, scores] = classify(net, 'image')

I only get one label, whereas I would like to get multiple labels, e.g., five, and their corresponding scores by AlexNet.

I do not know how to do it and would really be very thankful if anyone could give me, at least, a hint.

Body:
The scores matrix tells you how each class scored when classifying the data.  Specifically, each column i tells you how the score of the ith class faired when trying to classifying the input with class i.  Each row is one input into AlexNet.

If you want to get the top k scores for each input, you can sort - specifically look at the second output variable and sort each row individually.  After, you can extract out the first k columns of the result which tells you the top 5 classes or labels that were associated with the input.  If you're concerned about the actual classes, look at the first output.

% First classify the image(s) you would like
[label, scores] = classify(net, ...);

k = 5; % We want 5 classes
[scores_sorted, classes] = sort(scores, 2); % Sort each row individually
scores_sorted = scores_sorted(:, 1 : k);
classes = classes(:, 1 : k);

scores_sorted and classes will now give you k column matrices where each row tells you the top k classes assigned for each input (stored in classes) as well as the scores provided by AlexNet (scores_sorted).

To finally determine what the actual classes are, when you create AlexNet, the final layer has the categories of classification. Assuming that you created the default net:

net = alexnet;

... you can determine what the classes are for each label ID by:

c = net.Layers(end).ClassNames;

This is a cell array of classes, and there should be 1000 elements in total. Therefore, given the classes variable from the code I wrote above, you can thus do:

out = net.Layers(end).ClassNames(classes);

classes would thus be used to index into the cell array and it will thus will give you a N x k cell array where each row in this cell array tells you the labels assigned by AlexNet for the top k classes per input image.


问:
Looping Through Firebase Datasnapshot and storing values in an array
I was working on a simple Android magazine app and I would like to iterate through Firebase DataSnapshot to retrieve stored information about magazines and save them in different arrays.I used this step by step instructions to retrieve data from Firebase database.I tried looking for other questions but they didn't help. </p>

```<code> DatabaseReference ref;
        ref=FirebaseDatabase.getInstance().getReference("magazines");
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                magazineNameSize(5);
                int i = 0;
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Magazine magazine = snapshot.getValue(Magazine.class);
                    dateOfIssue[i] =magazine.getDateOfIssue();
                    magazineCover[i]=magazine.getImageUri();
                    magazineName[i]=magazine.getMagazineName();
                    i++;
                }
            }
</code>```

答:
To store those values in dateOfIssue, magazineCover and magazineName arrays, you need to declare those arrays in the onDataChange() method otherwise you'll get null outside this method.

Hope it helps.

Body:
I was working on a simple Android magazine app and I would like to iterate through Firebase DataSnapshot to retrieve stored information about magazines and save them in different arrays.I used this step by step instructions to retrieve data from Firebase database.I tried looking for other questions but they didn't help.

 DatabaseReference ref;
        ref=FirebaseDatabase.getInstance().getReference("magazines");
        ref.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                magazineNameSize(5);
                int i = 0;
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    Magazine magazine = snapshot.getValue(Magazine.class);
                    dateOfIssue[i] =magazine.getDateOfIssue();
                    magazineCover[i]=magazine.getImageUri();
                    magazineName[i]=magazine.getMagazineName();
                    i++;
                }
            }


问:
How to use sed in a Makefile
I have tried putting the following in my Makefile:

```<code>@if [ $(DEMO) -eq 0 ]; then \
    cat sys.conf | sed -e "s#^public_demo[\s=].*$#public_demo=0#" >sys.conf.temp; \
else \
    cat sys.conf | sed -e "s#^public_demo[\s=].*$#public_demo=1#" >sys.conf.temp; \
fi
</code>```

but when I run make, I get the following error:

```<code>sed: -e expression #1, char 30: unterminated `s' command
</code>```

If I run the exact lines that contain sed in the console, they behave correctly.

Why am I getting this error and how can the problem be fixed?

答:
I tried double $$ sign but it didn't work in my problem, maybe $$$$ or $$$$$$$$ would have worked, because my Makefile calls other Makefiles and so on. But I found a better solution:

Create a shell file replacer.sh in the same folder as your Makefile that executes the sed command. Give it executable bit with

```<code>chmod +x replacer.sh
</code>```

Now you can call this file in your Makefile:

```<code>./replacer.sh
</code>```

ContentLicense: CC BY-SA 2.5

Title: How to use sed in a Makefile

Body:
I have tried putting the following in my Makefile:

@if [ $(DEMO) -eq 0 ]; then \
    cat sys.conf | sed -e "s#^public_demo[\s=].*$#public_demo=0#" >sys.conf.temp; \
else \
    cat sys.conf | sed -e "s#^public_demo[\s=].*$#public_demo=1#" >sys.conf.temp; \
fi

but when I run make, I get the following error:

sed: -e expression #1, char 30: unterminated `s' command

If I run the exact lines that contain sed in the console, they behave correctly.

Why am I getting this error and how can the problem be fixed?

Body:
I tried double $$ sign but it didn't work in my problem, maybe $$$$ or $$$$$$$$ would have worked, because my Makefile calls other Makefiles and so on. But I found a better solution:

Create a shell file replacer.sh in the same folder as your Makefile that executes the sed command. Give it executable bit with

chmod +x replacer.sh

Now you can call this file in your Makefile:

./replacer.sh

ContentLicense: CC BY-SA 4.0


问:
Return int[][] array
this might be an ridiculous question, but I don`t make it. I got two arrays this Type:

String[] string{"A", "B", "C"} and
int[][] array {{1, 2, 3},{1, 2, 3}}

and wish to get this output:

A 1 1

B 2 2

C 3 3

I have almost tried every possible for loop, but it does not get in that order.
Thanks a lot for helping me!

答:
```<code>    String[] string = {"A", "B", "C"};
    int[][] array = {{1, 2, 3},{1, 2, 3}};

    for (int i = 0; i < string.length; i++) {
        System.out.print(string[i]);
        for (int j = 0; j < array.length; j++) {
            System.out.print(" " + array[j][i]);
        }
        System.out.println();
    }
</code>```

This one will result in your desired output, as long as your string array has the same length as every int array in your 2d array. You can adjust the for-loops based on your use-case, but you'll get the idea.

Title: Return int[][] array

Body:
    String[] string = {"A", "B", "C"};
    int[][] array = {{1, 2, 3},{1, 2, 3}};

    for (int i = 0; i < string.length; i++) {
        System.out.print(string[i]);
        for (int j = 0; j < array.length; j++) {
            System.out.print(" " + array[j][i]);
        }
        System.out.println();
    }

This one will result in your desired output, as long as your string array has the same length as every int array in your 2d array. You can adjust the for-loops based on your use-case, but you'll get the idea.


问:
Open view controller programatically and dont see navigation bar. Swift 3
On my story board I have a collection view controller embedded in a navigation controller. Now from the cell of the collection view, I programaticly open the second view controller (called TwoPicsViewController), like this:

```<code> let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

            let nextViewController = storyBoard.instantiateViewController(withIdentifier: "TwoPicsViewController") as! TwoPicsViewController

            self.present(nextViewController, animated:true, completion:nil)
</code>```

However when my TwoPicsViewController opens, I don't see the navigation bar at all. On the story board I connected the TwoPicsViewController to the first view controller with a segue show.

Am I missing something else?

Thanks

答:
To push a new UIViewController to the navigation stack you should use:

```<code>self.navigationController?.pushViewController(nextViewController, animated: true)
</code>```

Instead of:

```<code>self.present(nextViewController, animated:true, completion:nil)
</code>```

Body:
On my story board I have a collection view controller embedded in a navigation controller. Now from the cell of the collection view, I programaticly open the second view controller (called TwoPicsViewController), like this:

 let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

            let nextViewController = storyBoard.instantiateViewController(withIdentifier: "TwoPicsViewController") as! TwoPicsViewController

            self.present(nextViewController, animated:true, completion:nil)

However when my TwoPicsViewController opens, I don't see the navigation bar at all. On the story board I connected the TwoPicsViewController to the first view controller with a segue show.

Am I missing something else?

Thanks

Body:
To push a new UIViewController to the navigation stack you should use:

self.navigationController?.pushViewController(nextViewController, animated: true)

Instead of:

self.present(nextViewController, animated:true, completion:nil)


问:
Python ssl get ciphers supported
I was wondering why isn't there a simple way to find the ciphers supported by a particular ssl context? (Or did I miss it)

I know we can use socket.cipher() to get the one being used for the connection for that particular socket, but why not something to get all supported ciphers?

Another things is,

I have a server which is running openssl library with the cipher string "HIGH+TLSv1.2:!MD5:!SHA1". The client is a python file using the ssl library, with default options, and after the connection is established the socket.cipher() shows the below tuple

```<code>('DHE-RSA-AES256-GCM-SHA384', 'TLSv1/SSLv3', 256)
</code>```

How is the connection established with TLSv1, when I explicitly mentioned TLSv1.2, and how is it using SHA384, when TLSv1 doesn't have support for anything higher then SHA1?

答:
I was wondering why isn't there a simple way to find the ciphers supported by a particular ssl context? (Or did I miss it)

Only OpenSSL 1.1.0 added a function SSL_CTX_get_ciphers to access this list and this functionality is not yet available in Python.

```<code>('DHE-RSA-AES256-GCM-SHA384', 'TLSv1/SSLv3', 256)
</code>```

How is the connection established with TLSv1, when I explicitly mentioned TLSv1.2, and how is it using SHA384, when TLSv1 doesn't have support for anything higher then SHA1?

According to the source code Python is using SSL_CIPHER_get_version to find out the version string. The matching OpenSSL documentation says for OpenSSL 1.0.2:

SSL_CIPHER_get_version() returns string which indicates the SSL/TLS protocol version that first defined the cipher. This is currently SSLv2 or TLSv1/SSLv3. In some cases it should possibly return "TLSv1.2" but does not; use SSL_CIPHER_description()

Thus it is a bug in OpenSSL which according to the documentation of the same function in OpenSSL 1.1.0 was fixed in the latest OpenSSL version.

Title: Python ssl get ciphers supported

Body:
I was wondering why isn't there a simple way to find the ciphers supported by a particular ssl context? (Or did I miss it)

I know we can use socket.cipher() to get the one being used for the connection for that particular socket, but why not something to get all supported ciphers?

Another things is,

I have a server which is running openssl library with the cipher string "HIGH+TLSv1.2:!MD5:!SHA1". The client is a python file using the ssl library, with default options, and after the connection is established the socket.cipher() shows the below tuple

('DHE-RSA-AES256-GCM-SHA384', 'TLSv1/SSLv3', 256)

How is the connection established with TLSv1, when I explicitly mentioned TLSv1.2, and how is it using SHA384, when TLSv1 doesn't have support for anything higher then SHA1?

Body:
I was wondering why isn't there a simple way to find the ciphers supported by a particular ssl context? (Or did I miss it)

Only OpenSSL 1.1.0 added a function SSL_CTX_get_ciphers to access this list and this functionality is not yet available in Python.

('DHE-RSA-AES256-GCM-SHA384', 'TLSv1/SSLv3', 256)

How is the connection established with TLSv1, when I explicitly mentioned TLSv1.2, and how is it using SHA384, when TLSv1 doesn't have support for anything higher then SHA1?

According to the source code Python is using SSL_CIPHER_get_version to find out the version string. The matching OpenSSL documentation says for OpenSSL 1.0.2:

SSL_CIPHER_get_version() returns string which indicates the SSL/TLS protocol version that first defined the cipher. This is currently SSLv2 or TLSv1/SSLv3. In some cases it should possibly return "TLSv1.2" but does not; use SSL_CIPHER_description()

Thus it is a bug in OpenSSL which according to the documentation of the same function in OpenSSL 1.1.0 was fixed in the latest OpenSSL version.


问:
Django login form: where have I gone wrong?
Really not sure what is wrong with my login form and view...I will display it here in the hope that someone may know roughly where I have gone wrong:

Essentially on "submit" - the control flow doesn't break into the form.is_valid nest...

views.py:

```<code>def login_view(request):
    title = "login"
    form = UserLoginForm(request.POST or None)

    context = { "form": form, "title": title }

    print(request.user.is_authenticated())

    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")
        user = authenticate(username = username, password = password)
        login(request, user)
        print(request.user.is_authenticated())

        if username == "":
            error = "Please enter a username..."
            context = { "form": form, "title": title, 'error': error }

        if password =="":
            error = "Please enter a password..."
            context = { "form": form, "title": title, 'error': error }

        #If a password and username exists lets see if we can authenticate it:
        if username and password:
            if user is not None:
                #Checking if the user exists and the user is not none, if so continue, else raise an active user error:
                if user.is_active:
                    #Check that the password is correct and matches up to the password in the User.user model:
                    if user.check_password(password):
                        if user:
                            #One further check to see if user is true, if so let's login them in:
                            #Let's print server side that True if the the user is autheticated, if not print False:
                            print(request.user.is_authenticated())
                        else:
                            error = "This user does not exist..."
                            context = { "form": form, "title": title, 'error': error }
                    else:
                        error = "Incorrect password..."
                        context = { "form": form, "title": title, 'error': error }
                else:
                    error = "This user does not appear to be active."
                    context = { "form": form, "title": title, 'error': error }

        #Display the redirect if the form was valid and if user authentication was successful:

    return render(request, "blog/user_auth/login_form.html", context)
</code>```

forms.py:

```<code>class UserLoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

    def clean(self, *args, **kwargs):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")

        # Alternative method for validation our authenticated user:
        # user_queryset = User.objects.filter(username=username)
        # if user_queryset() == 1:
        #     user = user_queryset.first()
        if username and password:
            user = authenticate(username = username, password = password)
            if not user:
                raise forms.ValidationError("This user does not exist..")

            if not user.check_password(password):
                raise forms.ValidationError("Incorrect password...")

            if not user.is_active:
                raise forms.ValidationError("This user does not appear to be active.")

        return super(UserLoginForm, self).clean(*args, **kwargs)
</code>```

login_view.html (relevant section):

```<code><form class="contact-form contact-form-two" name="contact-form" method="POST" action='.' enctype='multipart/form-data'>
  <div class="form-group">
  {% csrf_token %}
     <input type="text" class="form-control" required="required" placeholder="User ID">
     <input type="password" class="form-control" required="required" placeholder="Password">
     {% if error %}
       <div>{{ error }}</div>
     {% endif %}
     <button type="submit" class="btn btn-primary" value='{{ title }}'>Sign In</button>
  </div>
</form><!-- /.contact-form -->
</code>```

I don't get any errors - just that the print(request.user.is_authenticated()) prints neither true or false.

答:
I would recommend just using the login view that comes with django. There are function and class based versions of it

```<code>from django.contrib.auth.views import login

urlpatterns = [
    ...
    url('login/$', login),
]
</code>```

Or class based

```<code>from django.contrib.auth.views import LoginView

urlpatterns = [
    ...
    url('login/$', LoginView.as_view()),
]
</code>```

The default form will take care of all of the validation and authentication for you.

Edit:

Customization is also still possible if you use the class based view. For example, let's say you want to use a custom template and a different succes url.

```<code>#urls.py
from my_app.views import MyLoginView

urlpatterns = [
    ...
    url('login/$', MyLoginView.as_view()),
]

# views.py
from django.contrib.auth.views import LoginView

class MyLoginView(LoginView):
    template_name = 'my/custom/template.html'

    def get_success_url(self):
        return reverse('some-landing-page')
</code>```

A custom template would look like this. It will take care of showing errors and rendering the fields.

```<code><form method="post">
    {% csrf_token %}

    {% if form.username.errors %}{% for error in form.username.errors %}<p class="error">{{ error }}</p>{% endfor %}{% endif %}
    <inpyt type="text" class="form-control" name="{{ form.username.name }}" placeholder="User ID" required {% if form.username.value %}value="{{ form.username.value }}"{% endif %}/>

    {% if form.password.errors %}{% for error in errors %}<p class="error">{{ error }}</p>{% endfor %}{% endif %}
    <input type="password" class="form-control" name="{{ form.passwords.name }}" placeholder="Password" required/>

    <input class="btn btn-primary" type="submit" />
</form>
</code>```

Body:
Really not sure what is wrong with my login form and view...I will display it here in the hope that someone may know roughly where I have gone wrong:

Essentially on "submit" - the control flow doesn't break into the form.is_valid nest...

views.py:

def login_view(request):
    title = "login"
    form = UserLoginForm(request.POST or None)

    context = { "form": form, "title": title }

    print(request.user.is_authenticated())

    if form.is_valid():
        username = form.cleaned_data.get("username")
        password = form.cleaned_data.get("password")
        user = authenticate(username = username, password = password)
        login(request, user)
        print(request.user.is_authenticated())

        if username == "":
            error = "Please enter a username..."
            context = { "form": form, "title": title, 'error': error }

        if password =="":
            error = "Please enter a password..."
            context = { "form": form, "title": title, 'error': error }

        #If a password and username exists lets see if we can authenticate it:
        if username and password:
            if user is not None:
                #Checking if the user exists and the user is not none, if so continue, else raise an active user error:
                if user.is_active:
                    #Check that the password is correct and matches up to the password in the User.user model:
                    if user.check_password(password):
                        if user:
                            #One further check to see if user is true, if so let's login them in:
                            #Let's print server side that True if the the user is autheticated, if not print False:
                            print(request.user.is_authenticated())
                        else:
                            error = "This user does not exist..."
                            context = { "form": form, "title": title, 'error': error }
                    else:
                        error = "Incorrect password..."
                        context = { "form": form, "title": title, 'error': error }
                else:
                    error = "This user does not appear to be active."
                    context = { "form": form, "title": title, 'error': error }

        #Display the redirect if the form was valid and if user authentication was successful:

    return render(request, "blog/user_auth/login_form.html", context)

forms.py:

class UserLoginForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

    def clean(self, *args, **kwargs):
        username = self.cleaned_data.get("username")
        password = self.cleaned_data.get("password")

        # Alternative method for validation our authenticated user:
        # user_queryset = User.objects.filter(username=username)
        # if user_queryset() == 1:
        #     user = user_queryset.first()
        if username and password:
            user = authenticate(username = username, password = password)
            if not user:
                raise forms.ValidationError("This user does not exist..")

            if not user.check_password(password):
                raise forms.ValidationError("Incorrect password...")

            if not user.is_active:
                raise forms.ValidationError("This user does not appear to be active.")

        return super(UserLoginForm, self).clean(*args, **kwargs)

login_view.html (relevant section):

<form class="contact-form contact-form-two" name="contact-form" method="POST" action='.' enctype='multipart/form-data'>

  {% csrf_token %}
     <input type="text" class="form-control" required="required" placeholder="User ID">
     <input type="password" class="form-control" required="required" placeholder="Password">
     {% if error %}

{{ error }}

     {% endif %}
     <button type="submit" class="btn btn-primary" value='{{ title }}'>Sign In</button>

</form>

I don't get any errors - just that the print(request.user.is_authenticated()) prints neither true or false.

Body:
I would recommend just using the login view that comes with django. There are function and class based versions of it

from django.contrib.auth.views import login

urlpatterns = [
    ...
    url('login/$', login),
]

Or class based

from django.contrib.auth.views import LoginView

urlpatterns = [
    ...
    url('login/$', LoginView.as_view()),
]

The default form will take care of all of the validation and authentication for you.

Edit:

Customization is also still possible if you use the class based view. For example, let's say you want to use a custom template and a different succes url.

#urls.py
from my_app.views import MyLoginView

urlpatterns = [
    ...
    url('login/$', MyLoginView.as_view()),
]

# views.py
from django.contrib.auth.views import LoginView

class MyLoginView(LoginView):
    template_name = 'my/custom/template.html'

    def get_success_url(self):
        return reverse('some-landing-page')

A custom template would look like this. It will take care of showing errors and rendering the fields.

<form method="post">
    {% csrf_token %}

    {% if form.username.errors %}{% for error in form.username.errors %}<p class="error">{{ error }}</p>{% endfor %}{% endif %}
    <inpyt type="text" class="form-control" name="{{ form.username.name }}" placeholder="User ID" required {% if form.username.value %}value="{{ form.username.value }}"{% endif %}/>

    {% if form.password.errors %}{% for error in errors %}<p class="error">{{ error }}</p>{% endfor %}{% endif %}
    <input type="password" class="form-control" name="{{ form.passwords.name }}" placeholder="Password" required/>

    <input class="btn btn-primary" type="submit" />
</form>


问:
Invalid pointer exception when closing app after upgrade from Delphi 2006 to Delphi XE
I've just upgraded a project from Delphi 2006 to Delphi XE. Everything is working as expected except I get an exception when I close my app.

It's not breaking on a code line. It breaks to the CPU window on a LEAVE command.
I've attached a Eureka log if that is any help.

```<code>EurekaLog 6.0.25

Application:
------------------------------------------------------
  1.1 Start Date      : Fri, 3 Dec 2010 10:44:17 +0100
  1.2 Name/Description: LogoTid.exe
  1.3 Version Number  :
  1.4 Parameters      :
  1.5 Compilation Date: Fri, 3 Dec 2010 10:44:15 +0100
  1.6 Up Time         : 5 seconds

Exception:
----------------------------------------------------
  2.1 Date          : Fri, 3 Dec 2010 10:44:22 +0100
  2.2 Address       : 004062A0
  2.3 Module Name   : LogoTid.exe
  2.4 Module Version:
  2.5 Type          : EInvalidPointer
  2.6 Message       : Invalid pointer operation.
  2.7 ID            : 5E21
  2.8 Count         : 1
  2.9 Status        : New
  2.10 Note         :

User:
-------------------------------------------------------
  3.1 ID        : oda
  3.2 Name      :
  3.3 Email     :
  3.4 Company   :
  3.5 Privileges: SeIncreaseQuotaPrivilege        - OFF
                  SeSecurityPrivilege             - OFF
                  SeTakeOwnershipPrivilege        - OFF
                  SeLoadDriverPrivilege           - OFF
                  SeSystemProfilePrivilege        - OFF
                  SeSystemtimePrivilege           - OFF
                  SeProfileSingleProcessPrivilege - OFF
                  SeIncreaseBasePriorityPrivilege - OFF
                  SeCreatePagefilePrivilege       - OFF
                  SeBackupPrivilege               - OFF
                  SeRestorePrivilege              - OFF
                  SeShutdownPrivilege             - OFF
                  SeDebugPrivilege                - ON
                  SeSystemEnvironmentPrivilege    - OFF
                  SeChangeNotifyPrivilege         - ON
                  SeRemoteShutdownPrivilege       - OFF
                  SeUndockPrivilege               - OFF
                  SeManageVolumePrivilege         - OFF
                  SeImpersonatePrivilege          - ON
                  SeCreateGlobalPrivilege         - ON
                  SeIncreaseWorkingSetPrivilege   - OFF
                  SeTimeZonePrivilege             - OFF
                  SeCreateSymbolicLinkPrivilege   - OFF

Active Controls:
------------------------------------------------------------------
  4.1 Form Class   : TAppBuilder
  4.2 Form Text    : LogoTid - Delphi XE - uMain [Running] [Built]
  4.3 Control Class:
  4.4 Control Text :

Computer:
------------------------------------------------------------------------------------------------
  5.1 Name          : OLE-LAPTOP
  5.2 Total Memory  : 3891 Mb
  5.3 Free Memory   : 778 Mb
  5.4 Total Disk    : 120 Gb
  5.5 Free Disk     : 57,93 Gb
  5.6 System Up Time: 1 day, 23 hours, 16 minutes, 56 seconds
  5.7 Processor     : Intel(R) Core(TM) i5 CPU       M 520  @ 2.40GHz
  5.8 Display Mode  : 1920 x 1200, 32 bit
  5.9 Display DPI   : 96
  5.10 Video Card   : Intel(R) Graphics Media Accelerator HD (driver 8.15.10.2025 - RAM 1721 MB)
  5.11 Printer      : RICOH Aficio 2232C RPCS (driver 1.0.0)

Operating System:
--------------------------------------------
  6.1 Type    : Microsoft Windows 7 (64 bit)
  6.2 Build # : 7600
  6.3 Update  :
  6.4 Language: Danish
  6.5 Charset : 0

Call Stack Information:
-------------------------------------------------------------------
|Address |Module      |Unit       |Class|Procedure/Method   |Line |
-------------------------------------------------------------------
|Running Thread: ID=5632; Priority=0; Class=; [Main]              |
|-----------------------------------------------------------------|
|00D171A1|LogoTid.exe |LogoTid.dpr|     |                   |32[5]|
|76A73675|kernel32.dll|           |     |BaseThreadInitThunk|     |
-------------------------------------------------------------------

Assembler Information:
-----------------------------------------------------------------
; System.TObject.FreeInstance
; ----------------------------
00406294  push    ebx
00406295  mov     ebx, eax
00406297  mov     eax, ebx
00406299  call    System.TObject.CleanupInstance
0040629E  mov     eax, ebx
004062A0  call    System._FreeMem                 ; <-- EXCEPTION
004062A5  pop     ebx
004062A6  ret

Registers:
-----------------------------
EAX: 02AF8058   EDI: 00000001
EBX: 004062A5   ESI: 004062A5
ECX: 0041D700   ESP: 0018FE98
EDX: 004062A5   EIP: 004062A0

Stack:               Memory Dump:
------------------   ---------------------------------------------------------------------------
0018FE98: FFFFFF02   004062A0: E8 3B E7 FF FF 5B C3 90 83 C0 CC 8B 00 C3 8B C0  .;...[..........
0018FE9C: 00404B78   004062B0: 84 D2 74 08 83 C4 F0 E8 54 05 00 00 84 D2 74 0F  ..t.....T.....t.
0018FEA0: 02B1CEC0   004062C0: E8 A3 05 00 00 64 8F 05 00 00 00 00 83 C4 0C C3  .....d..........
0018FEA4: 02B1CEC0   004062D0: E8 E3 05 00 00 84 D2 7E 05 E8 82 05 00 00 C3 90  .......~........
0018FEA8: 00404BC2   004062E0: 85 C0 74 07 B2 01 8B 08 FF 51 FC C3 53 56 57 89  ..t......Q..SVW.
0018FEAC: 02B1CEC0   004062F0: C3 89 D7 AB 8B 4B CC 31 C0 51 C1 E9 02 49 F3 AB  .....K.1.Q...I..
0018FEB0: 0018FEE8   00406300: 59 83 E1 03 F3 AA 89 D0 89 E2 8B 4B AC 85 C9 74  Y..........K...t
0018FEB4: 004062A5   00406310: 01 51 8B 5B D0 85 DB 74 04 8B 1B EB ED 39 D4 74  .Q.[...t.....9.t
0018FEB8: 03A02F01   00406320: 1D 5B 8B 0B 83 C3 04 8B 73 10 85 F6 74 06 8B 7B  .[......s...t..{
0018FEBC: 00406865   00406330: 14 89 34 07 83 C3 1C 49 75 ED 39 D4 75 E3 5F 5E  ..4....Iu.9.u._^
0018FEC0: 0045B949   00406340: 5B C3 8B C0 53 56 89 C3 89 C6 8B 36 8B 56 B4 8B  [...SV.....6.V..
0018FEC4: 03A02FA0   00406350: 76 D0 85 D2 74 07 E8 85 36 00 00 89 D8 85 F6 75  v...t...6......u
0018FEC8: 03A02F01   00406360: E9 89 D8 E8 78 06 00 00 5E 5B C3 90 87 D1 81 F9  ....x...^[......
0018FECC: 004062EB   00406370: 00 00 00 FF 73 11 81 F9 00 00 00 FE 72 07 0F BF  ....s.......r...
0018FED0: 00912606   00406380: C9 03 08 FF 21 FF E1 81 E1 FF FF FF 00 01 C1 89  ....!...........
0018FED4: 00000000   00406390: D0 8B 11 E9 A8 59 00 00 C3 8D 40 00 3B C2 0F 94  .....Y....@.;...
</code>```

--- Edit

Ok, tried turning of parts of my program until the error went away, and found the troublemaker.

It's my webservice WSDL generated proxy. If I create the proxy object without calling any functions on the service, it throws the error.

I've created a test project without any other code than the proxy object creation and it also throws the error. I've also tried with another webservice, same error. Both webservices was created with Delphi 2006 (.net 1.1).

Lastly I tried with a .net 4.0 webservice created in VS2010. No problems. So either Delphi XE is projects is not compatible with .net 1.1 webservices or Delphi 2006 webservices. Either way it's a mess.

Any thouhts on how to solve this, maybe a workaround?

答:
Likely related to the fact that the string is now a Unicode string (2 bytes per char), and not an AnsiString (1 byte per char). If you play with the raw bytes of strings, this is a major problem. To solve it, simply replace all string to AnsiString and all char to AnsiChar. Of course, you will lose Unicode support by doing this. A better fix is to rework your string handling routines. Often, what is necessary is only to add some multiplicative factors sizeof(char) (=2) every here and there.

Example (old code):

```<code>byteSize = length(str);
</code>```

Example (new code):

```<code>byteSize = length(str) * sizeof(char);
</code>```

Body:
I've just upgraded a project from Delphi 2006 to Delphi XE. Everything is working as expected except I get an exception when I close my app.

It's not breaking on a code line. It breaks to the CPU window on a LEAVE command.
I've attached a Eureka log if that is any help.

EurekaLog 6.0.25

Application:
------------------------------------------------------
  1.1 Start Date      : Fri, 3 Dec 2010 10:44:17 +0100
  1.2 Name/Description: LogoTid.exe
  1.3 Version Number  :
  1.4 Parameters      :
  1.5 Compilation Date: Fri, 3 Dec 2010 10:44:15 +0100
  1.6 Up Time         : 5 seconds

Exception:
----------------------------------------------------
  2.1 Date          : Fri, 3 Dec 2010 10:44:22 +0100
  2.2 Address       : 004062A0
  2.3 Module Name   : LogoTid.exe
  2.4 Module Version:
  2.5 Type          : EInvalidPointer
  2.6 Message       : Invalid pointer operation.
  2.7 ID            : 5E21
  2.8 Count         : 1
  2.9 Status        : New
  2.10 Note         :

User:
-------------------------------------------------------
  3.1 ID        : oda
  3.2 Name      :
  3.3 Email     :
  3.4 Company   :
  3.5 Privileges: SeIncreaseQuotaPrivilege        - OFF
                  SeSecurityPrivilege             - OFF
                  SeTakeOwnershipPrivilege        - OFF
                  SeLoadDriverPrivilege           - OFF
                  SeSystemProfilePrivilege        - OFF
                  SeSystemtimePrivilege           - OFF
                  SeProfileSingleProcessPrivilege - OFF
                  SeIncreaseBasePriorityPrivilege - OFF
                  SeCreatePagefilePrivilege       - OFF
                  SeBackupPrivilege               - OFF
                  SeRestorePrivilege              - OFF
                  SeShutdownPrivilege             - OFF
                  SeDebugPrivilege                - ON
                  SeSystemEnvironmentPrivilege    - OFF
                  SeChangeNotifyPrivilege         - ON
                  SeRemoteShutdownPrivilege       - OFF
                  SeUndockPrivilege               - OFF
                  SeManageVolumePrivilege         - OFF
                  SeImpersonatePrivilege          - ON
                  SeCreateGlobalPrivilege         - ON
                  SeIncreaseWorkingSetPrivilege   - OFF
                  SeTimeZonePrivilege             - OFF
                  SeCreateSymbolicLinkPrivilege   - OFF

Active Controls:
------------------------------------------------------------------
  4.1 Form Class   : TAppBuilder
  4.2 Form Text    : LogoTid - Delphi XE - uMain [Running] [Built]
  4.3 Control Class:
  4.4 Control Text :

Computer:
------------------------------------------------------------------------------------------------
  5.1 Name          : OLE-LAPTOP
  5.2 Total Memory  : 3891 Mb
  5.3 Free Memory   : 778 Mb
  5.4 Total Disk    : 120 Gb
  5.5 Free Disk     : 57,93 Gb
  5.6 System Up Time: 1 day, 23 hours, 16 minutes, 56 seconds
  5.7 Processor     : Intel(R) Core(TM) i5 CPU       M 520  @ 2.40GHz
  5.8 Display Mode  : 1920 x 1200, 32 bit
  5.9 Display DPI   : 96
  5.10 Video Card   : Intel(R) Graphics Media Accelerator HD (driver 8.15.10.2025 - RAM 1721 MB)
  5.11 Printer      : RICOH Aficio 2232C RPCS (driver 1.0.0)

Operating System:
--------------------------------------------
  6.1 Type    : Microsoft Windows 7 (64 bit)
  6.2 Build # : 7600
  6.3 Update  :
  6.4 Language: Danish
  6.5 Charset : 0

Call Stack Information:
-------------------------------------------------------------------
|Address |Module      |Unit       |Class|Procedure/Method   |Line |
-------------------------------------------------------------------
|Running Thread: ID=5632; Priority=0; Class=; [Main]              |
|-----------------------------------------------------------------|
|00D171A1|LogoTid.exe |LogoTid.dpr|     |                   |32[5]|
|76A73675|kernel32.dll|           |     |BaseThreadInitThunk|     |
-------------------------------------------------------------------

Assembler Information:
-----------------------------------------------------------------
; System.TObject.FreeInstance
; ----------------------------
00406294  push    ebx
00406295  mov     ebx, eax
00406297  mov     eax, ebx
00406299  call    System.TObject.CleanupInstance
0040629E  mov     eax, ebx
004062A0  call    System._FreeMem                 ; <-- EXCEPTION
004062A5  pop     ebx
004062A6  ret

Registers:
-----------------------------
EAX: 02AF8058   EDI: 00000001
EBX: 004062A5   ESI: 004062A5
ECX: 0041D700   ESP: 0018FE98
EDX: 004062A5   EIP: 004062A0

Stack:               Memory Dump:
------------------   ---------------------------------------------------------------------------
0018FE98: FFFFFF02   004062A0: E8 3B E7 FF FF 5B C3 90 83 C0 CC 8B 00 C3 8B C0  .;...[..........
0018FE9C: 00404B78   004062B0: 84 D2 74 08 83 C4 F0 E8 54 05 00 00 84 D2 74 0F  ..t.....T.....t.
0018FEA0: 02B1CEC0   004062C0: E8 A3 05 00 00 64 8F 05 00 00 00 00 83 C4 0C C3  .....d..........
0018FEA4: 02B1CEC0   004062D0: E8 E3 05 00 00 84 D2 7E 05 E8 82 05 00 00 C3 90  .......~........
0018FEA8: 00404BC2   004062E0: 85 C0 74 07 B2 01 8B 08 FF 51 FC C3 53 56 57 89  ..t......Q..SVW.
0018FEAC: 02B1CEC0   004062F0: C3 89 D7 AB 8B 4B CC 31 C0 51 C1 E9 02 49 F3 AB  .....K.1.Q...I..
0018FEB0: 0018FEE8   00406300: 59 83 E1 03 F3 AA 89 D0 89 E2 8B 4B AC 85 C9 74  Y..........K...t
0018FEB4: 004062A5   00406310: 01 51 8B 5B D0 85 DB 74 04 8B 1B EB ED 39 D4 74  .Q.[...t.....9.t
0018FEB8: 03A02F01   00406320: 1D 5B 8B 0B 83 C3 04 8B 73 10 85 F6 74 06 8B 7B  .[......s...t..{
0018FEBC: 00406865   00406330: 14 89 34 07 83 C3 1C 49 75 ED 39 D4 75 E3 5F 5E  ..4....Iu.9.u._^
0018FEC0: 0045B949   00406340: 5B C3 8B C0 53 56 89 C3 89 C6 8B 36 8B 56 B4 8B  [...SV.....6.V..
0018FEC4: 03A02FA0   00406350: 76 D0 85 D2 74 07 E8 85 36 00 00 89 D8 85 F6 75  v...t...6......u
0018FEC8: 03A02F01   00406360: E9 89 D8 E8 78 06 00 00 5E 5B C3 90 87 D1 81 F9  ....x...^[......
0018FECC: 004062EB   00406370: 00 00 00 FF 73 11 81 F9 00 00 00 FE 72 07 0F BF  ....s.......r...
0018FED0: 00912606   00406380: C9 03 08 FF 21 FF E1 81 E1 FF FF FF 00 01 C1 89  ....!...........
0018FED4: 00000000   00406390: D0 8B 11 E9 A8 59 00 00 C3 8D 40 00 3B C2 0F 94  .....Y....@.;...

--- Edit

Ok, tried turning of parts of my program until the error went away, and found the troublemaker.

It's my webservice WSDL generated proxy. If I create the proxy object without calling any functions on the service, it throws the error.

I've created a test project without any other code than the proxy object creation and it also throws the error. I've also tried with another webservice, same error. Both webservices was created with Delphi 2006 (.net 1.1).

Lastly I tried with a .net 4.0 webservice created in VS2010. No problems. So either Delphi XE is projects is not compatible with .net 1.1 webservices or Delphi 2006 webservices. Either way it's a mess.

Any thouhts on how to solve this, maybe a workaround?

Body:
Likely related to the fact that the string is now a Unicode string (2 bytes per char), and not an AnsiString (1 byte per char). If you play with the raw bytes of strings, this is a major problem. To solve it, simply replace all string to AnsiString and all char to AnsiChar. Of course, you will lose Unicode support by doing this. A better fix is to rework your string handling routines. Often, what is necessary is only to add some multiplicative factors sizeof(char) (=2) every here and there.

Example (old code):

byteSize = length(str);

Example (new code):

byteSize = length(str) * sizeof(char);


问:
CSS3 blur overlay
I am trying to create overlay that would cover whole site page and blur everything that is behind it. I searched for solution, tried multiple versions with CSS3 blur filter, but without success. Main problem is when body tag have background, it is not blurred.

Toy example:

body
{
  background: url("https://upload.wikimedia.org/wikipedia/commons/8/8a/Too-cute-doggone-it-video-playlist.jpg");

}

h1
{
  text-align: center;
}

#overlay
{
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  -webkit-filter: blur(10px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head></head>
<body>
  <h1>
     Text
  </h1>

  <div id="overlay">
      overlay
  </div>
</body>
</html></code>```

I want to try to blur everything behind overlay div.
If I add blur to h1 (or if I wrap it inside other div and add blur on that div) I could reach near solution, but without blur of background.

Is there any solution that could fulfil all requests?

Idea is to create a JavaScript file, that would do this programatically so that I could use on multiple pages.

答:
You can use the filter property with blur, although it's not widely supported: http://jsfiddle.net/GkXdM/1/. It's supported on Chrome, but it comes with a big performance penalty when used on the whole page.

```<code>body {
    filter: blur(2px);
}
</code>```

Or you can just use a div that's full screen (like you have) and just adjust the z-index. I wouldn't suggest putting an background on the body though. No reason for that.

Title: CSS3 blur overlay

Body:
I am trying to create overlay that would cover whole site page and blur everything that is behind it. I searched for solution, tried multiple versions with CSS3 blur filter, but without success. Main problem is when body tag have background, it is not blurred.

Toy example:

body
{
  background: url("https://upload.wikimedia.org/wikipedia/commons/8/8a/Too-cute-doggone-it-video-playlist.jpg");

}

h1
{
  text-align: center;
}

#overlay
{
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  -webkit-filter: blur(10px);
}

     Text

      overlay

I want to try to blur everything behind overlay div.
If I add blur to h1 (or if I wrap it inside other div and add blur on that div) I could reach near solution, but without blur of background.

Is there any solution that could fulfil all requests?

Idea is to create a JavaScript file, that would do this programatically so that I could use on multiple pages.

Body:
You can use the filter property with blur, although it's not widely supported: http://jsfiddle.net/GkXdM/1/. It's supported on Chrome, but it comes with a big performance penalty when used on the whole page.

body {
    filter: blur(2px);
}

Or you can just use a div that's full screen (like you have) and just adjust the z-index. I wouldn't suggest putting an background on the body though. No reason for that.


问:
Python - Bubble sort
Hi I reviewed other posts with bubble sort, but solution didn't work in my case:
So algorithm works until I repeat few times while loop. But how can I do this without using input? Here is my code so you know what I mean:</p>

```<code>x = [0, 0, 1, 3, 3, 2, 2, 1, 0, 4, 5]

h = None
flag = True

while flag == True:
    #flag = True
    for i in range(len(x) - 1):
        if x[i] > x[i + 1]:
    #       flag = False
            h = x[i]
            x[i] = x[i + 1]
            x[i + 1] = h
    print(x)

    #input = raw_input('Satisfied? ')
    #if input == 'q':
    #   break

print(x)
'''
we can replace variable h, with:
x[i] , x[i+1] = x[i+1], x[i]
'''
</code>```

答:
With this algorithm, you can previously know how many steps (max) are needed to sort the whole array, because the algorithm is convergent and bounded. In each pass, the highest no-placed value is placed correctly, so you will need n-1 passes to complete the sorting.

Here an example:

```<code>mylist = [54,26,93,17,77,31,44,55,20]

for num in range(len(mylist)-1, 0, -1):
    for i in range(num):
        if mylist[i] > mylist[i+1]:
            aux = mylist[i]
            mylist[i] = mylist[i+1]
            mylist[i+1] = aux

print(mylist)
</code>```

Hope it helps

PS: What you intended to do, stopping when the list is sorted before the n-1 pass, is better done with the "insertion algorithm". Here there is an interesting comparision between insertion and bubble sorting:
Insertion sort vs Bubble Sort Algorithms

Title: Python - Bubble sort

Body:
Hi I reviewed other posts with bubble sort, but solution didn't work in my case:
So algorithm works until I repeat few times while loop. But how can I do this without using input? Here is my code so you know what I mean:

x = [0, 0, 1, 3, 3, 2, 2, 1, 0, 4, 5]

h = None
flag = True

while flag == True:
    #flag = True
    for i in range(len(x) - 1):
        if x[i] > x[i + 1]:
    #       flag = False
            h = x[i]
            x[i] = x[i + 1]
            x[i + 1] = h
    print(x)

    #input = raw_input('Satisfied? ')
    #if input == 'q':
    #   break

print(x)
'''
we can replace variable h, with:
x[i] , x[i+1] = x[i+1], x[i]
'''

Body:
With this algorithm, you can previously know how many steps (max) are needed to sort the whole array, because the algorithm is convergent and bounded. In each pass, the highest no-placed value is placed correctly, so you will need n-1 passes to complete the sorting.

Here an example:

mylist = [54,26,93,17,77,31,44,55,20]

for num in range(len(mylist)-1, 0, -1):
    for i in range(num):
        if mylist[i] > mylist[i+1]:
            aux = mylist[i]
            mylist[i] = mylist[i+1]
            mylist[i+1] = aux

print(mylist)

Hope it helps

PS: What you intended to do, stopping when the list is sorted before the n-1 pass, is better done with the "insertion algorithm". Here there is an interesting comparision between insertion and bubble sorting:
Insertion sort vs Bubble Sort Algorithms


问:
Swift Progress View animation makes the bar go further than 100%
When using animations for the ProgressView, it works completely fine if I let the animation run out but if I try to run this code again while the animation is still going, it will add 100% to the current bar and make it go through the bar. Images should explain the situation in a more logical sense.

Progress starts at 1.0 (100%):

Progress is half-way through:

The code was ran again, resulting in the progress going above 100%, although it uses the correct amount of time to finish.

Here's the code used:

```<code>self.progressView.setProgress(1.0, animated: false)

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  UIView.animate(withDuration: 10, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction], animations: { [unowned self] in
    self.progressView.setProgress(0, animated: true)
  })
}
</code>```

Thanks in advance!

答:
Some quick research...

Turns out UIProgressView needs a little special effort to stop the current animation. See if this does the job for you:

```<code>    // stop any current animation
    self.progressView.layer.sublayers?.forEach { $0.removeAllAnimations() }

    // reset progressView to 100%
    self.progressView.setProgress(1.0, animated: false)

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        // set progressView to 0%, with animated set to false
        self.progressView.setProgress(0.0, animated: false)
        // 10-second animation changing from 100% to 0%
        UIView.animate(withDuration: 10, delay: 0, options: [], animations: { [unowned self] in
            self.progressView.layoutIfNeeded()
        })
    }
</code>```

Body:
When using animations for the ProgressView, it works completely fine if I let the animation run out but if I try to run this code again while the animation is still going, it will add 100% to the current bar and make it go through the bar. Images should explain the situation in a more logical sense.

Progress starts at 1.0 (100%):

Progress is half-way through:

The code was ran again, resulting in the progress going above 100%, although it uses the correct amount of time to finish.

Here's the code used:

self.progressView.setProgress(1.0, animated: false)

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
  UIView.animate(withDuration: 10, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction], animations: { [unowned self] in
    self.progressView.setProgress(0, animated: true)
  })
}

Thanks in advance!

Body:
Some quick research...

Turns out UIProgressView needs a little special effort to stop the current animation. See if this does the job for you:

    // stop any current animation
    self.progressView.layer.sublayers?.forEach { $0.removeAllAnimations() }

    // reset progressView to 100%
    self.progressView.setProgress(1.0, animated: false)

    DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
        // set progressView to 0%, with animated set to false
        self.progressView.setProgress(0.0, animated: false)
        // 10-second animation changing from 100% to 0%
        UIView.animate(withDuration: 10, delay: 0, options: [], animations: { [unowned self] in
            self.progressView.layoutIfNeeded()
        })
    }


问:
What IDE has better support for groovy, Netbeans or Eclipse?
What IDE has better support for groovy, Netbeans or Eclipse?</p>

答:
Short answer

Eclipse

Longer answer

The Groovy-Eclipse plugin used to be unspeakably awful, but it has improved out of all recognition since version 2.X. If you want Grails (rather than just Groovy) support, the simplest option is to install the SpringSource Tool Suite (STS), which supports Groovy, Grails and lots of other products under the Spring portfolio.


问:
Join data frames based on item presence in a transaction
I have two data frames that I am trying to merge. The first table is a list of items and associated data such as:

```<code>items <- data.frame(
  item_code = c(1111, 2222, 3333, 4444),
  item_category = c("cata","catb","catc","catd")
  )
</code>```

And the second is a list of transactions:

```<code>transactions <- data.frame(
  tran_code = c('aaaa', 'bbbb', 'cccc', 'dddd'),
  tran_items = c("1111,1111,2222","3333,2222","1111,4444,4444","3333")
  )
</code>```

I am trying to create a column containing in each cell a list of transactions that the item appears in, like so:

```<code>view(final_df)

item_code item_category in_trans
1111      "cata"        "aaaa,cccc"
2222      "catb"        "aaaa,bbbb"
3333      "catc"        "bbbb,dddd"
4444      "catd"        "cccc"
</code>```

Can anyone provide suggestions on how to achieve this?

答:
Using data.table, you can do the following.

```<code>library(data.table)
setDT(transactions)[, .(item_code=as.numeric(unlist(strsplit(tran_items, split=",")))),
                    by=tran_code
                    ][items, on="item_code", .(item_category=unique(item_category),
                      in_trans=paste(unique(tran_code), collapse=",")), by=.EACHI]
   item_code item_category  in_trans
1:      1111          cata aaaa,cccc
2:      2222          catb aaaa,bbbb
3:      3333          catc bbbb,dddd
4:      4444          catd      cccc
</code>```

The first chain [] "reshapes" the transactions data to long, (one trans_item-tran_code per row). The second [] joins this onto the items data.frame on item code and then wraps up the items in the transaction by item_code with paste and unique. Using by=.EACHI allows for this operation to occur on the item_code level.

Note that this requires that none of your variables are factors. I used stringsAsFactors=FALSE in reading in your data.

Body:
I have two data frames that I am trying to merge. The first table is a list of items and associated data such as:

items <- data.frame(
  item_code = c(1111, 2222, 3333, 4444),
  item_category = c("cata","catb","catc","catd")
  )

And the second is a list of transactions:

transactions <- data.frame(
  tran_code = c('aaaa', 'bbbb', 'cccc', 'dddd'),
  tran_items = c("1111,1111,2222","3333,2222","1111,4444,4444","3333")
  )

I am trying to create a column containing in each cell a list of transactions that the item appears in, like so:

view(final_df)

item_code item_category in_trans
1111      "cata"        "aaaa,cccc"
2222      "catb"        "aaaa,bbbb"
3333      "catc"        "bbbb,dddd"
4444      "catd"        "cccc"

Can anyone provide suggestions on how to achieve this?

Body:
Using data.table, you can do the following.

library(data.table)
setDT(transactions)[, .(item_code=as.numeric(unlist(strsplit(tran_items, split=",")))),
                    by=tran_code
                    ][items, on="item_code", .(item_category=unique(item_category),
                      in_trans=paste(unique(tran_code), collapse=",")), by=.EACHI]
   item_code item_category  in_trans
1:      1111          cata aaaa,cccc
2:      2222          catb aaaa,bbbb
3:      3333          catc bbbb,dddd
4:      4444          catd      cccc

The first chain [] "reshapes" the transactions data to long, (one trans_item-tran_code per row). The second [] joins this onto the items data.frame on item code and then wraps up the items in the transaction by item_code with paste and unique. Using by=.EACHI allows for this operation to occur on the item_code level.

Note that this requires that none of your variables are factors. I used stringsAsFactors=FALSE in reading in your data.


问:
Text Overflowing Flex With React Native
I am trying to setup a row for a ListView, the problem is that the message part keeps overflowing and the text seems to go behind the right hand element. Any way to stop it from flowing behind? Thanks

```<code>return (
        <TouchableOpacity onPress={() => this.pressRow()}>
            <View style={styles.messageWrapper}>
                <View style={styles.messageContentWrapper}>
                    <View style={styles.avatarWrapper} >
                        <Image source={require('../../images/demo/Profile/sample2.jpg')} style={{width: 50, height: 50}}/>
                    </View>
                    <View style={styles.messageTextWrapper} >
                        <Text style={styles.messageName}>Holly Hayes</Text>
                        <Text style={styles.messageText}>Hi Matt! Do you want to meet for happy hour tonight? I will...</Text>
                    </View>
                </View>
                <View style={styles.messageRightSide}>
                    <Text style={styles.minutes}>37 Min</Text>
                    <Image source={require('../../images/icons/IconArrowRight.png')} style={{width: 20, height: 20}}/>
                </View>
            </View>
        </TouchableOpacity>
    );

var styles = StyleSheet.create({
    wrapper: {
        backgroundColor: "#f6f6f6",
        height: (screenHeight - 40),
    },
    navWrapper: {
        height: 40,
        backgroundColor: "#fff",
    },
    messageWrapper: {
        padding: 20,
        backgroundColor: "#fff",
        marginLeft: 10,
        marginRight: 10,
        marginTop: 10,
        //justifyContent: 'space-between',
        flexDirection: "row",
        flex: 1,
    },
    listWrapper: {
        paddingBottom: 10,
    },
    messageRightSide: {
        //justifyContent: 'space-between',
        //alignItems: 'flex-end',
        flex: 0.2,
        backgroundColor: "green",
    },
    minutes: {
        color: "#1d1d26",
        fontSize: 12,
        fontFamily: "Avenir-Book",
        marginBottom: 10,
    },
    messageContentWrapper: {
        backgroundColor: "blue",
        flexDirection: "row",
        flex: 0.8,
    },
    avatarWrapper: {
        overflow: "hidden",
        borderRadius: 25,
    },
    messageTextWrapper: {
        marginLeft: 10,
    },
    messageName: {
        fontSize: 14,
        fontFamily: "Avenir-Heavy",
    },
    messageText: {
        color: "#919191",
        fontFamily: "Avenir-Light",
        fontSize: 12,
    }
});
</code>```

答:
You need to move your avatar view outside of the content wrapper view (Snack):</p>

```<code><TouchableOpacity onPress={() => this.pressRow()}>
    <View style={styles.messageWrapper}>
        <View style={styles.avatarWrapper} >
            <Image source={require('../../images/demo/Profile/sample2.jpg')} style={{width: 50, height: 50}}/>
        </View>
        <View style={styles.messageContentWrapper}>
            <View style={styles.messageTextWrapper} >
                <Text style={styles.messageName}>Holly Hayes</Text>
                <Text style={styles.messageText}>Hi Matt! Do you want to meet for happy hour tonight? I will...</Text>
            </View>
        </View>
        <View style={styles.messageRightSide}>
            <Text style={styles.minutes}>37 Min</Text>
            <Image source={require('../../images/icons/IconArrowRight.png')} style={{width: 20, height: 20}}/>
        </View>
    </View>
</TouchableOpacity>
</code>```

Title: Text Overflowing Flex With React Native

Body:
I am trying to setup a row for a ListView, the problem is that the message part keeps overflowing and the text seems to go behind the right hand element. Any way to stop it from flowing behind? Thanks

return (
        <TouchableOpacity onPress={() => this.pressRow()}>
            <View style={styles.messageWrapper}>
                <View style={styles.messageContentWrapper}>
                    <View style={styles.avatarWrapper} >
                        <Image source={require('../../images/demo/Profile/sample2.jpg')} style={{width: 50, height: 50}}/>
                    </View>
                    <View style={styles.messageTextWrapper} >
                        <Text style={styles.messageName}>Holly Hayes</Text>
                        <Text style={styles.messageText}>Hi Matt! Do you want to meet for happy hour tonight? I will...</Text>
                    </View>
                </View>
                <View style={styles.messageRightSide}>
                    <Text style={styles.minutes}>37 Min</Text>
                    <Image source={require('../../images/icons/IconArrowRight.png')} style={{width: 20, height: 20}}/>
                </View>
            </View>
        </TouchableOpacity>
    );

var styles = StyleSheet.create({
    wrapper: {
        backgroundColor: "#f6f6f6",
        height: (screenHeight - 40),
    },
    navWrapper: {
        height: 40,
        backgroundColor: "#fff",
    },
    messageWrapper: {
        padding: 20,
        backgroundColor: "#fff",
        marginLeft: 10,
        marginRight: 10,
        marginTop: 10,
        //justifyContent: 'space-between',
        flexDirection: "row",
        flex: 1,
    },
    listWrapper: {
        paddingBottom: 10,
    },
    messageRightSide: {
        //justifyContent: 'space-between',
        //alignItems: 'flex-end',
        flex: 0.2,
        backgroundColor: "green",
    },
    minutes: {
        color: "#1d1d26",
        fontSize: 12,
        fontFamily: "Avenir-Book",
        marginBottom: 10,
    },
    messageContentWrapper: {
        backgroundColor: "blue",
        flexDirection: "row",
        flex: 0.8,
    },
    avatarWrapper: {
        overflow: "hidden",
        borderRadius: 25,
    },
    messageTextWrapper: {
        marginLeft: 10,
    },
    messageName: {
        fontSize: 14,
        fontFamily: "Avenir-Heavy",
    },
    messageText: {
        color: "#919191",
        fontFamily: "Avenir-Light",
        fontSize: 12,
    }
});

Body:
You need to move your avatar view outside of the content wrapper view (Snack):

<TouchableOpacity onPress={() => this.pressRow()}>
    <View style={styles.messageWrapper}>
        <View style={styles.avatarWrapper} >
            <Image source={require('../../images/demo/Profile/sample2.jpg')} style={{width: 50, height: 50}}/>
        </View>
        <View style={styles.messageContentWrapper}>
            <View style={styles.messageTextWrapper} >
                <Text style={styles.messageName}>Holly Hayes</Text>
                <Text style={styles.messageText}>Hi Matt! Do you want to meet for happy hour tonight? I will...</Text>
            </View>
        </View>
        <View style={styles.messageRightSide}>
            <Text style={styles.minutes}>37 Min</Text>
            <Image source={require('../../images/icons/IconArrowRight.png')} style={{width: 20, height: 20}}/>
        </View>
    </View>
</TouchableOpacity>


问:
Align text underneath images in css
I'd like to make some sort of a program page for a festival. I want to create a list of images with little text underneath. I don't succeed in placing the text underneath (it always ends up next to the images instead of underneath). Can somebody help?

It should look like this:

[img1] [img2] [img3]

[text1] [text2] [text3]

[img4] [img5]

[text4] [text5]

... and so on

The size of the images is fixed, so that the rows with only 2 images are the same size as those who have 3.

This is my code in CSS thus far:

For the texts (small and big):

```<code>.prog_big{width:321px; height:434px; margin-left:30px; font-family: Lucida Sans,Calibri; font-size:16px; float:left; text-align:center}

.prog_small{width:207px; height:283px; margin-left:30px; font-family: Lucida Sans,Calibri; font-size:16px; float:left;text-align:center}
</code>```

For the images (small and big):

```<code>.poster_big{width:321px; height:434px; margin-left:30px; float:left}

.poster_small{width:207px; height:283px; margin-left:30px; float:left}
</code>```

答:
I don't this this is a css issue really. You can achieve this in HTML with this type of layout</p>

```<code><figure>
 <img src="your_Image">
 <figcaption>text here</figcaption>
</figure>
</code>```

Title: Align text underneath images in css

Body:
I'd like to make some sort of a program page for a festival. I want to create a list of images with little text underneath. I don't succeed in placing the text underneath (it always ends up next to the images instead of underneath). Can somebody help?

It should look like this:

[img1] [img2] [img3]

[text1] [text2] [text3]

[img4] [img5]

[text4] [text5]

... and so on

The size of the images is fixed, so that the rows with only 2 images are the same size as those who have 3.

This is my code in CSS thus far:

For the texts (small and big):

.prog_big{width:321px; height:434px; margin-left:30px; font-family: Lucida Sans,Calibri; font-size:16px; float:left; text-align:center}

.prog_small{width:207px; height:283px; margin-left:30px; font-family: Lucida Sans,Calibri; font-size:16px; float:left;text-align:center}

For the images (small and big):

.poster_big{width:321px; height:434px; margin-left:30px; float:left}

.poster_small{width:207px; height:283px; margin-left:30px; float:left}

Body:
I don't this this is a css issue really. You can achieve this in HTML with this type of layout

<figure>
 <img src="your_Image">
 <figcaption>text here</figcaption>
</figure>


问:
This page isn’t working HTTP ERROR 500
I am trying to use a php post method in my  project but I don't know why it isn't working.

Basically I have 2 pages: index.php and data.php

From index.php a php form is there through which one can enter his details and click submit , the other page data.php should retrieve it but it isn't doing so.I'm getting error

This page isn't working ... HTTP ERROR 500

index.php

```<code><html>
<body>
    <form action="data.php" method="post">
        Enter your tt: <input type="text" name="token"><br>
        <input type="submit">
    </form>
</body>
</html>
</code>```

JsFiddle Link

data.php

```<code><?php

if(isset($_POST['token'])){
    $abc = explode('token=',$_POST['token']);

    if($abc[1]){

        $test = explode('&expires_in=',$abc[1]);
    }
    else
    {
        $test[0] =$_POST['token'];
    }

    include 'qwert1.php';
}

else{}

$titror ='?><script>alert("Sorry, Its Invalid");document.location="/";</script><?';

?>
</code>```

JsFiddle Link

答:
Update this:

```<code>$titror ='?><script>alert("Sorry, Its Invalid");document.location="/";</script><?';
</code>```

to this:

```<code>?><script>alert("Sorry, Its Invalid");document.location="/";</script>
</code>```

You cant start a string:

```<code>$titror = '
</code>```

and close php tag.

Title: This page isn’t working HTTP ERROR 500

Body:
I am trying to use a php post method in my  project but I don't know why it isn't working.

Basically I have 2 pages: index.php and data.php

From index.php a php form is there through which one can enter his details and click submit , the other page data.php should retrieve it but it isn't doing so.I'm getting error

This page isn't working ... HTTP ERROR 500

index.php

    <form action="data.php" method="post">
        Enter your tt: <input type="text" name="token">

        <input type="submit">
    </form>

JsFiddle Link

data.php

<?php

if(isset($_POST['token'])){
    $abc = explode('token=',$_POST['token']);

    if($abc[1]){

        $test = explode('&expires_in=',$abc[1]);
    }
    else
    {
        $test[0] =$_POST['token'];
    }

    include 'qwert1.php';
}

else{}

$titror ='?><?';

?>

JsFiddle Link

Body:
Update this:

$titror ='?><script>alert("Sorry, Its Invalid");document.location="/";</script><?';

to this:

?><script>alert("Sorry, Its Invalid");document.location="/";</script>

You cant start a string:

$titror = '

and close php tag.


问:
Linq throws exception on .Substring()
I've got a situation where I need to have my LINQ to Entities query return a substring depending on the length of the string.
Here's the Query:

```<code>var query = (
    from f in Context.Files
    orderby f.DateAdded descending
    select new
    {
        Concerns = f.Concerns.Name,
        Sender = f.Sender.Name,
        CategoryCount = f.Categories.Count(),
        DateAdded = f.DateAdded,
        Comment = (f.Comment == null || f.Comment.Length < 5)
            ? f.Comment : f.Comment
    }).Take(10);
</code>```

So what I'm doing is getting the last 10 added Entities of type Files and then select a set of properties from it to display inside a listview. Some are plain strings (Concerns, Sender). CategoryCount returns the number of categories which are associated with the File object.

However, I want the comment to be truncated if it is longer then a given length. In the above code, everything is working correctly. Now when I replace this line:

```<code>Comment = (f.Comment == null || f.Comment.Length < 5)
    ? f.Comment : f.Comment
</code>```

With this line:

```<code>Comment = (f.Comment == null || f.Comment.Length < 5)
    ? f.Comment : f.Comment.SubString(0,5)
</code>```

the application throws a XamlParseException (???)

The invocation of the constructor on type 'DocumentManager.Views.ListEntriesView' that matches the specified binding constraints threw an exception

I really don't know why it would do that. Is the SubString method not supported in LINQ?

Hope someone can help me here. Until then, I'll just leave it the way it is.

EDIT 2 (Somehow, my first edit got lost. So I'm redoing it):
Based on the comments I got I changed my code to this and it works now:

```<code>var query = App.Context.Files.OrderByDescending(File => File.DateAdded).Take(10).AsEnumerable()
            .Select(File => new
            {
                Concerns = File.Concerns.Name,
                Sender = File.Sender.Name,
                CategoryCount = File.Categories.Count(),
                DateAdded = File.DateAdded,
                Comment = (File.Comment == null || File.Comment.Length < 100) ? File.Comment : File.Comment.Substring(0, 100) + "..."
            });
</code>```

I forgot to mention that I'm using SQLite. So maybe Substring is not implemented in the SQLite EF Provider.

答: I don't know for sure, but I would suspect substring isn't supported by Linq-to-Entities.  I would move your Take(10) to before your select statement, then after Take(10) call AsEnumerable(), then have your select statement after that.  That will cause you to pull back a collection of Files from the database, then the projection will be done in-memory.</p>

Title: Linq throws exception on .Substring()

Body:
I've got a situation where I need to have my LINQ to Entities query return a substring depending on the length of the string.
Here's the Query:

var query = (
    from f in Context.Files
    orderby f.DateAdded descending
    select new
    {
        Concerns = f.Concerns.Name,
        Sender = f.Sender.Name,
        CategoryCount = f.Categories.Count(),
        DateAdded = f.DateAdded,
        Comment = (f.Comment == null || f.Comment.Length < 5)
            ? f.Comment : f.Comment
    }).Take(10);

So what I'm doing is getting the last 10 added Entities of type Files and then select a set of properties from it to display inside a listview. Some are plain strings (Concerns, Sender). CategoryCount returns the number of categories which are associated with the File object.

However, I want the comment to be truncated if it is longer then a given length. In the above code, everything is working correctly. Now when I replace this line:

Comment = (f.Comment == null || f.Comment.Length < 5)
    ? f.Comment : f.Comment

With this line:

Comment = (f.Comment == null || f.Comment.Length < 5)
    ? f.Comment : f.Comment.SubString(0,5)

the application throws a XamlParseException (???)

The invocation of the constructor on type 'DocumentManager.Views.ListEntriesView' that matches the specified binding constraints threw an exception

I really don't know why it would do that. Is the SubString method not supported in LINQ?

Hope someone can help me here. Until then, I'll just leave it the way it is.

EDIT 2 (Somehow, my first edit got lost. So I'm redoing it):
Based on the comments I got I changed my code to this and it works now:

var query = App.Context.Files.OrderByDescending(File => File.DateAdded).Take(10).AsEnumerable()
            .Select(File => new
            {
                Concerns = File.Concerns.Name,
                Sender = File.Sender.Name,
                CategoryCount = File.Categories.Count(),
                DateAdded = File.DateAdded,
                Comment = (File.Comment == null || File.Comment.Length < 100) ? File.Comment : File.Comment.Substring(0, 100) + "..."
            });

I forgot to mention that I'm using SQLite. So maybe Substring is not implemented in the SQLite EF Provider.


问:
Django REST, Accessing methods of the selected object
this part of my code fills the queryset with [category_object].subcats.all(). let subcats be a method of category object:

serializer:

```<code>class CatSrlz(serializers.ModelSerializer):
class Meta:
    model = Category
    fields = ('id', 'label', )
</code>```

View:

```<code>class CatsViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Category.objects.filter(parent=None)
serializer_class = CatSrlz

def retrieve(self, request, *args, **kwargs):
    # return Response({'res': self.kwargs})
    queryset = Category.objects.get(pk=str(self.kwargs['pk'])).subCats.all()
    dt = CatSrlz(queryset, many=True)
    return Response(dt.data)
</code>```

and url:

```<code>router.register(r'cats', views.CatsViewSet)
</code>```

it works but i'm pretty sure that there must be a more correct way of doing so
Is there one?

thanks

答:
When retrieving a single object, you can use the get_object method in your view, which look like this in DRF without modifications :

```<code>def get_object(self):
    """
    Returns the object the view is displaying.

    You may want to override this if you need to provide non-standard
    queryset lookups.  Eg if objects are referenced using multiple
    keyword arguments in the url conf.
    """
    queryset = self.filter_queryset(self.get_queryset())

    # Perform the lookup filtering.
    lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

    assert lookup_url_kwarg in self.kwargs, (
        'Expected view %s to be called with a URL keyword argument '
        'named "%s". Fix your URL conf, or set the `.lookup_field` '
        'attribute on the view correctly.' %
        (self.__class__.__name__, lookup_url_kwarg)
    )

    filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
    obj = get_object_or_404(queryset, **filter_kwargs)

    # May raise a permission denied
    self.check_object_permissions(self.request, obj)

    return obj
</code>```

So you could adapt the part where you get your object :

```<code>filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
obj = get_object_or_404(queryset, **filter_kwargs)
</code>```

and add your subcat logic there.

By the way, I don't get why you are using

```<code>dt = CatSrlz(queryset, many=True)
</code>```

Shouldn't "retrieve" return a single object?

Body:
this part of my code fills the queryset with [category_object].subcats.all(). let subcats be a method of category object:

serializer:

class CatSrlz(serializers.ModelSerializer):
class Meta:
    model = Category
    fields = ('id', 'label', )

View:

class CatsViewSet(viewsets.ReadOnlyModelViewSet):
queryset = Category.objects.filter(parent=None)
serializer_class = CatSrlz

def retrieve(self, request, *args, **kwargs):
    # return Response({'res': self.kwargs})
    queryset = Category.objects.get(pk=str(self.kwargs['pk'])).subCats.all()
    dt = CatSrlz(queryset, many=True)
    return Response(dt.data)

and url:

router.register(r'cats', views.CatsViewSet)

it works but i'm pretty sure that there must be a more correct way of doing so
Is there one?

thanks

Body:
When retrieving a single object, you can use the get_object method in your view, which look like this in DRF without modifications :

def get_object(self):
    """
    Returns the object the view is displaying.

    You may want to override this if you need to provide non-standard
    queryset lookups.  Eg if objects are referenced using multiple
    keyword arguments in the url conf.
    """
    queryset = self.filter_queryset(self.get_queryset())

    # Perform the lookup filtering.
    lookup_url_kwarg = self.lookup_url_kwarg or self.lookup_field

    assert lookup_url_kwarg in self.kwargs, (
        'Expected view %s to be called with a URL keyword argument '
        'named "%s". Fix your URL conf, or set the `.lookup_field` '
        'attribute on the view correctly.' %
        (self.__class__.__name__, lookup_url_kwarg)
    )

    filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
    obj = get_object_or_404(queryset, **filter_kwargs)

    # May raise a permission denied
    self.check_object_permissions(self.request, obj)

    return obj

So you could adapt the part where you get your object :

filter_kwargs = {self.lookup_field: self.kwargs[lookup_url_kwarg]}
obj = get_object_or_404(queryset, **filter_kwargs)

and add your subcat logic there.

By the way, I don't get why you are using

dt = CatSrlz(queryset, many=True)

Shouldn't "retrieve" return a single object?


问:
print 24 number in different raw and in snake pattern with for loop
I want to know how I can code in python 3.x below pattern:

```<code>24 23 22 21 20 19

13 14 15 16 17 18

12 11 10 9 8  7

1  2  3  4 5  6
</code>```

This is what I tried:

```<code>rows = 16
for i in range(rows):
    k = i*8+1
    for j in range(k,k+8):
        print '{0:4d}'.format(j),
    print " "
</code>```

答:
The spacing in your desired output is not clear. I'll assume you want each number to take 4 spaces, as in your attempted code. Here is Python 3.6.1 code that uses multiple ranges and avoids lists, dictionaries, comprehensions, and joins, as your code also does. Those features might make the code more concise. This code does use a Boolean flag variable and a range using a ternary operator.

```<code>rows = 4
cols = 6

increasing = True
for j in range(rows * cols, 0, -cols):
    increasing = not increasing
    for k in range(j-cols+1, j+1) if increasing else range(j, j-cols, -1):
        print('{0:4d}'.format(k), sep='', end='')
    print()
</code>```

I get the result:

```<code>  24  23  22  21  20  19
  13  14  15  16  17  18
  12  11  10   9   8   7
   1   2   3   4   5   6
</code>```

Here is a version that does not use a Boolean flag variable, directly using the largest value in a row to decide if that row is in increasing or decreasing order:

```<code>rows = 4
cols = 6

for j in range(rows * cols, 0, -cols):
    for k in range(j-cols+1, j+1) if j // cols % 2 else range(j, j-cols, -1):
        print('{0:4d}'.format(k), sep='', end='')
    print()
</code>```

This code is two lines shorter but less clear than my previous code. For 4 rows and 6 columns that gives the same output as my previous code. However, my previous code always prints the first row in decreasing order, while this code always prints the last row in increasing order. You only see the difference if the number of rows is odd, and your problem description does not make it clear which you want. This last code could be modified to always agree with my first code but that would make it more complicated.

A Boolean value is a truth value, with only two possible values, encoded into a computer. In Python the two values are True and False. The type is named after George Boole who first made an algebra of logic. A flag variable is a variable that holds one of two possible values, often but not always Boolean values. It represents some state of the system and communicates that state to parts of the program. It is like the "flag" on old-fashioned American postal boxes which were raised to show that the box contained outgoing mail and lowered to show no outgoing mail. Many railroad systems had similar flags--only two states, showing/raised or not showing/not raised.

In my first code, increasing is a Boolean flag variable. It represents the direction that the numbers in the "current row" are to be printed--True means increasing order, while False means decreasing order. That flag is reversed for each line, to get the desired "snake pattern." I start it out by setting it to True (increasing order) before any rows are examined, so the first printed row will be printed in decreasing order. The state of that flag is used to choose the proper range for the row--the two possible ranges for a row have the same values but in a different order.

In my second code, I avoided a flag variable by directly calculating the proper order for a row by examining the value of j, the largest number in the row. I divide that by the number of columns, yielding the row number for the current row, where 1 is the last row. I then see if that row number is even or odd by checking the remainder after dividing the row number by two. All that is done in the expression j // cols % 2. If that value is odd, the remainder is one, and Python considers any non-zero number to be "Truthy" and treats that expression as True. If the row number is even, the calculated remainder is zero and thus "Falsey" and is treated as False. So I get a logical result without using a flag variable or any Boolean value at all. As I said, this is shorter than my first code but harder to understand.

Body:
I want to know how I can code in python 3.x below pattern:

24 23 22 21 20 19

13 14 15 16 17 18

12 11 10 9 8  7

1  2  3  4 5  6

This is what I tried:

rows = 16
for i in range(rows):
    k = i*8+1
    for j in range(k,k+8):
        print '{0:4d}'.format(j),
    print " "

Body:
The spacing in your desired output is not clear. I'll assume you want each number to take 4 spaces, as in your attempted code. Here is Python 3.6.1 code that uses multiple ranges and avoids lists, dictionaries, comprehensions, and joins, as your code also does. Those features might make the code more concise. This code does use a Boolean flag variable and a range using a ternary operator.

rows = 4
cols = 6

increasing = True
for j in range(rows * cols, 0, -cols):
    increasing = not increasing
    for k in range(j-cols+1, j+1) if increasing else range(j, j-cols, -1):
        print('{0:4d}'.format(k), sep='', end='')
    print()

I get the result:

  24  23  22  21  20  19
  13  14  15  16  17  18
  12  11  10   9   8   7
   1   2   3   4   5   6

Here is a version that does not use a Boolean flag variable, directly using the largest value in a row to decide if that row is in increasing or decreasing order:

rows = 4
cols = 6

for j in range(rows * cols, 0, -cols):
    for k in range(j-cols+1, j+1) if j // cols % 2 else range(j, j-cols, -1):
        print('{0:4d}'.format(k), sep='', end='')
    print()

This code is two lines shorter but less clear than my previous code. For 4 rows and 6 columns that gives the same output as my previous code. However, my previous code always prints the first row in decreasing order, while this code always prints the last row in increasing order. You only see the difference if the number of rows is odd, and your problem description does not make it clear which you want. This last code could be modified to always agree with my first code but that would make it more complicated.

A Boolean value is a truth value, with only two possible values, encoded into a computer. In Python the two values are True and False. The type is named after George Boole who first made an algebra of logic. A flag variable is a variable that holds one of two possible values, often but not always Boolean values. It represents some state of the system and communicates that state to parts of the program. It is like the "flag" on old-fashioned American postal boxes which were raised to show that the box contained outgoing mail and lowered to show no outgoing mail. Many railroad systems had similar flags--only two states, showing/raised or not showing/not raised.

In my first code, increasing is a Boolean flag variable. It represents the direction that the numbers in the "current row" are to be printed--True means increasing order, while False means decreasing order. That flag is reversed for each line, to get the desired "snake pattern." I start it out by setting it to True (increasing order) before any rows are examined, so the first printed row will be printed in decreasing order. The state of that flag is used to choose the proper range for the row--the two possible ranges for a row have the same values but in a different order.

In my second code, I avoided a flag variable by directly calculating the proper order for a row by examining the value of j, the largest number in the row. I divide that by the number of columns, yielding the row number for the current row, where 1 is the last row. I then see if that row number is even or odd by checking the remainder after dividing the row number by two. All that is done in the expression j // cols % 2. If that value is odd, the remainder is one, and Python considers any non-zero number to be "Truthy" and treats that expression as True. If the row number is even, the calculated remainder is zero and thus "Falsey" and is treated as False. So I get a logical result without using a flag variable or any Boolean value at all. As I said, this is shorter than my first code but harder to understand.