问:
How to fix 'SQLSTATE[42883]: Undefined function: 7 ERROR' on postgres?
I hava a function trigger that feed a column with a geometry converted from another column with json. It was working without problems until recently, when i started getting this error: ' SQLSTATE[42883]: Undefined function: 7 ERROR ...  No function matches the given name and argument types. You might need to add explicit type casts.'

This is the script for my function:

```<code>CREATE OR REPLACE FUNCTION update_formulario_ep()
RETURNS trigger AS $teste_trigger$
BEGIN
UPDATE formulario.formulario_ep
SET geom = (SELECT ST_GeomFromText( ST_AsText( CAST(ST_GeomFromGeoJSON(geom_js) AS TEXT) ), 4326 ));
RETURN NEW;
END;
$teste_trigger$ LANGUAGE plpgsql;
</code>```

And this is the script for the trigger:

```<code>CREATE TRIGGER update_allrows_trigger_ep
AFTER INSERT ON formulario.formulario_ep
FOR EACH ROW
EXECUTE PROCEDURE update_formulario_ep();
</code>```

答:
You need to make sure that the schema where PostGIS is installed is available in the search_path of the user that do the insert, as detailed in this post.

Also your trigger could be greatly simplified by making it a BEFORE trigger, allowing to simply set the NEW.geom value:

```<code>CREATE OR REPLACE FUNCTION update_formulario_ep()
RETURNS trigger AS $teste_trigger$
 BEGIN
   NEW.geom = ST_SetSRID(ST_GeomFromGeoJSON(NEW.geom_js),4326);
   RETURN NEW;
  END;
$teste_trigger$ LANGUAGE plpgsql;

CREATE TRIGGER update_allrows_trigger_ep
BEFORE INSERT ON formulario.formulario_ep
FOR EACH ROW
EXECUTE PROCEDURE update_formulario_ep();
</code>```

Body:
I hava a function trigger that feed a column with a geometry converted from another column with json. It was working without problems until recently, when i started getting this error: ' SQLSTATE[42883]: Undefined function: 7 ERROR ...  No function matches the given name and argument types. You might need to add explicit type casts.'

This is the script for my function:

CREATE OR REPLACE FUNCTION update_formulario_ep()
RETURNS trigger AS $teste_trigger$
BEGIN
UPDATE formulario.formulario_ep
SET geom = (SELECT ST_GeomFromText( ST_AsText( CAST(ST_GeomFromGeoJSON(geom_js) AS TEXT) ), 4326 ));
RETURN NEW;
END;
$teste_trigger$ LANGUAGE plpgsql;

And this is the script for the trigger:

CREATE TRIGGER update_allrows_trigger_ep
AFTER INSERT ON formulario.formulario_ep
FOR EACH ROW
EXECUTE PROCEDURE update_formulario_ep();

Body:
You need to make sure that the schema where PostGIS is installed is available in the search_path of the user that do the insert, as detailed in this post.

Also your trigger could be greatly simplified by making it a BEFORE trigger, allowing to simply set the NEW.geom value:

CREATE OR REPLACE FUNCTION update_formulario_ep()
RETURNS trigger AS $teste_trigger$
 BEGIN
   NEW.geom = ST_SetSRID(ST_GeomFromGeoJSON(NEW.geom_js),4326);
   RETURN NEW;
  END;
$teste_trigger$ LANGUAGE plpgsql;

CREATE TRIGGER update_allrows_trigger_ep
BEFORE INSERT ON formulario.formulario_ep
FOR EACH ROW
EXECUTE PROCEDURE update_formulario_ep();


来源: stackexchange

问:
Getting error when dynamically unpivoting in SQL Server 2012
The goal is to dynamically pivot data and then dynamically unpivot it.

I am getting an error saying Invalid ControlNo

I am assuming its because variable @colsUnpivot contains ControlNo column.

But how can I fix it? I definitely need that ControlNo.

```<code>IF OBJECT_ID('tempdb..##A') IS NOT NULL DROP TABLE ##A
IF OBJECT_ID('tempdb..#table1') IS NOT NULL DROP TABLE #table1

Create table #Table1 ( ControlNo INT, Bound INT, Declined INT, Rated INT, Quoted INT, QuoteStatus VARCHAR(50) )

INSERT INTO #Table1 (ControlNo, Bound, Declined, Rated, Quoted, QuoteStatus)
    VALUES  (1111,1,0,1,1,'Lost'),
            (2222,0,1,0,1,'No Action'),
            (3333,1,1,0,0,NULL),
            (4444,1,0,0,1,'Lost'),
            (5555,0,1,1,1,'No Action')

DECLARE @columns AS NVARCHAR(MAX),
        @finalquery AS NVARCHAR(MAX);

SET @columns = STUFF((SELECT distinct ',' + QUOTENAME(QuoteStatus) FROM #Table1 FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')
--PRINT @columns

set @finalquery = '
        select  p.controlno,
                p.Bound,
                p.Declined,
                p.Rated,
                p.Quoted,' + @columns + '
        into ##A
        from ( select ControlNo, Bound, Declined, Rated, Quoted, QuoteStatus
                from #Table1
            )a
    pivot
    (
     COUNT(QuoteStatus)
     for QuoteStatus IN (' + @columns + ')
    )p '

exec(@finalquery)

--SELECT *
--FROM ##a

DECLARE @colsUnpivot AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)

select @colsUnpivot
  = stuff((select ','+quotename(C.name)
           FROM tempdb.sys.columns c
           WHERE c.object_id = OBJECT_ID('tempdb..##A')
           for xml path('')), 1, 1, '')
--PRINT @colsUnpivot

set @query
  = 'select ControlNo, Counts, Status
     from ##A
     unpivot
     (
        Counts
        for Status in ('+ @colsunpivot +')
     ) u'

exec sp_executesql @query;
</code>```

Output should look like this:

答:
I assume your sample output was that, a sample, and you excluded the other control numbers. If so, changing the where clause in your stuff will remove that column from the unpivot group, and give you desired results. You can't return a column that you are pivoting or unpivoting.

```<code>IF OBJECT_ID('tempdb..##A') IS NOT NULL DROP TABLE ##A
IF OBJECT_ID('tempdb..#table1') IS NOT NULL DROP TABLE #table1

Create table #Table1 ( ControlNo INT, Bound INT, Declined INT, Rated INT, Quoted INT, QuoteStatus VARCHAR(50) )

INSERT INTO #Table1 (ControlNo, Bound, Declined, Rated, Quoted, QuoteStatus)
    VALUES  (1111,1,0,1,1,'Lost'),
            (2222,0,1,0,1,'No Action'),
            (3333,1,1,0,0,NULL),
            (4444,1,0,0,1,'Lost'),
            (5555,0,1,1,1,'No Action')

DECLARE @columns AS NVARCHAR(MAX),
        @finalquery AS NVARCHAR(MAX);

SET @columns = STUFF((SELECT distinct ',' + QUOTENAME(QuoteStatus) FROM #Table1 FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')
--PRINT @columns

set @finalquery = '
        select  p.controlno,
                p.Bound,
                p.Declined,
                p.Rated,
                p.Quoted,' + @columns + '
        into ##A
        from ( select *
                from #Table1
            )a
    pivot
    (
     COUNT(QuoteStatus)
     for QuoteStatus IN (' + @columns + ')
    )p '

exec(@finalquery)

--SELECT *
--FROM ##a

DECLARE @colsUnpivot AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)

select @colsUnpivot
  = stuff((select ','+quotename(C.name)
           FROM tempdb.sys.columns c
           --notice i remove controlno here...
           WHERE c.object_id = OBJECT_ID('tempdb..##A') and c.name <> 'controlno'
           for xml path('')), 1, 1, '')
--PRINT @colsUnpivot

set @query
  = 'select  Controlno, Counts, Status
     from ##A
     unpivot
     (
        Counts
        for Status in ('+ @colsunpivot +')
     ) u'

exec sp_executesql @query;
</code>```

To get your exact output, then just add a where clause to the set @query.

```<code>set @query
  = 'select  Controlno, Counts, Status
     from ##A
     unpivot
     (
        Counts
        for Status in ('+ @colsunpivot +')
     ) u
     where controlno = 1111'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The goal is to dynamically pivot data and then dynamically unpivot it.

I am getting an error saying Invalid ControlNo

I am assuming its because variable @colsUnpivot contains ControlNo column.

But how can I fix it? I definitely need that ControlNo.

IF OBJECT_ID('tempdb..##A') IS NOT NULL DROP TABLE ##A
IF OBJECT_ID('tempdb..#table1') IS NOT NULL DROP TABLE #table1

Create table #Table1 ( ControlNo INT, Bound INT, Declined INT, Rated INT, Quoted INT, QuoteStatus VARCHAR(50) )

INSERT INTO #Table1 (ControlNo, Bound, Declined, Rated, Quoted, QuoteStatus)
    VALUES  (1111,1,0,1,1,'Lost'),
            (2222,0,1,0,1,'No Action'),
            (3333,1,1,0,0,NULL),
            (4444,1,0,0,1,'Lost'),
            (5555,0,1,1,1,'No Action')

DECLARE @columns AS NVARCHAR(MAX),
        @finalquery AS NVARCHAR(MAX);

SET @columns = STUFF((SELECT distinct ',' + QUOTENAME(QuoteStatus) FROM #Table1 FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')
--PRINT @columns

set @finalquery = '
        select  p.controlno,
                p.Bound,
                p.Declined,
                p.Rated,
                p.Quoted,' + @columns + '
        into ##A
        from ( select ControlNo, Bound, Declined, Rated, Quoted, QuoteStatus
                from #Table1
            )a
    pivot
    (
     COUNT(QuoteStatus)
     for QuoteStatus IN (' + @columns + ')
    )p '

exec(@finalquery)

--SELECT *
--FROM ##a

DECLARE @colsUnpivot AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)

select @colsUnpivot
  = stuff((select ','+quotename(C.name)
           FROM tempdb.sys.columns c
           WHERE c.object_id = OBJECT_ID('tempdb..##A')
           for xml path('')), 1, 1, '')
--PRINT @colsUnpivot

set @query
  = 'select ControlNo, Counts, Status
     from ##A
     unpivot
     (
        Counts
        for Status in ('+ @colsunpivot +')
     ) u'

exec sp_executesql @query;

Output should look like this:

Body:
I assume your sample output was that, a sample, and you excluded the other control numbers. If so, changing the where clause in your stuff will remove that column from the unpivot group, and give you desired results. You can't return a column that you are pivoting or unpivoting.

IF OBJECT_ID('tempdb..##A') IS NOT NULL DROP TABLE ##A
IF OBJECT_ID('tempdb..#table1') IS NOT NULL DROP TABLE #table1

Create table #Table1 ( ControlNo INT, Bound INT, Declined INT, Rated INT, Quoted INT, QuoteStatus VARCHAR(50) )

INSERT INTO #Table1 (ControlNo, Bound, Declined, Rated, Quoted, QuoteStatus)
    VALUES  (1111,1,0,1,1,'Lost'),
            (2222,0,1,0,1,'No Action'),
            (3333,1,1,0,0,NULL),
            (4444,1,0,0,1,'Lost'),
            (5555,0,1,1,1,'No Action')

DECLARE @columns AS NVARCHAR(MAX),
        @finalquery AS NVARCHAR(MAX);

SET @columns = STUFF((SELECT distinct ',' + QUOTENAME(QuoteStatus) FROM #Table1 FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')
--PRINT @columns

set @finalquery = '
        select  p.controlno,
                p.Bound,
                p.Declined,
                p.Rated,
                p.Quoted,' + @columns + '
        into ##A
        from ( select *
                from #Table1
            )a
    pivot
    (
     COUNT(QuoteStatus)
     for QuoteStatus IN (' + @columns + ')
    )p '

exec(@finalquery)

--SELECT *
--FROM ##a

DECLARE @colsUnpivot AS NVARCHAR(MAX),
        @query  AS NVARCHAR(MAX)

select @colsUnpivot
  = stuff((select ','+quotename(C.name)
           FROM tempdb.sys.columns c
           --notice i remove controlno here...
           WHERE c.object_id = OBJECT_ID('tempdb..##A') and c.name <> 'controlno'
           for xml path('')), 1, 1, '')
--PRINT @colsUnpivot

set @query
  = 'select  Controlno, Counts, Status
     from ##A
     unpivot
     (
        Counts
        for Status in ('+ @colsunpivot +')
     ) u'

exec sp_executesql @query;

To get your exact output, then just add a where clause to the set @query.

set @query
  = 'select  Controlno, Counts, Status
     from ##A
     unpivot
     (
        Counts
        for Status in ('+ @colsunpivot +')
     ) u
     where controlno = 1111'


问:
how to test a simple stack class using pytest
im trying to write a simple stack class to learn about TDD. but the problem is it fails to pass a test using the right code.

here is the code:

```<code>class Stack:
    def __init__(self):
        self.stack = []

    def push(self,new_item):
        self.stack.append(new_item)

    def pop(self):
        return int(self.stack.pop(0))
</code>```

and here is the test class:

```<code>import pytest
from Stack import Stack

def test_it_can_push():
    stack = Stack()
    stack.push(2)
    assert stack.stack is [2]
</code>```

and here is the error:

```<code>    def test_it_can_push():
        stack = Stack()
        stack.push(2)
>       assert stack.stack is [2]
E       assert [2] is [2]
E        +  where [2] = <Stack.Stack instance at 0x7f2273491560>.stack

test_stack.py:7: AssertionError
</code>```

can someone please, tell me how to fix this problem?

答:
You're doing the identity check (id -- memory location in CPython) using is, which will never be equal as the operands are two different lists (which are mutable objects), although they have the same elements, and you can check with id.

Do equity test:

```<code>assert stack.stack == [2]
</code>```

Body:
im trying to write a simple stack class to learn about TDD. but the problem is it fails to pass a test using the right code.

here is the code:

class Stack:
    def __init__(self):
        self.stack = []

    def push(self,new_item):
        self.stack.append(new_item)

    def pop(self):
        return int(self.stack.pop(0))

and here is the test class:

import pytest
from Stack import Stack

def test_it_can_push():
    stack = Stack()
    stack.push(2)
    assert stack.stack is [2]

and here is the error:

    def test_it_can_push():
        stack = Stack()
        stack.push(2)
>       assert stack.stack is [2]
E       assert [2] is [2]
E        +  where [2] = <Stack.Stack instance at 0x7f2273491560>.stack

test_stack.py:7: AssertionError

can someone please, tell me how to fix this problem?

Body:
You're doing the identity check (id -- memory location in CPython) using is, which will never be equal as the operands are two different lists (which are mutable objects), although they have the same elements, and you can check with id.

Do equity test:

assert stack.stack == [2]


问:
How to fix token issue with webchat
The bot framework api to generate a directline token results in a token that webchat cannot handle.

Recently I noticed the webchat on my website was not able to make a directline connection anymore. Using the directline secret results in a working webchat. Using the bot framework api to generate a very long token (816 characters) that webchat cannot handle (resulting in a message like unable to connect. This used to work just fine but now its broke (and nothing changed as far as I know)

I use some PHP to call the api and get a token:

```<code><?php
    $botSecret = 'DIRECLINE SECRET';
    $response = wp_remote_get( 'https://webchat.botframework.com/api/tokens',    array( 'headers' => 'Authorization: BotConnector ' . $botSecret ) );
if( is_array($response) ) {
  $header = $response['headers'];
  $token = $response['body'];
}
?>
<script type="text/javascript">
           var webChatToken = <?php echo $token; ?>;
       </script>
</code>```

And Html\Javascript to show the webchat client

```<code><html>
<body>
<div id="webchat" role="main"></div>
    <script src="https://cdn.botframework.com/botframework-webchat/latest/webchat.js"></script>
    <script>
       const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
         if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
           dispatch({
             type: 'WEB_CHAT/SEND_EVENT',
             payload: {
               name: 'webchat/join',
               value: { language: window.navigator.language }
             }
           });
         }
         return next(action);
       });
        window.WebChat.renderWebChat({
        directLine: window.WebChat.createDirectLine({ token: webChatToken }),
        store,
        styleOptions: {
        },
        userID: 'N/A',
        username: 'Web Chat User',
        locale: 'nl-NL'
      }, document.getElementById('webchat'));
    </script>
  </body>
</html>
</code>```

I would expect a shorter token or at least a token that can be used to use webchat

答:
The BotFramework Development Team just deployed an update that allows you to use a DirectLine secret with the Web Chat endpoint, so you can now use either a DirectLine or a WebChat secret to connect Web Chat to your bot.

```<code>const res = await fetch('https://webchat.botframework.com/api/tokens', {
    method: 'GET',
    headers: {
        Authorization: 'BotConnector <WEB_CHAT_SECRET | DIRECT_LINE_SECRET>'
    }
});

const token = await res.json();

window.WebChat.renderWebChat({
    directLine: window.WebChat.createDirectLine({ token })
}, document.getElementById('webchat'));
</code>```

Hope this helps!

Title: How to fix token issue with webchat

Body:
The bot framework api to generate a directline token results in a token that webchat cannot handle.

Recently I noticed the webchat on my website was not able to make a directline connection anymore. Using the directline secret results in a working webchat. Using the bot framework api to generate a very long token (816 characters) that webchat cannot handle (resulting in a message like unable to connect. This used to work just fine but now its broke (and nothing changed as far as I know)

I use some PHP to call the api and get a token:

<?php
    $botSecret = 'DIRECLINE SECRET';
    $response = wp_remote_get( 'https://webchat.botframework.com/api/tokens',    array( 'headers' => 'Authorization: BotConnector ' . $botSecret ) );
if( is_array($response) ) {
  $header = $response['headers'];
  $token = $response['body'];
}
?>

And Html\Javascript to show the webchat client

I would expect a shorter token or at least a token that can be used to use webchat

Body:
The BotFramework Development Team just deployed an update that allows you to use a DirectLine secret with the Web Chat endpoint, so you can now use either a DirectLine or a WebChat secret to connect Web Chat to your bot.

const res = await fetch('https://webchat.botframework.com/api/tokens', {
    method: 'GET',
    headers: {
        Authorization: 'BotConnector <WEB_CHAT_SECRET | DIRECT_LINE_SECRET>'
    }
});

const token = await res.json();

window.WebChat.renderWebChat({
    directLine: window.WebChat.createDirectLine({ token })
}, document.getElementById('webchat'));

Hope this helps!


问:
Created a fresh database, now running any artisan command throws an error about a missing table
I wanted a fresh development database so I could seed with new data, so I manually dropped and recreated my development database and now running any artisan commands throws an error. I continuously get an error saying that I'm missing a table.

```<code>In Connection.php line 647:

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mydatabase.stores'
  doesn't exist (SQL: select * from `stores`)

In PDOConnection.php line 63:

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mydatabase.stores'
  doesn't exist

In PDOConnection.php line 61:

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mydatabase.stores'
  doesn't exist
</code>```

I haven't run php artisan migrate:refresh in a long time so I'm not sure where the table stores is being used that's causing this error. Adding a -v flag doesn't provide any additional output to further trace the stack.

I've tried manually dropping the database and recreating it via the mysql. I've tried composer dump-autoload but that doesn't help either. I can't run php artisan migrate:install because calling ANY artisan command will throw the same error. Even calling php artisan throws the error. I've tried looking at my service providers to see if the table is being referenced in any of the constructors but I don't see it being used.

Is there anywhere in the code I should be checking for the use of this table? I'm not sure what is instantiated when php artisan is called.

The stores table is actually my first migration, so it's supposed to be the first thing created, but for some reason it's being called as a part of the artisan process.

答:
As mentioned by @aynber in the comment to my question, the problem was several of my commands in the app/Console/Commands/* directory were instantiating an object in its constructor that referenced the Store model in its parent constructor. Specifically, it was running the line

```<code>$this->storeId = Store::get()->last()->id;
</code>```

Commenting out this line allowed me to run my artisan commands.

Body:
I wanted a fresh development database so I could seed with new data, so I manually dropped and recreated my development database and now running any artisan commands throws an error. I continuously get an error saying that I'm missing a table.

In Connection.php line 647:

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mydatabase.stores'
  doesn't exist (SQL: select * from `stores`)

In PDOConnection.php line 63:

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mydatabase.stores'
  doesn't exist

In PDOConnection.php line 61:

  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'mydatabase.stores'
  doesn't exist

I haven't run php artisan migrate:refresh in a long time so I'm not sure where the table stores is being used that's causing this error. Adding a -v flag doesn't provide any additional output to further trace the stack.

I've tried manually dropping the database and recreating it via the mysql. I've tried composer dump-autoload but that doesn't help either. I can't run php artisan migrate:install because calling ANY artisan command will throw the same error. Even calling php artisan throws the error. I've tried looking at my service providers to see if the table is being referenced in any of the constructors but I don't see it being used.

Is there anywhere in the code I should be checking for the use of this table? I'm not sure what is instantiated when php artisan is called.

The stores table is actually my first migration, so it's supposed to be the first thing created, but for some reason it's being called as a part of the artisan process.

Body:
As mentioned by @aynber in the comment to my question, the problem was several of my commands in the app/Console/Commands/* directory were instantiating an object in its constructor that referenced the Store model in its parent constructor. Specifically, it was running the line

$this->storeId = Store::get()->last()->id;

Commenting out this line allowed me to run my artisan commands.


问:
How to trigger a late import of another module only when a certain object is needed from my module?

The Situation

I want to have a module that roughly works like the following:

```<code># my_module.py

my_number = 17

from other_module import foo
my_object = foo(23)
</code>```

However, there is a problem: Installing other_module causes problems for some users and is only required for those who want to use my_object – which in turn is only a small fraction of users. I want to spare those users who do not need my_object from installing other_module.

I therefore want the import of other_module to happen only if my_object is imported from my_module. With other words, the user should be able to run the following without having installed other_module:

```<code>from my_module import my_number
</code>```

My best solution so far

I could provide my_object via a function that contains the import:

```<code># in my_module.py

def get_my_object():
    from other_module import foo
    my_object = foo(23)
    return my_object
</code>```

The user would then have to do something like:

```<code>from my_module import get_my_object
my_object = get_my_object()
</code>```

Question

Is there a better way to conditionally trigger the import of other_module? I am mostly interested in keeping things as simple as possible for the users.

答:
Approach A – clean solution

Create a new separate module and have the user import the object from the other module. For example

```<code>from my_module import my_number # regular use
from my_module.extras import my_object # for a small part of the user base
</code>```

This means in your code you create a module folder my_module with an __init__.py where you import the usual stuff and don't import the extras submodule.

If you don't want to put extras in my_module (simpler), just create my_object in an individual extras.py module.

Approach B – signals bad architecture 99% of times

You can use importlib.import_module to dynamically import a module inside get_my_object without polluting the global space and that is cleaner than an import inside a function which creates side effects such as overriding your global variable with that import name (see this question and answers), however this is usually a sign of bad coding patterns on other part of the code.

Approach C – simple and effective

I usually tend to favour this simple pattern when there are users that might not have a library, as Python 3 discourages imports that are not at top level:

```<code>try:
    import other_module
    _HAS_OTHER_MODULE_ = True
except:
    _HAS_OTHER_MODULE_ = False

def get_my_object():
    assert _HAS_OTHER_MODULE_, "Please install other module"
    return other_module.foo(23)
</code>```

Body:
The Situation

I want to have a module that roughly works like the following:

# my_module.py

my_number = 17

from other_module import foo
my_object = foo(23)

However, there is a problem: Installing other_module causes problems for some users and is only required for those who want to use my_object – which in turn is only a small fraction of users. I want to spare those users who do not need my_object from installing other_module.

I therefore want the import of other_module to happen only if my_object is imported from my_module. With other words, the user should be able to run the following without having installed other_module:

from my_module import my_number

My best solution so far

I could provide my_object via a function that contains the import:

# in my_module.py

def get_my_object():
    from other_module import foo
    my_object = foo(23)
    return my_object

The user would then have to do something like:

from my_module import get_my_object
my_object = get_my_object()

Question

Is there a better way to conditionally trigger the import of other_module? I am mostly interested in keeping things as simple as possible for the users.

Body:
Approach A – clean solution

Create a new separate module and have the user import the object from the other module. For example

from my_module import my_number # regular use
from my_module.extras import my_object # for a small part of the user base

This means in your code you create a module folder my_module with an __init__.py where you import the usual stuff and don't import the extras submodule.

If you don't want to put extras in my_module (simpler), just create my_object in an individual extras.py module.

Approach B – signals bad architecture 99% of times

You can use importlib.import_module to dynamically import a module inside get_my_object without polluting the global space and that is cleaner than an import inside a function which creates side effects such as overriding your global variable with that import name (see this question and answers), however this is usually a sign of bad coding patterns on other part of the code.

Approach C – simple and effective

I usually tend to favour this simple pattern when there are users that might not have a library, as Python 3 discourages imports that are not at top level:

try:
    import other_module
    _HAS_OTHER_MODULE_ = True
except:
    _HAS_OTHER_MODULE_ = False

def get_my_object():
    assert _HAS_OTHER_MODULE_, "Please install other module"
    return other_module.foo(23)


问:
How to make Angular Universal and PWA work together?
I have a SSR Angular app which I am trying to transform into a PWA. I want it to be  server-side rendered for SEO and for the "fast first rendering" that it provides.

The PWA mode works fine when combined with SSR, but once the app is loaded, when we refresh it, the client index HTML file is loaded instead of the server-side rendered page.

I have dug into the code of ngsw-worker.js and I saw this:

// Next, check if this is a navigation request for a route. Detect circular
// navigations by checking if the request URL is the same as the index URL.
if (req.url !== this.manifest.index && this.isNavigationRequest(req)) {
    // This was a navigation request. Re-enter `handleFetch` with a request for
    // the URL.
    return this.handleFetch(this.adapter.newRequest(this.manifest.index), context);
}
```

I have no control over this file since it's from the framework and not exposed to developers.
Did anybody find a solution or workaround for this?

答:
Up-to-date answer (v11.0.0)

Angular now has a navigationRequestStrategy option which allows to prioritize server requests for navigation. Extract of the changelog:

service-worker: add the option to prefer network for navigation
requests (#38565) (a206852), closes #38194

To be used wisely! This warning appears in the documentation:

The freshness strategy usually results in more requests sent to the
server, which can increase response latency. It is recommended that
you use the default performance strategy whenever possible.

Old answer (for archaeological purposes)

I have found a working solution, the navigationUrls property of ngsw-config.json contains a list of navigation URLs included or excluded (with an exclamation mark) like explained in the documentation.

Then I configured it like this:

```<code>"navigationUrls": [
    "!/**"
]
</code>```

This way, none of the URLs redirect to index.html and the server-side rendered app comes into play when the app is first requested (or refreshed), whatever the URL is.

To go further, the three kinds of URLs managed by the service worker are:

Non-navigation URLs: static files cached by the service worker and listed in the generated ngsw.json file with their corresponding hashes

Navigation URLs: redirected to index.html by default, forwarded to the server if the "!/**" configuration is used

GET requests to the backend: forwarded to the backend

In order to distinguish a GET XMLHttpRequest from a navigation request, the service worker uses the Request.mode property and the Accept header that contains text/html when navigating and application/json, text/plain, */* when requesting the backend.

Edit: This is actually not a good practice to do that for two reasons:

Depending on the network quality, there is no guarantee that the server-side version will render faster than the cached browser version

It breaks the "update in background" mechanism. Indeed, the server-side rendered app will always refer to the latest versions of the JavaScript files

For more details on this, please take a look at the Angular's team member answer to my feature request: https://github.com/angular/angular/issues/30861

Body:
I have a SSR Angular app which I am trying to transform into a PWA. I want it to be  server-side rendered for SEO and for the "fast first rendering" that it provides.

The PWA mode works fine when combined with SSR, but once the app is loaded, when we refresh it, the client index HTML file is loaded instead of the server-side rendered page.

I have dug into the code of ngsw-worker.js and I saw this:

// Next, check if this is a navigation request for a route. Detect circular
// navigations by checking if the request URL is the same as the index URL.
if (req.url !== this.manifest.index && this.isNavigationRequest(req)) {
    // This was a navigation request. Re-enter `handleFetch` with a request for
    // the URL.
    return this.handleFetch(this.adapter.newRequest(this.manifest.index), context);
}

I have no control over this file since it's from the framework and not exposed to developers.
Did anybody find a solution or workaround for this?

Body:
Up-to-date answer (v11.0.0)

Angular now has a navigationRequestStrategy option which allows to prioritize server requests for navigation. Extract of the changelog:

service-worker: add the option to prefer network for navigation
requests (#38565) (a206852), closes #38194

To be used wisely! This warning appears in the documentation:

The freshness strategy usually results in more requests sent to the
server, which can increase response latency. It is recommended that
you use the default performance strategy whenever possible.

Old answer (for archaeological purposes)

I have found a working solution, the navigationUrls property of ngsw-config.json contains a list of navigation URLs included or excluded (with an exclamation mark) like explained in the documentation.

Then I configured it like this:

"navigationUrls": [
    "!/**"
]

This way, none of the URLs redirect to index.html and the server-side rendered app comes into play when the app is first requested (or refreshed), whatever the URL is.

To go further, the three kinds of URLs managed by the service worker are:

Non-navigation URLs: static files cached by the service worker and listed in the generated ngsw.json file with their corresponding hashes

Navigation URLs: redirected to index.html by default, forwarded to the server if the "!/**" configuration is used

GET requests to the backend: forwarded to the backend

In order to distinguish a GET XMLHttpRequest from a navigation request, the service worker uses the Request.mode property and the Accept header that contains text/html when navigating and application/json, text/plain, */* when requesting the backend.

Edit: This is actually not a good practice to do that for two reasons:

Depending on the network quality, there is no guarantee that the server-side version will render faster than the cached browser version

It breaks the "update in background" mechanism. Indeed, the server-side rendered app will always refer to the latest versions of the JavaScript files

For more details on this, please take a look at the Angular's team member answer to my feature request: https://github.com/angular/angular/issues/30861


问:
R: Replace last 3 zeroes with K in a column
I am trying to replace last 3 000 with K in a column in the dataframe

eg:

```<code>data <- data.frame(abc = c(1000, 100000, 450000))

abc <- 1000
then abc <- 1K

if
abc <- 100000
then abc <- 100K
</code>```

gsub or regex replaces the first 3 zeroes

I tried this:

```<code>lapply(data$abc, gsub, pattern = "000", replacement = "K", fixed = TRUE)
</code>```

Also, how can I make it work on an interval like :

```<code>data <- data.frame(abc = c("150000-250000", "100000-150000", "250000K+"))
</code>```

答:
An option is to use %/% with 1000 and paste the "K"

```<code>library(dplyr)
library(stringr)
data %>%
   mutate(abc = str_c(abc %/% 1000, "K"))
</code>```

Or using sub, match the 3 zeros at the end ($) of the string and replace with "K"

```<code>options(scipen = 999)
sub("0{3}$", "K", data$abc)
#[1] "1K"   "100K" "450K"
</code>```

If we have a different string with interval, then change the pattern to match 3 zeros at either at the end ($) or before a - and replace with "K"

```<code>gsub("0{3}(?=-|$)", "K", "150000-250000", perl = TRUE)
#[1] "150K-250K"
</code>```

Body:
I am trying to replace last 3 000 with K in a column in the dataframe

eg:

data <- data.frame(abc = c(1000, 100000, 450000))

abc <- 1000
then abc <- 1K

if
abc <- 100000
then abc <- 100K

gsub or regex replaces the first 3 zeroes

I tried this:

lapply(data$abc, gsub, pattern = "000", replacement = "K", fixed = TRUE)

Also, how can I make it work on an interval like :

data <- data.frame(abc = c("150000-250000", "100000-150000", "250000K+"))

Body:
An option is to use %/% with 1000 and paste the "K"

library(dplyr)
library(stringr)
data %>%
   mutate(abc = str_c(abc %/% 1000, "K"))

Or using sub, match the 3 zeros at the end ($) of the string and replace with "K"

options(scipen = 999)
sub("0{3}$", "K", data$abc)
#[1] "1K"   "100K" "450K"

If we have a different string with interval, then change the pattern to match 3 zeros at either at the end ($) or before a - and replace with "K"

gsub("0{3}(?=-|$)", "K", "150000-250000", perl = TRUE)
#[1] "150K-250K"


问:
get value from particular index in java?
in one big grid array(like 500 rows,500 columns), i want to get the value by using index as (150th row,200th column).The condition is , i should not us one dimensional array,2 dimensional,3 dimensional for retrieving that values.
i have no idea in hashmap?my colleague told to get the values from hashmap ?but i dont know
how to pass the index and get the value?plz help me anyone??????</p>

答:
I'm not sure I completly understand your sentence, but thing is, you can use a single index to access the positions using something like an hashmap, if you make sure the keys you use for placing the values are unique.

For the hashmap example you mention, you just have to imagine of putting all the elements of your matrix (grid) in a line, meaning that for position i, j,   in a single index x, it would be:

```<code> index x = (max_line_length*(i-1))+j
</code>```

where max_line_length = your_matrix.length

ContentLicense: CC BY-SA 3.0

Body:
I'm not sure I completly understand your sentence, but thing is, you can use a single index to access the positions using something like an hashmap, if you make sure the keys you use for placing the values are unique.

For the hashmap example you mention, you just have to imagine of putting all the elements of your matrix (grid) in a line, meaning that for position i, j,   in a single index x, it would be:

 index x = (max_line_length*(i-1))+j

where max_line_length = your_matrix.length


问:
How to limit memory usage in docker-compose?
Here is part of my docker-compose.yaml file

```<code>version: '3.4'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    working_dir: /app
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 23M
</code>```

Starting it docker-compose up -d

When I do docker stats it says that limit is still 1.9GiB. What am I doing wrong?

```<code>CONTAINER ID      NAME     CPU %     MEM USAGE / LIMIT     MEM %
13b6588evc1e      app_1    1.86%     20.45MiB / 1.952GiB   1.02%
</code>```

答:
Are you running the docker-compose in swarm mode ? If not Recommended to run 2.x version of compose file format.

3.X require docker-compose to be run in swarm mode for new set of resource directives to take effect.

Alternatives in 2.X are cpu_shares, cpu_quota, cpuset, mem_limit, memswap_limit, mem_swappiness

Body:
Here is part of my docker-compose.yaml file

version: '3.4'
services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    working_dir: /app
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 23M

Starting it docker-compose up -d

When I do docker stats it says that limit is still 1.9GiB. What am I doing wrong?

CONTAINER ID      NAME     CPU %     MEM USAGE / LIMIT     MEM %
13b6588evc1e      app_1    1.86%     20.45MiB / 1.952GiB   1.02%


问:
Having trouble constructing the correct Linq query syntax in c#.net for a join after join
I have troubles creating the correct query for a list of applications I have. I need to display them in a dashboard so consultants can handle the applications.
These applications can be uploaded by organisations or individuals.

Every consultant is 'owner' of a few organisations and individuals, in the dashboard they should only see the applications from individuals/organisations that they are also the 'owner' of.

The applications table:

```<code>Application
-----------
ID  |  requestIndividualID   |  requestOrganisationID | ...
</code>```

depending on who made the application the requesters ID will be saved in the table. So requestIndividualID or requestOrganisationID, one of them will be null, the other not.

The Individuals table:

```<code>Individual
----------
ID  |  name  |  ownerID
</code>```

Now comes the tricky part, the ownerID is not on the Organisation table, but on the OrganisationSegment table, something like this:

```<code>Organisation
------------
ID  |  name  |  city
</code>```

```<code>OrganisationSegment
-------------------
organisationID  |  ownerID
</code>```

The problem comes when I want to join the Organisation table with the OrganisationsSegment table, since it is possible that the organisationID is null.

Currently I have this code that is throwing errors:

```<code> var applications = from pa in _context.Applications

                 join individu in _context.Individu on pa.requestIndividualID equals individu.ID into IndividuResultList
                 from individu in IndividuResultList.DefaultIfEmpty()

                 join organisation in _context.Organisations on pa.requestOrganisationID equals organisation.ID into organisationsList
                 from organisation in organisationsList

                 join organisationSegment in _context.OrganisationSegment on organisation.ID equals organisationSegment.OrganisationId into organisationSegmentList
                 from organisationSegment in organisationSegmentList.DefaultIfEmpty()

                 select new {Data = new {PortalApplications = pa, individu, organisation, organisationSegment}};

</code>```

After this code I use the result to make a list where I can apply the filter for the owner Id.

When I execute this code, it throws System.InvalidOperationException : Nullable object must have a value. error.

My current solution is making 2 results, one for all the application that have a requestIndividualID and one for all the applications with a requestOrganisationID.

Then I apply the filter (the specific ownerID) to these 2 separate results, and adding the results in a list, since the results came from the same table, thats really easy.
But imo this is a quicky and dirty way of handling it.
I want the correct and clean answer.

Can somebody please help me?
Also i have trouble finding any help on the internet for this, so if you found some info, please link it as well, or tell me how to improve my google skills for issues like this (correct naming of the issue).

答:
I believe this is easier if you join the Orginisation and OrginisationSegment tables first, assuming every Orginisation has an ownerID in OrginisationSegment.

```<code>var OrganisationsWithOwner = from o in _context.Organisations
                             join os in _context.OrganisationSegment on o.ID equals os.OrganisationId
                             join i in _context.Individu on os.OwnerID equals i.ID
                             select new { o, i };
</code>```

Now you can join with Individu and the new OrginisationWithOwner and return the one that has a match.

```<code>var applications = from pa in _context.Applications

                   join indOwner in _context.Individu on pa.requestIndividualID equals indOwner.ID into IndividuResultList
                   from indOwner in IndividuResultList.DefaultIfEmpty()

                   join o in OrganisationsWithOwner on pa.requestOrganisationID equals o.o.ID into organisationsList
                   from o in organisationsList.DefaultIfEmpty()

                   select new { PortalApplications = pa, owner = (indOwner != null ? indOwner : o.i), organisation = o.o };
</code>```

Body:
I have troubles creating the correct query for a list of applications I have. I need to display them in a dashboard so consultants can handle the applications.
These applications can be uploaded by organisations or individuals.

Every consultant is 'owner' of a few organisations and individuals, in the dashboard they should only see the applications from individuals/organisations that they are also the 'owner' of.

The applications table:

Application
-----------
ID  |  requestIndividualID   |  requestOrganisationID | ...

depending on who made the application the requesters ID will be saved in the table. So requestIndividualID or requestOrganisationID, one of them will be null, the other not.

The Individuals table:

Individual
----------
ID  |  name  |  ownerID

Now comes the tricky part, the ownerID is not on the Organisation table, but on the OrganisationSegment table, something like this:

Organisation
------------
ID  |  name  |  city

OrganisationSegment
-------------------
organisationID  |  ownerID

The problem comes when I want to join the Organisation table with the OrganisationsSegment table, since it is possible that the organisationID is null.

Currently I have this code that is throwing errors:

 var applications = from pa in _context.Applications

                 join individu in _context.Individu on pa.requestIndividualID equals individu.ID into IndividuResultList
                 from individu in IndividuResultList.DefaultIfEmpty()

                 join organisation in _context.Organisations on pa.requestOrganisationID equals organisation.ID into organisationsList
                 from organisation in organisationsList

                 join organisationSegment in _context.OrganisationSegment on organisation.ID equals organisationSegment.OrganisationId into organisationSegmentList
                 from organisationSegment in organisationSegmentList.DefaultIfEmpty()

                 select new {Data = new {PortalApplications = pa, individu, organisation, organisationSegment}};

After this code I use the result to make a list where I can apply the filter for the owner Id.

When I execute this code, it throws System.InvalidOperationException : Nullable object must have a value. error.

My current solution is making 2 results, one for all the application that have a requestIndividualID and one for all the applications with a requestOrganisationID.

Then I apply the filter (the specific ownerID) to these 2 separate results, and adding the results in a list, since the results came from the same table, thats really easy.
But imo this is a quicky and dirty way of handling it.
I want the correct and clean answer.

Can somebody please help me?
Also i have trouble finding any help on the internet for this, so if you found some info, please link it as well, or tell me how to improve my google skills for issues like this (correct naming of the issue).

Body:
I believe this is easier if you join the Orginisation and OrginisationSegment tables first, assuming every Orginisation has an ownerID in OrginisationSegment.

var OrganisationsWithOwner = from o in _context.Organisations
                             join os in _context.OrganisationSegment on o.ID equals os.OrganisationId
                             join i in _context.Individu on os.OwnerID equals i.ID
                             select new { o, i };

Now you can join with Individu and the new OrginisationWithOwner and return the one that has a match.

var applications = from pa in _context.Applications

                   join indOwner in _context.Individu on pa.requestIndividualID equals indOwner.ID into IndividuResultList
                   from indOwner in IndividuResultList.DefaultIfEmpty()

                   join o in OrganisationsWithOwner on pa.requestOrganisationID equals o.o.ID into organisationsList
                   from o in organisationsList.DefaultIfEmpty()

                   select new { PortalApplications = pa, owner = (indOwner != null ? indOwner : o.i), organisation = o.o };


问:
WF4 - Argument types limited to .NET types only?
I'm trying to set a workflow argument to a custom type 'Contact' class but no matter what I try it just won't find it in the explorer. The only things I see under my namespace are the 2 names of my xaml files, App & MainWindow1

What gives? I want to pass in a Contact object and use the workflow to check a few different items then return true/false.

答: Make your models public, kthx.</p>

Body: Make your models public, kthx.


问:
Job queue with job affinity
I am currently facing a problem for which I am pretty sure there is an official name, but I don't know what to search the web for. I hope that if I describe the problem and the solution I have in mind, somebody is able to tell me the name of the design pattern (if there is one that matches what I am going to describe).

Basically, what I want to have is a job queue: I have multiple clients that create jobs (publishers), and a number of workers that process these jobs (consumers). Now I want to distribute the jobs created by the publishers to the various consumers, which is basically doable using almost any message queue with load balancing across a queue, e.g. using RabbitMQ or even MQTT 5.

However, now things get complicated... every job refers to an external entity, let's say a user. What I want is that the jobs for a single user get processed in order, but for multiple users in parallel. I do not have the requirement that the jobs for user X always go to worker Y, since they should be processed sequentially anyway.

Now I could solve this using RabbitMQ and its consistent hashing exchange, but then I have a data race when new workers enter the cluster, because RabbitMQ does not support re-locating the jobs that are already in a queue.

MQTT 5 does not support this either: Here this idea is known as "sticky shared subscriptions", but this is not official. It may be part of MQTT 6, or it may not. Who knows.

I have also taken a look at NSQ, NATS, and some other brokers. Most of them don't even support this very specific scenario, and those that do use consistent hashing, which has the previously mentioned data racing problem.

Now, the problem would be gone if the broker would not sort the jobs into queues, once the jobs arrive, but if it would track if a job for a specific user is already being processed: If so, it should delay all other jobs for this user, but all jobs for other users should still process. This is, AFAICS, not possible using RabbitMQ et al.

I am pretty sure that I am not the only person with a use case for that. I could e.g. think of users uploading videos to a video platform, and although uploaded videos are processed in parallel, all the videos uploaded by a single user are processed sequentially.

So, to cut a long story short: Is what I describe known under a common name? Something such as distributed job queue? Task dispatcher with task affinity? Or anything else? I have tried lots of terms, but didn't succeed. This may mean that there is no solution for this, but as said, it's hard to imagine that I'm the only person on the planet with this problem.

Any ideas what I could look for? And: Are there any tools that implement this? Any protocols?

PS: Just using a predefined routing key is not an option, since the user ids (which I just used as a made-up example here) are basically UUIDs, so there can be billions of it, so I need something more dynamic. Hence, consistent hashing is basically the correct approach, but as said, the distribution has to work piece by piece, not upfront, to avoid data races.

答:
If I'm understanding your scenario correctly, I believe the feature you are describing is pretty similar to how Message Sessions work in Azure Service Bus.

You'd basically set the SessionId property of the message to the UserId before pushing them into a queue.

Each consumer will lock onto a session processing messages one after the other and these messages would belong to the same user. Once done, the consumer could just move on to the next available session.

Also, Azure Functions has recently released Service Bus Sessions support which is in preview but allows you to achieve all this with very little effort.

Unfortunately, I'm not familiar enough to know if this feature exists in one of the open source alternates but I hope this helps.

Title: Job queue with job affinity


问:
I use intent to start an another appliaction's activity class why i fail?
In frist appliaction ,i want use intent to lunach another application's activity class ,and this class is belong another application! them are not in same application. i dont have and not know second application's activity 's  action and other value in it's AndroidManifits.xml .

how i fix it? i remember this code could run a week ago ,now it can't...

help

these code could run before some days ago ,but now it can't, because second application had update?, but his class name,package name never changed!

```<code>public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
        ComponentName apk2Component1 =
                new ComponentName(the second appliaction's package name, the second appliaction's activity class name);
        Intent mIntent = new Intent();
        mIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        mIntent.setComponent(apk2Component1);
        startActivity(mIntent);
    }
}
</code>```

```<code><application
    android:icon="@mipmap/ic_launcher"
    android:label="d"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

```<code>java.lang.SecurityException: Permission Denial: starting Intent { cat=[android.intent.category.LAUNCHER] cmp=com.chinarainbow.tft/.mvp.ui.activity.TFTQRActivity } from ProcessRecord{8525c14 17370:com.dqj.tianfu/u0a802} (pid=17370, uid=10802) not exported from uid 10005
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2931)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1620)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:6701)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:249)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
        at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:108)
     Caused by: java.lang.SecurityException: Permission Denial: starting Intent { cat=[android.intent.category.LAUNCHER] cmp=class name } from ProcessRecord{8525c14 17370:com.dqj.tianfu/u0a802} (pid=17370, uid=10802) not exported from uid 10005
        at android.os.Parcel.readException(Parcel.java:1954)
        at android.os.Parcel.readException(Parcel.java:1900)
        at android.app.IActivityManager$Stub$Proxy.startActivity(IActivityManager.java:4465)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1616)
        at android.app.Activity.startActivityForResult(Activity.java:4536)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
        at android.app.Activity.startActivityForResult(Activity.java:4494)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
        at android.app.Activity.startActivity(Activity.java:4855)
        at android.app.Activity.startActivity(Activity.java:4823)
        at com.dqj.tianfu.MainActivity.onCreate(MainActivity.java:20)
        at android.app.Activity.performCreate(Activity.java:7050)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2809)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2931)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1620)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:6701)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:249)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
        at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:108)
</code>```

答:
it's possible the app you're launching has disabled the exported flag, which controls whether other apps can launch it. You may want to set that flag to true in the app you're launching:

```<code><service
    android:exported="true"
/>
</code>```

https://developer.android.com/guide/topics/manifest/service-element#exported

Body:
In frist appliaction ,i want use intent to lunach another application's activity class ,and this class is belong another application! them are not in same application. i dont have and not know second application's activity 's  action and other value in it's AndroidManifits.xml .

how i fix it? i remember this code could run a week ago ,now it can't...

help

these code could run before some days ago ,but now it can't, because second application had update?, but his class name,package name never changed!

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
        ComponentName apk2Component1 =
                new ComponentName(the second appliaction's package name, the second appliaction's activity class name);
        Intent mIntent = new Intent();
        mIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        mIntent.setComponent(apk2Component1);
        startActivity(mIntent);
    }
}

<application
    android:icon="@mipmap/ic_launcher"
    android:label="d"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

java.lang.SecurityException: Permission Denial: starting Intent { cat=[android.intent.category.LAUNCHER] cmp=com.chinarainbow.tft/.mvp.ui.activity.TFTQRActivity } from ProcessRecord{8525c14 17370:com.dqj.tianfu/u0a802} (pid=17370, uid=10802) not exported from uid 10005
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2856)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2931)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1620)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:6701)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:249)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
        at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:108)
     Caused by: java.lang.SecurityException: Permission Denial: starting Intent { cat=[android.intent.category.LAUNCHER] cmp=class name } from ProcessRecord{8525c14 17370:com.dqj.tianfu/u0a802} (pid=17370, uid=10802) not exported from uid 10005
        at android.os.Parcel.readException(Parcel.java:1954)
        at android.os.Parcel.readException(Parcel.java:1900)
        at android.app.IActivityManager$Stub$Proxy.startActivity(IActivityManager.java:4465)
        at android.app.Instrumentation.execStartActivity(Instrumentation.java:1616)
        at android.app.Activity.startActivityForResult(Activity.java:4536)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:767)
        at android.app.Activity.startActivityForResult(Activity.java:4494)
        at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:754)
        at android.app.Activity.startActivity(Activity.java:4855)
        at android.app.Activity.startActivity(Activity.java:4823)
        at com.dqj.tianfu.MainActivity.onCreate(MainActivity.java:20)
        at android.app.Activity.performCreate(Activity.java:7050)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2809)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2931)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1620)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:176)
        at android.app.ActivityThread.main(ActivityThread.java:6701)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:249)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
        at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:108)

Body:
it's possible the app you're launching has disabled the exported flag, which controls whether other apps can launch it. You may want to set that flag to true in the app you're launching:

<service
    android:exported="true"
/>

https://developer.android.com/guide/topics/manifest/service-element#exported


问:
Why does python round(np.float16(np.pi),5) return infinity? Bug, limitation, or expected?
I have a Python 3 function rounding floats to 6 digits (the logic handles various precision levels).  When passed with many (possibly all) numpy.float16 values it generates multiply-overflow warnings and returns infinity.

The short snippet in the question title or shown below illustrates the behavior.

The workaround is easy, just convert to larger floats first, but I'm curious whether the behavior is expected.

import numpy as np
x = np.float16(3.14)
x = round(x, 5)
if np.isinf(x):
    print("you've made an infinity through rounding....", 1, x)
else:
    print('just x: ', x)
```

I expect round to affect precision, but never cause an overflow or change a value into infinity.

答:
This is a limitation of NumPy's round algorithm. I hesitate to call it a bug: that's for the NumPy core developers to decide, but it may be worth reporting nevertheless.

Here's the problem: to round to 5 decimal places, NumPy does the equivalent of scaling by 100000.0, rounding to the nearest integer, then diving by 100000.0 again. That initial scaling can potentially overflow, even when the final result of the round operation would be expected to be within range.

Here's the portion of the NumPy source where this is implemented. You need to backtrack a bit in the source to figure out that in this case op1 is multiplication and op2 refers to division.

With float64 or float32 this would be unlikely to cause issues, because for normal uses you're unlikely to be within 100000.0 of the upper bound of the representable range of the floating-point type. But if you do get too close to that upper bound, you'll see the same problem. Here's an example with np.float64:

```<code>>>> np.finfo(np.float64).max
1.7976931348623157e+308
>>> x = np.float64(1e304)  # pick something within 1e5 of that max
>>> x * 1e5
__main__:1: RuntimeWarning: overflow encountered in double_scalars
inf
>>> np.round(x, 5)  # same multiplication happening internally
/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numpy/core/fromnumeric.py:56: RuntimeWarning: overflow encountered in multiply
  return getattr(obj, method)(*args, **kwds)
inf
</code>```

And here's the same thing with float32:

```<code>>>> np.finfo(np.float32).max
3.4028235e+38
>>> x = np.float32(1e35)
>>> x * 1e5  # okay; NumPy converts to `float64`
1.0000000409184788e+40
>>> np.round(x, 5)
inf
</code>```

With np.float16, it's exactly the same issue, but since the dynamic range of the float16 type is so small, you're much more likely to observe the issue in practice.

In general, though, note that even if this were fixed, it is possible for two-argument round to overflow: it's possible that the original value is within the range of the relevant floating-point type, while the rounded value is not. Here's an example with Python's own round function:

```<code>>>> x = 1.76e308
>>> x
1.76e+308
>>> round(x, -307)  # should be 1.8e308, but that's out of range
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: rounded value too large to represent
</code>```

But this can only happen for a negative ndigits argument. If the second argument were nonnegative, then there's no possibility of overflow - every sufficiently large representable value in any of the standard floating-point types is already integral, so a round with a nonnegative ndigits shouldn't change its value.

Body:
I have a Python 3 function rounding floats to 6 digits (the logic handles various precision levels).  When passed with many (possibly all) numpy.float16 values it generates multiply-overflow warnings and returns infinity.

The short snippet in the question title or shown below illustrates the behavior.

The workaround is easy, just convert to larger floats first, but I'm curious whether the behavior is expected.

import numpy as np
x = np.float16(3.14)
x = round(x, 5)
if np.isinf(x):
    print("you've made an infinity through rounding....", 1, x)
else:
    print('just x: ', x)

I expect round to affect precision, but never cause an overflow or change a value into infinity.

Body:
This is a limitation of NumPy's round algorithm. I hesitate to call it a bug: that's for the NumPy core developers to decide, but it may be worth reporting nevertheless.

Here's the problem: to round to 5 decimal places, NumPy does the equivalent of scaling by 100000.0, rounding to the nearest integer, then diving by 100000.0 again. That initial scaling can potentially overflow, even when the final result of the round operation would be expected to be within range.

Here's the portion of the NumPy source where this is implemented. You need to backtrack a bit in the source to figure out that in this case op1 is multiplication and op2 refers to division.

With float64 or float32 this would be unlikely to cause issues, because for normal uses you're unlikely to be within 100000.0 of the upper bound of the representable range of the floating-point type. But if you do get too close to that upper bound, you'll see the same problem. Here's an example with np.float64:

>>> np.finfo(np.float64).max
1.7976931348623157e+308
>>> x = np.float64(1e304)  # pick something within 1e5 of that max
>>> x * 1e5
__main__:1: RuntimeWarning: overflow encountered in double_scalars
inf
>>> np.round(x, 5)  # same multiplication happening internally
/opt/local/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/numpy/core/fromnumeric.py:56: RuntimeWarning: overflow encountered in multiply
  return getattr(obj, method)(*args, **kwds)
inf

And here's the same thing with float32:

>>> np.finfo(np.float32).max
3.4028235e+38
>>> x = np.float32(1e35)
>>> x * 1e5  # okay; NumPy converts to `float64`
1.0000000409184788e+40
>>> np.round(x, 5)
inf

With np.float16, it's exactly the same issue, but since the dynamic range of the float16 type is so small, you're much more likely to observe the issue in practice.

In general, though, note that even if this were fixed, it is possible for two-argument round to overflow: it's possible that the original value is within the range of the relevant floating-point type, while the rounded value is not. Here's an example with Python's own round function:

>>> x = 1.76e308
>>> x
1.76e+308
>>> round(x, -307)  # should be 1.8e308, but that's out of range
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: rounded value too large to represent

But this can only happen for a negative ndigits argument. If the second argument were nonnegative, then there's no possibility of overflow - every sufficiently large representable value in any of the standard floating-point types is already integral, so a round with a nonnegative ndigits shouldn't change its value.


问:
Async to wait for a key in F#?
I would like to block async execution until the users presses any key in the console.

Here is what I have come up with:

```<code>let waitForAnyKey = async {
  do!
    new Task (fun () ->
      printfn "%s" "waiting for a key"
      Console.ReadKey () |> ignore
      printfn "%s" "got a key"
    )
    |> Async.AwaitTask
}
</code>```

Used like this:

```<code>async {
  printfn "%s" "Press any key... "
  do! waitForAnyKey
  printfn "%s" "You pressed a key. "
}
</code>```

However, the Task is never run.

How should I write this in F#?

Can I avoid creating a Task for this entirely?

答:
The Task constructor creates a new Task but does not start it. Using Task.Run instead should fix the problem:

```<code>let waitForAnyKey = async {
  do!
    Task.Run (fun () ->
      printfn "%s" "waiting for a key"
      Console.ReadKey () |> ignore
      printfn "%s" "got a key"
    )
    |> Async.AwaitTask
}
</code>```

Console.ReadKey does not currently have an equivalent that returns a Task (which surprised me), although the idea has been suggested.

Title: Async to wait for a key in F#?

Body:
I would like to block async execution until the users presses any key in the console.

Here is what I have come up with:

let waitForAnyKey = async {
  do!
    new Task (fun () ->
      printfn "%s" "waiting for a key"
      Console.ReadKey () |> ignore
      printfn "%s" "got a key"
    )
    |> Async.AwaitTask
}

Used like this:

async {
  printfn "%s" "Press any key... "
  do! waitForAnyKey
  printfn "%s" "You pressed a key. "
}

However, the Task is never run.

How should I write this in F#?

Can I avoid creating a Task for this entirely?

Body:
The Task constructor creates a new Task but does not start it. Using Task.Run instead should fix the problem:

let waitForAnyKey = async {
  do!
    Task.Run (fun () ->
      printfn "%s" "waiting for a key"
      Console.ReadKey () |> ignore
      printfn "%s" "got a key"
    )
    |> Async.AwaitTask
}

Console.ReadKey does not currently have an equivalent that returns a Task (which surprised me), although the idea has been suggested.


问:
Something horribly wrong with my js code, anyone can help me debug?
I'm trying to write this tool, to animate a game map from a range of dates. The flow is like this:

1st: choose game world

2nd: set map display parameters (date range, map type and animation speed)

3rd: the js code grab png file according to the dates and display them one by one according to the animation speed

The problem I'm having is this:
if you just click on one world, and click animate, everything is fine, the animation displays correctly. Then if you choose another world (without refreshing the page), the animation either flickers or somehow displaying image from other worlds. and I can't figure out what's causing this (I'm totally n00b at js)

```<code>$(function(){
        $("#image_area").hide();
        $("#tw_image").hide();
        $('#W40').click(function(){
            $("#tw_image").hide();
            show_image_area('40');
        });

        $('#W42').click(function(){
            $("#tw_image").hide();
            show_image_area('42');
        });

        $('#W56').click(function(){
            $("#tw_image").hide();
            show_image_area('56');
        });
    });

    function show_image_area(world){
        $("#tw_image").hide();
        if(world == "40" || world == "42" || world == "56"){
            $("#map_notice").remove();
            $("#image_area").prepend('<div id="map_notice">Map for W'+world+' available from <span id="date_highlight">April 7th 2011</span>, all previous dates invalid and will not have map available</div>');
        }
        $("#date_from").datepicker({ showAnim: 'blind' });
        $("#date_to").datepicker({ showAnim: 'blind' });
        $('#image_area').show();
        $("#animate").click(function(){
            $("#tw_image").hide();
            var date_from = $("#date_from").val();
            var date_to = $("#date_to").val();
            if(!(date_from && date_to)){
                alert("From and To dates required.")
                return false;
            }
            var map_type = $("#map_type").val();
            var speed = $("#speed").val();
            var days = daydiff(parseDate(date_from), parseDate(date_to));
            var date_one = new Date(Date.parse(date_from));
            var b = date_one.toISOString().split("T")[0].split("-");
            var c = get_map_type(map_type) + b[0] + b[1] + b[2];
            var width = get_map_type_width(map_type);
            var img_load = "" + world + "/" + c + ".png";
            $('#image_area').load(img_load, function(){
                $("#tw_image").attr("width", width);
                $("#tw_image").attr("src", img_load);
                $("#tw_image").show();
                $("#debug").html("world = "+world);
            });

            var i = 0;
            var interval = setInterval(
            function(){
                date_one.setDate(date_one.getDate() + 1);
                b = date_one.toISOString().split("T")[0].split("-");
                c = get_map_type(map_type) + b[0] + b[1] + b[2];
                var src_one = "" + world + "/"+c+".png";
                var img = new Image();
                img.src = src_one;
                img.onload = function(){
                    $("#tw_image").attr("src", img.src);
                    $("#debug").html("world = "+world);
                }
                i++;
                if(i >= days) clearInterval(interval);
            },speed);

        });
    }

    function get_map_type(map_type){
        if(map_type == "topk"){
            return "topktribes";
        }
        if(map_type == "toptribe"){
            return "toptribes";
        }
        if(map_type == "topnoble"){
            return "topnoblers";
        }
    }

    function get_map_type_width(map_type){
        if(map_type == "topk"){
            return 1000;
        }
        if(map_type == "toptribe"){
            return 1300;
        }
        if(map_type == "topnoble"){
            return 1300;
        }
    }

    function parseDate(str) {
        var mdy = str.split('/');
        return new Date(mdy[2], mdy[0]-1, mdy[1]);
    }

    function daydiff(first, second) {
        return (second-first)/(1000*60*60*24)
    }
</code>```

答:
Ok I think I have a solution here although its not what I thought it was going to be.  Basically every time you are calling image_area_world you are creating a new click handler on the animate button.  Due to the way JavaScript scope works the World variable is kept the same for that click handler at the point of creation.

Anyway to solve this problem what you can try is this just before you define your click handler.

```<code>$("#animate").unbind("click");
$("#animate").click(function () { *code* }
</code>```

A couple of tools to help you out.

Visual Event

Firebug

Also a bit explaining how JavaScript Scope and Closures work

Body:
I'm trying to write this tool, to animate a game map from a range of dates. The flow is like this:

1st: choose game world

2nd: set map display parameters (date range, map type and animation speed)

3rd: the js code grab png file according to the dates and display them one by one according to the animation speed

The problem I'm having is this:
if you just click on one world, and click animate, everything is fine, the animation displays correctly. Then if you choose another world (without refreshing the page), the animation either flickers or somehow displaying image from other worlds. and I can't figure out what's causing this (I'm totally n00b at js)

$(function(){
        $("#image_area").hide();
        $("#tw_image").hide();
        $('#W40').click(function(){
            $("#tw_image").hide();
            show_image_area('40');
        });

        $('#W42').click(function(){
            $("#tw_image").hide();
            show_image_area('42');
        });

        $('#W56').click(function(){
            $("#tw_image").hide();
            show_image_area('56');
        });
    });

    function show_image_area(world){
        $("#tw_image").hide();
        if(world == "40" || world == "42" || world == "56"){
            $("#map_notice").remove();
            $("#image_area").prepend('
Map for W'+world+' available from April 7th 2011, all previous dates invalid and will not have map available
');
        }
        $("#date_from").datepicker({ showAnim: 'blind' });
        $("#date_to").datepicker({ showAnim: 'blind' });
        $('#image_area').show();
        $("#animate").click(function(){
            $("#tw_image").hide();
            var date_from = $("#date_from").val();
            var date_to = $("#date_to").val();
            if(!(date_from && date_to)){
                alert("From and To dates required.")
                return false;
            }
            var map_type = $("#map_type").val();
            var speed = $("#speed").val();
            var days = daydiff(parseDate(date_from), parseDate(date_to));
            var date_one = new Date(Date.parse(date_from));
            var b = date_one.toISOString().split("T")[0].split("-");
            var c = get_map_type(map_type) + b[0] + b[1] + b[2];
            var width = get_map_type_width(map_type);
            var img_load = "" + world + "/" + c + ".png";
            $('#image_area').load(img_load, function(){
                $("#tw_image").attr("width", width);
                $("#tw_image").attr("src", img_load);
                $("#tw_image").show();
                $("#debug").html("world = "+world);
            });

            var i = 0;
            var interval = setInterval(
            function(){
                date_one.setDate(date_one.getDate() + 1);
                b = date_one.toISOString().split("T")[0].split("-");
                c = get_map_type(map_type) + b[0] + b[1] + b[2];
                var src_one = "" + world + "/"+c+".png";
                var img = new Image();
                img.src = src_one;
                img.onload = function(){
                    $("#tw_image").attr("src", img.src);
                    $("#debug").html("world = "+world);
                }
                i++;
                if(i >= days) clearInterval(interval);
            },speed);

        });
    }

    function get_map_type(map_type){
        if(map_type == "topk"){
            return "topktribes";
        }
        if(map_type == "toptribe"){
            return "toptribes";
        }
        if(map_type == "topnoble"){
            return "topnoblers";
        }
    }

    function get_map_type_width(map_type){
        if(map_type == "topk"){
            return 1000;
        }
        if(map_type == "toptribe"){
            return 1300;
        }
        if(map_type == "topnoble"){
            return 1300;
        }
    }

    function parseDate(str) {
        var mdy = str.split('/');
        return new Date(mdy[2], mdy[0]-1, mdy[1]);
    }

    function daydiff(first, second) {
        return (second-first)/(1000*60*60*24)
    }

Body:
Ok I think I have a solution here although its not what I thought it was going to be.  Basically every time you are calling image_area_world you are creating a new click handler on the animate button.  Due to the way JavaScript scope works the World variable is kept the same for that click handler at the point of creation.

Anyway to solve this problem what you can try is this just before you define your click handler.

$("#animate").unbind("click");
$("#animate").click(function () { *code* }

A couple of tools to help you out.

Visual Event

Firebug

Also a bit explaining how JavaScript Scope and Closures work


问:
How to display and filter this array for angular/typescript app?
I'm wanting to group and display the data by BreakdownPalletID in the array below. I'm using typescript/angular and wanting to show this data grouped by Breakdown Pallet ID and then for each show the list of LPs and Skus for each one but i'm not sure how to do that with the JSON object the way it is below. The number of breakdownPalletIDs is also dynamic</p>

```<code> {
        "palletCount": 4,
        "lpCount": 6,
        "Sku": [
            {
                "sku": 394211,
                "lp": "00006844763464291206",
                "breakdownPalletID": 4,
                "customerMessages": ["DO NOT STACK", "DO NOT DO THAT"]

            },
            {
                "sku": 395299,
                "lp": "00006844763464289555",
                "breakdownPalletID": 1,
                "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 460957,
                "lp": "00006844763464289555",
                "breakdownPalletID": 4,
                    "customerMessages": ["DO NOT STACK", "DO NOT DO THAT"]
            },
            {
                "sku": 460957,
                "lp": "00006844763464291039",
                "breakdownPalletID": 2,
                "customerMessages": ["MESSAGE 1","MESSAGE 2","MESSAGE 3"]
            },
            {
                "sku": 461716,
                "lp": "00006844763464291336",
                "breakdownPalletID": 1,
                "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 506733,
                "lp": "00006844763464289555",
                "breakdownPalletID": 1,
            "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 519795,
                "lp": "00006844763464291206",
                "breakdownPalletID": 3,
                "customerMessages": ["MESSAGE 5","MESSAGE 6","MESSAGE 7"]

            }
            ]
    }
</code>```

答:
You can try something like this.

```<code>  groupBy(origArray: any[], key: string) {
    return origArray.reduce(function (rv, x) {
      (rv[x[key]] = rv[x[key]] || []).push(x);
      return rv;
    }, {});
  }
</code>```

See demo

Body:
I'm wanting to group and display the data by BreakdownPalletID in the array below. I'm using typescript/angular and wanting to show this data grouped by Breakdown Pallet ID and then for each show the list of LPs and Skus for each one but i'm not sure how to do that with the JSON object the way it is below. The number of breakdownPalletIDs is also dynamic

 {
        "palletCount": 4,
        "lpCount": 6,
        "Sku": [
            {
                "sku": 394211,
                "lp": "00006844763464291206",
                "breakdownPalletID": 4,
                "customerMessages": ["DO NOT STACK", "DO NOT DO THAT"]

            },
            {
                "sku": 395299,
                "lp": "00006844763464289555",
                "breakdownPalletID": 1,
                "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 460957,
                "lp": "00006844763464289555",
                "breakdownPalletID": 4,
                    "customerMessages": ["DO NOT STACK", "DO NOT DO THAT"]
            },
            {
                "sku": 460957,
                "lp": "00006844763464291039",
                "breakdownPalletID": 2,
                "customerMessages": ["MESSAGE 1","MESSAGE 2","MESSAGE 3"]
            },
            {
                "sku": 461716,
                "lp": "00006844763464291336",
                "breakdownPalletID": 1,
                "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 506733,
                "lp": "00006844763464289555",
                "breakdownPalletID": 1,
            "customerMessages": ["MAKE IT 3 HIGH AND LOW"]
            },
            {
                "sku": 519795,
                "lp": "00006844763464291206",
                "breakdownPalletID": 3,
                "customerMessages": ["MESSAGE 5","MESSAGE 6","MESSAGE 7"]

            }
            ]
    }

Body:
You can try something like this.

  groupBy(origArray: any[], key: string) {
    return origArray.reduce(function (rv, x) {
      (rv[x[key]] = rv[x[key]] || []).push(x);
      return rv;
    }, {});
  }

See demo


问:
Loop through 2 list of dictionaries
I have this 2 list of dictionaries, I was trying to print out all the names from list1 if they are not found in list2.

```<code>list1=[{'name':'A','color':'1'},
       {'name':'B','color':'2'}]

list2=[{'name':'A','color':'3'},
       {'name':'C','color':'1'}]

for item in list1:
    for ii in list2:
        if item['name'] != ii['name']:
            print item['name']
</code>```

The output I'm getting is

```<code>A
B
B
</code>```

I expected it to print B because there's not b in list2. Not sure what I'm doing wrong...any help would be appreciated.

Thanks

答:
If the names are unique in list1, you can use a set:

```<code>list1=[{'name':'A','color':'1'},
       {'name':'B','color':'2'}]

list2=[{'name':'A','color':'3'},
       {'name':'C','color':'1'}]

set1         = set(d['name'] for d in list1)
missingNames = set1.difference(d['name'] for d in list2) # {'B'}
</code>```

If they are not unique and you want to match number of instances, you can do it with Counter from collections:

```<code>from collections import Counter
count1 = Counter(d['name'] for d in list1)
count2 = Counter(d['name'] for d in list2)
missingNames = list((count1-count2).elements()) # ['B']
</code>```

With Counter, if you had two entries in list1 with name 'A', then the output would have been ['A','B'] since only one of the two 'A' in list1 would find a match in list2

Title: Loop through 2 list of dictionaries

Body:
I have this 2 list of dictionaries, I was trying to print out all the names from list1 if they are not found in list2.

list1=[{'name':'A','color':'1'},
       {'name':'B','color':'2'}]

list2=[{'name':'A','color':'3'},
       {'name':'C','color':'1'}]

for item in list1:
    for ii in list2:
        if item['name'] != ii['name']:
            print item['name']

The output I'm getting is

A
B
B

I expected it to print B because there's not b in list2. Not sure what I'm doing wrong...any help would be appreciated.

Thanks

Body:
If the names are unique in list1, you can use a set:

list1=[{'name':'A','color':'1'},
       {'name':'B','color':'2'}]

list2=[{'name':'A','color':'3'},
       {'name':'C','color':'1'}]

set1         = set(d['name'] for d in list1)
missingNames = set1.difference(d['name'] for d in list2) # {'B'}

If they are not unique and you want to match number of instances, you can do it with Counter from collections:

from collections import Counter
count1 = Counter(d['name'] for d in list1)
count2 = Counter(d['name'] for d in list2)
missingNames = list((count1-count2).elements()) # ['B']

With Counter, if you had two entries in list1 with name 'A', then the output would have been ['A','B'] since only one of the two 'A' in list1 would find a match in list2