问:
Using Spring Security OAuth2, what's the right way to refresh the stored authentication in the TokenStore?
We're using resource-owner credentials grant type (with oauth2:password in security-config.xml. Let's play out this scenario to explain my predicament:

Bob was created with authorities ROLE_USER

Bob tries to access an oauth2 protected resource

Bob uses the official mobile app to access it, so the client credentials are correct

Bob's access token is created and stored in the TokenStore, keyed on his username, client_id, and scope. (see DefaultAuthenticationKeyGenerator.java)

Bob's phone tries to call the protected services with this access token, but those services require users to have an authority of ROLE_MOBILE_USER.

Bob contacts the db owner and has ROLE_MOBLE_USER added to his user in the database.

Bob tries to get another access token, but the DefaultTokenServices returns him the same, non-working access token.

The only way to take advantage of his new authority is to wait until his old access token expires so he can get a new access token with the correct authority.

There are a number of ways to address this.

For one, the administration app that adds ROLE_MOBILE_USER to Bob's authorities could then clear all access tokens and authorizations in the database. This way the DefaultTokenServices will just create a new one with the correct authorities serialized as his new OAuth2Authentication. However we may not want the Administration webapp to be concerned with OAuth at this point (at least not yet). If possible we'd like to keep the administration app concerns as concise as possible, and right now there are no dependencies on oauth.

We could expose the DELETE method to the /oauth/access_token endpoint and tell the mobile app to try deleting that access token and re-requesting one, just in case the stored authorities are stale. This feels more like a work-around though.

Finally I can serialize the authorities in my own defined AuthenticationKeyGenerator. It would basically use the username, client_id, scope, and authorities of the authorization and perform the same digest algorithm on them. This way when Bob tries to log in he'll get the same access token, but the underlying token store will recognize that he has a different authentication (from the authentication manager in the token granter bean) and refresh its database. The problem I have with this solution is that it simply relies on the implementation behavior of the underlying token store (though both InMemoryTokenStore and JdbcTokenStore behave this way).

Can you think of any better/cleaner solutions? Am I over-thinking this?

Thanks in advance.

答:
I Had the same problem and this was the solution </p>

```<code>@RequestMapping(value = "/updateToken", method = RequestMethod.POST)
 void updateToken(@RequestBody tokenReq req) {
            Collection<OAuth2AccessToken> tokenCollection = tokenStore.findTokensByClientIdAndUserName(req.idclient, req.username);
            for (OAuth2AccessToken AToken : tokenCollection){
                OAuth2Authentication Auth = tokenStore.readAuthentication(AToken);
                OAuth2AccessToken newToken = tokenServices.createAccessToken(Auth);
                tokenStore.removeAccessToken(AToken);
                tokenStore.storeAccessToken(newToken, Auth);
            }

 }
</code>```

Body:
I Had the same problem and this was the solution

@RequestMapping(value = "/updateToken", method = RequestMethod.POST)
 void updateToken(@RequestBody tokenReq req) {
            Collection<OAuth2AccessToken> tokenCollection = tokenStore.findTokensByClientIdAndUserName(req.idclient, req.username);
            for (OAuth2AccessToken AToken : tokenCollection){
                OAuth2Authentication Auth = tokenStore.readAuthentication(AToken);
                OAuth2AccessToken newToken = tokenServices.createAccessToken(Auth);
                tokenStore.removeAccessToken(AToken);
                tokenStore.storeAccessToken(newToken, Auth);
            }

 }


来源: stackexchange

问:
copy tables from word without repeating header
```<code>Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True      ' Do show Word.

For Each f In fo.Files
If f.Name Like "*.docx" And Left(f.Name, 2) <> "~$" Then
    Set wdDoc = wdApp.Documents.Open(f.Path, False, True, Format:="doc Files")
    tableTot = wdDoc.Tables.Count
    If tableTot = 0 Then
        MsgBox "The file" & wdDoc.Name & "does not have invoice table", vbInformation, "Invoice sheet is invalid"
    End If

    Set xlwb = Workbooks.Add
    Set xlsh = xlwb.Sheets(1)
    Set rng = xlsh.Range("A1")
    xlsh.Activate

            For Each t In wdDoc.Tables
                t.Range.Copy
                rng.Select
                rng.Parent.PasteSpecial Format:="Text", Link:=False, _
                            DisplayAsIcon:=False
                With rng.Resize(t.Rows.Count, t.Columns.Count)
                    .Cells.UnMerge
                    .Cells.ColumnWidth = 14
                    .Cells.RowHeight = 14
                    .Cells.Font.Size = 10
                End With
            Set rng = rng.Offset(t.Rows.Count, 0)
            Next
            xlwb.SaveAs (excel_path & "\" & Replace(f.Name, ".docx", ".xlsx"))
            wdDoc.Close False
            xlwb.Close False
            Set t = Nothing: Set rng = Nothing: Set wdDoc = Nothing
            tableTot = 0
End If
Next
</code>```

Hi, I am trying to create new excel sheets for all invoices from a given folder. But the invoice has many other text which are in small tables so it copies that too.
Is there a way I can start my table based on keyword from a row (since the keyword column is also not constant) and pull my table without repeating the header in my excel file?

答:
You could replace:

```<code>For Each t In wdDoc.Tables
  t.Range.Copy
  rng.Select
</code>```

with:

```<code>h As Long: h = 0
For Each t In wdDoc.Tables
  With t
    If InStr(1, .Range.Text, "KeyWord", vbTextCompare) > 0 Then
      If h > 0 Then .Rows(1).Delete
      .Range.Copy
      h = h + 1
    End If
  End With
</code>```

or, if you don't want any header rows (you post isn't clear):

```<code>For Each t In wdDoc.Tables
  With t
    If InStr(1, .Range.Text, "KeyWord", vbTextCompare) > 0 Then
      .Rows(1).Delete
      .Range.Copy
    End If
  End With
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True      ' Do show Word.

For Each f In fo.Files
If f.Name Like "*.docx" And Left(f.Name, 2) <> "~$" Then
    Set wdDoc = wdApp.Documents.Open(f.Path, False, True, Format:="doc Files")
    tableTot = wdDoc.Tables.Count
    If tableTot = 0 Then
        MsgBox "The file" & wdDoc.Name & "does not have invoice table", vbInformation, "Invoice sheet is invalid"
    End If

    Set xlwb = Workbooks.Add
    Set xlsh = xlwb.Sheets(1)
    Set rng = xlsh.Range("A1")
    xlsh.Activate

            For Each t In wdDoc.Tables
                t.Range.Copy
                rng.Select
                rng.Parent.PasteSpecial Format:="Text", Link:=False, _
                            DisplayAsIcon:=False
                With rng.Resize(t.Rows.Count, t.Columns.Count)
                    .Cells.UnMerge
                    .Cells.ColumnWidth = 14
                    .Cells.RowHeight = 14
                    .Cells.Font.Size = 10
                End With
            Set rng = rng.Offset(t.Rows.Count, 0)
            Next
            xlwb.SaveAs (excel_path & "\" & Replace(f.Name, ".docx", ".xlsx"))
            wdDoc.Close False
            xlwb.Close False
            Set t = Nothing: Set rng = Nothing: Set wdDoc = Nothing
            tableTot = 0
End If
Next

Hi, I am trying to create new excel sheets for all invoices from a given folder. But the invoice has many other text which are in small tables so it copies that too.
Is there a way I can start my table based on keyword from a row (since the keyword column is also not constant) and pull my table without repeating the header in my excel file?

Body:
You could replace:

For Each t In wdDoc.Tables
  t.Range.Copy
  rng.Select

with:

h As Long: h = 0
For Each t In wdDoc.Tables
  With t
    If InStr(1, .Range.Text, "KeyWord", vbTextCompare) > 0 Then
      If h > 0 Then .Rows(1).Delete
      .Range.Copy
      h = h + 1
    End If
  End With

or, if you don't want any header rows (you post isn't clear):

For Each t In wdDoc.Tables
  With t
    If InStr(1, .Range.Text, "KeyWord", vbTextCompare) > 0 Then
      .Rows(1).Delete
      .Range.Copy
    End If
  End With


问:
Pandas - change in value to negative with a specific condition for particular groups of values
I have an example of a df that looks like this:

```<code>   Group   0       1       Total
0    1     Text    5        5
1    1     Text2   5        5
2    1     SUM     10       10
3    2     10%     10       10
4    2     100%    100      100
5    2     SUM     110      110
6    3     Text3   4        4
7    3     SUM     4        4
</code>```

Each row is divided into groups - in this case groups from 1 to 3 - the number of groups is different, but this does not matter.

I would like all elements in df[0] being number and % sign (e.g. 10% or 100%) to change their value in Total column to negative values

An example of such a solution:

```<code>   Group   0       1       Total
0    1     Text    5        5
1    1     Text2   5        5
2    1     SUM     10       10
3    2     10%     10       -10    <--- change the value here
4    2     100%    100      -100   <--- change the value here
5    2     SUM     110      110
6    3     Text3   4        4
7    3     SUM     4        4
</code>```

as far as I can pull this off, I don't know how to change these values. I've tried that way:

df[df[0].str.contains('\d%', regex= True, na=False)]

This way I have all the rows in which the value of df[0] have these requirements - the problem is that I don't know how to change their value in the Total column to negative. I tried that, but it doesn't help and there are errors:

df['Total'] = np.where(df[df[0].str.contains('\d%', regex= True, na=False)], df['Total'] *= -1,  df['Total'])

In addition, I would like to change the value df[0] == SUM  to a negative value but only when all the elements in the same group as SUM were values that met the previous requirements.

Example:

```<code>   Group   0       1       Total
0    1     Text    5        5
1    1     Text2   5        5
2    1     SUM     10       10
3    2     10%     10       -10
4    2     100%    100      -100
5    2     SUM     110      -110   <--- here should be a negative value - they are in the same group
6    3     Text3   4        4
7    3     SUM     4        4
</code>```

if in a given group (in this case group 2) there are values which for df[0] contain only a number and a sign of percentage, then their values for the Total column should be negative. Additionally, if all rows in the group meet this condition (these are numbers with a percentage sign) then for df[0] == SUM the value in Total column should also change the sign.

How to connect it to such a regex? How to make SUM dependence in a given group on previous values in same group?

Body:
I have an example of a df that looks like this:

   Group   0       1       Total
0    1     Text    5        5
1    1     Text2   5        5
2    1     SUM     10       10
3    2     10%     10       10
4    2     100%    100      100
5    2     SUM     110      110
6    3     Text3   4        4
7    3     SUM     4        4

Each row is divided into groups - in this case groups from 1 to 3 - the number of groups is different, but this does not matter.

I would like all elements in df[0] being number and % sign (e.g. 10% or 100%) to change their value in Total column to negative values

An example of such a solution:

   Group   0       1       Total
0    1     Text    5        5
1    1     Text2   5        5
2    1     SUM     10       10
3    2     10%     10       -10    <--- change the value here
4    2     100%    100      -100   <--- change the value here
5    2     SUM     110      110
6    3     Text3   4        4
7    3     SUM     4        4

as far as I can pull this off, I don't know how to change these values. I've tried that way:

df[df[0].str.contains('\d%', regex= True, na=False)]

This way I have all the rows in which the value of df[0] have these requirements - the problem is that I don't know how to change their value in the Total column to negative. I tried that, but it doesn't help and there are errors:

df['Total'] = np.where(df[df[0].str.contains('\d%', regex= True, na=False)], df['Total'] *= -1,  df['Total'])

In addition, I would like to change the value df[0] == SUM  to a negative value but only when all the elements in the same group as SUM were values that met the previous requirements.

Example:

   Group   0       1       Total
0    1     Text    5        5
1    1     Text2   5        5
2    1     SUM     10       10
3    2     10%     10       -10
4    2     100%    100      -100
5    2     SUM     110      -110   <--- here should be a negative value - they are in the same group
6    3     Text3   4        4
7    3     SUM     4        4

if in a given group (in this case group 2) there are values which for df[0] contain only a number and a sign of percentage, then their values for the Total column should be negative. Additionally, if all rows in the group meet this condition (these are numbers with a percentage sign) then for df[0] == SUM the value in Total column should also change the sign.

How to connect it to such a regex? How to make SUM dependence in a given group on previous values in same group?

Body:
try this,

df.loc[df['0'].str.contains("%"), "Total"] *= -1

df.loc[df.groupby("Group")['Total']
           .transform(lambda x : x * -1 if any(x < 0) else x) < 0, "Total"] *= -1

output,

   idx  Group      0    1  Total
0    0      1   Text    5      5
1    1      1  Text2    5      5
2    2      1    SUM   10     10
3    3      2    10%   10    -10
4    4      2   100%  100   -100
5    5      2    SUM  110   -110
6    6      3  Text3    4      4
7    7      3    SUM    4      4


问:
Help needed for developing iPhone application
I have following system configuration:

```<code>MAC OS X (10.5.8)
XCode (3.1.4)
iOS (3.0)
</code>```

1) Can i develop application for iPhone 4 with this configuration?

2) If not then what are the basic system requirement for developing application for both iPhone 3 and iPhone 4.

Thanks.

答: I suggest you read the Apple documentation: http://developer.apple.com/devcenter/ios/index.action</p>

ContentLicense: CC BY-SA 3.0

Body:
I have following system configuration:

MAC OS X (10.5.8)
XCode (3.1.4)
iOS (3.0)

1) Can i develop application for iPhone 4 with this configuration?

2) If not then what are the basic system requirement for developing application for both iPhone 3 and iPhone 4.

Thanks.


问:
Trying to install new libraries on Spyder (Python 3.7)
I am new to python and I am having trouble downloading some new libraries that don't appear to be pre-installed.  The names of them are rasterio and retrying.  I continuously get an invalid syntax error, and I have tried using some different suggestions found online.

pip install rasterio

Above is the way I was attempting to do it, and I also tried without the pip in there, but neither option worked.  I am new enough to the language that troubleshooting is very difficult.  Any help is greatly appreciated!

答:
I suppose you are using Spyder IDE with Anaconda. So, to install rasterio package you can open anaconda prompt and type:

conda install -c conda-forge rasterio

For further information about package installation check out this link.
Also, to install any conda packages just google it once, you will find instructions to install it mostly in anaconda's official site.

Edit:
Please remove the rasterio package once. And install it again, see if works. If it doesn't work create a new environment like: conda create --name myenv. Then install rasterio again.

If this still doesn't work, try to install rasterio from here like conda install -c ioos rasterio.


问:
does java support hotswap of annotations?
Afaik, java has many restrictions on hotswap operations such as not allowing change fields or method names. Then what about adding or delete annotations of fields ?

If so, there are still many kinds of annotations besides field annotation such as method annotation, class annotation etc. Does these annotions all support hotswap?

for example, before swap:

```<code>class A{
@FieldAnnotation1 int field;
}
</code>```

after :

```<code>class A{
@FieldAnnotation2 int field;
}
</code>```

答:
AFAIK, Java has many restrictions on hotswap operations such as not allowing change fields or method names.

It depends on how hotswap is implemented;

These restrictions don't apply if you hotswap code by (say) replacing a servlet.

For hotswapping in an IDE, the limiting factor is probably the sophistication of the IDE's debugger rather than Java itself.

Then what about adding or delete annotations of fields ?

It is not Java that you need to worry about1.  The Java runtime system will cope with this.  As far as Java is concerned, when you "hotswap" a class you are creating a new class.  Java doesn't know what the old or new annotations mean, or indeed that the new class is somehow related to the old class.  As long as the new annotation can be retrieved from the new class, Java has done its job.

The real issues are:

Can the IDE cope with it?  That depends on the IDE.

Can the framework that you are using cope with it.  It is the framework that "understands" what the annotations mean, and includes the software that deals with them.  It would be up to that software to make any adjustments to runtime data structures, behavior and so on if an annotation is changed by hotswapping.  Whether it does or does not will depend on the framework.

1 - The reason I say this is that annotations do not directly affect bytecode execution or the layout of object or stack frames.  However, I must admit that I cannot find any clear descriptions of the hotswap or its limitations at the JVMTI level.

Body:
Afaik, java has many restrictions on hotswap operations such as not allowing change fields or method names. Then what about adding or delete annotations of fields ?

If so, there are still many kinds of annotations besides field annotation such as method annotation, class annotation etc. Does these annotions all support hotswap?

for example, before swap:

class A{
@FieldAnnotation1 int field;
}

after :

class A{
@FieldAnnotation2 int field;
}


问:
How spin locks are implemented on platforms without CAS instructions?
The normal practice is to wrap the CAS instruction in a while loop on platforms that support CAS instructions. But platforms such as SPARC don't have atomic CAS instructions. </p>

答:
SPARC v8 (32-bit) and earlier lack CAS, but v9 (64-bit) does have CAS.

For a spin-lock v7 and v8 provide LDSTUB which is an atomic-read-modify-write of an unsigned byte, which writes 0xFF.  That does the lock phase of a spin-lock.  An ordinary write of 0 (or anything not 0xFF) will unlock, when using TSO -- for PSO you need an STBAR before the write.  [There is also the SWAP atomic-read-modify-write, which can be used in the same way.]

To implement CAS (and Fetch-Op) operations on v7/v8 you need an auxiliary spin-lock.

More generally:

(and as noted in comments) for "modern" devices, if CAS is not supported then some form of "LL/SC" probably is...

...and a CAS operation can be synthesized using LL/SC.  [FWIW: LL/SC is more general than CAS and avoids the dreaded ABA that straight CAS is prone to :-(]

but otherwise, once you have a spin-lock you can simulate most things...

...but if the thread holding a spin-lock goes to sleep, everybody gets to wait :-(

Machines (now historic) which provide neither LL/SC nor hardware support for a spin-lock may well have sequentially-consistent memory.  In which case you can implement a spin-lock using Peterson's Algorithm, or Burns', or others'), in software.


问:
How to get CodeIgnitor 3 to autoload when coding tests?
I'm new to CI and am struggling to get my head around it.

I'm familiar with Laravel and Symfony and I'm finding it very difficult to test CI code.

I'm considering the service locator pattern to try and work around the dependency injection limitations, but right now I'm struggling with autoloading.

Let's say that I have a model like this:

```<code><?php

class FooModel extends CI_Model
{
    public function __construct()
    {
        parent::__construct();

        $this->load->library('alertnotificationservice');
    }
}
</code>```

I want to write a test that looks like this:

```<code><?php

namespace Test\AlertNotification;

// extends TestCase and offers reflection helper methods
use Test\TestBase;

class FooModelTest extends TestBase
{

    public function test_my_method()
    {
        $objectUnderTest = new \FooModel();
    }
}
</code>```

When I run my test I get the error Error: Class 'CI_Model' not found.

I'm using CodeIgnitor 3.1.2 and it doesn't use composer or include the phpunit.xml.dist file that the version 4 manual refers to.

What is the "proper" way to get the autoloading to happen so that I can run my tests?

答:
I haven't found a satisfactory way to do this.  I ended up creating a bootstrap.php file that I include from phpunit.xml.dist

It looks something like this:

```<code><?php

require(__DIR__ . '/../vendor/autoload.php');
// this is a copy of the default index.php shipped with CodeIgnitor
// The system and application_folder variables are replaced
// Also, in this version we do not bootstrap the framework and rather include our own version below
require('loader.php');
// this is a modified version of system/core/CodeIgniter.php
// they do bootstrapping, routing, and dispatching in one place
// so we can't use the whole file because dispatching fails when running tests
require('framework.php');

// set up the test environment database connection
putenv('DATABASE_HOST=localhost');
putenv('DATABASE_USER=user');
putenv('DATABASE_PASSWORD=password');
putenv('DATABASE=control_panel');

// CI uses a singleton approach and creates an instance of a child of this class during dispatch
// We need to make sure that the singleton holder is populated
$controller = new CI_Controller();
</code>```

The framework.php is a stripped down version of that CodeIgnitor file where I've removed the routing and dispatch logic.  I've put the files up as a Gist

The crux of the loading in CI seems to exist in system/core/Controller.php and the controller is intended to be something that lets "so that CI can run as one big super object".  The load_class function (declared in system/core/Common.php) is responsible for hunting down and loading the class files.

I should also include my composer.json file.  I'm using this for testing (CI 3.1.12 does not use composer)

```<code>{
    "require": {
        "guzzlehttp/guzzle": "^6.5"
    },
    "require-dev": {
        "phpunit/phpunit": "^9.1"
    },
    "autoload": {
        "psr-4": {
            "Test\\": "tests/"
        },
        "classmap": ["application/", "system/"]
    }
}
</code>```

I would really like to avoid loading absolutely everything, and would like to be able to mock out bits and pieces, but I'm not optimistic that CodeIgnitor lends itself to this.

Anyway, this approach at least lets me boot my app.  There has to be a better way of doing this, I can't believe that the framework could be so popular if it's so hard to test properly.

Body:
I'm new to CI and am struggling to get my head around it.

I'm familiar with Laravel and Symfony and I'm finding it very difficult to test CI code.

I'm considering the service locator pattern to try and work around the dependency injection limitations, but right now I'm struggling with autoloading.

Let's say that I have a model like this:

<?php

class FooModel extends CI_Model
{
    public function __construct()
    {
        parent::__construct();

        $this->load->library('alertnotificationservice');
    }
}

I want to write a test that looks like this:

<?php

namespace Test\AlertNotification;

// extends TestCase and offers reflection helper methods
use Test\TestBase;

class FooModelTest extends TestBase
{

    public function test_my_method()
    {
        $objectUnderTest = new \FooModel();
    }
}

When I run my test I get the error Error: Class 'CI_Model' not found.

I'm using CodeIgnitor 3.1.2 and it doesn't use composer or include the phpunit.xml.dist file that the version 4 manual refers to.

What is the "proper" way to get the autoloading to happen so that I can run my tests?

Body:
I haven't found a satisfactory way to do this.  I ended up creating a bootstrap.php file that I include from phpunit.xml.dist

It looks something like this:

<?php

require(__DIR__ . '/../vendor/autoload.php');
// this is a copy of the default index.php shipped with CodeIgnitor
// The system and application_folder variables are replaced
// Also, in this version we do not bootstrap the framework and rather include our own version below
require('loader.php');
// this is a modified version of system/core/CodeIgniter.php
// they do bootstrapping, routing, and dispatching in one place
// so we can't use the whole file because dispatching fails when running tests
require('framework.php');

// set up the test environment database connection
putenv('DATABASE_HOST=localhost');
putenv('DATABASE_USER=user');
putenv('DATABASE_PASSWORD=password');
putenv('DATABASE=control_panel');

// CI uses a singleton approach and creates an instance of a child of this class during dispatch
// We need to make sure that the singleton holder is populated
$controller = new CI_Controller();

The framework.php is a stripped down version of that CodeIgnitor file where I've removed the routing and dispatch logic.  I've put the files up as a Gist

The crux of the loading in CI seems to exist in system/core/Controller.php and the controller is intended to be something that lets "so that CI can run as one big super object".  The load_class function (declared in system/core/Common.php) is responsible for hunting down and loading the class files.

I should also include my composer.json file.  I'm using this for testing (CI 3.1.12 does not use composer)

{
    "require": {
        "guzzlehttp/guzzle": "^6.5"
    },
    "require-dev": {
        "phpunit/phpunit": "^9.1"
    },
    "autoload": {
        "psr-4": {
            "Test\\": "tests/"
        },
        "classmap": ["application/", "system/"]
    }
}

I would really like to avoid loading absolutely everything, and would like to be able to mock out bits and pieces, but I'm not optimistic that CodeIgnitor lends itself to this.

Anyway, this approach at least lets me boot my app.  There has to be a better way of doing this, I can't believe that the framework could be so popular if it's so hard to test properly.


问:
How create one query?
One author has many books. There are many authors with books in the database.
It is required to get the latest books of authors. In one query.</p>

```<code>class Autor(models.Model):
    name = models.Charfield()

class Book(models.Model):
    name = models.Charfield()
    author = models.ForegnKey("Autors", models.CASCADE)
    created_at = models.DatetimeField(auto_now_add=True)

# its a many queries
last_books = []
for author in Autor.objects.all():
    last_book = Book.object.filter(autor=autor).latest("created_at")
    last_books.append(last_book)
# need one query
</code>```

答:
Get all books by the author, sort in descending order and fetch first record</p>

```<code>latest_books = []
for author in Author.objects.all():
    last_book = Books.objects.filter(author=author).order_by("-created_at")[0]
    latest_books.append(last_book)
</code>```

Title: How create one query?

Body:
One author has many books. There are many authors with books in the database.
It is required to get the latest books of authors. In one query.

class Autor(models.Model):
    name = models.Charfield()

class Book(models.Model):
    name = models.Charfield()
    author = models.ForegnKey("Autors", models.CASCADE)
    created_at = models.DatetimeField(auto_now_add=True)

# its a many queries
last_books = []
for author in Autor.objects.all():
    last_book = Book.object.filter(autor=autor).latest("created_at")
    last_books.append(last_book)
# need one query

Body:
Get all books by the author, sort in descending order and fetch first record

latest_books = []
for author in Author.objects.all():
    last_book = Books.objects.filter(author=author).order_by("-created_at")[0]
    latest_books.append(last_book)


问:
error: dereferencing pointer to incomplete type - C language
A few days ago I made a function, which worked just fine. This is struct defining I used.

```<code>typedef struct {
    int data;
    struct Node * next;
} Node;

typedef struct {
    Node * head;
    Node * current;
    int size;
} List;
</code>```

Then I have this function

```<code>void returnMiddle(List * list){
    Node * first = list->head;
    Node * second = list->head;

    if(list->head != NULL){
        while(second != NULL && second->next != NULL){
            first = first->next;
            second = first->next->next;
        }
        printf("Middle is: %d", first->data);
    }
}
</code>```

But now I receive given error and I don't understand why? Does anyone know?

second = first->next->next; <<< this is where I get an error message, up to here it works fine

答:
```<code>struct Node * next;
</code>```

struct Node is a forward declaration to structure Node, but you haven´t defined a structure called Node yet - means struct Node is an incomplete type.

```<code>typedef struct {
   ...
} Node;
</code>```

Node is a typedef for the structure definition. it is not equal to struct Node.

Provide the structure tag Node:

```<code>typedef struct Node {
    int data;
    struct Node * next;
} Node;
</code>```

and your code works fine.

Also have a look at here:

typedef struct vs struct definitions

Body:
A few days ago I made a function, which worked just fine. This is struct defining I used.

typedef struct {
    int data;
    struct Node * next;
} Node;

typedef struct {
    Node * head;
    Node * current;
    int size;
} List;

Then I have this function

void returnMiddle(List * list){
    Node * first = list->head;
    Node * second = list->head;

    if(list->head != NULL){
        while(second != NULL && second->next != NULL){
            first = first->next;
            second = first->next->next;
        }
        printf("Middle is: %d", first->data);
    }
}

But now I receive given error and I don't understand why? Does anyone know?

second = first->next->next; <<< this is where I get an error message, up to here it works fine

Body:
struct Node * next;

struct Node is a forward declaration to structure Node, but you haven´t defined a structure called Node yet - means struct Node is an incomplete type.

typedef struct {
   ...
} Node;

Node is a typedef for the structure definition. it is not equal to struct Node.

Provide the structure tag Node:

typedef struct Node {
    int data;
    struct Node * next;
} Node;

and your code works fine.

Also have a look at here:

typedef struct vs struct definitions


问:
C# LINQ Expression getting rather long
So, I have a list of objects (containers) in my code and I want to check if the container I will add, will contribute to the maximum weight on top of each container (container.MaxWeightOnTop). I have created this function:

```<code>    private bool TooMuchWeight(Container referenceContainer)
    {
        var tempList = _containers;
        tempList.Add(referenceContainer);
        SortStack(tempList);

        foreach (var container in tempList)
        {
            var index = tempList.FindIndex(c => c == container);
            var weightOnContainer = tempList.Where(c => tempList.FindIndex(i => i == container) > index)
                .Sum(c => container.Weight);

            if (weightOnContainer > Container.MaxWeightOnTop)
                return false;
        }

        return true;
    }
</code>```

As you can see it gets rather long, my IDE even suggest this LINQ expression for the entire foreach loop:

```<code> return (from container in tempList
            let index = tempList.FindIndex(c => c == container)
            select tempList.Where(c => tempList.FindIndex(i => i == container) > index)
                .Sum(c => container.Weight)).All(weightOnContainer => weightOnContainer <= Container.MaxWeightOnTop);
</code>```

Even when I use the .GetRange function it still remains long:

```<code>return tempList
            .Select(container =>
                tempList.GetRange(tempList.FindIndex(c => c == container), Length).Sum(c => c.Weight))
            .All(weightOnContainer => weightOnContainer <= Container.MaxWeightOnTop);
</code>```

Question: Is it possible to compress this expression?

答:
In terms of readability and maybe even a little bit performance, I think your code could leverage indexed Enumerable.Select overload and value tuples:

```<code>    var tempList = _containers;
    tempList.Add(referenceContainer);
    SortStack(tempList);
    var indexed = tempList.Select((container, index) => (container, index)).ToList();
    foreach (var (container, index) in indexed)
    {
        var weightOnContainer = indexed
            .Where((c, i) => i > index)
            .Sum((c, i) => c.Weight);

        if (weightOnContainer > Container.MaxWeightOnTop)
            return false;
    }
</code>```

Also in original version .Sum(c => container.Weight) clause looks a little bit funky to me, should not it be .Sum(c => c.Weight)?

Title: C# LINQ Expression getting rather long

Body:
So, I have a list of objects (containers) in my code and I want to check if the container I will add, will contribute to the maximum weight on top of each container (container.MaxWeightOnTop). I have created this function:

    private bool TooMuchWeight(Container referenceContainer)
    {
        var tempList = _containers;
        tempList.Add(referenceContainer);
        SortStack(tempList);

        foreach (var container in tempList)
        {
            var index = tempList.FindIndex(c => c == container);
            var weightOnContainer = tempList.Where(c => tempList.FindIndex(i => i == container) > index)
                .Sum(c => container.Weight);

            if (weightOnContainer > Container.MaxWeightOnTop)
                return false;
        }

        return true;
    }

As you can see it gets rather long, my IDE even suggest this LINQ expression for the entire foreach loop:

 return (from container in tempList
            let index = tempList.FindIndex(c => c == container)
            select tempList.Where(c => tempList.FindIndex(i => i == container) > index)
                .Sum(c => container.Weight)).All(weightOnContainer => weightOnContainer <= Container.MaxWeightOnTop);

Even when I use the .GetRange function it still remains long:

return tempList
            .Select(container =>
                tempList.GetRange(tempList.FindIndex(c => c == container), Length).Sum(c => c.Weight))
            .All(weightOnContainer => weightOnContainer <= Container.MaxWeightOnTop);

Question: Is it possible to compress this expression?

Body:
In terms of readability and maybe even a little bit performance, I think your code could leverage indexed Enumerable.Select overload and value tuples:

    var tempList = _containers;
    tempList.Add(referenceContainer);
    SortStack(tempList);
    var indexed = tempList.Select((container, index) => (container, index)).ToList();
    foreach (var (container, index) in indexed)
    {
        var weightOnContainer = indexed
            .Where((c, i) => i > index)
            .Sum((c, i) => c.Weight);

        if (weightOnContainer > Container.MaxWeightOnTop)
            return false;
    }

Also in original version .Sum(c => container.Weight) clause looks a little bit funky to me, should not it be .Sum(c => c.Weight)?


问:
Deserialize with dynamic object JSON by following type of content - C#
I have JSON string with different object depends on type of message. Example :

Text

```<code>{
"message": {
    "name": "sender",
    "from": "60123456789",
    "id": "ABGGYBJlBxcPAgo6zXukA7i8jnSe",
    "timestamp": "1585125726",
    "type": "text",
    "text": {
        "body": "Hi"
    }
}
</code>```

Image

```<code>{
"message": {
    "name": "sender",
    "from": "60123456789",
    "id": "ABGGYBJlBxcPAgo6zXukA7i8jnSe",
    "timestamp": "1585125726",
    "type": "image",
    "image": {
        "mime_type": "image/jpeg",
        "link": "http://lala.com/Files/image.jpeg",
        "caption": "your image caption"
    }
}
</code>```

And many more. The key such name, from, id and others is still same.

So what I do in code, I have to create objects for each type :

Object for Text

```<code>public class InboundMessageText
{
    public Message Message { get; set; }
}

public class Message
{
    public string Name { get; set; }
    public string From { get; set; }
    public string Id { get; set; }
    public int Timestamp { get; set; }
    public string Type { get; set; }
    public TextMessage Text { get; set; }
}

public class TextMessage
{
    public string Body { get; set; }
}
</code>```

Object for Image

```<code>public class InboundMessageImage
{
    public Message Message { get; set; }
}

public class Message
{
    public string Name { get; set; }
    public string From { get; set; }
    public string Id { get; set; }
    public int Timestamp { get; set; }
    public string Type { get; set; }
    public ImageMessage Image{ get; set; }
}

public class ImageMessage
{
    public string Mime_Type { get; set; }
    public string Link { get; set; }
    public string Caption { get; set; }
}
</code>```

This how I deserialize

```<code>var inboundMessage = JsonConvert.DeserializeObject <InboundMessageText> ("json string");

var addInboundMessage = new Data.Domain.InboundMessage {
    From = inboundMessage.Message.From,
    Name = inboundMessage.Message.Name,
    MessageId = inboundMessage.Message.Id,
    MessageTimestamp = DateTimeOffset.FromUnixTimeSeconds(inboundMessage.Message.Timestamp).LocalDateTime,
};

if (inboundMessage.Message.Type == "text") {

    addInboundMessage.InboundType = InboundType.Text;
    addInboundMessage.Text = inboundMessage.Message.TextMessage.Body;

}
else if (inboundMessage.Message.Type == "image") {
    //So here I have to deserialize again for image object

    var inboundMessageImage = JsonConvert.DeserializeObject <InboundMessageImage>("json string");

    addInboundMessage.InboundType = InboundType.Image;

    //Business logic
}
//and many type more...
</code>```

The code is working, but I have more than 7 types of message so make it my code is to long.

It's that possible to simplify the code?

答:
You can manage a base class for any message, and classes for specific types (text, image, etc), like that.

public class BaseMessage
{
    public string Name { get; set; }
    public string From { get; set; }
    public string Id { get; set; }
    public int Timestamp { get; set; }
    public string Type { get; set; }
}

public class ImageMessage : BaseMessage
{
    public ImageMessageContent Image { get; set; }
}

public class TextMessage : BaseMessage
{
    public TextMessageContent Text { get; set; }
}

public class ImageMessageContent
{
    public string Mime_Type { get; set; }
    public string Link { get; set; }
    public string Caption { get; set; }
}

public class TextMessageContent
{
    public string Body { get; set; }
}
```

<p>Note, that I've slightly changed the naming of your classes. There is no need to create a separate class for every type of message and container for that.</p>

<p>After that you can parse your JSON string to <code>JObject</code>, get the <code>type</code> value and create a concrete <code>Message</code> instance according to this value using <code>ToObject<T></code> method</p>

<pre class="lang-cs prettyprint-override"><code>var json = JObject.Parse(jsonString);
var type = json["message"]?["type"]?.Value<string>();

BaseMessage message;
switch (type)
{
    case "text":
        message = json["message"]?.ToObject<TextMessage>();
        break;
    case "image":
        message = json["message"]?.ToObject<ImageMessage>();
        break;
}
</code>```

Body:
I have JSON string with different object depends on type of message. Example :

Text

{
"message": {
    "name": "sender",
    "from": "60123456789",
    "id": "ABGGYBJlBxcPAgo6zXukA7i8jnSe",
    "timestamp": "1585125726",
    "type": "text",
    "text": {
        "body": "Hi"
    }
}

Image

{
"message": {
    "name": "sender",
    "from": "60123456789",
    "id": "ABGGYBJlBxcPAgo6zXukA7i8jnSe",
    "timestamp": "1585125726",
    "type": "image",
    "image": {
        "mime_type": "image/jpeg",
        "link": "http://lala.com/Files/image.jpeg",
        "caption": "your image caption"
    }
}

And many more. The key such name, from, id and others is still same.

So what I do in code, I have to create objects for each type :

Object for Text

public class InboundMessageText
{
    public Message Message { get; set; }
}

public class Message
{
    public string Name { get; set; }
    public string From { get; set; }
    public string Id { get; set; }
    public int Timestamp { get; set; }
    public string Type { get; set; }
    public TextMessage Text { get; set; }
}

public class TextMessage
{
    public string Body { get; set; }
}

Object for Image

public class InboundMessageImage
{
    public Message Message { get; set; }
}

public class Message
{
    public string Name { get; set; }
    public string From { get; set; }
    public string Id { get; set; }
    public int Timestamp { get; set; }
    public string Type { get; set; }
    public ImageMessage Image{ get; set; }
}

public class ImageMessage
{
    public string Mime_Type { get; set; }
    public string Link { get; set; }
    public string Caption { get; set; }
}

This how I deserialize

var inboundMessage = JsonConvert.DeserializeObject <InboundMessageText> ("json string");

var addInboundMessage = new Data.Domain.InboundMessage {
    From = inboundMessage.Message.From,
    Name = inboundMessage.Message.Name,
    MessageId = inboundMessage.Message.Id,
    MessageTimestamp = DateTimeOffset.FromUnixTimeSeconds(inboundMessage.Message.Timestamp).LocalDateTime,
};

if (inboundMessage.Message.Type == "text") {

    addInboundMessage.InboundType = InboundType.Text;
    addInboundMessage.Text = inboundMessage.Message.TextMessage.Body;

}
else if (inboundMessage.Message.Type == "image") {
    //So here I have to deserialize again for image object

    var inboundMessageImage = JsonConvert.DeserializeObject <InboundMessageImage>("json string");

    addInboundMessage.InboundType = InboundType.Image;

    //Business logic
}
//and many type more...

The code is working, but I have more than 7 types of message so make it my code is to long.

It's that possible to simplify the code?

Body:
You can manage a base class for any message, and classes for specific types (text, image, etc), like that.

public class BaseMessage
{
    public string Name { get; set; }
    public string From { get; set; }
    public string Id { get; set; }
    public int Timestamp { get; set; }
    public string Type { get; set; }
}

public class ImageMessage : BaseMessage
{
    public ImageMessageContent Image { get; set; }
}

public class TextMessage : BaseMessage
{
    public TextMessageContent Text { get; set; }
}

public class ImageMessageContent
{
    public string Mime_Type { get; set; }
    public string Link { get; set; }
    public string Caption { get; set; }
}

public class TextMessageContent
{
    public string Body { get; set; }
}

Note, that I've slightly changed the naming of your classes. There is no need to create a separate class for every type of message and container for that.

After that you can parse your JSON string to JObject, get the type value and create a concrete Message instance according to this value using ToObject<T> method

var json = JObject.Parse(jsonString);
var type = json["message"]?["type"]?.Value<string>();

BaseMessage message;
switch (type)
{
    case "text":
        message = json["message"]?.ToObject<TextMessage>();
        break;
    case "image":
        message = json["message"]?.ToObject<ImageMessage>();
        break;
}


问:
Flutter Web reload bug?
I'm having this issue where if I navigate to a page (through a named route), say for example /privacy, directly through the url, it works fine. When I click the refresh button, it stays on the page for a second, and goes to the root url ("/") and then traverses to a different page.

Here is a bit of my code:

```<code>routes: {
    Landing.route: (context) => Landing(),
    PrivPol.route: (context) => PrivPol(),
    "/": (context) => Loading(),
},
initialRoute: "/",
</code>```

and from the tutorials I've been looking at if I directly type in localhost:port/{PrivPol.route} it should go to and stay on that page, even if I refresh the page.

答: So it turns out that in one of the other files, I had a future that was being called, which was causing the re-route to take place!</p>

Title: Flutter Web reload bug?

Body:
I'm having this issue where if I navigate to a page (through a named route), say for example /privacy, directly through the url, it works fine. When I click the refresh button, it stays on the page for a second, and goes to the root url ("/") and then traverses to a different page.

Here is a bit of my code:

routes: {
    Landing.route: (context) => Landing(),
    PrivPol.route: (context) => PrivPol(),
    "/": (context) => Loading(),
},
initialRoute: "/",

and from the tutorials I've been looking at if I directly type in localhost:port/{PrivPol.route} it should go to and stay on that page, even if I refresh the page.


问:
Switching user control in WPF only shows the name of ViewModel
I've built WPF app using MVVM design with some simple navigation. I added two Views(User Controls) and dummy ViewModels (empty classess) to the project to switch them through this navigation. Here is my folder structure:
Folder Structure

So when I click i.e. on the first button in navi instead of the view of user control, I got the name of the ViewModel like this:
App screen
(View.ViewModels.NameoftheViewModel)

Here is how I implemented this:

Window.Resources with DataTemplate

Navi buttons for switching user controls

MainWindow.xaml.cs :

```<code>    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new NavigationViewModel();
    }
</code>```

NavigationViewModel used for switching :

```<code>class NavigationViewModel : INotifyPropertyChanged
{
    public ICommand CurrencyCommand { get; set; }
    public ICommand GoldCommand { get; set; }
    private object selectedViewModel;
    public object SelectedViewModel
    {
        get { return selectedViewModel; }
        set { selectedViewModel = value; OnPropertyChanged("SelectedViewModel"); }
    }

    public NavigationViewModel()
    {
        CurrencyCommand = new BaseCommand(OpenCurrency);
        GoldCommand = new BaseCommand(OpenGold);
    }

    public void OpenCurrency(object obj)
    {
        SelectedViewModel = new CurrencyViewModel();
    }

    public void OpenGold(object obj)
    {
        SelectedViewModel = new GoldViewModel();
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propName)

    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }

    }
}
</code>```

BaseCommand class simply implements ICommand interface.

XAML for showing user controls :

```<code><ContentControl Margin="45, 50, 0, 0" Content="{Binding SelectedViewModel}"/>
</code>```

Does anyone knows why is this happening? I did this from the tutorial: Tutorial link and it works all fine for this tutorial case but in my project it does not.

答:
from linked tutorial:

Create a DataTemplate of type EmployeeViewModel and it should contain EmployeeView UserControl inside it. Important thing is you should specify any key to the DataTemplates, since these DataTemplates are going to get queried by their DataType.

you should not specify x:Key for DataTemplates for your view models. DataTemplates can be picked by DataType only if there is no x:Key

```<code><DataTemplate DataType="{x:Type vm:CurrencyViewModel}">
    <vs:CurrencyControl/>
</DataTemplate>
</code>```

Body:
I've built WPF app using MVVM design with some simple navigation. I added two Views(User Controls) and dummy ViewModels (empty classess) to the project to switch them through this navigation. Here is my folder structure:
Folder Structure

So when I click i.e. on the first button in navi instead of the view of user control, I got the name of the ViewModel like this:
App screen
(View.ViewModels.NameoftheViewModel)

Here is how I implemented this:

Window.Resources with DataTemplate

Navi buttons for switching user controls

MainWindow.xaml.cs :

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = new NavigationViewModel();
    }

NavigationViewModel used for switching :

class NavigationViewModel : INotifyPropertyChanged
{
    public ICommand CurrencyCommand { get; set; }
    public ICommand GoldCommand { get; set; }
    private object selectedViewModel;
    public object SelectedViewModel
    {
        get { return selectedViewModel; }
        set { selectedViewModel = value; OnPropertyChanged("SelectedViewModel"); }
    }

    public NavigationViewModel()
    {
        CurrencyCommand = new BaseCommand(OpenCurrency);
        GoldCommand = new BaseCommand(OpenGold);
    }

    public void OpenCurrency(object obj)
    {
        SelectedViewModel = new CurrencyViewModel();
    }

    public void OpenGold(object obj)
    {
        SelectedViewModel = new GoldViewModel();
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propName)

    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }

    }
}

BaseCommand class simply implements ICommand interface.

XAML for showing user controls :

<ContentControl Margin="45, 50, 0, 0" Content="{Binding SelectedViewModel}"/>

Does anyone knows why is this happening? I did this from the tutorial: Tutorial link and it works all fine for this tutorial case but in my project it does not.

Body:
from linked tutorial:

Create a DataTemplate of type EmployeeViewModel and it should contain EmployeeView UserControl inside it. Important thing is you should specify any key to the DataTemplates, since these DataTemplates are going to get queried by their DataType.

you should not specify x:Key for DataTemplates for your view models. DataTemplates can be picked by DataType only if there is no x:Key

<DataTemplate DataType="{x:Type vm:CurrencyViewModel}">
    <vs:CurrencyControl/>
</DataTemplate>


问:
What is the difference between these two C++ statements to concatenate a string?
I'm new to C++ and I was wondering what the difference is between these two lines:

```<code>cout << "John " << "Doe" << endl;
cout << "John " + "Doe" << endl;
</code>```

The first one works but the second one doesn't. Any ideas?

答: The reason the second one does not work is that you can't concatenate two string literals with <code>+</code> operator. On the other hand, the first approach utilizes chaining of insertion operators to print multiple expressions </p>

Body:
I'm new to C++ and I was wondering what the difference is between these two lines:

cout << "John " << "Doe" << endl;
cout << "John " + "Doe" << endl;

The first one works but the second one doesn't. Any ideas?

Body: The reason the second one does not work is that you can't concatenate two string literals with + operator. On the other hand, the first approach utilizes chaining of insertion operators to print multiple expressions


问:
React Native Action Button - Unable to Add buttons Dynamically
Unable to Add ActionButton Items dynamically.

I have the following setup --

```<code><ActionButton>
    <ActionButton.item name={constant_btn1} />
    <ActionButton.item name={constant_btn2} />
</ActionButton>
</code>```

I want to add dynamic buttons to this list. (The list is received from backend)

I have created a function that returns me views of these buttons.

```<code>getDynamicBtns() {
    return dynamicButtonsList.map(item, key) => {(
        return <ActionButton.item name={item.btnName} />;
    )};
}
</code>```

and I have used it in this way -->

```<code><ActionButton>
    <ActionButton.item name={constant_btn1} />
    <ActionButton.item name={constant_btn2} />
    {this.getDynamicBtns()}
</ActionButton>
</code>```

So this is rendering my constant buttons, but not the dynamic buttons.

EDIT -
I am returning the map from the getDynamicBtns() function and calling invoking the function call too from within render(). This is just some simplified sample code that I have wriiten.

EDIT2 -
To prevent any confusion, changing original question's code.

答:
You are no returning anything in getDynamicBtns function. You should return the result of your map:</p>

```<code>getDynamicBtns() {
    return dynamicButtonsList.map(item => <ActionButton.item name={item.btnName} />)
}
</code>```

Body:
Unable to Add ActionButton Items dynamically.

I have the following setup --

<ActionButton>
    <ActionButton.item name={constant_btn1} />
    <ActionButton.item name={constant_btn2} />
</ActionButton>

I want to add dynamic buttons to this list. (The list is received from backend)

I have created a function that returns me views of these buttons.

getDynamicBtns() {
    return dynamicButtonsList.map(item, key) => {(
        return <ActionButton.item name={item.btnName} />;
    )};
}

and I have used it in this way -->

<ActionButton>
    <ActionButton.item name={constant_btn1} />
    <ActionButton.item name={constant_btn2} />
    {this.getDynamicBtns()}
</ActionButton>

So this is rendering my constant buttons, but not the dynamic buttons.

EDIT -
I am returning the map from the getDynamicBtns() function and calling invoking the function call too from within render(). This is just some simplified sample code that I have wriiten.

EDIT2 -
To prevent any confusion, changing original question's code.

Body:
You are no returning anything in getDynamicBtns function. You should return the result of your map:

getDynamicBtns() {
    return dynamicButtonsList.map(item => <ActionButton.item name={item.btnName} />)
}


问:
shared_from_this when inheriting from class defined by third party
I've read many posts on stack-overflow about shared_from_this, bad_weak_ptr exceptions, and multiple inheritance while trying to research my problem. All of them propose you inherit a base class from enable_shared_from_this, and then derive from that. Well, what does one do when the class you have to derive from is a coming from a third party library that you cannot edit?

Example:

```<code>#include <iostream>
#include <memory>

class ThirdPartyClass
{
public:
    ThirdPartyClass() {}
    ThirdPartyClass(const ThirdPartyClass &) = delete;
    virtual ~ThirdPartyClass() {};
};

class A : public ThirdPartyClass, std::enable_shared_from_this<A>
{
public:
    A():ThirdPartyClass(){}
    virtual ~A(){}

    void Foo();
};

void DoStuff(std::shared_ptr<A> ptr)
{
    std::cout << "Good job if you made it this far!" << std::endl;
}

void A::Foo()
{
    DoStuff(shared_from_this());    // throws here
}

int main() {
    std::shared_ptr<A> a = std::make_shared<A>();
    a->Foo();
    return 0;
}
</code>```

答:
You get the error because you are not public inheriting from enable_shared_from_this and shared_ptr and make_shared cannot detect that the object requires such support. Not because of inheritance from third party class.

So, to fix just inherit as public:

```<code>class A : public ThirdPartyClass, public std::enable_shared_from_this<A>
</code>```

Body:
I've read many posts on stack-overflow about shared_from_this, bad_weak_ptr exceptions, and multiple inheritance while trying to research my problem. All of them propose you inherit a base class from enable_shared_from_this, and then derive from that. Well, what does one do when the class you have to derive from is a coming from a third party library that you cannot edit?

Example:

#include <iostream>
#include <memory>

class ThirdPartyClass
{
public:
    ThirdPartyClass() {}
    ThirdPartyClass(const ThirdPartyClass &) = delete;
    virtual ~ThirdPartyClass() {};
};

class A : public ThirdPartyClass, std::enable_shared_from_this
{
public:
    A():ThirdPartyClass(){}
    virtual ~A(){}

    void Foo();
};

void DoStuff(std::shared_ptr ptr)
{
    std::cout << "Good job if you made it this far!" << std::endl;
}

void A::Foo()
{
    DoStuff(shared_from_this());    // throws here
}

int main() {
    std::shared_ptr a = std::make_shared();
    a->Foo();
    return 0;
}

Body:
You get the error because you are not public inheriting from enable_shared_from_this and shared_ptr and make_shared cannot detect that the object requires such support. Not because of inheritance from third party class.

So, to fix just inherit as public:

class A : public ThirdPartyClass, public std::enable_shared_from_this<A>


答:
The first line

```<code>cout << "John " << "Doe" << endl;
</code>```

doesn't concatenate strings. It prints "John " and then it prints "Doe". But there never existed a string "John Doe".

The second line

```<code>cout << "John " + "Doe" << endl;
</code>```

is syntactically wrong. There is no operator+ overloaded for char arrays.

To concatenate string literals you can use

```<code>#include <iostream>
#include <string>
using std::literals::string_literals::operator""s;

int main() {
    std::cout << "John "s + "Doe"s << std::endl;
    // or
    auto name = "John "s + "Doe"s;
    std::cout << name << std::endl;
}
</code>```

since C++14. operator""s creates a std::string with operator+.

Title: What is the difference between these two C++ statements to concatenate a string?

Body:
The first line

cout << "John " << "Doe" << endl;

doesn't concatenate strings. It prints "John " and then it prints "Doe". But there never existed a string "John Doe".

The second line

cout << "John " + "Doe" << endl;

is syntactically wrong. There is no operator+ overloaded for char arrays.

To concatenate string literals you can use

#include <iostream>
#include <string>
using std::literals::string_literals::operator""s;

int main() {
    std::cout << "John "s + "Doe"s << std::endl;
    // or
    auto name = "John "s + "Doe"s;
    std::cout << name << std::endl;
}

since C++14. operator""s creates a std::string with operator+.


问:
how to sort array object based on another object
it possible to sort and rearrange an array that looks like this:

```<code>items:[{
     id: '5',
     name: 'wa'
     },{
     id: '3',
     name: 'ads'
     },{
     id: '1',
     name: 'fdf'
     }]
</code>```

to match the arrangement of this object:

```<code> Item_sequence: {
        "5": {index: 1},
        "1": { index: 0 }
      }
</code>```

Here is the output I’m looking for:

```<code> items:[{
     id: '1',
     name: 'fdf'
     },{
     id: '5',
     name: 'wa'
     },{
     id: '3',
     name: 'ads'
     }]
</code>```

答:
You could check if the index is supplied and if not take a lage value for sorting by delta of two items.

var data = { items: [{ id: '5', name: 'wa' }, { id: '3', name: 'ads' }, { id: '1', name: 'fdf' }] },
    sequence = { 5: { index: 1 }, 1: { index: 0 } };

data.items.sort(({ id: a }, { id: b }) =>
    (a in sequence ? sequence[a].index : Number.MAX_VALUE) -
    (b in sequence ? sequence[b].index : Number.MAX_VALUE)
);

console.log(data.items);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
it possible to sort and rearrange an array that looks like this:

items:[{
     id: '5',
     name: 'wa'
     },{
     id: '3',
     name: 'ads'
     },{
     id: '1',
     name: 'fdf'
     }]

to match the arrangement of this object:

 Item_sequence: {
        "5": {index: 1},
        "1": { index: 0 }
      }

Here is the output I’m looking for:

 items:[{
     id: '1',
     name: 'fdf'
     },{
     id: '5',
     name: 'wa'
     },{
     id: '3',
     name: 'ads'
     }]

Body:
You could check if the index is supplied and if not take a lage value for sorting by delta of two items.

var data = { items: [{ id: '5', name: 'wa' }, { id: '3', name: 'ads' }, { id: '1', name: 'fdf' }] },
    sequence = { 5: { index: 1 }, 1: { index: 0 } };

data.items.sort(({ id: a }, { id: b }) =>
    (a in sequence ? sequence[a].index : Number.MAX_VALUE) -
    (b in sequence ? sequence[b].index : Number.MAX_VALUE)
);

console.log(data.items);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Trying to make a timer which resets at the main Menu
I have a timer for a game in Unity and I have it carrying across to each new scene and working. The issue is I also want the timer to reset when the MainMenu scene has loaded and I can not for the life of me get this to work. Help would be appreciated, code's below -</p>

```<code>using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.UI;

using UnityEngine.SceneManagement;

public class Timer : MonoBehaviour

{

public Text TimerText;

public float StartTime = 0f;

     // Start is called before the first frame update
     void Start()
     {
         string Scene = SceneManager.GetActiveScene().name;
         if (Scene == "MainMenu")
         {
             Destroy(this.gameObject);
         }
         else
         {
             DontDestroyOnLoad(this.gameObject);
         }
     }
     void Update()
     {
         float t = Time.time - StartTime;
         string minutes = ((int)t / 60).ToString();
         string seconds = (t % 60).ToString("f2");
         TimerText.text = minutes + ":" + seconds;
     }

}
</code>```

答:
Don't destroy the game object when main menu is loaded. Just set the time to 0 and make the game object last for all the scenes. Thus since the game object is available to all the scenes, create a bool variable called shouldCountTime. In the update function, just say if shouldCountTime == true then timer code is executed else not. When main menu is loaded, set time to zero and shouldCountTime to false. In start check if the scene loaded is not the main menu, then set shouldCountTime to true.

Code should look like:

void Start() {
    if(SceneManager.getActiveScene.name != "MainMenu") {
        shouldCountTime = true;
    } else {
        shouldCountTime = false;
        Time = 0;
    }

void Update(){

    if(shouldCountTime){

        Time += Time.deltaTime;
//All the timer code

}}
```

Body:
I have a timer for a game in Unity and I have it carrying across to each new scene and working. The issue is I also want the timer to reset when the MainMenu scene has loaded and I can not for the life of me get this to work. Help would be appreciated, code's below -

using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using UnityEngine.UI;

using UnityEngine.SceneManagement;

public class Timer : MonoBehaviour

{

public Text TimerText;

public float StartTime = 0f;

     // Start is called before the first frame update
     void Start()
     {
         string Scene = SceneManager.GetActiveScene().name;
         if (Scene == "MainMenu")
         {
             Destroy(this.gameObject);
         }
         else
         {
             DontDestroyOnLoad(this.gameObject);
         }
     }
     void Update()
     {
         float t = Time.time - StartTime;
         string minutes = ((int)t / 60).ToString();
         string seconds = (t % 60).ToString("f2");
         TimerText.text = minutes + ":" + seconds;
     }

}


答:
String literals like "foo" cannot be added (i.e. operator+) together for concatenation like in many other languages. This is reasonable in a low-level language like C++ because (in the general case) that would mean an allocation would have to take place.

However, if you are fine with that, then you can use std::string objects which do have those facilities for you. The following works:

```<code>cout << string("John ") + string("Doe") << endl;
</code>```

Body:
String literals like "foo" cannot be added (i.e. operator+) together for concatenation like in many other languages. This is reasonable in a low-level language like C++ because (in the general case) that would mean an allocation would have to take place.

However, if you are fine with that, then you can use std::string objects which do have those facilities for you. The following works:

cout << string("John ") + string("Doe") << endl;


问:
Return null if top two rows are same in mysql
I have a use case where I want to return null in MySQL if the top two rows have the same value.

```<code>SELECT FACILITY_ID, INVENTORY FROM FACILITY
ORDER BY INVENTORY DESC LIMIT 2;
</code>```

Here is the same date

```<code>FACILITY_ID | INVENTORY

1 | 10

2 | 10
</code>```

答:
You can use the MySQL LAG() Function. Here's the documentation:

https://www.mysqltutorial.org/mysql-window-functions/mysql-lag-function/

Body:
I have a use case where I want to return null in MySQL if the top two rows have the same value.

SELECT FACILITY_ID, INVENTORY FROM FACILITY
ORDER BY INVENTORY DESC LIMIT 2;

Here is the same date

FACILITY_ID | INVENTORY

1 | 10

2 | 10


问:
Diff function Flex
I am looking for a way to compare two XML files (old and new) and copy to an array all the nodes that are present in the new version but not the old version. I think it should be relatively straight forward to, for each node in the new XML file, iterate through the old XML file and see if it's found ... however, I do not think this is an efficient solution for large XML files (<10k nodes). I am wondering if there is a better solution - either algorithmic or function in Flex - to accomplish this task.

Thanks for all the assistance!

答: Jackson Dunstan has recently tested XML performance and found it indeed slow, even for access. Alternatives are nested Objects or Dictionaries containing XML data - but you must build them from XML once it is parsed, and this is not justified for a single pass. Or parse it yourself - but I'm not sure how much faster that would be, even with Alchemy.</p>

Title: Diff function Flex


问:
How to convert the file with multiple delimiter to dataframe
I have a text file as below

```<code>1234_4567_DigitalDoc_XRay-01.pdf
2345_5678_DigitalDoc_CTC-03.png
1234_5684_DigitalDoc_XRay-05.pdf
1234_3345_DigitalDoc_XRay-02.pdf
</code>```

I am expecting the output as

```<code>| catg|sub_catg|      doc_name        |revision_label|extension|
|1234|     4567|DigitalDoc_XRay-01.pdf|   01         |pdf      |
</code>```

I have created a custom schema

```<code> val customSchema = StructType(
      StructField("catg", StringType, true)
        :: StructField("sub_catg", StringType, true)
        :: StructField("doc_name", StringType, true)
        :: StructField("revision_label", StringType, true)
        :: StructField("extension", StringType, true)
        :: Nil
    )
</code>```

I am trying to create a dataframe as

```<code>val df = sparkSession.read
  .format("csv")
  .schema(customSchema)
  .option("delimiter", "_")
  .load("src/main/resources/data/sample.txt")

df.show()
</code>```

I am wondering how to break that each line by custom record

I could probably write a java code something of this kind, can someone please help me with the spark. I am new to spark.

```<code>String word[] = line.split("_");

            String filenName[] = word[3].split("-");
            String revision = filenName[1];
            word[0]+","+word[1]+","+ word[2]+"_"+word[3]+","+revision.replace(".", " ");
</code>```

Body:
I have a text file as below

1234_4567_DigitalDoc_XRay-01.pdf
2345_5678_DigitalDoc_CTC-03.png
1234_5684_DigitalDoc_XRay-05.pdf
1234_3345_DigitalDoc_XRay-02.pdf

I am expecting the output as

| catg|sub_catg|      doc_name        |revision_label|extension|
|1234|     4567|DigitalDoc_XRay-01.pdf|   01         |pdf      |

I have created a custom schema

 val customSchema = StructType(
      StructField("catg", StringType, true)
        :: StructField("sub_catg", StringType, true)
        :: StructField("doc_name", StringType, true)
        :: StructField("revision_label", StringType, true)
        :: StructField("extension", StringType, true)
        :: Nil
    )

I am trying to create a dataframe as

val df = sparkSession.read
  .format("csv")
  .schema(customSchema)
  .option("delimiter", "_")
  .load("src/main/resources/data/sample.txt")

df.show()

I am wondering how to break that each line by custom record

I could probably write a java code something of this kind, can someone please help me with the spark. I am new to spark.

String word[] = line.split("_");

            String filenName[] = word[3].split("-");
            String revision = filenName[1];
            word[0]+","+word[1]+","+ word[2]+"_"+word[3]+","+revision.replace(".", " ");

Body:
You could use "split" function

  import org.apache.spark.sql.functions._

  val df = Seq("1234_4567_DigitalDoc_XRay-01.pdf",
  "2345_5678_DigitalDoc_CTC-03.png",
  "1234_5684_DigitalDoc_XRay-05.pdf",
  "1234_3345_DigitalDoc_XRay-02.pdf")
  .toDF("filename")

  df.select(split($"filename","_").as("x"))
  .select(
    $"x".getItem(0).as("cat"),
    $"x".getItem(1).as("subcat"),
    $"x".getItem(2).as("doc"),
    split($"x".getItem(3), "\\.").as("y")
  )
  .select($"cat", $"subcat", $"doc",
    $"y".getItem(0).as("rev"),
    $"y".getItem(1).as("ext")
  )
  .show(false)

+----+------+----------+-------+---+
|cat |subcat|doc       |rev    |ext|
+----+------+----------+-------+---+
|1234|4567  |DigitalDoc|XRay-01|pdf|
|2345|5678  |DigitalDoc|CTC-03 |png|
|1234|5684  |DigitalDoc|XRay-05|pdf|
|1234|3345  |DigitalDoc|XRay-02|pdf|
+----+------+----------+-------+---+


答:
The first method is the correct method to concatenate two strings in C++. Whereas the second method, is by default the method to concatenate two strings in Python.

You can't use the second as it is not supported as it indicates addition of two strings and not concatenation (as seen by c++ compiler).


问:
Return React component as object value and bind props to it
There's one global hook which returns react components when used:

const { SomeComponent1, SomeComponent2 } = useHook({ prop1, prop2 })
```

<p>How do I pass props to the components I am returning from the hook?</p>

<pre class="lang-js prettyprint-override"><code>const useHook = ({ prop1, prop2 }) => {

  return {
    SomeComponent1, // <-- I'd like to 'bind' props to the component here
    SomeComponent2,
    // THE CODE BELOW IS INCORRECT
    // it's a way to illustrate what I am after:
    // SomeComponent1: <SomeComponent1 prop1={prop1} />
  }
}
</code>```

Passing the props down to destructed react components is a no-go for me:

const { Comp1, Comp2 } = useHook()

return (
  <Comp1 prop={prop1} />
)
```

答:
You can create the components as functional components and use useMemo inside your useHook to prevent remounting of the components on each render

```<code>const useHook = ({ prop1, prop2 }) => {

  const SomeComponent1Wrap = useMemo(() => () => {
     return <SomeComponent1 prop={prop1} />
  }, [prop1]);

  const SomeComponent2Wrap = useMemo(() => () => {
     return <SomeComponent2 prop={prop2} />
  }, [prop2]);

  return {
    SomeComponent1: SomeComponent1Wrap,
    SomeComponent2: SomeComponent2Wrap
  }
}
</code>```

Body:
There's one global hook which returns react components when used:

const { SomeComponent1, SomeComponent2 } = useHook({ prop1, prop2 })

How do I pass props to the components I am returning from the hook?

const useHook = ({ prop1, prop2 }) => {

  return {
    SomeComponent1, // <-- I'd like to 'bind' props to the component here
    SomeComponent2,
    // THE CODE BELOW IS INCORRECT
    // it's a way to illustrate what I am after:
    // SomeComponent1: <SomeComponent1 prop1={prop1} />
  }
}

Passing the props down to destructed react components is a no-go for me:

const { Comp1, Comp2 } = useHook()

return (
  <Comp1 prop={prop1} />
)

Body:
You can create the components as functional components and use useMemo inside your useHook to prevent remounting of the components on each render

const useHook = ({ prop1, prop2 }) => {

  const SomeComponent1Wrap = useMemo(() => () => {
     return <SomeComponent1 prop={prop1} />
  }, [prop1]);

  const SomeComponent2Wrap = useMemo(() => () => {
     return <SomeComponent2 prop={prop2} />
  }, [prop2]);

  return {
    SomeComponent1: SomeComponent1Wrap,
    SomeComponent2: SomeComponent2Wrap
  }
}


问:
Struct of multidimensional arrays in CUDA
I am facing some issues in kernels using a big struct including 1D, 2D and 3D arrays such as the following example:

```<code>typedef struct {
    float  data[N];
    int    map_a[N][M];
    int    map_b[N][M];
    int    map_c[B][N][M];
    ...
} my_struct;
</code>```

When I use a struct like that, a kernel that do: my_struct->map_dbx][y] = value hangs the program. Of course, x and y are lower than array size. However, other kernel using the same struct writing in map_a, works as expected.
My suspicion is that wrong memory accesses are occurring in multidimensional arrays. So it would be nice is someone can help me with some doubts about multidimensional arrays allocation within a struct in CUDA:

As suggested in the CUDA Programming guide, function cudaMallocPitch() should be used to allocate arrays while guaranteeing padding needed when the array size does not match the warp size. Would it be correctly allocated this struct with cudaMalloc(&my_struct, sizeof(my_struct));? i.e. is cudaMallocPitch() used internally to ensure arrays paddding?

As I suspect that the answer of the first question is 'NO', How could I correctly allocate a struct of multidimensional arrays in the device while using cudaMallocPitch()? and how could I properly make a cudaMemcpy() between host and device of that struct?

Some answers in stackoverflow about issues with 2D arrays suggest to use arrays flattening. I have tried it and I have no problems using them. Is that the only solution to properly use a struct of multidimensional arrays in CUDA?

Another solution would be to use separate arrays instead a struct but I have a big amount of arrays that would have to be passed to kernels. I hope someone have some advice to solve this issue.

答:
As suggested in the CUDA Programming guide, function cudaMallocPitch() should be used to allocate arrays while guaranteeing padding needed when the array size does not match the warp size.

That is not what the padding is for. It is primarily for hardware restrictions in things like the texturing unit cache line size. It is unnecessary for general allocations and your use case does not require it. In statically defined structures, the compiler will ensure safe alignment of the structure, and will emit warnings or errors if it can detect you are trying to do something which would violate static alignment requirements of the hardware.

Would it be correctly allocated this struct with cudaMalloc(&my_struct, sizeof(my_struct));?

Yes

i.e. is cudaMallocPitch() used internally to ensure arrays paddding?

No. The two things have no relation to one another. The APIs know nothing about the structures you are allocating, just their size. All internal memory layout and alignment is decided by the compiler.

As I suspect that the answer of the first question is 'NO', How could I correctly allocate a struct of multidimensional arrays in the device while using cudaMallocPitch()? and how could I properly make a cudaMemcpy() between host and device of that struct?

You can't. Not under any circumstances. The layout of your structure is statically defined by the compiler. There is nothing the pitched APIs could possibly help you with.

Some answers in stackoverflow about issues with 2D arrays suggest to use arrays flattening. I have tried it and I have no problems using
  them. Is that the only solution to properly use a struct of
  multidimensional arrays in CUDA?

Again all of that is totally irrelevant to whatever your actual problem is. Array flattening is  related to use cases like multidimensional arrays defined using arrays of pointers and nested vectors and the like. It will have no relationship to anything in the code you have shown.

Body:
I am facing some issues in kernels using a big struct including 1D, 2D and 3D arrays such as the following example:

typedef struct {
    float  data[N];
    int    map_a[N][M];
    int    map_b[N][M];
    int    map_c[B][N][M];
    ...
} my_struct;

When I use a struct like that, a kernel that do: my_struct->map_dbx][y] = value hangs the program. Of course, x and y are lower than array size. However, other kernel using the same struct writing in map_a, works as expected.
My suspicion is that wrong memory accesses are occurring in multidimensional arrays. So it would be nice is someone can help me with some doubts about multidimensional arrays allocation within a struct in CUDA:

As suggested in the CUDA Programming guide, function cudaMallocPitch() should be used to allocate arrays while guaranteeing padding needed when the array size does not match the warp size. Would it be correctly allocated this struct with cudaMalloc(&my_struct, sizeof(my_struct));? i.e. is cudaMallocPitch() used internally to ensure arrays paddding?

As I suspect that the answer of the first question is 'NO', How could I correctly allocate a struct of multidimensional arrays in the device while using cudaMallocPitch()? and how could I properly make a cudaMemcpy() between host and device of that struct?

Some answers in stackoverflow about issues with 2D arrays suggest to use arrays flattening. I have tried it and I have no problems using them. Is that the only solution to properly use a struct of multidimensional arrays in CUDA?

Another solution would be to use separate arrays instead a struct but I have a big amount of arrays that would have to be passed to kernels. I hope someone have some advice to solve this issue.


问:
How do I speed up a SQL UPDATE that also contains a JOIN on 25 million rows
the query i'd like to speed up (or replace with another process):

```<code>UPDATE en_pages, keywords
SET en_pages.keyword = keywords.keyword
WHERE en_pages.keyword_id = keywords.id
</code>```

table en_pages has the proper structure but only has non-unique page_ids and keyword_ids in it.  i'm trying to add the actual keywords(strings) to this table where they match keyword_ids.  there are 25 million rows in table en_pages that need updating.

i'm adding the keywords so that this one table can be queried in real time and return keywords (the join is obviously too slow for "real time").

we apply this query (and some others) to sub units of our larger dataset.  we do this frequently to create custom interfaces for specific sub units of our data for different user groups (sorry if that's confusing).

this all works fine if you give it an hour to run, but i'm trying to speed it up.

is there a better way to do this that would be faster using php and/or mysql?

答:
I actually don't think you can speed up the process.

You can still add brutal power to your database by cluserting new servers.

Body:
the query i'd like to speed up (or replace with another process):

UPDATE en_pages, keywords
SET en_pages.keyword = keywords.keyword
WHERE en_pages.keyword_id = keywords.id

table en_pages has the proper structure but only has non-unique page_ids and keyword_ids in it.  i'm trying to add the actual keywords(strings) to this table where they match keyword_ids.  there are 25 million rows in table en_pages that need updating.

i'm adding the keywords so that this one table can be queried in real time and return keywords (the join is obviously too slow for "real time").

we apply this query (and some others) to sub units of our larger dataset.  we do this frequently to create custom interfaces for specific sub units of our data for different user groups (sorry if that's confusing).

this all works fine if you give it an hour to run, but i'm trying to speed it up.

is there a better way to do this that would be faster using php and/or mysql?


问:
TextView setContentDescription not working
I'm trying to set the contentDescription on a TextView but it doesn't seem to be announced by TalkBack. TalkBack is only vocalizing the text content.

```<code>textView.setText("2d 9h left");
textView.setContentDescription("2days 9hours left");
</code>```

The second line above has no effect. TalkBack says, "2d 9h left".

I've also tried the following:

```<code>    ViewCompat.setAccessibilityDelegate(textView, new AccessibilityDelegateCompat()
    {
        @Override
        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event)
        {
            super.onPopulateAccessibilityEvent(host, event);
            event.getText().add(host.getContentDescription());
        }
    });
</code>```

but this results in TalkBack announcing "2days 9hours left 2d 9h left", which is also incorrect.

答:
The only that worked for me is AccessibilityDelegate (Kotlin):</p>

```<code>val accessibilityDelegate: View.AccessibilityDelegate =
            object : View.AccessibilityDelegate() {
                override fun onInitializeAccessibilityNodeInfo(v: View?, info: AccessibilityNodeInfo) {
                    super.onInitializeAccessibilityNodeInfo(v, info)
                    info.text = "Custom Text"
                }
            }
myView.accessibilityDelegate = accessibilityDelegate
</code>```

Body:
I'm trying to set the contentDescription on a TextView but it doesn't seem to be announced by TalkBack. TalkBack is only vocalizing the text content.

textView.setText("2d 9h left");
textView.setContentDescription("2days 9hours left");

The second line above has no effect. TalkBack says, "2d 9h left".

I've also tried the following:

    ViewCompat.setAccessibilityDelegate(textView, new AccessibilityDelegateCompat()
    {
        @Override
        public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event)
        {
            super.onPopulateAccessibilityEvent(host, event);
            event.getText().add(host.getContentDescription());
        }
    });

but this results in TalkBack announcing "2days 9hours left 2d 9h left", which is also incorrect.

Body:
The only that worked for me is AccessibilityDelegate (Kotlin):

val accessibilityDelegate: View.AccessibilityDelegate =
            object : View.AccessibilityDelegate() {
                override fun onInitializeAccessibilityNodeInfo(v: View?, info: AccessibilityNodeInfo) {
                    super.onInitializeAccessibilityNodeInfo(v, info)
                    info.text = "Custom Text"
                }
            }
myView.accessibilityDelegate = accessibilityDelegate


问:
Where can I find all the subprocess.call() codes (0,1,2 ..)?
I am running the following Python code and checked the docs of subprocess but still din't find the code map:

```<code>import pkg_resources
from subprocess import call

packages = [dist.project_name for dist in pkg_resources.working_set]
call("sudo pip3 install --upgrade " + ' '.join(packages), shell=True)
</code>```

Output: 2

What 2 means? Sometimes it's 0 or 1.

答:
Every Linux command executed by the shell script or user, has an exit status.

The Linux man pages stats the exit statuses of each command.

0 exit status means the command was successful without any errors.

A non-zero (1-255 values) exit status means command was failure.

Typical signals are:

0 – Success.

1 – A built-in command failure.

2 – A syntax error has occurred.

3 – Signal received that is not trapped.

Certain exit status values have been reserved for special uses:

126 - A file to be executed was found, but it was not an executable utility.

127 - A utility to be executed was not found.

128 - A command was interrupted by a signal.

A negative value -N indicates that the child was terminated by signal N (POSIX only).

The codes are platform specific, for example on Windows:

0 - Success

1 - Invalid function

2 - File not found

3 - Path not found

4 - Too many open files

etc...

From the python doc:

Some systems have a convention for assigning specific meanings to
specific exit codes, but these are generally underdeveloped; Unix
programs generally use 2 for command line syntax errors and 1 for all
other kind of errors.

Body:
I am running the following Python code and checked the docs of subprocess but still din't find the code map:

import pkg_resources
from subprocess import call

packages = [dist.project_name for dist in pkg_resources.working_set]
call("sudo pip3 install --upgrade " + ' '.join(packages), shell=True)

Output: 2

What 2 means? Sometimes it's 0 or 1.


问:
Trying to install new libraries on Spyder (Python 3.7)
I am new to python and I am having trouble downloading some new libraries that don't appear to be pre-installed.  The names of them are rasterio and retrying.  I continuously get an invalid syntax error, and I have tried using some different suggestions found online.

pip install rasterio

Above is the way I was attempting to do it, and I also tried without the pip in there, but neither option worked.  I am new enough to the language that troubleshooting is very difficult.  Any help is greatly appreciated!

答:
There are several ways to install rasterio, using anaconda you have the documentation here: https://anaconda.org/conda-forge/rasterio

If you are on windows installing rasterio using pip install can be difficult since it requires binary wheels, but here is the tutorial: https://rasterio.readthedocs.io/en/latest/installation.html

I advise you to use linux since it is much easier to install packages, you can either install a dual boot or a virtual box.


答:
The second expression is evaluated as

```<code>cout << ("John " + "Doe") << endl;
</code>```

due to the language grammar (often thought of as operator precedence).

But "John " is a const char[6] type and "Doe" is const char[4] type. Due to the +, both decay to a const char* pointer. And pointers cannot be added, so the compiler issues a diagnostic.

In the first case, the overload << on std::ostream for a const char* is used twice, with the results you expect.

Body:
I'm new to C++ and I was wondering what the difference is between these two lines:

cout << "John " << "Doe" << endl;
cout << "John " + "Doe" << endl;

The first one works but the second one doesn't. Any ideas?

Body:
The second expression is evaluated as

cout << ("John " + "Doe") << endl;

due to the language grammar (often thought of as operator precedence).

But "John " is a const char[6] type and "Doe" is const char[4] type. Due to the +, both decay to a const char* pointer. And pointers cannot be added, so the compiler issues a diagnostic.

In the first case, the overload << on std::ostream for a const char* is used twice, with the results you expect.


答:
I would do conditional aggregation with window function : </p>

```<code>sum(case when SubAccount when 'zzClosing Balance' then 0 else amount end) over (partition by MasterAccount order by Sort rows unbounded preceding)
</code>```

Title: Running Balance per Account Number

Body:
I require to have a running balance per Account Number.

I tried developing a function, but keep getting the wrong values.

See below Sample Data and how I currently calculate the Running Balance:

declare @tbl table (id int primary key identity, Sort varchar(100), MasterAccount varchar(50), SubAccount varchar(50), Amount float)
insert into @tbl (Sort,MasterAccount,SubAccount,Amount)
values
('1000_1','1000','aaOpening Balance',78137.58)
,('1000_2_13699','1000','1000',35516.34)
,('1000_2_14379','1000','1000',16675)
,('1000_2_15141','1000','1000',9252.21)
,('1000_2_15151','1000','1000',8167.3)
,('1000_2_15161','1000','1000',5729.3)
,('1000_2_15166','1000','1000',8898.7)
,('1000_2_15623','1000','1000',3335)
,('1000_2_15633','1000','1000',2620.85)
,('1000_2_15638','1000','1000',3425.39)
,('1000_2_17582','1000','1000',7281.55)
,('1000_2_18756','1000','1000',2126)
,('1000_2_19698','1000','1000',8000)
,('1000_2_19713','1000','1000',8000)
,('1000_2_19718','1000','1000',8000)
,('1000_2_19847','1000','1000',8000)
,('1000_2_20055','1000','1000',3933.1)
,('1000_2_20060','1000','1000',5304.37)
,('1000_2_20099','1000','1000',0.00000000123)
,('1000_2_20104','1000','1000',-0.00000000123)
,('1000_2_20330','1000','1000',8000)
,('1000_2_20340','1000','1000',8000)
,('1000_2_20360','1000','1000',8000)
,('1000_2_20390','1000','1000',8000)
,('1000_2_20416','1000','1000',8000)
,('1000_2_20576','1000','1000',8000)
,('1000_2_21033','1000','1000',8000)
,('1000_3','1000','zzClosing Balance',278402.69)
,('2000_1','2000','aaOpening Balance',128023.65)
,('2000_2_14381','2000','2000',15174.5)
,('2000_2_15143','2000','2000',10534.92)
,('2000_2_15153','2000','2000',9299.6)
,('2000_2_15163','2000','2000',6523.6)
,('2000_2_15168','2000','2000',10132.4)
,('2000_2_15625','2000','2000',3084.28)
,('2000_2_15635','2000','2000',2652.48)
,('2000_2_15640','2000','2000',3466.73)
,('2000_2_17584','2000','2000',8489.38)
,('2000_2_18758','2000','2000',2132.41)
,('2000_2_20057','2000','2000',3944.96)
,('2000_2_20062','2000','2000',5320.37)
,('2000_3','2000','zzClosing Balance',208779.28)

select
*
,   round(case SubAccount when 'zzClosing Balance' then 0 else sum(Amount) over(order by [Sort] rows unbounded preceding) end,2) RunningBalance
from    @tbl

The results look as following:

The problem I am facing is the balance for the second Account Number (in this case Acc Number "2000") is calculated wrong.

I require the Running Balance to Start with the value 128,023.65 and end with 208,779.28.

To give you a better idea, my expected results would look like this:

How would I get the Expected results?

Your assistance is greatly appreciated!

Body:
I would do conditional aggregation with window function :

sum(case when SubAccount when 'zzClosing Balance' then 0 else amount end) over (partition by MasterAccount order by Sort rows unbounded preceding)


问:
How to play a .mp3 file from a folder discord bot
I have a music bot in Discord and I'd like to add custom songs it can play. The problem is that there are a lot of albums I want to add and, let's say that having 100+ .mp3 files in one folder would be confusing to manage.
So how do I specify a directory for voice.play(FFmpegPCMAudio('Traveller.mp3)) to play a file from a
different folder? For example, I could use different album folders to play .mp3's from them.

```<code>@bot.command()
async def wake(ctx):
    channel = ctx.message.author.voice.channel
    try:
        voice = await channel.connect()
    except:
        pass
    voice.play(FFmpegPCMAudio('Traveller.mp3'))
</code>```

答:
To specify a specific path to a file, you can use the relative path:

voice.play(FFmpegPCMAudio("path/to/Traveller.mp3"))
```

<p>Or you can use an absolute path:</p>

<pre class="lang-py prettyprint-override"><code>voice.play(FFmpegPCMAudio("A:/path/to/Traveller.mp3"))
</code>```

Body:
I have a music bot in Discord and I'd like to add custom songs it can play. The problem is that there are a lot of albums I want to add and, let's say that having 100+ .mp3 files in one folder would be confusing to manage.
So how do I specify a directory for voice.play(FFmpegPCMAudio('Traveller.mp3)) to play a file from a
different folder? For example, I could use different album folders to play .mp3's from them.

@bot.command()
async def wake(ctx):
    channel = ctx.message.author.voice.channel
    try:
        voice = await channel.connect()
    except:
        pass
    voice.play(FFmpegPCMAudio('Traveller.mp3'))

Body:
To specify a specific path to a file, you can use the relative path:

voice.play(FFmpegPCMAudio("path/to/Traveller.mp3"))

Or you can use an absolute path:

voice.play(FFmpegPCMAudio("A:/path/to/Traveller.mp3"))