问:
How do I groupBy on a HTTP response?
I'm getting an array of objects as a HTTP response and I'm trying to group them by a value in the object. As an example let's say I get the following:

```<code>[
{player: 'Jordy Nelson', team: 'Packers'},
{player: 'Aaron Rogers', team: 'Packers'},
{player: 'Dak Prescott', team: 'Cowboys'},
{player: 'Ezekiel Elliot', team: 'Cowboys'},
{player: 'Joe Flacco', team: 'Ravens'},
{player: 'Julio Jones', team: 'Falcons'},
]
</code>```

I'm trying to take that response and convert it to an array of objects, containing an array of objects

```<code>[
{'Packers':
  [
    {player: 'Jordy Nelson', team: 'Packers'},
    {player: 'Aaron Rogers', team: 'Packers'}
  ]
},
{'Cowboys':
  [
    {player: 'Dak Prescott', team: 'Cowboys'},
    {player: 'Ezekiel Elliot', team: 'Cowboys'}
  ]
},
{'Ravens':
  [
    {player: 'Joe Flacco', team: 'Ravens'}
  ]
},
{'Falcons':
  [
    {player: 'Julio Jones', team: 'Falcons'}
  ]
}
]
</code>```

I've tried using groupBy in the way mentioned in other SO posts

```<code>return this.http
  .get(`${environment.baseUrl}/players`, options)
  .map(res => res.json())
  .groupBy(
    res => res.team,
    res => res // I've also tried removing this, filtering and flatmap
  )
  .flatMap(teams => {return teams})
</code>```

But it returns a 2d array where axis 1 is a single object like so:

```<code>[
  [
    {'Packers': {player: 'Jordy Nelson', team: 'Packers'}
  ],
  [
    {'Packers': {player: 'Aaron Rogers', team: 'Packers'}
  ]
]
</code>```

What do I need I to do format my response properly? Thanks!

With a lot of help from @coderek answer I wrote a little function that can dynamically regroup HTTP responses (so you don't hit the API for each time you'd like to groupBy on a different key). Here's the post on reddit if anyone else comes across this problem https://www.reddit.com/r/Angular2/comments/629nfg/how_to_dynamically_group_a_http_response/

答:
GroupBy works on streams. So
First, you need to convert your source to stream first instead of array.
Second, you get group results by stream, that's how observable works.

```<code>this.http.get('api/players')
  .mergeMap(a=> a.json().data)
  .groupBy(
      a=>a.team,
      a=>a,
  )
  .subscribe(
    (obs) =>{
        obs.subscribe((a)=>{
            console.log(a, obs.key);
        });
    }
  )
}
</code>```

Title: How do I groupBy on a HTTP response?

Body:
I'm getting an array of objects as a HTTP response and I'm trying to group them by a value in the object. As an example let's say I get the following:

[
{player: 'Jordy Nelson', team: 'Packers'},
{player: 'Aaron Rogers', team: 'Packers'},
{player: 'Dak Prescott', team: 'Cowboys'},
{player: 'Ezekiel Elliot', team: 'Cowboys'},
{player: 'Joe Flacco', team: 'Ravens'},
{player: 'Julio Jones', team: 'Falcons'},
]

I'm trying to take that response and convert it to an array of objects, containing an array of objects

[
{'Packers':
  [
    {player: 'Jordy Nelson', team: 'Packers'},
    {player: 'Aaron Rogers', team: 'Packers'}
  ]
},
{'Cowboys':
  [
    {player: 'Dak Prescott', team: 'Cowboys'},
    {player: 'Ezekiel Elliot', team: 'Cowboys'}
  ]
},
{'Ravens':
  [
    {player: 'Joe Flacco', team: 'Ravens'}
  ]
},
{'Falcons':
  [
    {player: 'Julio Jones', team: 'Falcons'}
  ]
}
]

I've tried using groupBy in the way mentioned in other SO posts

return this.http
  .get(`${environment.baseUrl}/players`, options)
  .map(res => res.json())
  .groupBy(
    res => res.team,
    res => res // I've also tried removing this, filtering and flatmap
  )
  .flatMap(teams => {return teams})

But it returns a 2d array where axis 1 is a single object like so:

[
  [
    {'Packers': {player: 'Jordy Nelson', team: 'Packers'}
  ],
  [
    {'Packers': {player: 'Aaron Rogers', team: 'Packers'}
  ]
]

What do I need I to do format my response properly? Thanks!

With a lot of help from @coderek answer I wrote a little function that can dynamically regroup HTTP responses (so you don't hit the API for each time you'd like to groupBy on a different key). Here's the post on reddit if anyone else comes across this problem https://www.reddit.com/r/Angular2/comments/629nfg/how_to_dynamically_group_a_http_response/

Body:
GroupBy works on streams. So
First, you need to convert your source to stream first instead of array.
Second, you get group results by stream, that's how observable works.

this.http.get('api/players')
  .mergeMap(a=> a.json().data)
  .groupBy(
      a=>a.team,
      a=>a,
  )
  .subscribe(
    (obs) =>{
        obs.subscribe((a)=>{
            console.log(a, obs.key);
        });
    }
  )
}


来源: stackexchange

问:
Function declaration in R and its evaluation?
Sorry for not being more specific in my question title but I was not sure how to phrase it.

I am just trying to understand how function declarations work in R.

```<code>library(magrittr)
library(compiler)

fn1 <- function(x) {x + 1} %>% cmpfun()
fn2 <- (function(x) {x + 1}) %>% cmpfun()

fn1(1) # gives an error
fn2(1) # works as expected
</code>```

Why do I need parentheses around the function declaration so that fn2 works and fn1 does not?

If function is just like any other function, then why are not function calls (as in function declarations) obeying the normal syntax... From the help page on function, its syntax is:

```<code>function( arglist ) expr
return(value)
</code>```

答:
Because

```<code>fn1 <- function(x) {x + 1} %>% cmpfun()
</code>```

is the same as

```<code>fn1 <- function(x) {
    {x + 1} %>% cmpfun()
}
</code>```

So like the documentation says: function( arglist ) expr -- basically everything after the function(x) is being treated as a single expression. When there are parenthesis, it knows when to "stop" the expression.

Which is different from

```<code>fn2 <- (function(x) {x + 1}) %>% cmpfun()
</code>```

which is more like

```<code>fn2 <- `%>%`( function(x) {x + 1}, cmpfun())
</code>```

So the first is just defining a function while the second is actually calling the pipe operator.

ContentLicense: CC BY-SA 3.0

Body:
Sorry for not being more specific in my question title but I was not sure how to phrase it.

I am just trying to understand how function declarations work in R.

library(magrittr)
library(compiler)

fn1 <- function(x) {x + 1} %>% cmpfun()
fn2 <- (function(x) {x + 1}) %>% cmpfun()

fn1(1) # gives an error
fn2(1) # works as expected

Why do I need parentheses around the function declaration so that fn2 works and fn1 does not?

If function is just like any other function, then why are not function calls (as in function declarations) obeying the normal syntax... From the help page on function, its syntax is:

function( arglist ) expr
return(value)

Body:
Because

fn1 <- function(x) {x + 1} %>% cmpfun()

is the same as

fn1 <- function(x) {
    {x + 1} %>% cmpfun()
}

So like the documentation says: function( arglist ) expr -- basically everything after the function(x) is being treated as a single expression. When there are parenthesis, it knows when to "stop" the expression.

Which is different from

fn2 <- (function(x) {x + 1}) %>% cmpfun()

which is more like

fn2 <- `%>%`( function(x) {x + 1}, cmpfun())

So the first is just defining a function while the second is actually calling the pipe operator.


问:
Angular 2 and Spring Kerberos
Is it possible to use Kerberos in an Angular 2 application? We are using Spring which hosts our REST service and also protects the Angular 2 resources with Kerberos. We want to add roles and define what funtionality in the Angular2 application is available for certain roles. There seems to be little information around on how to do this since most of the people seem to have gone to use JWT or OAuth.

Would it be possible to use Kerberos for the initial authentication and then generate a JWT which is sent back to the browser?

At the moment I am thinking about setting up a REST endpoint /user which returns all the information about the currently logged-in user including his/her permissions. In Angular I can then read those permissions and manipulate the UI and the routes accordingly. The data coming from the server would already be protected by Kerberos and Spring. So if the user can still alter their local Angular to visit some of the protected routes, they would not see any data.

答:
You choice of auth technology on backend side shouldn't influence your decisions on frontend side much, be it OAuth, JWT, Kerberos, or something custom made.

You will need to authenticate user in your backend using Kerberos, keep ticket (auth token) somewhere on frontend side (e.g. in cookie or local storage), and when use that ticket to authenticate future requests. This will require some custom made code and basic knowledge of Kerberos protocol (http://www.roguelynn.com/words/explain-like-im-5-kerberos/, Kerberos authentication in Node.js https.get or https.request), since I don't see any existing implementation for Kerberos protocol in Angular2 (shouldn't be too hard, though).

You can use JWT over Kerberos, but this will require additional layer between endpoint and frontend. IMHO, it will be easier to stick with only one technology that you are already using (Kerberos).

Then, you can implement custom guards in Angular2 to protect routes from unauthorized access (see https://blog.thoughtram.io/angular/2016/07/18/guards-in-angular-2.html).

Title: Angular 2 and Spring Kerberos


问:
TYPO3: Generate in realURL multiple URLs with the same postVarSets in different levels
In my TYPO3 there are multiple storages with different sport activities.
The one belongs to place A, the other to place B with different content.
Now I would like to generate the followingURLs.

The first one is for general, the other one are specific.

```<code>/sport/golf
/place-a/sport/golf
/place-b/sport/golf
</code>```

sport is decoded to /sport-detail/controller/action/sport/

I used the default lookUpTable, but the URLs cant be resolved.

```<code>'lookUpTable' => array(
    'table' => 'tx_myext_domain_model_sport',
    'id_field' => 'uid',
    'alias_field' => "url",
    'addWhereClause' => ' AND deleted = 0 AND hidden = 0',
    'useUniqueCache' => 1,
    'languageGetVar' => 'L',
    'languageField' => 'sys_language_uid',
    'transOrigPointerField' => 'l10n_parent',
    'useUniqueCache_conf' => array(
        'strtolower' => 1,
        'spaceCharacter' => '-',
    ),
)
</code>```

What is needed to create valid URLs, without golf-1 etc.. for all levels?

答:
Finally I wrote a UserFunction that fulfills my needs. In this function I extend the given lookuptable function from realURL and fetch me the values yourself.
The model has been renamed in the meantime to activity.
I do now save the detail pid for the show action and the storage pid in the sport model so I can search the whole URL path to find place name and lookup the storage pid. With the storage pid of the place I can find the right activity. And with a correct lookup in the database I can return a valid ID.
For SEO reasons I added a new field URL to the model that contains the string in the URL path. In the id2alias method I return the url value of the activity with the given ID.

I noticed one behavior that realURL doesn't find the correct entry in the caching table once all the parameters are hashed, so I had to exclude the activity GETvar from cHash generation.

```<code>$GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParameters'] = tx_myext_activity[activity]
</code>```

After all this is my working setup :-)

RealURL config:

```<code>'GETvar' => 'tx_myext_activity[activity]',
'type' => 'user',
'languageGetVar' => 'L',
'languageField' => 'sys_language_uid',
'useUniqueCache' => 0,
'userFunc' => 'EXT:MyUserFunc.php:&MyUserFunc->main'
</code>```

The UserFunction handles now the URL generation.

```<code><?php

class MyUserFunc
{
    protected $sys_language_uid;
    protected $params;
    protected $localizedStrings;

    public function main($params, $ref)
    {
        if ($params) {
            $this->params = $params;
            $dirParts = $this->params['pObj']->dirParts;

            //language
            $this->sys_language_uid = 0;

            //is realUrl in encode or decode
            if ($this->params['decodeAlias']) {
                return $this->alias2id($this->params['value']);
            } else {
                return $this->id2alias($this->params['value']);
            }
        }
    }

    /*
     * Generate URL param
     */
    protected function id2alias($value)
    {
        $sysLanguageToBuild = $this->params['pathParts'][0];

        //if not default, use l10n_parent with sysuid
        if ($sysLanguageToBuild > 0) {
            $additionalWhere = ' AND l10n_parent = ' . (int)$value;
            $additionalWhere .= ' AND sys_language_uid = ' . (int)$sysLanguageToBuild;
        } else {
            $additionalWhere = ' AND uid = ' . (int)$value;
        }

        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
            'url',
            'tx_myext_domain_model_activity',
            'deleted = 0 AND hidden = 0' . $additionalWhere
        );

        $activityRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);

        if (is_array($activityRow)) {
            return $activityRow['url'];
        }

        return 'undefined';
    }

    /**
     * Decode string to uid
     * respect activities with different pid
     *
     * @param $value
     * @return int
     */
    protected function alias2id($value)
    {
        $dirParts = $this->params['pObj']->dirParts; //get array of complete path
        $place = htmlspecialchars($this->params['pObj']->dirParts[2]); //get place

        //transform place string
        $place = strtolower($place);
        $place = preg_replace("/[^A-Za-z0-9\s-._\/]/", "", $place);
        $place = trim(preg_replace("/[\s-]+/", " ", $place));

        //Query Place
        $placeRes = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
            'uid, activity_storage_page',
            'tx_myext_domain_model_place',
            'deleted = 0 AND hidden = 0 AND sys_language_uid = '. $this->sys_language_uid .
            ' AND LOWER(name) = "' . $place . '"'
        );

        $placeRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($placeRes);

        //Query Activity
        if (is_array($placeRow)) {
            $additionalWhere .= " AND tx_myext_domain_model_activity.pid = '" . (int)$placeRow['activity_storage_page'] . "'";
        }

        $additionalWhere = "  AND tx_myext_domain_model_activity.sys_language_uid = " . $this->sys_language_uid;
        $additionalWhere .= " AND tx_myext_domain_model_activity.url = '" . $value . "'";
        $additionalWhere .= " AND tx_myext_domain_model_activity.pid = '" . $pid . "'";

        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
            'tx_myext_domain_model_activity.uid',
            'tx_myext_domain_model_activity',
            'deleted = 0 AND hidden = 0' . $additionalWhere
        );

        while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
            return (int)$row['uid'];
        }

        //catch old URLs and return uid
        $additionalWhere = "  AND tx_myext_domain_model_activity.sys_language_uid = " . $this->sys_language_uid;
        $additionalWhere .= " AND tx_myext_domain_model_activity.name = '" . $value . "'";

        $resElse = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
            'tx_myext_domain_model_activity.uid',
            'tx_myext_domain_model_activity',
            'deleted = 0 AND hidden = 0' . $additionalWhere
        );
        while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($resElse)) {
            return (int)$row['uid'];
        }

        return false;
    }
}
</code>```

Body:
In my TYPO3 there are multiple storages with different sport activities.
The one belongs to place A, the other to place B with different content.
Now I would like to generate the followingURLs.

The first one is for general, the other one are specific.

/sport/golf
/place-a/sport/golf
/place-b/sport/golf

sport is decoded to /sport-detail/controller/action/sport/

I used the default lookUpTable, but the URLs cant be resolved.

'lookUpTable' => array(
    'table' => 'tx_myext_domain_model_sport',
    'id_field' => 'uid',
    'alias_field' => "url",
    'addWhereClause' => ' AND deleted = 0 AND hidden = 0',
    'useUniqueCache' => 1,
    'languageGetVar' => 'L',
    'languageField' => 'sys_language_uid',
    'transOrigPointerField' => 'l10n_parent',
    'useUniqueCache_conf' => array(
        'strtolower' => 1,
        'spaceCharacter' => '-',
    ),
)

What is needed to create valid URLs, without golf-1 etc.. for all levels?

Body:
Finally I wrote a UserFunction that fulfills my needs. In this function I extend the given lookuptable function from realURL and fetch me the values yourself.
The model has been renamed in the meantime to activity.
I do now save the detail pid for the show action and the storage pid in the sport model so I can search the whole URL path to find place name and lookup the storage pid. With the storage pid of the place I can find the right activity. And with a correct lookup in the database I can return a valid ID.
For SEO reasons I added a new field URL to the model that contains the string in the URL path. In the id2alias method I return the url value of the activity with the given ID.

I noticed one behavior that realURL doesn't find the correct entry in the caching table once all the parameters are hashed, so I had to exclude the activity GETvar from cHash generation.

$GLOBALS['TYPO3_CONF_VARS']['FE']['cHashExcludedParameters'] = tx_myext_activity[activity]

After all this is my working setup :-)

RealURL config:

'GETvar' => 'tx_myext_activity[activity]',
'type' => 'user',
'languageGetVar' => 'L',
'languageField' => 'sys_language_uid',
'useUniqueCache' => 0,
'userFunc' => 'EXT:MyUserFunc.php:&MyUserFunc->main'

The UserFunction handles now the URL generation.

<?php

class MyUserFunc
{
    protected $sys_language_uid;
    protected $params;
    protected $localizedStrings;

    public function main($params, $ref)
    {
        if ($params) {
            $this->params = $params;
            $dirParts = $this->params['pObj']->dirParts;

            //language
            $this->sys_language_uid = 0;

            //is realUrl in encode or decode
            if ($this->params['decodeAlias']) {
                return $this->alias2id($this->params['value']);
            } else {
                return $this->id2alias($this->params['value']);
            }
        }
    }

    /*
     * Generate URL param
     */
    protected function id2alias($value)
    {
        $sysLanguageToBuild = $this->params['pathParts'][0];

        //if not default, use l10n_parent with sysuid
        if ($sysLanguageToBuild > 0) {
            $additionalWhere = ' AND l10n_parent = ' . (int)$value;
            $additionalWhere .= ' AND sys_language_uid = ' . (int)$sysLanguageToBuild;
        } else {
            $additionalWhere = ' AND uid = ' . (int)$value;
        }

        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
            'url',
            'tx_myext_domain_model_activity',
            'deleted = 0 AND hidden = 0' . $additionalWhere
        );

        $activityRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);

        if (is_array($activityRow)) {
            return $activityRow['url'];
        }

        return 'undefined';
    }

    /**
     * Decode string to uid
     * respect activities with different pid
     *
     * @param $value
     * @return int
     */
    protected function alias2id($value)
    {
        $dirParts = $this->params['pObj']->dirParts; //get array of complete path
        $place = htmlspecialchars($this->params['pObj']->dirParts[2]); //get place

        //transform place string
        $place = strtolower($place);
        $place = preg_replace("/[^A-Za-z0-9\s-._\/]/", "", $place);
        $place = trim(preg_replace("/[\s-]+/", " ", $place));

        //Query Place
        $placeRes = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
            'uid, activity_storage_page',
            'tx_myext_domain_model_place',
            'deleted = 0 AND hidden = 0 AND sys_language_uid = '. $this->sys_language_uid .
            ' AND LOWER(name) = "' . $place . '"'
        );

        $placeRow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($placeRes);

        //Query Activity
        if (is_array($placeRow)) {
            $additionalWhere .= " AND tx_myext_domain_model_activity.pid = '" . (int)$placeRow['activity_storage_page'] . "'";
        }

        $additionalWhere = "  AND tx_myext_domain_model_activity.sys_language_uid = " . $this->sys_language_uid;
        $additionalWhere .= " AND tx_myext_domain_model_activity.url = '" . $value . "'";
        $additionalWhere .= " AND tx_myext_domain_model_activity.pid = '" . $pid . "'";

        $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
            'tx_myext_domain_model_activity.uid',
            'tx_myext_domain_model_activity',
            'deleted = 0 AND hidden = 0' . $additionalWhere
        );

        while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
            return (int)$row['uid'];
        }

        //catch old URLs and return uid
        $additionalWhere = "  AND tx_myext_domain_model_activity.sys_language_uid = " . $this->sys_language_uid;
        $additionalWhere .= " AND tx_myext_domain_model_activity.name = '" . $value . "'";

        $resElse = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
            'tx_myext_domain_model_activity.uid',
            'tx_myext_domain_model_activity',
            'deleted = 0 AND hidden = 0' . $additionalWhere
        );
        while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($resElse)) {
            return (int)$row['uid'];
        }

        return false;
    }
}


问:
Postgres - Lateral join with random values on both sides
I am trying to generate the following table:

```<code>random person a | random utility 1
random person a | random utility 2
random person a | random utility 3
random person b | random utility 4
random person b | random utility 5
random person b | random utility 6
</code>```

So, I want to generate two random persons and for each person, 3 random utilities. Generated utilities are not shared between persons.

I came up with the following query:

```<code>select              gen_random_uuid() person, utility.utility
from                generate_series(1, 2) person
inner join lateral  (select person, gen_random_uuid() utility from generate_series(1, 3)) utility
on                  person.person = utility.person;
</code>```

But this generates the following:

```<code>64bf364b-ff74-4888-b2d9-0ffcf3147dd7 | f8455aa3-73ab-4432-9c49-2c940da28fa7
05f54217-0316-410d-83e8-2b5306eee143 | 68f7b48-2561-438c-a906-34b141c4adc5
07c23fc3-a6b9-4d74-a611-264c4de9a0bd | 5a597190-09f9-44ea-960d-f6657aa10a81
b5903b45-f96a-4eb4-8b67-95340131a29b | 742daba-de73-45c4-8b2b-758663c4af47
6ba75082-77e4-408b-9e19-92595121cf43 | 01635986-98e3-432e-9f4e-0a88edba3d67
48d7ab6f-4a32-4306-b060-f0019aef1d11 | 99f4e91f-c05f-496c-a4a3-7b62f64ed6e1
</code>```

So, as you can see, the result contains 6 random persons, with each person his/her own random utility.

As said, I need 2 random persons with each 3 random utlities. How can I fix this query?

答:
Your problem is that you are assigning the person uuid in the outermost select.  So, you get one for each row.

My first thought is a bit more complicated:

```<code>with p as (
      select gen_random_uuid() as person, g.i
      from generate_series(1, 2) g(i)
     ),
     u as (
      select gen_random_uuid() as utility, g.i
      from generate_series(1, 6) g(i)
    )
select p.person, u.utility
from p join
     u
     on mod(p.i, 2) = mod(u.i, 2);
</code>```

Admittedly, a lateral join is simpler, but a similar idea can be used:

```<code>with p as (
      select gen_random_uuid() as person, g.i
      from generate_series(1, 2) g(i)
     )
select p.person, u.utility
from p, lateral
     (select gen_random_uuid() as utility
      from generate_series(1, 3)
     ) u;
</code>```

Or, without a lateral join at all:

```<code>with p as (
      select gen_random_uuid() as person, g.i
      from generate_series(1, 2) g(i)
     )
select p.person, gen_random_uuid() as utility
from p cross join
     generate_series(1, 3);
</code>```

Body:
I am trying to generate the following table:

random person a | random utility 1
random person a | random utility 2
random person a | random utility 3
random person b | random utility 4
random person b | random utility 5
random person b | random utility 6

So, I want to generate two random persons and for each person, 3 random utilities. Generated utilities are not shared between persons.

I came up with the following query:

select              gen_random_uuid() person, utility.utility
from                generate_series(1, 2) person
inner join lateral  (select person, gen_random_uuid() utility from generate_series(1, 3)) utility
on                  person.person = utility.person;

But this generates the following:

64bf364b-ff74-4888-b2d9-0ffcf3147dd7 | f8455aa3-73ab-4432-9c49-2c940da28fa7
05f54217-0316-410d-83e8-2b5306eee143 | 68f7b48-2561-438c-a906-34b141c4adc5
07c23fc3-a6b9-4d74-a611-264c4de9a0bd | 5a597190-09f9-44ea-960d-f6657aa10a81
b5903b45-f96a-4eb4-8b67-95340131a29b | 742daba-de73-45c4-8b2b-758663c4af47
6ba75082-77e4-408b-9e19-92595121cf43 | 01635986-98e3-432e-9f4e-0a88edba3d67
48d7ab6f-4a32-4306-b060-f0019aef1d11 | 99f4e91f-c05f-496c-a4a3-7b62f64ed6e1

So, as you can see, the result contains 6 random persons, with each person his/her own random utility.

As said, I need 2 random persons with each 3 random utlities. How can I fix this query?

Body:
Your problem is that you are assigning the person uuid in the outermost select.  So, you get one for each row.

My first thought is a bit more complicated:

with p as (
      select gen_random_uuid() as person, g.i
      from generate_series(1, 2) g(i)
     ),
     u as (
      select gen_random_uuid() as utility, g.i
      from generate_series(1, 6) g(i)
    )
select p.person, u.utility
from p join
     u
     on mod(p.i, 2) = mod(u.i, 2);

Admittedly, a lateral join is simpler, but a similar idea can be used:

with p as (
      select gen_random_uuid() as person, g.i
      from generate_series(1, 2) g(i)
     )
select p.person, u.utility
from p, lateral
     (select gen_random_uuid() as utility
      from generate_series(1, 3)
     ) u;

Or, without a lateral join at all:

with p as (
      select gen_random_uuid() as person, g.i
      from generate_series(1, 2) g(i)
     )
select p.person, gen_random_uuid() as utility
from p cross join
     generate_series(1, 3);


问:
Delphi: How to get the address of a static record
```<code>    type
      TMyRecord = record
      private
        class constructor create;
      public
        class var MyField1: string;
        class var MyField2: integer;
        class var MyField3: extended;
        class function ToString: string; static;
      end;

    class constructor TMyRecord.Create;
    begin
        TMyRecord.MyField1 := 'Hello, world!';
        TMyRecord.MyField2 := 123;
        TMyRecord.MyField3 := 3.1415927;
    end;

    class function TMyRecord.ToString: string;
    var
      RecType: TRTTIType;
      RecFields: TArray<TRttiField>;
      I: integer;
    begin
      RecType := TRTTIContext.Create.GetType(TypeInfo(TMyRecord));
      Result := RecType.ToString;
      RecFields := RecType.GetFields;
      for I := 0 to High(RecFields) do
        Result := Result + Format('%s: %s = %s', [RecFields[I].Name, RecFields[I].FieldType.ToString, RecFields[I].GetValue(@TMyRecord).ToString]) + sLineBreak;
    end;
</code>```

I am trying to get TMyRecord.ToString to return:

```<code>    TMyRecord
    MyField1: string = Hello, world!
    MyField2: integer = 123;
    MyField3: extended = 3.1415927;
</code>```

However, I get a compiler error on GetValue(@TMyRecord) - E2029 '(' expected but ')' found

Normally GetValue should be called with the address of the 'instance' of the record. But in this case the record is static.
I do not want to convert this record to a normal record, create an instance etc. I'm trying to solve this for a static record.
How can I get the address that should be passed to GetValue?

答:
Thank you LU RD for your contribution! Quite clever, using a nested record and declaring a local class var 'r', allowing access to both the type as well as an instance.

In the mean time I had come up with another solution, although that uses a class (with an external instance) instead of a record, which I didn't want to do, but I didn't see another way, so thanks for your solution!

```<code>type
  TMyRecord = class
  private
    constructor create;
  public
    MyField1: string;
    MyField2: integer;
    MyField3: extended;
    function ToString: string;
  end;
var
  MyRecord: TMyRecord;

constructor TMyRecord.Create;
begin
  MyField1 := 'Hello, world!';
  MyField2 := 123;
  MyField3 := 3.1415927;
end;

function TMyRecord.ToString: string;
var
  Field: TRttiField;
begin
  Result := sLineBreak;
  for Field in TRTTIContext.Create.GetType(Self.ClassType).GetFields do
    Result := Result + Format('%s: %s = %s', [Field.Name, Field.FieldType.ToString, Field.GetValue(Self).ToString]) + sLineBreak;
end;
</code>```

Body:
    type
      TMyRecord = record
      private
        class constructor create;
      public
        class var MyField1: string;
        class var MyField2: integer;
        class var MyField3: extended;
        class function ToString: string; static;
      end;

    class constructor TMyRecord.Create;
    begin
        TMyRecord.MyField1 := 'Hello, world!';
        TMyRecord.MyField2 := 123;
        TMyRecord.MyField3 := 3.1415927;
    end;

    class function TMyRecord.ToString: string;
    var
      RecType: TRTTIType;
      RecFields: TArray<TRttiField>;
      I: integer;
    begin
      RecType := TRTTIContext.Create.GetType(TypeInfo(TMyRecord));
      Result := RecType.ToString;
      RecFields := RecType.GetFields;
      for I := 0 to High(RecFields) do
        Result := Result + Format('%s: %s = %s', [RecFields[I].Name, RecFields[I].FieldType.ToString, RecFields[I].GetValue(@TMyRecord).ToString]) + sLineBreak;
    end;

I am trying to get TMyRecord.ToString to return:

    TMyRecord
    MyField1: string = Hello, world!
    MyField2: integer = 123;
    MyField3: extended = 3.1415927;

However, I get a compiler error on GetValue(@TMyRecord) - E2029 '(' expected but ')' found

Normally GetValue should be called with the address of the 'instance' of the record. But in this case the record is static.
I do not want to convert this record to a normal record, create an instance etc. I'm trying to solve this for a static record.
How can I get the address that should be passed to GetValue?

Body:
Thank you LU RD for your contribution! Quite clever, using a nested record and declaring a local class var 'r', allowing access to both the type as well as an instance.

In the mean time I had come up with another solution, although that uses a class (with an external instance) instead of a record, which I didn't want to do, but I didn't see another way, so thanks for your solution!

type
  TMyRecord = class
  private
    constructor create;
  public
    MyField1: string;
    MyField2: integer;
    MyField3: extended;
    function ToString: string;
  end;
var
  MyRecord: TMyRecord;

constructor TMyRecord.Create;
begin
  MyField1 := 'Hello, world!';
  MyField2 := 123;
  MyField3 := 3.1415927;
end;

function TMyRecord.ToString: string;
var
  Field: TRttiField;
begin
  Result := sLineBreak;
  for Field in TRTTIContext.Create.GetType(Self.ClassType).GetFields do
    Result := Result + Format('%s: %s = %s', [Field.Name, Field.FieldType.ToString, Field.GetValue(Self).ToString]) + sLineBreak;
end;


问:
Obtained source code of python function is wrong
I would like to obtain the source code of a Python function. However, the functions I am dealing with have decorators that are instantiated with functions themselves. It seems like inspect or dill have problems with that. In particular, I tried the following MWE:

```<code>class Decorator(object):
    def __init__(self, item):
        self.item = item
        self.func = None
    def __call__(self, func):
        self.func = func
        return self

@Decorator(42)
def fun_1():
    pass

@Decorator(lambda x: 42)
def fun_2():
    pass

@Decorator(fun_2.item)
def fun_3():
    pass

import inspect
print("Inspect results")
print(inspect.getsource(fun_1.func))
print(inspect.getsource(fun_2.func))
print(inspect.getsource(fun_3.func))

import dill
print("Dill results")
print(dill.source.getsource(fun_1.func))
print(dill.source.getsource(fun_2.func))
print(dill.source.getsource(fun_3.func))
</code>```

For functions fun_1 and fun_3, this gives the expected results. For fun_2 (although it is essentially the same as fun_3), the source code as returned by inspect or dill is just wrong - it only gives me the decorator line. I would expect to get

```<code>@Decorator(lambda x: 42)
def fun_2():
    pass
</code>```

but all I get is

```<code>@Decorator(lambda x: 42)
</code>```

I can imagine that both modules just search for the first function declaration. Is this assumption correct and is there a good workaround besides reimplementing inspect or dill?

Edit: I am using Python 2.7, but experienced the same behavior using Python 3.4.

答:
I'm the dill author.  I think you've found a bug in inspect, with regard to parsing code blocks containing a lambda as an argument in a decorator.

```<code>>>> f = lambda x: 42
>>> @Decorator(f)
... def fun_4():
...     pass
...
>>>
>>> print dill.source.getsource(fun_4.func)
@Decorator(f)
def fun_4():
    pass

>>>
</code>```

Note that the above works, when you simply use a pointer to the lambda object.  So that's your workaround.

I believe this corner case is a bug in inspect, which dill is using under the covers... so it's a bug in dill also.

I've opened a ticket on the dill GitHub page, and I'll investigate it further to see (1) if there's an easy workaround that can be implemented in dill, and (2) if indeed it's a bug in inspect (I'm guessing it is) -- and if so, it should be populated up to the python developers.  Here's the link to the ticket: https://github.com/uqfoundation/dill/issues/221

Body:
I would like to obtain the source code of a Python function. However, the functions I am dealing with have decorators that are instantiated with functions themselves. It seems like inspect or dill have problems with that. In particular, I tried the following MWE:

class Decorator(object):
    def __init__(self, item):
        self.item = item
        self.func = None
    def __call__(self, func):
        self.func = func
        return self

@Decorator(42)
def fun_1():
    pass

@Decorator(lambda x: 42)
def fun_2():
    pass

@Decorator(fun_2.item)
def fun_3():
    pass

import inspect
print("Inspect results")
print(inspect.getsource(fun_1.func))
print(inspect.getsource(fun_2.func))
print(inspect.getsource(fun_3.func))

import dill
print("Dill results")
print(dill.source.getsource(fun_1.func))
print(dill.source.getsource(fun_2.func))
print(dill.source.getsource(fun_3.func))

For functions fun_1 and fun_3, this gives the expected results. For fun_2 (although it is essentially the same as fun_3), the source code as returned by inspect or dill is just wrong - it only gives me the decorator line. I would expect to get

@Decorator(lambda x: 42)
def fun_2():
    pass

but all I get is

@Decorator(lambda x: 42)

I can imagine that both modules just search for the first function declaration. Is this assumption correct and is there a good workaround besides reimplementing inspect or dill?

Edit: I am using Python 2.7, but experienced the same behavior using Python 3.4.

Body:
I'm the dill author.  I think you've found a bug in inspect, with regard to parsing code blocks containing a lambda as an argument in a decorator.

>>> f = lambda x: 42
>>> @Decorator(f)
... def fun_4():
...     pass
...
>>>
>>> print dill.source.getsource(fun_4.func)
@Decorator(f)
def fun_4():
    pass

>>>

Note that the above works, when you simply use a pointer to the lambda object.  So that's your workaround.

I believe this corner case is a bug in inspect, which dill is using under the covers... so it's a bug in dill also.

I've opened a ticket on the dill GitHub page, and I'll investigate it further to see (1) if there's an easy workaround that can be implemented in dill, and (2) if indeed it's a bug in inspect (I'm guessing it is) -- and if so, it should be populated up to the python developers.  Here's the link to the ticket: https://github.com/uqfoundation/dill/issues/221


问:
HTML5 alternative to flash-based ZeroClipboard for safe copying of data to clipboard?
With flash on the way out in many environments (iPhone, Android, IE10, etc...), is there any new solution forthcoming in any browsers that will allow a safe copy of information to the clipboard without flash installed?

I've been using ZeroClipboard so far, but I'm worried about more viewers that don't have flash and this functionality is going to be broken and I'd love to not depend on Flash whenever possible.

答:
To use the execCommand, you must first select() something on the page, so you do not just copy whatever was last put into the clipboard.  With this function, I pass the id of the input textbox into the function and select() it, then perform the copy command.  No need to add listeners or further complicate your code. The document.execCommand() returns false if not enabled or supported, thus you can use the window.prompt as the backup method.

```<code>function copyToClipboard(id) {
    var blnCopied;
    document.getElementById(id).select();
    blnCopied = document.execCommand("copy", false, null);
    if (blnCopied)
        alert('Link copied to clipboard');
    else
        window.prompt ("Copy to clipboard: Ctrl+C, Enter", jQuery("#"+id).val());
}
</code>```

Use a standard "a" anchor tag with an onclick="copyToClipboard('some_id')"

Body:
To use the execCommand, you must first select() something on the page, so you do not just copy whatever was last put into the clipboard.  With this function, I pass the id of the input textbox into the function and select() it, then perform the copy command.  No need to add listeners or further complicate your code. The document.execCommand() returns false if not enabled or supported, thus you can use the window.prompt as the backup method.

function copyToClipboard(id) {
    var blnCopied;
    document.getElementById(id).select();
    blnCopied = document.execCommand("copy", false, null);
    if (blnCopied)
        alert('Link copied to clipboard');
    else
        window.prompt ("Copy to clipboard: Ctrl+C, Enter", jQuery("#"+id).val());
}

Use a standard "a" anchor tag with an onclick="copyToClipboard('some_id')"


问:
Assert specific constructor called by child class
I am trying to write a test to verify that child classes call a specific base class' constructor. Effectively, IDs for my entities are generated when the object is instantiated by the server. I am using NHibernate as my ORM, and so I need a 0-parameter constructor. I would prefer that this constructor not generate a Guid everytime that NHibernate hydrates an entity, so I created a second constructor for my base entity with a Guid as a paramter.

It looks something like this

```<code>public abstract class EntityBase {
    public Guid ID {get; protected set;}

    protected EntityBase() { }

    public EntityBase(Guid id) { ID = id }

    public static Guid NewID => GenerateGuid();
}

public class Entity : EntityBase {
    public int X {get; set;}

    protected Entity() { }

    public Entity(int x) : base(NewID) { X = x; }
}
</code>```

This test I want to write should assert that all constructors (except the 0-parameter constructor) of all concrete child classes of EntityBase call the correct base constructor:

public EntityBase(Guid id) { ID = id }

Currently, my code loops through constructors on all concrete classes assignable from EntityBase, but I don't know how to make the final check. Research into solutions suggested attempting to read IL using reflection. I considered trying to check if 'NewID' had been called, but was unable to find any accomplish that either.

Is there a way to achieve this, or is my solution to the NHibernate problem the real issue?

答: You need to detect which base constructor is called by each constructor, check if no-args constructor is only called by no-args non public constructor, and do that recursively on the class hierarchy till your base class. </p>

Body:
I am trying to write a test to verify that child classes call a specific base class' constructor. Effectively, IDs for my entities are generated when the object is instantiated by the server. I am using NHibernate as my ORM, and so I need a 0-parameter constructor. I would prefer that this constructor not generate a Guid everytime that NHibernate hydrates an entity, so I created a second constructor for my base entity with a Guid as a paramter.

It looks something like this

public abstract class EntityBase {
    public Guid ID {get; protected set;}

    protected EntityBase() { }

    public EntityBase(Guid id) { ID = id }

    public static Guid NewID => GenerateGuid();
}

public class Entity : EntityBase {
    public int X {get; set;}

    protected Entity() { }

    public Entity(int x) : base(NewID) { X = x; }
}

This test I want to write should assert that all constructors (except the 0-parameter constructor) of all concrete child classes of EntityBase call the correct base constructor:

public EntityBase(Guid id) { ID = id }

Currently, my code loops through constructors on all concrete classes assignable from EntityBase, but I don't know how to make the final check. Research into solutions suggested attempting to read IL using reflection. I considered trying to check if 'NewID' had been called, but was unable to find any accomplish that either.

Is there a way to achieve this, or is my solution to the NHibernate problem the real issue?


问:
UIRefreshControll no progress activityIndicator -> start immediately?
this is my simple code:

```<code>self.refreshControl = [UIRefreshControl new];
[self.refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.myTableView addSubview:self.refreshControl];
</code>```

or

```<code>self.myTableView.refreshControl = self.refreshControl;
</code>```

refresh: method is calling when scroll offset of myTable is -1 (immediately !!), no progress indicator while pulling...

App is on iOS10.3 xcode is 8.3

I saw in Mail app and in a lot of samples on stack that UIRefreshControll before starting show activity like a clock and when it's completed start refreshing.

I have also try to put UIRefreshControll on UITableViewCOntroller, but I saw immediately complete spin and start immediately to refresh:

I'm getting crazy I was suppose is very simple but I can't show progress indicator, can you help me ??

答:
UIScrollView (and therefore UITableView) have a refreshControl property you set instead of adding it as a subview yourself. So:

```<code>self.myTableView.refreshControl = self.refreshControl
</code>```

This should cause it to behave correctly.

Body:
this is my simple code:

self.refreshControl = [UIRefreshControl new];
[self.refreshControl addTarget:self action:@selector(refresh:) forControlEvents:UIControlEventValueChanged];
[self.myTableView addSubview:self.refreshControl];

or

self.myTableView.refreshControl = self.refreshControl;

refresh: method is calling when scroll offset of myTable is -1 (immediately !!), no progress indicator while pulling...

App is on iOS10.3 xcode is 8.3

I saw in Mail app and in a lot of samples on stack that UIRefreshControll before starting show activity like a clock and when it's completed start refreshing.

I have also try to put UIRefreshControll on UITableViewCOntroller, but I saw immediately complete spin and start immediately to refresh:

I'm getting crazy I was suppose is very simple but I can't show progress indicator, can you help me ??

Body:
UIScrollView (and therefore UITableView) have a refreshControl property you set instead of adding it as a subview yourself. So:

self.myTableView.refreshControl = self.refreshControl

This should cause it to behave correctly.


问:
rendering JSON with Grails?
I tried to find a cool guide how rendering JSON with Grails works, the documentation on official website -  to me - very little information.

which articles you used that to understand how it works?

Thanks.

答:
It depends on what you mean by understanding how it works.  If you really want to understand the how, the best thing to do is get the source code from Grails and step through it.  If you just need to understand how to use it, the documentation is more than adequate.  What exactly are you having problems with?

Documentation: http://grails.org/doc/latest/guide/6.%20The%20Web%20Layer.html#6.1.7 XML and JSON Responses

ContentLicense: CC BY-SA 2.5

Title: rendering JSON with Grails?


问:
Accessing name of flat file from FlatFileItemReader LineMapper
I have a need to be able to access the name of the flat file that the current line being read is from. We are porting an application and some processes that are currently in place require this information.

Here is my current configuration:

```<code>private FlatFileItemReader<Invoice> invoiceFlatFileItemReader() throws Exception {
    FlatFileItemReader<Invoice> reader = new FlatFileItemReader<>();
    reader.setLinesToSkip(1); // header row
    reader.setLineMapper(new InvoiceLineMapper());
    reader.afterPropertiesSet();

    return reader;
}
</code>```

InvoiceLineMapper:

```<code>public class InvoiceLineMapper implements LineMapper<Invoice> {

    @Override
    public Invoice mapLine(String line, int lineNumber) throws Exception {
        String[] fields = line.split(",");
        ArrayList<String> fieldList = new ArrayList<>();

        for (int i = 0; i < fields.length; i++) {
            fieldList.add(fields[i].replaceAll("\"", "");
        }

        Invoice invoice = new Invoice();

        invoice.setCustomerNumber(Integer.parseInt(fieldList.get(0));
        invoice.setCustomerName(fieldList.get(1));

        // set other things and stuff...

        //Need to be able to set the file name on the model here
        invoice.setFileName(theFileName);
    }
}
</code>```

I am delegating to the invoiceFlatFileItemReader() via a MultiResourceItemReader:

```<code>@Bean
public ItemReader<Invoice> invoiceItemReader() throws Exception {
    ResourcePatternResolver resolver = new PathMatchingResourcePatterResolver(this.getClass().getClassLoader());

    // currently being loaded from the classpath, eventually will be read from S3...that comes later
    Resource[] resources = resolver.getResources("classpath*:**/InvoiceList*.csv*");

    MultiResourceItemReader<Invoice> reader = new MultiResourceItemReader<>();
    reader.setResources(resources);
    reader.setDelegate(invoiceFlatFileItemReader());

    return reader;
}
</code>```

How can I get the name of the resource passed down the chain to where I can access it in the InvoiceLineMapper class and add it to the model (which later gets persisted with a RepositoryItemWriter)?

答: There is an interface ResourceAware that your item can implement.  If it does implement that interface, when using MultiResourceItemReader, the resource will be injected automatically for you.  You can read more about the ResourceAware interface in the documentation here: http://docs.spring.io/spring-batch/apidocs/org/springframework/batch/item/ResourceAware.html

Body:
I have a need to be able to access the name of the flat file that the current line being read is from. We are porting an application and some processes that are currently in place require this information.

Here is my current configuration:

private FlatFileItemReader<Invoice> invoiceFlatFileItemReader() throws Exception {
    FlatFileItemReader<Invoice> reader = new FlatFileItemReader<>();
    reader.setLinesToSkip(1); // header row
    reader.setLineMapper(new InvoiceLineMapper());
    reader.afterPropertiesSet();

    return reader;
}

InvoiceLineMapper:

public class InvoiceLineMapper implements LineMapper<Invoice> {

    @Override
    public Invoice mapLine(String line, int lineNumber) throws Exception {
        String[] fields = line.split(",");
        ArrayList<String> fieldList = new ArrayList<>();

        for (int i = 0; i < fields.length; i++) {
            fieldList.add(fields[i].replaceAll("\"", "");
        }

        Invoice invoice = new Invoice();

        invoice.setCustomerNumber(Integer.parseInt(fieldList.get(0));
        invoice.setCustomerName(fieldList.get(1));

        // set other things and stuff...

        //Need to be able to set the file name on the model here
        invoice.setFileName(theFileName);
    }
}

I am delegating to the invoiceFlatFileItemReader() via a MultiResourceItemReader:

@Bean
public ItemReader<Invoice> invoiceItemReader() throws Exception {
    ResourcePatternResolver resolver = new PathMatchingResourcePatterResolver(this.getClass().getClassLoader());

    // currently being loaded from the classpath, eventually will be read from S3...that comes later
    Resource[] resources = resolver.getResources("classpath*:**/InvoiceList*.csv*");

    MultiResourceItemReader<Invoice> reader = new MultiResourceItemReader<>();
    reader.setResources(resources);
    reader.setDelegate(invoiceFlatFileItemReader());

    return reader;
}

How can I get the name of the resource passed down the chain to where I can access it in the InvoiceLineMapper class and add it to the model (which later gets persisted with a RepositoryItemWriter)?


问:
Garbage collector tries to collect shared memory object
I've got two Python scripts that both should do essentially the same thing: grab a large object in memory, then fork a bunch of children. The first script uses bare os.fork:

import time
import signal
import os
import gc

gc.set_debug(gc.DEBUG_STATS)

class GracefulExit(Exception):
    pass

def child(i):
    def exit(sig, frame):
        raise GracefulExit("{} out".format(i))

    signal.signal(signal.SIGTERM, exit)
    while True:
        time.sleep(1)

if __name__ == '__main__':
    workers = []

    d = {}
    for i in xrange(30000000):
        d[i] = i

    for i in range(5):
        pid = os.fork()
        if pid == 0:
            child(i)
        else:
            print pid
            workers.append(pid)

    while True:
        wpid, status = os.waitpid(-1, os.WNOHANG)
        if wpid:
            print wpid, status
        time.sleep(1)
```

<p>The second script uses <code>multiprocessing</code> module. I'm running both on Linux (Ubuntu 14.04), so it should use <code>os.fork</code> under the hood too, as documentation states:</p>

<pre class="lang-python prettyprint-override"><code>import multiprocessing
import time
import signal
import gc

gc.set_debug(gc.DEBUG_STATS)

class GracefulExit(Exception):
    pass

def child(i):
    def exit(sig, frame):
        raise GracefulExit("{} out".format(i))

    signal.signal(signal.SIGTERM, exit)
    while True:
        time.sleep(1)

if __name__ == '__main__':
    workers = []

    d = {}
    for i in xrange(30000000):
        d[i] = i

    for i in range(5):
        p = multiprocessing.Process(target=child, args=(i,))
        p.start()
        print p.pid
        workers.append(p)

    while True:
        for worker in workers:
            if not worker.is_alive():
                worker.join()
        time.sleep(1)
</code>```

The difference between those two scripts is the following: when I kill a child (sending a SIGTERM), bare-fork script tries to garbagecollect the shared dictionary, despite the fact that it is still referenced by parent process and isn't actually copied into child's memory (because of copy-on-write)

```<code>kill <pid>

Traceback (most recent call last):
  File "test_mp_fork.py", line 33, in <module>
    child(i)
  File "test_mp_fork.py", line 19, in child
    time.sleep(1)
  File "test_mp_fork.py", line 15, in exit
    raise GracefulExit("{} out".format(i))
__main__.GracefulExit: 3 out
gc: collecting generation 2...
gc: objects in each generation: 521 3156 0
gc: done, 0.0024s elapsed.
</code>```

(perf record -e page-faults -g -p <pid> output:)

```<code>+  99,64%  python  python2.7           [.] PyInt_ClearFreeList
+   0,15%  python  libc-2.19.so        [.] vfprintf
+   0,09%  python  python2.7           [.] 0x0000000000144e90
+   0,06%  python  libc-2.19.so        [.] strlen
+   0,05%  python  python2.7           [.] PyArg_ParseTupleAndKeywords
+   0,00%  python  python2.7           [.] PyEval_EvalFrameEx
+   0,00%  python  python2.7           [.] Py_AddPendingCall
+   0,00%  python  libpthread-2.19.so  [.] sem_trywait
+   0,00%  python  libpthread-2.19.so  [.] __errno_location
</code>```

While multiprocessing-based script does no such thing:

```<code>kill <pid>

Process Process-3:
Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "test_mp.py", line 19, in child
    time.sleep(1)
  File "test_mp.py", line 15, in exit
    raise GracefulExit("{} out".format(i))
GracefulExit: 2 out
</code>```

(perf record -e page-faults -g -p <pid> output:)

```<code>+  62,96%  python  python2.7           [.] 0x0000000000047a5b
+  32,28%  python  python2.7           [.] PyString_Format
+   2,65%  python  python2.7           [.] Py_BuildValue
+   1,06%  python  python2.7           [.] PyEval_GetFrame
+   0,53%  python  python2.7           [.] Py_AddPendingCall
+   0,53%  python  libpthread-2.19.so  [.] sem_trywait
</code>```

I can also force the same behavior on multiprocessing-based script by explicitly calling gc.collect() before raising GracefulExit. Curiously enough, the reverse is not true: calling gc.disable(); gc.set_threshold(0) in bare-fork script doesn't help to get rid of PyInt_ClearFreeList calls.

To the actual questions:

Why is this happening? I sort of understand why python would like to free all the allocated memory on process exit, ignoring the fact that the child process doesn't physically own it, but how come multiprocessing module doesn't do the same?

I'd like to achieve second-script-like behavior (i.e.: not trying to free the memory which has been allocated by a parent process) with bare-fork solution (mainly because I use a third-party process manager library which doesn't use multiprocessing); how could I possibly do that?

答: Multiprocessing behaves differently because it uses os._exit which doesn't call exit handler, which, apparently, involves garbage collection (more on the topic). Explicitly calling os._exit in bare-fork version of the script achieves the same result.

Body:
I've got two Python scripts that both should do essentially the same thing: grab a large object in memory, then fork a bunch of children. The first script uses bare os.fork:

import time
import signal
import os
import gc

gc.set_debug(gc.DEBUG_STATS)

class GracefulExit(Exception):
    pass

def child(i):
    def exit(sig, frame):
        raise GracefulExit("{} out".format(i))

    signal.signal(signal.SIGTERM, exit)
    while True:
        time.sleep(1)

if __name__ == '__main__':
    workers = []

    d = {}
    for i in xrange(30000000):
        d[i] = i

    for i in range(5):
        pid = os.fork()
        if pid == 0:
            child(i)
        else:
            print pid
            workers.append(pid)

    while True:
        wpid, status = os.waitpid(-1, os.WNOHANG)
        if wpid:
            print wpid, status
        time.sleep(1)

The second script uses multiprocessing module. I'm running both on Linux (Ubuntu 14.04), so it should use os.fork under the hood too, as documentation states:

import multiprocessing
import time
import signal
import gc

gc.set_debug(gc.DEBUG_STATS)

class GracefulExit(Exception):
    pass

def child(i):
    def exit(sig, frame):
        raise GracefulExit("{} out".format(i))

    signal.signal(signal.SIGTERM, exit)
    while True:
        time.sleep(1)

if __name__ == '__main__':
    workers = []

    d = {}
    for i in xrange(30000000):
        d[i] = i

    for i in range(5):
        p = multiprocessing.Process(target=child, args=(i,))
        p.start()
        print p.pid
        workers.append(p)

    while True:
        for worker in workers:
            if not worker.is_alive():
                worker.join()
        time.sleep(1)

The difference between those two scripts is the following: when I kill a child (sending a SIGTERM), bare-fork script tries to garbagecollect the shared dictionary, despite the fact that it is still referenced by parent process and isn't actually copied into child's memory (because of copy-on-write)

kill <pid>

Traceback (most recent call last):
  File "test_mp_fork.py", line 33, in <module>
    child(i)
  File "test_mp_fork.py", line 19, in child
    time.sleep(1)
  File "test_mp_fork.py", line 15, in exit
    raise GracefulExit("{} out".format(i))
__main__.GracefulExit: 3 out
gc: collecting generation 2...
gc: objects in each generation: 521 3156 0
gc: done, 0.0024s elapsed.

(perf record -e page-faults -g -p <pid> output:)

+  99,64%  python  python2.7           [.] PyInt_ClearFreeList
+   0,15%  python  libc-2.19.so        [.] vfprintf
+   0,09%  python  python2.7           [.] 0x0000000000144e90
+   0,06%  python  libc-2.19.so        [.] strlen
+   0,05%  python  python2.7           [.] PyArg_ParseTupleAndKeywords
+   0,00%  python  python2.7           [.] PyEval_EvalFrameEx
+   0,00%  python  python2.7           [.] Py_AddPendingCall
+   0,00%  python  libpthread-2.19.so  [.] sem_trywait
+   0,00%  python  libpthread-2.19.so  [.] __errno_location

While multiprocessing-based script does no such thing:

kill <pid>

Process Process-3:
Traceback (most recent call last):
  File "/usr/lib/python2.7/multiprocessing/process.py", line 258, in _bootstrap
    self.run()
  File "/usr/lib/python2.7/multiprocessing/process.py", line 114, in run
    self._target(*self._args, **self._kwargs)
  File "test_mp.py", line 19, in child
    time.sleep(1)
  File "test_mp.py", line 15, in exit
    raise GracefulExit("{} out".format(i))
GracefulExit: 2 out

(perf record -e page-faults -g -p <pid> output:)

+  62,96%  python  python2.7           [.] 0x0000000000047a5b
+  32,28%  python  python2.7           [.] PyString_Format
+   2,65%  python  python2.7           [.] Py_BuildValue
+   1,06%  python  python2.7           [.] PyEval_GetFrame
+   0,53%  python  python2.7           [.] Py_AddPendingCall
+   0,53%  python  libpthread-2.19.so  [.] sem_trywait

I can also force the same behavior on multiprocessing-based script by explicitly calling gc.collect() before raising GracefulExit. Curiously enough, the reverse is not true: calling gc.disable(); gc.set_threshold(0) in bare-fork script doesn't help to get rid of PyInt_ClearFreeList calls.

To the actual questions:

Why is this happening? I sort of understand why python would like to free all the allocated memory on process exit, ignoring the fact that the child process doesn't physically own it, but how come multiprocessing module doesn't do the same?

I'd like to achieve second-script-like behavior (i.e.: not trying to free the memory which has been allocated by a parent process) with bare-fork solution (mainly because I use a third-party process manager library which doesn't use multiprocessing); how could I possibly do that?


问:
C- gethostbyaddr & Valgrind
For some reason valgrind keeps throwing the following error:

```<code>==6263== Invalid read of size 4
==6263==    at 0x40151B9: (within /lib/ld-2.7.so)
==6263==    by 0x4005C29: (within /lib/ld-2.7.so)
==6263==    by 0x4007A47: (within /lib/ld-2.7.so)
==6263==    by 0x40114F3: (within /lib/ld-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4010F0D: (within /lib/ld-2.7.so)
==6263==    by 0x4141391: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4141554: __libc_dlopen_mode (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B286: __nss_lookup_function (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B39F: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411CFC5: __nss_hosts_lookup (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==  Address 0x4183d24 is 36 bytes inside a block of size 37 alloc'd
==6263==    at 0x4022AB8: malloc (vg_replace_malloc.c:207)
</code>```

Here is the way I'm doing it. Any reasons why this is happening? Thanks

```<code>#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>

char *IPtoHostname(const char *ipaddress)
{
    struct hostent *host;
    unsigned int ip = 0;
    ip = inet_addr (ipaddress);
    host = gethostbyaddr ((char *) &ip, sizeof (unsigned int), AF_INET);
    if (host == NULL) return NULL;
    return strdup(host->h_name);
}

int main () {
   const char *ip = "65.55.4.170";
   char *a =  NULL;
   a = IPtoHostname(ip);
   printf ("%s\n", a);
   free (a);

   return 0;
}
</code>```

Update: It happens when I run it under Linux hardy 2.6.24-16-generic It does not happen under Ubuntu 9.10

答:
One way to eliminate the problem in these legacy functions is to stop using them. gethostbyname and gethostbyaddr have been removed from POSIX as of 2008; they have serious issues with IPv6 support, thread-safety, unclear specification and inconsistent implementation across platforms, and so on. You simply should not use them.

The modern replacements are getaddrinfo and getnameinfo. If you use these functions, you'll never have to write ugly wrappers like you're doing.

Title: C- gethostbyaddr & Valgrind

Body:
For some reason valgrind keeps throwing the following error:

==6263== Invalid read of size 4
==6263==    at 0x40151B9: (within /lib/ld-2.7.so)
==6263==    by 0x4005C29: (within /lib/ld-2.7.so)
==6263==    by 0x4007A47: (within /lib/ld-2.7.so)
==6263==    by 0x40114F3: (within /lib/ld-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4010F0D: (within /lib/ld-2.7.so)
==6263==    by 0x4141391: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x400D585: (within /lib/ld-2.7.so)
==6263==    by 0x4141554: __libc_dlopen_mode (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B286: __nss_lookup_function (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411B39F: (within /lib/tls/i686/cmov/libc-2.7.so)
==6263==    by 0x411CFC5: __nss_hosts_lookup (in /lib/tls/i686/cmov/libc-2.7.so)
==6263==  Address 0x4183d24 is 36 bytes inside a block of size 37 alloc'd
==6263==    at 0x4022AB8: malloc (vg_replace_malloc.c:207)

Here is the way I'm doing it. Any reasons why this is happening? Thanks

#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>

char *IPtoHostname(const char *ipaddress)
{
    struct hostent *host;
    unsigned int ip = 0;
    ip = inet_addr (ipaddress);
    host = gethostbyaddr ((char *) &ip, sizeof (unsigned int), AF_INET);
    if (host == NULL) return NULL;
    return strdup(host->h_name);
}

int main () {
   const char *ip = "65.55.4.170";
   char *a =  NULL;
   a = IPtoHostname(ip);
   printf ("%s\n", a);
   free (a);

   return 0;
}

Update: It happens when I run it under Linux hardy 2.6.24-16-generic It does not happen under Ubuntu 9.10


问:
Insert a textbox on a specific word page
I am iterating through all storyranges in a word document, to find shapes that do not adhere to company standards. When I find such a shape, I would like to add a textbox in the upper right corner of it's page. I only managed to add it to the first page so far.

```<code>foreach (Word.InlineShape shape in storyRange.InlineShapes)
        {
            if (shape.Type == Word.WdInlineShapeType.wdInlineShapePicture)
            {
                if (shape.Width != CurrentWordApp.CentimetersToPoints(Constants.LogoWidth))
                {
                    anchor = shape.Range;
                    shapePageNumber = (int)shape.Range.Information[Word.WdInformation.wdActiveEndPageNumber];
                    AddMarkerToPage(shapePageNumber, anchor);
                }
            }
        }
</code>```

This is an excerpt from the AddMarkerToPage method. The only place I found to add a textbox, is the header. And the only place I found the header was through the section object. But section does not equal page.

```<code> Word.HeaderFooter header =  anchor.Sections.First.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
 if (!pageHasMarker)
        {
            Word.Shape tbx = header.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal,
                        CurrentWordApp.CentimetersToPoints(Helper.errorMarkerFromLeft),
                        CurrentWordApp.CentimetersToPoints(Helper.errorMarkerFromTop),
                        CurrentWordApp.CentimetersToPoints(Helper.errorMarkerWidth),
                         CurrentWordApp.CentimetersToPoints(Helper.errorMarkerHeight), pageRange);
            tbx.Name = "errorBox";
            tbx.TextFrame.TextRange.Text = Resources.Strings.txtDesignCheckHeaderLogo;
        }
 }
</code>```

How can I either get to the header on the page the shape is on, or have another object that allows me to position a textbox on a specific page (I have the number available from the shape object)

答:
Don't use the header, use the Document.Shapes collection.

```<code>Word.Shape tbx = <document>.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal,
                 CurrentWordApp.CentimetersToPoints(Helper.errorMarkerFromLeft),
                 CurrentWordApp.CentimetersToPoints(Helper.errorMarkerFromTop),
                 CurrentWordApp.CentimetersToPoints(Helper.errorMarkerWidth),
                  CurrentWordApp.CentimetersToPoints(Helper.errorMarkerHeight), anchor);
tbx.Name = "errorBox";
tbx.TextFrame.TextRange.Text = Resources.Strings.txtDesignCheckHeaderLogo;
</code>```

I think you'll also need these:

```<code>tbx.RelativeVerticalPosition = WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;
tbx.RelativeHorizontalPosition = WdRelativeHorizontalPosition.wdRelativeHorizontalPositionColumn;
</code>```

Body:
I am iterating through all storyranges in a word document, to find shapes that do not adhere to company standards. When I find such a shape, I would like to add a textbox in the upper right corner of it's page. I only managed to add it to the first page so far.

foreach (Word.InlineShape shape in storyRange.InlineShapes)
        {
            if (shape.Type == Word.WdInlineShapeType.wdInlineShapePicture)
            {
                if (shape.Width != CurrentWordApp.CentimetersToPoints(Constants.LogoWidth))
                {
                    anchor = shape.Range;
                    shapePageNumber = (int)shape.Range.Information[Word.WdInformation.wdActiveEndPageNumber];
                    AddMarkerToPage(shapePageNumber, anchor);
                }
            }
        }

This is an excerpt from the AddMarkerToPage method. The only place I found to add a textbox, is the header. And the only place I found the header was through the section object. But section does not equal page.

 Word.HeaderFooter header =  anchor.Sections.First.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary];
 if (!pageHasMarker)
        {
            Word.Shape tbx = header.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal,
                        CurrentWordApp.CentimetersToPoints(Helper.errorMarkerFromLeft),
                        CurrentWordApp.CentimetersToPoints(Helper.errorMarkerFromTop),
                        CurrentWordApp.CentimetersToPoints(Helper.errorMarkerWidth),
                         CurrentWordApp.CentimetersToPoints(Helper.errorMarkerHeight), pageRange);
            tbx.Name = "errorBox";
            tbx.TextFrame.TextRange.Text = Resources.Strings.txtDesignCheckHeaderLogo;
        }
 }

How can I either get to the header on the page the shape is on, or have another object that allows me to position a textbox on a specific page (I have the number available from the shape object)

Body:
Don't use the header, use the Document.Shapes collection.

Word.Shape tbx = <document>.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal,
                 CurrentWordApp.CentimetersToPoints(Helper.errorMarkerFromLeft),
                 CurrentWordApp.CentimetersToPoints(Helper.errorMarkerFromTop),
                 CurrentWordApp.CentimetersToPoints(Helper.errorMarkerWidth),
                  CurrentWordApp.CentimetersToPoints(Helper.errorMarkerHeight), anchor);
tbx.Name = "errorBox";
tbx.TextFrame.TextRange.Text = Resources.Strings.txtDesignCheckHeaderLogo;

I think you'll also need these:

tbx.RelativeVerticalPosition = WdRelativeVerticalPosition.wdRelativeVerticalPositionPage;
tbx.RelativeHorizontalPosition = WdRelativeHorizontalPosition.wdRelativeHorizontalPositionColumn;


问:
compile angularjs ionic app with Phonegap Build
is it ok to compile a AngularJS+ Ionic app using Phonegap Build or Steroids ?
Or should I use another platform ?

I would like your feedback!

Thanks

答: yes you can use PhoneGap Build to build your application on android and window phone but ios you need key Provisioning profile  good luck </p>


问:
Inverting animation direction
I want to invert animation in HTML/CSS/jQuery.
I was trying to do it with flexbox, but I can't.

Now it's animating from right to left, but I want to do it from left to right. Also content 1 should be visible at the beginning, and then after animation finished content 2 should be visible.

HTML:

```<code><div id="slides">
  <div class="cont1 activeTab">
    Content 1
  </div>
  <div class="cont2">
    Content 2
  </div>
</div>
<div>
  <button>xxx</button>
</div>
</code>```

CSS:

```<code>#slides{
  position:relative;
  overflow:hidden;
  margin:0 auto;
  background:#cf5;
  width:400px;
  height:200px;
  white-space:nowrap;
}
#slides div{
  position:relative;
  display:inline-block;
  margin-right:-4px;
  white-space:normal;
  vertical-align:top;
  *display:inline;
  background:#eee;
  width:400px;
  height:200px;
}
#slides .cont1 {
  background: red;
}
#slides .cont2 {
  background: blue;
}
</code>```

jQuery:

```<code>$(function(){

  var slideW = $('#slides').width();
  $('button').click(function( e ){
    var el = $(this),
        state = el.data('animState');
    if(state == 'busy') {
       return false;
    }
    el.data('animState', 'busy');
    if ($('.cont1').hasClass('activeTab')) {
      $('#slides').animate({scrollLeft: slideW }, 600, function(){
        $('.cont1').removeClass('activeTab');
        $('.cont2').addClass('activeTab');
        el.data('animState', 'complete');
      });
    } else {
      $('#slides').animate({scrollLeft: 0 }, 600, function(){
        $('.cont1').addClass('activeTab');
        $('.cont2').removeClass('activeTab');
        el.data('animState', 'complete');
      });
    }
  });

});
</code>```

Here is the jsfiddle

Anyone can help?

答:
You can use flexbox like this:

```<code>#slides{
  position:relative;
  overflow:hidden;
  margin:0 auto;
  background:#cf5;
  width:400px;
  height:200px;
  display:flex;
  flex-direction:row-reverse;
}
#slides div{
  flex:0 0 100%;
  position:relative;
  background:#eee;
  width:400px;
  height:200px;
}
</code>```

And then on your JS just change the scrollLeft value to be animated first to 0 and after to slideW.

Updated Fiddle

Title: Inverting animation direction

Body:
I want to invert animation in HTML/CSS/jQuery.
I was trying to do it with flexbox, but I can't.

Now it's animating from right to left, but I want to do it from left to right. Also content 1 should be visible at the beginning, and then after animation finished content 2 should be visible.

HTML:

    Content 1

    Content 2

  <button>xxx</button>

CSS:

#slides{
  position:relative;
  overflow:hidden;
  margin:0 auto;
  background:#cf5;
  width:400px;
  height:200px;
  white-space:nowrap;
}
#slides div{
  position:relative;
  display:inline-block;
  margin-right:-4px;
  white-space:normal;
  vertical-align:top;
  *display:inline;
  background:#eee;
  width:400px;
  height:200px;
}
#slides .cont1 {
  background: red;
}
#slides .cont2 {
  background: blue;
}

jQuery:

$(function(){

  var slideW = $('#slides').width();
  $('button').click(function( e ){
    var el = $(this),
        state = el.data('animState');
    if(state == 'busy') {
       return false;
    }
    el.data('animState', 'busy');
    if ($('.cont1').hasClass('activeTab')) {
      $('#slides').animate({scrollLeft: slideW }, 600, function(){
        $('.cont1').removeClass('activeTab');
        $('.cont2').addClass('activeTab');
        el.data('animState', 'complete');
      });
    } else {
      $('#slides').animate({scrollLeft: 0 }, 600, function(){
        $('.cont1').addClass('activeTab');
        $('.cont2').removeClass('activeTab');
        el.data('animState', 'complete');
      });
    }
  });

});

Here is the jsfiddle

Anyone can help?

Body:
You can use flexbox like this:

#slides{
  position:relative;
  overflow:hidden;
  margin:0 auto;
  background:#cf5;
  width:400px;
  height:200px;
  display:flex;
  flex-direction:row-reverse;
}
#slides div{
  flex:0 0 100%;
  position:relative;
  background:#eee;
  width:400px;
  height:200px;
}

And then on your JS just change the scrollLeft value to be animated first to 0 and after to slideW.

Updated Fiddle


问:
How to add new nodes / neurons dynamically in tensorflow
If I want to add new nodes to on of my tensorflow layers on the fly, how can I do that?

For example if I want to change the amount of hidden nodes from 10 to 11 after the model has been training for a while. Also, assume I know what value I want the weights coming in and out of this node/neuron to be.

I can create a whole new graph, but is there a different/better way?

答: Instead of creating a whole new graph you might be better off creating a graph which has initially more neurons than you need and mask it off by multiplying by a non-trainable variable which has ones and zeros. You can then change the value of this mask variable to allow effectively new neurons to act for the first time.</p>


问:
what's the pythonic way to count the occurrence of an element in a list?
this is what I did. is there a better way in python?

```
for k in a_list:
  if kvMap.has_key(k):
    kvMap[k]=kvMap[k]+1
  else:
    kvMap[k]=1
```

Thanks

答:
If your list is sorted, an alternative way would be to use itertools.groupby. This might not be the most effective way, but it's interesting nonetheless. It retuns a dict of item > count :</p>

```<code>>>> import itertools
>>> l = [1,1,2,3,4,4,4,5,5,6,6,6,7]
>>> dict([(key, len([e for e in group]))
          for (key, group)
          in itertools.groupby(l)])
{1: 2, 2: 1, 3: 1, 4: 3, 5: 2, 6: 3, 7: 1}
</code>```

Body:
this is what I did. is there a better way in python?

for k in a_list:
  if kvMap.has_key(k):
    kvMap[k]=kvMap[k]+1
  else:
    kvMap[k]=1

Thanks

Body:
If your list is sorted, an alternative way would be to use itertools.groupby. This might not be the most effective way, but it's interesting nonetheless. It retuns a dict of item > count :

>>> import itertools
>>> l = [1,1,2,3,4,4,4,5,5,6,6,6,7]
>>> dict([(key, len([e for e in group]))
          for (key, group)
          in itertools.groupby(l)])
{1: 2, 2: 1, 3: 1, 4: 3, 5: 2, 6: 3, 7: 1}

OwnerDisplayName: runeh


问:
Create array from one field in a set of objects in Rails 5
```<code>@ride.passengers
</code>```

Gives me something like this:

```<code>[
  {
    "id": null,
    "salutation": "Sr",
    "first_name": "fsd",
    "last_name": "sfd",
    "email": "sf@sdf.sdf",
    "mobile": "123234345",
    "company_id": 7,
    "cost_center_id": null,
    "created_at": null,
    "updated_at": null
  },
  {
    "id": null,
    "salutation": null,
    "first_name": null,
    "last_name": null,
    "email": null,
    "mobile": null,
    "company_id": 12,
    "cost_center_id": null,
    "created_at": null,
    "updated_at": null
  }
]
</code>```

I want to create an array with all company_ids:

```<code>[7,12]
</code>```

I tried:

```<code>@ride.passengers.pluck(:company_id)
</code>```

But this returns an empty error.

答:
pluck is an active record method. You are trying to manipulate the data returned from an active record query, try

```<code>@rides.passengers.map{ |object| object["company_id"} }
</code>```

Body:
@ride.passengers

Gives me something like this:

[
  {
    "id": null,
    "salutation": "Sr",
    "first_name": "fsd",
    "last_name": "sfd",
    "email": "sf@sdf.sdf",
    "mobile": "123234345",
    "company_id": 7,
    "cost_center_id": null,
    "created_at": null,
    "updated_at": null
  },
  {
    "id": null,
    "salutation": null,
    "first_name": null,
    "last_name": null,
    "email": null,
    "mobile": null,
    "company_id": 12,
    "cost_center_id": null,
    "created_at": null,
    "updated_at": null
  }
]

I want to create an array with all company_ids:

[7,12]

I tried:

@ride.passengers.pluck(:company_id)

But this returns an empty error.

Body:
pluck is an active record method. You are trying to manipulate the data returned from an active record query, try

@rides.passengers.map{ |object| object["company_id"} }


问:
TestNG report with customized error in place of stack trace, when my script fails
I am using Testng and selenium, if my script is fail then it shows the total stack trace in report but i need only custom message to know the error.

Error is comming like this:

```<code> FAILED: abc
java.lang.AssertionError: url:http//:abc.com
at org.testng.Assert.fail(Assert.java:94)
at com.ebates.qa.dotcom.test.MerchantImages.storeSmallIconImageVerification(MerchantImages.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================
</code>```

but actually i don't want to this stacktrace
i need a custom message in place of stacktrace..

答:
You could add custom TestListener to your code like:

```<code>public class TestListener extends TestListenerAdapter {

    @Override
    public void onTestFailure(ITestResult tr) {
        Throwable th = tr.getThrowable();
        if (th != null) {
            System.out.println(th.getMessage());
            tr.setThrowable(null);
        }
    }
}
</code>```

and add listener to test case class:

```<code>@Listeners({TestListener.class})
public class myTest() {
    . . . // tests
}
</code>```

Body:
I am using Testng and selenium, if my script is fail then it shows the total stack trace in report but i need only custom message to know the error.

Error is comming like this:

 FAILED: abc
java.lang.AssertionError: url:http//:abc.com
at org.testng.Assert.fail(Assert.java:94)
at com.ebates.qa.dotcom.test.MerchantImages.storeSmallIconImageVerification(MerchantImages.java:63)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767)
at org.testng.TestRunner.run(TestRunner.java:617)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:334)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:291)
at org.testng.SuiteRunner.run(SuiteRunner.java:240)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1224)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1149)
at org.testng.TestNG.run(TestNG.java:1057)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)

===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================

===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================

but actually i don't want to this stacktrace
i need a custom message in place of stacktrace..

Body:
You could add custom TestListener to your code like:

public class TestListener extends TestListenerAdapter {

    @Override
    public void onTestFailure(ITestResult tr) {
        Throwable th = tr.getThrowable();
        if (th != null) {
            System.out.println(th.getMessage());
            tr.setThrowable(null);
        }
    }
}

and add listener to test case class:

@Listeners({TestListener.class})
public class myTest() {
    . . . // tests
}


问:
Regex : Everything in group except white space
I have this regex right here :

```<code>^(@include rem\(\s*(.*)),\s*(.*)\)
</code>```

That matches this string :

```<code>@include rem( padding-top, $alert-padding );
</code>```

I want to be able that the group with $alert-padding ignores the white space at the end. I tried doing :

```<code>^(@include rem\(\s*(.*)),\s*(/S)\)
</code>```

replace the .* by /S but it doesn't match.

You can play around with the regex here :
https://regex101.com/r/9rouVU/1/

答:
You can make the match in the second group lazy and then match for further optional whitespace:</p>

```<code>^(@include rem\(\s*(.*)),\s*(.*?)\s*\)
</code>```

Body:
I have this regex right here :

^(@include rem\(\s*(.*)),\s*(.*)\)

That matches this string :

@include rem( padding-top, $alert-padding );

I want to be able that the group with $alert-padding ignores the white space at the end. I tried doing :

^(@include rem\(\s*(.*)),\s*(/S)\)

replace the .* by /S but it doesn't match.

You can play around with the regex here :
https://regex101.com/r/9rouVU/1/

Body:
You can make the match in the second group lazy and then match for further optional whitespace:

^(@include rem\(\s*(.*)),\s*(.*?)\s*\)


问:
VBS for opening the Windows 10 task view
I have an Elan touchpad on my notebook. Sadly the driver does not support the new "task view" feature, only executing external programs.

I already found out: it's not possible to send the WIN key via vbs and also this solution suggested

```<code>Set objShell = CreateObject("Shell.Application")
objShell.WindowSwitcher
</code>```

does not work anymore. Same goes with the rundll32 solution.

I DON'T want to install 3rd party thingies.

So, is there solution to this?

答:
If you include () after windowswitcher it worked for me. On 7 it worked fine without, but I suppose 10 is a bit more picky:

```<code>Set objShell = CreateObject("Shell.Application")
objShell.WindowSwitcher()
</code>```

Body:
I have an Elan touchpad on my notebook. Sadly the driver does not support the new "task view" feature, only executing external programs.

I already found out: it's not possible to send the WIN key via vbs and also this solution suggested

Set objShell = CreateObject("Shell.Application")
objShell.WindowSwitcher

does not work anymore. Same goes with the rundll32 solution.

I DON'T want to install 3rd party thingies.

So, is there solution to this?

Body:
If you include () after windowswitcher it worked for me. On 7 it worked fine without, but I suppose 10 is a bit more picky:

Set objShell = CreateObject("Shell.Application")
objShell.WindowSwitcher()


问:
Dynamically setting Flask-SQLAlchemy database connection in multi-tenant app
I have a "multi-tenant" Flask web application which interfaces with 1 "master" MySQL database (used to look up the client information) and dozens of "client" MySQL databases (which all have the same schema).

I'm currently trying to use SQLAlchemy along with the Flask-SQLAlchemy extension to interface with the databases, but I'm struggling to find a way to allow the Models I define in my app to dynamically switch context from one client database to another, depending on the client.

On the Flask-SQLAlchemy site, a simple example is shown along the lines of:

```<code>from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@Y.Y.Y.Y/db1'
db = SQLAlchemy(app)

class User(db.Model):
    # Etc.
</code>```

The only problem is, the SQLALCHEMY_DATABASE_URI configuration is done statically. I may need to switch between mysql://username:password@Y.Y.Y.Y/db1 and mysql://username:password@Z.Z.Z.Z/db1 (or any other arbitrary MySQL URI), depending on which client is making the request.

I've found some similar questions (see below), but I have yet to figure out a clean way to do it when using the Flask-SQLAlchemy extension specifically.

With sqlalchemy how to dynamically bind to database engine on a per-request basis

Flask SQLAlchemy setup dynamic URI

I've also seen some examples that were provided for handling sharded databases (which should apply as well, as the databases are essentially sharded logically by client), but, again, nothing specific to Flask-SQLAlchemy.

If it makes sense, I'm also open to using SQLAlchemy directly, without the Flask-SQLAlchemy extension. I'm new to SQLAlchemy - any help would be greatly appreciated!

Edit: Being able to reflect the table schemas from the database would be a bonus.

答:
If you're using flask-sqlalchemy 0.12 or later, this feature is supported with BINDS.

```<code>SQLALCHEMY_DATABASE_URI = 'postgres://localhost/main'
SQLALCHEMY_BINDS = {
'users':        'mysqldb://localhost/users',
'appmeta':      'sqlite:////path/to/appmeta.db'
}
</code>```

And you can specify connection database in the model definition.

```<code>class User(db.Model):
    __bind_key__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
</code>```

It will use the mysqldb auto. For more details, you can refer official document. Multiple Databases with Binds

Body:
I have a "multi-tenant" Flask web application which interfaces with 1 "master" MySQL database (used to look up the client information) and dozens of "client" MySQL databases (which all have the same schema).

I'm currently trying to use SQLAlchemy along with the Flask-SQLAlchemy extension to interface with the databases, but I'm struggling to find a way to allow the Models I define in my app to dynamically switch context from one client database to another, depending on the client.

On the Flask-SQLAlchemy site, a simple example is shown along the lines of:

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@Y.Y.Y.Y/db1'
db = SQLAlchemy(app)

class User(db.Model):
    # Etc.

The only problem is, the SQLALCHEMY_DATABASE_URI configuration is done statically. I may need to switch between mysql://username:password@Y.Y.Y.Y/db1 and mysql://username:password@Z.Z.Z.Z/db1 (or any other arbitrary MySQL URI), depending on which client is making the request.

I've found some similar questions (see below), but I have yet to figure out a clean way to do it when using the Flask-SQLAlchemy extension specifically.

With sqlalchemy how to dynamically bind to database engine on a per-request basis

Flask SQLAlchemy setup dynamic URI

I've also seen some examples that were provided for handling sharded databases (which should apply as well, as the databases are essentially sharded logically by client), but, again, nothing specific to Flask-SQLAlchemy.

If it makes sense, I'm also open to using SQLAlchemy directly, without the Flask-SQLAlchemy extension. I'm new to SQLAlchemy - any help would be greatly appreciated!

Edit: Being able to reflect the table schemas from the database would be a bonus.

Body:
If you're using flask-sqlalchemy 0.12 or later, this feature is supported with BINDS.

SQLALCHEMY_DATABASE_URI = 'postgres://localhost/main'
SQLALCHEMY_BINDS = {
'users':        'mysqldb://localhost/users',
'appmeta':      'sqlite:////path/to/appmeta.db'
}

And you can specify connection database in the model definition.

class User(db.Model):
    __bind_key__ = 'users'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)

It will use the mysqldb auto. For more details, you can refer official document. Multiple Databases with Binds