问:
Where can I find my credentials for putting in a SQL server connection string?
I am currently using asp.net mvc5 where I am following a tutorial. However I have got to a point of the tutorial where it asks me to enter in a connection string </p>

```<code><add name="CountryConnectionString" connectionString="data source=server name,1436;database=Sample;user id=sa;password=123456;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>
</code>```

<p>It asks to enter my own credentials but unfortunately I don't think I have ever set a username and password is there a way of finding out? Apologies if this is a silly question. </p>

答:
You can get the solution with the use of integrated security like the below code

```<code><add name="ConnectionStringName"
    providerName="System.Data.SqlClient"
    connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True"/>
</code>```

Integrated Security (synonym: Trusted_Connection)

This setting specifies whether the connection should use the user ID and password in the connection string to log on to the SQL Server instance, or the current Windows account credentials should be used for authentication:

True means use Windows integrated security to log in to SQL Server, even if the connection string includes User ID and Password settings.

False means use SQL Server security to log in by using the User ID and Password values in the connection string, and raise an exception if they are not present.

SSPI (Security Support Provider Interface) means use Windows Security if User ID and Password are absent, and use SQL Server security if they are present.

Useful link:https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx

Body:
I am currently using asp.net mvc5 where I am following a tutorial. However I have got to a point of the tutorial where it asks me to enter in a connection string

<add name="CountryConnectionString" connectionString="data source=server name,1436;database=Sample;user id=sa;password=123456;MultipleActiveResultSets=True" providerName="System.Data.SqlClient"/>

It asks to enter my own credentials but unfortunately I don't think I have ever set a username and password is there a way of finding out? Apologies if this is a silly question.

Body:
You can get the solution with the use of integrated security like the below code

<add name="ConnectionStringName"
    providerName="System.Data.SqlClient"
    connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True"/>

Integrated Security (synonym: Trusted_Connection)

This setting specifies whether the connection should use the user ID and password in the connection string to log on to the SQL Server instance, or the current Windows account credentials should be used for authentication:

True means use Windows integrated security to log in to SQL Server, even if the connection string includes User ID and Password settings.

False means use SQL Server security to log in by using the User ID and Password values in the connection string, and raise an exception if they are not present.

SSPI (Security Support Provider Interface) means use Windows Security if User ID and Password are absent, and use SQL Server security if they are present.

Useful link:https://msdn.microsoft.com/en-us/library/jj653752(v=vs.110).aspx


来源: stackexchange

问:
How come my count() passes evaluation?
I am fairly new at SQL and I am trying to create a query that tries to determine in which countries only 3 specific languages (spanish,italian,german) are spoken and no other languages.

```<code>select country
from langusage
group by country
having count(case when language in ('spanish','german','italian') then 1 else 5 end)=3
</code>```

The output are all countries that have at least 1 of the aforementioned languages . How come they pass the '=3' test?

答:
The reason is that count(1) = count(5).  count() counts the number of non-NULL values.

You intend sum():

```<code>select country
from langusage
group by country
having sum(case when iso in ('spanish', 'german', 'italian') then 1 else 5 end) = 3
</code>```

ContentLicense: CC BY-SA 3.0

Title: How come my count() passes evaluation?

Body:
I am fairly new at SQL and I am trying to create a query that tries to determine in which countries only 3 specific languages (spanish,italian,german) are spoken and no other languages.

select country
from langusage
group by country
having count(case when language in ('spanish','german','italian') then 1 else 5 end)=3

The output are all countries that have at least 1 of the aforementioned languages . How come they pass the '=3' test?

Body:
The reason is that count(1) = count(5).  count() counts the number of non-NULL values.

You intend sum():

select country
from langusage
group by country
having sum(case when iso in ('spanish', 'german', 'italian') then 1 else 5 end) = 3


问:
Aws Base64 S3 http post bucket
I am trying to recreate the example from http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html

And the first step is to convert the policy to base64. So in this example

```<code>{ "expiration": "2015-12-30T12:00:00.000Z",
  "conditions": [
    {"bucket": "sigv4examplebucket"},
    ["starts-with", "$key", "user/user1/"],
    {"acl": "public-read"},
    {"success_action_redirect": "http://sigv4examplebucket.s3.amazonaws.com/successful_upload.html"},
    ["starts-with", "$Content-Type", "image/"],
    {"x-amz-meta-uuid": "14365123651274"},
    {"x-amz-server-side-encryption": "AES256"},
    ["starts-with", "$x-amz-meta-tag", ""],

    {"x-amz-credential": "AKIAIOSFODNN7EXAMPLE/20151229/us-east-1/s3/aws4_request"},
    {"x-amz-algorithm": "AWS4-HMAC-SHA256"},
    {"x-amz-date": "20151229T000000Z" }
  ]
}
</code>```

They say in base64 this should be

```<code>eyAiZXhwaXJhdGlvbiI6ICIyMDE1LTEyLTMwVDEyOjAwOjAwLjAwMFoiLA0KICAiY29uZGl0aW9ucyI6IFsNCiAgICB7ImJ1Y2tldCI6ICJzaWd2NGV4YW1wbGVidWNrZXQifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci91c2VyMS8iXSwNCiAgICB7ImFjbCI6ICJwdWJsaWMtcmVhZCJ9LA0KICAgIHsic3VjY2Vzc19hY3Rpb25fcmVkaXJlY3QiOiAiaHR0cDovL3NpZ3Y0ZXhhbXBsZWJ1Y2tldC5zMy5hbWF6b25hd3MuY29tL3N1Y2Nlc3NmdWxfdXBsb2FkLmh0bWwifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiaW1hZ2UvIl0sDQogICAgeyJ4LWFtei1tZXRhLXV1aWQiOiAiMTQzNjUxMjM2NTEyNzQifSwNCiAgICB7IngtYW16LXNlcnZlci1zaWRlLWVuY3J5cHRpb24iOiAiQUVTMjU2In0sDQogICAgWyJzdGFydHMtd2l0aCIsICIkeC1hbXotbWV0YS10YWciLCAiIl0sDQoNCiAgICB7IngtYW16LWNyZWRlbnRpYWwiOiAiQUtJQUlPU0ZPRE5ON0VYQU1QTEUvMjAxNTEyMjkvdXMtZWFzdC0xL3MzL2F3czRfcmVxdWVzdCJ9LA0KICAgIHsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwNCiAgICB7IngtYW16LWRhdGUiOiAiMjAxNTEyMjlUMDAwMDAwWiIgfQ0KICBdDQp9
</code>```

Using the following java code I am expecting to get the same

```<code>   String policy_document = "{ \"expiration\": \"2015-12-30T12:00:00.000Z\",\n" +
            "  \"conditions\": [\n" +
            "    {\"bucket\": \"sigv4examplebucket\"},\n" +
            "    [\"starts-with\", \"$key\", \"user/user1/\"],\n" +
            "    {\"acl\": \"public-read\"},\n" +
            "    {\"success_action_redirect\": \"http://sigv4examplebucket.s3.amazonaws.com/successful_upload.html\"},\n" +
            "    [\"starts-with\", \"$Content-Type\", \"image/\"],\n" +
            "    {\"x-amz-meta-uuid\": \"14365123651274\"},\n" +
            "    {\"x-amz-server-side-encryption\": \"AES256\"},\n" +
            "    [\"starts-with\", \"$x-amz-meta-tag\", \"\"],\n" +
            "\n" +
            "    {\"x-amz-credential\": \"AKIAIOSFODNN7EXAMPLE/20151229/us-east-1/s3/aws4_request\"},\n" +
            "    {\"x-amz-algorithm\": \"AWS4-HMAC-SHA256\"},\n" +
            "    {\"x-amz-date\": \"20151229T000000Z\" }\n" +
            "  ]\n" +
            "}";
    final byte[] authBytes = policy_document.getBytes(StandardCharsets.UTF_8);
    final String encoded = Base64.getEncoder().encodeToString(authBytes);

    System.out.println("base64 " + encoded);
</code>```

but I am getting (which is different)

```<code>eyAiZXhwaXJhdGlvbiI6ICIyMDE1LTEyLTMwVDEyOjAwOjAwLjAwMFoiLAogICJjb25kaXRpb25zIjogWwogICAgeyJidWNrZXQiOiAic2lndjRleGFtcGxlYnVja2V0In0sCiAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci91c2VyMS8iXSwKICAgIHsiYWNsIjogInB1YmxpYy1yZWFkIn0sCiAgICB7InN1Y2Nlc3NfYWN0aW9uX3JlZGlyZWN0IjogImh0dHA6Ly9zaWd2NGV4YW1wbGVidWNrZXQuczMuYW1hem9uYXdzLmNvbS9zdWNjZXNzZnVsX3VwbG9hZC5odG1sIn0sCiAgICBbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiaW1hZ2UvIl0sCiAgICB7IngtYW16LW1ldGEtdXVpZCI6ICIxNDM2NTEyMzY1MTI3NCJ9LAogICAgeyJ4LWFtei1zZXJ2ZXItc2lkZS1lbmNyeXB0aW9uIjogIkFFUzI1NiJ9LAogICAgWyJzdGFydHMtd2l0aCIsICIkeC1hbXotbWV0YS10YWciLCAiIl0sCgogICAgeyJ4LWFtei1jcmVkZW50aWFsIjogIkFLSUFJT1NGT0ROTjdFWEFNUExFLzIwMTUxMjI5L3VzLWVhc3QtMS9zMy9hd3M0X3JlcXVlc3QifSwKICAgIHsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwKICAgIHsieC1hbXotZGF0ZSI6ICIyMDE1MTIyOVQwMDAwMDBaIiB9CiAgXQp9
</code>```

Any ideas? I've literally copied and pasted the policy from their page? Without this I can not recreate the example. When I decode both signatures using https://www.base64decode.org/ they return the same policy?? So what's wrong?

答:
Try using this

        final String policy_document = "{ \"expiration\": \"2015-12-30T12:00:00.000Z\",\r\n" + "  \"conditions\": [\r\n"
                + "    {\"bucket\": \"sigv4examplebucket\"},\r\n"
                + "    [\"starts-with\", \"$key\", \"user/user1/\"],\r\n" + "    {\"acl\": \"public-read\"},\r\n"
                + "    {\"success_action_redirect\": \"http://sigv4examplebucket.s3.amazonaws.com/successful_upload.html\"},\r\n"
                + "    [\"starts-with\", \"$Content-Type\", \"image/\"],\r\n"
                + "    {\"x-amz-meta-uuid\": \"14365123651274\"},\r\n"
                + "    {\"x-amz-server-side-encryption\": \"AES256\"},\r\n"
                + "    [\"starts-with\", \"$x-amz-meta-tag\", \"\"],\r\n" + "\r\n"
                + "    {\"x-amz-credential\": \"AKIAIOSFODNN7EXAMPLE/20151229/us-east-1/s3/aws4_request\"},\r\n"
                + "    {\"x-amz-algorithm\": \"AWS4-HMAC-SHA256\"},\r\n"
                + "    {\"x-amz-date\": \"20151229T000000Z\" }\r\n" + "  ]\r\n" + "}";

After I replaced all \n with \r\n, I got the same base64 encoded value as the one provided by the AWS documentation page.

Title: Aws Base64 S3 http post bucket

Body:
I am trying to recreate the example from http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html

And the first step is to convert the policy to base64. So in this example

{ "expiration": "2015-12-30T12:00:00.000Z",
  "conditions": [
    {"bucket": "sigv4examplebucket"},
    ["starts-with", "$key", "user/user1/"],
    {"acl": "public-read"},
    {"success_action_redirect": "http://sigv4examplebucket.s3.amazonaws.com/successful_upload.html"},
    ["starts-with", "$Content-Type", "image/"],
    {"x-amz-meta-uuid": "14365123651274"},
    {"x-amz-server-side-encryption": "AES256"},
    ["starts-with", "$x-amz-meta-tag", ""],

    {"x-amz-credential": "AKIAIOSFODNN7EXAMPLE/20151229/us-east-1/s3/aws4_request"},
    {"x-amz-algorithm": "AWS4-HMAC-SHA256"},
    {"x-amz-date": "20151229T000000Z" }
  ]
}

They say in base64 this should be

eyAiZXhwaXJhdGlvbiI6ICIyMDE1LTEyLTMwVDEyOjAwOjAwLjAwMFoiLA0KICAiY29uZGl0aW9ucyI6IFsNCiAgICB7ImJ1Y2tldCI6ICJzaWd2NGV4YW1wbGVidWNrZXQifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci91c2VyMS8iXSwNCiAgICB7ImFjbCI6ICJwdWJsaWMtcmVhZCJ9LA0KICAgIHsic3VjY2Vzc19hY3Rpb25fcmVkaXJlY3QiOiAiaHR0cDovL3NpZ3Y0ZXhhbXBsZWJ1Y2tldC5zMy5hbWF6b25hd3MuY29tL3N1Y2Nlc3NmdWxfdXBsb2FkLmh0bWwifSwNCiAgICBbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiaW1hZ2UvIl0sDQogICAgeyJ4LWFtei1tZXRhLXV1aWQiOiAiMTQzNjUxMjM2NTEyNzQifSwNCiAgICB7IngtYW16LXNlcnZlci1zaWRlLWVuY3J5cHRpb24iOiAiQUVTMjU2In0sDQogICAgWyJzdGFydHMtd2l0aCIsICIkeC1hbXotbWV0YS10YWciLCAiIl0sDQoNCiAgICB7IngtYW16LWNyZWRlbnRpYWwiOiAiQUtJQUlPU0ZPRE5ON0VYQU1QTEUvMjAxNTEyMjkvdXMtZWFzdC0xL3MzL2F3czRfcmVxdWVzdCJ9LA0KICAgIHsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwNCiAgICB7IngtYW16LWRhdGUiOiAiMjAxNTEyMjlUMDAwMDAwWiIgfQ0KICBdDQp9

Using the following java code I am expecting to get the same

   String policy_document = "{ \"expiration\": \"2015-12-30T12:00:00.000Z\",\n" +
            "  \"conditions\": [\n" +
            "    {\"bucket\": \"sigv4examplebucket\"},\n" +
            "    [\"starts-with\", \"$key\", \"user/user1/\"],\n" +
            "    {\"acl\": \"public-read\"},\n" +
            "    {\"success_action_redirect\": \"http://sigv4examplebucket.s3.amazonaws.com/successful_upload.html\"},\n" +
            "    [\"starts-with\", \"$Content-Type\", \"image/\"],\n" +
            "    {\"x-amz-meta-uuid\": \"14365123651274\"},\n" +
            "    {\"x-amz-server-side-encryption\": \"AES256\"},\n" +
            "    [\"starts-with\", \"$x-amz-meta-tag\", \"\"],\n" +
            "\n" +
            "    {\"x-amz-credential\": \"AKIAIOSFODNN7EXAMPLE/20151229/us-east-1/s3/aws4_request\"},\n" +
            "    {\"x-amz-algorithm\": \"AWS4-HMAC-SHA256\"},\n" +
            "    {\"x-amz-date\": \"20151229T000000Z\" }\n" +
            "  ]\n" +
            "}";
    final byte[] authBytes = policy_document.getBytes(StandardCharsets.UTF_8);
    final String encoded = Base64.getEncoder().encodeToString(authBytes);

    System.out.println("base64 " + encoded);

but I am getting (which is different)

eyAiZXhwaXJhdGlvbiI6ICIyMDE1LTEyLTMwVDEyOjAwOjAwLjAwMFoiLAogICJjb25kaXRpb25zIjogWwogICAgeyJidWNrZXQiOiAic2lndjRleGFtcGxlYnVja2V0In0sCiAgICBbInN0YXJ0cy13aXRoIiwgIiRrZXkiLCAidXNlci91c2VyMS8iXSwKICAgIHsiYWNsIjogInB1YmxpYy1yZWFkIn0sCiAgICB7InN1Y2Nlc3NfYWN0aW9uX3JlZGlyZWN0IjogImh0dHA6Ly9zaWd2NGV4YW1wbGVidWNrZXQuczMuYW1hem9uYXdzLmNvbS9zdWNjZXNzZnVsX3VwbG9hZC5odG1sIn0sCiAgICBbInN0YXJ0cy13aXRoIiwgIiRDb250ZW50LVR5cGUiLCAiaW1hZ2UvIl0sCiAgICB7IngtYW16LW1ldGEtdXVpZCI6ICIxNDM2NTEyMzY1MTI3NCJ9LAogICAgeyJ4LWFtei1zZXJ2ZXItc2lkZS1lbmNyeXB0aW9uIjogIkFFUzI1NiJ9LAogICAgWyJzdGFydHMtd2l0aCIsICIkeC1hbXotbWV0YS10YWciLCAiIl0sCgogICAgeyJ4LWFtei1jcmVkZW50aWFsIjogIkFLSUFJT1NGT0ROTjdFWEFNUExFLzIwMTUxMjI5L3VzLWVhc3QtMS9zMy9hd3M0X3JlcXVlc3QifSwKICAgIHsieC1hbXotYWxnb3JpdGhtIjogIkFXUzQtSE1BQy1TSEEyNTYifSwKICAgIHsieC1hbXotZGF0ZSI6ICIyMDE1MTIyOVQwMDAwMDBaIiB9CiAgXQp9

Any ideas? I've literally copied and pasted the policy from their page? Without this I can not recreate the example. When I decode both signatures using https://www.base64decode.org/ they return the same policy?? So what's wrong?


问:
Efficiently Querying a Large Database
I have a blacklist stored in a table that contains approximately 1.5 billion records. My goal is to load the records into a HashSet so my program can later check if domain names are blacklisted (this is not the entire functionality of the program, just a piece). I currently have the following code to load the records:

```<code>    HashSet<String> list = new HashSet<String>();
    try {
        Statement stmt = conn.createStatement();
        stmt.setFetchSize(100000000);
        try {
            ResultSet rs = stmt.executeQuery("SELECT DNname FROM " + table);
            try {
                while (rs.next()) {
                    list.add(rs.getString(1));
                }
            } finally {
                rs.close();
            }
        } finally {
            stmt.close();
        }
    } catch (SQLException e) {
        System.out.println("Error loading blacklist from DB");
        e.printStackTrace();
    }
</code>```

However, this takes incredibly long to complete. Is there a more efficient way to accomplish my goal?

答:
"this takes incredibly long to complete" - what takes long to complete? How long does the query take if you run it from a DB client console?

You've not provided any information on what indexes are present in the table, so that's something you'll want to look into.

setFetchSize is a hint to the JDBC driver - you really want a WHERE clause where you can limit the records fetched. Oracle DB can do that using ROWNUM; for other DBs, you'll have to look for yourself.

That said, I concur with @ScaryWombat; keeping 1.5 billion records in memory is not scalable design. An alternative would to be build up a client cache by caching the database look up for each domain; in all practicality, the cache will have fewer than 1.5 billion entries.

Title: Efficiently Querying a Large Database

Body:
I have a blacklist stored in a table that contains approximately 1.5 billion records. My goal is to load the records into a HashSet so my program can later check if domain names are blacklisted (this is not the entire functionality of the program, just a piece). I currently have the following code to load the records:

    HashSet<String> list = new HashSet<String>();
    try {
        Statement stmt = conn.createStatement();
        stmt.setFetchSize(100000000);
        try {
            ResultSet rs = stmt.executeQuery("SELECT DNname FROM " + table);
            try {
                while (rs.next()) {
                    list.add(rs.getString(1));
                }
            } finally {
                rs.close();
            }
        } finally {
            stmt.close();
        }
    } catch (SQLException e) {
        System.out.println("Error loading blacklist from DB");
        e.printStackTrace();
    }

However, this takes incredibly long to complete. Is there a more efficient way to accomplish my goal?


问:
Angular 2 Quickstart: unexpected token <
I am trying to set up angular 2 according the quickstart found at http://angular.io. I have copied every file exactly as described in the guide, but when I run npm start and a browser tab opens, I get the "Loading..." with the following error in the console:

```<code>Uncaught SyntaxError: Unexpected token <                        (program):1
     __exec @ system.src.js:1374
Uncaught SyntaxError: Unexpected token <          angular2-polyfills.js:138
    Evaluating http://localhost:3000/app/boot
    Error loading http://localhost:3000/app/boot
</code>```

This is my app.component.ts:

```<code>import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: `<h1>My First Angular 2 App</h1>`
})
export class AppComponent {

}
</code>```

My boot.ts:

```<code>import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';

bootstrap(AppComponent);
</code>```

My index.html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Angular 2 Quick Start</title>

    <script src="node_modules/es6-shim/es6-shim.js"></script>
    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <script src="node_modules/rxjs/bundles/Rx.js"></script>
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script>

    <script>
    System.config({
        packages: {
            format: 'register',
            defaultExtension: 'js'
        }
    });

    System.import('app/boot')
        .then(null, console.error.bind(console));
    </script>
</head>
<body>
    <my-app>Loading...</my-app>
</body>
</html>
</code>```

My package.json:

```<code>{
    "name": "angular2-quickstart",
    "version": "0.1.0",
    "scripts": {
        "tsc": "tsc",
        "tsc:w": "tsc -w",
        "lite": "lite-server",
        "start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
    },
    "license": "MIT",
    "dependencies": {
        "angular2": "2.0.0-beta.0",
        "systemjs": "0.19.6",
        "es6-promise": "^3.0.2",
        "es6-shim": "^0.33.3",
        "reflect-metadata": "0.1.2",
        "rxjs": "5.0.0-beta.0",
        "zone.js": "0.5.10"
    },
    "devDependencies": {
        "concurrently": "^1.0.0",
        "lite-server": "^1.3.1",
        "typescript": "^1.7.3"
    }
}
</code>```

And finally my tsconfig.json:

```<code>{
    "compilerOptions": {
        "target": "ES5",
        "module": "system",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false
    },
    "exclude": [
        "node_modules"
    ]
}
</code>```

答:
The primary cause of this issue is that the file you are trying to import is an html file, not a js file. You can see this by using the network tab in Chrome to have a look at the file it actually imported.

My issue wasn't solved by the methods above. For me, this happened because I had routed all default routes through to the index.html page, which is how I get Angular deep linking working in Visual Studio Enterprise. When I requested a file without the extension, and it couldn't find that file, it would serve the default index.html page, which would start with a < character, and fail.

The giveaway for me was that when I put the full path to the exact file, it would work.

Anyhow, to fix this, I had to add an Ignore route for the node_modules folder in my RouteConfig.cs file:

```<code>public static void RegisterRoutes(RouteCollection routes)
{
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
   routes.IgnoreRoute("node_modules/{*pathInfo}");

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to set up angular 2 according the quickstart found at http://angular.io. I have copied every file exactly as described in the guide, but when I run npm start and a browser tab opens, I get the "Loading..." with the following error in the console:

Uncaught SyntaxError: Unexpected token <                        (program):1
     __exec @ system.src.js:1374
Uncaught SyntaxError: Unexpected token <          angular2-polyfills.js:138
    Evaluating http://localhost:3000/app/boot
    Error loading http://localhost:3000/app/boot

This is my app.component.ts:

import {Component} from 'angular2/core';

@Component({
    selector: 'my-app',
    template: `<h1>My First Angular 2 App</h1>`
})
export class AppComponent {

}

My boot.ts:

import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';

bootstrap(AppComponent);

My index.html:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Angular 2 Quick Start</title>

    <my-app>Loading...</my-app>

My package.json:

{
    "name": "angular2-quickstart",
    "version": "0.1.0",
    "scripts": {
        "tsc": "tsc",
        "tsc:w": "tsc -w",
        "lite": "lite-server",
        "start": "concurrent \"npm run tsc:w\" \"npm run lite\" "
    },
    "license": "MIT",
    "dependencies": {
        "angular2": "2.0.0-beta.0",
        "systemjs": "0.19.6",
        "es6-promise": "^3.0.2",
        "es6-shim": "^0.33.3",
        "reflect-metadata": "0.1.2",
        "rxjs": "5.0.0-beta.0",
        "zone.js": "0.5.10"
    },
    "devDependencies": {
        "concurrently": "^1.0.0",
        "lite-server": "^1.3.1",
        "typescript": "^1.7.3"
    }
}

And finally my tsconfig.json:

{
    "compilerOptions": {
        "target": "ES5",
        "module": "system",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "removeComments": false,
        "noImplicitAny": false
    },
    "exclude": [
        "node_modules"
    ]
}

Body:
The primary cause of this issue is that the file you are trying to import is an html file, not a js file. You can see this by using the network tab in Chrome to have a look at the file it actually imported.

My issue wasn't solved by the methods above. For me, this happened because I had routed all default routes through to the index.html page, which is how I get Angular deep linking working in Visual Studio Enterprise. When I requested a file without the extension, and it couldn't find that file, it would serve the default index.html page, which would start with a < character, and fail.

The giveaway for me was that when I put the full path to the exact file, it would work.

Anyhow, to fix this, I had to add an Ignore route for the node_modules folder in my RouteConfig.cs file:

public static void RegisterRoutes(RouteCollection routes)
{
   routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
   routes.IgnoreRoute("node_modules/{*pathInfo}");

}


问:
Javafx Button size, EmptyBorder, and Read txt File into TextArea
I am trying to switch to javafx instead of swing but it has been a bit bumpy trying to find methods that do the exact tasks.

I am trying to get the buttons width to fill the entire scene and adjusts accordingly when you adjust the scene size.

Get a small empty border around text area and buttons.

Getting a method that reads a plain text file and replaces the current Text Area (not append).

```<code>package gui;

mport javafx.application.Application;
mport javafx.scene.Scene;
mport javafx.scene.control.Button;
mport javafx.stage.Stage;
mport javafx.scene.layout.*;
mport javafx.scene.control.TextArea;

public class Main extends Application{

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("TextArea Experiment 1");

        TextArea textArea = new TextArea();
        // Which TextArea method would I call to set a plain
        // text file into the text area ?
        BorderPane border = new BorderPane();
        border.setCenter(textArea);
        //border.setBorder(new EmptyBorder(10,10,10,10));
        // Is there a method like this in JavaFx ?
        GridPane grid = new GridPane();
        border.setBottom(grid);

        double screensize = border.getMaxWidth();
        Button option1 = new Button("Button 1");
        Button option2 = new Button("Button 2");
        Button option3 = new Button("Button 3");
        // how can I get the buttons to be max scene size and
        //adjust dynamically to scene dimensions ?
        option1.setMaxSize(Double.MAX_VALUE,Double.MAX_VALUE);
        //option1.setPrefWidth(Double.MAX_VALUE);
        System.out.println(screensize);
        grid.add(option1, 0,1);
        grid.add(option2,0,2);
        grid.add(option3,0,3);

        Scene scene = new Scene(border, 200, 100);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
           Application.launch(args);
    }
}
</code>```

答:
Rewrite your question and only ask the question for this answer. You can then ask the other questions on their own thread.

```<code>    GridPane grid = new GridPane();
    grid.setMaxWidth(Double.MAX_VALUE);//Make sure the GridPane MaxWidth is set to MAX_VALUE. you can use grid.gridLinesVisibleProperty().set(true); to get an idea of the GRIDPANES current borders

    border.setBottom(grid);
    grid.gridLinesVisibleProperty().set(true);
    Button option1 = new Button("Button 1");
    option1.setMaxWidth(Double.MAX_VALUE);//Set button one MaxWidth to MAX_VALUE

    Button option2 = new Button("Button 2");
    option2.setMaxWidth(Double.MAX_VALUE);//Set button two MaxWidth to MAX_VALUE

    Button option3 = new Button("Button 3");
    option3.setMaxWidth(Double.MAX_VALUE);//Set button three MaxWidth to MAX_VALUE

    //Add ColumnConstraints and set the width to 100%.
    ColumnConstraints columnConstraint = new ColumnConstraints();
    columnConstraint.setPercentWidth(100);
    grid.getColumnConstraints().add(0, columnConstraint);

    grid.add(option1, 0, 1);
    grid.add(option2, 0, 2);
    grid.add(option3, 0, 3);
</code>```

Body:
I am trying to switch to javafx instead of swing but it has been a bit bumpy trying to find methods that do the exact tasks.

I am trying to get the buttons width to fill the entire scene and adjusts accordingly when you adjust the scene size.

Get a small empty border around text area and buttons.

Getting a method that reads a plain text file and replaces the current Text Area (not append).

package gui;

mport javafx.application.Application;
mport javafx.scene.Scene;
mport javafx.scene.control.Button;
mport javafx.stage.Stage;
mport javafx.scene.layout.*;
mport javafx.scene.control.TextArea;

public class Main extends Application{

    @Override
    public void start(Stage primaryStage) throws Exception {
        primaryStage.setTitle("TextArea Experiment 1");

        TextArea textArea = new TextArea();
        // Which TextArea method would I call to set a plain
        // text file into the text area ?
        BorderPane border = new BorderPane();
        border.setCenter(textArea);
        //border.setBorder(new EmptyBorder(10,10,10,10));
        // Is there a method like this in JavaFx ?
        GridPane grid = new GridPane();
        border.setBottom(grid);

        double screensize = border.getMaxWidth();
        Button option1 = new Button("Button 1");
        Button option2 = new Button("Button 2");
        Button option3 = new Button("Button 3");
        // how can I get the buttons to be max scene size and
        //adjust dynamically to scene dimensions ?
        option1.setMaxSize(Double.MAX_VALUE,Double.MAX_VALUE);
        //option1.setPrefWidth(Double.MAX_VALUE);
        System.out.println(screensize);
        grid.add(option1, 0,1);
        grid.add(option2,0,2);
        grid.add(option3,0,3);

        Scene scene = new Scene(border, 200, 100);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
           Application.launch(args);
    }
}

Body:
Rewrite your question and only ask the question for this answer. You can then ask the other questions on their own thread.

    GridPane grid = new GridPane();
    grid.setMaxWidth(Double.MAX_VALUE);//Make sure the GridPane MaxWidth is set to MAX_VALUE. you can use grid.gridLinesVisibleProperty().set(true); to get an idea of the GRIDPANES current borders

    border.setBottom(grid);
    grid.gridLinesVisibleProperty().set(true);
    Button option1 = new Button("Button 1");
    option1.setMaxWidth(Double.MAX_VALUE);//Set button one MaxWidth to MAX_VALUE

    Button option2 = new Button("Button 2");
    option2.setMaxWidth(Double.MAX_VALUE);//Set button two MaxWidth to MAX_VALUE

    Button option3 = new Button("Button 3");
    option3.setMaxWidth(Double.MAX_VALUE);//Set button three MaxWidth to MAX_VALUE

    //Add ColumnConstraints and set the width to 100%.
    ColumnConstraints columnConstraint = new ColumnConstraints();
    columnConstraint.setPercentWidth(100);
    grid.getColumnConstraints().add(0, columnConstraint);

    grid.add(option1, 0, 1);
    grid.add(option2, 0, 2);
    grid.add(option3, 0, 3);


问:
Groupby one column and find max (absolute) value of difference of other two columns in pandas
I have a dataframe with about 20 columns, but I need groupby one columns called ID and calculate difference of, let's called them, value1 and value 2  columns.
Example df:

```<code>ID  value1   value2
1     3         2
1     6         2
2     6         1
3     5         8
4     7         2
4     3         2
</code>```

Desired output:

```<code>ID  value1   value2  maxabs
1     3         2      4
1     6         2      4
2     6         1      5
3     5         8      3
4     7         2      5
4     3         2      5
</code>```

I've tried simply with this:

```<code>df['maxabs'] = df.groupby(['ID'])[(df['value1'] - df['value2'])].abs().idxmax()
</code>```

Error said that columns are not found and printed me a lot of 'nan'. Columns are there, surely. Maybe I need to add when both values are 'nan' to print 'nan;
But not sure that I even hit the direction.

答:
Switch the order of your calculation; Calculate the difference between value1 and value2 firstly, and then group by ID and calculate max with transform:

```<code>df['maxabs'] = df.value1.sub(df.value2).abs().groupby(df.ID).transform('max')

df
#  ID   value1  value2  maxabs
#0  1        3       2       4
#1  1        6       2       4
#2  2        6       1       5
#3  3        5       8       3
#4  4        7       2       5
#5  4        3       2       5
</code>```

Body:
I have a dataframe with about 20 columns, but I need groupby one columns called ID and calculate difference of, let's called them, value1 and value 2  columns.
Example df:

ID  value1   value2
1     3         2
1     6         2
2     6         1
3     5         8
4     7         2
4     3         2

Desired output:

ID  value1   value2  maxabs
1     3         2      4
1     6         2      4
2     6         1      5
3     5         8      3
4     7         2      5
4     3         2      5

I've tried simply with this:

df['maxabs'] = df.groupby(['ID'])[(df['value1'] - df['value2'])].abs().idxmax()

Error said that columns are not found and printed me a lot of 'nan'. Columns are there, surely. Maybe I need to add when both values are 'nan' to print 'nan;
But not sure that I even hit the direction.

Body:
Switch the order of your calculation; Calculate the difference between value1 and value2 firstly, and then group by ID and calculate max with transform:

df['maxabs'] = df.value1.sub(df.value2).abs().groupby(df.ID).transform('max')

df
#  ID   value1  value2  maxabs
#0  1        3       2       4
#1  1        6       2       4
#2  2        6       1       5
#3  3        5       8       3
#4  4        7       2       5
#5  4        3       2       5


问:
OrderBy in SQL Server with custom "max" integer
I have table in SQL Server which contains a sort column of integers. All values in the column are positive. I want to sort the table such that I chose a "max" value (like 3) and all values are returned decreasing relative to 3. The "descending" order doesn't actually matter much as long as each item in the database is listed.

Database example:

```<code>Value SortColumn
A     1
B     5
C     4
D     3
E     0
F     2
</code>```

Desired output (with 3 as "max"):

```<code>Value SortColumn
D        3
C        4
B        5
E        0
A        1
F        2
</code>```

It seems that this similar post might be in the right direction, but it's not quite what I want....

答:
I've tested solution by Tim and Gordon but the result is not matching with what you want.

My solution is very long though. have a look:

```<code>DECLARE @table TABLE (Value CHAR,SortColumn INT)
INSERT INTO @table VALUES ('A',1),('B',5),('C',4),('D',3),('E',0),('F',2)

DECLARE @max INT=3;

;WITH CTE AS(
SELECT 1-ROW_NUMBER() OVER (ORDER BY SortColumn DESC) RN, * FROM @table WHERE SortColumn >=@max
UNION
SELECT ROW_NUMBER() OVER (ORDER BY SortColumn) RN,* FROM @table WHERE SortColumn <@max
)
SELECT Value,SortColumn FROM CTE ORDER BY RN
</code>```

and output is:

Body:
I have table in SQL Server which contains a sort column of integers. All values in the column are positive. I want to sort the table such that I chose a "max" value (like 3) and all values are returned decreasing relative to 3. The "descending" order doesn't actually matter much as long as each item in the database is listed.

Database example:

Value SortColumn
A     1
B     5
C     4
D     3
E     0
F     2

Desired output (with 3 as "max"):

Value SortColumn
D        3
C        4
B        5
E        0
A        1
F        2

It seems that this similar post might be in the right direction, but it's not quite what I want....

Body:
I've tested solution by Tim and Gordon but the result is not matching with what you want.

My solution is very long though. have a look:

DECLARE @table TABLE (Value CHAR,SortColumn INT)
INSERT INTO @table VALUES ('A',1),('B',5),('C',4),('D',3),('E',0),('F',2)

DECLARE @max INT=3;

;WITH CTE AS(
SELECT 1-ROW_NUMBER() OVER (ORDER BY SortColumn DESC) RN, * FROM @table WHERE SortColumn >=@max
UNION
SELECT ROW_NUMBER() OVER (ORDER BY SortColumn) RN,* FROM @table WHERE SortColumn <@max
)
SELECT Value,SortColumn FROM CTE ORDER BY RN

and output is:


问:
How to correctly override BasicDataSource for Spring and Hibernate
Currently I have following basic data source in Spring:

```<code><bean id="dbcpDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost/test?relaxAutoCommit=true" />
    ...
</bean>
</code>```

Now I need to provide custom data source based on server environment (not config), for which I need to calculate driverClassName and url fields based on some condition.

I tried overriding createDataSource() method:

```<code>public class MyDataSource extends BasicDataSource {

    @Override
    protected synchronized DataSource createDataSource() throws SQLException {
        if(condition) {
            super.setDriverClassName("com.mysql.jdbc.Driver");
            super.setUrl("jdbc:mysql://localhost/test?relaxAutoCommit=true");
        } else {
            //...
        }
        return super.createDataSource();
    }
}
</code>```

Which works, but I noticed that createDataSource() is getting called each time a query is executed(?), so I would rather move my condition testing elsewhere.

I tried overriding setDriverClassName() and setUrl() which also works and is getting called only once from what I can tell, but then I need to provide some values in Spring configuration in order to trigger those setters as they are not called otherwise:

```<code><bean id="dbcpDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="whatever" />
    <property name="url" value="whatever" />
    ...
</bean>
</code>```

which might look confusing.

Are there any better solutions?

答:
There is no need to extend BasicDataSource. Inheritance is the strongest form of coupling and should be avoided unless you have a real reason to use it.

You have two options:

Create a wrapper (use composition instead of inheritance)

```<code>public class MyDataSource implements DataSource {
    private BasicDataSource target = new BasicDataSource();
    public MyDataSource() {
        if (condition) {
            target.setDriverClassName("com.mysql.jdbc.Driver");
            target.setUrl("jdbc:mysql://localhost/test?relaxAutoCommit=true");
        } else { ... }
    }
    public Connection getConnection() {
        return target.getConnection();
    }
    ... etc ...
}
</code>```

Create a factory (since you need to customize only the creation phase of the object, you don't need to control the whole lifetime of it).

```<code> public class MyDataSourceFactory {
    public DataSource createDataSource() {
        BasicDataSource target = new BasicDataSource();
        if (condition) {
            target.setDriverClassName("com.mysql.jdbc.Driver");
            target.setUrl("jdbc:mysql://localhost/test?relaxAutoCommit=true");
        } else { ... }
        return target;
    }
}
</code>```

.

```<code><bean id = "factory" class = "MyDataSourceFactory" />
<bean id = "dbcpDataSource"
     factory-bean = "factory" factory-method = "createDataSource">
     <property ... />
</bean>
</code>```

EDIT: Note that you still can configure the object obtained from the factory as a regular Spring bean.

Also if your condition is simple enough, you can avoid writing your own code at all by using declarative approaches provided by Spring, such as Spring Expression language.

ContentLicense: CC BY-SA 2.5

Body:
Currently I have following basic data source in Spring:

<bean id="dbcpDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost/test?relaxAutoCommit=true" />
    ...
</bean>

Now I need to provide custom data source based on server environment (not config), for which I need to calculate driverClassName and url fields based on some condition.

I tried overriding createDataSource() method:

public class MyDataSource extends BasicDataSource {

    @Override
    protected synchronized DataSource createDataSource() throws SQLException {
        if(condition) {
            super.setDriverClassName("com.mysql.jdbc.Driver");
            super.setUrl("jdbc:mysql://localhost/test?relaxAutoCommit=true");
        } else {
            //...
        }
        return super.createDataSource();
    }
}

Which works, but I noticed that createDataSource() is getting called each time a query is executed(?), so I would rather move my condition testing elsewhere.

I tried overriding setDriverClassName() and setUrl() which also works and is getting called only once from what I can tell, but then I need to provide some values in Spring configuration in order to trigger those setters as they are not called otherwise:

<bean id="dbcpDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="whatever" />
    <property name="url" value="whatever" />
    ...
</bean>

which might look confusing.

Are there any better solutions?

Body:
There is no need to extend BasicDataSource. Inheritance is the strongest form of coupling and should be avoided unless you have a real reason to use it.

You have two options:

Create a wrapper (use composition instead of inheritance)

public class MyDataSource implements DataSource {
    private BasicDataSource target = new BasicDataSource();
    public MyDataSource() {
        if (condition) {
            target.setDriverClassName("com.mysql.jdbc.Driver");
            target.setUrl("jdbc:mysql://localhost/test?relaxAutoCommit=true");
        } else { ... }
    }
    public Connection getConnection() {
        return target.getConnection();
    }
    ... etc ...
}

Create a factory (since you need to customize only the creation phase of the object, you don't need to control the whole lifetime of it).

 public class MyDataSourceFactory {
    public DataSource createDataSource() {
        BasicDataSource target = new BasicDataSource();
        if (condition) {
            target.setDriverClassName("com.mysql.jdbc.Driver");
            target.setUrl("jdbc:mysql://localhost/test?relaxAutoCommit=true");
        } else { ... }
        return target;
    }
}

.

<bean id = "factory" class = "MyDataSourceFactory" />
<bean id = "dbcpDataSource"
     factory-bean = "factory" factory-method = "createDataSource">
     <property ... />
</bean>

EDIT: Note that you still can configure the object obtained from the factory as a regular Spring bean.

Also if your condition is simple enough, you can avoid writing your own code at all by using declarative approaches provided by Spring, such as Spring Expression language.


答:
Try this . Ps. you can also use merge or join , I just get used to map

```<code>df['maxabs']=df.ID.map(df.groupby(['ID']).apply(lambda x: max(abs(x.value1-x.value2))))

   ID  value1  value2  maxabs
0   1       3       2       4
1   1       6       2       4
2   2       6       1       5
3   3       5       8       3
4   4       7       2       5
5   4       3       2       5
</code>```

Title: Groupby one column and find max (absolute) value of difference of other two columns in pandas

Body:
Try this . Ps. you can also use merge or join , I just get used to map

df['maxabs']=df.ID.map(df.groupby(['ID']).apply(lambda x: max(abs(x.value1-x.value2))))

   ID  value1  value2  maxabs
0   1       3       2       4
1   1       6       2       4
2   2       6       1       5
3   3       5       8       3
4   4       7       2       5
5   4       3       2       5


问:
Resources exceed limits big query
```<code>SELECT A,B, C, D, E, F ,EXTRACT(MONTH FROM PARSE_DATE('%b',Month))
as MonthNumber,PARSE_DATETIME(' %Y%b%d ', CONCAT(CAST(Year AS STRING),Month,'1'))
as G FROM `XXX.YYY.ZZZ`
where A !='null' and B = 'MYSTRING' order by A,Year
</code>```

The query processes about 20 GB per run.

My table ZZZ has 396,567,431 (396 million) rows with a size of 53 GB. If I execute the above query without a LIMIT clause , I get an error saying "Resources exceeded".

If i execute it with a LIMIT clause , then it gives the same error for larger limits.

I am writing a python script using the API that runs the query above and then computes some metrics and then writes the output to another table. It writes some 1.7 million output rows, so basically aggregates the first table based on column A i.e original table has multiple rows for column A.

Now I know we can set Allow large results to on and select an output table to get around this error but for the purposes of my script it doesn't server the purpose.

Also , I read that order by is the expesnive part causing this but below is my algorithm and I dont see a way around order by.

Also my script pages the query results 100000 rows at a time.

```<code>log=[]
    while True:
        rows, total_rows, page_token = query_job.results.fetch_data(max_results=100000, page_token=page_token)
        for row in rows:
            try:
                lastAValue=log[-1][0]
            except IndexError:
                lastAValue=None

            if(lastAValue==None or row[0]==lastAValue):
                log.append(row)
            else:
                res=Compute(lastAValue,EntityType,lastAValue)
                allresults.append(res)
                log=[]
                log.append(row)
        if not page_token:
            break
</code>```

I have two questions :

Column A |  Column B ......

123      | NDG

123      | KOE

123      | TR

345      | POP

345      | KOP

345      | POL

The way I kept my logic is : I iterate through the rows and check if column A is same as last row column A. If same , then I add that row to an array. The moment I encounter a different column A i.e 345 , I send the first group of column A for processing , compute and add the data to my array. Based on this approach I had some questions :

1) I am effectively querying only once . So , I should be charged only for 1 query. Does big query charge as per totalRows/noOf pages ? i.e will individual pages from above code be separate query and charged separately ?

2) Assume page size in the above example would be 5 , what would happen is the 345 entries would be spread across pages , in this case will I lose information about the 6 th 345 -POL entry as it will be in a different page ? Is there a work around for this ?

3)Is there a direct way to get around the whole check the successive rows if they differ in values ? like a direct group by and get groups as array mechanism ? The above approach takes a couple of hours (estimated ) to run if i add a limit of 1 million.

4) How can I get around this error of Resources exceeded by specifying higher limits than 1 million.?

答:
You are asking BigQuery to produce one huge sorted result, which BigQuery currently cannot efficiently parallelize, so you get the "Resources exceeded" error.

The efficient way to perform this kind of queries is to allow your computation to happen in SQL inside of BigQuery, rather than extracting huge result from it, and doing post-processing in Python. Analytical functions is common way to do what you described, if the Compute() function can be expressed in SQL.

E.g. for finding value of B in last row before A changes, you can find this row using LAST_VALUE function, something like

```<code>select LAST_VALUE(B) OVER(PARTITION BY A ORDER BY Yeah) from ...
</code>```

If you could describe what Compute() does, we could try to fill details.

Title: Resources exceed limits big query

Body:
SELECT A,B, C, D, E, F ,EXTRACT(MONTH FROM PARSE_DATE('%b',Month))
as MonthNumber,PARSE_DATETIME(' %Y%b%d ', CONCAT(CAST(Year AS STRING),Month,'1'))
as G FROM `XXX.YYY.ZZZ`
where A !='null' and B = 'MYSTRING' order by A,Year

The query processes about 20 GB per run.

My table ZZZ has 396,567,431 (396 million) rows with a size of 53 GB. If I execute the above query without a LIMIT clause , I get an error saying "Resources exceeded".

If i execute it with a LIMIT clause , then it gives the same error for larger limits.

I am writing a python script using the API that runs the query above and then computes some metrics and then writes the output to another table. It writes some 1.7 million output rows, so basically aggregates the first table based on column A i.e original table has multiple rows for column A.

Now I know we can set Allow large results to on and select an output table to get around this error but for the purposes of my script it doesn't server the purpose.

Also , I read that order by is the expesnive part causing this but below is my algorithm and I dont see a way around order by.

Also my script pages the query results 100000 rows at a time.

log=[]
    while True:
        rows, total_rows, page_token = query_job.results.fetch_data(max_results=100000, page_token=page_token)
        for row in rows:
            try:
                lastAValue=log[-1][0]
            except IndexError:
                lastAValue=None

            if(lastAValue==None or row[0]==lastAValue):
                log.append(row)
            else:
                res=Compute(lastAValue,EntityType,lastAValue)
                allresults.append(res)
                log=[]
                log.append(row)
        if not page_token:
            break

I have two questions :

Column A |  Column B ......

123      | NDG

123      | KOE

123      | TR

345      | POP

345      | KOP

345      | POL

The way I kept my logic is : I iterate through the rows and check if column A is same as last row column A. If same , then I add that row to an array. The moment I encounter a different column A i.e 345 , I send the first group of column A for processing , compute and add the data to my array. Based on this approach I had some questions :

1) I am effectively querying only once . So , I should be charged only for 1 query. Does big query charge as per totalRows/noOf pages ? i.e will individual pages from above code be separate query and charged separately ?

2) Assume page size in the above example would be 5 , what would happen is the 345 entries would be spread across pages , in this case will I lose information about the 6 th 345 -POL entry as it will be in a different page ? Is there a work around for this ?

3)Is there a direct way to get around the whole check the successive rows if they differ in values ? like a direct group by and get groups as array mechanism ? The above approach takes a couple of hours (estimated ) to run if i add a limit of 1 million.

4) How can I get around this error of Resources exceeded by specifying higher limits than 1 million.?

Body:
You are asking BigQuery to produce one huge sorted result, which BigQuery currently cannot efficiently parallelize, so you get the "Resources exceeded" error.

The efficient way to perform this kind of queries is to allow your computation to happen in SQL inside of BigQuery, rather than extracting huge result from it, and doing post-processing in Python. Analytical functions is common way to do what you described, if the Compute() function can be expressed in SQL.

E.g. for finding value of B in last row before A changes, you can find this row using LAST_VALUE function, something like

select LAST_VALUE(B) OVER(PARTITION BY A ORDER BY Yeah) from ...

If you could describe what Compute() does, we could try to fill details.


问:
Can I do a smooth resize animation on a control with only a 2 size increase
I want to have a control (button) to have a smooth resizing animation, although the problem is that you can only set the size of a control to a int (whole) value, which won't make it a smooth animation.

So is there anyway I can achieve a smooth resize animation with only a 2 increase in size?

For example, the buttons in the Windows 10 settings application when you let go of a button and how they have a smooth animation, although the resize is very small.

答:
No.  The Control.Size structure does not take floating-point values, but rather Int32.  Pixels or points, but always integer.
 Reference here</p>


问:
how to add asterisk after input field and the position same after zoom in
i am using bootstrap and glyphicons. i need to add asterisk after each mandatory fields. after zoom in i want the position keep same.</p>

```<code>  <form class="well form-horizontal" action=" " method="post"
    id="user_edit">
   <div class="form-group">

      <div class="col-md-8 inputGroupContainer">
         <div class="input-group "><span class="input-group-addon">
         <i class="glyphicon glyphicon-user"></i></span>
         <input type="text" placeholder="First Name" class="form-control"
         name="first_name" value='<?php echo $profile_fields[0]["value"];?>'
        id="first_name" maxlength="50" />
         </div>
      </div>
     </div>
 </form>
</code>```

答:
Just position the asterisk after the field using ::after.  It should stay in the same position when the user zooms in.

.required::before {
  position: absolute;
  left: -10px;
  top: 0;
  content: '*';
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form class="well form-horizontal" action=" " method="post"
    id="user_edit">
   <div class="form-group">

      <div class="col-md-8 inputGroupContainer ">
         <div class="input-group required"><span class="input-group-addon">
         <i class="glyphicon glyphicon-user"></i></span>
         <input type="text" placeholder="First Name" class="form-control"
         name="first_name" value=''
        id="first_name" maxlength="50" />
         </div>
      </div>
     </div>
 </form></code>```

Note: Give all required fields (input-group) a distinct class, such as required.

Body:
i am using bootstrap and glyphicons. i need to add asterisk after each mandatory fields. after zoom in i want the position keep same.

  <form class="well form-horizontal" action=" " method="post"
    id="user_edit">

         <input type="text" placeholder="First Name" class="form-control"
         name="first_name" value='<?php echo $profile_fields[0]["value"];?>'
        id="first_name" maxlength="50" />

 </form>

Body:
Just position the asterisk after the field using ::after.  It should stay in the same position when the user zooms in.

.required::before {
  position: absolute;
  left: -10px;
  top: 0;
  content: '*';
  color: red;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form class="well form-horizontal" action=" " method="post"
    id="user_edit">
   <div class="form-group">

      <div class="col-md-8 inputGroupContainer ">
         <div class="input-group required"><span class="input-group-addon">
         <i class="glyphicon glyphicon-user"></i></span>
         <input type="text" placeholder="First Name" class="form-control"
         name="first_name" value=''
        id="first_name" maxlength="50" />
         </div>
      </div>
     </div>
 </form>

Note: Give all required fields (input-group) a distinct class, such as required.


问:
Save data in python
I'm a little stuck here. I'm running a twitter api request loop and I need to store these tweets in a csv file. I'm doing something like:

```<code>for tweet in tweepy.Cursor(api.search,q=search+ lang="en").items(num_tweets):
    data = tweet.text
    print (tweet.text)
</code>```

My question is what's the easiest way to save tweets in this format:

```<code>["Hello world. I love Reddit!", "Lorem ipsum dolor sit amaet."]
</code>```

答:
if tweet.text itself is a list then:

```<code>result = []
for tweet in tweepy.Cursor(api.search,q=search+lang="en").items(num_tweets):
    result += tweet.text
</code>```

if tweet.text is a string then use result.append(tweet.text) instead.

Title: Save data in python

Body:
I'm a little stuck here. I'm running a twitter api request loop and I need to store these tweets in a csv file. I'm doing something like:

for tweet in tweepy.Cursor(api.search,q=search+ lang="en").items(num_tweets):
    data = tweet.text
    print (tweet.text)

My question is what's the easiest way to save tweets in this format:

["Hello world. I love Reddit!", "Lorem ipsum dolor sit amaet."]

Body:
if tweet.text itself is a list then:

result = []
for tweet in tweepy.Cursor(api.search,q=search+lang="en").items(num_tweets):
    result += tweet.text

if tweet.text is a string then use result.append(tweet.text) instead.


问:
Comparing file contents in F#
I wrote a quick and dirty function to compare file contents (BTW, I have already tested that they are of equal size):

```<code>let eqFiles f1 f2 =
  let bytes1 = Seq.ofArray (File.ReadAllBytes f1)
  let bytes2 = Seq.ofArray (File.ReadAllBytes f2)
  let res = Seq.compareWith (fun x y -> (int x) - (int y)) bytes1 bytes2
  res = 0
</code>```

I'm not happy with reading the whole contents into an array. I'd rather have a lazy sequence of bytes, but I can't find the right API in F#.

答:
As the others already said, use a stream for lazy I/O, for instance</p>

```<code>open System

let seqOfFstream (fstream: IO.FileStream) = seq {
    let currentByte = ref 0
    while !currentByte >= 0 do
        currentByte := fstream.ReadByte()
        yield !currentByte
}

let fileEq fname1 fname2 =
    use f1 = IO.File.OpenRead fname1
    use f2 = IO.File.OpenRead fname2
    not (Seq.exists2 (fun a b -> a <> b) (seqOfFstream f1) (seqOfFstream f2))
</code>```

Title: Comparing file contents in F#

Body:
I wrote a quick and dirty function to compare file contents (BTW, I have already tested that they are of equal size):

let eqFiles f1 f2 =
  let bytes1 = Seq.ofArray (File.ReadAllBytes f1)
  let bytes2 = Seq.ofArray (File.ReadAllBytes f2)
  let res = Seq.compareWith (fun x y -> (int x) - (int y)) bytes1 bytes2
  res = 0

I'm not happy with reading the whole contents into an array. I'd rather have a lazy sequence of bytes, but I can't find the right API in F#.

Body:
As the others already said, use a stream for lazy I/O, for instance

open System

let seqOfFstream (fstream: IO.FileStream) = seq {
    let currentByte = ref 0
    while !currentByte >= 0 do
        currentByte := fstream.ReadByte()
        yield !currentByte
}

let fileEq fname1 fname2 =
    use f1 = IO.File.OpenRead fname1
    use f2 = IO.File.OpenRead fname2
    not (Seq.exists2 (fun a b -> a <> b) (seqOfFstream f1) (seqOfFstream f2))


问:
Return value instead of a promise [to stop nested deferred promise]
I've a bunch of functions which are nested due to top level function is a ajax request.
So i want to return a value instead of a promise in nested child function.

Parent

```<code>let getUserPermissions = function(id) {
      let deferred = $q.defer();
      let promise = accessRequestService.getPermissions(id);
      promise.then(function(data) {
        deferred.resolve(data);
      }, function(err) {
        deferred.reject(err);
      })
      return deferred.promise;
    }
</code>```

Child 1

```<code>$rootScope.userInit = function() {
        return getUserPermissions(vzid)
          .then(function(data) {

            //Some code here

            return data;
          })

    }
</code>```

Child 2

```<code>let checkAuthorize = function(toState) {
  return $rootScope.userInit().then(
    function(data) {
//some code here
      return data;
    });
}
</code>```

Level 3

```<code>checkAuthorize(toState).then( function(val){
 $rootScope.isAuthorized = val;
  if ($rootScope.isAuthorized == true) {
        $log.info('is Authorized')
      } else {
        $log.info('is not Authorized');
        throw new AuthorizationError()
      }
  })
</code>```

At Level 3 we are still working with a promise. Can child 2 return a value instead of promise.

Expectation @ Level 3

```<code>$rootScope.isAuthorized = checkAuthorize(toState);

  if ($rootScope.isAuthorized == true) {
      $log.info('is Authorized')
      } else {
      $log.info('is not Authorized');
      throw new AuthorizationError()
     }
</code>```

答: Based on what you're hoping to achieve in Level 3, I'm guessing this function is going to be called multiple times with the same input. In this case, what I would do is make the call to the promise if there is not a cached result, and cache the result. This way you don't have to go down the promise chain, although I only count one promise in the code provided. There are multiple handlers on resolve, but only one promise.</p>

Body:
I've a bunch of functions which are nested due to top level function is a ajax request.
So i want to return a value instead of a promise in nested child function.

Parent

let getUserPermissions = function(id) {
      let deferred = $q.defer();
      let promise = accessRequestService.getPermissions(id);
      promise.then(function(data) {
        deferred.resolve(data);
      }, function(err) {
        deferred.reject(err);
      })
      return deferred.promise;
    }

Child 1

$rootScope.userInit = function() {
        return getUserPermissions(vzid)
          .then(function(data) {

            //Some code here

            return data;
          })

    }

Child 2

let checkAuthorize = function(toState) {
  return $rootScope.userInit().then(
    function(data) {
//some code here
      return data;
    });
}

Level 3

checkAuthorize(toState).then( function(val){
 $rootScope.isAuthorized = val;
  if ($rootScope.isAuthorized == true) {
        $log.info('is Authorized')
      } else {
        $log.info('is not Authorized');
        throw new AuthorizationError()
      }
  })

At Level 3 we are still working with a promise. Can child 2 return a value instead of promise.

Expectation @ Level 3

$rootScope.isAuthorized = checkAuthorize(toState);

  if ($rootScope.isAuthorized == true) {
      $log.info('is Authorized')
      } else {
      $log.info('is not Authorized');
      throw new AuthorizationError()
     }


问:
Elixir how to iterate over two lists at once to produce a new list?
I'd like to iterate over two lists at once, but can't figure out how. The for loop, which allows you to have multiple lists acts as nested for loops and I'm not that familiar with Enum, but perhaps there's a solution there.

Python has zip(list_1,list_2) and enumerate(list_1) to accomplish this

In Tcl is even easier for me:

```<code>% foreach var1 [list 1 3] var2 [list 2 4] {
    puts "$var1 $var2"
  }
1 2
3 4
</code>```

But I cannot figure out how to do it in Elixir.

The reason I want to do it is because I have a list of maps like this

```<code>[%{"a" => "1539", "b" => "300"},
 %{"a" => "4095", "b" => "0"},
 %{"a" => "5371", "b" => "0"},
 %{"a" => "7524", "b" => "0"},
 %{"a" => "8267", "b" => "27"}]
</code>```

and I have a list of items of the same size:

```<code>["a","b","c","d","e"]
</code>```

and I'd like to run them through a loop together to replace items in the map if and when one of the elements in the map is a certain condition (not 0):

```<code>[%{"a" => "a", "b" => "300"},   # notice the change in element "a"
 %{"a" => "4095", "b" => "0"},
 %{"a" => "5371", "b" => "0"},
 %{"a" => "7524", "b" => "0"},
 %{"a" => "e", "b" => "27"}]    # notice the change in element "a"
</code>```

Anyway. Can someone help me understand enumerable or how to iterate over two lists in elixir?

答:
You can use Enum.zip/2 and Enum.map/2 in Elixir to do accomplish the same thing:

```<code>list_of_maps
|> Enum.zip(list_of_items)
|> Enum.map(fn {map, item} ->
   if (map["b"] == "0"), do: map, else: Map.put(map, "a", item)
end)
</code>```

Body:
I'd like to iterate over two lists at once, but can't figure out how. The for loop, which allows you to have multiple lists acts as nested for loops and I'm not that familiar with Enum, but perhaps there's a solution there.

Python has zip(list_1,list_2) and enumerate(list_1) to accomplish this

In Tcl is even easier for me:

% foreach var1 [list 1 3] var2 [list 2 4] {
    puts "$var1 $var2"
  }
1 2
3 4

But I cannot figure out how to do it in Elixir.

The reason I want to do it is because I have a list of maps like this

[%{"a" => "1539", "b" => "300"},
 %{"a" => "4095", "b" => "0"},
 %{"a" => "5371", "b" => "0"},
 %{"a" => "7524", "b" => "0"},
 %{"a" => "8267", "b" => "27"}]

and I have a list of items of the same size:

["a","b","c","d","e"]

and I'd like to run them through a loop together to replace items in the map if and when one of the elements in the map is a certain condition (not 0):

[%{"a" => "a", "b" => "300"},   # notice the change in element "a"
 %{"a" => "4095", "b" => "0"},
 %{"a" => "5371", "b" => "0"},
 %{"a" => "7524", "b" => "0"},
 %{"a" => "e", "b" => "27"}]    # notice the change in element "a"

Anyway. Can someone help me understand enumerable or how to iterate over two lists in elixir?

Body:
You can use Enum.zip/2 and Enum.map/2 in Elixir to do accomplish the same thing:

list_of_maps
|> Enum.zip(list_of_items)
|> Enum.map(fn {map, item} ->
   if (map["b"] == "0"), do: map, else: Map.put(map, "a", item)
end)


问:
How do I return promise to satisfy the directive?
I have the following code and I have tried just bout everything to return a promise that would work with the directive. I have even tried returning the response data and return $q.when(data) and nothing. Ive tried reading on promises and this one is a bit different then Ive read. Something I'm missing?

```<code>myApp.controller('smsCtrl', function($scope){
        $scope.sendSMS = function(){
            let sms = {'number': $scope.number  ,'message': $scope.message};
            serviceNameHere.sendSMS(sms).then(function(response){
                $scope.smsSuccessMsg = "Message Sent Successfully";
            }, function(response){
                $scope.smsErrorMsg = response.data['message'];
            });
    };
})

myApp.directive('onClickDisable', function() {
  return {
    scope: {
      onClickDisable: '&'
    },
    link: function(scope, element, attrs) {
      element.bind('click', function() {
        element.prop('disabled',true);
        scope.onClickDisable().finally(function() {
          element.prop('disabled',false);
        })
      });
    }
  };
});
</code>```

The following html

```<code><div ng-controller="smsCtrl">
<-- field inputs here --></-->
    <button type="button" class="btn btn-primary" on-click-disable="sendSMS()">SEND</button>
</div>
</code>```

JSfiddle Example

答:
There is no need to have a special directive for this. Simply use ng-disabled and ng-click:

```<code><div ng-controller="smsCtrl">
    <!-- field inputs here -->
    <button ng-click="sendSMS()" ng-disabled="pendingSMS">
      SEND
    </button>
</div>
</code>```

In the controller:

```<code>myApp.controller('smsCtrl', function($scope, serviceNameHere){
        $scope.sendSMS = function(){
            let sms = {'number': $scope.number  ,'message': $scope.message};
            $scope.pendingSMS = true;
            serviceNameHere.sendSMS(sms).then(function(response){
                $scope.smsSuccessMsg = "Message Sent Successfully";
            }, function(response){
                $scope.smsErrorMsg = response.data['message'];
            }).finally(function() {
                $scope.pendingSMS = false;
            });
    };
})
</code>```

When the SMS message starts, the controller sets the pendingSMS flag to disable the Send button. When the service completes, the flag is reset and the button is re-enabled.

Body:
I have the following code and I have tried just bout everything to return a promise that would work with the directive. I have even tried returning the response data and return $q.when(data) and nothing. Ive tried reading on promises and this one is a bit different then Ive read. Something I'm missing?

myApp.controller('smsCtrl', function($scope){
        $scope.sendSMS = function(){
            let sms = {'number': $scope.number  ,'message': $scope.message};
            serviceNameHere.sendSMS(sms).then(function(response){
                $scope.smsSuccessMsg = "Message Sent Successfully";
            }, function(response){
                $scope.smsErrorMsg = response.data['message'];
            });
    };
})

myApp.directive('onClickDisable', function() {
  return {
    scope: {
      onClickDisable: '&'
    },
    link: function(scope, element, attrs) {
      element.bind('click', function() {
        element.prop('disabled',true);
        scope.onClickDisable().finally(function() {
          element.prop('disabled',false);
        })
      });
    }
  };
});

The following html

<-- field inputs here --></-->
    <button type="button" class="btn btn-primary" on-click-disable="sendSMS()">SEND</button>

JSfiddle Example

Body:
There is no need to have a special directive for this. Simply use ng-disabled and ng-click:

<div ng-controller="smsCtrl">
    <!-- field inputs here -->
    <button ng-click="sendSMS()" ng-disabled="pendingSMS">
      SEND
    </button>
</div>

In the controller:

myApp.controller('smsCtrl', function($scope, serviceNameHere){
        $scope.sendSMS = function(){
            let sms = {'number': $scope.number  ,'message': $scope.message};
            $scope.pendingSMS = true;
            serviceNameHere.sendSMS(sms).then(function(response){
                $scope.smsSuccessMsg = "Message Sent Successfully";
            }, function(response){
                $scope.smsErrorMsg = response.data['message'];
            }).finally(function() {
                $scope.pendingSMS = false;
            });
    };
})

When the SMS message starts, the controller sets the pendingSMS flag to disable the Send button. When the service completes, the flag is reset and the button is re-enabled.


问:
How can I set the width of certain columns?
I'm playing around with the code sample below.

```<code>Sub Hide_Columns_Containing_Value()

Dim c As Range
Dim ThisIsToday As Date
Dim TwoWeeksBack As Date
Dim ThreeMonthsAhead As Date

    ThisIsToday = Date
    TwoWeeksBack = ThisIsToday - 14
    ThreeMonthsAhead = ThisIsToday + 100

For Each c In Range("O4:XA4").Cells
If c.Value < TwoWeeksBack Or c.Value > ThreeMonthsAhead Then
    Range(c.Address).Select
    Selection.ColumnWidth = 1.75
    Else
        c.EntireColumn.Hidden = True
    End If
Next c

End Sub
</code>```

Basically I want to loop through all cells and if the value is a date less than two seeks ago, or more than 3 months from now, I want to hide the column.  The problem is that the dates are not in every cell; the dates are in every 7 cells, which represent every Friday.  The hiding and showing of columns is not working like I want it to, because of all the blank cells.

Here is a screen shot of the dates.

答:
Is this what you were trying to do

```<code>Option Explicit

Public Sub HideColumnsContainingValue()

    Dim c As Range
    Dim thisIsToday As Date
    Dim twoWeeksBack As Date
    Dim threeMonthsAhead As Date

    thisIsToday = Date
    twoWeeksBack = thisIsToday - 14
    threeMonthsAhead = thisIsToday + 100

    For Each c In Range("O4:XA4").Cells
        With c
            If Len(.Value2) > 0 Then        'if not empty
                If IsDate(.Value) Then      'if date

                    If .Value < twoWeeksBack Or .Value > threeMonthsAhead Then
                        .EntireColumn.Hidden = True
                    Else
                        .ColumnWidth = 1.75
                    End If

                End If
            End If
        End With
    Next
End Sub
</code>```

This version is a bit faster

```<code>Public Sub HideDatesNotInRange()
    Dim dateRng As Range, dateArr As Variant
    Dim c As Long, minDay As Date, maxDay As Date

    minDay = Date - 14
    maxDay = Date + 100
    Set dateRng = Range("O4:XA4")
    dateArr = dateRng                       'iterate over array

    Application.ScreenUpdating = False
    For c = 1 To UBound(dateArr, 2)
        If Len(dateArr(1, c)) > 0 Then      'if not empty
            If IsDate(dateArr(1, c)) Then   'if date
                With dateRng(1, c)
                    If dateArr(1, c) < minDay Or dateArr(1, c) > maxDay Then
                        .EntireColumn.Hidden = True
                    Else
                        .ColumnWidth = 1.75
                    End If
                End With
            End If
        End If
    Next
    Application.ScreenUpdating = True
End Sub
</code>```

Body:
I'm playing around with the code sample below.

Sub Hide_Columns_Containing_Value()

Dim c As Range
Dim ThisIsToday As Date
Dim TwoWeeksBack As Date
Dim ThreeMonthsAhead As Date

    ThisIsToday = Date
    TwoWeeksBack = ThisIsToday - 14
    ThreeMonthsAhead = ThisIsToday + 100

For Each c In Range("O4:XA4").Cells
If c.Value < TwoWeeksBack Or c.Value > ThreeMonthsAhead Then
    Range(c.Address).Select
    Selection.ColumnWidth = 1.75
    Else
        c.EntireColumn.Hidden = True
    End If
Next c

End Sub

Basically I want to loop through all cells and if the value is a date less than two seeks ago, or more than 3 months from now, I want to hide the column.  The problem is that the dates are not in every cell; the dates are in every 7 cells, which represent every Friday.  The hiding and showing of columns is not working like I want it to, because of all the blank cells.

Here is a screen shot of the dates.

Body:
Is this what you were trying to do

Option Explicit

Public Sub HideColumnsContainingValue()

    Dim c As Range
    Dim thisIsToday As Date
    Dim twoWeeksBack As Date
    Dim threeMonthsAhead As Date

    thisIsToday = Date
    twoWeeksBack = thisIsToday - 14
    threeMonthsAhead = thisIsToday + 100

    For Each c In Range("O4:XA4").Cells
        With c
            If Len(.Value2) > 0 Then        'if not empty
                If IsDate(.Value) Then      'if date

                    If .Value < twoWeeksBack Or .Value > threeMonthsAhead Then
                        .EntireColumn.Hidden = True
                    Else
                        .ColumnWidth = 1.75
                    End If

                End If
            End If
        End With
    Next
End Sub

This version is a bit faster

Public Sub HideDatesNotInRange()
    Dim dateRng As Range, dateArr As Variant
    Dim c As Long, minDay As Date, maxDay As Date

    minDay = Date - 14
    maxDay = Date + 100
    Set dateRng = Range("O4:XA4")
    dateArr = dateRng                       'iterate over array

    Application.ScreenUpdating = False
    For c = 1 To UBound(dateArr, 2)
        If Len(dateArr(1, c)) > 0 Then      'if not empty
            If IsDate(dateArr(1, c)) Then   'if date
                With dateRng(1, c)
                    If dateArr(1, c) < minDay Or dateArr(1, c) > maxDay Then
                        .EntireColumn.Hidden = True
                    Else
                        .ColumnWidth = 1.75
                    End If
                End With
            End If
        End If
    Next
    Application.ScreenUpdating = True
End Sub


问:
How to get OS language and locale?
My app changes the language at runtime and advises the user to restart the app. I do it like this:

```<code>    typealias LanguageLocaleType = (language: String?, locale: String?, title: String)

    let elements: [LanguageLocaleType] = [
        (nil, nil, "System Default"),
        ("en", "en_US", "English"),
        ("ar", "ar_SA", "Arabic"),
    ]

    //...func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)...

    let element = elements[indexPath.row]

    guard let language = element.language else {
        // How to really reset app back to OS language/locale???
        UserDefaults.standard.removeObject(forKey: "AppleLanguages")
        UserDefaults.standard.removeObject(forKey: "AppleLocale")
        return
    }

    UserDefaults.standard.set([language], forKey: "AppleLanguages")

    if let locale = element.locale, !locale.isEmpty,
        Locale.current.identifier != locale,
        !Locale.current.identifier.hasPrefix("\(language)_") {
            UserDefaults.standard.set(locale, forKey: "AppleLocale")
    }
</code>```

I want to offer to set languages in a list with the right one selected, one of which being offered it to set language back to System Default. However, there's no way to find the OS-level language and locale that I could find. Since after I mess around with setting the UserDefaults, Bundle.main.preferredLocalizations is not reliable and do not match the system default (event when I remove the key from the User Default).

Is there a way to get the OS-level language and locale instead of the app-level?

答:
I will recommend you to use this library from Cocoa pods.

In your Podfile add this line:

```<code>pod 'Localize-Swift', '~> 1.7'
</code>```

An then install your pods using this command:

```<code>pod install
</code>```

Then if you don't have Localizable.strings, for example Localizable.strings (English) file add this lines.

```<code>"LD" = "Loading ...";
"CAMP" = "Campus";
"MAP" = "MAP";
</code>```

The first word is like your TAG and the next word is your value .

Then in your ViewController you can use your string like this.

Example of use:

```<code>let progressHUD = ProgressHUD(text: "LD".localized())
let progressHUD = ProgressHUD(text: "CAMP".localized())
let progressHUD = ProgressHUD(text: "MAP".localized())
</code>```

And that is all.

I hope this help.

Title: How to get OS language and locale?

Body:
My app changes the language at runtime and advises the user to restart the app. I do it like this:

    typealias LanguageLocaleType = (language: String?, locale: String?, title: String)

    let elements: [LanguageLocaleType] = [
        (nil, nil, "System Default"),
        ("en", "en_US", "English"),
        ("ar", "ar_SA", "Arabic"),
    ]

    //...func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)...

    let element = elements[indexPath.row]

    guard let language = element.language else {
        // How to really reset app back to OS language/locale???
        UserDefaults.standard.removeObject(forKey: "AppleLanguages")
        UserDefaults.standard.removeObject(forKey: "AppleLocale")
        return
    }

    UserDefaults.standard.set([language], forKey: "AppleLanguages")

    if let locale = element.locale, !locale.isEmpty,
        Locale.current.identifier != locale,
        !Locale.current.identifier.hasPrefix("\(language)_") {
            UserDefaults.standard.set(locale, forKey: "AppleLocale")
    }

I want to offer to set languages in a list with the right one selected, one of which being offered it to set language back to System Default. However, there's no way to find the OS-level language and locale that I could find. Since after I mess around with setting the UserDefaults, Bundle.main.preferredLocalizations is not reliable and do not match the system default (event when I remove the key from the User Default).

Is there a way to get the OS-level language and locale instead of the app-level?

Body:
I will recommend you to use this library from Cocoa pods.

In your Podfile add this line:

pod 'Localize-Swift', '~> 1.7'

An then install your pods using this command:

pod install

Then if you don't have Localizable.strings, for example Localizable.strings (English) file add this lines.

"LD" = "Loading ...";
"CAMP" = "Campus";
"MAP" = "MAP";

The first word is like your TAG and the next word is your value .

Then in your ViewController you can use your string like this.

Example of use:

let progressHUD = ProgressHUD(text: "LD".localized())
let progressHUD = ProgressHUD(text: "CAMP".localized())
let progressHUD = ProgressHUD(text: "MAP".localized())

And that is all.

I hope this help.


问:
Mindstorms EV3 Path-Finding Algorithm
I'm trying to find a way to write a path-finding algorithm for the Lego Mindstorms ev3 using Python (EV3DEV).

I am allowed to use the following sensors:
-Touch
-Gyro
-Ultrasonic
-Color

I want it to run through a "corridor" where it may hit a wall and it has to turn left or right (depending if there is room).
How would I use the sensors to determine if it should turn left or right? (and not end up going backwards)

答:
Depending on the number of ports left on your robot, I would configure your robot as below. Here is a high level example of how I would go about the algorithm

```<code>while True:
    if touch_pressed:
        drive backwards
        if right_ultra1 and right ultra2 clear:
            turnRight()
        else:
            turnLeft()
    drive_forward
</code>```

Basically the robot drives forward until it hits on object. Then it backs up just enough to make a turn without hitting the wall. Next, it checks the sensors. Since the sensors are positioned to be as close to the length of the robot as possible, the narrowness of the passage can be estimated. If both sensors read an arbitrarily large value, the passage is wide enough else, the passage is not wide enough. After turning/if sensor was not pressed, it drives forward. Hope this helps!

Title: Mindstorms EV3 Path-Finding Algorithm

Body:
Depending on the number of ports left on your robot, I would configure your robot as below. Here is a high level example of how I would go about the algorithm

while True:
    if touch_pressed:
        drive backwards
        if right_ultra1 and right ultra2 clear:
            turnRight()
        else:
            turnLeft()
    drive_forward

Basically the robot drives forward until it hits on object. Then it backs up just enough to make a turn without hitting the wall. Next, it checks the sensors. Since the sensors are positioned to be as close to the length of the robot as possible, the narrowness of the passage can be estimated. If both sensors read an arbitrarily large value, the passage is wide enough else, the passage is not wide enough. After turning/if sensor was not pressed, it drives forward. Hope this helps!


问:
How to work with abstract type members in Scala
I'm running into issues with the following code (heavily simplified). Looks like the problem may be with the way I use abstract type members. I would appreciate someone pointing out and explaining what I'm doing wrong here. Compiler error at the bottom.
I'm using Scala version 2.12.

```<code>trait DataType {
    type A

    def convert(value: String): A
    def convertToString(value: A): String
}

case object IntType extends DataType {
    type A = Int

    def convert(value: String): A = value.toInt
    def convertToString(value: A): String = value.toString
}

trait Codec[T <: DataType] {
    val dtype: T

    def encode(data: Array[String]): Array[T#A]
    def decode(data: Array[T#A]): Array[String]
}

class CodecImp[T <: DataType](val dtype: T)(implicit tag: ClassTag[T#A]) extends Codec[T] {
    def encode(data: Array[String]): Array[T#A] = {
        Array[T#A](dtype.convert(data(0)))
    }

    def decode(data: Array[T#A]): Array[String] = {
        Array[String](dtype.convertToString(data(0)))
    }
}

val cod = new CodecImp(IntType)
val encoded = cod.encode(Array("1", "2", "3")) // expecting: Array[IntType.A]
val decoded = cod.decode(encoded) // expecting: Array[String]
</code>```

Compiler error.

```<code>Error:(30, 50) type mismatch;
 found   : T#A
 required: CodecImp.this.dtype.A
        Array[String](dtype.convertToString(data(0)))
                 ^
</code>```

答:
The thing is that each instance of DataType can have A defined as anything whatsoever. Consider this:

```<code>class Foo extends DataType {
   type A = Int
   def convertToString(i: Int) = i.toString
   def convert(s: String) = s.toInt
}

class Bar extends DataType {
    type A = String
    def convertToString(s: String) = s
    def convert(s: String) = s
 }
</code>```

Now, if I do val codecs = Seq(CodecImpl(new Foo, new Bar)

and if that compiles, then what type should the argument be to codecs.map(_.decode(whateverMakesSenseHere))?

This doesn't work ... You can't use T#A like this, because it is abstract.

I get a feeling, you'd be better off modeling what you need to model with type parameters rather than path dependent types. This just doesn't really seem like a use case for the latter.

Body:
I'm running into issues with the following code (heavily simplified). Looks like the problem may be with the way I use abstract type members. I would appreciate someone pointing out and explaining what I'm doing wrong here. Compiler error at the bottom.
I'm using Scala version 2.12.

trait DataType {
    type A

    def convert(value: String): A
    def convertToString(value: A): String
}

case object IntType extends DataType {
    type A = Int

    def convert(value: String): A = value.toInt
    def convertToString(value: A): String = value.toString
}

trait Codec[T <: DataType] {
    val dtype: T

    def encode(data: Array[String]): Array[T#A]
    def decode(data: Array[T#A]): Array[String]
}

class CodecImp[T <: DataType](val dtype: T)(implicit tag: ClassTag[T#A]) extends Codec[T] {
    def encode(data: Array[String]): Array[T#A] = {
        Array[T#A](dtype.convert(data(0)))
    }

    def decode(data: Array[T#A]): Array[String] = {
        Array[String](dtype.convertToString(data(0)))
    }
}

val cod = new CodecImp(IntType)
val encoded = cod.encode(Array("1", "2", "3")) // expecting: Array[IntType.A]
val decoded = cod.decode(encoded) // expecting: Array[String]

Compiler error.

Error:(30, 50) type mismatch;
 found   : T#A
 required: CodecImp.this.dtype.A
        Array[String](dtype.convertToString(data(0)))
                 ^

Body:
The thing is that each instance of DataType can have A defined as anything whatsoever. Consider this:

class Foo extends DataType {
   type A = Int
   def convertToString(i: Int) = i.toString
   def convert(s: String) = s.toInt
}

class Bar extends DataType {
    type A = String
    def convertToString(s: String) = s
    def convert(s: String) = s
 }

Now, if I do val codecs = Seq(CodecImpl(new Foo, new Bar)

and if that compiles, then what type should the argument be to codecs.map(_.decode(whateverMakesSenseHere))?

This doesn't work ... You can't use T#A like this, because it is abstract.

I get a feeling, you'd be better off modeling what you need to model with type parameters rather than path dependent types. This just doesn't really seem like a use case for the latter.