问:
Using text-overflow: ellipses in an HTML table
I must be missing something here, but why isn't my text-overflow: ellipses rule working correctly here?

Fiddle: https://jsfiddle.net/sgj9rv5r/

```<code>td {
    white-space: nowrap;
    width: 50px;
    overflow: hidden;
    text-overflow: ellipsis;
}

<table border="1">
  <tr>
    <td>
      This content should shorten to ellipses after the 50px width has been reached.
    </td>
  </tr>
</table>
</code>```

答: Using max-width as suggested by Michael Coker solves this problem.

Body:
I must be missing something here, but why isn't my text-overflow: ellipses rule working correctly here?

Fiddle: https://jsfiddle.net/sgj9rv5r/

td {
    white-space: nowrap;
    width: 50px;
    overflow: hidden;
    text-overflow: ellipsis;
}

      This content should shorten to ellipses after the 50px width has been reached.


来源: stackexchange

问:
Python Turtle Graphics and Loops
I am trying to create a loop which prints out 6 parallel lines horizontally.However when I using the code below I only am able to see one line that just moves continuously. Any tips would be appreciated. Here is the code:  </p>

```<code>count = 0;
while(count < 6):
  actor.penup()
  actor.backward(100)
  actor.pendown()
  actor.forward(150)
  count = count + 1
</code>```

答:
You can use your familiarity with Cartesian co-ordinates. Move the pen to one end of each line, pen down then move the pen to the opposite end of that line.

```<code>>>> from turtle import *
>>> for _ in range(6):
...     up()
...     goto(0, 10*_)
...     down()
...     goto(50, 10*_)
...
>>> up()
>>> home()
</code>```

There must be other ways but I'm not at all familiar with turtle.

ContentLicense: CC BY-SA 3.0

Title: Python Turtle Graphics and Loops

Body:
I am trying to create a loop which prints out 6 parallel lines horizontally.However when I using the code below I only am able to see one line that just moves continuously. Any tips would be appreciated. Here is the code:

count = 0;
while(count < 6):
  actor.penup()
  actor.backward(100)
  actor.pendown()
  actor.forward(150)
  count = count + 1

Body:
You can use your familiarity with Cartesian co-ordinates. Move the pen to one end of each line, pen down then move the pen to the opposite end of that line.

>>> from turtle import *
>>> for _ in range(6):
...     up()
...     goto(0, 10*_)
...     down()
...     goto(50, 10*_)
...
>>> up()
>>> home()

There must be other ways but I'm not at all familiar with turtle.


问:
Print stylish text on image in php
Is it possible to print html div tag with style on image in PHP?. if not, then what is the alternative way?</p>

答:
You can set the image as the background graphic of any div using CSS. Then the text within that div will appear on top of the image.</p>

```<code>(CSS)
.mydiv {
    background:url(/path/to/image.gif);
    width:100px;  /* set to width of the image */
    height:100px;  /* set to height of the image */
}

(HTML)
<div class='mydiv'>Some text here</div>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Print stylish text on image in php

Body:
You can set the image as the background graphic of any div using CSS. Then the text within that div will appear on top of the image.

(CSS)
.mydiv {
    background:url(/path/to/image.gif);
    width:100px;  /* set to width of the image */
    height:100px;  /* set to height of the image */
}

(HTML)
<div class='mydiv'>Some text here</div>


问:
Cross platform component react-native-web
I use react-native-web and I would like to create cross-platform components. I would like to differentiate each components by platform.

So I followed this tutorial: https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/

I have 3 files :

     - friendsList.android.js

     - friendsList.ios.js

     - friendsList.web.js

And for import FriendsList, in the index.android.js, index.ios.js index.web.js :

```<code>Import FriendsList from './friendsList';
</code>```

On Ios and Android, it works fine. But on the web, it does not recognize the file. I actually have 3 solutions:

- specify when importing: import FriendsList from './friendsList.web';

     - define a service who dispatch for each platform

- or to define an alias in webpack:

```<code> resolve: {
        alias: {
            'react-native': 'react-native-web',
            './friendsList': './friendsList.web',
        },
    },
</code>```

Is there a way to import .web without this ways ?

Maybe it's not thought to do like that ?

答:
According to react-native-web getting started documentation, you need to set the extensions.

```<code>resolve: {
  // Maps the 'react-native' import to 'react-native-web'.
  alias: {
    'react-native': 'react-native-web'
  },
  // If you're working on a multi-platform React Native app, web-specific
  // module implementations should be written in files using the extension
  // `.web.js`.
  extensions: [ '.web.js', '.js' ]
}
</code>```

Body:
I use react-native-web and I would like to create cross-platform components. I would like to differentiate each components by platform.

So I followed this tutorial: https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/

I have 3 files :

     - friendsList.android.js

     - friendsList.ios.js

     - friendsList.web.js

And for import FriendsList, in the index.android.js, index.ios.js index.web.js :

Import FriendsList from './friendsList';

On Ios and Android, it works fine. But on the web, it does not recognize the file. I actually have 3 solutions:

- specify when importing: import FriendsList from './friendsList.web';

     - define a service who dispatch for each platform

- or to define an alias in webpack:

 resolve: {
        alias: {
            'react-native': 'react-native-web',
            './friendsList': './friendsList.web',
        },
    },

Is there a way to import .web without this ways ?

Maybe it's not thought to do like that ?

Body:
According to react-native-web getting started documentation, you need to set the extensions.

resolve: {
  // Maps the 'react-native' import to 'react-native-web'.
  alias: {
    'react-native': 'react-native-web'
  },
  // If you're working on a multi-platform React Native app, web-specific
  // module implementations should be written in files using the extension
  // `.web.js`.
  extensions: [ '.web.js', '.js' ]
}


问:
AWS Server Size for Hosting
I am looking into purchasing server space with AWS to host what will eventually be over 50 websites. They will have many different ranges of traffic coming in. I would like to know if anyone has a recommendation on what size of server that would be able to handle this many sites.

Also, I was wondering if it's more cost effective/efficient to host an separate EC-2 instance for each site or too purchase a large umbrella server and host all sites on a single instance?

Thanks,

答:
The short correct answer:

If those sites are only static(html, css and js). EC2 won't be necessary because you can use S3 and it will be more cheap and you won't have to worry about scaling.

But if those sites have a dynamic part like php, python and similar. Well it is a different story.

Title: AWS Server Size for Hosting


问:
Unable to get docs and facets in one solr CQL query in DSE Search
Requirement: Is to implement faceted search using DSE Search

Problem: Unable to get docs or data and facets in one CQL solr query.

Tools & Technology Used: Datastax Sandbox 5.1 (Cent OS + Virtual box) and trying DSE search

Created following table & used dsetool enable solr (DSE Search):

```<code>CREATE TABLE test.employee_copy1 (
    empid int,
    deptid int,
    name text,
    solr_query text, -- column got created by enabling DSE Search
    PRIMARY KEY (empid, deptid)
)
</code>```

Inserted following data,

```<code>INSERT INTO employee (empid,deptid,name) VALUES (100,200,'John');
INSERT INTO employee (empid,deptid,name) VALUES (101,201,'Helen');
INSERT INTO employee (empid,deptid,name) VALUES (102,201,'John');
</code>```

I tried facet query from Solr Admin as below

```<code>http://localhost:8983/solr/test.employee/select?q=*:*&wt=json&indent=true&facet=true&facet.field=name
</code>```

Got the results containing both docs ( or data) and facets as expected,

```<code>{
    "responseHeader": {
        "status": 0,
        "QTime": 1
    },
    "response": {
        "numFound": 3,
        "start": 0,
        "docs": [{
                "_uniqueKey": "[\"100\",\"200\"]",
                "empid": 100,
                "deptid": 200,
                "name": "John"
            },
            {
                "_uniqueKey": "[\"101\",\"201\"]",
                "empid": 101,
                "deptid": 201,
                "name": "Helen"
            },
            {
                "_uniqueKey": "[\"102\",\"201\"]",
                "empid": 102,
                "deptid": 201,
                "name": "John"
            }
        ]
    },
    "facet_counts": {
        "facet_queries": {},
        "facet_fields": {
            "name": [
                "john", 2,
                "helen", 1
            ]
        },
        "facet_dates": {},
        "facet_ranges": {},
        "facet_intervals": {}
    }
}
</code>```

But when tried the following query (CQL) in Datastax devcenter expecting to see data and facets, I see only facets

```<code>select JSON * from test.employee where solr_query = '{"q":"*:*", "facet" : {"field":"name"}}';
</code>```

Got the result but it has only facets and not data:

```<code>{"facet_fields" : {"name" : {"john" : 2,"helen" : 1 } } }
</code>```

Question: Can anyone explain why CQL query doesn't return data in-spite of specifying "q":"*:*"?

答:
It's simply a product decision. As Caleb pointed out, the developer experience with parsing the result was seen as less than desirable. Further more, with a distributed, P2P datastore (C*), the workaround of issuing 2 async queries, 1 for the facet result and 1 for the "Top Ten" is the preferred query pattern. They do not have to be done serially.

Ultimately, if the Solr behavior is desired, than the Solr HTTP API is available to use in DSE. The CQL API is aimed more at providing simple FTS on the C* data, not necessarily supporting or doing everything vanilla Solr does through CQL.

Body:
Requirement: Is to implement faceted search using DSE Search

Problem: Unable to get docs or data and facets in one CQL solr query.

Tools & Technology Used: Datastax Sandbox 5.1 (Cent OS + Virtual box) and trying DSE search

Created following table & used dsetool enable solr (DSE Search):

CREATE TABLE test.employee_copy1 (
    empid int,
    deptid int,
    name text,
    solr_query text, -- column got created by enabling DSE Search
    PRIMARY KEY (empid, deptid)
)

Inserted following data,

INSERT INTO employee (empid,deptid,name) VALUES (100,200,'John');
INSERT INTO employee (empid,deptid,name) VALUES (101,201,'Helen');
INSERT INTO employee (empid,deptid,name) VALUES (102,201,'John');

I tried facet query from Solr Admin as below

http://localhost:8983/solr/test.employee/select?q=*:*&wt=json&indent=true&facet=true&facet.field=name

Got the results containing both docs ( or data) and facets as expected,

{
    "responseHeader": {
        "status": 0,
        "QTime": 1
    },
    "response": {
        "numFound": 3,
        "start": 0,
        "docs": [{
                "_uniqueKey": "[\"100\",\"200\"]",
                "empid": 100,
                "deptid": 200,
                "name": "John"
            },
            {
                "_uniqueKey": "[\"101\",\"201\"]",
                "empid": 101,
                "deptid": 201,
                "name": "Helen"
            },
            {
                "_uniqueKey": "[\"102\",\"201\"]",
                "empid": 102,
                "deptid": 201,
                "name": "John"
            }
        ]
    },
    "facet_counts": {
        "facet_queries": {},
        "facet_fields": {
            "name": [
                "john", 2,
                "helen", 1
            ]
        },
        "facet_dates": {},
        "facet_ranges": {},
        "facet_intervals": {}
    }
}

But when tried the following query (CQL) in Datastax devcenter expecting to see data and facets, I see only facets

select JSON * from test.employee where solr_query = '{"q":"*:*", "facet" : {"field":"name"}}';

Got the result but it has only facets and not data:

{"facet_fields" : {"name" : {"john" : 2,"helen" : 1 } } }

Question: Can anyone explain why CQL query doesn't return data in-spite of specifying "q":"*:*"?


问:
How to get the weekday from day of month using pyspark
I have a dataframe log_df:

I generate a new dataframe based on the following code:

```<code>from pyspark.sql.functions import split, regexp_extract
split_log_df = log_df.select(regexp_extract('value', r'^([^\s]+\s)', 1).alias('host'),
                          regexp_extract('value', r'^.*\[(\d\d/\w{3}/\d{4}:\d{2}:\d{2}:\d{2} -\d{4})]', 1).alias('timestamp'),
                          regexp_extract('value', r'^.*"\w+\s+([^\s]+)\s+HTTP.*"', 1).alias('path'),
                          regexp_extract('value', r'^.*"\s+([^\s]+)', 1).cast('integer').alias('status'),
                          regexp_extract('value', r'^.*\s+(\d+)$', 1).cast('integer').alias('content_size'))
split_log_df.show(10, truncate=False)
</code>```

the new dataframe is like:

I need another column showing the dayofweek, what would be the best elegant way to create it? ideally just adding a udf like field in the select.

Thank you very much.

Updated: my question is different than the one in the comment, what I need is to make the calculation based on a string in log_df, not based on the timestamp like the comment, so this is not a duplicate question. Thanks.

Body:
I have a dataframe log_df:

I generate a new dataframe based on the following code:

from pyspark.sql.functions import split, regexp_extract
split_log_df = log_df.select(regexp_extract('value', r'^([^\s]+\s)', 1).alias('host'),
                          regexp_extract('value', r'^.*\[(\d\d/\w{3}/\d{4}:\d{2}:\d{2}:\d{2} -\d{4})]', 1).alias('timestamp'),
                          regexp_extract('value', r'^.*"\w+\s+([^\s]+)\s+HTTP.*"', 1).alias('path'),
                          regexp_extract('value', r'^.*"\s+([^\s]+)', 1).cast('integer').alias('status'),
                          regexp_extract('value', r'^.*\s+(\d+)$', 1).cast('integer').alias('content_size'))
split_log_df.show(10, truncate=False)

the new dataframe is like:

I need another column showing the dayofweek, what would be the best elegant way to create it? ideally just adding a udf like field in the select.

Thank you very much.

Updated: my question is different than the one in the comment, what I need is to make the calculation based on a string in log_df, not based on the timestamp like the comment, so this is not a duplicate question. Thanks.

Body:
I suggest a bit different method

from pyspark.sql.functions import date_format
df.select('capturetime', date_format('capturetime', 'u').alias('dow_number'), date_format('capturetime', 'E').alias('dow_string'))
df3.show()

It gives ...

+--------------------+----------+----------+
|         capturetime|dow_number|dow_string|
+--------------------+----------+----------+
|2017-06-05 10:05:...|         1|       Mon|
|2017-06-05 10:05:...|         1|       Mon|
|2017-06-05 10:05:...|         1|       Mon|
|2017-06-05 10:05:...|         1|       Mon|
|2017-06-05 10:05:...|         1|       Mon|
|2017-06-05 10:05:...|         1|       Mon|
|2017-06-05 10:05:...|         1|       Mon|
|2017-06-05 10:05:...|         1|       Mon|


问:
Iterating through object array in $scope and updating it
I have an array of objects in the scope ($scope.contracts). When I run my function, I pass in a contract. I Want it to iterate through $scope.contracts and find the one with the same .CONT_ORDNO. Then I want to set this contract to the contract passed in.

```<code>    $scope.mergeContract = function (contractThatsReplaced) {//clicked 2nd new
        angular.forEach($scope.contracts, function (con) {
            if (con.CONT_ORDNO == contractThatsReplaced.CONT_ORDNO) {
                con = $scope.contractToMerge;
            }
        });
    };
</code>```

Here is me trying to do it, it does everything I want except that only the con variable is changed, the actual contract that's an array location in $scope.contracts is not being updated. How do I make sure it is?

Note I don't want to remove and replace the contract, I want to update it.

Edit: I updated the if statement to have two (==). This doesn't fix it. It still is only setting the con variable correctly, not the $scope.contracts array location.

答:
need <code>==</code> in the if condition </p>

```<code>if (con.CONT_ORDNO == contractThatsReplaced.CONT_ORDNO) {
</code>```

Body:
I have an array of objects in the scope ($scope.contracts). When I run my function, I pass in a contract. I Want it to iterate through $scope.contracts and find the one with the same .CONT_ORDNO. Then I want to set this contract to the contract passed in.

    $scope.mergeContract = function (contractThatsReplaced) {//clicked 2nd new
        angular.forEach($scope.contracts, function (con) {
            if (con.CONT_ORDNO == contractThatsReplaced.CONT_ORDNO) {
                con = $scope.contractToMerge;
            }
        });
    };

Here is me trying to do it, it does everything I want except that only the con variable is changed, the actual contract that's an array location in $scope.contracts is not being updated. How do I make sure it is?

Note I don't want to remove and replace the contract, I want to update it.

Edit: I updated the if statement to have two (==). This doesn't fix it. It still is only setting the con variable correctly, not the $scope.contracts array location.

Body:
need == in the if condition

if (con.CONT_ORDNO == contractThatsReplaced.CONT_ORDNO) {


问:
AWS SSH: Permission denied (publickey)
I'm trying to connect to AWS instance. I know that I definitely have the keypair downloaded on my desktop, but for some reason it doesn't recognize it? I've changed the permissions by using chmod 400 but the following still happens:

martycep:~ martincepeda1$ ssh -v -i “privatekey.pem” ec2-user@ec2-xx-xx-xx-xx.us-east-2.compute.amazonaws.com
Warning: Identity file privatekey.pem not accessible: No such file or directory.
OpenSSH_6.9p1, LibreSSL 2.1.8
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 21: Applying options for *
debug1: Connecting to ec2-xx-xx-xxx-xx.us-east-2.compute.amazonaws.com [xx.xx.xxx.xx] port 22.
debug1: Connection established.
debug1: identity file /Users/martincepeda1/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/martincepeda1/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/martincepeda1/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/martincepeda1/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/martincepeda1/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/martincepeda1/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/martincepeda1/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /Users/martincepeda1/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_6.9
debug1: Remote protocol version 2.0, remote software version OpenSSH_6.6.1
debug1: match: OpenSSH_6.6.1 pat OpenSSH_6.6.1* compat 0x04000000
debug1: Authenticating to ec2-xx-xx-xxx-xx.us-east-2.compute.amazonaws.com:22 as 'ec2-user'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client chacha20-poly1305@openssh.com <implicit> none
debug1: kex: client->server chacha20-poly1305@openssh.com <implicit> none
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key:xxxxxxxxxxxxxx
debug1: Host 'ec2-xx-xx-xxx-xx.us-east-2.compute.amazonaws.com' is known and matches the ECDSA host key.
debug1: Found key in /Users/martincepeda1/.ssh/known_hosts:6
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /Users/martincepeda1/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Offering RSA public key: /Users/martincepeda1/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Offering RSA public key: /Users/martincepeda1/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Trying private key: /Users/martincepeda1/.ssh/id_dsa
debug1: Trying private key: /Users/martincepeda1/.ssh/id_ecdsa
debug1: Trying private key: /Users/martincepeda1/.ssh/id_ed25519
debug1: No more authentication methods to try.
Permission denied (publickey).
martycep:~ martincepeda1$

Any suggestions/ideas would be appreciated. Thanks.

答:
Warning: Identity file privatekey.pem not accessible: No such file or
  directory

This output says that you don't have any file called "privatekey.pem"

Maybe you changed the key permissions like:

```<code>chmod 0400 **~/.ssh/privatekey.pem**
</code>```

And the file should look like this:

```<code>-r--------+ 1 user group     1671 Jun  5 11:37 privatekey.pem
</code>```

In that scenario you should do:

```<code>ssh -i **~/.ssh/privatekey.pem** ec2-user@ec2-xx-xx-xx-xx.us-east-2.compute.amazonaws.com
</code>```

Check where is your key!

After solving that, don't forget you had to add the public key in the host: ec2-user@ec2-xx-xx-xx-xx.us-east-2.compute.amazonaws.com

```<code>cat 'your_public_key' >>  ~/.ssh/authorized_keys
</code>```

Otherwise your privatekey won't match with the public one in the server.

Title: AWS SSH: Permission denied (publickey)

Body:
Warning: Identity file privatekey.pem not accessible: No such file or
  directory

This output says that you don't have any file called "privatekey.pem"

Maybe you changed the key permissions like:

chmod 0400 **~/.ssh/privatekey.pem**

And the file should look like this:

-r--------+ 1 user group     1671 Jun  5 11:37 privatekey.pem

In that scenario you should do:

ssh -i **~/.ssh/privatekey.pem** ec2-user@ec2-xx-xx-xx-xx.us-east-2.compute.amazonaws.com

Check where is your key!

After solving that, don't forget you had to add the public key in the host: ec2-user@ec2-xx-xx-xx-xx.us-east-2.compute.amazonaws.com

cat 'your_public_key' >>  ~/.ssh/authorized_keys

Otherwise your privatekey won't match with the public one in the server.


问:
Retrieving Entity Metadata using web api
we have a requirement where we have to retrieve an Entity's Metadata.
Exact requirement: Im reading a field value on a form which ia having "entity schema name". With that I need to get that Entity's primary key schema name. Is it possible? If so please help me.
Eg: in that field if I enter "lead" , that web api should fetch me "leadid" and store it in another field.
2. If I enter "incident" , that web api should get me "incidentid" </p>

答:
Yeah, I do agree that there is no need to retrieve if it's primary key schema name as for each entity it's entity schema name + id (Lead + id = leadid). But, we felt it's not a good practice. We achieved this with the following code... It's perfectly working fine. When we provide correct Entity Schema Name, it will automatically populate that Primary Id Attribute into another field.
new_primarykey - where I am populating the Primary Key Schema Name on entering Entity Schema Name in new_entityschemaname fieldon the form.

function getPrimaryKey() {
    var Oldprimary = Xrm.Page.data.entity.attributes.get("new_primarykey").getValue();
    var req = new XMLHttpRequest();
    var entityName = Xrm.Page.data.entity.attributes.get("new_entityschemaname").getValue();
    var url = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" + "EntityDefinitions?$select=PrimaryIdAttribute&$filter=SchemaName eq '" + entityName + "'";
    req.open("GET", url, false);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    req.onreadystatechange = function () {
        Xrm.Page.data.entity.attributes.get("new_primarykey").setValue("");
        if (this.readyState === 4) {

            req.onreadystatechange = null;
            if (this.status === 200) {
                var results = JSON.parse(this.response);
                var primarykey = results.value[0].PrimaryIdAttribute;
                Xrm.Page.data.entity.attributes.get("new_primarykey").setValue(primarykey);

            }
            else {
                Xrm.Utility.alertDialog("Error");
            }
        }
    }
    req.send();
};
 ```

enter image description here

Body:
Yeah, I do agree that there is no need to retrieve if it's primary key schema name as for each entity it's entity schema name + id (Lead + id = leadid). But, we felt it's not a good practice. We achieved this with the following code... It's perfectly working fine. When we provide correct Entity Schema Name, it will automatically populate that Primary Id Attribute into another field.
new_primarykey - where I am populating the Primary Key Schema Name on entering Entity Schema Name in new_entityschemaname fieldon the form.

function getPrimaryKey() {
    var Oldprimary = Xrm.Page.data.entity.attributes.get("new_primarykey").getValue();
    var req = new XMLHttpRequest();
    var entityName = Xrm.Page.data.entity.attributes.get("new_entityschemaname").getValue();
    var url = Xrm.Page.context.getClientUrl() + "/api/data/v8.2/" + "EntityDefinitions?$select=PrimaryIdAttribute&$filter=SchemaName eq '" + entityName + "'";
    req.open("GET", url, false);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    req.onreadystatechange = function () {
        Xrm.Page.data.entity.attributes.get("new_primarykey").setValue("");
        if (this.readyState === 4) {

            req.onreadystatechange = null;
            if (this.status === 200) {
                var results = JSON.parse(this.response);
                var primarykey = results.value[0].PrimaryIdAttribute;
                Xrm.Page.data.entity.attributes.get("new_primarykey").setValue(primarykey);

            }
            else {
                Xrm.Utility.alertDialog("Error");
            }
        }
    }
    req.send();
};

enter image description here


问:
Do you recommend using semicolons after every statement in JavaScript?
In many situations, JavaScript parsers will insert semicolons for you if you leave them out. My question is, do you leave them out?

If you're unfamiliar with the rules, there's a description of semicolon insertion on the Mozilla site. Here's the key point:

If the first through the nth tokens of a JavaScript program form are grammatically valid but the first through the n+1st tokens are not and there is a line break between the nth tokens and the n+1st tokens, then the parser tries to parse the program again after inserting a virtual semicolon token between the nth and the n+1st tokens.

That description may be incomplete, because it doesn't explain @Dreas's example. Anybody have a link to the complete rules, or see why the example gets a semicolon? (I tried it in JScript.NET.)

This stackoverflow question is related, but only talks about a specific scenario.

答:
JavaScript automatically inserts semicolons whilst interpreting your code, so if you put the value of the return statement below the line, it won't be returned:

Your Code:

```<code>return
5
</code>```

JavaScript Interpretation:

```<code>return;
5;
</code>```

Thus, nothing is returned, because of JavaScript's auto semicolon insertion

OwnerDisplayName: anon

LastEditorDisplayName: anon

Body:
JavaScript automatically inserts semicolons whilst interpreting your code, so if you put the value of the return statement below the line, it won't be returned:

Your Code:

return
5

JavaScript Interpretation:

return;
5;

Thus, nothing is returned, because of JavaScript's auto semicolon insertion


问:
Curious behaviour of std::string::operator[] in MSVC
I've been using some semi-iterators to tokenize a std::string, and I've run into a curious problem with operator[]. When constructing a new string from a position using char*, I've used something like the following:

```<code>t.begin = i;
t.end = i + 1;
t.contents = std::string(&arg.second[t.begin], &arg.second[t.end]);
</code>```

where arg.second is a std::string. But, if i is the position of the last character, then arg.second[t.end] will throw a debugging assertion- even though taking a pointer of one-past-the-end is well defined behaviour and even common for primitive arrays, and since the constructor is being called using iterators I know that the end iterator will never be de-referenced. Doesn't it seem logical that arg.second[arg.second.size()] should be a valid expression, producing the equivalent of arg.second.end() as a char*?

答: You're not taking a pointer to one past the end, you're ACCESSING one past the end and then getting the address of that.  Entirely different and while the the former is well defined and well formed, the latter is not either.  I suggest using the iterator constructor, which is basically what you ARE using but do so with iterators instead of char*.  See Alexandre's comment.</p>

Body:
I've been using some semi-iterators to tokenize a std::string, and I've run into a curious problem with operator[]. When constructing a new string from a position using char*, I've used something like the following:

t.begin = i;
t.end = i + 1;
t.contents = std::string(&arg.second[t.begin], &arg.second[t.end]);

where arg.second is a std::string. But, if i is the position of the last character, then arg.second[t.end] will throw a debugging assertion- even though taking a pointer of one-past-the-end is well defined behaviour and even common for primitive arrays, and since the constructor is being called using iterators I know that the end iterator will never be de-referenced. Doesn't it seem logical that arg.second[arg.second.size()] should be a valid expression, producing the equivalent of arg.second.end() as a char*?


问:
Angular 2- Parent with multiple children
I have a situation where at first seemed fairly straight forward to myself but after a couple of days changing my solution structure it has become so convoluted!
Well I have a got a parent/child component relationship as following:

Parent

Child 1

Grandchild 1

Grandchild 2

Grandchild 3

Child 2

Grandchild 1

Grandchild 2

Grandchild 3

Each of these components (parent, child and grand child) has a property as "isValid" and a "validate()" method. All I want to achieve is a solution in which each component validity state depends on its own validate logic PLUS validity of all children component.
Here is a simple validation rules for each component:

Parent isValid = true if all children and grandchildren are valid

Child isValid = true if number of its children neither more than 3 and nor less than 1 Plus all children are valid

grandchild isValid = true if the textbox within it has a value

I have already read this https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#parent-to-child-on-changes and tried all possible ways it describes but neither fits my requirements of having the parent level component valid if ALL its children are valid!

thanks for your advice in advance :)

答:
In the documentation you mention you can use parent-listens-for-child-event. In each child you will have an EventEmitter like so:

```<code>@Output() isValid = new EventEmitter<boolean>();

validate(valid: boolean) {
    this.isValid.emit(valid);
  }
</code>```

that will be de-validated through a button for example:

```<code><button (click)="validate(true)">Make child Valid</button>
</code>```

The parent binds an event handler that responds to the child event payload $event and calculates its own validity:

```<code>children_valid:boolean[]; // for each parent children_valid.length==number_of_children
valid:boolen;
onValidate(valid: boolean, child_number: number) {
   this.children_valid[child_number-1]=valid;
   this.children_valid.some(x=>x==false) ? this.valid=false : this.valid=true
}

// Inside the template of the parent:
<my-child1
  (onValidate)="onValidate($event,1)">
</my-child1>
<my-child2
  (onValidate)="onValidate($event,2)">
</my-child2>
<my-child3
  (onValidate)="onValidate($event,3)">
</my-child3>
</code>```

If a component is a parent and a child it must emit and receive an event when something changes.

Body:
In the documentation you mention you can use parent-listens-for-child-event. In each child you will have an EventEmitter like so:

@Output() isValid = new EventEmitter<boolean>();

validate(valid: boolean) {
    this.isValid.emit(valid);
  }

that will be de-validated through a button for example:

<button (click)="validate(true)">Make child Valid</button>

The parent binds an event handler that responds to the child event payload $event and calculates its own validity:

children_valid:boolean[]; // for each parent children_valid.length==number_of_children
valid:boolen;
onValidate(valid: boolean, child_number: number) {
   this.children_valid[child_number-1]=valid;
   this.children_valid.some(x=>x==false) ? this.valid=false : this.valid=true
}

// Inside the template of the parent:
<my-child1
  (onValidate)="onValidate($event,1)">
</my-child1>
<my-child2
  (onValidate)="onValidate($event,2)">
</my-child2>
<my-child3
  (onValidate)="onValidate($event,3)">
</my-child3>

If a component is a parent and a child it must emit and receive an event when something changes.


问:
get auto_increment value from mysql to jtextfield in java
i have created a two column in mysql

```<code>Category    varchar(30) YES
Serial_No   int(11) NO  PRI     auto_increment
</code>```

how to retrieve Category column using Serial_No in mysql and set this category data in Jtextfield in java.

答:
Step 1:

In your Java Swing code,

Connect to MySQL using the corresponding Driver.

Connection con =DriverManager.getConnection (hostname:port/db_name, user, password)

Step 2:

Write the query to fetch the required detail. In your case, the query will look like,

select Category from table_name where Serial_No='your_value'

Step 3:

With the Connection object, create an instance of Statement.

Statement mysqlStatement = yourConnectionObject.createStatement ( )

Step 4:

Execute the query with the help of Statement

ResultSet rs = mysqlStatement.execute (query)

Step 5:

Iterate ResultSet, get Category and assign it to JTextField.

while (rs.next ( ))
{
   String category = rs.getString ("Category")
   JTextField myTextField = new JTextField (category); // or if you have already a text field, then myTextField.setText (category); this setText ( ) method is inherited from JTextComponent
}

Step 6:

Once everything is over don't forget to make your frame visible.

myJFrame.setVisible (true)

Body:
i have created a two column in mysql

Category    varchar(30) YES
Serial_No   int(11) NO  PRI     auto_increment

how to retrieve Category column using Serial_No in mysql and set this category data in Jtextfield in java.


问:
Rails ActiveRecord: Skip validations for associations
I'm re-asking this question because the code and example is wrong (it actually works in the case shown).

Given these models:

```<code>class Author < ActiveRecord::Base
  has_many :books
  validates_presence_of :email
end

class Book < ActiveRecord::Base
  belongs_to :author
  validates_presence_of :title
end
</code>```

We can skip validations when creating a Book:

```<code>b = Book.new
b.save(:validate => false)
</code>```

But if we retrieve the invalid Book from the database and assign it to the association in Author, we aren't allowed to save Author:

```<code>a = Author.new
a.email = "foo"
a.books = Book.all
a.save!
</code>```

This is the error:

ActiveRecord::RecordInvalid: Validation failed: Books is invalid

How do we skip validations for the associated Book models without skipping them for Author?

Note that saying has_many :books, :validate => false in Author doesn't help: the association is silently discarded with the Author is saved.

答:
Try that

```<code>class Author < ActiveRecord::Base
  has_many :books, :validate => false
  validates_presence_of :email
  after_save :save_invalid_books

  def save_invalid_books
    books.each do |b|
      b.save(false)
    end
  end
end
</code>```

As far as I understand, the validate => false only allows you to save author without being stopped by an invalid book, but to save the association you need a valid book as you will change the author_id key.
You can't change rails internals, but you can still trick it, by saving the author without validation, and then updating each book and forcing save (with save(false)) right after.

Of course this code can be enhanced in many ways, as it's probably not necessary to save all books each time for a start, but you get the idea.

Body:
I'm re-asking this question because the code and example is wrong (it actually works in the case shown).

Given these models:

class Author < ActiveRecord::Base
  has_many :books
  validates_presence_of :email
end

class Book < ActiveRecord::Base
  belongs_to :author
  validates_presence_of :title
end

We can skip validations when creating a Book:

b = Book.new
b.save(:validate => false)

But if we retrieve the invalid Book from the database and assign it to the association in Author, we aren't allowed to save Author:

a = Author.new
a.email = "foo"
a.books = Book.all
a.save!

This is the error:

ActiveRecord::RecordInvalid: Validation failed: Books is invalid

How do we skip validations for the associated Book models without skipping them for Author?

Note that saying has_many :books, :validate => false in Author doesn't help: the association is silently discarded with the Author is saved.

Body:
Try that

class Author < ActiveRecord::Base
  has_many :books, :validate => false
  validates_presence_of :email
  after_save :save_invalid_books

  def save_invalid_books
    books.each do |b|
      b.save(false)
    end
  end
end

As far as I understand, the validate => false only allows you to save author without being stopped by an invalid book, but to save the association you need a valid book as you will change the author_id key.
You can't change rails internals, but you can still trick it, by saving the author without validation, and then updating each book and forcing save (with save(false)) right after.

Of course this code can be enhanced in many ways, as it's probably not necessary to save all books each time for a start, but you get the idea.


问:
The sum seems to be 40 but how
I am trying to explore php and to learn it a little bit but when i tried this

```<code>    $n=2;
    $a=5;
    $x=3;
    $s=0;
    $i;
    for($i=1; $i<=($n+2);$i++)
    $s=$s+(2*$i+$a);

   //$g=3*$x+4*$s;
   echo "$s";
</code>```

the result seems to be 40, and when i calculate it by myself the sum of s is 13
I know this is simple but I cannot figure it out.

Title: The sum seems to be 40 but how

Body:
I am trying to explore php and to learn it a little bit but when i tried this

    $n=2;
    $a=5;
    $x=3;
    $s=0;
    $i;
    for($i=1; $i<=($n+2);$i++)
    $s=$s+(2*$i+$a);

   //$g=3*$x+4*$s;
   echo "$s";

the result seems to be 40, and when i calculate it by myself the sum of s is 13
I know this is simple but I cannot figure it out.

Body:
N=2;
A=5;
X=3;
S=0;

for
  I=1 => S (0) = 0 + (2*1+5) = 7

  I=2 => S (7) = 7 + (2*2+5) = 16

  I=3 => S (16) =  16 + (2*3+5) = 27

  I=4 => S (27) = 27 (2*4+5) = 40


问:
libgcc_s_sjlj-1.dll is missing from your computer
After downloading GCC 4.9.2 TDM (SJLJ)-32 bit for SFML for codeblocks, I can build and run but can not run .exe files. Whenever i try to run .exe files, an error message shows up: "The program can't start because libgcc_s_sjlj-1.dll is missing from your computer. Try reinstalling the program to fix this problem. " I tried going to settings->compilers -> linker settings -> other linker settings -> added -shared-libgcc and -shared-libstdc++ , but same error message shows up still. Can anyone help me? I may need specific answers because I am a newbie. I spent hours trying to figure this out...</p>

答:
As always on Windows, any DLL with which a program is linked at buildtime
must be found at runtime by the OS program loader in one of the directories
where it looks for DLLs as per the Windows Dynamic-Link Library Search Order.

Therefore make sure that libgcc_s_sjlj-1.dll is in one of those
directories. The crudest way of doing this is to copy the DLL to
the same directory that contains the program. This DLL is your GCC compiler's runtime library, and you will find it in <Your_TDM_GCC_Install_Dir>/bin - e.g. C:/TDM-GCC-64/bin


Title: The sum seems to be 40 but how

Body:
Using pseudo code:

n = 2
a = 5
s = 0

for ( i in { 1...4 } ) {

    s = s + ( ( 2 * i ) + 5 )
}

So we have

s =  0 + ( ( 2 * 1 ) + 5 ) =  0 +  7 = 7
s =  7 + ( ( 2 * 2 ) + 5 ) =  7 +  9 = 16
s = 16 + ( ( 2 * 3 ) + 5 ) = 16 + 11 = 27
s = 27 + ( ( 2 * 4 ) + 5 ) = 27 + 13 = 40


问:
PHP Shouldnot Repeat and should be from an array
I'm trying to build a script that does two thing.
1) The Numbers should not repeat.
2) The numbers should be from an array called $id.

```<code><?php
$a = array(); // final array which will have our id's to display
$id = array(1, 3, 5, 7, 9); //final array should contain a number only from this list
$itemstoshow = 3; // how many items to display
for($i = 0; $i < $itemstoshow; $i++) {
    do {
        $a[$i] = assignid(9);
        $chkid = checkeer($a[$i], $i);
        $chkdata = chkdata($a[$i], $i);
    } while($chkdata == "nonexist" or $chkid == "repeatedid");
}

// display numbers in the array
for($i = 0; $i < $itemstoshow; $i++) {
    echo "Item " . $a[$i] . "--------";
}

// check for redundancy function
function checkeer($x, $y)
{  //first parameter is query aray second is counter
    global $a;
    $err = 0;
    // check if repeating number
    for($i = 0; $i <= $y - 1; $i++) {
        if($x == $a[$i]) {
            $err = 1;
        }
    }
    if($err == 1) {
        return "repeatedid";
    }
}

//check if array $a holds value from $id or not
function chkdata($x, $y)
{
    global $a;
    global $id;
    for($i = 0; $i <= $y - 1; $i++) {
        if($x !== $id[$i]) {
            return "nonexist";
        }
    }

}

//assign id function
function assignid($x)
{
    return rand(1, $x);
}
</code>```

problem number 1 solved problem number 2 still not solved please help me.
the code should show 3 numbers from 1 to 9 which donot repeat and are in the array $id

答:
You could use a combination of array_rand and array_map to get random values from the array that has the values your basing the randomization. Take a look:

```<code>$id = array(1,3,5,7,9); //final array should contain a number only from this list
$itemstoshow = 3;
$values = array_map(function($item) use($id){
    return $id[$item];
}, array_rand($id, $itemstoshow));

print_r($values);
</code>```

Output:

```<code>Array
(
    [0] => 1
    [1] => 3
    [2] => 9
)
</code>```

Running again:

```<code>Array
(
    [0] => 3
    [1] => 7
    [2] => 9
)
</code>```

Body:
I'm trying to build a script that does two thing.
1) The Numbers should not repeat.
2) The numbers should be from an array called $id.

<?php
$a = array(); // final array which will have our id's to display
$id = array(1, 3, 5, 7, 9); //final array should contain a number only from this list
$itemstoshow = 3; // how many items to display
for($i = 0; $i < $itemstoshow; $i++) {
    do {
        $a[$i] = assignid(9);
        $chkid = checkeer($a[$i], $i);
        $chkdata = chkdata($a[$i], $i);
    } while($chkdata == "nonexist" or $chkid == "repeatedid");
}

// display numbers in the array
for($i = 0; $i < $itemstoshow; $i++) {
    echo "Item " . $a[$i] . "--------";
}

// check for redundancy function
function checkeer($x, $y)
{  //first parameter is query aray second is counter
    global $a;
    $err = 0;
    // check if repeating number
    for($i = 0; $i <= $y - 1; $i++) {
        if($x == $a[$i]) {
            $err = 1;
        }
    }
    if($err == 1) {
        return "repeatedid";
    }
}

//check if array $a holds value from $id or not
function chkdata($x, $y)
{
    global $a;
    global $id;
    for($i = 0; $i <= $y - 1; $i++) {
        if($x !== $id[$i]) {
            return "nonexist";
        }
    }

}

//assign id function
function assignid($x)
{
    return rand(1, $x);
}

problem number 1 solved problem number 2 still not solved please help me.
the code should show 3 numbers from 1 to 9 which donot repeat and are in the array $id

Body:
You could use a combination of array_rand and array_map to get random values from the array that has the values your basing the randomization. Take a look:

$id = array(1,3,5,7,9); //final array should contain a number only from this list
$itemstoshow = 3;
$values = array_map(function($item) use($id){
    return $id[$item];
}, array_rand($id, $itemstoshow));

print_r($values);

Output:

Array
(
    [0] => 1
    [1] => 3
    [2] => 9
)

Running again:

Array
(
    [0] => 3
    [1] => 7
    [2] => 9
)


问:
How to average the difference between 2 rows
No rush, this is pure curiosity as i've already finished the project but i want to know if there's a faster and cleaner way of averaging the difference between 2 rows.

I have 2 rows of data and i need to average the difference between the 2.

i.e.

```<code>Row1  5 6 8 4
Row2  4 7 8 9
</code>```

what i want to average

```<code>1,-1,0,-5
</code>```

I tried this formula but failed.

```<code>{=AVERAGE(G26:U26-G28:U28)}
</code>```

答:
Average of the differences is equal to the difference of the averages, so

```<code>=AVERAGE(Row1)-AVERAGE(Row2)
</code>```

Hope that helps

Body:
No rush, this is pure curiosity as i've already finished the project but i want to know if there's a faster and cleaner way of averaging the difference between 2 rows.

I have 2 rows of data and i need to average the difference between the 2.

i.e.

Row1  5 6 8 4
Row2  4 7 8 9

what i want to average

1,-1,0,-5

I tried this formula but failed.

{=AVERAGE(G26:U26-G28:U28)}

Body:
Average of the differences is equal to the difference of the averages, so

=AVERAGE(Row1)-AVERAGE(Row2)

Hope that helps


答:
A string is not a primitive array, so I'd say the implementation is free to add some debug diagnostics if you are doing something dangerous like accessing elements outside its range. I would guess that a release build will probably work.

But...

For what you are trying to do, why not just use the basic_string( const basic_string& str, size_type index, size_type length ); constructor to create the sub strings?

Title: Curious behaviour of std::string::operator[] in MSVC


问:
Find out if a Security Account Manager (SAM) name is a user or a group
edited from original question because the real problem was something unrelated to the question

I got a list of trustees from NTFS permissions and now I want to expand the groups to show membership. If I have a SAM name like MyDomain\name, there's no indication of whether that is a group or not. The Get-ADobject command has an ObjectClass property which will indicate group or user if this is an Active Directory domain object. One can use:
Get-ADObject -filter 'SamAccountName -eq "My Users"' or
$sam = "My Users"
Get-ADObject -filter 'SamAccountName -eq $sam'
Thanks to JPBlanc who had an alternate form of writing that with a script block and some other suggestions.
And thanks, user2142466. That looks like a good suggestion for my original script.

答:
I received a list and was asked to determine whether the objects were users or group, and I came up with this.  It worked!</p>

```<code>cls
$Users = @()
$Groups = @()
$list = Get-Content z:\pcm.txt
Foreach ($o in $list)
{
$ObjectClass = (Get-ADObject -Filter {SamAccountName -eq $o}).ObjectClass
  If ($ObjectClass -eq "User")
  {
  $U = Get-ADUser -Properties * -Identity $o
  $User = "" | Select FullUserName, LoginID, Description
  $User.FullUserName = $U.DisplayName
  $User.LoginID = $U.SamAccountName
  $User.Description = $U.description
  $Users += $User
  }
 Else
 {
 If ($ObjectClass -eq "Group")
 {
 $G = Get-ADGroup -Properties * -Identity $o
 $Group = "" | Select GroupName, Description
 $Group.GroupName = $G.Name
 $Group.Description = $G.Description
 $Groups += $Group
 }
}
}
$Users | Export-Csv z:\Users.csv -NoTypeInformation
$Groups | Export-Csv z:\Groups.csv -NoTypeInformation
</code>```

Body:
I received a list and was asked to determine whether the objects were users or group, and I came up with this.  It worked!

cls
$Users = @()
$Groups = @()
$list = Get-Content z:\pcm.txt
Foreach ($o in $list)
{
$ObjectClass = (Get-ADObject -Filter {SamAccountName -eq $o}).ObjectClass
  If ($ObjectClass -eq "User")
  {
  $U = Get-ADUser -Properties * -Identity $o
  $User = "" | Select FullUserName, LoginID, Description
  $User.FullUserName = $U.DisplayName
  $User.LoginID = $U.SamAccountName
  $User.Description = $U.description
  $Users += $User
  }
 Else
 {
 If ($ObjectClass -eq "Group")
 {
 $G = Get-ADGroup -Properties * -Identity $o
 $Group = "" | Select GroupName, Description
 $Group.GroupName = $G.Name
 $Group.Description = $G.Description
 $Groups += $Group
 }
}
}
$Users | Export-Csv z:\Users.csv -NoTypeInformation
$Groups | Export-Csv z:\Groups.csv -NoTypeInformation


问:
SQL how can I use distinct on with the count function inside a join
I am new to sql and am using postgres 9.6, I have 2 queries and I would like to join them into 1 . I want to use the Count function and order by a field in descending order which I have done here

1st query

```<code>select count(s.city)::text as most_topics,
city::text || ', ' || state::text AS location from streams s
group by (location) order by most_topics desc limit 5
</code>```

That first query is exactly the information I want in the same exact order, the issue is that I need to do an inner join and get data from a second table which I have done here . This second query gets all the data I need however I do not know how to use the Count() function in the second query any suggestions would be great . To sum things up the 1st query gives me halve the data I want as I need to join on a second data called zips on the fields (city and state) . The second query gives me all the data I need but I can't seem to have the Count() function working there .

2nd query

```<code>select DISTINCT ON(s.city,s.state)s.city as location,
z.latitudes,z.statelong,z.longitudes,z.thirtylatmin,z.thirtylatmax
 ,z.longitudes,z.thirtylatmin,z.thirtylatmax,
 z.thirtylonmin,z.thirtylonmax from streams s inner join zips z
 on (s.city=z.city and s.state=z.state) where  order by s.city,s.state desc limit 5
</code>```

first query results

second query results: Lutz is supposed to be on top not bottom

答:
You can use CTEs or subqueries:</p>

```<code>with l5 as (
      select count(s.city)::text as most_topics,
             city::text || ', ' || state::text AS location,
             city, state
      from streams s
      group by city, state
      order by most_topics desc
      limit 5
     )
select distinct on (l5.locatin) l5.location, l5.most_topics, z.*
from l5 join
     zips z
     on l5.city = z.city and l5.state = z.state
order by l5.location;
</code>```

Body:
I am new to sql and am using postgres 9.6, I have 2 queries and I would like to join them into 1 . I want to use the Count function and order by a field in descending order which I have done here

1st query

select count(s.city)::text as most_topics,
city::text || ', ' || state::text AS location from streams s
group by (location) order by most_topics desc limit 5

That first query is exactly the information I want in the same exact order, the issue is that I need to do an inner join and get data from a second table which I have done here . This second query gets all the data I need however I do not know how to use the Count() function in the second query any suggestions would be great . To sum things up the 1st query gives me halve the data I want as I need to join on a second data called zips on the fields (city and state) . The second query gives me all the data I need but I can't seem to have the Count() function working there .

2nd query

select DISTINCT ON(s.city,s.state)s.city as location,
z.latitudes,z.statelong,z.longitudes,z.thirtylatmin,z.thirtylatmax
 ,z.longitudes,z.thirtylatmin,z.thirtylatmax,
 z.thirtylonmin,z.thirtylonmax from streams s inner join zips z
 on (s.city=z.city and s.state=z.state) where  order by s.city,s.state desc limit 5

first query results

second query results: Lutz is supposed to be on top not bottom

Body:
You can use CTEs or subqueries:

with l5 as (
      select count(s.city)::text as most_topics,
             city::text || ', ' || state::text AS location,
             city, state
      from streams s
      group by city, state
      order by most_topics desc
      limit 5
     )
select distinct on (l5.locatin) l5.location, l5.most_topics, z.*
from l5 join
     zips z
     on l5.city = z.city and l5.state = z.state
order by l5.location;


问:
How to export a org-mode table to LaTeX with the correct placement [h]?
I'm trying to export a table to LaTeX form my org-file which looks like this:

```<code>    #+LATEX_HEADER: \usepackage{adjustbox}
    * table test

    #+begin_table
    #+LATEX: \caption{my caption}
    label:tab:mylabel
    #+ATTR_LATEX: :placement [h]
    #+LATEX: \centering
    #+LATEX: \adjustbox{max width=\linewidth}{
    #+ATTR_LATEX: :center nil
    |    |                          |
    | id | Question                 |
    |----+--------------------------|
    |    |                          |
    |  1 | Does it export with [h]? |
    #+end_table
</code>```

I want to get the exported TeX to look like this:

```<code>    ...
    \begin{table}[h]
    \caption{my caption}
    \label{tab:mylabel}
    \centering
    \adjustbox{max width=\linewidth}{
    \begin{tabular}{ll}
     & \\
    id & Question\\
    \hline
     & \\
    1 & Does it export with [h]?\\
    \end{tabular}
    \end{table}
    ...
</code>```

but I'm just getting

```<code>    ...
    \begin{table}
    \caption{my caption}
    \label{tab:mylabel}
    \centering
    \adjustbox{max width=\linewidth}{
    \begin{tabular}{ll}
     & \\
    id & Question\\
    \hline
     & \\
    1 & Does it export with [h]?\\
    \end{tabular}
    \end{table}
    ...
</code>```

using  the following versions

GNU Emacs 25.1.1 (x86_64-apple-darwin15.5.0, NS appkit-1404.47 Version 10.11.5 (Build 15F34)) of 2017-01-06

Org mode version 9.0.5 (release_9.0.5-444-g998576 @ ~/git/org-mode/lisp/)

I also tried

#+ATTR_LATEX: :float t :placement [h]

#+ATTR_LATEX: :center nil :float t :placement [h]

#+ATTR_LATEX: :center nil :placement [h]

#+begin_table :placement [h]

#+begin_table :float t :placement [h]

My search on the internet only found some emails from 2010, when org-latex.el existed. Since it still exists in the documentation I thought it should work somehow.

So can anyone help me? Or leak the magic words I have to feed Google with to find my answer?

Thx @Nick, we're on the right way but sadly not at the end of it.

Well I did not want to break the parsing, it explains some things.
I've got some more requirements and things to explain.

At First some of my tables are a bit wider like this:

```<code>   | id | Question                                                                                |
   |----+---------------------------------------------------------------------------------------------------------------------------|
   |  1 | Does it export with [h]?                                                                                |
   |  2 | I have some tables witch are very wide so What if you have a really wide table wich needs to be shrinked to the right size |
</code>```

The Adjustbox package is the first I found that shrinks the whole table to the correct width. I tried your suggested tabularx but it's not shrinking the contents of the table. Without the shrinking most of my tables look weird.

The second Thing, I'm using org-ref. With your version (which I would prefer when the 2 probs are gone) exports to:

```<code>   \caption{\label{tab:org56e3a68}
   My caption}
</code>```

I added #+label: tab:my-label as intended in the documentation. Added it before and after #+caption: and #+name: but it does not change anything in the .tex file.

any idea?

答:
I can do everything you want, except the adjustbox stuff with this:

```<code>#+BIND: org-latex-prefer-user-labels t
* table test

#+caption: My caption
#+name:my-label
#+ATTR_LATEX: :placement [h] :center t
|    |                          |
| id | Question                 |
|----+--------------------------|
|    |                          |
|  1 | Does it export with [h]? |
</code>```

I don't know what \adjustbox does or how it has to be used and where it has to be placed; however, you can't add #+LATEX: lines in between the #+caption and the table: they apparently break the parsing.

You could add another attribute to the ATTR_LATEX line:

```<code>#+ATTR_LATEX: :placement [h] :center t :width \linewidth
</code>```

but it's not clear that does what you want. Also, I just tested and it does not do anything: that's because the standard environment is tabular which does not take a width argument. The following works:

```<code>#+ATTR_LATEX: :environment tabularx :placement [h] :center t :width \linewidth
</code>```

but you also have to add

```<code>#+LATEX_HEADER: \usepackage{tabularx}
</code>```

at the top of the file.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to export a table to LaTeX form my org-file which looks like this:

    #+LATEX_HEADER: \usepackage{adjustbox}
    * table test

    #+begin_table
    #+LATEX: \caption{my caption}
    label:tab:mylabel
    #+ATTR_LATEX: :placement [h]
    #+LATEX: \centering
    #+LATEX: \adjustbox{max width=\linewidth}{
    #+ATTR_LATEX: :center nil
    |    |                          |
    | id | Question                 |
    |----+--------------------------|
    |    |                          |
    |  1 | Does it export with [h]? |
    #+end_table

I want to get the exported TeX to look like this:

    ...
    \begin{table}[h]
    \caption{my caption}
    \label{tab:mylabel}
    \centering
    \adjustbox{max width=\linewidth}{
    \begin{tabular}{ll}
     & \\
    id & Question\\
    \hline
     & \\
    1 & Does it export with [h]?\\
    \end{tabular}
    \end{table}
    ...

but I'm just getting

    ...
    \begin{table}
    \caption{my caption}
    \label{tab:mylabel}
    \centering
    \adjustbox{max width=\linewidth}{
    \begin{tabular}{ll}
     & \\
    id & Question\\
    \hline
     & \\
    1 & Does it export with [h]?\\
    \end{tabular}
    \end{table}
    ...

using  the following versions

GNU Emacs 25.1.1 (x86_64-apple-darwin15.5.0, NS appkit-1404.47 Version 10.11.5 (Build 15F34)) of 2017-01-06

Org mode version 9.0.5 (release_9.0.5-444-g998576 @ ~/git/org-mode/lisp/)

I also tried

#+ATTR_LATEX: :float t :placement [h]

#+ATTR_LATEX: :center nil :float t :placement [h]

#+ATTR_LATEX: :center nil :placement [h]

#+begin_table :placement [h]

#+begin_table :float t :placement [h]

My search on the internet only found some emails from 2010, when org-latex.el existed. Since it still exists in the documentation I thought it should work somehow.

So can anyone help me? Or leak the magic words I have to feed Google with to find my answer?

Thx @Nick, we're on the right way but sadly not at the end of it.

Well I did not want to break the parsing, it explains some things.
I've got some more requirements and things to explain.

At First some of my tables are a bit wider like this:

   | id | Question                                                                                |
   |----+---------------------------------------------------------------------------------------------------------------------------|
   |  1 | Does it export with [h]?                                                                                |
   |  2 | I have some tables witch are very wide so What if you have a really wide table wich needs to be shrinked to the right size |

The Adjustbox package is the first I found that shrinks the whole table to the correct width. I tried your suggested tabularx but it's not shrinking the contents of the table. Without the shrinking most of my tables look weird.

The second Thing, I'm using org-ref. With your version (which I would prefer when the 2 probs are gone) exports to:

   \caption{\label{tab:org56e3a68}
   My caption}

I added #+label: tab:my-label as intended in the documentation. Added it before and after #+caption: and #+name: but it does not change anything in the .tex file.

any idea?

Body:
I can do everything you want, except the adjustbox stuff with this:

#+BIND: org-latex-prefer-user-labels t
* table test

#+caption: My caption
#+name:my-label
#+ATTR_LATEX: :placement [h] :center t
|    |                          |
| id | Question                 |
|----+--------------------------|
|    |                          |
|  1 | Does it export with [h]? |

I don't know what \adjustbox does or how it has to be used and where it has to be placed; however, you can't add #+LATEX: lines in between the #+caption and the table: they apparently break the parsing.

You could add another attribute to the ATTR_LATEX line:

#+ATTR_LATEX: :placement [h] :center t :width \linewidth

but it's not clear that does what you want. Also, I just tested and it does not do anything: that's because the standard environment is tabular which does not take a width argument. The following works:

#+ATTR_LATEX: :environment tabularx :placement [h] :center t :width \linewidth

but you also have to add

#+LATEX_HEADER: \usepackage{tabularx}

at the top of the file.


问:
How to use Eigen library for Arduino within Atmel Studio 7?

I tried to use Eigen library within the Arduino IDE fist. Then I got the error:

fatal error: eigenfolder/Eigen/Dense: No such file or directory

Then I tried to use EigenArduino library. Then I got an error

fatal error  cstddef  No such file or directory #include cstddef

So I realized that there is probably a lot of standard library that is not linked/implemented into this Arduino IDE. So before getting everythin I decided to move into ATMEL STUDIO 7. My hope was that Atmel Studio gets everything automatically.

But in order to use my previous Arduino Sketches, I also installed Visual Micro that is a Plug-In for Atmel Studio so that you can use everything like in the Arduino IDE.

==> So the problem starts all over again. Same errors in Atmel Studio 7. It seems like I am just using the Atmel Studio 7 Editor now, but the same compiler settings, libraries etc. (Since I am a newbie :-) this is just a guess ).

How can I link all this together? Can somebody please help?

答:
How did you add the library ?

Did you use libraries manager in Arduino IDE ?

Or you downloaded the library separately ?

I found out that using libraries manager solve most compatibility issues.


问:
Are the Oct 2010 Macbook Airs sufficiently capable to run all the tools to develop iPhone apps on?
Pretty much as the title says. I'll likely use Monotouch for some/all projects if that makes a difference (noting this still needs a Mac).

I've read this Question...

Macbook Air for iPhone Development?

...and see the related answers note performance issues and buggy/non performant screen spanning issues on previous generation models.

I'd like to know if these two issues are resolved with the new specs.

Observations on performance running Win7 and WP7 under bootcamp are welcome but not required. Related question raised here looking for specifics on WDDM1.1 compliance on this model if you care to comment there.

edit: formating/highlighting.

答:
As both my answer and Marco Arment's in the other question indicate, the previous generation MacBook Air was more than capable of running all the developer tools.  In fact, Marco's review was based on the original MacBook Air, which was even less capable than the second-generation one that I had.

Performance is a relative metric, and it only improves with these later models.  The second-generation MacBook Air that I had was never the bottleneck in my development process.

Pretty much all of the bugs were worked out by the second-generation model that I had.  I noticed no issues with driving external monitors from the system at all.  Again, Marco was basing his review on the very first build of the Air, which had some known issues.

Screen size will be an issue on the go when developing with many windows open, or trying to simulate the iPad, but that would be the same with a 13" laptop of another type.  I imagine you'll be connecting this into an external display for extended development at your desk anyway.

The only reason I no longer am using it as my primary machine is that I found I didn't need the portability after getting an iPad.


问:
Gulp event.js:163 throw err; // Unhandled 'error' event
I have taken git clone and run npm install without sudo, the same setup was working perfect on windows machine but its breaking on Mac OSX:

Here is my gulpfile.js

```<code>var gulp        =   require('gulp');

// Load plugins
var plugin = require('gulp-load-plugins')({
  pattern: '*'
});

var paths = {
  css:      'app/resources/css',
  sass:     'app/resources/scss',
  js:       'app/**/*.module.js, app/components/**/*.js',
  html:     'app/*.html'
};

//  Compile SASS using Compass,
//  Compass required as we using its utitlities
gulp.task('compass', function(){
  return gulp.src( paths.sass + '/*.scss' )
    .pipe(plugin.compass({
      css: paths.css,
      sass: paths.sass,
      task: 'watch',
      comments: false
    }));
});

// Watch task, keep checking for changes
gulp.task('watch', function(){
  gulp.watch([
    paths.sass + '/*.scss',
    paths.html,
    paths.js
  ]).on('change', plugin.browserSync.reload);
});

//  LiveReload Task
gulp.task('serve', function(){
    plugin.browserSync.init([], {
      server:  {
        baseDir: ['./', './app']
      }
  });
});

// Build HTML
gulp.task('html', function(){
  return gulp.src('app/*.html')
              .pipe(plugin.useref())
              .pipe(gulp.dest('dist'));
});

// Copy Images
gulp.task('images', function(){
  return gulp.src('app/resources/images/*')
            .pipe(gulp.dest('dist/resources/images/'));
});

// Copy Fonts
gulp.task('fonts', function(){
  return gulp.src('app/resources/fonts/*')
            .pipe(gulp.dest('dist/resources/fonts/'));
});

// Copy Templates
gulp.task('templates', function(){
  return gulp.src('app/components/**/*')
            .pipe(gulp.dest('dist/components/'));
});

// Clean
gulp.task('clean', function(){
  return gulp.src([
      'dist/base', 'dist/components', 'dist/resources'
    ], {
      read: false
    })
    .pipe( plugin.clean());
});

// Build
gulp.task('build', [ 'compass', 'html', 'images', 'fonts', 'templates', 'serve'])

// Default
gulp.task('default', ['clean'], function(){
    gulp.start('build');
});
</code>```

I am getting following error on terminal, thinks path is picking wrong dont know where i made mistake:

```<code>events.js:163
      throw er; // Unhandled 'error' event
      ^

Error: Error: File not found with singular glob: /learning/recharge-desktop-code/learning/recharge-desktop-code/app/resources/css/common.css
    at DestroyableTransform.<anonymous> (/learning/recharge-desktop-code/node_modules/gulp-useref/index.js:65:28)
    at emitOne (events.js:101:20)
    at DestroyableTransform.emit (events.js:191:7)
    at emitOne (events.js:101:20)
    at Through2.emit (events.js:191:7)
    at OrderedStreams.<anonymous> (/learning/recharge-desktop-code/node_modules/gulp-useref/node_modules/glob-stream/index.js:140:20)
    at emitOne (events.js:96:13)
    at OrderedStreams.emit (events.js:191:7)
    at emitOne (events.js:96:13)
    at DestroyableTransform.emit (events.js:191:7)
</code>```

答:
Maybe is this problem.
It's say

```<code>Thanks! We are aware of this issue and a fix is being worked on. Closing as this is a duplicate of #12841. Be on the lookout for the next v7.x release (which will probably be next week). Thanks!
</code>```

https://github.com/nodejs/node/issues/13077

Body:
I have taken git clone and run npm install without sudo, the same setup was working perfect on windows machine but its breaking on Mac OSX:

Here is my gulpfile.js

var gulp        =   require('gulp');

// Load plugins
var plugin = require('gulp-load-plugins')({
  pattern: '*'
});

var paths = {
  css:      'app/resources/css',
  sass:     'app/resources/scss',
  js:       'app/**/*.module.js, app/components/**/*.js',
  html:     'app/*.html'
};

//  Compile SASS using Compass,
//  Compass required as we using its utitlities
gulp.task('compass', function(){
  return gulp.src( paths.sass + '/*.scss' )
    .pipe(plugin.compass({
      css: paths.css,
      sass: paths.sass,
      task: 'watch',
      comments: false
    }));
});

// Watch task, keep checking for changes
gulp.task('watch', function(){
  gulp.watch([
    paths.sass + '/*.scss',
    paths.html,
    paths.js
  ]).on('change', plugin.browserSync.reload);
});

//  LiveReload Task
gulp.task('serve', function(){
    plugin.browserSync.init([], {
      server:  {
        baseDir: ['./', './app']
      }
  });
});

// Build HTML
gulp.task('html', function(){
  return gulp.src('app/*.html')
              .pipe(plugin.useref())
              .pipe(gulp.dest('dist'));
});

// Copy Images
gulp.task('images', function(){
  return gulp.src('app/resources/images/*')
            .pipe(gulp.dest('dist/resources/images/'));
});

// Copy Fonts
gulp.task('fonts', function(){
  return gulp.src('app/resources/fonts/*')
            .pipe(gulp.dest('dist/resources/fonts/'));
});

// Copy Templates
gulp.task('templates', function(){
  return gulp.src('app/components/**/*')
            .pipe(gulp.dest('dist/components/'));
});

// Clean
gulp.task('clean', function(){
  return gulp.src([
      'dist/base', 'dist/components', 'dist/resources'
    ], {
      read: false
    })
    .pipe( plugin.clean());
});

// Build
gulp.task('build', [ 'compass', 'html', 'images', 'fonts', 'templates', 'serve'])

// Default
gulp.task('default', ['clean'], function(){
    gulp.start('build');
});

I am getting following error on terminal, thinks path is picking wrong dont know where i made mistake:

events.js:163
      throw er; // Unhandled 'error' event
      ^

Error: Error: File not found with singular glob: /learning/recharge-desktop-code/learning/recharge-desktop-code/app/resources/css/common.css
    at DestroyableTransform.<anonymous> (/learning/recharge-desktop-code/node_modules/gulp-useref/index.js:65:28)
    at emitOne (events.js:101:20)
    at DestroyableTransform.emit (events.js:191:7)
    at emitOne (events.js:101:20)
    at Through2.emit (events.js:191:7)
    at OrderedStreams.<anonymous> (/learning/recharge-desktop-code/node_modules/gulp-useref/node_modules/glob-stream/index.js:140:20)
    at emitOne (events.js:96:13)
    at OrderedStreams.emit (events.js:191:7)
    at emitOne (events.js:96:13)
    at DestroyableTransform.emit (events.js:191:7)

Body:
Maybe is this problem.
It's say

Thanks! We are aware of this issue and a fix is being worked on. Closing as this is a duplicate of #12841. Be on the lookout for the next v7.x release (which will probably be next week). Thanks!

https://github.com/nodejs/node/issues/13077


问:
NHibernate and MySql Missing column Exception
From time to time my web application begins throwing the following errors.

Using NHibernate 4.0.0.4000 and MySql.Data 6.8.3

Stack Trace

ERROR [(null)] - Message:could not execute query

NHibernate log

NHibernate.Util.ADOExceptionReporter WARN - System.IndexOutOfRangeException: Could not find specified column in results:

Once once of these errors occur it begins to happen frequently until the web application is restart.

It's odd that it only happens to some users and not all.  Also I noticed in this particular log message the values of p4 and p5 should be swapped.

Is this an issue with the query cache?

Does anyone have some insight into why this is happening?

If it helps here is the gnarly query (but I see this error on much simpler queries as well)

```<code>FunderInfoViewModel funderDto = null;
Funder funderAlias = null;
Contact contactAlias = null;

var totalOpportunitiesAwardedCount = QueryOver.Of<Opportunity>()
                .Where(o => o.Funder.Id == funderAlias.Id)
                .And(o => o.Status == OpportunityStatus.Awarded || o.Status == OpportunityStatus.AwardedClosed)
                .SelectList(list => list
                    .SelectCount(o => o.Id));

            var totalOpportunitiesAwardedSum = QueryOver.Of<Opportunity>()
                .Where(o => o.Funder.Id == funderAlias.Id)
                .And(o => o.Status == OpportunityStatus.Awarded || o.Status == OpportunityStatus.AwardedClosed)
                .SelectList(list => list
                    .SelectSum(o => o.AmountAwarded));

            var totalOpportunitiesCount = QueryOver.Of<Opportunity>()
                .Where(o => o.Funder.Id == funderAlias.Id)
                .SelectList(list => list
                    .SelectCount(o => o.Id));

            IEnumerable<FunderInfoViewModel> funders = _session.QueryOver(() => funderAlias)
                .Left.JoinAlias(f => f.Contacts, () => contactAlias, x => x.IsDefault)
                .Where(o => o.Organization.Id == organizationId)
                .SelectList(list => list
                    .Select(x => x.Id)
                    .WithAlias(() => funderDto.Id)
                    .Select(x => x.Name)
                    .WithAlias(() => funderDto.Name)
                    .Select(x => x.Description)
                    .WithAlias(() => funderDto.Description)
                    .Select(x => x.AreasOfInterest)
                    .WithAlias(() => funderDto.AreasOfInterest)
                    .Select(x => x.Type)
                    .WithAlias(() => funderDto.FunderType)
                    .Select(x => x.TaxId)
                    .WithAlias(() => funderDto.TaxId)
                    .Select(x => x.PhoneNumber)
                    .WithAlias(() => funderDto.PhoneNumber)
                    .Select(x => x.FaxNumber)
                    .WithAlias(() => funderDto.FaxNumber)
                    .Select(x => x.EmailAddress)
                    .WithAlias(() => funderDto.EmailAddress)
                    .Select(x => x.Website)
                    .WithAlias(() => funderDto.Website)
                    .Select(x => x.CustomLink)
                    .WithAlias(() => funderDto.CustomLink)
                    .Select(x => x.MinimumFundingRange)
                    .WithAlias(() => funderDto.MinimumFundingRange)
                    .Select(x => x.MaximumFundingRange)
                    .WithAlias(() => funderDto.MaximumFundingRange)
                    .Select(() => contactAlias.FirstName)
                    .WithAlias(() => funderDto.PrimaryContactFirstName)
                    .Select(() => contactAlias.LastName)
                    .WithAlias(() => funderDto.PrimaryContactLastName)
                    .Select(() => contactAlias.Title)
                    .WithAlias(() => funderDto.PrimaryContactTitle)
                    .SelectSubQuery(totalOpportunitiesAwardedCount)
                    .WithAlias(() => funderDto.AwardedOpportunitiesCount)
                    .SelectSubQuery(totalOpportunitiesAwardedSum)
                    .WithAlias(() => funderDto.AwardedOpportunitiesValue)
                    .SelectSubQuery(totalOpportunitiesCount)
                    .WithAlias(() => funderDto.OpportunitiesCount)
                )
                .OrderBy(f => f.Name)
                .Asc
                .TransformUsing(Transformers.AliasToBean<FunderInfoViewModel>())
                .List<FunderInfoViewModel>();
</code>```

答:
Ok got the problem. Its because some of the arguement you are passing in your prepared statement is null, thats why this error. I had similar issue earlier and i solved it by checking only if it is not null add it in query filtering.

Also there is another possibility of row lock by any other query. Are you using lock in mysql query?

2nd problem seems like see the solution stated below

https://forums.asp.net/t/1230295.aspx?IDataReader+Could+not+find+specified+column+in+results+

Body:
From time to time my web application begins throwing the following errors.

Using NHibernate 4.0.0.4000 and MySql.Data 6.8.3

Stack Trace

ERROR [(null)] - Message:could not execute query

NHibernate log

NHibernate.Util.ADOExceptionReporter WARN - System.IndexOutOfRangeException: Could not find specified column in results:

Once once of these errors occur it begins to happen frequently until the web application is restart.

It's odd that it only happens to some users and not all.  Also I noticed in this particular log message the values of p4 and p5 should be swapped.

Is this an issue with the query cache?

Does anyone have some insight into why this is happening?

If it helps here is the gnarly query (but I see this error on much simpler queries as well)

FunderInfoViewModel funderDto = null;
Funder funderAlias = null;
Contact contactAlias = null;

var totalOpportunitiesAwardedCount = QueryOver.Of<Opportunity>()
                .Where(o => o.Funder.Id == funderAlias.Id)
                .And(o => o.Status == OpportunityStatus.Awarded || o.Status == OpportunityStatus.AwardedClosed)
                .SelectList(list => list
                    .SelectCount(o => o.Id));

            var totalOpportunitiesAwardedSum = QueryOver.Of<Opportunity>()
                .Where(o => o.Funder.Id == funderAlias.Id)
                .And(o => o.Status == OpportunityStatus.Awarded || o.Status == OpportunityStatus.AwardedClosed)
                .SelectList(list => list
                    .SelectSum(o => o.AmountAwarded));

            var totalOpportunitiesCount = QueryOver.Of<Opportunity>()
                .Where(o => o.Funder.Id == funderAlias.Id)
                .SelectList(list => list
                    .SelectCount(o => o.Id));

            IEnumerable<FunderInfoViewModel> funders = _session.QueryOver(() => funderAlias)
                .Left.JoinAlias(f => f.Contacts, () => contactAlias, x => x.IsDefault)
                .Where(o => o.Organization.Id == organizationId)
                .SelectList(list => list
                    .Select(x => x.Id)
                    .WithAlias(() => funderDto.Id)
                    .Select(x => x.Name)
                    .WithAlias(() => funderDto.Name)
                    .Select(x => x.Description)
                    .WithAlias(() => funderDto.Description)
                    .Select(x => x.AreasOfInterest)
                    .WithAlias(() => funderDto.AreasOfInterest)
                    .Select(x => x.Type)
                    .WithAlias(() => funderDto.FunderType)
                    .Select(x => x.TaxId)
                    .WithAlias(() => funderDto.TaxId)
                    .Select(x => x.PhoneNumber)
                    .WithAlias(() => funderDto.PhoneNumber)
                    .Select(x => x.FaxNumber)
                    .WithAlias(() => funderDto.FaxNumber)
                    .Select(x => x.EmailAddress)
                    .WithAlias(() => funderDto.EmailAddress)
                    .Select(x => x.Website)
                    .WithAlias(() => funderDto.Website)
                    .Select(x => x.CustomLink)
                    .WithAlias(() => funderDto.CustomLink)
                    .Select(x => x.MinimumFundingRange)
                    .WithAlias(() => funderDto.MinimumFundingRange)
                    .Select(x => x.MaximumFundingRange)
                    .WithAlias(() => funderDto.MaximumFundingRange)
                    .Select(() => contactAlias.FirstName)
                    .WithAlias(() => funderDto.PrimaryContactFirstName)
                    .Select(() => contactAlias.LastName)
                    .WithAlias(() => funderDto.PrimaryContactLastName)
                    .Select(() => contactAlias.Title)
                    .WithAlias(() => funderDto.PrimaryContactTitle)
                    .SelectSubQuery(totalOpportunitiesAwardedCount)
                    .WithAlias(() => funderDto.AwardedOpportunitiesCount)
                    .SelectSubQuery(totalOpportunitiesAwardedSum)
                    .WithAlias(() => funderDto.AwardedOpportunitiesValue)
                    .SelectSubQuery(totalOpportunitiesCount)
                    .WithAlias(() => funderDto.OpportunitiesCount)
                )
                .OrderBy(f => f.Name)
                .Asc
                .TransformUsing(Transformers.AliasToBean<FunderInfoViewModel>())
                .List<FunderInfoViewModel>();


问:
New to Angular, getting Uncaught TypeError: Cannot read property '$$minErr' of undefined when trying to run code
I'm new to angular and I'm attempting to take data in a json object and fill a simple table with it. After googling my error, most people are saying that with this error, the url for my library of angular is in the wrong spot, but I'm fairly sure it isn't. Can anyone help me out?

Here's my code

```<code><!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular-animate.js"></script>
<body>

<div ng-app="myApp" ng-controller="myAppCtrl">
  <table border="1">
    <tr>
      <th>Name</th>.
      <th>Email</th>
      <th>Office</th>
    </tr>
    <tr ng-repeat="x in items">
      <td>{{x.Name}}</td>
      <td>{{x.Email}}</td>
      <td>{{x.Office}}</td></tr>
  </table>
</div>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular-animate.js">
var app = angular.module('myApp', []);

app.controller('myAppCtrl', function($scope, $http) {
$http.get("testData.txt")
  .then(function(response) {
      var needsJSON = response.data;
      var processed = JSON.parse(needsJSON);
      console.log(processed);
      $scope.items = processed;
  });
});

</script>

</body>
</html>
</code>```

Here is the text document with my data if anyone is interested

```<code>{ "Name" : "Test1", "Email" : "test1@test.com", "Office" : "NY" },
{ "Name" : "Test2", "Email" : "test2@test.com", "Office" : "LA" },
{ "Name" : "Test3", "Email" : "test3@test.com", "Office" : "ATL" }
</code>```

答:
You have wrong angular url, Please use the following code</p>

```<code><!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.js"></script>
<body>

<div ng-app="myApp" ng-controller="myAppCtrl">
  <table border="1">
    <tr>
      <th>Name</th>.
      <th>Email</th>
      <th>Office</th>
    </tr>
    <tr ng-repeat="x in items">
      <td>{{x.Name}}</td>
      <td>{{x.Email}}</td>
      <td>{{x.Office}}</td></tr>
  </table>
</div>

<script type="text/javascript">
var app = angular.module('myApp', []);

app.controller('myAppCtrl', function($scope, $http) {
$http.get("testData.txt")
  .then(function(response) {
      var needsJSON = response.data;
      var processed = JSON.parse(needsJSON);
      console.log(processed);
      $scope.items = processed;
  });
});

</script>

</body>
</html>
</code>```

Body:
I'm new to angular and I'm attempting to take data in a json object and fill a simple table with it. After googling my error, most people are saying that with this error, the url for my library of angular is in the wrong spot, but I'm fairly sure it isn't. Can anyone help me out?

Here's my code

<!DOCTYPE html>

      Name	.
      Email
      Office

      {{x.Name}}
      {{x.Email}}
      {{x.Office}}

Here is the text document with my data if anyone is interested

{ "Name" : "Test1", "Email" : "test1@test.com", "Office" : "NY" },
{ "Name" : "Test2", "Email" : "test2@test.com", "Office" : "LA" },
{ "Name" : "Test3", "Email" : "test3@test.com", "Office" : "ATL" }

Body:
You have wrong angular url, Please use the following code

<!DOCTYPE html>
<html>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.js"></script>
<body>

<div ng-app="myApp" ng-controller="myAppCtrl">
  <table border="1">
    <tr>
      <th>Name</th>.
      <th>Email</th>
      <th>Office</th>
    </tr>
    <tr ng-repeat="x in items">
      <td>{{x.Name}}</td>
      <td>{{x.Email}}</td>
      <td>{{x.Office}}</td></tr>
  </table>
</div>

<script type="text/javascript">
var app = angular.module('myApp', []);

app.controller('myAppCtrl', function($scope, $http) {
$http.get("testData.txt")
  .then(function(response) {
      var needsJSON = response.data;
      var processed = JSON.parse(needsJSON);
      console.log(processed);
      $scope.items = processed;
  });
});

</script>

</body>
</html>


问:
Construct index/membership vectors from lists of items
Say you have the following baskets:

```<code>basket1 = ['apple', 'orange', 'banana']
basket2 = ['orange', 'grape']
basket3 = ['banana', 'grape', 'kiwi', 'orange']

baskets = [basket1, basket2, basket3]
</code>```

And your goal is to create the following datastructure:

```<code>pd.DataFrame({'apple': {'basket1': 1,'basket2': 0,'basket3': 0 }, 'orange': {'basket1': 1,'basket2': 1,'basket3': 1 }, 'banana': {'basket1': 1,'basket2': 0,'basket3': 1 }, 'grape': {'basket1': 0,'basket2': 1,'basket3': 1 }, 'kiwi': {'basket1': 0,'basket2': 0,'basket3': 1 } })
</code>```

Which looks like:

I know there's Counter from Collections and bincount from numpy which you could leverage if you just wanted a binary list like the one above, but say you wanted to put some other value at each of these points:

For example, say that instead of a 1, at each point, you wanted to put the weight of the fruit, which you happen to have in another table:

```<code>pd.DataFrame({'weight': {'apple': 3, 'orange':3, 'banana':2, 'grape':1, 'kiwi':2}})
</code>```

And the result you want is:

```<code>pd.DataFrame({'apple': { 'basket1': 3, 'basket2': 0, 'basket3': 0 }, 'orange': { 'basket1': 3, 'basket2': 3, 'basket3': 3 }, 'banana': { 'basket1': 2, 'basket2': 0, 'basket3': 2 }, 'grape': { 'basket1': 0, 'basket2': 1, 'basket3': 1 }, 'kiwi': { 'basket1': 0, 'basket2': 0, 'basket3': 2 } })
</code>```

How would you go about writing such an operation cleanly? I'm not quite sure how to go about performing this operation efficiently or well.

答:
Assuming you start out with a pd.Dataframe and a dict:

```<code>In [37]: df1
Out[37]:
         apple  banana  grape  kiwi  orange
basket1      1       1      0     0       1
basket2      0       0      1     0       1
basket3      0       1      1     1       1

In [38]: mapper = {'apple': 3, 'orange':3, 'banana':2, 'grape':1, 'kiwi':2}
</code>```

Then simply:

```<code>In [39]: for colname in df1:
    ...:     df1[colname] = df1[colname]*mapper[colname]
    ...:

In [40]: df1
Out[40]:
         apple  banana  grape  kiwi  orange
basket1      3       2      0     0       3
basket2      0       0      1     0       3
basket3      0       2      1     2       3
</code>```

Or even more simply, you can intelligently mutiply a pd.DataFrame by a pd.Series (i.e. a "column" of a dataframe):

```<code>In [5]: df2 = pd.DataFrame({'weight': {'apple': 3, 'orange':3, 'banana':2, 'grap
   ...: e':1, 'kiwi':2}})

In [6]: mapper = df2.squeeze() # convert to series

In [7]: df1*mapper
Out[7]:
         apple  banana  grape  kiwi  orange
basket1      3       2      0     0       3
basket2      0       0      1     0       3
basket3      0       2      1     2       3
</code>```

Or starting from scratch:

```<code>In [8]: basket1 = ['apple', 'orange', 'banana']
   ...: basket2 = ['orange', 'grape']
   ...: basket3 = ['banana', 'grape', 'kiwi', 'orange']
   ...:
   ...: baskets = [basket1, basket2, basket3]
   ...:

In [9]: fruitvolume = {'apple': 3, 'orange':3, 'banana':2, 'grape':1, 'kiwi':2}
</code>```

Then simply:

```<code>In [12]: data = [{item:fruitvolume[item] for item in basket} for basket in baskets]

In [13]: data
Out[13]:
[{'apple': 3, 'banana': 2, 'orange': 3},
 {'grape': 1, 'orange': 3},
 {'banana': 2, 'grape': 1, 'kiwi': 2, 'orange': 3}]

In [14]: pd.DataFrame(data)
Out[14]:
   apple  banana  grape  kiwi  orange
0    3.0     2.0    NaN   NaN       3
1    NaN     NaN    1.0   NaN       3
2    NaN     2.0    1.0   2.0       3
</code>```

But now you'll have to do some munging...

```<code>In [16]: df = df.fillna(0).astype(int)

In [17]: df
Out[17]:
   apple  banana  grape  kiwi  orange
0      3       2      0     0       3
1      0       0      1     0       3
2      0       2      1     2       3
</code>```

Body:
Say you have the following baskets:

basket1 = ['apple', 'orange', 'banana']
basket2 = ['orange', 'grape']
basket3 = ['banana', 'grape', 'kiwi', 'orange']

baskets = [basket1, basket2, basket3]

And your goal is to create the following datastructure:

pd.DataFrame({'apple': {'basket1': 1,'basket2': 0,'basket3': 0 }, 'orange': {'basket1': 1,'basket2': 1,'basket3': 1 }, 'banana': {'basket1': 1,'basket2': 0,'basket3': 1 }, 'grape': {'basket1': 0,'basket2': 1,'basket3': 1 }, 'kiwi': {'basket1': 0,'basket2': 0,'basket3': 1 } })

Which looks like:

I know there's Counter from Collections and bincount from numpy which you could leverage if you just wanted a binary list like the one above, but say you wanted to put some other value at each of these points:

For example, say that instead of a 1, at each point, you wanted to put the weight of the fruit, which you happen to have in another table:

pd.DataFrame({'weight': {'apple': 3, 'orange':3, 'banana':2, 'grape':1, 'kiwi':2}})

And the result you want is:

pd.DataFrame({'apple': { 'basket1': 3, 'basket2': 0, 'basket3': 0 }, 'orange': { 'basket1': 3, 'basket2': 3, 'basket3': 3 }, 'banana': { 'basket1': 2, 'basket2': 0, 'basket3': 2 }, 'grape': { 'basket1': 0, 'basket2': 1, 'basket3': 1 }, 'kiwi': { 'basket1': 0, 'basket2': 0, 'basket3': 2 } })

How would you go about writing such an operation cleanly? I'm not quite sure how to go about performing this operation efficiently or well.

Body:
Assuming you start out with a pd.Dataframe and a dict:

In [37]: df1
Out[37]:
         apple  banana  grape  kiwi  orange
basket1      1       1      0     0       1
basket2      0       0      1     0       1
basket3      0       1      1     1       1

In [38]: mapper = {'apple': 3, 'orange':3, 'banana':2, 'grape':1, 'kiwi':2}

Then simply:

In [39]: for colname in df1:
    ...:     df1[colname] = df1[colname]*mapper[colname]
    ...:

In [40]: df1
Out[40]:
         apple  banana  grape  kiwi  orange
basket1      3       2      0     0       3
basket2      0       0      1     0       3
basket3      0       2      1     2       3

Or even more simply, you can intelligently mutiply a pd.DataFrame by a pd.Series (i.e. a "column" of a dataframe):

In [5]: df2 = pd.DataFrame({'weight': {'apple': 3, 'orange':3, 'banana':2, 'grap
   ...: e':1, 'kiwi':2}})

In [6]: mapper = df2.squeeze() # convert to series

In [7]: df1*mapper
Out[7]:
         apple  banana  grape  kiwi  orange
basket1      3       2      0     0       3
basket2      0       0      1     0       3
basket3      0       2      1     2       3

Or starting from scratch:

In [8]: basket1 = ['apple', 'orange', 'banana']
   ...: basket2 = ['orange', 'grape']
   ...: basket3 = ['banana', 'grape', 'kiwi', 'orange']
   ...:
   ...: baskets = [basket1, basket2, basket3]
   ...:

In [9]: fruitvolume = {'apple': 3, 'orange':3, 'banana':2, 'grape':1, 'kiwi':2}

Then simply:

In [12]: data = [{item:fruitvolume[item] for item in basket} for basket in baskets]

In [13]: data
Out[13]:
[{'apple': 3, 'banana': 2, 'orange': 3},
 {'grape': 1, 'orange': 3},
 {'banana': 2, 'grape': 1, 'kiwi': 2, 'orange': 3}]

In [14]: pd.DataFrame(data)
Out[14]:
   apple  banana  grape  kiwi  orange
0    3.0     2.0    NaN   NaN       3
1    NaN     NaN    1.0   NaN       3
2    NaN     2.0    1.0   2.0       3

But now you'll have to do some munging...

In [16]: df = df.fillna(0).astype(int)

In [17]: df
Out[17]:
   apple  banana  grape  kiwi  orange
0      3       2      0     0       3
1      0       0      1     0       3
2      0       2      1     2       3


问:
Iterating through object array in $scope and updating it
I have an array of objects in the scope ($scope.contracts). When I run my function, I pass in a contract. I Want it to iterate through $scope.contracts and find the one with the same .CONT_ORDNO. Then I want to set this contract to the contract passed in.

```<code>    $scope.mergeContract = function (contractThatsReplaced) {//clicked 2nd new
        angular.forEach($scope.contracts, function (con) {
            if (con.CONT_ORDNO == contractThatsReplaced.CONT_ORDNO) {
                con = $scope.contractToMerge;
            }
        });
    };
</code>```

Here is me trying to do it, it does everything I want except that only the con variable is changed, the actual contract that's an array location in $scope.contracts is not being updated. How do I make sure it is?

Note I don't want to remove and replace the contract, I want to update it.

Edit: I updated the if statement to have two (==). This doesn't fix it. It still is only setting the con variable correctly, not the $scope.contracts array location.

答:
Assigning to con only changes the local variable. Try this instead:

```<code>$scope.mergeContract = function (contractThatsReplaced) {//clicked 2nd new
    angular.forEach($scope.contracts, function (con, i) {
        if (con.CONT_ORDNO == contractThatsReplaced.CONT_ORDNO) {
            $scope.contracts[i] = $scope.contractToMerge;
        }
    });
};
</code>```

Also, you need to change = to == in the if statement.

Body:
I have an array of objects in the scope ($scope.contracts). When I run my function, I pass in a contract. I Want it to iterate through $scope.contracts and find the one with the same .CONT_ORDNO. Then I want to set this contract to the contract passed in.

    $scope.mergeContract = function (contractThatsReplaced) {//clicked 2nd new
        angular.forEach($scope.contracts, function (con) {
            if (con.CONT_ORDNO == contractThatsReplaced.CONT_ORDNO) {
                con = $scope.contractToMerge;
            }
        });
    };

Here is me trying to do it, it does everything I want except that only the con variable is changed, the actual contract that's an array location in $scope.contracts is not being updated. How do I make sure it is?

Note I don't want to remove and replace the contract, I want to update it.

Edit: I updated the if statement to have two (==). This doesn't fix it. It still is only setting the con variable correctly, not the $scope.contracts array location.

Body:
Assigning to con only changes the local variable. Try this instead:

$scope.mergeContract = function (contractThatsReplaced) {//clicked 2nd new
    angular.forEach($scope.contracts, function (con, i) {
        if (con.CONT_ORDNO == contractThatsReplaced.CONT_ORDNO) {
            $scope.contracts[i] = $scope.contractToMerge;
        }
    });
};

Also, you need to change = to == in the if statement.