问:
VBA Input Box will not close
I currently have a code shown below for entering a password to have the code start. I am a VBA noob so please go easy on me.

Issue: When the input box prompt appears it works fine if the password is correct. If it is incorrect you are given more opportunities to enter it again but lets say you do not know the password and want to close the window, you cannot. The "x" option and cancel options will just cause the input box prompt to refresh rather than closing the window. How can I set the window up to close?

Here is the code in written form:

```<code>    Sub Pword()

        Dim Ans As Boolean
        Const Pword As String = "black2"

        Ans = False

        Do While Ans = False
            If InputBox("Please enter password to continue.", "Enter Password") = Pword Then
                Ans = True
            End If
        Loop

Sheets("Workshop").Range("B15:B20") = ""
Sheets("Workshop").Range("B24:B29") = ""
Sheets("Workshop").Range("B33:B35") = ""
Sheets("Workshop").Range("E5:E11") = ""
Sheets("Workshop").Range("E15:E26") = ""
Sheets("Workshop").Range("H5:H17") = ""

MsgBox "All data has been cleared."

End Sub
</code>```

答:
If you need to consider an empty string as a valid input value, the only way to check if the InputBox was actually cancelled isn't to compare its result with vbNullString or "" (both will be True).

So you can use the (undocumented) StrPtr function to determine if the InputBox call returned a legit empty string, or if it was actively cancelled with the [X] or [Cancel] button:

```<code>Dim result As String
result = InputBox(...)
If StrPtr(result) = 0 Then
    ' inputbox was cancelled
    Exit Sub
Else
    ' todo: validate result
End If
</code>```

Combine that with the other answers to get a reliable "retry" mechanism.

Title: VBA Input Box will not close

Body:
I currently have a code shown below for entering a password to have the code start. I am a VBA noob so please go easy on me.

Issue: When the input box prompt appears it works fine if the password is correct. If it is incorrect you are given more opportunities to enter it again but lets say you do not know the password and want to close the window, you cannot. The "x" option and cancel options will just cause the input box prompt to refresh rather than closing the window. How can I set the window up to close?

Here is the code in written form:

    Sub Pword()

        Dim Ans As Boolean
        Const Pword As String = "black2"

        Ans = False

        Do While Ans = False
            If InputBox("Please enter password to continue.", "Enter Password") = Pword Then
                Ans = True
            End If
        Loop

Sheets("Workshop").Range("B15:B20") = ""
Sheets("Workshop").Range("B24:B29") = ""
Sheets("Workshop").Range("B33:B35") = ""
Sheets("Workshop").Range("E5:E11") = ""
Sheets("Workshop").Range("E15:E26") = ""
Sheets("Workshop").Range("H5:H17") = ""

MsgBox "All data has been cleared."

End Sub

Body:
If you need to consider an empty string as a valid input value, the only way to check if the InputBox was actually cancelled isn't to compare its result with vbNullString or "" (both will be True).

So you can use the (undocumented) StrPtr function to determine if the InputBox call returned a legit empty string, or if it was actively cancelled with the [X] or [Cancel] button:

Dim result As String
result = InputBox(...)
If StrPtr(result) = 0 Then
    ' inputbox was cancelled
    Exit Sub
Else
    ' todo: validate result
End If

Combine that with the other answers to get a reliable "retry" mechanism.


来源: stackexchange

问:
NSURL doesn't like get variables
I'm getting an error when I pass a string to an NSURL.

```<code>Entity: line 6: parser error : EntityRef: expecting ';'
zzzzzzz.com/feeds/rss/zzzz/zzzz/get_feed.php?c=zzzz&s=zzzz&f
</code>```

It doesn't stop the app or anything but I feel like it should be addressed.  Looks like it doesn't like the & symbol.  I tried replacing with & but that doesn't do the trick.

```<code>NSString *blogAddress = @"http://zzzzzz.com/feeds/rss/zzzz/zzzz/get_feed.php?c=zzzz&s=zzzz&f=most_recent";
NSURL *url = [NSURL URLWithString: blogAddress];
CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];
</code>```

答:
Try encoding your URL string like this...</p>

```<code>NSURL *url = [NSURL URLWithString:[blogAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
</code>```

ContentLicense: CC BY-SA 2.5

Title: NSURL doesn't like get variables

Body:
I'm getting an error when I pass a string to an NSURL.

Entity: line 6: parser error : EntityRef: expecting ';'
zzzzzzz.com/feeds/rss/zzzz/zzzz/get_feed.php?c=zzzz&s=zzzz&f

It doesn't stop the app or anything but I feel like it should be addressed.  Looks like it doesn't like the & symbol.  I tried replacing with & but that doesn't do the trick.

NSString *blogAddress = @"http://zzzzzz.com/feeds/rss/zzzz/zzzz/get_feed.php?c=zzzz&s=zzzz&f=most_recent";
NSURL *url = [NSURL URLWithString: blogAddress];
CXMLDocument *rssParser = [[[CXMLDocument alloc] initWithContentsOfURL:url options:0 error:nil] autorelease];

Body:
Try encoding your URL string like this...

NSURL *url = [NSURL URLWithString:[blogAddress stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];


问:
Angular inside Apache HTTPS
I have an App in Angular 4 that I built with ng build --prod command, this files are in the Apache folder and working good but when I refresh the page or I try to access for example 192.168.1.10/login, I get this error:

Not Found The requested URL /login was not found on this server.

I know that this error is because Apache try to resolve the directory throw the folders but I setup it and it dosen't still working:

```<code><VirtualHost *:443>
    ServerName  my-app

    DocumentRoot /var/www/html

    <Directory /var/www/html>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html
        # to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>
</code>```

Observation:

Before to implements HTTPS I have this configuration and working fine:

```<code><VirtualHost *:80>
    ServerName my-app

    DocumentRoot /var/www/html

    <Directory /var/www/html
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html
        # to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>
</code>```

答:
Solution: I used this instruction in the routing.ts file:

```<code>RouterModule.forRoot(appRoutes, {useHash: true});
</code>```

Works fine.

ContentLicense: CC BY-SA 3.0

Title: Angular inside Apache HTTPS

Body:
I have an App in Angular 4 that I built with ng build --prod command, this files are in the Apache folder and working good but when I refresh the page or I try to access for example 192.168.1.10/login, I get this error:

Not Found The requested URL /login was not found on this server.

I know that this error is because Apache try to resolve the directory throw the folders but I setup it and it dosen't still working:

<VirtualHost *:443>
    ServerName  my-app

    DocumentRoot /var/www/html

    <Directory /var/www/html>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html
        # to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>

Observation:

Before to implements HTTPS I have this configuration and working fine:

<VirtualHost *:80>
    ServerName my-app

    DocumentRoot /var/www/html

    <Directory /var/www/html
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html
        # to allow html5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>

Body:
Solution: I used this instruction in the routing.ts file:

RouterModule.forRoot(appRoutes, {useHash: true});

Works fine.


问:
Is Android Cursor.moveToNext() Documentation Correct?
boolean android.database.Cursor.moveToNext() documentation says:

http://developer.android.com/reference/android/database/Cursor.html#moveToNext%28%29

Move the cursor to the next row.

This method will return false if the cursor is already past the last entry in the result set.

However, my book says to do the following to extract data from a cursor:

```
Cursor myCursor = myDatabase.query(...);
if (myCursor.moveToFirst()) {
    do {
    int value = myCursor.getInt(VALUE_COL);
    // use value
    } while (myCursor.moveToNext());
}
```

Who's right?  These both can't be true.  If you can't see the contradiction, imagine myCursor has 1 row returned from the query.  The first call to getInt() will work, but then moveToNext() will return true because it is not "already" past the last entry in the result set.  So now the cursor will be past the last entry and the second call to getInt() will do something undefined.

I suspect the documentation is wrong and should instead read:

This method will return false if the cursor is "already at" the last entry in the result set.

Must the cursor be already PAST (not AT) the last entry before the moveToNext() method returns false?

No Snark Please

答:
Cursor.moveToNext() returning a boolean is only useful if it will not move the cursor past the last entry in the data set. Thus, I have submitted a bug report on the documentation's issue tracker.

https://issuetracker.google.com/issues/69259484

It reccomends the following sentence:

"This method will return false if the current (at time of execution) entry is the last entry in the set, and there is no next entry to be had."

Body:
boolean android.database.Cursor.moveToNext() documentation says:

http://developer.android.com/reference/android/database/Cursor.html#moveToNext%28%29

Move the cursor to the next row.

This method will return false if the cursor is already past the last entry in the result set.

However, my book says to do the following to extract data from a cursor:

Cursor myCursor = myDatabase.query(...);
if (myCursor.moveToFirst()) {
    do {
    int value = myCursor.getInt(VALUE_COL);
    // use value
    } while (myCursor.moveToNext());
}

Who's right?  These both can't be true.  If you can't see the contradiction, imagine myCursor has 1 row returned from the query.  The first call to getInt() will work, but then moveToNext() will return true because it is not "already" past the last entry in the result set.  So now the cursor will be past the last entry and the second call to getInt() will do something undefined.

I suspect the documentation is wrong and should instead read:

This method will return false if the cursor is "already at" the last entry in the result set.

Must the cursor be already PAST (not AT) the last entry before the moveToNext() method returns false?

No Snark Please


问:
From where is my php.ini being loaded in php Docker container?
I am running this Docker instance of a linux debian:jessie with php 5.6.

This is part of my phpinfo :

As we can see the php.ini should be located at

```<code>/usr/local/etc/php
</code>```

And this is what I have inside /usr/local/etc/

But there is no php.ini inside it.

I the other hand, I have the php.ini inside

So, from where exactly is my php.ini being loaded?

We dont even have a php process running but the php seems to be ok - being displayed phpinfo in the screen.

答:
Let try it as an answer:

It does not exist at all, which means php will run the default options.

Look at your docker file, it starts from a "clean" OS, installs Apache and PHP in it. But it never copies the php.ini file from the PHP installation into /usr/local/etc/php. Actually in lines 31 and 32 it creates the conf.d directory but that is it.

So I would suggest, at the end of your docker file, add code to copy php.ini-production to /usr/local/etc/php.ini, and edits as required. Or use default options.

ContentLicense: CC BY-SA 4.0

Body:
I am running this Docker instance of a linux debian:jessie with php 5.6.

This is part of my phpinfo :

As we can see the php.ini should be located at

/usr/local/etc/php

And this is what I have inside /usr/local/etc/

But there is no php.ini inside it.

I the other hand, I have the php.ini inside

So, from where exactly is my php.ini being loaded?

We dont even have a php process running but the php seems to be ok - being displayed phpinfo in the screen.


问:
Would C# benefit from aggregate structs/classes?

Foreword

tl;wr: This is a discussion.

I am aware that this "question" is more of a discussion, hence why I will mark it as community wiki. However, according to the How to Ask page, it could belong here, as it is specifically programming related, not discussed anywhere on the web after an hour of research, specific, relevant to most C# programmers, and on-topic. Moreover, the question itself is meant to obtain an answer, for which I'd stay open-minded regardless of my bias: would C# really benefit from aggregate structs? Notwithstanding this foreword, I'd understand this to be closed, but would appreciate if the users with the authority and intention to close redirected me to an appropriate discussion spot on the Web.

Introduction

Lacks of struct mutability

Structs are flexible but debated types in C#. They offer the stack-allocated value type organizational paradigm, but not the immutability of other value types.

Some say structs should represent values, and values do not change (e.g. int i = 5;, 5 is immutable), while some perceive them as OOP layouts with subfields.

The debate on struct immutability (1, 2, 3) , for which the current solution seems to be having the programmer enforce immutability, is also unsolved.

For instance, the C# compiler will detect possible data loss when structs are accessed as a reference (bottom of this page) and restrict assignment. Moreover, since struct constructors, properties and functions are able to do whichever operation, with the limit (for constructors) of assigning all the fields before returning controls, structs cannot be declared as constant, which would be a correct declaration if they were limited to data representation.

Immutable subset of structs, aggregates

Aggregate classes (Wikipedia) are strict data structures with limited functionality, destined to offer syntactic sugar in counterpart for their lack of flexibility. In C++, they have "no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions". The theoretical specifics of such classes in C# are herein open for debate, although the core concept remains the same.

Since aggregate structs are strictly data holders with labeled accessors, their immutability (in a possible C# context) would be insured. Aggregates also couldn't be nulled, unless the null operator (?) is specified, as for other pure value types. For this reason, many illegal struct operations would become possible, as well as some syntactic sugar.

Uses

Aggregates could be declared as const, since their constructor would be enforced to do nothing but assign the fields.

Aggregates could be used as default values for method parameters.

Aggregates could be implicitly Sequential, facilitating interaction with native

Aggregates would be immutable, enforcing no data loss for reference access. Compiler detection of such subfield modifications could lead to a complete, implicit reassignment.libraries.

Hypothetical Syntax

Taking from the C++ syntax, we could imagine something along the lines of:
(Remember, this is a community wiki, improvement is welcome and encouraged)

```<code>aggregate Size
{
    int Width;
    int Height;
}

aggregate Vector
{
    // Default values for constructor.
    double X = 0, Y = 0, Z = 0;
}

aggregate Color
{
    byte R, G, B, A = 255;
}

aggregate Bar
{
    int X;
    Qux Qux;
}

aggregate Qux
{
    int X, Y;
}

static class Foo
{
    // Constant is possible.
    const Size Big = new Size(200, 100);

    // Inline constructor.
    const Vector Gravity = { 0, -9.8, 0 };

    // Default value / labeled parameter.
    const Color Fuschia = { 255, 0, 255 };
    const Vector Up = { y: 1 };

    // Sub-aggregate initialization
    const Bar Test = { 20, { 4, 3 } };

    static void SetVelocity(Vector velocity = { 0, 1, 0 }) { ... }
    static void SetGravity(Vector gravity = Foo.Gravity) { ... }

    static void Main()
    {
        Vector v = { 1, 2, 3 };

        double y = v.Y; // Valid.

        v.Y = 5; // Invalid, immutable.
    }
}
</code>```

Implicit (re)Assignment

As of today, assigning a subfield of a struct in C# 4.0 is valid:

```<code>Vector v = new Vector(1, 2, 3);
v.Z = 5; // Legal in current C#.
</code>```

However, sometimes, the compiler can detect when structs are mistakenly accessed as references, and will forbid changing subfields. For example, (example question)

```<code>//(in a Windows.Forms context)
control.Size.Width = 20; // Illegal in current C#.
</code>```

As Size is a property and struct Size a value type, we would be editing a copy/clone of the actual property, which would be useless in such a case. As C# users, we tend to assume most things are accessed by reference, especially in OOP designs, which would make us think that such a call is legitimate (and it would be, if struct Size were a class).

Moreover, when accessing collections, the compiler also forbids us from modifying a struct subfield: (example question)

```<code>List<Vector> vectors = ... // Imagine populated data.
vectors[4].Y = 10; // Illegal in current C#.
</code>```

The good news about these unfortunate restrictions is that the compiler does half of the possible aggregate solution for such cases: detect when they occur. The other half would be to implicitly reassign a new aggregate with the changed value.

When in local scope, simply reassign the vector.

When in external scope, locate a get, and if a matching set accessor is accessible, reassign to this one.

For this to be done and in order to avoid confusion, the delegate must be marked as implicit:

```<code>implicit aggregate Vector { ... }
implicit aggregate Size { ... }

// Example 1
{
    Vector v = new Vector(1, 2, 3);
    v.Z = 5; // Legal with implicit aggregates.

    // What is implicitly done:
    v = new Vector(v.X, v.Y, 5); // Local variable, simply reassign.
}

// Example 2
{
    //(in a Windows.Forms context)
    control.Size.Width = 20; // Legal with implicit aggregates.

    // What is implicitly done:
    Size old = control.Size.__get(); // External, MSIL detects a get.
    // If MSIL can find a matching, accessible __set:
    control.Size.__set({ 20, old.Height });
}

// Example 3
{
    List<Vector> vectors = ... // Imagine populated data.
    vectors[4].Y = 10; // Legal with implicit aggregates.

    // What is implicitly done:
    Vector old = vectors[4].__get(); // External, MSIL detects a get.
    // If MSIL can find a matching, accessible __set:
    vectors[4].__set({ old.X, 10, old.Z });
}

// Example 4
{
    Vector The5thVector(List<Vector> vectors) { return vectors[4]; }
    ...
    List<Vector> vectors = ...;
    The5thVector(vectors).Y = 10; // Illegal with implicit aggregates.

    // This is illegal because the compiler cannot find an implicit
    // "set" to match. as it is a function return, not a property or
    // indexer.
}
</code>```

Of course, this last implicit reassignment is only a syntactic simplification which could or could not be adopted. I simply propose it as the compiler seems to be able to detect such reference access to structs and could easily convert the code for the programmer if it was an aggregate.

Summary

Aggregates can have fields;

Aggregates are value types;

Aggregates are immutable;

Aggregates are allocated on the stack;

Aggregates cannot inherit;

Aggregates have a sequential layout;

Aggregates have a sequential default constructor;

Aggregates cannot have user defined constructors;

Aggregates can have default values and labeled constructions;

Aggregates can be defined inline;

Aggregates can be declared as constant;

Aggregates can be used as default parameters;

Aggregates are non-nullable unless specified (?);

Possibly:

Aggregates (could) be implicitly reassigned; See Marcelo Cantos' reply and comment.

Aggregates (could) have interfaces;

Aggregates (could) have methods;

Cons

As aggregates wouldn't replace structs but rather be another organizational scheme, I cannot find many cons, but hope that the C# veterans of S/O will be able to populate this CW section. On a last note, please answer the question directly, as well as discussing it: would C# benefit for aggregate classes as described in this post? I am no C# expert in any way, but only an enthusiast of the C# language, and miss this feature which seems crucial to me. I'm seeking advice and comments from experienced programmers regarding this case. I am aware that there are numerous workarounds that exist and actively use them everyday, I simply think that they are too common to be ignored.

答:
I wish that structs had been defined with something like your proposed semantics in the first place.

However, we're stuck with what we've got now and I think it is unlikely that we'll ever get a whole new "kind of type" into the CLR. Introducing a new kind of type means introducing it to every .NET language, not just C#, and that's a big change.

I think what is more likely -- and remember, when I talk about hypothetical language features for hypothetical, unannounced future products that don't exist and may never exist, I'm doing so for entertainment purposes only -- is that we'll find some way to make better immutability annotations and enforcements on both classes and structs. The compiler could do a better job of both enforcing immutability and making it easier to program in an immutable style, regardless of whether the type in question is a value type or a reference type. And the compiler or CLR could also potentially do a better job of optimizing code that works on multi core machines if it had more immutability guarantees known at compile time or jit time.

While you are noodling away at your proposal, an interesting question you might want to consider is: if aggregate types have methods, is "this" a value or a variable?  For example:

```<code>aggregate Vector
{
    int x, y, z;
    public void M(Action action)
    {
         Console.WriteLine(this.x);
         action();
         Console.WriteLine(this.x);
    }
}
...
Vector v = new Vector(1, 2, 3);
Action action = ()=>{ v = new Vector(4, 5, 6); };
v.M(action);
</code>```

What happens? Does "this" get passed to M by value, in which case it writes out "1" twice, or does it get passed as a reference to the variable, in which case your so-called "immutable" type is observed to mutate?  (Because what is mutating is the variable; by definition variables are allowed to mutate, that's why they're called "vary-able".)

Body:
Foreword

tl;wr: This is a discussion.

I am aware that this "question" is more of a discussion, hence why I will mark it as community wiki. However, according to the How to Ask page, it could belong here, as it is specifically programming related, not discussed anywhere on the web after an hour of research, specific, relevant to most C# programmers, and on-topic. Moreover, the question itself is meant to obtain an answer, for which I'd stay open-minded regardless of my bias: would C# really benefit from aggregate structs? Notwithstanding this foreword, I'd understand this to be closed, but would appreciate if the users with the authority and intention to close redirected me to an appropriate discussion spot on the Web.

Introduction

Lacks of struct mutability

Structs are flexible but debated types in C#. They offer the stack-allocated value type organizational paradigm, but not the immutability of other value types.

Some say structs should represent values, and values do not change (e.g. int i = 5;, 5 is immutable), while some perceive them as OOP layouts with subfields.

The debate on struct immutability (1, 2, 3) , for which the current solution seems to be having the programmer enforce immutability, is also unsolved.

For instance, the C# compiler will detect possible data loss when structs are accessed as a reference (bottom of this page) and restrict assignment. Moreover, since struct constructors, properties and functions are able to do whichever operation, with the limit (for constructors) of assigning all the fields before returning controls, structs cannot be declared as constant, which would be a correct declaration if they were limited to data representation.

Immutable subset of structs, aggregates

Aggregate classes (Wikipedia) are strict data structures with limited functionality, destined to offer syntactic sugar in counterpart for their lack of flexibility. In C++, they have "no user-declared constructors, no private or protected non-static data members, no base classes, and no virtual functions". The theoretical specifics of such classes in C# are herein open for debate, although the core concept remains the same.

Since aggregate structs are strictly data holders with labeled accessors, their immutability (in a possible C# context) would be insured. Aggregates also couldn't be nulled, unless the null operator (?) is specified, as for other pure value types. For this reason, many illegal struct operations would become possible, as well as some syntactic sugar.

Uses

Aggregates could be declared as const, since their constructor would be enforced to do nothing but assign the fields.

Aggregates could be used as default values for method parameters.

Aggregates could be implicitly Sequential, facilitating interaction with native

Aggregates would be immutable, enforcing no data loss for reference access. Compiler detection of such subfield modifications could lead to a complete, implicit reassignment.libraries.

Hypothetical Syntax

Taking from the C++ syntax, we could imagine something along the lines of:
(Remember, this is a community wiki, improvement is welcome and encouraged)

aggregate Size
{
    int Width;
    int Height;
}

aggregate Vector
{
    // Default values for constructor.
    double X = 0, Y = 0, Z = 0;
}

aggregate Color
{
    byte R, G, B, A = 255;
}

aggregate Bar
{
    int X;
    Qux Qux;
}

aggregate Qux
{
    int X, Y;
}

static class Foo
{
    // Constant is possible.
    const Size Big = new Size(200, 100);

    // Inline constructor.
    const Vector Gravity = { 0, -9.8, 0 };

    // Default value / labeled parameter.
    const Color Fuschia = { 255, 0, 255 };
    const Vector Up = { y: 1 };

    // Sub-aggregate initialization
    const Bar Test = { 20, { 4, 3 } };

    static void SetVelocity(Vector velocity = { 0, 1, 0 }) { ... }
    static void SetGravity(Vector gravity = Foo.Gravity) { ... }

    static void Main()
    {
        Vector v = { 1, 2, 3 };

        double y = v.Y; // Valid.

        v.Y = 5; // Invalid, immutable.
    }
}

Implicit (re)Assignment

As of today, assigning a subfield of a struct in C# 4.0 is valid:

Vector v = new Vector(1, 2, 3);
v.Z = 5; // Legal in current C#.

However, sometimes, the compiler can detect when structs are mistakenly accessed as references, and will forbid changing subfields. For example, (example question)

//(in a Windows.Forms context)
control.Size.Width = 20; // Illegal in current C#.

As Size is a property and struct Size a value type, we would be editing a copy/clone of the actual property, which would be useless in such a case. As C# users, we tend to assume most things are accessed by reference, especially in OOP designs, which would make us think that such a call is legitimate (and it would be, if struct Size were a class).

Moreover, when accessing collections, the compiler also forbids us from modifying a struct subfield: (example question)

List<Vector> vectors = ... // Imagine populated data.
vectors[4].Y = 10; // Illegal in current C#.

The good news about these unfortunate restrictions is that the compiler does half of the possible aggregate solution for such cases: detect when they occur. The other half would be to implicitly reassign a new aggregate with the changed value.

When in local scope, simply reassign the vector.

When in external scope, locate a get, and if a matching set accessor is accessible, reassign to this one.

For this to be done and in order to avoid confusion, the delegate must be marked as implicit:

implicit aggregate Vector { ... }
implicit aggregate Size { ... }

// Example 1
{
    Vector v = new Vector(1, 2, 3);
    v.Z = 5; // Legal with implicit aggregates.

    // What is implicitly done:
    v = new Vector(v.X, v.Y, 5); // Local variable, simply reassign.
}

// Example 2
{
    //(in a Windows.Forms context)
    control.Size.Width = 20; // Legal with implicit aggregates.

    // What is implicitly done:
    Size old = control.Size.__get(); // External, MSIL detects a get.
    // If MSIL can find a matching, accessible __set:
    control.Size.__set({ 20, old.Height });
}

// Example 3
{
    List<Vector> vectors = ... // Imagine populated data.
    vectors[4].Y = 10; // Legal with implicit aggregates.

    // What is implicitly done:
    Vector old = vectors[4].__get(); // External, MSIL detects a get.
    // If MSIL can find a matching, accessible __set:
    vectors[4].__set({ old.X, 10, old.Z });
}

// Example 4
{
    Vector The5thVector(List<Vector> vectors) { return vectors[4]; }
    ...
    List<Vector> vectors = ...;
    The5thVector(vectors).Y = 10; // Illegal with implicit aggregates.

    // This is illegal because the compiler cannot find an implicit
    // "set" to match. as it is a function return, not a property or
    // indexer.
}

Of course, this last implicit reassignment is only a syntactic simplification which could or could not be adopted. I simply propose it as the compiler seems to be able to detect such reference access to structs and could easily convert the code for the programmer if it was an aggregate.

Summary

Aggregates can have fields;

Aggregates are value types;

Aggregates are immutable;

Aggregates are allocated on the stack;

Aggregates cannot inherit;

Aggregates have a sequential layout;

Aggregates have a sequential default constructor;

Aggregates cannot have user defined constructors;

Aggregates can have default values and labeled constructions;

Aggregates can be defined inline;

Aggregates can be declared as constant;

Aggregates can be used as default parameters;

Aggregates are non-nullable unless specified (?);

Possibly:

Aggregates (could) be implicitly reassigned; See Marcelo Cantos' reply and comment.

Aggregates (could) have interfaces;

Aggregates (could) have methods;

Cons

As aggregates wouldn't replace structs but rather be another organizational scheme, I cannot find many cons, but hope that the C# veterans of S/O will be able to populate this CW section. On a last note, please answer the question directly, as well as discussing it: would C# benefit for aggregate classes as described in this post? I am no C# expert in any way, but only an enthusiast of the C# language, and miss this feature which seems crucial to me. I'm seeking advice and comments from experienced programmers regarding this case. I am aware that there are numerous workarounds that exist and actively use them everyday, I simply think that they are too common to be ignored.

Body:
I wish that structs had been defined with something like your proposed semantics in the first place.

However, we're stuck with what we've got now and I think it is unlikely that we'll ever get a whole new "kind of type" into the CLR. Introducing a new kind of type means introducing it to every .NET language, not just C#, and that's a big change.

I think what is more likely -- and remember, when I talk about hypothetical language features for hypothetical, unannounced future products that don't exist and may never exist, I'm doing so for entertainment purposes only -- is that we'll find some way to make better immutability annotations and enforcements on both classes and structs. The compiler could do a better job of both enforcing immutability and making it easier to program in an immutable style, regardless of whether the type in question is a value type or a reference type. And the compiler or CLR could also potentially do a better job of optimizing code that works on multi core machines if it had more immutability guarantees known at compile time or jit time.

While you are noodling away at your proposal, an interesting question you might want to consider is: if aggregate types have methods, is "this" a value or a variable?  For example:

aggregate Vector
{
    int x, y, z;
    public void M(Action action)
    {
         Console.WriteLine(this.x);
         action();
         Console.WriteLine(this.x);
    }
}
...
Vector v = new Vector(1, 2, 3);
Action action = ()=>{ v = new Vector(4, 5, 6); };
v.M(action);

What happens? Does "this" get passed to M by value, in which case it writes out "1" twice, or does it get passed as a reference to the variable, in which case your so-called "immutable" type is observed to mutate?  (Because what is mutating is the variable; by definition variables are allowed to mutate, that's why they're called "vary-able".)


问:
What is the best way to pass data across multiple activities
I have an application requiring the user to fill a form in order to create a Route. This Route requires the user to create at least one Step, and a Riddle linked to the step. The user can create a Route with many Steps and Riddles.

So I have 3 activities (CreateCustomRouteActivity,CreateCustomStepActivity,CreateCustomRiddleActivity), each one composed of a form with differents fields corresponding to the object's properties.

I don't want the user to be able to create a Step without creating a Riddle, and I don't want him to create a Step and a Riddle without linking it to a Route

In the last activity, there's a button to validate and create the objects.

What is the best way to pass these data across the 3 activities? Should I use Parcelable interface? Should I use a bundle of extras in intents? Should i change the way i'm approaching it?

答:
It looks like a wizard pattern to me. I'd consider the following:

If your data is small, using Parcelable sounds like a good idea. It will be executed on the main thread so if you have a lot of data to parcel, that will block the UI.

I'd also consider implementing those 3 screens as fragments, you can have that data saved in the activity. You will still have to parcel it for configuration changes (rotation of the device for example)

You can store the data in a singleton object that won't get removed across configuration changes.


问:
Running `composer require ...` fails on post process cache clearing step
I can't seem to be able to complete installation of bundles using

composer require <bundle-name> because of these errors:

[Symfony\Component\Filesystem\Exception\IOException]   Failed to
  remove directory "/var/www/emerson-suite/var/cache/de~/pools/rDfZ

  I1q9aB": .

Complete console output of error:

Generating autoload files ocramius/package-versions:  Generating
  version class... ocramius/package-versions: ...done generating version
  class

Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::buildBootstrap
    Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache

// Clearing the cache for the dev environment with debug  // true

Symfony\Component\Filesystem\Exception\IOException]   Failed to
  remove directory "/var/www/emerson-suite/var/cache/de~/pools/rDfZ

  I1q9aB": .

cache:clear [--no-warmup] [--no-optional-warmers] [-h|--help]
  [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi]
  [-n|--no-interaction] [-e|--env ENV] [--no-debug] [--]

Script
  Sensio\Bundle\DistributionBundle\Composer\ScriptHandler::clearCache
  handling the post-update-cmd event terminated with an exception

Installation failed, reverting ./composer.json to its original
  content.

[RuntimeException]   An error occurred when executing the
  "'cache:clear --no-warmup'" command:    // Clearing the cache for the
  dev environment with debug    // true

[Symfony\Component\Filesystem\Exception\IOException]
  Failed to remove directory "/var/www/emerson-suite/var/cache/de~/pools/rDfZ
  I1q9aB": .

cache:clear [--no-warmup] [--no-optional-warmers] [-h|--help]
  [-q|--quiet] [-v|vv|vvv|--verbose] [-V|--version] [--ansi] [--no-ansi]
  [-n|--no-interaction] [-e|--env ENV]   [--no-debug] [--]

Tried running composer with both sudo and without.
The command that I ran is: $ sudo composer require javiereguiluz/easyadmin-bundle

Not sure what to do about this, any help is appreciated.

Update

My environment is Ubuntu on Vagrant VM on Mac OS X.

答:
Seems like it could be an issue involving permissions inside the OS and perhaps development environments.

Try looking for the answer here, a lot of people seem to be having this issue.
https://github.com/symfony/symfony/issues/19363#issuecomment-264655158


问:
Change Default Font Size in Power BI?
New Power BI user here- I cannot sort out how to change the default font sizes on my visualizations...

Any help is appreciated!

答:
There's no global default for font size right now. Each visual has its own options for font size.

Just in case you're not sure how to change the font size on a visual at all (I suspect you do but want to be thorough), select the visual and then:

Choose the Format tab of the visual

Choose which aspect you want to update (title, legend, and axis are common options for example)

Choose the font size

If a visual doesn't have an option for changing a particular font size, you're out of luck. For a custom visual, I'd recommend contacting the author of the visual.

If you'd like a global default font size in the future, there are a few ideas you can vote on that will let Microsoft know. Microsoft do pay attention and prioritize work based on who's voting for what, so I do recommend doing this:

Default Global Font Size: https://ideas.powerbi.com/forums/265200-power-bi-ideas/suggestions/13470411-default-global-font-size

Set default visualization formats: https://ideas.powerbi.com/forums/265200-power-bi-ideas/suggestions/17672380-set-default-visualization-formats

Title: Change Default Font Size in Power BI?


问:
Crash validating related model created using inline admin
I'm creating a one-to-one model to extend the functionality of an existing model type, but I want it to only allow creating the extension model in certain cases. I enforce this constraint by throwing a ValidationError in the full_clean on the new Extended model. This works great when I create Extended models using Extended's ModelAdmin directly (it highlights the a field if it's the wrong type), but when I use StackedInline to inline Extended creation in As ModelAdmin, and A is the wrong type, the form fails to catch the ValidationError and I get the message A server error occurred.  Please contact the administrator.

This is how I have the models set up:

```<code># models.py
from django.db import models

class A(models.Model):
    type = models.IntegerField(...)

class Extended(models.Model)
    a = models.OneToOneField(A)

    def clean_fields(self, **kwargs):
        if self.a.type != 3:
            raise ValidationError({'a': ["a must be of type 3"]})
        super(Extended, self).clean_fields(**kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(Extended, self).save(*args, **kwargs)

# admin.py
from django.contrib import admin

class ExtendedInline(admin.StackedInline):
    model = Extended

@admin.register(A)
class AAdmin(admin.ModelAdmin):
    inlines = (ExtendedInline,)
</code>```

The full traceback:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__
    return self.application(environ, start_response)
  File "/usr/local/lib/python2.7/site-packages/whitenoise/base.py", line 66, in __call__
    return self.application(environ, start_response)
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
    response = self.get_response(request)
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 218, in get_response
    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 618, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 233, in inner
    return view(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1521, in change_view
    return self.changeform_view(request, object_id, form_url, extra_context)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 34, in _wrapper
    return bound_func(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 30, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 145, in inner
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1470, in changeform_view
    self.save_related(request, form, formsets, not add)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1104, in save_related
    self.save_formset(request, form, formset, change=change)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1092, in save_formset
    formset.save()
  File "/usr/local/lib/python2.7/site-packages/django/forms/models.py", line 636, in save
    return self.save_existing_objects(commit) + self.save_new_objects(commit)
  File "/usr/local/lib/python2.7/site-packages/django/forms/models.py", line 767, in save_new_objects
    self.new_objects.append(self.save_new(form, commit=commit))
  File "/usr/local/lib/python2.7/site-packages/django/forms/models.py", line 900, in save_new
    obj.save()
  File "/code/app/models.py", line 162, in save
    self.full_clean()
  File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 1171, in full_clean
    raise ValidationError(errors)
ValidationError: {'a': [u'a must be of type 3']}
</code>```

I'm currently using Django version 1.8

答:
If I change

```<code>raise ValidationError({'a': ["a must be of type 3"]})
</code>```

to

```<code>raise ValidationError(["a must be of type 3"])
</code>```

I don't get the crash and it appears on the inline admin.

Body:
I'm creating a one-to-one model to extend the functionality of an existing model type, but I want it to only allow creating the extension model in certain cases. I enforce this constraint by throwing a ValidationError in the full_clean on the new Extended model. This works great when I create Extended models using Extended's ModelAdmin directly (it highlights the a field if it's the wrong type), but when I use StackedInline to inline Extended creation in As ModelAdmin, and A is the wrong type, the form fails to catch the ValidationError and I get the message A server error occurred.  Please contact the administrator.

This is how I have the models set up:

# models.py
from django.db import models

class A(models.Model):
    type = models.IntegerField(...)

class Extended(models.Model)
    a = models.OneToOneField(A)

    def clean_fields(self, **kwargs):
        if self.a.type != 3:
            raise ValidationError({'a': ["a must be of type 3"]})
        super(Extended, self).clean_fields(**kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(Extended, self).save(*args, **kwargs)

# admin.py
from django.contrib import admin

class ExtendedInline(admin.StackedInline):
    model = Extended

@admin.register(A)
class AAdmin(admin.ModelAdmin):
    inlines = (ExtendedInline,)

The full traceback:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/wsgiref/handlers.py", line 85, in run
    self.result = application(self.environ, self.start_response)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/staticfiles/handlers.py", line 63, in __call__
    return self.application(environ, start_response)
  File "/usr/local/lib/python2.7/site-packages/whitenoise/base.py", line 66, in __call__
    return self.application(environ, start_response)
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
    response = self.get_response(request)
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 218, in get_response
    response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
  File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 132, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 618, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/sites.py", line 233, in inner
    return view(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1521, in change_view
    return self.changeform_view(request, object_id, form_url, extra_context)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 34, in _wrapper
    return bound_func(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 110, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 30, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/usr/local/lib/python2.7/site-packages/django/utils/decorators.py", line 145, in inner
    return func(*args, **kwargs)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1470, in changeform_view
    self.save_related(request, form, formsets, not add)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1104, in save_related
    self.save_formset(request, form, formset, change=change)
  File "/usr/local/lib/python2.7/site-packages/django/contrib/admin/options.py", line 1092, in save_formset
    formset.save()
  File "/usr/local/lib/python2.7/site-packages/django/forms/models.py", line 636, in save
    return self.save_existing_objects(commit) + self.save_new_objects(commit)
  File "/usr/local/lib/python2.7/site-packages/django/forms/models.py", line 767, in save_new_objects
    self.new_objects.append(self.save_new(form, commit=commit))
  File "/usr/local/lib/python2.7/site-packages/django/forms/models.py", line 900, in save_new
    obj.save()
  File "/code/app/models.py", line 162, in save
    self.full_clean()
  File "/usr/local/lib/python2.7/site-packages/django/db/models/base.py", line 1171, in full_clean
    raise ValidationError(errors)
ValidationError: {'a': [u'a must be of type 3']}

I'm currently using Django version 1.8

Body:
If I change

raise ValidationError({'a': ["a must be of type 3"]})

to

raise ValidationError(["a must be of type 3"])

I don't get the crash and it appears on the inline admin.


问:
How to change default language of Web Browser control
I have a trouble with a WPF application. The application uses a web browser to display a certain page (Internet Explorer). The problem is the inner browser of the application shows the page always with a language configuration in English, regardless of the configuration of the browser.
When Im testing the application, It takes the language features of the browser; but before it compiles it changes and uses English language.

Is there a way to change the default language? How can I set it to use the language defined in the browser?

答:
I don't understand fine your problem, but WPF is known that ignores the "culture".
I solve with this trick:</p>

```<code>public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
    }
</code>```

Body:
I don't understand fine your problem, but WPF is known that ignores the "culture".
I solve with this trick:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
    }


答:
Short answer is you don't need one. If you're missing or want to add extensions, you can do so in your Dockerfile by doing docker-php-ext-install or docker-php-ext-enable.

Most of the common ones, you can simply do enable, such as mbstring for example, but for some less common ones, you might have to run pecl first or something to get the package. Take a look at this Docker documentation page for more information on php extensions

Title: From where is my php.ini being loaded in php Docker container?


问:
Understanding the declaration of formGroup in angular 4 forms
I am new to angular, and in the documentation i have learned that to pass data from the parent to the child we use the input decoration like this

```<code>export class demo {
  @input()
  someInput: any;
}
</code>```

and we pass the data from the parent to the child like this

```<code><div *ngFor='let data of moreData'>
<child-component [someData]='data'></child-component>
</div>
</code>```

now my question is, when we use the formGroup in the reactive form approach, we use

[formGroup]='form'

but why is the @input()formGroup:FormGroup tag not necessary for the component holding the form, am i missing something, if yes, please let me know

答:
You're not adding [formGroup] on the component holding the form. You're adding it on the <form> element. So it can't be an input of your component.

The formGroup attribute is the selector of the FormGroupDirective. And this directive has an input named formGroup.

So, by adding the formGroup attribute to an element, you trigger the instanciation of the FormGroupDirective, and by passing a value of type FormGroup as the value of this attribute, you pass the form group to the input of this directive.

Body:
I am new to angular, and in the documentation i have learned that to pass data from the parent to the child we use the input decoration like this

export class demo {
  @input()
  someInput: any;
}

and we pass the data from the parent to the child like this

<child-component [someData]='data'></child-component>

now my question is, when we use the formGroup in the reactive form approach, we use

[formGroup]='form'

but why is the @input()formGroup:FormGroup tag not necessary for the component holding the form, am i missing something, if yes, please let me know


问:
jQuery selector DOM traversal direction and efficiency
What is the standard direction of search for multipart jQuery selectors?

e.g. the case

```<code>$('#myTable tr.selected');
</code>```

Is the first search for #myTable and then the tr.selected search is only within that table?

Or is the first search for all tr.selected on the page and the second search checking each ones parent nodes?

答: You should watch this talk by John Resig on the subject. He says that, contrary to what you might expect, selector engines will search for tr.selected and then see if an ancestor matches #myTable.

Body:
What is the standard direction of search for multipart jQuery selectors?

e.g. the case

$('#myTable tr.selected');

Is the first search for #myTable and then the tr.selected search is only within that table?

Or is the first search for all tr.selected on the page and the second search checking each ones parent nodes?


问:
Programmatically evaluate a bean expression with Spring Expression Language
I have a simple Spring Bean Expression, which evaluates fine when I define it inside an application context file:

```<code><bean id="myConfigBean" class="com.example.myBeanConfigBean">
    <property name="myProperty" value="#{ someOtherBean.getData() }"/>
</bean>
</code>```

Now, I want to do the same evaluation programmatically. I have used the following code:

```<code>final ExpressionParser parser = new SpelExpressionParser();
final TemplateParserContext templateContext = new TemplateParserContext();
Expression expression = parser.parseExpression("#{ someOtherBean.getData() }", templateContext);
final String value = (String) expression.getValue();
</code>```

This throws an exception:

```<code>EL1007E:(pos 22): Field or property 'someOtherBean' cannot be found on null
</code>```

I guess I have to set a root object somehow that allows to the configured beans like a property. But I did not get it to work yet. Anyone, who has done this already and could give a hint?

答:
Please take a look @ https://www.mkyong.com/spring3/test-spring-el-with-expressionparser/

Sample java code

```<code>import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class App {
    public static void main(String[] args) {

        ExpressionParser parser = new SpelExpressionParser();

        //literal expressions
        Expression exp = parser.parseExpression("'Hello World'");
        String msg1 = exp.getValue(String.class);
        System.out.println(msg1);

        //method invocation
        Expression exp2 = parser.parseExpression("'Hello World'.length()");
        int msg2 = (Integer) exp2.getValue();
        System.out.println(msg2);

        //Mathematical operators
        Expression exp3 = parser.parseExpression("100 * 2");
        int msg3 = (Integer) exp3.getValue();
        System.out.println(msg3);

        //create an item object
        Item item = new Item("mkyong", 100);
        //test EL with item object
        StandardEvaluationContext itemContext = new StandardEvaluationContext(item);

        //display the value of item.name property
        Expression exp4 = parser.parseExpression("name");
        String msg4 = exp4.getValue(itemContext, String.class);
        System.out.println(msg4);

        //test if item.name == 'mkyong'
        Expression exp5 = parser.parseExpression("name == 'mkyong'");
        boolean msg5 = exp5.getValue(itemContext, Boolean.class);
        System.out.println(msg5);

    }
}
</code>```

Body:
I have a simple Spring Bean Expression, which evaluates fine when I define it inside an application context file:

<bean id="myConfigBean" class="com.example.myBeanConfigBean">
    <property name="myProperty" value="#{ someOtherBean.getData() }"/>
</bean>

Now, I want to do the same evaluation programmatically. I have used the following code:

final ExpressionParser parser = new SpelExpressionParser();
final TemplateParserContext templateContext = new TemplateParserContext();
Expression expression = parser.parseExpression("#{ someOtherBean.getData() }", templateContext);
final String value = (String) expression.getValue();

This throws an exception:

EL1007E:(pos 22): Field or property 'someOtherBean' cannot be found on null

I guess I have to set a root object somehow that allows to the configured beans like a property. But I did not get it to work yet. Anyone, who has done this already and could give a hint?

Body:
Please take a look @ https://www.mkyong.com/spring3/test-spring-el-with-expressionparser/

Sample java code

import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class App {
    public static void main(String[] args) {

        ExpressionParser parser = new SpelExpressionParser();

        //literal expressions
        Expression exp = parser.parseExpression("'Hello World'");
        String msg1 = exp.getValue(String.class);
        System.out.println(msg1);

        //method invocation
        Expression exp2 = parser.parseExpression("'Hello World'.length()");
        int msg2 = (Integer) exp2.getValue();
        System.out.println(msg2);

        //Mathematical operators
        Expression exp3 = parser.parseExpression("100 * 2");
        int msg3 = (Integer) exp3.getValue();
        System.out.println(msg3);

        //create an item object
        Item item = new Item("mkyong", 100);
        //test EL with item object
        StandardEvaluationContext itemContext = new StandardEvaluationContext(item);

        //display the value of item.name property
        Expression exp4 = parser.parseExpression("name");
        String msg4 = exp4.getValue(itemContext, String.class);
        System.out.println(msg4);

        //test if item.name == 'mkyong'
        Expression exp5 = parser.parseExpression("name == 'mkyong'");
        boolean msg5 = exp5.getValue(itemContext, Boolean.class);
        System.out.println(msg5);

    }
}


问:
Iterate through a list, divide values, store in new list
In the code I have series of lists, each one containing the same number of entries. What I want to do now is iterate through the list and divide one list index by the other.

```<code>threads = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dsk_indpt_PI = [99, 197, 295, 387, 391, 406, 407, 416, 424, 426, 425, 439]

avg_val = []
for x in threads:
    result = dsk_indpt_PI[x]/threads[x]
    avg_val.append(result[x])
</code>```

I am unsure if the above method works, previous methods I ran into the issue where it could not do division between type int and type list. Would the above example work better? If not, what should be changed to have it function as desired? Thank you.

答:
The better way to do this is to use zip.

You can try this:

```<code>avg_vals = []
for thread, dsk_ind in zip(threads, dsk_indpt_PI):
    avg_vals.append(dsk_ind / thread)
</code>```

zip takes two (or more) iterables and combines them into one list of tuples with length equal to the shortest iterable.

Body:
In the code I have series of lists, each one containing the same number of entries. What I want to do now is iterate through the list and divide one list index by the other.

threads = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dsk_indpt_PI = [99, 197, 295, 387, 391, 406, 407, 416, 424, 426, 425, 439]

avg_val = []
for x in threads:
    result = dsk_indpt_PI[x]/threads[x]
    avg_val.append(result[x])

I am unsure if the above method works, previous methods I ran into the issue where it could not do division between type int and type list. Would the above example work better? If not, what should be changed to have it function as desired? Thank you.

Body:
The better way to do this is to use zip.

You can try this:

avg_vals = []
for thread, dsk_ind in zip(threads, dsk_indpt_PI):
    avg_vals.append(dsk_ind / thread)

zip takes two (or more) iterables and combines them into one list of tuples with length equal to the shortest iterable.


问:
Cannot convert value of type '[String]' to expected argument type 'String'
I have a array (from a global constants file) which I am trying to use in an API call to make another dictionary array. The initial array is:

```<code>let callCountries = ["AU" : "Australia", "NZ" : "New Zealand", "UK" : "United Kingdom", "ZA" : "South Africa", "US" : "United States"]
</code>```

I then just want to grab the country shortcode and loop through it to build a new array as per below...

```<code>func getCallCentreNumbers(){

    var countrykeys = Array(callCountries.keys)

    API.getJudeContactNumbers({response in

            self.judeCallCentreNumberDict =  [
                countrykeys : (response.value(forKey: countrykeys) as! String),
        ]

    })

}
</code>```

The initial line of code without the array values being inserted was:

```<code>self.judeCallCentreNumberDict =  [
                "ZM" : (response.value(forKey: "ZM") as! String),
        ]
</code>```

I want to replace the "ZM"s with the countrykeys variable but cannot work this one out. (Sorry I am still quite a newbie). Can anyone point me in the right direction?

答:
It looks like you want to look at each number in the response and build a dictionary of the numbers for each country code. You were close to this implementation, but you need to iterate over the keys in countrykeys, looking at the value for each key and assigning that value to the corresponding country code in judeCallCentreNumberDict.

```<code>func getCallCentreNumbers() {
    var countrykeys = Array(callCountries.keys)

    API.getJudeContactNumbers { response in
        for countryKey in countryKeys {
            let number = (response.value(forKey: countrykeys) as! String)
            self.judeCallCentreNumberDict[countryKey] = number
        }
    }
}
</code>```

The above code will solve the compiler problem, but it seems like this code is unnecessary for what you want to do (at least in the context given). If all you want to do is make that API call and get a dictionary of contact numbers, it seems like that API is handling that sufficiently for you. It seems like the API is returning a dictionary of phone numbers for you already. So the code could be cut down to something like the code below. (Unless the response is returning JSON, in which case these implementations will fail)

```<code>func getCallCentreNumbers() {
    API.getJudeContactNumbers { response in
        self.judeCallCentreNumberDict = response
    }
}
</code>```

Body:
I have a array (from a global constants file) which I am trying to use in an API call to make another dictionary array. The initial array is:

let callCountries = ["AU" : "Australia", "NZ" : "New Zealand", "UK" : "United Kingdom", "ZA" : "South Africa", "US" : "United States"]

I then just want to grab the country shortcode and loop through it to build a new array as per below...

func getCallCentreNumbers(){

    var countrykeys = Array(callCountries.keys)

    API.getJudeContactNumbers({response in

            self.judeCallCentreNumberDict =  [
                countrykeys : (response.value(forKey: countrykeys) as! String),
        ]

    })

}

The initial line of code without the array values being inserted was:

self.judeCallCentreNumberDict =  [
                "ZM" : (response.value(forKey: "ZM") as! String),
        ]

I want to replace the "ZM"s with the countrykeys variable but cannot work this one out. (Sorry I am still quite a newbie). Can anyone point me in the right direction?

Body:
It looks like you want to look at each number in the response and build a dictionary of the numbers for each country code. You were close to this implementation, but you need to iterate over the keys in countrykeys, looking at the value for each key and assigning that value to the corresponding country code in judeCallCentreNumberDict.

func getCallCentreNumbers() {
    var countrykeys = Array(callCountries.keys)

    API.getJudeContactNumbers { response in
        for countryKey in countryKeys {
            let number = (response.value(forKey: countrykeys) as! String)
            self.judeCallCentreNumberDict[countryKey] = number
        }
    }
}

The above code will solve the compiler problem, but it seems like this code is unnecessary for what you want to do (at least in the context given). If all you want to do is make that API call and get a dictionary of contact numbers, it seems like that API is handling that sufficiently for you. It seems like the API is returning a dictionary of phone numbers for you already. So the code could be cut down to something like the code below. (Unless the response is returning JSON, in which case these implementations will fail)

func getCallCentreNumbers() {
    API.getJudeContactNumbers { response in
        self.judeCallCentreNumberDict = response
    }
}


答:
If you iterate over a list you obtain the values of the list, not the indices.

You can use range(len(..)) to obtain the indices. Furthermore the result is result, not result[x] to store it into the avg_val:

```<code>avg_val = []
for x in <b>range(len(threads))</b>:
    result = dsk_indpt_PI[x]/threads[x]
    avg_val.append(result)</code>```

But a more Pythonic version will use zip:

```<code>avg_val = []
for <b>a,b</b> in <b>zip(dsk_indpt_PI, threads)</b>:
    result = a/b
    avg_val.append(resul)</code>```

and we can turn this in list comprehension:

```<code>avg_val = [a/b for a,b in zip(dsk_indpt_PI, threads)]</code>```

List comprehension is a way to create a list in a more elegant way by writing generator syntax between square brackets.

Title: Iterate through a list, divide values, store in new list

Body:
If you iterate over a list you obtain the values of the list, not the indices.

You can use range(len(..)) to obtain the indices. Furthermore the result is result, not result[x] to store it into the avg_val:

avg_val = []
for x in range(len(threads)):
    result = dsk_indpt_PI[x]/threads[x]
    avg_val.append(result)

But a more Pythonic version will use zip:

avg_val = []
for a,b in zip(dsk_indpt_PI, threads):
    result = a/b
    avg_val.append(resul)

and we can turn this in list comprehension:

avg_val = [a/b for a,b in zip(dsk_indpt_PI, threads)]

List comprehension is a way to create a list in a more elegant way by writing generator syntax between square brackets.


问:
IE structural problems
I have just made a very simple static side via wordpress. However, I made the theme from scratch with html and css. It looks perfect and exactly how I want in FFox,Chrome,Safari etc...but upon inspection in IE 6,7,8 is is not right.

Click {here} to see the site and if you don't have IE... Here is a screen shot of how it is rendering in there.

Any idea on what this may be or an idea on how to fix it would be greatly appreciated. I can't find any syntax errors in my css and the html seems right

Thanks

答:
Well for one, not sure how new you are to CSS/HTML development, but this is NEVER a surprise that you create content in one browser only to have IE puke and choke and display something differently.  Its one of the crutches that web designers / developers have to carry when making projects.

You make it right, then you mod a stylesheet to be IE approved.

You need to use conditional comments to attach those IE only sheets, and you might even have to do it for IE6 / 7 / 8 seperately, depending on what you did and how it breaks the look.

http://www.quirksmode.org/css/condcom.html

Example of this usage in the :

```<code><!--[if IE 6]>
<link rel="stylesheet" href="ie6-fixes.css" />
<![endif]-->
</code>```

You would of course have your 'default' style sheet BEFORE the ie one, and the ie.css would overwrite the initially defined styles.

Only correct way to go about it.

Title: IE structural problems

Body:
Well for one, not sure how new you are to CSS/HTML development, but this is NEVER a surprise that you create content in one browser only to have IE puke and choke and display something differently.  Its one of the crutches that web designers / developers have to carry when making projects.

You make it right, then you mod a stylesheet to be IE approved.

You need to use conditional comments to attach those IE only sheets, and you might even have to do it for IE6 / 7 / 8 seperately, depending on what you did and how it breaks the look.

http://www.quirksmode.org/css/condcom.html

Example of this usage in the <head>:

<!--[if IE 6]>
<link rel="stylesheet" href="ie6-fixes.css" />
<![endif]-->

You would of course have your 'default' style sheet BEFORE the ie one, and the ie.css would overwrite the initially defined styles.

Only correct way to go about it.


问:
Ruby on Rails ActiveRecord size on association returns twice the amount of count after duplicating a model
After copying an active record object my new objects association.size returns double the amount of how many are actually in the database. I've seen that size trys to load a cached version and count actually executes a query but I don't want to always execute an SQL query just to show the amount.
My (relevant) code looks like this:

```<code>class Model1 < ActiveRecord::Base
def copy_model
 new_model = self.dup
 new_model.name = "Copy of #{name}"
 new_model.association = association.map{|a| a.dup}
 new_model.save
 new_model
end
</code>```

after this calling .size on new_model.association returns twice the amount of .count

答:
Don't do a map. Try the following:</p>

```<code>association.each do |a|
  new_model.association << a.dup
end
</code>```

Body:
After copying an active record object my new objects association.size returns double the amount of how many are actually in the database. I've seen that size trys to load a cached version and count actually executes a query but I don't want to always execute an SQL query just to show the amount.
My (relevant) code looks like this:

class Model1 < ActiveRecord::Base
def copy_model
 new_model = self.dup
 new_model.name = "Copy of #{name}"
 new_model.association = association.map{|a| a.dup}
 new_model.save
 new_model
end

after this calling .size on new_model.association returns twice the amount of .count

Body:
Don't do a map. Try the following:

association.each do |a|
  new_model.association << a.dup
end


问:
SQL Server - Get the Latest Date With Grouping
I am running a problem with SQL Server query that I couldn't figure out how to get it works correctly. I try to get the MAX date based on the Category grouped. I know it sounds confused, so let me explain what the result I want.

Let's say I have this table:

```<code>Table1
Category    Value   UpdatedDateTime
Cat1        5       2017-11-12 10:46
Cat1        2       2017-11-13 11:46
Cat1        4       2017-11-13 10:46
Cat2        5       2017-11-12 10:46
Cat2        7       2017-11-12 11:46
Cat2        3       2017-11-13 09:46
Cat3        1       2017-11-12 10:46
Cat3        2       2017-11-12 11:46
Cat3        7       2017-11-13 11:46
Cat3        8       2017-11-13 10:46
Cat3        3       2017-11-10 10:46
Cat4        4       2017-11-13 10:46
Cat4        4       2017-11-12 10:46
</code>```

I want the UpdatedDateTime in the result to pick the latest date by the Category grouping like this:

```<code>Category    Value   UpdatedDateTime
Cat1        5       2017-11-13 11:46
Cat1        2       2017-11-13 11:46
Cat1        4       2017-11-13 11:46
Cat2        5       2017-11-13 09:46
Cat2        7       2017-11-13 09:46
Cat2        3       2017-11-13 09:46
Cat3        1       2017-11-13 11:46
Cat3        2       2017-11-13 11:46
Cat3        7       2017-11-13 11:46
Cat3        8       2017-11-13 11:46
Cat3        3       2017-11-13 11:46
Cat4        4       2017-11-13 10:46
Cat4        4       2017-11-13 10:46
</code>```

I tried this query, but of course it doesn't work because I was looking for the Max(UpdatedDate) for the entire table, not by Category.  Then I got stuck.

```<code>With cte AS
(
    Select Category, Value, UpdatedDateTime FROM Table1
)
Select Category, Sum(Value)
, (Select Top 1 Max(UpdatedDateTime) FORM cte) AS UpdatedDateTime
FROM cte
Group By Category
</code>```

Please help, thanks in advance.

Body:
I am running a problem with SQL Server query that I couldn't figure out how to get it works correctly. I try to get the MAX date based on the Category grouped. I know it sounds confused, so let me explain what the result I want.

Let's say I have this table:

Table1
Category    Value   UpdatedDateTime
Cat1        5       2017-11-12 10:46
Cat1        2       2017-11-13 11:46
Cat1        4       2017-11-13 10:46
Cat2        5       2017-11-12 10:46
Cat2        7       2017-11-12 11:46
Cat2        3       2017-11-13 09:46
Cat3        1       2017-11-12 10:46
Cat3        2       2017-11-12 11:46
Cat3        7       2017-11-13 11:46
Cat3        8       2017-11-13 10:46
Cat3        3       2017-11-10 10:46
Cat4        4       2017-11-13 10:46
Cat4        4       2017-11-12 10:46

I want the UpdatedDateTime in the result to pick the latest date by the Category grouping like this:

Category    Value   UpdatedDateTime
Cat1        5       2017-11-13 11:46
Cat1        2       2017-11-13 11:46
Cat1        4       2017-11-13 11:46
Cat2        5       2017-11-13 09:46
Cat2        7       2017-11-13 09:46
Cat2        3       2017-11-13 09:46
Cat3        1       2017-11-13 11:46
Cat3        2       2017-11-13 11:46
Cat3        7       2017-11-13 11:46
Cat3        8       2017-11-13 11:46
Cat3        3       2017-11-13 11:46
Cat4        4       2017-11-13 10:46
Cat4        4       2017-11-13 10:46

I tried this query, but of course it doesn't work because I was looking for the Max(UpdatedDate) for the entire table, not by Category.  Then I got stuck.

With cte AS
(
    Select Category, Value, UpdatedDateTime FROM Table1
)
Select Category, Sum(Value)
, (Select Top 1 Max(UpdatedDateTime) FORM cte) AS UpdatedDateTime
FROM cte
Group By Category

Please help, thanks in advance.

Body:
You do can this with a partitioned window function easily.

declare @Something table
(
    Category varchar(10)
    , MyValue int
    , UpdatedDateTime datetime
)

insert @Something values
('Cat1', 5, '2017-11-12 10:46')
, ('Cat1', 2, '2017-11-13 11:46')
, ('Cat1', 4, '2017-11-13 10:46')
, ('Cat2', 5, '2017-11-12 10:46')
, ('Cat2', 7, '2017-11-12 11:46')
, ('Cat2', 3, '2017-11-13 09:46')
, ('Cat3', 1, '2017-11-12 10:46')
, ('Cat3', 2, '2017-11-12 11:46')
, ('Cat3', 7, '2017-11-13 11:46')
, ('Cat3', 8, '2017-11-13 10:46')
, ('Cat3', 3, '2017-11-10 10:46')
, ('Cat4', 4, '2017-11-13 10:46')
, ('Cat4', 4, '2017-11-12 10:46')

select Category
    , MyValue
    , UpdatedDateTime  = MAX(UpdatedDateTime) over(partition by Category)
from @Something


问:
Is it possible to avoid the for-loop to compute matrix entries?
I have to use a nested for-loop to compute the entries of a Eigen::MatrixXd type matrix output columnwise. Here input[0], input[1] and input[2] are defined as Eigen::ArrayXXd in order to use the elementwise oprerations. This part seems to be the bottleneck for my code. Can anyone help me to accelerate this loop? Thanks! </p>

```<code> for (int i = 0; i < r; i++) {
    for (int j = 0; j < r; j++) {
      for (int k = 0; k < r; k++) {
        output.col(i * (r * r) + j * r + k) =
            input[0].col(i) * input[1].col(j) * input[2].col(k);
      }
    }
  }
</code>```

答:
When thinking about optimizing code of a for loop, it helps to think, "Are there redundant calculations that I can eliminate?"

Notice how in the inner most loop, only k is changing. You should move all possible calculations that don't involve k out of that loop:

```<code>for (int i = 0; i < r; i++) {
  int temp1 = i * (r * r);
  for (int j = 0; j < r; j++) {
    int temp2 = j * r;
    for (int k = 0; k < r; k++) {
      output.col(temp1 + temp2 + k) =
          input[0].col(i) * input[1].col(j) * input[2].col(k);
    }
  }
}
</code>```

Notice how i * (r * r) is being calculated over and over, but the answer is always the same! You only need to recalculate this when i increments. The same goes for j * r.

Hopefully this helps!

Body:
I have to use a nested for-loop to compute the entries of a Eigen::MatrixXd type matrix output columnwise. Here input[0], input[1] and input[2] are defined as Eigen::ArrayXXd in order to use the elementwise oprerations. This part seems to be the bottleneck for my code. Can anyone help me to accelerate this loop? Thanks!

 for (int i = 0; i < r; i++) {
    for (int j = 0; j < r; j++) {
      for (int k = 0; k < r; k++) {
        output.col(i * (r * r) + j * r + k) =
            input[0].col(i) * input[1].col(j) * input[2].col(k);
      }
    }
  }

Body:
When thinking about optimizing code of a for loop, it helps to think, "Are there redundant calculations that I can eliminate?"

Notice how in the inner most loop, only k is changing. You should move all possible calculations that don't involve k out of that loop:

for (int i = 0; i < r; i++) {
  int temp1 = i * (r * r);
  for (int j = 0; j < r; j++) {
    int temp2 = j * r;
    for (int k = 0; k < r; k++) {
      output.col(temp1 + temp2 + k) =
          input[0].col(i) * input[1].col(j) * input[2].col(k);
    }
  }
}

Notice how i * (r * r) is being calculated over and over, but the answer is always the same! You only need to recalculate this when i increments. The same goes for j * r.

Hopefully this helps!


问:
SQL: Extract 5 different Address into one list
I am new to SQL coding and the office requested a printout of data to help them with printing mailing labels.

The database has up to 5 different address's for a student cnt1, cnt2, etc.  There is a flag for each cnt to determine if the cnt's should receive mail; cntx_recvmail=1

Each student can have up to 5 different address labels and it should be grouped by the student ID number.  Student 12345 if cnt1_flag=1, or cnt1_flag=2, etc. then
cnt1 name, street, city, state, zip
cnt2 name, street, city state, zip
ect. to cnt5

I need to pull out all cnt's who should receive mail in a list that includes the cnt's name, street, state, zip if cnt_recvmail=1. Any assistance would be appreciated.

This is an example of the code which works for cnt1:

```<code>SELECT s.first_name, s.last_name,
ps_customfields.getcf('students',id,'cnt1_fname'),
ps_customfields.getcf('students',id,'cnt1_lname'),
ps_customfields.getcf('students',id,'cnt1_street'),
ps_customfields.getcf('students',id,'cnt1_city'),
ps_customfields.getcf('students',id,'cnt1_state'),
ps_customfields.getcf('students',id,'cnt1_zip')
FROM students s
WHERE s.enroll_status=0
AND s.grade_level =9
AND ps_customfields.getcf('students',id,'cnt1_recvmail')=1;
</code>```

The output should group by student ID #12345
cnt1name, cnt1street, cnt1state, cnt1zip
cnt2name, cnt2street, cnt2state, cnt2zip
ect to cnt5

答:
Okay, here's a very simple answer. I should warn you, there are scenarios where this won't work, which is why people asked for more details in your question. For example, if your ps_customfields.getcf() function returns an error when it can't find any results.

It wasn't really clear from your question, but I think you want to show an address for a student (e.g. cnt4) only when the recvmail flag =1 (e.g. cnt4_recvmail=1). If this isn't what you want, please clarify and I'll update this answer.

EDIT: Oh! Well, if you want one address per row, that's actually a much simpler query. Try this out.

```<code>SELECT s.id, s.first_name, s.last_name,
    cnt.x,
    ps_customfields.getcf('students',id,'cnt' || cnt.x || '_fname') cnt_fname,
    ps_customfields.getcf('students',id,'cnt' || cnt.x || '_lname') cnt_lname,
    ps_customfields.getcf('students',id,'cnt' || cnt.x || '_street') cnt_street,
    ps_customfields.getcf('students',id,'cnt' || cnt.x || '_city') cnt_city,
    ps_customfields.getcf('students',id,'cnt' || cnt.x || '_state') cnt_state,
    ps_customfields.getcf('students',id,'cnt' || cnt.x || '_zip') cnt_zip
FROM students s
cross join (select level as x from dual connect by level <= 5) cnt
WHERE s.enroll_status=0
AND s.grade_level =9
AND ps_customfields.getcf('students',id,'cnt' || cnt.x || '_recvmail')=1
order by 1
;
</code>```

Also, it helps us a lot when you can make up an example - let's say one fake student name and 3 fake addresses, and then show us what that would look like in your results, like:

```<code>cnt1_recvmail=1, cnt2_recvmail=0, etc.

id   fn1 ln1   street1       city1      state1 zip1  fn2    ln2    street2  city2  state2 ... etc
S001 Bob Smith 1057 Main St. Washington DC     87234 (null) (null) (null)  (null) (null) ... etc
</code>```

Body:
I am new to SQL coding and the office requested a printout of data to help them with printing mailing labels.

The database has up to 5 different address's for a student cnt1, cnt2, etc.  There is a flag for each cnt to determine if the cnt's should receive mail; cntx_recvmail=1

Each student can have up to 5 different address labels and it should be grouped by the student ID number.  Student 12345 if cnt1_flag=1, or cnt1_flag=2, etc. then
cnt1 name, street, city, state, zip
cnt2 name, street, city state, zip
ect. to cnt5

I need to pull out all cnt's who should receive mail in a list that includes the cnt's name, street, state, zip if cnt_recvmail=1. Any assistance would be appreciated.

This is an example of the code which works for cnt1:

SELECT s.first_name, s.last_name,
ps_customfields.getcf('students',id,'cnt1_fname'),
ps_customfields.getcf('students',id,'cnt1_lname'),
ps_customfields.getcf('students',id,'cnt1_street'),
ps_customfields.getcf('students',id,'cnt1_city'),
ps_customfields.getcf('students',id,'cnt1_state'),
ps_customfields.getcf('students',id,'cnt1_zip')
FROM students s
WHERE s.enroll_status=0
AND s.grade_level =9
AND ps_customfields.getcf('students',id,'cnt1_recvmail')=1;

The output should group by student ID #12345
cnt1name, cnt1street, cnt1state, cnt1zip
cnt2name, cnt2street, cnt2state, cnt2zip
ect to cnt5

Body:
Okay, here's a very simple answer. I should warn you, there are scenarios where this won't work, which is why people asked for more details in your question. For example, if your ps_customfields.getcf() function returns an error when it can't find any results.

It wasn't really clear from your question, but I think you want to show an address for a student (e.g. cnt4) only when the recvmail flag =1 (e.g. cnt4_recvmail=1). If this isn't what you want, please clarify and I'll update this answer.

EDIT: Oh! Well, if you want one address per row, that's actually a much simpler query. Try this out.

SELECT s.id, s.first_name, s.last_name,
    cnt.x,
    ps_customfields.getcf('students',id,'cnt' || cnt.x || '_fname') cnt_fname,
    ps_customfields.getcf('students',id,'cnt' || cnt.x || '_lname') cnt_lname,
    ps_customfields.getcf('students',id,'cnt' || cnt.x || '_street') cnt_street,
    ps_customfields.getcf('students',id,'cnt' || cnt.x || '_city') cnt_city,
    ps_customfields.getcf('students',id,'cnt' || cnt.x || '_state') cnt_state,
    ps_customfields.getcf('students',id,'cnt' || cnt.x || '_zip') cnt_zip
FROM students s
cross join (select level as x from dual connect by level <= 5) cnt
WHERE s.enroll_status=0
AND s.grade_level =9
AND ps_customfields.getcf('students',id,'cnt' || cnt.x || '_recvmail')=1
order by 1
;

Also, it helps us a lot when you can make up an example - let's say one fake student name and 3 fake addresses, and then show us what that would look like in your results, like:

cnt1_recvmail=1, cnt2_recvmail=0, etc.

id   fn1 ln1   street1       city1      state1 zip1  fn2    ln2    street2  city2  state2 ... etc
S001 Bob Smith 1057 Main St. Washington DC     87234 (null) (null) (null)  (null) (null) ... etc


问:
How to drop a PostgreSQL database if there are active connections to it?
I need to write a script that will drop a PostgreSQL database. There may be a lot of connections to it, but the script should ignore that.

The standard DROP DATABASE db_name query doesn't work when there are open connections.

How can I solve the problem?

答:
Easy Peasy.

I just restart the service in Ubuntu to disconnect connected clients.

```<code>sudo service postgresql stop
sudo service postgresql start

psql
DROP DATABASE DB_NAME;
</code>```

Body:
Easy Peasy.

I just restart the service in Ubuntu to disconnect connected clients.

sudo service postgresql stop
sudo service postgresql start

psql
DROP DATABASE DB_NAME;


问:
How to get CryptoJS result as hash_hmac PHP (SHA1)
Try to genegarate HMAC on JS with CryptoJS lib from UTF8 string with UTF8 secret. Like PHP hash_hmac('sha1','...','...',true);

PHP :

```<code>$buf = ' accept';
$bufferedSecret = '��xDx�����4�J�?)#';

hash_hmac('sha1', $buf, $bufferedSecret, false);
/* d301cae776ed8c5d46ac93bd7441b01af4d1b888 */
hash_hmac('sha1', $buf, $bufferedSecret, true);
/* ���v�]F���tA��Ѹ� */
</code>```

JavaScript :

```<code>var buf = ' accept';
var bufferedSecret = '��xDx�����4�J�?)#';

CryptoJS.HmacSHA1(buf, bufferedSecret).toString();
/* d301cae776ed8c5d46ac93bd7441b01af4d1b888 */
var forBase64 = CryptoJS.HmacSHA1(buf, bufferedSecret);
CryptoJS.enc.Base64.stringify(forBase64);
/* 0wHK53btjF1GrJO9dEGwGvTRuIg= */
</code>```

How get same HMAC(SHA1) UTF8 value on JS?

答:
I was found a way for get UTF-8 RAW.

Used "convertWordArrayToUint8Array()" from here:
https://gist.github.com/getify/7325764
and just decode it.

```<code>var wordArr = CryptoJS.HmacSHA1(buf, bufferedSecret);
var utf8Arr = convertWordArrayToUint8Array(wordArr);
var string = new TextDecoder('utf-8').decode(utf8Arr);
</code>```

Body:
Try to genegarate HMAC on JS with CryptoJS lib from UTF8 string with UTF8 secret. Like PHP hash_hmac('sha1','...','...',true);

PHP :

$buf = ' accept';
$bufferedSecret = '��xDx�����4�J�?)#';

hash_hmac('sha1', $buf, $bufferedSecret, false);
/* d301cae776ed8c5d46ac93bd7441b01af4d1b888 */
hash_hmac('sha1', $buf, $bufferedSecret, true);
/* ���v�]F���tA��Ѹ� */

JavaScript :

var buf = ' accept';
var bufferedSecret = '��xDx�����4�J�?)#';

CryptoJS.HmacSHA1(buf, bufferedSecret).toString();
/* d301cae776ed8c5d46ac93bd7441b01af4d1b888 */
var forBase64 = CryptoJS.HmacSHA1(buf, bufferedSecret);
CryptoJS.enc.Base64.stringify(forBase64);
/* 0wHK53btjF1GrJO9dEGwGvTRuIg= */

How get same HMAC(SHA1) UTF8 value on JS?

Body:
I was found a way for get UTF-8 RAW.

Used "convertWordArrayToUint8Array()" from here:
https://gist.github.com/getify/7325764
and just decode it.

var wordArr = CryptoJS.HmacSHA1(buf, bufferedSecret);
var utf8Arr = convertWordArrayToUint8Array(wordArr);
var string = new TextDecoder('utf-8').decode(utf8Arr);


答: If you are iterating over a list with a regular for loop, you will get the values, and not the indices. If you want the indices, you could use for i in range(len(myList)): which would give every index i in your list. Alternatively, you could use for index, value in enumerate(myList) if you want both the index and the value.

Body:
In the code I have series of lists, each one containing the same number of entries. What I want to do now is iterate through the list and divide one list index by the other.

threads = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
dsk_indpt_PI = [99, 197, 295, 387, 391, 406, 407, 416, 424, 426, 425, 439]

avg_val = []
for x in threads:
    result = dsk_indpt_PI[x]/threads[x]
    avg_val.append(result[x])

I am unsure if the above method works, previous methods I ran into the issue where it could not do division between type int and type list. Would the above example work better? If not, what should be changed to have it function as desired? Thank you.


问:
Google Analytics reports 10 times lesser sessions than hits in server logs
Let's say I've a page mysite.com/mypage

Landing Page Report in GA for this URL for a specified duration, gives me a number of sessions - say 50.

For the same duration, I checked Apache's access.log, and did a grep "GET /mypage, and I've got around 10x more hits -- say 500.

How can we have a 10x anomaly between GA & Server Logs? Where did the hits go?

This anomaly is present for other durations too. I've compared various durations.

Before someone tells the standard reasons for this, let me point out that:

A difference of 2x or 3x is understandable, but not 10x.

No, this is not Bot Traffic. I extracted all unique IPs from the logs, and the IPs are 99% unique. So the traffic is all coming from different IPs.

I also analyzed user agents, and they all look real (with various models of phones like iPhone, Samsung etc.)

GA also says that this report is based on 100% data (sampling ruled out).

As I pointed out, I'm only counting the GET requests to the /mypage. That is, I'm not counting asset downloads, favicon hits etc. etc.

I performed another test. I took all IPs, then made them unique, then for each IP I analyzed how many hits came from that IP. I found from 84% of the IPs, there's no second request. They made only 1 request.

I've read Anamoly between google analytics and server hits and have taken care of everything given in the accepted answer.

What could it be? Any clues on how to debug this? The traffic is coming from Paid Facebook Ads.

答:
You are comparing sessions to pageviews, which is not an apples-to-apples comparison.

A session indicates a period of continuous hits (e.g. pageviews, events) before 30 minutes of inactivity. Therefore 1 session could consist of many pageviews.

When you are doing a search for GET /mypage in your logs, you are looking at how many times that page was requested from your servers. This is equivalent to the pageview metric in Google Analytics.

I recommend you compare pageviews for /mypage against GET /mypage entries in your logs. This should give you a much closer comparison.

Keep in mind that it will be rare to get a 100% match due to scenarios where the Google Analytics tag may not fire on the user's browser. Examples of scenarios include:

GA code doesn't load before user navigates away from the page

Ad blockers may prevent the tag from firing

Do not track settings may prevent the tag from firing


问:
auto scroll to bottom directive doesn't work in angular 2
I am creating a chat application where I need to implement auto-scroll to bottom of the text messages. div should be done on the initial load and reload of the page. I created a custom directive to implement this. However this doesn't seems to work.

directive:

```<code>import { Directive,ElementRef,AfterViewInit} from '@angular/core';

@Directive({ selector: '[scrollToBottom]' })
export class ScrollToBottomDirective implements AfterViewInit {
    constructor(private element:ElementRef) {
        console.log('scroll', this.element);
    }
    ngAfterViewInit(){
        this.scrollToBottom();
    }
    scrollToBottom(){
        if(this.element){
            (this.element as any).nativeElement.scrollTop =(this.element as any).nativeElement.scrollHeight;
            console.log('scroll', (this.element as any).nativeElement.scrollTop)
            console.log('scrollHeight', (this.element as any).nativeElement.scrollHeight)
        }
    }
}
</code>```

Where I am doing wrong?

答:
Also, if you need to scroll bottom once, I recommend next solution:</p>

```<code>import { Directive, ElementRef, AfterViewChecked, HostListener } from '@angular/core';

@Directive({
  selector: '[scrollToBottom]'
})
export class ScrollToBottomDirective implements AfterViewChecked {
  isActive = true;

  @HostListener('scroll') onFrameScroll() {
    this.isActive = false;
  }

  constructor(private element: ElementRef) {}

  ngAfterViewChecked() {
    this.scrollToBottom();
  }

  scrollToBottom() {
    if (this.element && this.isActive) {
      this.element.nativeElement.scrollTop = this.element.nativeElement.scrollHeight;
    }
  }
}
</code>```

Body:
I am creating a chat application where I need to implement auto-scroll to bottom of the text messages. div should be done on the initial load and reload of the page. I created a custom directive to implement this. However this doesn't seems to work.

directive:

import { Directive,ElementRef,AfterViewInit} from '@angular/core';

@Directive({ selector: '[scrollToBottom]' })
export class ScrollToBottomDirective implements AfterViewInit {
    constructor(private element:ElementRef) {
        console.log('scroll', this.element);
    }
    ngAfterViewInit(){
        this.scrollToBottom();
    }
    scrollToBottom(){
        if(this.element){
            (this.element as any).nativeElement.scrollTop =(this.element as any).nativeElement.scrollHeight;
            console.log('scroll', (this.element as any).nativeElement.scrollTop)
            console.log('scrollHeight', (this.element as any).nativeElement.scrollHeight)
        }
    }
}

Where I am doing wrong?

Body:
Also, if you need to scroll bottom once, I recommend next solution:

import { Directive, ElementRef, AfterViewChecked, HostListener } from '@angular/core';

@Directive({
  selector: '[scrollToBottom]'
})
export class ScrollToBottomDirective implements AfterViewChecked {
  isActive = true;

  @HostListener('scroll') onFrameScroll() {
    this.isActive = false;
  }

  constructor(private element: ElementRef) {}

  ngAfterViewChecked() {
    this.scrollToBottom();
  }

  scrollToBottom() {
    if (this.element && this.isActive) {
      this.element.nativeElement.scrollTop = this.element.nativeElement.scrollHeight;
    }
  }
}


问:
How do I update or sync a forked repository on GitHub?
I forked a project, made changes, and created a pull request which was accepted. New commits were later added to the repository. How do I get those commits into my fork?</p>

答:
Android Studio now has learned to work with GitHub fork repositories (you don't even have to add "upstream" remote repository by console command).

Open menu VCS → Git

And pay attention to the two last popup menu items:

Rebase my GitHub fork

Create Pull Request

Try them. I use the first one to synchronize my local repository. Anyway the branches from the parent remote repository ("upstream") will be accessible in Android Studio after you click "Rebase my GitHub fork", and you will be able to operate with them easily.

(I use Android Studio 3.0 with "Git integration" and "GitHub" plugins.)


问:
convert WPF WebBrowser to WinForms
I am trying to convert a WPF WebBrowser control to a WinForms WebBrowser control using this code:

```<code>System.Windows.Forms.WebBrowser wb = myWebBrowser as System.Windows.Forms.WebBrowser();
</code>```

I am getting this error:

"Cannot convert type 'System.Windows.Controls.WebBrowser' to 'System.Windows.Forms.WebBrowser' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion"

Any help would be appreciated.

Thanks!

答: wpf and winforms controls are very different (apples and oranges) and can't be converted between each other.</p>

Title: convert WPF WebBrowser to WinForms

Body:
I am trying to convert a WPF WebBrowser control to a WinForms WebBrowser control using this code:

System.Windows.Forms.WebBrowser wb = myWebBrowser as System.Windows.Forms.WebBrowser();

I am getting this error:

"Cannot convert type 'System.Windows.Controls.WebBrowser' to 'System.Windows.Forms.WebBrowser' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion"

Any help would be appreciated.

Thanks!