问:
Invert an array of booleans in JavaScript
I am trying to invert the values of a string of boolean values so that instead  of

inverted([true, false, true, false, true])

it is  [false, true, false, true, false]

So far I have come up with this:

```<code>function inverted(bools) {
    var inversion = [];
    var string= [];
    while(!bools) {
      string.push(bools);
    }
    return inversion;
}
</code>```

But my code is not working, any and all help will be much appreciated!

答:
You need to split up bools with bools.split(). Then you can check and invert them. You also are not putting anything in inversion[] prior to returning it. Something like the below should work:</p>

```<code>function inverted(bools) {
var inversion = [];
var string= bools.split(",");
for(var i=0; i<string.length(); i++) {
  inversion.push(string[i]);
}

return inversion;

}
</code>```

Body:
I am trying to invert the values of a string of boolean values so that instead  of

inverted([true, false, true, false, true])

it is  [false, true, false, true, false]

So far I have come up with this:

function inverted(bools) {
    var inversion = [];
    var string= [];
    while(!bools) {
      string.push(bools);
    }
    return inversion;
}

But my code is not working, any and all help will be much appreciated!

Body:
You need to split up bools with bools.split(). Then you can check and invert them. You also are not putting anything in inversion[] prior to returning it. Something like the below should work:

function inverted(bools) {
var inversion = [];
var string= bools.split(",");
for(var i=0; i<string.length(); i++) {
  inversion.push(string[i]);
}

return inversion;

}


来源: stackexchange

问:
Get HTTP status 404 for /j_spring_security_check with GWT
I'm attempting to get Spring Security working, and failing utterly.  No matter what I try, I can't get j_spring_security_check to be valid.

Error:

HTTP Status 404 - /j_spring_security_check

  type Status report

  message /j_spring_security_check

  description The requested resource is not available.

Login.html file:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>My App</title>
    <link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico">

    <form method = "post" action="/j_spring_security_check">
      Username:
      <input type = "text" name = "username" />

      Password:
      <input type = "password" name = "password" />

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

```

<p><code>web.xml</code>:</p>

<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /META-INF/application*.xml
        </param-value>
    </context-param>

    <!-- Creates the Spring Container -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  <!-- Servlets -->
  <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>com.me.portal.server.MyPortalServiceImpl</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/MyPortal/MyPortal</url-pattern>
  </servlet-mapping>

  <!-- Default page to serve -->
  <welcome-file-list>
    <welcome-file>Login.html</welcome-file>
  </welcome-file-list>

</web-app>
</code>```

application.security.xml:

<?xml version = "1.0" encoding = "UTF-8"?>
<beans:beans xmlns = "http://www.springframework.org/schema/security"
             xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans = "http://www.springframework.org/schema/beans"
             xmlns:util = "http://www.springframework.org/schema/util"
             xsi:schemaLocation = "http://www.springframework.org/schema/beans
                                 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                                 http://www.springframework.org/schema/util
                                 http://www.springframework.org/schema/util/spring-util-4.3.xsd
                                 http://www.springframework.org/schema/security
                                 http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http auto-config = 'true' use-expressions = "false" entry-point-ref = "customAuthenticationEntryPoint">
        <intercept-url pattern = "/j_spring_security_check" access = "IS_AUTHENTICATED_ANONYMOUSLY"/>
        <intercept-url pattern = "/login" access = "IS_AUTHENTICATED_ANONYMOUSLY"/>
        <intercept-url pattern = "/Login.html" access = "IS_AUTHENTICATED_ANONYMOUSLY" />
        <intercept-url pattern = "/img/favicon.ico" access = "IS_AUTHENTICATED_ANONYMOUSLY" />
        <intercept-url pattern = "/**" access = "IS_AUTHENTICATED_FULLY" />
        <logout logout-success-url = "/Login.html" />
        <form-login login-page = "/Login.html" default-target-url = "/index.gwt.html" always-use-default-target = "true"
                    login-processing-url = "/j_spring_security_check" username-parameter = "username" password-parameter = "password"
                    authentication-success-handler-ref = "customAuthenticationSuccessHandler"
                    authentication-failure-handler-ref="customAuthenticationFailureHandler"/>

        <session-management invalid-session-url = "/Login.html"
                            session-authentication-error-url = "/Login.html"
                            session-fixation-protection = "newSession">
            <concurrency-control max-sessions = "1" error-if-maximum-exceeded = "false" />
        </session-management>
    </http>

    <ldap-server {Our settings} />

    <authentication-manager alias = "authenticationManager">
        <ldap-authentication-provider
                {Our LDAP Info}
        </ldap-authentication-provider>
    </authentication-manager>

    <beans:bean id = "customAuthenticationEntryPoint" class = "com.me.portal.server.security.CustomAuthenticationEntryPoint"/>

    <beans:bean id = "customAuthenticationSuccessHandler" class = "com.me.portal.server.security.CustomAuthenticationSuccessHandler"/>

    <beans:bean id = "customAuthenticationFailureHandler" class = "com.me.portal.server.security.CustomAuthenticationFailureHandler"/>

</beans:beans>
```

<p>Spring JARs used:</p>

```spring-aop-4.3.2.RELEASE.jar
spring-beans-4.3.2.RELEASE.jar
spring-context-4.3.2.RELEASE.jar
spring-core-4.3.2.RELEASE.jar
spring-expression-4.3.2.RELEASE.jar
spring-ldap-core-2.3.1.RELEASE.jar
spring-security-config-3.2.7.RELEASE.jar
spring-security-core-3.2.7.RELEASE.jar
spring-security-ldap-3.2.7.RELEASE.jar
spring-security-web-3.2.7.RELEASE.jar
spring-tx-4.3.2.RELEASE.jar
spring-web-4.3.2.RELEASE.jar
```

<p>As requested, Headers:
<img src="https://i.stack.imgur.com/25pax.png" alt="Headers for the failure"></p>

<p>Response:</p>

```<!DOCTYPE html>
<title>Apache Tomcat/8.0.22 - Error report</title>

HTTP Status 404 - /j_spring_security_check

type Status report

message /j_spring_security_check

description The requested resource is not available.

Apache Tomcat/8.0.22

```

答:
You should change the action path to relative path.

<form method = "post" action="j_spring_security_check">

or it will submit the request to base dir.

ContentLicense: CC BY-SA 3.0

Body:
I'm attempting to get Spring Security working, and failing utterly.  No matter what I try, I can't get j_spring_security_check to be valid.

Error:

HTTP Status 404 - /j_spring_security_check

  type Status report

  message /j_spring_security_check

  description The requested resource is not available.

Login.html file:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>My App</title>
    <link rel="shortcut icon" type="image/x-icon" href="img/favicon.ico">

    <form method = "post" action="/j_spring_security_check">
      Username:
      <input type = "text" name = "username" />

      Password:
      <input type = "password" name = "password" />

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

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
    "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /META-INF/application*.xml
        </param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

  <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>com.me.portal.server.MyPortalServiceImpl</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/MyPortal/MyPortal</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>Login.html</welcome-file>
  </welcome-file-list>

</web-app>

application.security.xml:

<?xml version = "1.0" encoding = "UTF-8"?>
<beans:beans xmlns = "http://www.springframework.org/schema/security"
             xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans = "http://www.springframework.org/schema/beans"
             xmlns:util = "http://www.springframework.org/schema/util"
             xsi:schemaLocation = "http://www.springframework.org/schema/beans
                                 http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
                                 http://www.springframework.org/schema/util
                                 http://www.springframework.org/schema/util/spring-util-4.3.xsd
                                 http://www.springframework.org/schema/security
                                 http://www.springframework.org/schema/security/spring-security-3.2.xsd">

    <http auto-config = 'true' use-expressions = "false" entry-point-ref = "customAuthenticationEntryPoint">
        <intercept-url pattern = "/j_spring_security_check" access = "IS_AUTHENTICATED_ANONYMOUSLY"/>
        <intercept-url pattern = "/login" access = "IS_AUTHENTICATED_ANONYMOUSLY"/>
        <intercept-url pattern = "/Login.html" access = "IS_AUTHENTICATED_ANONYMOUSLY" />
        <intercept-url pattern = "/img/favicon.ico" access = "IS_AUTHENTICATED_ANONYMOUSLY" />
        <intercept-url pattern = "/**" access = "IS_AUTHENTICATED_FULLY" />
        <logout logout-success-url = "/Login.html" />
        <form-login login-page = "/Login.html" default-target-url = "/index.gwt.html" always-use-default-target = "true"
                    login-processing-url = "/j_spring_security_check" username-parameter = "username" password-parameter = "password"
                    authentication-success-handler-ref = "customAuthenticationSuccessHandler"
                    authentication-failure-handler-ref="customAuthenticationFailureHandler"/>

        <session-management invalid-session-url = "/Login.html"
                            session-authentication-error-url = "/Login.html"
                            session-fixation-protection = "newSession">
            <concurrency-control max-sessions = "1" error-if-maximum-exceeded = "false" />
        </session-management>
    </http>

    <ldap-server {Our settings} />

    <authentication-manager alias = "authenticationManager">
        <ldap-authentication-provider
                {Our LDAP Info}
        </ldap-authentication-provider>
    </authentication-manager>

    <beans:bean id = "customAuthenticationEntryPoint" class = "com.me.portal.server.security.CustomAuthenticationEntryPoint"/>

    <beans:bean id = "customAuthenticationSuccessHandler" class = "com.me.portal.server.security.CustomAuthenticationSuccessHandler"/>

    <beans:bean id = "customAuthenticationFailureHandler" class = "com.me.portal.server.security.CustomAuthenticationFailureHandler"/>

</beans:beans>

Spring JARs used:

spring-aop-4.3.2.RELEASE.jar
spring-beans-4.3.2.RELEASE.jar
spring-context-4.3.2.RELEASE.jar
spring-core-4.3.2.RELEASE.jar
spring-expression-4.3.2.RELEASE.jar
spring-ldap-core-2.3.1.RELEASE.jar
spring-security-config-3.2.7.RELEASE.jar
spring-security-core-3.2.7.RELEASE.jar
spring-security-ldap-3.2.7.RELEASE.jar
spring-security-web-3.2.7.RELEASE.jar
spring-tx-4.3.2.RELEASE.jar
spring-web-4.3.2.RELEASE.jar

As requested, Headers:

Response:

<!DOCTYPE html>
<title>Apache Tomcat/8.0.22 - Error report</title>

HTTP Status 404 - /j_spring_security_check

type Status report

message /j_spring_security_check

description The requested resource is not available.

Apache Tomcat/8.0.22


问:
Macro to delete only values of 0.00 and not 150.00, etc
I created a macro to search a column and delete the entire row if the value is 0.00. The problem is it also deletes all rows that contain that string i.e 140.00, 150.00, etc... so i'm losing good data. Not sure how to fix?

My Macro:

```<code>Dim c As Range
Dim SrchRng

Set SrchRng = ActiveSheet.Range("J5", ActiveSheet.Range("J65536").End(xlUp))
Do
    Set c = SrchRng.Find("0.00", LookIn:=xlValues)
    If Not c Is Nothing Then c.EntireRow.Delete
Loop While Not c Is Nothing
</code>```

Thanks for any help

答:
Try the following:

```<code>For i = ActiveSheet.UsedRange.Columns("J").Cells.Count to 5 Step -1
    If Range("J" & i).Value = 0# Then Range("J" & i).EntireRow.Delete
Next
</code>```

Give it a try and let me know your comments

Body:
I created a macro to search a column and delete the entire row if the value is 0.00. The problem is it also deletes all rows that contain that string i.e 140.00, 150.00, etc... so i'm losing good data. Not sure how to fix?

My Macro:

Dim c As Range
Dim SrchRng

Set SrchRng = ActiveSheet.Range("J5", ActiveSheet.Range("J65536").End(xlUp))
Do
    Set c = SrchRng.Find("0.00", LookIn:=xlValues)
    If Not c Is Nothing Then c.EntireRow.Delete
Loop While Not c Is Nothing

Thanks for any help

Body:
Try the following:

For i = ActiveSheet.UsedRange.Columns("J").Cells.Count to 5 Step -1
    If Range("J" & i).Value = 0# Then Range("J" & i).EntireRow.Delete
Next

Give it a try and let me know your comments


问:
Check based on value of previously captured group value
I have a regular expression. I want the .com to match only if it is not www.somesite.com but match if it is www.somesite.info.

Is there a way to achieve that? Essentially within the com|info section, can I somehow check the value of the previously captured group value

```<code>((?!www).*)\.someveryspecificsite\.(com|info)

www.someveryspecificsite.info - should match
anystring.someveryspecificsite.info - should match
anystring.someveryspecificsite.com - should match
www.someveryspecificsite.com - should not match
anything else - should not match
</code>```

答:
```<code>((?:.*?someveryspecificsite\.info$)|(?:^(?!w{3}).*?someveryspecificsite\.?com$))
</code>```

Solution on Regexpal.

Body:
I have a regular expression. I want the .com to match only if it is not www.somesite.com but match if it is www.somesite.info.

Is there a way to achieve that? Essentially within the com|info section, can I somehow check the value of the previously captured group value

((?!www).*)\.someveryspecificsite\.(com|info)

www.someveryspecificsite.info - should match
anystring.someveryspecificsite.info - should match
anystring.someveryspecificsite.com - should match
www.someveryspecificsite.com - should not match
anything else - should not match

Body:
((?:.*?someveryspecificsite\.info$)|(?:^(?!w{3}).*?someveryspecificsite\.?com$))

Solution on Regexpal.


问:
Kalman filter: how to use it with no "state transition model"?
I am working on accelerometer from an android phone. I wish to filter the horrible noise the accelerometer is returning recording the phone's moves.

I was reading around on Kalman filter, because low pass are just not enough.

But I don't have a model of the transition from ACCELERATION(k-1) to ACCELERATION(k) because it is the movements of the user. So I have no state transition matrix (H or F in different papers, the one that multiply Xk-1 in the equation Xk = HXk-1 + Bcommand+noise)

I saw some people taking the identity matrix in simple examples. How can it work for dynamic acceleration?

I know Kalman Filters, people always produce some H matrix, I just don't know how in my case.

答: The thing with kalman filter is that it does prediction and then corrects your prediction based on your observation. If your model is not very dynamic although your model assumes constant position but based on your observation you will get something in between.So Identity could work.  </p>


问:
Inconsistent behavior in JavaScript's conditional checking
I want to build an object obj1 with property obj2, which is another object.  To avoid redeclaring obj1 and obj2, I use the following code:

```<code>if (!obj1) obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1
</code>```

Assume, obj1 and obj1.obj2 aren't defined yet, the code causes the browser to report the error "obj1 is not defined".

If I change the code to:

```<code>if (typeof obj1==='undefined') obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1
</code>```

Then there's no error, while I think it should report "obj2 is not defined".  I'm puzzled as to why the JavaScript treats the short-hand falsy check of a reference and a property differently.  Can anyone shed a light on that?

答:
I think the latter code boils down to §8.7.1 and §8.12.3 in ECMAScript 5:

8.7.1 GetValue

If Type(V) is not Reference, return V.

Let base be the result of calling GetBase(V). If

IsUnresolvableReference(V), throw a
  ReferenceError exception.

If
  IsPropertyReference(V), then

a. If
    HasPrimitiveBase(V) is false, then let
    get be the [[Get]] internal method of
    base, otherwise let get be the special
    [[Get]] internal method defined below.

b. Return the result of calling the
    get internal method using base as its
    this value, and passing
    GetReferencedName(V) for the argument.

5. Else, base must be an environment
  record.

a. Return the result of
    calling the GetBindingValue (see
    10.2.1) concrete method of base passing GetReferencedName(V) and
    IsStrictReference(V) as arguments.

8.12.3 [[Get]]

When the [[Get]] internal method of O
  is called with property name P, the
  following steps are taken:

8. Let desc be the result of calling the [[GetProperty]] internal method of
  O with property name P.

9. If desc is
  undefined, return undefined.

10 If
  IsDataDescriptor(desc) is true, return
  desc.[[Value]].

11 Otherwise,
  IsAccessorDescriptor(desc) must be
  true so, let getter be desc.[[Get]].

12. If getter is undefined, return
  undefined.

13. Return the result calling
  the [[Call]] internal method of getter
  providing O as the this value and
  providing no arguments.

As you can see, it only throws a ReferenceError here for IsUnresolvableReference.  That applies if the base (obj1) is undefined.  There is a list of places where ReferenceError is thrown in §15.11.6.3.

ContentLicense: CC BY-SA 2.5

Body:
I want to build an object obj1 with property obj2, which is another object.  To avoid redeclaring obj1 and obj2, I use the following code:

if (!obj1) obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1

Assume, obj1 and obj1.obj2 aren't defined yet, the code causes the browser to report the error "obj1 is not defined".

If I change the code to:

if (typeof obj1==='undefined') obj1 = {};
if (!obj1.obj2) obj1.obj2 = {};
// code to use obj1

Then there's no error, while I think it should report "obj2 is not defined".  I'm puzzled as to why the JavaScript treats the short-hand falsy check of a reference and a property differently.  Can anyone shed a light on that?


问:
Are multiple `with` statements on one line equivalent to nested `with` statements, in python?
Are these two statements equivalent?

```<code>with A() as a, B() as b:
  # do something

with A() as a:
  with B() as b:
    # do something
</code>```

I ask because both a and b alter global variables (tensorflow here) and b depends on changes made by a. So I know the 2nd form is safe to use, but is it equivalent to shorten it to the 1st form?

答:
Yes, listing multiple with statements on one line is exactly the same as nesting them, according to the Python 2.7 language reference:

With more than one item, the context managers are processed as if multiple with statements were nested:

```<code>with A() as a, B() as b:
   suite
</code>```

is equivalent to

```<code>with A() as a:
   with B() as b:
       suite
</code>```

Similar language appears in the Python 3 language reference.

Update for 3.10+

Changed in version 3.10: Support for using grouping parentheses to break the statement in multiple lines.

with (
   A() as a,
   B() as b,
):
   SUITE
```

ContentLicense: CC BY-SA 4.0

Body:
Are these two statements equivalent?

with A() as a, B() as b:
  # do something

with A() as a:
  with B() as b:
    # do something

I ask because both a and b alter global variables (tensorflow here) and b depends on changes made by a. So I know the 2nd form is safe to use, but is it equivalent to shorten it to the 1st form?

Body:
Yes, listing multiple with statements on one line is exactly the same as nesting them, according to the Python 2.7 language reference:

With more than one item, the context managers are processed as if multiple with statements were nested:

with A() as a, B() as b:
   suite

is equivalent to

with A() as a:
   with B() as b:
       suite

Similar language appears in the Python 3 language reference.

Update for 3.10+

Changed in version 3.10: Support for using grouping parentheses to break the statement in multiple lines.

with (
   A() as a,
   B() as b,
):
   SUITE


问:
pdfminer3k has no method named create_pages in PDFPage
Since I want to move from python 2 to 3, I tried to work with pdfmine.3kr in python 3.4. It seems like they have edited everything. Their change logs do not reflect the changes they have done but I had no success in parsing pdf with pdfminer3k. For example:

They have moved PDFDocument into pdfparser (sorry, if I spell incorrectly). PDFPage used to have create_pages method which is gone now. All I can see inside PDFPage are internal methods. Does anybody has a working example of pdfminer3k? It seems like there is no new documentation to reflect any of the changes.

答:
Perhaps,you could use pdfminer.six.
It's description:

fork of PDFMiner using six for Python 2+3 compatibility

After installing it using pip：

pip install pdfminer.six

The usage of it is just like pdfminer, at least in my code.

Hope this could save your day :)


答: Absolutely identical. Just depends on your personal preference.</p>

Title: Are multiple `with` statements on one line equivalent to nested `with` statements, in python?


问:
New TFS 2015 Web based build definition is not cleaning artifact from previous build even after specify clean
Building a solution with new web based build definition. passing MSBuild arguments during the build. checked clean options. but TFS is not removing old build artifacts from previous build, instead of removing an artifacts, it's giving just appending new one with old one.

using MS Build arguments:  /p:DeployOnBuild=true /P:PackageTempRootDir=\Release /p:DeployIisAppPath="Default Web Site";DefaultPackageFileName=DemoApp.zip /p:OutputPath="$(Build.BinariesDirectory)\$(BuildPlatform)\$(BuildConfiguration)"

I tried by changing the name of DefaultPackageFileName with something else like (TestApp.zip)

if I see in my output folder. I am getting both zip file created instead of one. what can be issue?

答: According to the comment above. Please copy this build definition to a new build definition.</p>


问:
Migrating from non-partitioned to Partitioned tables
In June the BQ team announced support for date-partitioned tables. But the guide is missing how to migrate old non-partitioned tables into the new style.

I am looking for a way to update several or if not all tables to the new style.

Also outside of DAY type partitioned what other options are available? Does the BQ UI show this, as I wasn't able to create such a new partitioned table from the BQ Web UI.

答:
from Pavan’s answer: Please note that this approach will charge you the scan cost of the source table for the query as many times as you query it.

  from Pentium10 comments: So suppose I have several years of data, I need to prepare different query for each day and run all of it, and suppose I have 1000 days in history, I need to pay 1000 times the full query price from the source table?

As we can see - the main problem here is on having full scan for each and every day. The rest is less of a problem and can be easily scripted out in any client of the choice

So, below is to - How to partition table while avoid full table scan for each and every day?

Below step-by-step shows the approach

It is generic enough to extend/apply to anyone real use-case - meantime I am using bigquery-public-data.noaa_gsod.gsod2017 and I am limiting "exercise" to just 10 days to keep it readable

Step 1 – Create Pivot table

In this step we

a) compress each row’s content into record/array

and

b) put them all into respective ”daily” column

#standardSQL
SELECT
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170101' THEN r END) AS day20170101,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170102' THEN r END) AS day20170102,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170103' THEN r END) AS day20170103,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170104' THEN r END) AS day20170104,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170105' THEN r END) AS day20170105,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170106' THEN r END) AS day20170106,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170107' THEN r END) AS day20170107,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170108' THEN r END) AS day20170108,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170109' THEN r END) AS day20170109,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170110' THEN r END) AS day20170110
FROM (
  SELECT d, r, ROW_NUMBER() OVER(PARTITION BY d) AS line
  FROM (
    SELECT
      stn, CONCAT('day', year, mo, da) AS d, ARRAY_AGG(t) AS r
    FROM `bigquery-public-data.noaa_gsod.gsod2017` AS t
    GROUP BY stn, d
  )
)
GROUP BY line
```

<p>Run above query in Web UI with pivot_table (or whatever name is preferred) as a destination</p>

<p>As we can see - here we will get table with 10 columns – one column for one day and schema of each column is a copy of schema of original table:  </p>

<p><img src="https://i.stack.imgur.com/jmGEM.jpg" alt="enter image description here"></p>

<p><strong>Step 2</strong> – Processing partitions one-by-one ONLY scanning respective column (no full table scan) – inserting into respective partition </p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
SELECT r.*
FROM pivot_table, UNNEST(day20170101) AS r
</code>```

Run above query from Web UI with destination table named mytable$20160101

You can run same for next day

#standardSQL
SELECT r.*
FROM pivot_table, UNNEST(day20170102) AS r
```

<p>Now you should have destination table as mytable$20160102 and so on  </p>

<p><img src="https://i.stack.imgur.com/MQGFS.png" alt="enter image description here"></p>

<p>You should be able to automate/script this step with any client of your choice</p>

<p>There are many variations of how you can use above approach - it is up to your creativity</p>

<p>Note: BigQuery allows up to 10000 columns in table, so 365 columns for respective days of one year is definitely not a problem here :o)
Unless there is a limitation on how far back you can go with new partitions – I heard (but didn’t have chance to check yet) there is now no more than 90 days back</p>

<blockquote>
  <p>Update   </p>
</blockquote>

<p>Please note:
Above version has a little extra logic of packing all aggregated cells into as least final number of rows as possible.   </p>

<p><code>ROW_NUMBER() OVER(PARTITION BY d) AS line</code><br>
and then<br>
<code>GROUP BY line</code><br>
along with<br>
<code>ARRAY_CONCAT_AGG(…)</code><br>
does this      </p>

<p>This works well when row size in your original table is not that big so final combined row size still will be within rows size limit that BigQuery has (which I believe is 10 MB as of now)</p>

<p>If your source table already has row size close to that limit – use below adjusted version   </p>

<p>In this version – grouping is removed such that each row has only value for one column</p>

<pre class="lang-sql prettyprint-override"><code>#standardSQL
SELECT
    CASE WHEN d = 'day20170101' THEN r END AS day20170101,
    CASE WHEN d = 'day20170102' THEN r END AS day20170102,
    CASE WHEN d = 'day20170103' THEN r END AS day20170103,
    CASE WHEN d = 'day20170104' THEN r END AS day20170104,
    CASE WHEN d = 'day20170105' THEN r END AS day20170105,
    CASE WHEN d = 'day20170106' THEN r END AS day20170106,
    CASE WHEN d = 'day20170107' THEN r END AS day20170107,
    CASE WHEN d = 'day20170108' THEN r END AS day20170108,
    CASE WHEN d = 'day20170109' THEN r END AS day20170109,
    CASE WHEN d = 'day20170110' THEN r END AS day20170110
FROM (
    SELECT
        stn, CONCAT('day', year, mo, da) AS d, ARRAY_AGG(t) AS r
    FROM `bigquery-public-data.noaa_gsod.gsod2017` AS t
    GROUP BY stn, d
)
WHERE d BETWEEN 'day20170101' AND 'day20170110'
</code>```

As you can see now  -  pivot table (sparce_pivot_table) is sparse enough (same 21.5 MB but now 114,089 rows vs. 11,584 rows in pivot_table) so it has average row size of 190B vs 1.9KB in initial version. Which is obviously about 10 times less as per number of columns in the example.

So before using this approach some math needs to be done to project/estimate what and how can be done!

Still: each cell in pivot table is sort of JSON representation of whole row in original table. It is such as it holds not just values as it was for rows in original table but also has a schema in it

As such it is quite verbose - thus the size of cell can be multiple times bigger than original size [which limits the usage of this approach ... unless you get even more creative :o) ... which is still plenty of areas here to apply :o) ]

Body:
from Pavan’s answer: Please note that this approach will charge you the scan cost of the source table for the query as many times as you query it.

  from Pentium10 comments: So suppose I have several years of data, I need to prepare different query for each day and run all of it, and suppose I have 1000 days in history, I need to pay 1000 times the full query price from the source table?

As we can see - the main problem here is on having full scan for each and every day. The rest is less of a problem and can be easily scripted out in any client of the choice

So, below is to - How to partition table while avoid full table scan for each and every day?

Below step-by-step shows the approach

It is generic enough to extend/apply to anyone real use-case - meantime I am using bigquery-public-data.noaa_gsod.gsod2017 and I am limiting "exercise" to just 10 days to keep it readable

Step 1 – Create Pivot table

In this step we

a) compress each row’s content into record/array

and

b) put them all into respective ”daily” column

#standardSQL
SELECT
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170101' THEN r END) AS day20170101,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170102' THEN r END) AS day20170102,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170103' THEN r END) AS day20170103,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170104' THEN r END) AS day20170104,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170105' THEN r END) AS day20170105,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170106' THEN r END) AS day20170106,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170107' THEN r END) AS day20170107,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170108' THEN r END) AS day20170108,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170109' THEN r END) AS day20170109,
  ARRAY_CONCAT_AGG(CASE WHEN d = 'day20170110' THEN r END) AS day20170110
FROM (
  SELECT d, r, ROW_NUMBER() OVER(PARTITION BY d) AS line
  FROM (
    SELECT
      stn, CONCAT('day', year, mo, da) AS d, ARRAY_AGG(t) AS r
    FROM `bigquery-public-data.noaa_gsod.gsod2017` AS t
    GROUP BY stn, d
  )
)
GROUP BY line

Run above query in Web UI with pivot_table (or whatever name is preferred) as a destination

As we can see - here we will get table with 10 columns – one column for one day and schema of each column is a copy of schema of original table:

Step 2 – Processing partitions one-by-one ONLY scanning respective column (no full table scan) – inserting into respective partition

#standardSQL
SELECT r.*
FROM pivot_table, UNNEST(day20170101) AS r

Run above query from Web UI with destination table named mytable$20160101

You can run same for next day

#standardSQL
SELECT r.*
FROM pivot_table, UNNEST(day20170102) AS r

Now you should have destination table as mytable$20160102 and so on

You should be able to automate/script this step with any client of your choice

There are many variations of how you can use above approach - it is up to your creativity

Note: BigQuery allows up to 10000 columns in table, so 365 columns for respective days of one year is definitely not a problem here :o)
Unless there is a limitation on how far back you can go with new partitions – I heard (but didn’t have chance to check yet) there is now no more than 90 days back

Update

Please note:
Above version has a little extra logic of packing all aggregated cells into as least final number of rows as possible.

ROW_NUMBER() OVER(PARTITION BY d) AS line

and then

GROUP BY line

along with

ARRAY_CONCAT_AGG(…)

does this

This works well when row size in your original table is not that big so final combined row size still will be within rows size limit that BigQuery has (which I believe is 10 MB as of now)

If your source table already has row size close to that limit – use below adjusted version

In this version – grouping is removed such that each row has only value for one column

#standardSQL
SELECT
    CASE WHEN d = 'day20170101' THEN r END AS day20170101,
    CASE WHEN d = 'day20170102' THEN r END AS day20170102,
    CASE WHEN d = 'day20170103' THEN r END AS day20170103,
    CASE WHEN d = 'day20170104' THEN r END AS day20170104,
    CASE WHEN d = 'day20170105' THEN r END AS day20170105,
    CASE WHEN d = 'day20170106' THEN r END AS day20170106,
    CASE WHEN d = 'day20170107' THEN r END AS day20170107,
    CASE WHEN d = 'day20170108' THEN r END AS day20170108,
    CASE WHEN d = 'day20170109' THEN r END AS day20170109,
    CASE WHEN d = 'day20170110' THEN r END AS day20170110
FROM (
    SELECT
        stn, CONCAT('day', year, mo, da) AS d, ARRAY_AGG(t) AS r
    FROM `bigquery-public-data.noaa_gsod.gsod2017` AS t
    GROUP BY stn, d
)
WHERE d BETWEEN 'day20170101' AND 'day20170110'

As you can see now  -  pivot table (sparce_pivot_table) is sparse enough (same 21.5 MB but now 114,089 rows vs. 11,584 rows in pivot_table) so it has average row size of 190B vs 1.9KB in initial version. Which is obviously about 10 times less as per number of columns in the example.

So before using this approach some math needs to be done to project/estimate what and how can be done!

Still: each cell in pivot table is sort of JSON representation of whole row in original table. It is such as it holds not just values as it was for rows in original table but also has a schema in it

As such it is quite verbose - thus the size of cell can be multiple times bigger than original size [which limits the usage of this approach ... unless you get even more creative :o) ... which is still plenty of areas here to apply :o) ]


问:
IList.Cast<typeof(T)>() returns error, syntax looks ok
```<code>public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}
</code>```

<p>So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here? </p>

答:
@Jon and @Jonathan is correct, but you also have to change the return type to

```<code>IList<T>
</code>```

also.  Unless that is just a markdown bug.

@Jonathan, figured that was the case.

I am not sure what version of nHibernate you are using.  I haven't tried the gold release of 2.0 yet, but you could clean the method up some, by removing some lines:

```<code>public static IList<T> LoadObjectListAll()
{
    ISession session = CheckForExistingSession();
    // Not sure if you can configure a session after retrieving it.  CheckForExistingSession should have this logic.
    // var cfg = new NHibernate.Cfg.Configuration().Configure();
    var criteria = session.CreateCriteria(typeof(T));
    return criteria.List<T>();
}
</code>```

OwnerDisplayName: Sara Chipps

Body:
public static IList<T> LoadObjectListAll<T>()
{
    ISession session = CheckForExistingSession();
    var cfg = new NHibernate.Cfg.Configuration().Configure();
    var returnList = session.CreateCriteria(typeof(T));
    var list = returnList.List();
    var castList = list.Cast<typeof(T)>();
    return castList;
}

So, I'm getting a build error where I am casting the "list" element to a generic IList .... can anyone see a glaring error here?

Body:
@Jon and @Jonathan is correct, but you also have to change the return type to

IList<T>

also.  Unless that is just a markdown bug.

@Jonathan, figured that was the case.

I am not sure what version of nHibernate you are using.  I haven't tried the gold release of 2.0 yet, but you could clean the method up some, by removing some lines:

public static IList<T> LoadObjectListAll()
{
    ISession session = CheckForExistingSession();
    // Not sure if you can configure a session after retrieving it.  CheckForExistingSession should have this logic.
    // var cfg = new NHibernate.Cfg.Configuration().Configure();
    var criteria = session.CreateCriteria(typeof(T));
    return criteria.List<T>();
}

OwnerDisplayName: Dale Ragan

LastEditorDisplayName: Dale Ragan


问:
What kind of WPF control to use?
I want to create a 2D control that looks like a can. One color on the bottom and another color on the side. I will place many instances of this control on a canvas, and the canvas inside av viewbox.

I need support for tooltip, rightclick and drag&drop. It also has to support databinding and resizing.

What is the best way to create this control? Any advise is welcome. Thanks!

答: My advice is make a VisualBrush which has the drawing of the can as its contents. Then each item would be a Rectangle (which will support the features you need), and the Rectangle's Fill property will be set to the VisualBrush

Title: What kind of WPF control to use?


问:
Index multiple columns and Match distinct values, returning list of unique values across columns
I've searched far and wide for a solution to my problem... over several long weeks now. I've come up a partially working solutions, which I'll include at the bottom for those who might know how to modify/extend them to resolve the problem.

Here's what I'm trying to accomplish (the following descriptions are in reference to this screen capture http://imgur.com/oTkbjrw):

1) I am looking to match values from Column G with Column A ($G2 with $A$2:$A$10).

2) If the values match, then extract unique values (excluding blanks) from adjacent Columns B, C, and D, and return them across columns (H through M).

So, as shown in the 'desired results 1' table (G1:M10), if G2 (Vancouver) is found in A2:A10, then extract indexed values from columns B,C, and D where Vancouver is a match (i.e., Blue, ,Green,Green,Red,Yellow,Teal,Green, , , ,Pink,Pink,Pink, ,) and return only the unique values (excluding blanks) across columns H through L (blue,Green,Red,Yellow,Teal,Pink).

I've been looking for a formula solution that can be popped into H2 and then dragged horizontally to M2, to reveal the results. I'm not married to this solution, however. An alternative that I've also considered is to return the unique values in comma delimited format rather than across columns(see 'desired Results 2'). If this is easier to accomplish, I'm all for it.

Note: I will be running this formula on 10,000+ rows. A lean/efficient solution is desirable if possible.

PARTIAL SOLUTIONS I'VE PUT TOGETHER:

1) {Array formula 1}, results can be seen here:

```<code>=IFERROR(INDEX($B$2:$B$10, SMALL(IF(COUNTIF($G2,$A$2:$A$10), MATCH(ROW($B$2:$B$10), ROW($B$2:$B$10)), ""), COLUMN(A1))),"")
</code>```

This formula is only able to index column B, but it successfully matches and returns values across columns. Unfortunately, it doesn't extract unique values and returns blank cells.

2) Re: Justin's comment about a likely VBA solution, figure I should pop up one of the VBA solutions I came across.

```<code>Function UNIQUE_PH(Lookupvalue As String, LookupRange As Range, ColumnNumber As Integer)
Dim i As Long
Dim Result As String
For i = 1 To LookupRange.Columns(1).Cells.Count
  If LookupRange.Cells(i, 1) = Lookupvalue Then
    For J = 1 To i - 1
    If LookupRange.Cells(J, 1) = Lookupvalue Then
      If LookupRange.Cells(J, ColumnNumber) = LookupRange.Cells(i, ColumnNumber) Then
        GoTo Skip
      End If
    End If
    Next J
    Result = Result & " " & LookupRange.Cells(i, ColumnNumber) & ","
Skip:
  End If
Next i
UNIQUE_PH = Left(Result, Len(Result) - 1)
End Function

'It takes 3 arguments as inputs:

'1. Lookupvalue – A string that we need to look-up in a range of cells.
'2. LookupRange  – An array of cells from where we need to fetch the data
'3. ColumnNumber – It is the column number of the table/array from which matching value is to be returned (e.g. 2 for second column).
</code>```

This basically does what the above formula accomplishes, with the exception that it successfully identifies unique values. It presents the results in one cell as comma delimited (similar to 'desired Results 2'). This isn't able to search through multiple columns and doesn't remove blank cells. I also tried to run it on 10,000 rows of data and it was very slow. I know very little about VBA, so I'm not sure what could be contributing to the lag.

答:
Try this UDF

```<code>Function UniquePh(Lookupvalue As String, LookupRange As Range, ValueRng As Range) As String
Dim dict As Object
Dim lkpArr() As Variant
Dim ValArr() As Variant
Set LookupRange = Intersect(LookupRange, LookupRange.Parent.UsedRange)
Set ValueRng = Intersect(ValueRng, ValueRng.Parent.UsedRange)
If LookupRange.Rows.Count <> ValueRng.Rows.Count Or LookupRange.Columns.Count > 1 Then Exit Function

Set dict = CreateObject("Scripting.Dictionary")
lkpArr = LookupRange.Value
ValArr = ValueRng.Value

For i = LBound(lkpArr, 1) To UBound(lkpArr, 1)
    If lkpArr(i, 1) = Lookupvalue Then
        For j = LBound(ValArr, 2) To UBound(ValArr, 2)
            If ValArr(i, j) <> "" Then
                On Error Resume Next
                    dict.Add ValArr(i, j), ValArr(i, j)
                On Error GoTo 0
            End If
        Next j
    End If
Next i

For Each itm In dict
    UniquePh = UniquePh & itm & ", "
Next itm
If Len(UniquePh) > 0 Then
    UniquePh = Left(UniquePh, Len(UniquePh) - 2)
Else: UniquePh = ""
End If

End Function
</code>```

Put it in a modules attached to the workbook.  Then call it from the sheet.  Put this formula in H2:

```<code>=UniquePh(G2,$A$2:$A$10,$B$2:$D$10)
</code>```

It should run a lot faster.

Body:
I've searched far and wide for a solution to my problem... over several long weeks now. I've come up a partially working solutions, which I'll include at the bottom for those who might know how to modify/extend them to resolve the problem.

Here's what I'm trying to accomplish (the following descriptions are in reference to this screen capture http://imgur.com/oTkbjrw):

1) I am looking to match values from Column G with Column A ($G2 with $A$2:$A$10).

2) If the values match, then extract unique values (excluding blanks) from adjacent Columns B, C, and D, and return them across columns (H through M).

So, as shown in the 'desired results 1' table (G1:M10), if G2 (Vancouver) is found in A2:A10, then extract indexed values from columns B,C, and D where Vancouver is a match (i.e., Blue, ,Green,Green,Red,Yellow,Teal,Green, , , ,Pink,Pink,Pink, ,) and return only the unique values (excluding blanks) across columns H through L (blue,Green,Red,Yellow,Teal,Pink).

I've been looking for a formula solution that can be popped into H2 and then dragged horizontally to M2, to reveal the results. I'm not married to this solution, however. An alternative that I've also considered is to return the unique values in comma delimited format rather than across columns(see 'desired Results 2'). If this is easier to accomplish, I'm all for it.

Note: I will be running this formula on 10,000+ rows. A lean/efficient solution is desirable if possible.

PARTIAL SOLUTIONS I'VE PUT TOGETHER:

1) {Array formula 1}, results can be seen here:

=IFERROR(INDEX($B$2:$B$10, SMALL(IF(COUNTIF($G2,$A$2:$A$10), MATCH(ROW($B$2:$B$10), ROW($B$2:$B$10)), ""), COLUMN(A1))),"")

This formula is only able to index column B, but it successfully matches and returns values across columns. Unfortunately, it doesn't extract unique values and returns blank cells.

2) Re: Justin's comment about a likely VBA solution, figure I should pop up one of the VBA solutions I came across.

Function UNIQUE_PH(Lookupvalue As String, LookupRange As Range, ColumnNumber As Integer)
Dim i As Long
Dim Result As String
For i = 1 To LookupRange.Columns(1).Cells.Count
  If LookupRange.Cells(i, 1) = Lookupvalue Then
    For J = 1 To i - 1
    If LookupRange.Cells(J, 1) = Lookupvalue Then
      If LookupRange.Cells(J, ColumnNumber) = LookupRange.Cells(i, ColumnNumber) Then
        GoTo Skip
      End If
    End If
    Next J
    Result = Result & " " & LookupRange.Cells(i, ColumnNumber) & ","
Skip:
  End If
Next i
UNIQUE_PH = Left(Result, Len(Result) - 1)
End Function

'It takes 3 arguments as inputs:

'1. Lookupvalue – A string that we need to look-up in a range of cells.
'2. LookupRange  – An array of cells from where we need to fetch the data
'3. ColumnNumber – It is the column number of the table/array from which matching value is to be returned (e.g. 2 for second column).

This basically does what the above formula accomplishes, with the exception that it successfully identifies unique values. It presents the results in one cell as comma delimited (similar to 'desired Results 2'). This isn't able to search through multiple columns and doesn't remove blank cells. I also tried to run it on 10,000 rows of data and it was very slow. I know very little about VBA, so I'm not sure what could be contributing to the lag.

Body:
Try this UDF

Function UniquePh(Lookupvalue As String, LookupRange As Range, ValueRng As Range) As String
Dim dict As Object
Dim lkpArr() As Variant
Dim ValArr() As Variant
Set LookupRange = Intersect(LookupRange, LookupRange.Parent.UsedRange)
Set ValueRng = Intersect(ValueRng, ValueRng.Parent.UsedRange)
If LookupRange.Rows.Count <> ValueRng.Rows.Count Or LookupRange.Columns.Count > 1 Then Exit Function

Set dict = CreateObject("Scripting.Dictionary")
lkpArr = LookupRange.Value
ValArr = ValueRng.Value

For i = LBound(lkpArr, 1) To UBound(lkpArr, 1)
    If lkpArr(i, 1) = Lookupvalue Then
        For j = LBound(ValArr, 2) To UBound(ValArr, 2)
            If ValArr(i, j) <> "" Then
                On Error Resume Next
                    dict.Add ValArr(i, j), ValArr(i, j)
                On Error GoTo 0
            End If
        Next j
    End If
Next i

For Each itm In dict
    UniquePh = UniquePh & itm & ", "
Next itm
If Len(UniquePh) > 0 Then
    UniquePh = Left(UniquePh, Len(UniquePh) - 2)
Else: UniquePh = ""
End If

End Function

Put it in a modules attached to the workbook.  Then call it from the sheet.  Put this formula in H2:

=UniquePh(G2,$A$2:$A$10,$B$2:$D$10)

It should run a lot faster.


问:
queue up promises while using them in setters
I'm trying to iterate through an array and set one property of each element using an asynchronous function. I want to return this entire thing as one Promise. What's a good way to queue up all these promises? (I can import a NodeJS library if needed.)

The code basically looks like this:

```<code>.then(articles => {
    articles.forEach(article => {
      article.content = someAsyncFunction();
    });
    // How do I queue up and return each of these promises?
})
.then(() => { /* other stuff... */ })
</code>```

答:
Use promise.all. js fiddle: https://jsfiddle.net/rohitanand/fdkt16L2/

function createPromise(value,aftertime){
 return new Promise(function(resolve){
   setTimeout(function(){
     resolve(value);
    },aftertime)
  })
}
var abc = Promise.resolve({a:1,b:2,c:3})
.then(function(value){
 var promisearr =[];
  promisearr.push(createPromise(5,1000).then(function(val){ value.a = val;}));
   promisearr.push(createPromise(10,2000).then(function(val){ value.b = val;}));
    promisearr.push(createPromise(15,3000).then(function(val){ value.c = val;}));
    return Promise.all(promisearr).then(function(){return value});
}).then(function(value){
  console.log(value);
})```

Body:
I'm trying to iterate through an array and set one property of each element using an asynchronous function. I want to return this entire thing as one Promise. What's a good way to queue up all these promises? (I can import a NodeJS library if needed.)

The code basically looks like this:

.then(articles => {
    articles.forEach(article => {
      article.content = someAsyncFunction();
    });
    // How do I queue up and return each of these promises?
})
.then(() => { /* other stuff... */ })


答:
This is another way to achieve  that :

```<code>var booleans = [true, false, true, false, true];

function inverted(bools) {
    var inversion = [],i=0;

    while(i< bools.length) {
      inversion.push(!(bools[i]));
      i++;
    }
    return inversion;
}

var inverted =  inverted(booleans);

console.log(inverted);//Outpu : [false, true, false, true, false]
</code>```

Title: Invert an array of booleans in JavaScript

Body:
This is another way to achieve  that :

var booleans = [true, false, true, false, true];

function inverted(bools) {
    var inversion = [],i=0;

    while(i< bools.length) {
      inversion.push(!(bools[i]));
      i++;
    }
    return inversion;
}

var inverted =  inverted(booleans);

console.log(inverted);//Outpu : [false, true, false, true, false]


问:
Debugging array related error (core dumped)
I was working to implement the rod cutting problem and I encountered this error:

```<code>a.out: malloc.c:2392: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted (core dumped)
</code>```

The dashed comment block is where I suspect the error is coming from, but I'm not sure why. Trying to run under gdb I am having hard time pin-pointing it (seems to be crashing at i = 7) (compiling using: g++)

```<code>#include <iostream>
#include <cstdlib>

using namespace std;

int max_from(int * arr, int n)
{
    int maxval = arr[1];
    for(size_t i = 2; i < n; ++i)
        if(arr[i] > maxval) maxval = arr[i];

    return maxval;
}

int main()
{
    int n = 11;

    int * V = new int[n]; // given arr, price at(i)
    int * C = new int[n]; // optimal at length(i)

    V[0] = 0; // non-affecting value, using 1 as starting point

    V[1] = 1;
    V[2] = 5;
    V[3] = 8;
    V[4] = 9;
    V[5] = 10;
    V[6] = 17;
    V[7] = 17;
    V[8] = 20;
    V[9] = 24;
    V[10] = 30;

    C[0] = 0;

    // --------------------------------------------------

    for(size_t i = 1; i < n; ++i)
    {
        int * arr = new int[i];
        for(size_t k = 1; k <= i; ++k)
        {
            arr[k] = V[k] + C[i-k];
        }

        C[i] = max_from(arr, n);

        delete [ ] arr;
    }

    cout << max_from(C, n) << '\n'; // maximized cost
    // --------------------------------------------------

    delete [ ] V;
    delete [ ] C;
}
</code>```

答:
I suppose the problem is in

```<code>    C[i] = max_from(arr, n);
</code>```

in the for loop in main().

Observe that arr is allocated of dimension i

```<code>    int * arr = new int[i];
</code>```

where i start from 1.

But in max_from(arr, n), arr is used at position i where i start from 2 and end to n-1.

So, for the first loop, when the i in the main loop is 1, arr is allocated of size 1 but is accessed at position 10.

Crash!

p.s.: well... but ikh is right too.

Body:
I was working to implement the rod cutting problem and I encountered this error:

a.out: malloc.c:2392: sysmalloc: Assertion `(old_top == initial_top (av) && old_size == 0) || ((unsigned long) (old_size) >= MINSIZE && prev_inuse (old_top) && ((unsigned long) old_end & (pagesize - 1)) == 0)' failed.
Aborted (core dumped)

The dashed comment block is where I suspect the error is coming from, but I'm not sure why. Trying to run under gdb I am having hard time pin-pointing it (seems to be crashing at i = 7) (compiling using: g++)

#include <iostream>
#include <cstdlib>

using namespace std;

int max_from(int * arr, int n)
{
    int maxval = arr[1];
    for(size_t i = 2; i < n; ++i)
        if(arr[i] > maxval) maxval = arr[i];

    return maxval;
}

int main()
{
    int n = 11;

    int * V = new int[n]; // given arr, price at(i)
    int * C = new int[n]; // optimal at length(i)

    V[0] = 0; // non-affecting value, using 1 as starting point

    V[1] = 1;
    V[2] = 5;
    V[3] = 8;
    V[4] = 9;
    V[5] = 10;
    V[6] = 17;
    V[7] = 17;
    V[8] = 20;
    V[9] = 24;
    V[10] = 30;

    C[0] = 0;

    // --------------------------------------------------

    for(size_t i = 1; i < n; ++i)
    {
        int * arr = new int[i];
        for(size_t k = 1; k <= i; ++k)
        {
            arr[k] = V[k] + C[i-k];
        }

        C[i] = max_from(arr, n);

        delete [ ] arr;
    }

    cout << max_from(C, n) << '\n'; // maximized cost
    // --------------------------------------------------

    delete [ ] V;
    delete [ ] C;
}

Body:
I suppose the problem is in

    C[i] = max_from(arr, n);

in the for loop in main().

Observe that arr is allocated of dimension i

    int * arr = new int[i];

where i start from 1.

But in max_from(arr, n), arr is used at position i where i start from 2 and end to n-1.

So, for the first loop, when the i in the main loop is 1, arr is allocated of size 1 but is accessed at position 10.

Crash!

p.s.: well... but ikh is right too.


答:
Assuming you change someAsyncFunction to return a promise, you could then call articles.reduce to call the function for each entry value and get an array of outstanding promises. Passing the array to Promise.all returns a single promise for successful completion, although the return promise will be rejected if any single operation fails. (I would hope  recent versions of Node.js support Promise.all by now).

The fulfilled value of Promise.all is a result array containing all the fulfilled values of the input promises. Hence you use the result array to set the the content property of entries in articles with matching index.

However, the initial number of outstanding promises is the same as the number of entries in articles. If this could be large or very large, you may not wish to initiate that many concurrent active asynchronous requests. A solution to this is to use "asynchronous" recursion to process asynchronous requests serially, one after the other.

There are 300 results for searching SO for "[javascript] asynchronous recursion", so I won't go into further detail here.

Title: queue up promises while using them in setters


问:
How to create nestable object
At the begining I would like to say hello, so ... Hello. I need to create a nested object structure.
I've got an object (xaml page) like this

```<code><navigation:Page x:Class="ItemTemplateExample.ContentItem"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
       mc:Ignorable="d"
       xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
       d:DesignWidth="200" d:DesignHeight="20"
       Title="ContentItem Page">
<Grid x:Name="LayoutRoot">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="50"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button x:Name="button1" />
    <ContentControl  Grid.Column="1" x:Name="content1" />
</Grid>
</code>```

Now I would like to use it in nested structure. For Example

```<code><local:ContentItem ButtonText="level 1">
     <local:ContentItem ButtonText="level 2" />
     <local:ContentItem ButtonText="level 2" />
     <local:ContentItem ButtonText="level 2">
          <local:ContentItem ButtonText="level 3" />
     </local:ContentItem>
</local:ContentItem>
</code>```

Where ButtonText will be known value (set when adding nested object) and Content of each object will be object of the same type. I have no idea how to start. Please give me some hint, exmaples. Thank You.

答:
Two possible solutions: a user control or a data template. The user control is probably the simplest to get to from where you are now, but the data template may be a better solution in the long run.

Adding a user control to a project is straightforward - Visual Studio has a template for that. You could just put the exact same Grid you've shown here inside your ContentItem user control's Xaml. And then you'd just need to define a property called ButtonText in the codebehind of your user control. This should do it:

```<code>public string ButtonText
{
    get { return button1.Content.ToString(); }
    set { button1.Content = value; }
}
</code>```

That should let you use Xaml more or less exactly like you've shown.

The reason I'm suggesting that a data template might be better is that you might not want to hard-code the nested structure in Xaml. It's often nice to be able to generate such structure from data rather than baking it into the UI. However, if your structure is completely fixed, the approach you've asked for is probably OK.

Title: How to create nestable object

Body:
At the begining I would like to say hello, so ... Hello. I need to create a nested object structure.
I've got an object (xaml page) like this

<navigation:Page x:Class="ItemTemplateExample.ContentItem"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
       xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
       mc:Ignorable="d"
       xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
       d:DesignWidth="200" d:DesignHeight="20"
       Title="ContentItem Page">
<Grid x:Name="LayoutRoot">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="50"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button x:Name="button1" />
    <ContentControl  Grid.Column="1" x:Name="content1" />
</Grid>

Now I would like to use it in nested structure. For Example

<local:ContentItem ButtonText="level 1">
     <local:ContentItem ButtonText="level 2" />
     <local:ContentItem ButtonText="level 2" />
     <local:ContentItem ButtonText="level 2">
          <local:ContentItem ButtonText="level 3" />
     </local:ContentItem>
</local:ContentItem>

Where ButtonText will be known value (set when adding nested object) and Content of each object will be object of the same type. I have no idea how to start. Please give me some hint, exmaples. Thank You.

Body:
Two possible solutions: a user control or a data template. The user control is probably the simplest to get to from where you are now, but the data template may be a better solution in the long run.

Adding a user control to a project is straightforward - Visual Studio has a template for that. You could just put the exact same Grid you've shown here inside your ContentItem user control's Xaml. And then you'd just need to define a property called ButtonText in the codebehind of your user control. This should do it:

public string ButtonText
{
    get { return button1.Content.ToString(); }
    set { button1.Content = value; }
}

That should let you use Xaml more or less exactly like you've shown.

The reason I'm suggesting that a data template might be better is that you might not want to hard-code the nested structure in Xaml. It's often nice to be able to generate such structure from data rather than baking it into the UI. However, if your structure is completely fixed, the approach you've asked for is probably OK.


问:
100% code coverage, complaining about MoveNext()
I am trying to achieve 100% code coverage.
However, somehow code coverage is complaining about some MoveNext() method that is not covered, however, there is no code path that's iterating an IEnumerable...

Any ideas how to cover the MoveNext method? Where is the MoveNext() located?

答:
Honestly, and I'm speaking from experience of trying to attain and maintain 100% code coverage for a medium sized project with an average sized team where the code followed SOLID principles reasonably well, you should forget trying to achieve 100% code coverage.

Best practices suggest that, for good reason, a system with 70% coverage is pretty good, 80% very good, 90% exceptional. It sounds like you're in the high nineties, so you be proud, and not overly worry about that final piece which, by the sounds of it, isn't even testing your code base per se. Or to put it another way, would you rather hit that 100% holy grail or spend the time refactoring code to make future maintenance easier ?

When I tried maintaining 100% coverage I was new to C# and ended up writing unit tests to test the .Net framework's getters and setters - I thought I was really clever hitting 100% (for all of one week until someone in the team added a few lines of ultra-somple code) and then someone politely pointed out the stupidity of some of my tests - what a fool I felt.

I realise that my "answer" does not actually answer your question, and I started off this response as a comment, not an answer, but as I was writing I realised that my comments were so relevant that even without directly answering the question a mere comment was an insufficient explanation. I truly admire any attempt at 100% coverage, but don't get hung up on achieving it - "done is better than perfect".

Good luck nevertheless !


问:
Flexbox 3 divs, two columns, one with two rows
I am trying to take

```<code><div></div>
<div></div>
<div></div>
</code>```

Three sequential divs and turn it into below. Where red is div 1, green is div 2, blue is div 3.

I can do this with floats, something like

```<code>.div1 { float: left; }
.div2 { float: left; }
.div3 { float: left; }
</code>```

But I can't seem to get it working in flexbox, is this possible?

答:
After thinking about this a little more, it is possible with flexbox. The container just has to have a defined height (%, px or vh) will work.

http://codeply.com/go/U1DCKAx85d

```<code>body {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  height: 100vh;
}

.a {
  flex: 0 0 100%;
  background: red;
}

.b, .c {
  flex: 0 0 50%;
  background: green;
}

.c {
  background: blue;
}
</code>```

Body:
I am trying to take

Three sequential divs and turn it into below. Where red is div 1, green is div 2, blue is div 3.

I can do this with floats, something like

.div1 { float: left; }
.div2 { float: left; }
.div3 { float: left; }

But I can't seem to get it working in flexbox, is this possible?

Body:
After thinking about this a little more, it is possible with flexbox. The container just has to have a defined height (%, px or vh) will work.

http://codeply.com/go/U1DCKAx85d

body {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  height: 100vh;
}

.a {
  flex: 0 0 100%;
  background: red;
}

.b, .c {
  flex: 0 0 50%;
  background: green;
}

.c {
  background: blue;
}


问:
How can I efficiently find the maximum element and its indices in a scipy csr_matrix?
I have a sparse undirected graph stored in a scipy csr_matrix, and I need to find out the edge with maximum weight, which means that I need to find the maximum value and its corresponding row and column indices (actually I have to find the K largest values but to simplify the problem). Hence I wrote:

```<code>M=M.toarray()
for i in range(1,len(M)):
    for j in range(i+1,len(M[i])):
        if M[i][j] > maximum:
            row,col,maximum = i,j,M[i][j]
</code>```

It seems to be clumsy and performs poorly. Is there any better way to do this?

答:
```<code>import numpy as np
np.array(np.unravel_index(np.argsort(M.flatten(), axis=0)[-K:], M.shape)).T[::-1]
</code>```

This returns an array of indices of the K largest values, in descending order.
Example:

```<code>M=np.ones((10,10))
M[2,6]=10
M[4,3]=12
np.array(np.unravel_index(np.argsort(M.flatten(), axis=0)[-2:], M.shape)).T[::-1]
</code>```

Output: [[4,3], [2,6]]

Edit:

(Assuming you have a square matrix).
If you don't want any diagonal elements returned you could mask the array:

```<code>mask = (1-np.identity(M.shape[0]))
np.array(np.unravel_index(np.argsort((M*mask).flatten(), axis=0)[-2:], M.shape)).T[::-1]
</code>```

Body:
I have a sparse undirected graph stored in a scipy csr_matrix, and I need to find out the edge with maximum weight, which means that I need to find the maximum value and its corresponding row and column indices (actually I have to find the K largest values but to simplify the problem). Hence I wrote:

M=M.toarray()
for i in range(1,len(M)):
    for j in range(i+1,len(M[i])):
        if M[i][j] > maximum:
            row,col,maximum = i,j,M[i][j]

It seems to be clumsy and performs poorly. Is there any better way to do this?

Body:
import numpy as np
np.array(np.unravel_index(np.argsort(M.flatten(), axis=0)[-K:], M.shape)).T[::-1]

This returns an array of indices of the K largest values, in descending order.
Example:

M=np.ones((10,10))
M[2,6]=10
M[4,3]=12
np.array(np.unravel_index(np.argsort(M.flatten(), axis=0)[-2:], M.shape)).T[::-1]

Output: [[4,3], [2,6]]

Edit:

(Assuming you have a square matrix).
If you don't want any diagonal elements returned you could mask the array:

mask = (1-np.identity(M.shape[0]))
np.array(np.unravel_index(np.argsort((M*mask).flatten(), axis=0)[-2:], M.shape)).T[::-1]


问:
Cell formatting in Grid Geometry manager
I have this code:

```<code>from tkinter import *
from tkinter import ttk

class Application:
    def __init__(self, master):#Change to game class when combining code
        self.master = master#remove when combining code
        self.frame_Canvas = ttk.Frame(self.master, width = 600, height = 600)
        self.frame_Canvas.pack(side = 'left')
        self.frame_Canvas.pack_propagate(False)
        self.frame_Canvas.grid_propagate(False)
        self.hangman = Canvas(self.frame_Canvas, width = 600, height = 600,
                              background = 'white').pack()
        self.FullName = ttk.Label(self.frame_Canvas, text = "Full Name", background = 'white')#full name will be entered here
        self.FullName.config(font=("TkDefaultFont", 20))
        self.FullName.place(x = 10, y = 10)
        self.frame_Interact = ttk.Frame(self.master, width = 200, height = 600)
        self.frame_Interact.pack(side = 'right')
        self.frame_Interact.pack_propagate(False)
        self.frame_Interact.grid_propagate(False)
        self.QuestionLabel = ttk.Label(self.frame_Interact, text = "Question:")
        self.QuestionLabel.config(font=("TkDefaultFont", 20))
        self.QuestionLabel.grid(column = 0, row = 0)
        self.QuestionShow = Text(self.frame_Interact, height=1, width=8)#input question here
        self.QuestionShow.config(font=("TkDefaultFont", 20))
        self.QuestionShow.grid(column = 0, row = 1)#FIX THE FORMATTING OF QUESTION, GRID CELL TO LEFT, NOT BIG ENOUGTH?

        self.AnswerEntry = ttk.Entry(self.frame_Interact, width = 10)#do later

def main():

    root = Tk()
    root.wm_title("Hangman")
    Menu = Application(root)
    root.resizable(width=False, height=False)
    root.iconbitmap("windowicon.ico")
    root.mainloop()

if __name__ == "__main__": main()
</code>```

I dont know why, but the Answer box and label on the right side of my tkinter GUI is on the left side of its frame. I want it in the center. Does anyone know a way to frix it, or any improvements for the code so far. Thanks :)

答:
There are two ways you can do this, first way will to be to use .pack() instead of .grid() since pack is very easy to use and does the aligning for you automatically.

So you can just replace:

```<code>self.QuestionLabel.grid(column = 0, row = 0)
# and
self.QuestionShow.grid(column = 0, row = 1)
</code>```

With:

```<code>self.QuestionLabel.pack()
# and
self.QuestionLShow.pack()
</code>```

This way isn't recommended for your situation whatsoever, since that will involve mixing pack and grid together which could cause future errors in your code.

As Bryan Oakley said:
it will cause errors immediately, if the widgets share the same parent. It won't ever cause problems if the widgets have different parents.

You should instead do this:

```<code>from tkinter import *
from tkinter import ttk

class Application:
    def __init__(self, master):#Change to game class when combining code
        self.master = master#remove when combining code
        self.frame_Canvas = ttk.Frame(self.master, width = 600, height = 600)
        self.frame_Canvas.pack(side = 'left')
        self.frame_Canvas.pack_propagate(False)
        self.frame_Canvas.grid_propagate(False)
        self.hangman = Canvas(self.frame_Canvas, width = 600, height = 600,
                              background = 'white').pack()
        self.FullName = ttk.Label(self.frame_Canvas, text = "Full Name", background = 'white')#full name will be entered here
        self.FullName.config(font=("TkDefaultFont", 20))
        self.FullName.place(x = 10, y = 10)
        self.frame_Interact = ttk.Frame(self.master, width = 200, height = 600)
        self.frame_Interact.pack(side = 'right')
        self.frame_Interact.pack_propagate(False)
        self.frame_Interact.grid_propagate(False)
        Grid.columnconfigure(self.frame_Interact, 0, weight=1) # NOTE, THIS CHANGED
        self.QuestionLabel = ttk.Label(self.frame_Interact, text = "Question:")
        self.QuestionLabel.config(font=("TkDefaultFont", 20))
        self.QuestionLabel.grid(column = 0, row = 0)
        self.QuestionShow = Text(self.frame_Interact, height=1, width=8)
        self.QuestionShow.config(font=("TkDefaultFont", 20))
        self.QuestionShow.grid(column = 0, row = 1)

def main():
    root = Tk()
    root.wm_title("Hangman")
    Menu = Application(root)
    root.resizable(width=False, height=False)
    root.iconbitmap("windowicon.ico")
    root.mainloop()

if __name__ == "__main__":
    main()
</code>```

By adding Grid.columnconfigure(self.frame_Interact, 0, weight=1) it will help grid know how to allocate extra space. so that the label will try to take up the whole column. The same goes for rows if you're wondering, you can add Grid.rowconfigure(self.frame_Interact, 0, weight=1) to make the widgets fill the whole row.

And for some improvements to your code, you should change this line:

```<code>self.hangman = Canvas(self.frame_Canvas, width = 600, height = 600,
                          background = 'white').pack()

# to
self.hangman = Canvas(self.frame_Canvas, width = 600, height = 600, background = 'white')
self.hangman.pack()
</code>```

Or else self.hangman will be None, as it is in your code.

Body:
I have this code:

from tkinter import *
from tkinter import ttk

class Application:
    def __init__(self, master):#Change to game class when combining code
        self.master = master#remove when combining code
        self.frame_Canvas = ttk.Frame(self.master, width = 600, height = 600)
        self.frame_Canvas.pack(side = 'left')
        self.frame_Canvas.pack_propagate(False)
        self.frame_Canvas.grid_propagate(False)
        self.hangman = Canvas(self.frame_Canvas, width = 600, height = 600,
                              background = 'white').pack()
        self.FullName = ttk.Label(self.frame_Canvas, text = "Full Name", background = 'white')#full name will be entered here
        self.FullName.config(font=("TkDefaultFont", 20))
        self.FullName.place(x = 10, y = 10)
        self.frame_Interact = ttk.Frame(self.master, width = 200, height = 600)
        self.frame_Interact.pack(side = 'right')
        self.frame_Interact.pack_propagate(False)
        self.frame_Interact.grid_propagate(False)
        self.QuestionLabel = ttk.Label(self.frame_Interact, text = "Question:")
        self.QuestionLabel.config(font=("TkDefaultFont", 20))
        self.QuestionLabel.grid(column = 0, row = 0)
        self.QuestionShow = Text(self.frame_Interact, height=1, width=8)#input question here
        self.QuestionShow.config(font=("TkDefaultFont", 20))
        self.QuestionShow.grid(column = 0, row = 1)#FIX THE FORMATTING OF QUESTION, GRID CELL TO LEFT, NOT BIG ENOUGTH?

        self.AnswerEntry = ttk.Entry(self.frame_Interact, width = 10)#do later

def main():

    root = Tk()
    root.wm_title("Hangman")
    Menu = Application(root)
    root.resizable(width=False, height=False)
    root.iconbitmap("windowicon.ico")
    root.mainloop()

if __name__ == "__main__": main()

I dont know why, but the Answer box and label on the right side of my tkinter GUI is on the left side of its frame. I want it in the center. Does anyone know a way to frix it, or any improvements for the code so far. Thanks :)

Body:
There are two ways you can do this, first way will to be to use .pack() instead of .grid() since pack is very easy to use and does the aligning for you automatically.

So you can just replace:

self.QuestionLabel.grid(column = 0, row = 0)
# and
self.QuestionShow.grid(column = 0, row = 1)

With:

self.QuestionLabel.pack()
# and
self.QuestionLShow.pack()

This way isn't recommended for your situation whatsoever, since that will involve mixing pack and grid together which could cause future errors in your code.

As Bryan Oakley said:
it will cause errors immediately, if the widgets share the same parent. It won't ever cause problems if the widgets have different parents.

You should instead do this:

from tkinter import *
from tkinter import ttk

class Application:
    def __init__(self, master):#Change to game class when combining code
        self.master = master#remove when combining code
        self.frame_Canvas = ttk.Frame(self.master, width = 600, height = 600)
        self.frame_Canvas.pack(side = 'left')
        self.frame_Canvas.pack_propagate(False)
        self.frame_Canvas.grid_propagate(False)
        self.hangman = Canvas(self.frame_Canvas, width = 600, height = 600,
                              background = 'white').pack()
        self.FullName = ttk.Label(self.frame_Canvas, text = "Full Name", background = 'white')#full name will be entered here
        self.FullName.config(font=("TkDefaultFont", 20))
        self.FullName.place(x = 10, y = 10)
        self.frame_Interact = ttk.Frame(self.master, width = 200, height = 600)
        self.frame_Interact.pack(side = 'right')
        self.frame_Interact.pack_propagate(False)
        self.frame_Interact.grid_propagate(False)
        Grid.columnconfigure(self.frame_Interact, 0, weight=1) # NOTE, THIS CHANGED
        self.QuestionLabel = ttk.Label(self.frame_Interact, text = "Question:")
        self.QuestionLabel.config(font=("TkDefaultFont", 20))
        self.QuestionLabel.grid(column = 0, row = 0)
        self.QuestionShow = Text(self.frame_Interact, height=1, width=8)
        self.QuestionShow.config(font=("TkDefaultFont", 20))
        self.QuestionShow.grid(column = 0, row = 1)

def main():
    root = Tk()
    root.wm_title("Hangman")
    Menu = Application(root)
    root.resizable(width=False, height=False)
    root.iconbitmap("windowicon.ico")
    root.mainloop()

if __name__ == "__main__":
    main()

By adding Grid.columnconfigure(self.frame_Interact, 0, weight=1) it will help grid know how to allocate extra space. so that the label will try to take up the whole column. The same goes for rows if you're wondering, you can add Grid.rowconfigure(self.frame_Interact, 0, weight=1) to make the widgets fill the whole row.

And for some improvements to your code, you should change this line:

self.hangman = Canvas(self.frame_Canvas, width = 600, height = 600,
                          background = 'white').pack()

# to
self.hangman = Canvas(self.frame_Canvas, width = 600, height = 600, background = 'white')
self.hangman.pack()

Or else self.hangman will be None, as it is in your code.


答:
Sample Data solution

```<code>'in G2
=A2
'in H2 as an array formula with CSE
=IFERROR(INDEX($B$2:$B$16, MATCH(0, IF($A$2:$A$16=$G2, IF(SIGN(LEN($B$2:$B$16)), COUNTIF($G2:G2, $B$2:$B$16), 1), 1), 0), 1),
 IFERROR(INDEX($C$2:$C$16, MATCH(0, IF($A$2:$A$16=$G2, IF(SIGN(LEN($C$2:$C$16)), COUNTIF($G2:G2, $C$2:$C$16), 1), 1), 0), 1),
 IFERROR(INDEX($D$2:$D$16, MATCH(0, IF($A$2:$A$16=$G2, IF(SIGN(LEN($D$2:$D$16)), COUNTIF($G2:G2, $D$2:$D$16), 1), 1), 0), 1),
 TEXT(,))))
'in G19
=G2
'in H19
=TEXTJOIN(",", TRUE, H2:N2)
</code>```

Fill H2 right then G2:N2 down as appropriate. Fill G19:H19 down to collate the values above. See footnote ¹ if you get a #NAME! error on the TEXTJOIN function.

10K Rows of Data solution

Array formulas chew up calculations exponentially the referenced ranges increase in size. The only way to do this as an array formula is to only reference the rows with Vancouver when you are creating a unique list for Vancouver and only reference the rows with Seattle when you are creating a unique list for Seattle. In other words, don't reference rows 2:10000 for Vancouver when Vancouver's data is in rows 2:6.

Note: you will have to sort your data with column A as the primary key. This operation requires it. Unsorted data (even grouped) will not allow the second MATCH function to locate the terminating row.

The rows of data in column B containing Vancouver in column A can be referenced with this.

```<code>INDEX(B:B, MATCH("vancouver", A:A, 0)):INDEX(B:B, MATCH("vancouver", A:A))
</code>```

Now all you have to do is replace all occurrences of $B$2:$B$16 with the above. Adjust the formula and make the replacements for $C$2:$C$16 and $D$2:$D$16 as well. The bonus is that you can get rid of the check to see IF($A$2:$A$16=$G2, ... since by definition, you are only referencing rows with the appropriate city in column A. Make sure you reference G2 and do not hardcode in Vancouver.

```<code>'in H2 as an array formula with CSE
=IFERROR(INDEX(INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A))), 1), 0)),
 IFERROR(INDEX(INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A))), 1), 0)),
 IFERROR(INDEX(INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A))), 1), 0)),
 TEXT(,))))
</code>```

You should be able to live with the calculation time on that array formula even through 10K rows.

I'm pretty sure that this is as far as native worksheet functions can go. Further improvements would be using variant memory arrays.

Addendum²

There is one further optimization. A worksheet IF only processes the part of the formula that is true. If you look at the names of the cities and only process the array portion of the formula when the city names change, copying directly from above when they are the same you should be able to limit the calculations further.

```<code>'in H2 as an array formula with CSE
=IF($G2=$G1, H1,
    IFERROR(INDEX(INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A))), 1), 0)),
    IFERROR(INDEX(INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A))), 1), 0)),
    IFERROR(INDEX(INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A))), 1), 0)),
    TEXT(,)))))
</code>```

Addendum³

There was a problem with single city entries and this amendment takes care of that.

You may receive a Circular Reference warning with this. Technically, the warning is true but you wil never actually get a circular reference due to the nested IF structure. In other words, the circular reference is only valid when an IF is false. Excel reports this because it does not examine the conditions; only the possibility of a circular reference which technically is true but can never actually occur.

```<code>'in H2 as an array formula with CSE
=IF($G2=$G1, H1, IF(COUNTIF($A:$A, $G2)=1,
    IFERROR(INDEX(INDEX($B:$D, MATCH($G2, $A:$A, 0), 0), MATCH(0, IF(INDEX($B:$D, MATCH($G2, $A:$A, 0), 0)<>"", COUNTIF($G2:G2, INDEX($B:$D, MATCH($G2, $A:$A, 0), 0)), 1), 0)), TEXT(,)),
    IFERROR(INDEX(INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A))), 1), 0)),
    IFERROR(INDEX(INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A))), 1), 0)),
    IFERROR(INDEX(INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A))), 1), 0)),
    TEXT(,))))))
</code>```

¹ If your Excel version does not support the TEXTJOIN function, search this site for [excel][textjoin] to find  alternatives in ragged-length, delimited string concatenation.

Title: Index multiple columns and Match distinct values, returning list of unique values across columns

Body:
Sample Data solution

'in G2
=A2
'in H2 as an array formula with CSE
=IFERROR(INDEX($B$2:$B$16, MATCH(0, IF($A$2:$A$16=$G2, IF(SIGN(LEN($B$2:$B$16)), COUNTIF($G2:G2, $B$2:$B$16), 1), 1), 0), 1),
 IFERROR(INDEX($C$2:$C$16, MATCH(0, IF($A$2:$A$16=$G2, IF(SIGN(LEN($C$2:$C$16)), COUNTIF($G2:G2, $C$2:$C$16), 1), 1), 0), 1),
 IFERROR(INDEX($D$2:$D$16, MATCH(0, IF($A$2:$A$16=$G2, IF(SIGN(LEN($D$2:$D$16)), COUNTIF($G2:G2, $D$2:$D$16), 1), 1), 0), 1),
 TEXT(,))))
'in G19
=G2
'in H19
=TEXTJOIN(",", TRUE, H2:N2)

Fill H2 right then G2:N2 down as appropriate. Fill G19:H19 down to collate the values above. See footnote ¹ if you get a #NAME! error on the TEXTJOIN function.

10K Rows of Data solution

Array formulas chew up calculations exponentially the referenced ranges increase in size. The only way to do this as an array formula is to only reference the rows with Vancouver when you are creating a unique list for Vancouver and only reference the rows with Seattle when you are creating a unique list for Seattle. In other words, don't reference rows 2:10000 for Vancouver when Vancouver's data is in rows 2:6.

Note: you will have to sort your data with column A as the primary key. This operation requires it. Unsorted data (even grouped) will not allow the second MATCH function to locate the terminating row.

The rows of data in column B containing Vancouver in column A can be referenced with this.

INDEX(B:B, MATCH("vancouver", A:A, 0)):INDEX(B:B, MATCH("vancouver", A:A))

Now all you have to do is replace all occurrences of $B$2:$B$16 with the above. Adjust the formula and make the replacements for $C$2:$C$16 and $D$2:$D$16 as well. The bonus is that you can get rid of the check to see IF($A$2:$A$16=$G2, ... since by definition, you are only referencing rows with the appropriate city in column A. Make sure you reference G2 and do not hardcode in Vancouver.

'in H2 as an array formula with CSE
=IFERROR(INDEX(INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A))), 1), 0)),
 IFERROR(INDEX(INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A))), 1), 0)),
 IFERROR(INDEX(INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A))), 1), 0)),
 TEXT(,))))

You should be able to live with the calculation time on that array formula even through 10K rows.

I'm pretty sure that this is as far as native worksheet functions can go. Further improvements would be using variant memory arrays.

Addendum²

There is one further optimization. A worksheet IF only processes the part of the formula that is true. If you look at the names of the cities and only process the array portion of the formula when the city names change, copying directly from above when they are the same you should be able to limit the calculations further.

'in H2 as an array formula with CSE
=IF($G2=$G1, H1,
    IFERROR(INDEX(INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A))), 1), 0)),
    IFERROR(INDEX(INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A))), 1), 0)),
    IFERROR(INDEX(INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A))), 1), 0)),
    TEXT(,)))))

Addendum³

There was a problem with single city entries and this amendment takes care of that.

You may receive a Circular Reference warning with this. Technically, the warning is true but you wil never actually get a circular reference due to the nested IF structure. In other words, the circular reference is only valid when an IF is false. Excel reports this because it does not examine the conditions; only the possibility of a circular reference which technically is true but can never actually occur.

'in H2 as an array formula with CSE
=IF($G2=$G1, H1, IF(COUNTIF($A:$A, $G2)=1,
    IFERROR(INDEX(INDEX($B:$D, MATCH($G2, $A:$A, 0), 0), MATCH(0, IF(INDEX($B:$D, MATCH($G2, $A:$A, 0), 0)<>"", COUNTIF($G2:G2, INDEX($B:$D, MATCH($G2, $A:$A, 0), 0)), 1), 0)), TEXT(,)),
    IFERROR(INDEX(INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($B:$B, MATCH($G2, $A:$A, 0)):INDEX($B:$B, MATCH($G2, $A:$A))), 1), 0)),
    IFERROR(INDEX(INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($C:$C, MATCH($G2, $A:$A, 0)):INDEX($C:$C, MATCH($G2, $A:$A))), 1), 0)),
    IFERROR(INDEX(INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A)), MATCH(0, IF(SIGN(LEN(INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A)))), COUNTIF($G2:G2, INDEX($D:$D, MATCH($G2, $A:$A, 0)):INDEX($D:$D, MATCH($G2, $A:$A))), 1), 0)),
    TEXT(,))))))

¹ If your Excel version does not support the TEXTJOIN function, search this site for [excel][textjoin] to find  alternatives in ragged-length, delimited string concatenation.


问:
PHP print to wireless printer
I am trying to print using PHP to a wireless printer. I googled and seems that php_printer.dll might work but I am unable to achieve the print after multiple attempts. I included the DLL file inside the extension_dir inside php.ini and added the line extension=php_printer.dll but it still did not load.

Is there any other ways for me to print a PDF to a wireless printer from PHP?

答:
I think I should post my solution here which might be helpful to others.

After a bit of research, I decided to print by calling an application called "Foxit Reader" using shell_exec(). But you will need to set the correct default printer so that "Foxit Reader" will print to the printer accordingly.

The reason for using "Foxit Reader" is because it does not leave the application running in the background after printing unlike Adobe Reader which will just leave a process running after printing.

Title: PHP print to wireless printer