问:
MS Access Formula to Update one field in a table based on the amount "between" two other fields
I'm hoping someone can help me out.  I was hoping I could do an update query in MS Access that will update a field I have called "Materiality by Fiscal Year", based on whether or not another field "Brand Savings" is equal to or between a set of dollar ranges I have in another table.  The first table is as follows, which is the primary table:

```<code>+----------+------------+---------------+----------------------------+
|  Brand   | Project ID | Brand Savings | Materiality by Fiscal Year |
+----------+------------+---------------+----------------------------+
| aBS Corp |        121 | $110,000.00   |                            |
| aBS Corp |        151 | $17,640.67    |                            |
| aBS Corp |        152 | $5,682.37     |                            |
| aBS Corp |        154 | $564,669.58   |                            |
| aBS Corp |        157 | $5,097.00     |                            |
| aBS Corp |        159 | $33,798.00    |                            |
| aBS Corp |        190 | $200,000.00   |                            |
| aBS Corp |        193 | $250,000.00   |                            |
| aBS Corp |        194 | $366,666.67   |                            |
| aBS Corp |        197 | $90,799.00    |                            |
| aBS Corp |         20 | $14,000.00    |                            |
| aBS Corp |        219 | $2,800.00     |                            |
| aBS Corp |        222 | $132.58       |                            |
| aBS Corp |         23 | $2,068.30     |                            |
| aBS Corp |        233 | $32,908.60    |                            |
| aBS Corp |         25 | $9,143.18     |                            |
| aBS Corp |         34 | $11,674.85    |                            |
| aBS Corp |         35 | $11,615.60    |                            |
| aBS Corp |         36 | $14,959.28    |                            |
| aBS Corp |         39 | $35,000.00    |                            |
| aBS Corp |         40 | $100,000.00   |                            |
| aBS Corp |         60 | $55,000.00    |                            |
| aBS Corp |         61 | $250,094.72   |                            |
| aBS Corp |         64 | $925,000.00   |                            |
| aBS Corp |         69 | $400,000.00   |                            |
| aBS Corp |         75 | $14,625.00    |                            |
+----------+------------+---------------+----------------------------+
</code>```

The second table is a reference table:

```<code>+------------+-------------------+--------------------+----------------+
| FiscalYear |     Low Range     |     High Range     |     Result     |
+------------+-------------------+--------------------+----------------+
|       2016 |  (100,000,000.00) |         24,999.00  | 0-24.9K        |
|       2016 |  25,000.00        |         49,999.00  | 25-49.9K       |
|       2016 |  50,000.00        |         99,999.00  | 50-99.9K       |
|       2016 |  100,000.00       |  1,000,000,000.00  | 100K or Higher |
+------------+-------------------+--------------------+----------------+
</code>```

I was hoping to be able to reference the 2nd table in order to update the "Materiality by  fiscal Year" field based on whether or not the value in "Brand Savings" is BETWEEN the "Low Range" and "High Range" fields.  I couldn't figure it out however, and it's driving me crazy.  Instead, I have 4 different queries that will update the "Materiality by Fiscal Year" field (an example of the formula used in the query is below:)

IIf(([Brand Savings]>=0) And ([Brand Savings]<=24999),"$0-24.9K")

Basically what I'm asking is whether or not there's a formula I can use to reference the "Low range" and "High range" fields in the reference table to determine if the "Brand Savings" value from the main table is BETWEEN those two amounts, and if so, populate the "Materiality by Fiscal Year" field with the "Result" field from the Reference table?

Sorry, that's kind of "wordy", just don't know how else to explain it.

Thanks all!

答:
Let's assume that the table with the Brand Savings is called tblBrandSavings and the table with the ranges is called tblRanges.
Then you could use this UPDATE statement:

```<code>UPDATE tblBrandSavings, tblRanges
SET [Materiality by Fiscal Year] = tblRanges.Result
WHERE  tblBrandSavings.[Brand Savings] BETWEEN tblRanges.[Low Range] AND tblRanges.[High Range];
</code>```

The question is why you would run to store the same date in multiple tables.
I'd suggest a simple SELECT statement:

```<code>SELECT tblBrandSavings.Brand, tblBrandSavings.[Project ID], tblBrandSavings.[Brand Savings], (
SELECT tblRanges.Result
FROM tblRanges
WHERE  tblBrandSavings.[Brand Savings] BETWEEN tblRanges.[Low Range] AND tblRanges.[High Range]
 ) AS [Materiality by Fiscal Year]
FROM tblBrandSavings;
</code>```

Body:
I'm hoping someone can help me out.  I was hoping I could do an update query in MS Access that will update a field I have called "Materiality by Fiscal Year", based on whether or not another field "Brand Savings" is equal to or between a set of dollar ranges I have in another table.  The first table is as follows, which is the primary table:

+----------+------------+---------------+----------------------------+
|  Brand   | Project ID | Brand Savings | Materiality by Fiscal Year |
+----------+------------+---------------+----------------------------+
| aBS Corp |        121 | $110,000.00   |                            |
| aBS Corp |        151 | $17,640.67    |                            |
| aBS Corp |        152 | $5,682.37     |                            |
| aBS Corp |        154 | $564,669.58   |                            |
| aBS Corp |        157 | $5,097.00     |                            |
| aBS Corp |        159 | $33,798.00    |                            |
| aBS Corp |        190 | $200,000.00   |                            |
| aBS Corp |        193 | $250,000.00   |                            |
| aBS Corp |        194 | $366,666.67   |                            |
| aBS Corp |        197 | $90,799.00    |                            |
| aBS Corp |         20 | $14,000.00    |                            |
| aBS Corp |        219 | $2,800.00     |                            |
| aBS Corp |        222 | $132.58       |                            |
| aBS Corp |         23 | $2,068.30     |                            |
| aBS Corp |        233 | $32,908.60    |                            |
| aBS Corp |         25 | $9,143.18     |                            |
| aBS Corp |         34 | $11,674.85    |                            |
| aBS Corp |         35 | $11,615.60    |                            |
| aBS Corp |         36 | $14,959.28    |                            |
| aBS Corp |         39 | $35,000.00    |                            |
| aBS Corp |         40 | $100,000.00   |                            |
| aBS Corp |         60 | $55,000.00    |                            |
| aBS Corp |         61 | $250,094.72   |                            |
| aBS Corp |         64 | $925,000.00   |                            |
| aBS Corp |         69 | $400,000.00   |                            |
| aBS Corp |         75 | $14,625.00    |                            |
+----------+------------+---------------+----------------------------+

The second table is a reference table:

+------------+-------------------+--------------------+----------------+
| FiscalYear |     Low Range     |     High Range     |     Result     |
+------------+-------------------+--------------------+----------------+
|       2016 |  (100,000,000.00) |         24,999.00  | 0-24.9K        |
|       2016 |  25,000.00        |         49,999.00  | 25-49.9K       |
|       2016 |  50,000.00        |         99,999.00  | 50-99.9K       |
|       2016 |  100,000.00       |  1,000,000,000.00  | 100K or Higher |
+------------+-------------------+--------------------+----------------+

I was hoping to be able to reference the 2nd table in order to update the "Materiality by  fiscal Year" field based on whether or not the value in "Brand Savings" is BETWEEN the "Low Range" and "High Range" fields.  I couldn't figure it out however, and it's driving me crazy.  Instead, I have 4 different queries that will update the "Materiality by Fiscal Year" field (an example of the formula used in the query is below:)

IIf(([Brand Savings]>=0) And ([Brand Savings]<=24999),"$0-24.9K")

Basically what I'm asking is whether or not there's a formula I can use to reference the "Low range" and "High range" fields in the reference table to determine if the "Brand Savings" value from the main table is BETWEEN those two amounts, and if so, populate the "Materiality by Fiscal Year" field with the "Result" field from the Reference table?

Sorry, that's kind of "wordy", just don't know how else to explain it.

Thanks all!

Body:
Let's assume that the table with the Brand Savings is called tblBrandSavings and the table with the ranges is called tblRanges.
Then you could use this UPDATE statement:

UPDATE tblBrandSavings, tblRanges
SET [Materiality by Fiscal Year] = tblRanges.Result
WHERE  tblBrandSavings.[Brand Savings] BETWEEN tblRanges.[Low Range] AND tblRanges.[High Range];

The question is why you would run to store the same date in multiple tables.
I'd suggest a simple SELECT statement:

SELECT tblBrandSavings.Brand, tblBrandSavings.[Project ID], tblBrandSavings.[Brand Savings], (
SELECT tblRanges.Result
FROM tblRanges
WHERE  tblBrandSavings.[Brand Savings] BETWEEN tblRanges.[Low Range] AND tblRanges.[High Range]
 ) AS [Materiality by Fiscal Year]
FROM tblBrandSavings;


来源: stackexchange

问:
Creating subset list , in a list based on length of words
I have this code here: which takes user input and adds it to a list until they input to stop. At that point, it sorts the list items based on length.

What I am trying to do is put each word the user enters into a list of words with the same length. Like 2-letter words are put into one list, 3-letter words are put into another list.

When complete, I'm trying to return a list containing all of the individual word lists that were created.

So far all I have achieved is organizing them and then adding them to another list that outputs the list as many time as word entered.

```<code>def wordsList():
    stop = "stop"

    sentence = []
    sentence2 = []
    while True:
        word = input("Enter a word: ")
        if word == stop:
            # exit the loop
            break
        sentence.append(word)

        sentence.sort(key=len)
        cat= len(sentence)
        for sublist in sentence:

            sentence.append(sentence)
            # sublist.insert(sentence)
        # sentence2=[sentence]

    # print(" ".join(sentence)) # Goes through the list and finds a smaller word and convert the list of words into a single string, each word separated by a space.
    print(sentence)

wordsList()
</code>```

答:
Welcome to StackOverflow,

I'd recommend using a dictionary where the keys are the length of the words and the values are the list of words that have that length. Here is a potential implementation:

```<code>import collections
STOP = "stop"

def wordsList():
    words = collections.defaultdict(list)
    while True:
        word = input("Enter a word: ")
        if word == STOP:
            break
        length = len(word)
        words[length].append(word)
    return list(words.values())
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this code here: which takes user input and adds it to a list until they input to stop. At that point, it sorts the list items based on length.

What I am trying to do is put each word the user enters into a list of words with the same length. Like 2-letter words are put into one list, 3-letter words are put into another list.

When complete, I'm trying to return a list containing all of the individual word lists that were created.

So far all I have achieved is organizing them and then adding them to another list that outputs the list as many time as word entered.

def wordsList():
    stop = "stop"

    sentence = []
    sentence2 = []
    while True:
        word = input("Enter a word: ")
        if word == stop:
            # exit the loop
            break
        sentence.append(word)

        sentence.sort(key=len)
        cat= len(sentence)
        for sublist in sentence:

            sentence.append(sentence)
            # sublist.insert(sentence)
        # sentence2=[sentence]

    # print(" ".join(sentence)) # Goes through the list and finds a smaller word and convert the list of words into a single string, each word separated by a space.
    print(sentence)

wordsList()

Body:
Welcome to StackOverflow,

I'd recommend using a dictionary where the keys are the length of the words and the values are the list of words that have that length. Here is a potential implementation:

import collections
STOP = "stop"

def wordsList():
    words = collections.defaultdict(list)
    while True:
        word = input("Enter a word: ")
        if word == STOP:
            break
        length = len(word)
        words[length].append(word)
    return list(words.values())


问:
Multiple mat-table with MatSort within the same component
I have 2 material 2 tables in the same component with sorting. I cannot find a way to assign the MatSort directive to its own table. I'm only able to use MatSort on the first table and the second table doesn't recognize there is a MatSort on it. Does anyone know how to configure two tables with sorting in the same component?

I've tried defining the ViewChild with different names, but it didn't work.

```<code>@ViewChild('hBSort') hBSort: MatSort;
@ViewChild('sBSort') sBSort: MatSort;

this.hBSource = new HBDataSource(this.hBDatabase, this.hBPaginator,
this.hBSort);
this.sBSource = new SBDataSource(this.sBDatabase, this.sBPaginator,
this.sBSort);

Table 1
const displayDataChanges = [
   this.hBPaginator.page,
   this.hBSort.sortChange,
   this._filterChange
];

Table 2
const displayDataChanges = [
   this.sBPaginator.page,
   this.sBSort.sortChange,
   this._filterChange
];

Table 1
<mat-table #hBtable [dataSource]="hBSource" matSort style="min-width:
740px;">
    <ng-container matColumnDef="domain">
        <mat-header-cell *matHeaderCellDef mat-sort-header> {{'list.domain' | translate}} </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.domain}} </mat-cell>
    </ng-container>
    <ng-container matColumnDef="general">
        <mat-header-cell *matHeaderCellDef mat-sort-header> {{'list.general' | translate}} </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.general.gNum}} ({{row.general.gPct | number: '1.1-2'}}%) </mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="hBColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: hBColumns;"></mat-row>
 </mat-table>

Table 2
<mat-table #sBSort [dataSource]="sBSource" matSort style="min-width: 1200px;">
      <ng-container matColumnDef="domain">
        <mat-header-cell *matHeaderCellDef mat-sort-header> {{'list.domain' | translate}} </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.domain}} </mat-cell>
      </ng-container>
      <ng-container matColumnDef="general">
        <mat-header-cell *matHeaderCellDef mat-sort-header> {{'list.general' | translate}} </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.general.gNum}} ({{row.general.gPct | number: '1.1-2'}}%) </mat-cell>
      </ng-container>
      <mat-header-row *matHeaderRowDef="sBColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: sBColumns;"></mat-row>
</mat-table>
</code>```

答:
Edit:

I believe you need:

```<code>@ViewChild(MatSort) sort: MatSort;
</code>```

above your:

```<code>@ViewChild('hBSort') hBSort: MatSort;
@ViewChild('sBSort') sBSort: MatSort;
</code>```

Then:

```<code>ngAfterViewInit() {
    this.hBSource.sort = this.sort;
    this.sBSource.sort = this.sort;
  }
</code>```

Assuming that your HBDataSource and SBDataSource both export MatTableDataSource();

I'm referencing these sources:

https://material.angular.io/components/sort/overview
https://github.com/angular/material2/blob/master/src/demo-app/table/table-demo.ts

Body:
I have 2 material 2 tables in the same component with sorting. I cannot find a way to assign the MatSort directive to its own table. I'm only able to use MatSort on the first table and the second table doesn't recognize there is a MatSort on it. Does anyone know how to configure two tables with sorting in the same component?

I've tried defining the ViewChild with different names, but it didn't work.

@ViewChild('hBSort') hBSort: MatSort;
@ViewChild('sBSort') sBSort: MatSort;

this.hBSource = new HBDataSource(this.hBDatabase, this.hBPaginator,
this.hBSort);
this.sBSource = new SBDataSource(this.sBDatabase, this.sBPaginator,
this.sBSort);

Table 1
const displayDataChanges = [
   this.hBPaginator.page,
   this.hBSort.sortChange,
   this._filterChange
];

Table 2
const displayDataChanges = [
   this.sBPaginator.page,
   this.sBSort.sortChange,
   this._filterChange
];

Table 1
<mat-table #hBtable [dataSource]="hBSource" matSort style="min-width:
740px;">
    <ng-container matColumnDef="domain">
        <mat-header-cell *matHeaderCellDef mat-sort-header> {{'list.domain' | translate}} </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.domain}} </mat-cell>
    </ng-container>
    <ng-container matColumnDef="general">
        <mat-header-cell *matHeaderCellDef mat-sort-header> {{'list.general' | translate}} </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.general.gNum}} ({{row.general.gPct | number: '1.1-2'}}%) </mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="hBColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: hBColumns;"></mat-row>
 </mat-table>

Table 2
<mat-table #sBSort [dataSource]="sBSource" matSort style="min-width: 1200px;">
      <ng-container matColumnDef="domain">
        <mat-header-cell *matHeaderCellDef mat-sort-header> {{'list.domain' | translate}} </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.domain}} </mat-cell>
      </ng-container>
      <ng-container matColumnDef="general">
        <mat-header-cell *matHeaderCellDef mat-sort-header> {{'list.general' | translate}} </mat-header-cell>
        <mat-cell *matCellDef="let row"> {{row.general.gNum}} ({{row.general.gPct | number: '1.1-2'}}%) </mat-cell>
      </ng-container>
      <mat-header-row *matHeaderRowDef="sBColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: sBColumns;"></mat-row>
</mat-table>

Body:
Edit:

I believe you need:

@ViewChild(MatSort) sort: MatSort;

above your:

@ViewChild('hBSort') hBSort: MatSort;
@ViewChild('sBSort') sBSort: MatSort;

Then:

ngAfterViewInit() {
    this.hBSource.sort = this.sort;
    this.sBSource.sort = this.sort;
  }

Assuming that your HBDataSource and SBDataSource both export MatTableDataSource();

I'm referencing these sources:

https://material.angular.io/components/sort/overview
https://github.com/angular/material2/blob/master/src/demo-app/table/table-demo.ts


问:
DynamoDb: Delete all items having same Hash Key
Consider the following table:

```<code>Table (documentId : Hash Key, userId: Range Key)
</code>```

How can I write a code to delete all the items having the same documentId and preferably without retrieving the items.

答:
If you want to delete only by hash key, you need to query records first and then use batchDelete to delete all the records.

```<code>HashMap<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
eav.put(":v1", new AttributeValue().withS(value));
DynamoDBQueryExpression<DocumentTable> queryExpression = new DynamoDBQueryExpression<DocumentTable>()
            .withKeyConditionExpression("documentId = :v1")
            .withExpressionAttributeValues(eav);
List<DocumentTable> ddbResults = dynamoDBMapper.query(DocumentTable.class, queryExpression);
dynamoDBMapper.batchDelete(ddbResults);
</code>```

I would like to call out here that deleteItem deletes only one item at a time and both hash key and range key needs to be specified for this.

Body:
Consider the following table:

Table (documentId : Hash Key, userId: Range Key)

How can I write a code to delete all the items having the same documentId and preferably without retrieving the items.

Body:
If you want to delete only by hash key, you need to query records first and then use batchDelete to delete all the records.

HashMap<String, AttributeValue> eav = new HashMap<String, AttributeValue>();
eav.put(":v1", new AttributeValue().withS(value));
DynamoDBQueryExpression<DocumentTable> queryExpression = new DynamoDBQueryExpression<DocumentTable>()
            .withKeyConditionExpression("documentId = :v1")
            .withExpressionAttributeValues(eav);
List<DocumentTable> ddbResults = dynamoDBMapper.query(DocumentTable.class, queryExpression);
dynamoDBMapper.batchDelete(ddbResults);

I would like to call out here that deleteItem deletes only one item at a time and both hash key and range key needs to be specified for this.


问:
can't add all files to git due to permissions
I want to add all the files in the current directory to git:

```<code>git add .
error: open(".mysql_history"): Permission denied
fatal: unable to index file .mysql_history
</code>```

That's fine. That file happens to be in this directory and owned by root. I want to add all other files.  Is there a way to do that without having to manually add each file by hand?

I know that I could add the file to exclude or .gitignore, but I'd like to have it just ignore things based on permissions (there's a good chance other files like this will end up in the directory, and adding them to .gitignore all the time is a pain).

答:
I was using @matli's solution but still having troubles sometimes.

I ended up using

```<code>git add --ignore-errors --force .
</code>```

OwnerDisplayName: singpolyma

Body:
I want to add all the files in the current directory to git:

git add .
error: open(".mysql_history"): Permission denied
fatal: unable to index file .mysql_history

That's fine. That file happens to be in this directory and owned by root. I want to add all other files.  Is there a way to do that without having to manually add each file by hand?

I know that I could add the file to exclude or .gitignore, but I'd like to have it just ignore things based on permissions (there's a good chance other files like this will end up in the directory, and adding them to .gitignore all the time is a pain).

LastEditorDisplayName: singpolyma

Body:
I was using @matli's solution but still having troubles sometimes.

I ended up using

git add --ignore-errors --force .

ContentLicense: CC BY-SA 4.0


问:
I can't download Pod ParallaxHeader by Github
My question is about an Pod of Github.

I have a problem with a version. I can't download it! :(

https://github.com/romansorochak/ParallaxHeader (I want version of Swift3 -> 1.0.6)

I tried this: pod 'ParallaxHeader', '~> 1.0.6'

But Promt shows this error:

[!] Unable to find a specification for ParallaxHeader (~> 1.0.6)

Somebody knows whats happen??

Thank you so much!

答:
I resolved the issue like that with these steps:

Open terminal.

Go to your project path.

Write:

pod repo update

pod install.


问:
How to generate a new Tensor with different vectors in PyTorch?
I want to generate new a○b vector with a and b (○ means element wise multiply). My code is below, but the performance looks bad because of for. Are there any efficient way?

```<code>a = torch.rand(batch_size, a_len, hid_dim)
b = torch.rand(batch_size, b_len, hid_dim)
# a_elmwise_mul_b = torch.zeros(batch_size, a_len, b_len, hid_dim)
for sample in range(batch_size):
    for ai in range(a_len):
        for bi in range(b_len):
            a_elmwise_mul_b[sample, ai, bi] = torch.mul(a[sample, ai], b[sample, bi])
</code>```

Update

I updated my code refer to Ahmad! Thank you.

```<code>N = 16
hid_dim = 50
a_seq_len = 10
b_seq_len = 20
a = torch.randn(N, a_seq_len, hid_dim)
b = torch.randn(N, b_seq_len, hid_dim)
shape = (N, a_seq_len, b_seq_len, hid_dim)

a_dash = a.unsqueeze(2) # (N, a_len, 1,     hid_dim)
b_dash = b.unsqueeze(1) # (N, 1,     b_len, hid_dim)
a_dash = a_dash.expand(shape)
b_dash = b_dash.expand(shape)
print(a_dash.size(), b_dash.size())
mul = a_dash * b_dash
print(mul.size())
----------
torch.Size([16, 10, 20, 50]) torch.Size([16, 10, 20, 50])
torch.Size([16, 10, 20, 50])
</code>```

答:
From your problem definition, it looks like you want to multiply two tensors, say A and B of shape AxE and BxE and want to get a tensor of shape AxBxE. It means you want to multiply, each row of tensor A with the whole tensor B. If it is correct, then we don't call it element-wise multiplication.

You can accomplish your goal as follows.

```<code>import torch

# batch_size = 16, a_len = 10, b_len = 20, hid_dim = 50
a = torch.rand(16, 10, 50)
b = torch.rand(16, 20, 50)

c = a.unsqueeze(2).expand(*a.size()[:-1], b.size(1), a.size()[-1])
d = b.unsqueeze(1).expand(b.size()[0], a.size(1), *b.size()[1:])
print(c.size(), d.size())
print(c.size(), d.size())

mul = c * d       # shape of c, d: 16 x 10 x 20 x 50
print(mul.size()) # 16 x 10 x 20 x 50
</code>```

Here, mul tensor is your desired result. Just to clarify, the above two lines realted to c and d computation, are equivalent to:

```<code>c = a.unsqueeze(2).expand(a.size(0), a.size(1), b.size(1), a.size(2))
d = b.unsqueeze(1).expand(b.size(0), a.size(1), b.size(1), b.size(2))
</code>```

Body:
I want to generate new a○b vector with a and b (○ means element wise multiply). My code is below, but the performance looks bad because of for. Are there any efficient way?

a = torch.rand(batch_size, a_len, hid_dim)
b = torch.rand(batch_size, b_len, hid_dim)
# a_elmwise_mul_b = torch.zeros(batch_size, a_len, b_len, hid_dim)
for sample in range(batch_size):
    for ai in range(a_len):
        for bi in range(b_len):
            a_elmwise_mul_b[sample, ai, bi] = torch.mul(a[sample, ai], b[sample, bi])

Update

I updated my code refer to Ahmad! Thank you.

N = 16
hid_dim = 50
a_seq_len = 10
b_seq_len = 20
a = torch.randn(N, a_seq_len, hid_dim)
b = torch.randn(N, b_seq_len, hid_dim)
shape = (N, a_seq_len, b_seq_len, hid_dim)

a_dash = a.unsqueeze(2) # (N, a_len, 1,     hid_dim)
b_dash = b.unsqueeze(1) # (N, 1,     b_len, hid_dim)
a_dash = a_dash.expand(shape)
b_dash = b_dash.expand(shape)
print(a_dash.size(), b_dash.size())
mul = a_dash * b_dash
print(mul.size())
----------
torch.Size([16, 10, 20, 50]) torch.Size([16, 10, 20, 50])
torch.Size([16, 10, 20, 50])

Body:
From your problem definition, it looks like you want to multiply two tensors, say A and B of shape AxE and BxE and want to get a tensor of shape AxBxE. It means you want to multiply, each row of tensor A with the whole tensor B. If it is correct, then we don't call it element-wise multiplication.

You can accomplish your goal as follows.

import torch

# batch_size = 16, a_len = 10, b_len = 20, hid_dim = 50
a = torch.rand(16, 10, 50)
b = torch.rand(16, 20, 50)

c = a.unsqueeze(2).expand(*a.size()[:-1], b.size(1), a.size()[-1])
d = b.unsqueeze(1).expand(b.size()[0], a.size(1), *b.size()[1:])
print(c.size(), d.size())
print(c.size(), d.size())

mul = c * d       # shape of c, d: 16 x 10 x 20 x 50
print(mul.size()) # 16 x 10 x 20 x 50

Here, mul tensor is your desired result. Just to clarify, the above two lines realted to c and d computation, are equivalent to:

c = a.unsqueeze(2).expand(a.size(0), a.size(1), b.size(1), a.size(2))
d = b.unsqueeze(1).expand(b.size(0), a.size(1), b.size(1), b.size(2))


问:
SQL: Creating a new table for a query result grouping by repeated column values
sorry for the weird question but I didn't know how to exactly ask this. Or if there are similar questions to look at, please let me know.

I have the following table in my database. Basically it stores the prices of an item at different stores. Every store will always have the same items, meaning if store_id 3, 4,... n values are later added, they will have the same item_ids

```<code>+----+---------+----------+---------+
| id | item_id | store_id |  price  |
+----+---------+----------+---------+
|  1 |       1 |        1 |    74.99|
|  2 |       2 |        1 |    25.99|
|  3 |       3 |        1 |    89.99|
|  4 |       1 |        2 |    69.99|
|  5 |       2 |        2 |    39.99|
|  6 |       3 |        2 |    95.99|
+----+---------+----------+---------+
</code>```

My sql knowledge is pretty basic, but I was wondering if there is a way to get this result.

I need to add every store_id value as a column and then get the price value for the item_id at every store available and put that in a single row. Since there could be more values for store_id, every different value

```<code>+---------+-----------+-----------+
| item_id | price for | price for |
|         | store_id 1| store_id 2|
+---------+-----------+-----------+
|       1 |     74.99 |      69.99|
|       2 |     25.99 |      39.99|
|       3 |     89.99 |      95.99|
+---------+-----------+-----------+
</code>```

Thanks.

答:
you could use a self join eg:</p>

```<code>  select a.item_id, a.price as price_store_1, b.price  as price_store_2
  from my_table a
  inner join my_table b on a.item_id = b.item_1 and b.store_id = 2
  where a.store_id = 1
</code>```

Body:
sorry for the weird question but I didn't know how to exactly ask this. Or if there are similar questions to look at, please let me know.

I have the following table in my database. Basically it stores the prices of an item at different stores. Every store will always have the same items, meaning if store_id 3, 4,... n values are later added, they will have the same item_ids

+----+---------+----------+---------+
| id | item_id | store_id |  price  |
+----+---------+----------+---------+
|  1 |       1 |        1 |    74.99|
|  2 |       2 |        1 |    25.99|
|  3 |       3 |        1 |    89.99|
|  4 |       1 |        2 |    69.99|
|  5 |       2 |        2 |    39.99|
|  6 |       3 |        2 |    95.99|
+----+---------+----------+---------+

My sql knowledge is pretty basic, but I was wondering if there is a way to get this result.

I need to add every store_id value as a column and then get the price value for the item_id at every store available and put that in a single row. Since there could be more values for store_id, every different value

+---------+-----------+-----------+
| item_id | price for | price for |
|         | store_id 1| store_id 2|
+---------+-----------+-----------+
|       1 |     74.99 |      69.99|
|       2 |     25.99 |      39.99|
|       3 |     89.99 |      95.99|
+---------+-----------+-----------+

Thanks.

Body:
you could use a self join eg:

  select a.item_id, a.price as price_store_1, b.price  as price_store_2
  from my_table a
  inner join my_table b on a.item_id = b.item_1 and b.store_id = 2
  where a.store_id = 1


问:
While Loop to Iterate through Databases
I was wondering if someone could help me with creating a while loop to iterate through several databases to obtain data from one table from two columns.  this is was I have done so far.  nothing works because i do not know how to make the select statement work through each database with regards to the table that I am querying from each database (dbo.tbldoc)</p>

```<code>DECLARE @Loop int
DECLARE @DBName varchar(300)
DECLARE @SQL varchar(max)
DECLARE @tableName VARCHAR(255)

SET @Loop = 1
SET @DBName = ''

   WHILE @Loop = 1
BEGIN

   SELECT [name] FROM sys.databases
   WHERE [name] like 'z%' and create_date between '2010-10-17' and '2011-01-15'
   ORDER BY [name]

      SET @Loop = @@ROWCOUNT

   IF @Loop = 0
      BREAK

   SET @SQL = ('USE ['+ @DBNAME +']')
      IF EXISTS(SELECT [name] FROM sys.tables WHERE name != 'dbo.tbldoc' )
                  BEGIN
               SELECT SUM(PGCOUNT), CREATED FROM **dbo.tbldoc**
            END
            ELSE
            --BEGIN
               PRINT 'ErrorLog'
            END
</code>```

答:
```<code>CREATE TABLE #T
(dbname sysname NOT NULL PRIMARY KEY,
SumPGCOUNT INT,
CREATED DATETIME)

DECLARE @Script NVARCHAR(MAX) = ''

SELECT @Script = @Script + '

USE ' + QUOTENAME(name) + '
IF EXISTS(SELECT * FROM sys.tables WHERE OBJECT_ID=OBJECT_ID(''dbo.tbldoc''))
  INSERT INTO #T
  SELECT db_name() AS dbname, SUM(PGCOUNT) AS SumPGCOUNT, CREATED
  FROM dbo.tbldoc
  GROUP BY CREATED;
  '
FROM sys.databases
WHERE state=0 AND user_access=0 and has_dbaccess(name) = 1
 AND [name] like 'z%' and create_date between '2010-10-17' and '2011-01-15'
ORDER BY [name]

IF (@@ROWCOUNT > 0)
 BEGIN
 --PRINT @Script
 EXEC (@Script)
 SELECT * FROM #T
 END

 DROP TABLE #T
</code>```

ContentLicense: CC BY-SA 2.5

Title: While Loop to Iterate through Databases

Body:
I was wondering if someone could help me with creating a while loop to iterate through several databases to obtain data from one table from two columns.  this is was I have done so far.  nothing works because i do not know how to make the select statement work through each database with regards to the table that I am querying from each database (dbo.tbldoc)

DECLARE @Loop int
DECLARE @DBName varchar(300)
DECLARE @SQL varchar(max)
DECLARE @tableName VARCHAR(255)

SET @Loop = 1
SET @DBName = ''

   WHILE @Loop = 1
BEGIN

   SELECT [name] FROM sys.databases
   WHERE [name] like 'z%' and create_date between '2010-10-17' and '2011-01-15'
   ORDER BY [name]

      SET @Loop = @@ROWCOUNT

   IF @Loop = 0
      BREAK

   SET @SQL = ('USE ['+ @DBNAME +']')
      IF EXISTS(SELECT [name] FROM sys.tables WHERE name != 'dbo.tbldoc' )
                  BEGIN
               SELECT SUM(PGCOUNT), CREATED FROM **dbo.tbldoc**
            END
            ELSE
            --BEGIN
               PRINT 'ErrorLog'
            END


问:
Get child component inside of a @ChildComponent Angular
I'm trying to get a children component of another component, is it possible? For example, I have this QueryList:

```<code>@ContentChildren(SysColumn) syscolumns: QueryList<SysColumn>;
</code>```

It will create a QueryList of all the SysColumns classes instanciated, that's perfectp, but i need to get a list of the child components inside of SysColums... The HTML will be like this:

```<code><parent>
 <sys-column>
  <child></child>
 </sys-column>
 <sys-column>
   <child></child>
 </sys-column>
</parent>
</code>```

If I do a Foreach of the QueryList it will show the two SysColms, but now I need to have the inner components. How can I achieve it

答:
If you want to query Child components, @ContentChildren() needs to look like

```<code>@ContentChildren(Child, {descendants: true}) children: QueryList<Child>;
</code>```

{descendants: true} might be the default anyway (don't remember)

Body:
I'm trying to get a children component of another component, is it possible? For example, I have this QueryList:

@ContentChildren(SysColumn) syscolumns: QueryList<SysColumn>;

It will create a QueryList of all the SysColumns classes instanciated, that's perfectp, but i need to get a list of the child components inside of SysColums... The HTML will be like this:

<parent>
 <sys-column>
  <child></child>
 </sys-column>
 <sys-column>
   <child></child>
 </sys-column>
</parent>

If I do a Foreach of the QueryList it will show the two SysColms, but now I need to have the inner components. How can I achieve it

Body:
If you want to query Child components, @ContentChildren() needs to look like

@ContentChildren(Child, {descendants: true}) children: QueryList<Child>;

{descendants: true} might be the default anyway (don't remember)


问:
ASP.Net MVC RouteAttribute Error with Route Parameter
I'm getting a lot of different errors while trying to add Route mapping to a certain action!

I'm trying to get this route for GET /Admin/Users/User/1
and POST /Admin/Users/User

But sadly there is already a User property in Controller!
So i cannot use public ActionResult User(long id) because i need to hide the user property (that i need to keep because it's the IPrincipal of the Controller and i still get the same error).

Defining route this way :

```<code>// First in RouteConfig
routes.MapMvcAttributeRoutes();

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

// Then i'm registering my Areas.
</code>```

this controller is in Admin Areas.
UsersController : Controller

```<code>[HttpGet]
[Route(Name = "User/{id:long}")]
public ActionResult GetUser(long id)
{
    var model = new UserViewModel
    {
        User = _usersService.GetUser(id),
        Roles = _rolesService.GetRoleDropdown()
    };

    return View("User");
}

[HttpPost]
[Route(Name = "User")]
public ActionResult GetUser(UserViewModel model)
{
    if (ModelState.IsValid)
    {
        _usersService.UpdateUserRoles(model.User);
        return RedirectToAction("Index");
    }

    return View("User", model);
}
</code>```

Here is the error i'm getting :

```<code>The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int64' for method 'System.Web.Mvc.ActionResult User(Int64)' in 'MyProjectName.Web.Areas.Admin.Controllers.UsersController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
</code>```

I'm not sure to really understand what's wrong!

I checked this page that explain the attributes and i see nothing wrong
https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/

EDIT 1

It still doesn't work, i changed my registration to

```<code>routes.MapMvcAttributeRoutes();

AreaRegistration.RegisterAllAreas();

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
</code>```

Here is my full controller code because now it doesn't work for my Index action that was not in the initial code.

```<code>[RouteArea("Admin")]
[RoutePrefix("Users")]
public class UsersController : Controller
{
    private readonly IUsersService _usersService;
    private readonly IRolesService _rolesService;

    public UsersController(
        IUsersService usersService,
        IRolesService rolesService)
    {
        _usersService = usersService;
        _rolesService = rolesService;
    }

    [HttpGet]
    [Route(Name = "Index")]
    public ActionResult Index()
    {
        var model = new UsersViewModel
        {
            Users = _usersService.GetUsers()
        };

        return View(model);
    }

    [HttpGet]
    [Route(Name = "User/{id:long}")]
    public new ActionResult User(long id)
    {
        var model = new UserViewModel
        {
            User = _usersService.GetUser(id),
            Roles = _rolesService.GetRoleDropdown()
        };

        return View("User");
    }

    [HttpPost]
    [Route(Name = "User")]
    public new ActionResult User(UserViewModel model)
    {
        if (ModelState.IsValid)
        {
            _usersService.UpdateUserRoles(model.User);
            return RedirectToAction("Index");
        }

        return View("User", model);
    }
}
</code>```

Now, i'm getting while trying to go to my index action:

The current request is ambiguous between the following action methods:
  System.Web.Mvc.ActionResult Index() on type
  EspaceBiere.Web.Areas.Admin.Controllers.UsersController
  System.Web.Mvc.ActionResult User(Int64) on type
  EspaceBiere.Web.Areas.Admin.Controllers.UsersController
  System.Web.Mvc.ActionResult
  User(EspaceBiere.Web.Areas.Admin.ViewModels.Users.UserViewModel) on
  type EspaceBiere.Web.Areas.Admin.Controllers.UsersController

and this while trying to go to User Action

A public action method 'User' was not found on controller
  'EspaceBiere.Web.Areas.Admin.Controllers.UsersController'.

And my link to the index action was :

tried with   /Admin/Users   for my Index Action

tried with   /Admin/Users/User/1   for User Action

EDIT 2

Ok, my index is now working perfectly, but my user action still is not working!
I've removed all the Name properties of the RouteAttribute to keep them in the constructor (as template)  ->         [Route("User/{id:long}")]

Sorry, if i didn't see them on first read!

Here is the link to the action

```<code>                    <a href="@Url.Action("User", "Users", new { Area = "Admin", id = user.UserId })" class="btn btn-warning">
                    <i class="fa fa-pencil"></i>
                </a>
</code>```

Here is the error

```<code>No matching action was found on controller 'EspaceBiere.Web.Areas.Admin.Controllers.UsersController'. This can happen when a controller uses RouteAttribute for routing, but no action on that controller matches the request.
</code>```

It does work if i write in the URL   /Admin/Users/User/1
So how should i write my Url.Action ?

答:
Nice, </p>

```<code>    [HttpPost]
    [Route("User")]
    public ActionResult PostUser(UserViewModel model) {
        if (ModelState.IsValid) {
            _usersService.UpdateUserRoles(model.User);
            return RedirectToAction("Index");
        }enter code here

        return View("User", model);
    }
</code>```

Body:
I'm getting a lot of different errors while trying to add Route mapping to a certain action!

I'm trying to get this route for GET /Admin/Users/User/1
and POST /Admin/Users/User

But sadly there is already a User property in Controller!
So i cannot use public ActionResult User(long id) because i need to hide the user property (that i need to keep because it's the IPrincipal of the Controller and i still get the same error).

Defining route this way :

// First in RouteConfig
routes.MapMvcAttributeRoutes();

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

// Then i'm registering my Areas.

this controller is in Admin Areas.
UsersController : Controller

[HttpGet]
[Route(Name = "User/{id:long}")]
public ActionResult GetUser(long id)
{
    var model = new UserViewModel
    {
        User = _usersService.GetUser(id),
        Roles = _rolesService.GetRoleDropdown()
    };

    return View("User");
}

[HttpPost]
[Route(Name = "User")]
public ActionResult GetUser(UserViewModel model)
{
    if (ModelState.IsValid)
    {
        _usersService.UpdateUserRoles(model.User);
        return RedirectToAction("Index");
    }

    return View("User", model);
}

Here is the error i'm getting :

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int64' for method 'System.Web.Mvc.ActionResult User(Int64)' in 'MyProjectName.Web.Areas.Admin.Controllers.UsersController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

I'm not sure to really understand what's wrong!

I checked this page that explain the attributes and i see nothing wrong
https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/

EDIT 1

It still doesn't work, i changed my registration to

routes.MapMvcAttributeRoutes();

AreaRegistration.RegisterAllAreas();

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Here is my full controller code because now it doesn't work for my Index action that was not in the initial code.

[RouteArea("Admin")]
[RoutePrefix("Users")]
public class UsersController : Controller
{
    private readonly IUsersService _usersService;
    private readonly IRolesService _rolesService;

    public UsersController(
        IUsersService usersService,
        IRolesService rolesService)
    {
        _usersService = usersService;
        _rolesService = rolesService;
    }

    [HttpGet]
    [Route(Name = "Index")]
    public ActionResult Index()
    {
        var model = new UsersViewModel
        {
            Users = _usersService.GetUsers()
        };

        return View(model);
    }

    [HttpGet]
    [Route(Name = "User/{id:long}")]
    public new ActionResult User(long id)
    {
        var model = new UserViewModel
        {
            User = _usersService.GetUser(id),
            Roles = _rolesService.GetRoleDropdown()
        };

        return View("User");
    }

    [HttpPost]
    [Route(Name = "User")]
    public new ActionResult User(UserViewModel model)
    {
        if (ModelState.IsValid)
        {
            _usersService.UpdateUserRoles(model.User);
            return RedirectToAction("Index");
        }

        return View("User", model);
    }
}

Now, i'm getting while trying to go to my index action:

The current request is ambiguous between the following action methods:
  System.Web.Mvc.ActionResult Index() on type
  EspaceBiere.Web.Areas.Admin.Controllers.UsersController
  System.Web.Mvc.ActionResult User(Int64) on type
  EspaceBiere.Web.Areas.Admin.Controllers.UsersController
  System.Web.Mvc.ActionResult
  User(EspaceBiere.Web.Areas.Admin.ViewModels.Users.UserViewModel) on
  type EspaceBiere.Web.Areas.Admin.Controllers.UsersController

and this while trying to go to User Action

A public action method 'User' was not found on controller
  'EspaceBiere.Web.Areas.Admin.Controllers.UsersController'.

And my link to the index action was :

tried with   /Admin/Users   for my Index Action

tried with   /Admin/Users/User/1   for User Action

EDIT 2

Ok, my index is now working perfectly, but my user action still is not working!
I've removed all the Name properties of the RouteAttribute to keep them in the constructor (as template)  ->         [Route("User/{id:long}")]

Sorry, if i didn't see them on first read!

Here is the link to the action

Here is the error

No matching action was found on controller 'EspaceBiere.Web.Areas.Admin.Controllers.UsersController'. This can happen when a controller uses RouteAttribute for routing, but no action on that controller matches the request.

It does work if i write in the URL   /Admin/Users/User/1
So how should i write my Url.Action ?

Body:
Nice,

    [HttpPost]
    [Route("User")]
    public ActionResult PostUser(UserViewModel model) {
        if (ModelState.IsValid) {
            _usersService.UpdateUserRoles(model.User);
            return RedirectToAction("Index");
        }enter code here

        return View("User", model);
    }


问:
Building a React Native bridge but a file within the framework can't be found
I'm trying to build a React Native wrapper for the RichRelevance iOS SDK.

I've created the wrapper project and imported it into my React Native app. I'm using Cocoapods to add the RichRelevance SDK to the app

I'm now attempting to import the RichRelevance SDK into the wrapper project using:

    #import <RichRelevanceSDK/RichRelevanceSDK.h>

The problem I have is that when the compiler attempts to compile the RichRelevanceSDK, it throws an error that one of the files is not found:

Line 63 is the original import that was written in the SDK. I added Line 62 to show that the file can be found if the type of import is changed.  However, this isn't really an option since I don't want to modify the SDK (I don't own it).

In either type of import, I'm able to cmd+click the file and go to the definition.  So XCode seems to know about the file.  Additionally, I see the file in the Project browser under:

    Pods -> Pods -> RichRelevanceSDK -> RCHImportable.h

The primary difference with this file is that, if I look in the file browser, that file is located in a sub-folder, relative to all of the other files in the SDK:

I'm hoping there's a way to change my wrapper project so that this file can be found, so I don't have to edit or fork the SDK files.

So far, I've attempted to update the various Search Paths in my wrapper project but with no luck.  I've added the following two paths to all of the Search Paths:

UPDATE:
I was able to make some progress and I can now get it to compile.

I ended up:

cloning the SDK's repo to my computer

removing the SDK from the Podfile

adding the SDK's xcodeproj file to MyApp/Libraries

adding the SDK.framework file to MyApp -> Embedded Binaries

I can now import the SDK into my bridge module

I would still prefer to find a better way to do this though. This method either involves me committing the SDK to our repo or asking all of my colleagues to clone the repo to their machine. NPM can't seem to install the repo; my guess is this is due to the repo missing a package.json file

答:
There does appear to be something wrong with the packaging, as the header in question would appear to be captured in the public_header_files glob in the Podspec.

However, I think more direct path is to simply include the RCHSDK.h file, as RCHSDK is the entrypoint to the SDK functions. The RichRelevanceSDK.h serves primarily as a shorthand for importing additional headers versus specifying them individually.

Alternatively, you can follow the instructions in Include of non-modular header inside framework module, this seemed to correct the issue in local tests.


问:
Extract input parameter name from lambda expression
I am working with system.linq.dynamic.core
and nhibernate linq. Now I want to pass two dynamic linq expression to a method. One for the parent table and one for a joined child list.
The input parameter for both expressions are random, so an expression could be

"x => x.Name == \"Wick\" "

Or

" k => k.FirstName = \"John\" "

Now I know that with dynamic linq you could parse the string expressions to a LambdaExpression.

If I want to create a join there has to be an alias for the joined table. So from the expression I would like to extract the 'x' or the 'k'.
Is this possible?

答:
LambdaExpression has a Parameters property, which you can use to access information about lambda's parameters. In your case, that could be something like:

```<code>string GetParameterName(LambdaExpression expression) => expression.Parameters.Single().Name;
</code>```

Body:
LambdaExpression has a Parameters property, which you can use to access information about lambda's parameters. In your case, that could be something like:

string GetParameterName(LambdaExpression expression) => expression.Parameters.Single().Name;


问:
Delete latest git commit only in remote?
The commit sequence for my remote repo looks like

A > B > C > D

where commit D is a garbage commit that I don't want, and is not present in my local log (it was generated by github pages settings which i no longer need).  The commit sequence for local looks like

A > B > C > E

where E is a commit more recent than D that I'm trying to push.

How can I simply delete commit D from remote and push commit E? I can't seem to find an answer that doesn't also alter the local commit.

答:
You can use force push:

```<code>git push -f
</code>```

Local doesn't change, remote sync with local.

Body:
You can use force push:

git push -f

Local doesn't change, remote sync with local.


问:
How to make the page not reload clicking a button
I just learn html and css and I need to do a project that build a robot and control the robot using website.

When I click the button it will go to other page or reload

How do I pass the value in the button without reloading the page?

This is my code:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>RPOC</title>
    </head>

    <body>
        <form action="welcome.php" method="post" type='submit'>
            <button>FORWARD
            <input type="hidden" name="value" value="1"><br></button>
        </form>

        <form action="welcome.php" method="post" type='submit'>
            <button>BACKWARD
            <input type="hidden" name="value" value="2"><br></button>
        </form>

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

答:
Your html contains a few mistakes. Try this:

```<code><body>
    <form action="welcome.php" method="post">
        <input type="hidden" name="value" value="1">
        <button type="submit">FORWARD</button>
    </form>

    <form action="welcome.php" method="post">
        <input type="hidden" name="value" value="2">
        <button type="submit">FORWARD</button>
    </form>
</body>
</code>```

Removed type="submit" from form element

Removed hidden input in button element

Added type="submit" to button element

Body:
I just learn html and css and I need to do a project that build a robot and control the robot using website.

When I click the button it will go to other page or reload

How do I pass the value in the button without reloading the page?

This is my code:

<!DOCTYPE html>

        <title>RPOC</title>

        <form action="welcome.php" method="post" type='submit'>
            <button>FORWARD
            <input type="hidden" name="value" value="1">
</button>
        </form>

        <form action="welcome.php" method="post" type='submit'>
            <button>BACKWARD
            <input type="hidden" name="value" value="2">
</button>
        </form>

Body:
Your html contains a few mistakes. Try this:

<body>
    <form action="welcome.php" method="post">
        <input type="hidden" name="value" value="1">
        <button type="submit">FORWARD</button>
    </form>

    <form action="welcome.php" method="post">
        <input type="hidden" name="value" value="2">
        <button type="submit">FORWARD</button>
    </form>
</body>

Removed type="submit" from form element

Removed hidden input in button element

Added type="submit" to button element


问:
iOS APNS - Missing Push Notifications
I am sending notifications to apns one after the other just to test it. For example I send 20 notifications. Each time I send, a counter is incremented and its value is added to the beginning of the title in order to track delivery. The phone receives the first 5 and the 16th but none else.

I am not getting an error for any of them from the apns. They all receive success response.

Why could this be?

EDIT (some extra info):

I am communicating directly with https://api.push.apple.com. I am using http2 and jwtToken. And as suggested, I am keeping the connection alive.

EDIT2:

Device is not offline during this period.

答:
Well, if you send the notifications in a short time period, some may be discarded, especially if the device was temporarily offline when some of the notifications were sent.

Apple Push Notification service includes a Quality of Service (QoS) component that performs a store-and-forward function. If APNs attempts to deliver a notification and the destination device is offline, APNs stores the notification for a limited period of time and delivers it when the device becomes available again. This component stores only the most recent notification per device and per app. If a device is offline, sending a notification request targeting that device causes the previous request to be discarded. If a device remains offline for a long time, all its stored notifications in APNs are discarded.

(Source)

Your app should never depend on all the notifications being delivered.

Title: iOS APNS - Missing Push Notifications


问:
Using grep to find string with brackets
I have some problems with the grep command. I have the following two files in my folder:

test.dat:

```<code>fdf
bla(fd_bla_bla) =&
bdf bla
</code>```

test2.dat

```<code>fd
fd
fij
d
bla(fdf)

fdjk
bla
</code>```

Now I search for the bla having brackets after it with

```<code>grep 'bla(*)' *
</code>```

but it just gives me the entry of the first file...Do you have an idea why?

答:
```<code>grep -F "bla("
</code>```

This will tell grep to use special characters as a regular (Fixed) string.

Title: Using grep to find string with brackets

Body:
I have some problems with the grep command. I have the following two files in my folder:

test.dat:

fdf
bla(fd_bla_bla) =&
bdf bla

test2.dat

fd
fd
fij
d
bla(fdf)

fdjk
bla

Now I search for the bla having brackets after it with

grep 'bla(*)' *

but it just gives me the entry of the first file...Do you have an idea why?

Body:
grep -F "bla("

This will tell grep to use special characters as a regular (Fixed) string.


问:
I keep getting this error: Field 'api_token' doesn't have a default value in PHP Laravel 5.5
I'm new to laravel. Im trying to make an api. So if you register as a (auth)user, u'd be given an api_token for you to have an access to the dashboard
Here's some of my codes. And when I try to register it gives me this error:

Illuminate \ Database \ QueryException (HY000)
SQLSTATE[HY000]: General error: 1364 Field 'api_token' doesn't have a default value (SQL: insert into users (name, email, password, updated_at, created_at) values (goddies, f@gmail.com, $2y$10$uKJPI9hBJSdygMf7MefP1eM1GQ7VM3s74eVy5qcuFj4/s8HH2Iun., 2017-11-13 19:11:38, 2017-11-13 19:11:38))

On my migration for the user:

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('api_token', 20)->unique();
        $table->rememberToken();
        $table->timestamps();
    });
}

public function down()
{
    Schema::dropIfExists('users');
}
</code>```

}

here's my user model:

```<code><?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

protected $fillable = [
    'name', 'email', 'password', 'api_token',
];

protected $hidden = [
    'password', 'remember_token', 'api_token',
];
</code>```

}

答:
That error shows that the api_token field is empty when creating a new record. That's why the error shows that "it doesn't have a default value".

Modify your store method in your UserController (or the one that you use to save a new record) and generate a value for the api_token field:

public function store(Request $request)
{
    // some validation logic
    $user = new User;
    $user->name = $request->name;
    $user->email = $request->email;
    $user->password = $request->password;
    // ... the rest of your fields

    // to generate a new token for the new user
    $user->api_token = str_random(20);

    // then save
    $user->save();

    return $user;
}
```

Obs:

If your using a factory/seeder, you will need to generate that field or make nullable that column in the database.

Body:
I'm new to laravel. Im trying to make an api. So if you register as a (auth)user, u'd be given an api_token for you to have an access to the dashboard
Here's some of my codes. And when I try to register it gives me this error:

Illuminate \ Database \ QueryException (HY000)
SQLSTATE[HY000]: General error: 1364 Field 'api_token' doesn't have a default value (SQL: insert into users (name, email, password, updated_at, created_at) values (goddies, f@gmail.com, $2y$10$uKJPI9hBJSdygMf7MefP1eM1GQ7VM3s74eVy5qcuFj4/s8HH2Iun., 2017-11-13 19:11:38, 2017-11-13 19:11:38))

On my migration for the user:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->string('api_token', 20)->unique();
        $table->rememberToken();
        $table->timestamps();
    });
}

public function down()
{
    Schema::dropIfExists('users');
}

}

here's my user model:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

protected $fillable = [
    'name', 'email', 'password', 'api_token',
];

protected $hidden = [
    'password', 'remember_token', 'api_token',
];

}

Body:
That error shows that the api_token field is empty when creating a new record. That's why the error shows that "it doesn't have a default value".

Modify your store method in your UserController (or the one that you use to save a new record) and generate a value for the api_token field:

public function store(Request $request)
{
    // some validation logic
    $user = new User;
    $user->name = $request->name;
    $user->email = $request->email;
    $user->password = $request->password;
    // ... the rest of your fields

    // to generate a new token for the new user
    $user->api_token = str_random(20);

    // then save
    $user->save();

    return $user;
}

Obs:

If your using a factory/seeder, you will need to generate that field or make nullable that column in the database.


问:
What is wrong with this function call
Behold the code:

```<code>QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
ui->viewLabel->setPixmap(QPixmap::fromImage(qi,Qt::AutoColor));
</code>```

Why does this give me an error? What is it trying to get me to change the qi argument to in the call to fromImage? I am relatively new to C++ and it seems like I am setting this up correctly. It works if I change the line to

```<code>QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
    ui->viewLabel->setPixmap(QPixmap::fromImage(qi[0],Qt::AutoColor));
</code>```

But is that the correct way to do this?

答:
qi is a pointer, and setPixmap looks like waiting for an object, so that's why the first version fails.

Correct way is

```<code>QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
ui->viewLabel->setPixmap(QPixmap::fromImage(*qi,Qt::AutoColor));
</code>```

Title: What is wrong with this function call

Body:
Behold the code:

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
ui->viewLabel->setPixmap(QPixmap::fromImage(qi,Qt::AutoColor));

Why does this give me an error? What is it trying to get me to change the qi argument to in the call to fromImage? I am relatively new to C++ and it seems like I am setting this up correctly. It works if I change the line to

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
    ui->viewLabel->setPixmap(QPixmap::fromImage(qi[0],Qt::AutoColor));

But is that the correct way to do this?

Body:
qi is a pointer, and setPixmap looks like waiting for an object, so that's why the first version fails.

Correct way is

QImage *qi = new QImage(fullCharArray, imwidth, imheight, QImage::Format_Indexed8);
ui->viewLabel->setPixmap(QPixmap::fromImage(*qi,Qt::AutoColor));


问:
Video for windows, adding text/subtitle to AVI - not showing
Good afternoon,

The vfw framework has an option to add a text stream to a video. Is this stream supposed to show up as a subtitle stream in the final video file? I use the ‘AVIStreamWrite’ function to write text to each frame.

My question, is the text stream supposed for subtitle use? Is there perhaps an alternative to write/draw/bake subtitles into frames using the vfw framework?

I've got the feeling 'video for windows' is getting quite old and no longer supported/maintained. Perhaps there is a newer tool set?

答:
Even though VFW has a mention of text streams, I don't think you can embed captions this way with AVI file/format and have the file playable with captions widely accepted.

How to add subtitle text to AVI file

[...]

There is no native support in DirectShow, and thus WMP, for subtitle streams in AVI files.> That syntax is not part of the AVI standard by the extension used by
  VobSub and now used by other programs.

Perhaps the easiest is to write an AVI file, and captions separately in a standalone file like SRT. SRT is a simple text format easy to use.

VFW API is indeed somewhat old and, more important, limited in capabilities, however newer native APIs are not offering much in terms of subtitles either.


问:
Email address columns in SQL Server
What's the correct way to add a check constraint for columns that should only contain email addresses?

We've had buggy software in the past that's added garbage to email columns and I would like to prevent that from happening again.

Please note that "perfect" solutions are not expected. While full RFC compliance would be great, I think most of us can agree just catching obvious mistakes such as "domain/username" and "2017-12-3" would be enough.

And of course it cannot reject any valid email address.

答: Try to create a before trigger which checks(use regular expression) if it is a valid email and if it is, then allow it to be added to the column.</p>

Title: Email address columns in SQL Server


问:
How to remove beginning-digits only in R
I have some strings with digits and alpha characters in them. Some of the digits are important, but the ones at the beginning of the string (and only these) are unimportant. This is due to a peculiarity in how email addresses are stored. So the best example is:

x<-'12345johndoe23@gmail.com'
Should be transformed to johndoe23@gmail.com

unfortunately there are no spaces. I have tried gsub('[[:digit:]]+', '', x) but this removes all numbers, not just the beginning-ones

Edit: I have found some solutions in other languages: Python: Remove numbers at the beginning of a string

答:
As per my comment:

See regex in use here

```<code>^[[:digit:]]+
</code>```

^ Asserts position at the start of the string

Body:
As per my comment:

See regex in use here

^[[:digit:]]+

^ Asserts position at the start of the string


问:
Converting a String to DateTime with new format
How do you convert a string such as 13.11.2017 into a DateTime with that format 13/11/2017

I tried several ways but i didn't get solution  .

```<code>string Arrival = Request.QueryString["Arrival"];//13.11.2017
DateTime datee = DateTime.ParseExact(Arrival , "dd/MM/yyyy", null);
</code>```

here is updated code i split the string :

```<code>            string Arrival = Request.QueryString["Arrival"];//13.11.2017
      string year = Arrival.Split('.')[2];
                   string month = Arrival.Split('.')[1];
                        string day = Arrival.Split('.')[0];
                        string date = day + "/" + month + "/" + year;
                        DateTime datee = DateTime.ParseExact(date, "dd/MM/yyyy", null);
</code>```

答:
Had the same problem with Russian locale.
Currently using ISO format everywhere to avoid incorrect DateTime understandings (like MM.dd when you mean dd.MM).

```<code>public static string ToIsoStr(this DateTime dateTime)
    {
        return dateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
    }
</code>```

Your task will be solved with

```<code>return dateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
</code>```

Body:
How do you convert a string such as 13.11.2017 into a DateTime with that format 13/11/2017

I tried several ways but i didn't get solution  .

string Arrival = Request.QueryString["Arrival"];//13.11.2017
DateTime datee = DateTime.ParseExact(Arrival , "dd/MM/yyyy", null);

here is updated code i split the string :

            string Arrival = Request.QueryString["Arrival"];//13.11.2017
      string year = Arrival.Split('.')[2];
                   string month = Arrival.Split('.')[1];
                        string day = Arrival.Split('.')[0];
                        string date = day + "/" + month + "/" + year;
                        DateTime datee = DateTime.ParseExact(date, "dd/MM/yyyy", null);

Body:
Had the same problem with Russian locale.
Currently using ISO format everywhere to avoid incorrect DateTime understandings (like MM.dd when you mean dd.MM).

public static string ToIsoStr(this DateTime dateTime)
    {
        return dateTime.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
    }

Your task will be solved with

return dateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);


问:
How to Download PDF files from Netsuite File Cabinet to Local drive without any click?

I have one script customization, which creates multiple PDF files on daily basis and store it in File Cabinet.

Now i need to download all new created PDF files on daily basis.

I can download PDF by click on download button. Is there any idea or script to download all PDF files on my local drive at a time ?

答:
Put each batch in its own folder.

Navigate to the parent folder

click the batch folder's download link. You'll get a zipped file of the folder's contents


问:
Laravel 5.2 Many to Many query relationship with where clause
I have a little problem, I have a table with Movies and another with Genres ex: Action, Adventure etc...

Table names:

movies

movie_genre

genres

I want to fetch all the Movies with the selected Genre ex: Action

```<code>$movies = Movie::with('genres')
            ->when($genre, function ($query) use ($genre) {
                        return $query->where('genres.id', $genre->id);
                    })
            ->paginate(20);
</code>```

This php code doesn't work, how can I make it work?

PS: The genre is transfered from the view by $_GET['genre'] and stocked in the variable $genre.

Edit after the answer of @Shane and @Marcin Nabiałek :

The relationship is set in the models and when I use your code directly like this:

```<code>Movie::with('genres', 'countries', 'type')
            ->when($type, function ($query) use ($type) {
                        return $query->where('medias.type_id', $type->id);
                    })
            ->whereHas('genres', function ($query) use ($genre) {
                 return $query->where('genres.id', $genre->id);
               })
            ->paginate(20);
</code>```

it work perfectly, but with the when() function it dosn't. I have to use the when() to make the condition work only if there is a genre selected by the user.

答:
I'm not familiar with the when function. I use whereHas:

```<code>$movies = Movie::whereHas('genres', function ($query) use ($genre) {
    $query->where('id', $genre->id);
})->with('genres')->get();
</code>```

Also, is $genre the model or the ID? You mentioned it was received from $_GET which would mean it would be an ID probably.

I think a better solution would be to use your relationship function in the Genre model to get them:

```<code>$movies = Genre::find($genre_id)->movies;
</code>```

Body:
I have a little problem, I have a table with Movies and another with Genres ex: Action, Adventure etc...

Table names:

movies

movie_genre

genres

I want to fetch all the Movies with the selected Genre ex: Action

$movies = Movie::with('genres')
            ->when($genre, function ($query) use ($genre) {
                        return $query->where('genres.id', $genre->id);
                    })
            ->paginate(20);

This php code doesn't work, how can I make it work?

PS: The genre is transfered from the view by $_GET['genre'] and stocked in the variable $genre.

Edit after the answer of @Shane and @Marcin Nabiałek :

The relationship is set in the models and when I use your code directly like this:

Movie::with('genres', 'countries', 'type')
            ->when($type, function ($query) use ($type) {
                        return $query->where('medias.type_id', $type->id);
                    })
            ->whereHas('genres', function ($query) use ($genre) {
                 return $query->where('genres.id', $genre->id);
               })
            ->paginate(20);

it work perfectly, but with the when() function it dosn't. I have to use the when() to make the condition work only if there is a genre selected by the user.

Body:
I'm not familiar with the when function. I use whereHas:

$movies = Movie::whereHas('genres', function ($query) use ($genre) {
    $query->where('id', $genre->id);
})->with('genres')->get();

Also, is $genre the model or the ID? You mentioned it was received from $_GET which would mean it would be an ID probably.

I think a better solution would be to use your relationship function in the Genre model to get them:

$movies = Genre::find($genre_id)->movies;


问:
Commit fragment into DialogFragment
Hello I have a problem with commit fragment into DialogFragment
I have simple dialogFragment...

```<code>public class CustomCalendarDialog extends DialogFragment {

    public CustomCalendarDialog() {
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_custom_calendar, container);
        FrameLayout frame = view.findViewById(R.id.Dialogcontainer1);
        int id = frame.getId();

        FragmentManager fragmentManager = ((FragmentActivity) getActivity()).getSupportFragmentManager();
        Fragment customCalendarFragment = CustomCalendarFragment.newInstance();
        fragmentManager.beginTransaction().replace(id, customCalendarFragment );

        return view;
    }

}
</code>```

And have Fragment which can commit into activity with this lines

```<code>Fragment customCalendarFragment = CustomCalendarFragment.newInstance();
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    fragmentManager.beginTransaction().replace(frameLayout.getId(), customCalendarFragment ).commit();
</code>```

with this lines in activity program work good.

Now I need replace this fragment into Dialog/Dialog Fragment.

I have layout fragment_custom_calendar.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0000ff">
    <FrameLayout
        android:id="@+id/Dialogcontainer1"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>
</FrameLayout>
</code>```

Inflate layout into dialog

```<code>View view = inflater.inflate(R.layout.fragment_custom_calendar, container);
</code>```

variable container is null I don't know if it's ok or no.

View it's ok, On screen can see Blue layout (#0000ff) But I want see my fragment (Custom calendar)

Program not crashed on commit lines

```<code>FrameLayout frame = view.findViewById(R.id.Dialogcontainer1);
    int id = frame.getId();
    FragmentManager fragmentManager = ((FragmentActivity) getActivity()).getSupportFragmentManager();
    Fragment customCalendarFragment  = CustomCalendarFragment.newInstance();
    fragmentManager.beginTransaction().replace(id, customCalendarFragment );
</code>```

frame is not null id is not null customCalendarFragment  is not null but I cant see it.

I create fragment :

```<code>public static Fragment newInstance() {
    return (Fragment) new CustomCalendarFragment();
}
</code>```

My calling dialog from MainActivity

```<code>CustomCalendarDialog cdd = new CustomCalendarDialog();
    cdd.show(getFragmentManager(), "TAG");
</code>```

I need this fragment in dialog :( I don't know if commit fragment is posible in normal Dialog if yes please link me and i will look.

Thanks any idea

答:
I solve my similar problem with activity like here.

https://stackoverflow.com/a/18234691/8250313

```<code>    /* Start Activity */ public void onClick(View v) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setClassName("com.thinoo.ActivityTest", "com.thinoo.ActivityTest.NewActivity");
    startActivityForResult(intent,90); } /* Called when the second activity's finished */ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
    case 90:
        if (resultCode == RESULT_OK) {
            Bundle res = data.getExtras();
            String result = res.getString("param_result");
            Log.d("FIRST", "result:"+result);
        }
        break;
    } }

private void finishWithResult() {
    Bundle conData = new Bundle();
    conData.putString("param_result", "Thanks Thanks");
    Intent intent = new Intent();
    intent.putExtras(conData);
    setResult(RESULT_OK, intent);
    finish(); }
</code>```

Title: Commit fragment into DialogFragment

Body:
Hello I have a problem with commit fragment into DialogFragment
I have simple dialogFragment...

public class CustomCalendarDialog extends DialogFragment {

    public CustomCalendarDialog() {
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_custom_calendar, container);
        FrameLayout frame = view.findViewById(R.id.Dialogcontainer1);
        int id = frame.getId();

        FragmentManager fragmentManager = ((FragmentActivity) getActivity()).getSupportFragmentManager();
        Fragment customCalendarFragment = CustomCalendarFragment.newInstance();
        fragmentManager.beginTransaction().replace(id, customCalendarFragment );

        return view;
    }

}

And have Fragment which can commit into activity with this lines

Fragment customCalendarFragment = CustomCalendarFragment.newInstance();
                    FragmentManager fragmentManager = getSupportFragmentManager();
                    fragmentManager.beginTransaction().replace(frameLayout.getId(), customCalendarFragment ).commit();

with this lines in activity program work good.

Now I need replace this fragment into Dialog/Dialog Fragment.

I have layout fragment_custom_calendar.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0000ff">
    <FrameLayout
        android:id="@+id/Dialogcontainer1"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>
</FrameLayout>

Inflate layout into dialog

View view = inflater.inflate(R.layout.fragment_custom_calendar, container);

variable container is null I don't know if it's ok or no.

View it's ok, On screen can see Blue layout (#0000ff) But I want see my fragment (Custom calendar)

Program not crashed on commit lines

FrameLayout frame = view.findViewById(R.id.Dialogcontainer1);
    int id = frame.getId();
    FragmentManager fragmentManager = ((FragmentActivity) getActivity()).getSupportFragmentManager();
    Fragment customCalendarFragment  = CustomCalendarFragment.newInstance();
    fragmentManager.beginTransaction().replace(id, customCalendarFragment );

frame is not null id is not null customCalendarFragment  is not null but I cant see it.

I create fragment :

public static Fragment newInstance() {
    return (Fragment) new CustomCalendarFragment();
}

My calling dialog from MainActivity

CustomCalendarDialog cdd = new CustomCalendarDialog();
    cdd.show(getFragmentManager(), "TAG");

I need this fragment in dialog :( I don't know if commit fragment is posible in normal Dialog if yes please link me and i will look.

Thanks any idea

Body:
I solve my similar problem with activity like here.

https://stackoverflow.com/a/18234691/8250313

    /* Start Activity */ public void onClick(View v) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setClassName("com.thinoo.ActivityTest", "com.thinoo.ActivityTest.NewActivity");
    startActivityForResult(intent,90); } /* Called when the second activity's finished */ protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
    case 90:
        if (resultCode == RESULT_OK) {
            Bundle res = data.getExtras();
            String result = res.getString("param_result");
            Log.d("FIRST", "result:"+result);
        }
        break;
    } }

private void finishWithResult() {
    Bundle conData = new Bundle();
    conData.putString("param_result", "Thanks Thanks");
    Intent intent = new Intent();
    intent.putExtras(conData);
    setResult(RESULT_OK, intent);
    finish(); }


问:
Stack window shows no output when debugging Redis Lua scripts with ZeroBrane
I have followed this tutorial to debug Redis Lua scripts.
https://www.youtube.com/watch?v=7mlajCj4QPw

Everything works except for that the Stack window shows no output so I can't see the value of the variables which is what I need to debug. If I change the Lua interpreter to something else than redis, and try to debug some normal Lua code then it works, and stack window shows everything. But once I switch to Redis as Lua interpreter then nothing shows on the Stack window.

I load up the redis.lua plugin from this repository
as suggested in the video:
https://github.com/pkulchenko/ZeroBranePackage

Stack Window is empty as you can see:

What could be wrong?

Also for some reason when I enter GET foo in the remote console it says:

"Wrong number of args calling Redis command From Lua script"

Since I have redis running on another machine, I thought perhaps I had to change some settings:

```<code>debugger.hostname = "192.168.0.161"
debugger.port = 8172
</code>```

When I try to run it it says:

Can't connect to the debugger at '192.168.0.161:8172': connection refused

Do I have to do something special to the redis settings on my Virtual Linux Box to remote debug Redis? I am using Windows 7 so I can't install Redis 3.2 on it to debug so I have to run it on Cent OS 7 on VirtualBox.

答: Both of these issues (empty stack window and an error on Redis commands in console) should be fixed in the updated version of Redis plugin (0.33).</p>

Body:
I have followed this tutorial to debug Redis Lua scripts.
https://www.youtube.com/watch?v=7mlajCj4QPw

Everything works except for that the Stack window shows no output so I can't see the value of the variables which is what I need to debug. If I change the Lua interpreter to something else than redis, and try to debug some normal Lua code then it works, and stack window shows everything. But once I switch to Redis as Lua interpreter then nothing shows on the Stack window.

I load up the redis.lua plugin from this repository
as suggested in the video:
https://github.com/pkulchenko/ZeroBranePackage

Stack Window is empty as you can see:

What could be wrong?

Also for some reason when I enter GET foo in the remote console it says:

"Wrong number of args calling Redis command From Lua script"

Since I have redis running on another machine, I thought perhaps I had to change some settings:

debugger.hostname = "192.168.0.161"
debugger.port = 8172

When I try to run it it says:

Can't connect to the debugger at '192.168.0.161:8172': connection refused

Do I have to do something special to the redis settings on my Virtual Linux Box to remote debug Redis? I am using Windows 7 so I can't install Redis 3.2 on it to debug so I have to run it on Cent OS 7 on VirtualBox.


问:
Webpack. Pass parameters to entry point
I have a multi-page app. And I have configured multi-entry points with one js file. The reason for making this: these two pages have a lot of the same code.
So far, I have already read about webpack-plugins and webpack configuration without any result.

Question: Can I pass some parameter to page1 entry point and page2 entry point in order to my index.js file will resolve what exactly it should do? Is it possible? And could anyone give advice on this issue?

```<code>...
entry: {
    page1: "./index.js",
    page2: "./index.js"
},
...
</code>```

答:
I would suggest to create an entry point for each page and require index.js from there.

Cleaner and easily readable.

Title: Webpack. Pass parameters to entry point

Body:
I have a multi-page app. And I have configured multi-entry points with one js file. The reason for making this: these two pages have a lot of the same code.
So far, I have already read about webpack-plugins and webpack configuration without any result.

Question: Can I pass some parameter to page1 entry point and page2 entry point in order to my index.js file will resolve what exactly it should do? Is it possible? And could anyone give advice on this issue?

...
entry: {
    page1: "./index.js",
    page2: "./index.js"
},
...


问:
Having trouble searching binary search tree
Trying to search the binary search tree but there seems I cannot figure out why the there statement is not working, the method calls for the input of a String, but it says that a Node is required. Any suggestions how to fix this?

Here is the Node Class:

```<code>public class Node
{
    String key;
    Node left, right;

    public Node(String entry)
    {
        key = entry;
        left = right = null;
    }

    public Node getLeft()
    {
        return left;
    }

    public Node getRight()
    {
        return right;
    }

    public String getKey(String entry)
    {
        if(this.key.equals(key))
        {
            return key;
        }

        if(entry.compareTo(this.key) < 0)
        {
            return left == null ? null : left.getKey(entry);
        }
        else
        {
            return right == null ? null : right.getKey(entry);
        }
    }

    public void setLeft(Node left)
    {
        this.left = left;
    }

    public void setRight(Node right)
    {
        this.right = right;
    }
}
</code>```

Here is my Binary Search Tree:

```<code>public class BinarySearchTree
{
    Node root;

    public BinarySearchTree()
    {
        root = null;
    }

    public void insert(String key)
    {
        root = insertRec(root, key);
    }

    public Node insertRec(Node root, String key)
    {
        if(root == null)
        {
            root = new Node(key);
            return root;
        }

        if(key.compareTo(root.toString()) == -1)
        {
            root.setLeft(insertRec(root.getLeft(), key));
        }
        else if(key.compareTo(root.toString()) == 1)
        {
            root.setRight(insertRec(root.getRight(), key));
        }

        return root;
    }

    public Node search(String key)
    {
        return root == null ? null : root.getKey(key);
    }

    public void printPostOrder(Node node)
    {
        if(node == null)
            return;

        printPostOrder(root.getLeft());

        printPostOrder(node.getRight());

        System.out.print(node.getKey() + ", ");
    }

    public void printInOrder(Node node)
    {
        if(node == null)
            return;

        printInOrder(node.getLeft());

        System.out.print(node.getKey() + ", ");

        printInOrder(node.getRight());
    }

    public void printPreOrder(Node node)
    {
        if(node == null)
            return;

        System.out.print(node.getKey() + ", ");

        printPreOrder(node.getLeft());

        printPreOrder(node.getRight());
    }

    public void printPostOrder()
    {
        printPostOrder(root);
    }

    public void printInOrder()
    {
        printInOrder(root);
    }

    public void printPreOrder()
    {
        printPreOrder(root);
    }
}
</code>```

Any and all help is much appreciated if you need more information please let me know.

答:
whats up ?
your code is wrong in the class node in method getKey change your return String to Node  and your if equals and return to this.

Ex:.

```<code>public Node getKey(String entry)
{
    if(this.key.equals(entry))
    {
        return this;
    }
}
</code>```

if you change this your code work.

Full class BinarySearchTree tested ok

```<code> public class BinarySearchTree
 {
    Node root;

    public BinarySearchTree()
    {
        root = null;
    }

    public void insert(String key)
    {
        root = insertRec(root, key);
    }

    public Node insertRec(Node root, String key)
    {
        if(root == null)
        {
            root = new Node(key);
            return root;
        }

        if(key.compareTo(root.toString()) == -1)
        {
            root.setLeft(insertRec(root.getLeft(), key));
        }
        else if(key.compareTo(root.toString()) == 1)
        {
            root.setRight(insertRec(root.getRight(), key));
        }

        return root;
    }

    public Node search(String key)
    {
        return root == null ? null : root.getKey(key);
    }

    public void printPostOrder(Node node)
    {
        if(node == null)
            return;

        printPostOrder(root.getLeft());

        printPostOrder(node.getRight());

        System.out.print(node.getKey("") + ", ");
    }

    public void printInOrder(Node node)
    {
        if(node == null)
            return;

        printInOrder(node.getLeft());

        System.out.print(node.getKey("") + ", ");

        printInOrder(node.getRight());
    }

    public void printPreOrder(Node node)
    {
        if(node == null)
            return;

        System.out.print(node.getKey("") + ", ");

        printPreOrder(node.getLeft());

        printPreOrder(node.getRight());
    }

    public void printPostOrder()
    {
        printPostOrder(root);
    }

    public void printInOrder()
    {
        printInOrder(root);
    }

    public void printPreOrder()
    {
        printPreOrder(root);
    }

    public static void main (String args[]){
        BinarySearchTree bs = new BinarySearchTree();
        bs.insert("A");
        bs.search("A");
    }
 }
</code>```

and Node complete

```<code>public class Node
{
    String key;
    Node left, right;

    public Node(String entry)
    {
        key = entry;
        left = right = null;
    }

    public Node getLeft()
    {
        return left;
    }

    public Node getRight()
    {
        return right;
    }

    public Node getKey(String entry)
    {
        if(this.key.equals(key))
        {
            return this;
        }

        if(entry.compareTo(this.key) < 0)
        {
            return left == null ? null : left.getKey(entry);
        }
        else
        {
            return right == null ? null : right.getKey(entry);
        }
    }

    public void setLeft(Node left)
    {
        this.left = left;
    }

    public void setRight(Node right)
    {
        this.right = right;
    }
}
</code>```

Body:
Trying to search the binary search tree but there seems I cannot figure out why the there statement is not working, the method calls for the input of a String, but it says that a Node is required. Any suggestions how to fix this?

Here is the Node Class:

public class Node
{
    String key;
    Node left, right;

    public Node(String entry)
    {
        key = entry;
        left = right = null;
    }

    public Node getLeft()
    {
        return left;
    }

    public Node getRight()
    {
        return right;
    }

    public String getKey(String entry)
    {
        if(this.key.equals(key))
        {
            return key;
        }

        if(entry.compareTo(this.key) < 0)
        {
            return left == null ? null : left.getKey(entry);
        }
        else
        {
            return right == null ? null : right.getKey(entry);
        }
    }

    public void setLeft(Node left)
    {
        this.left = left;
    }

    public void setRight(Node right)
    {
        this.right = right;
    }
}

Here is my Binary Search Tree:

public class BinarySearchTree
{
    Node root;

    public BinarySearchTree()
    {
        root = null;
    }

    public void insert(String key)
    {
        root = insertRec(root, key);
    }

    public Node insertRec(Node root, String key)
    {
        if(root == null)
        {
            root = new Node(key);
            return root;
        }

        if(key.compareTo(root.toString()) == -1)
        {
            root.setLeft(insertRec(root.getLeft(), key));
        }
        else if(key.compareTo(root.toString()) == 1)
        {
            root.setRight(insertRec(root.getRight(), key));
        }

        return root;
    }

    public Node search(String key)
    {
        return root == null ? null : root.getKey(key);
    }

    public void printPostOrder(Node node)
    {
        if(node == null)
            return;

        printPostOrder(root.getLeft());

        printPostOrder(node.getRight());

        System.out.print(node.getKey() + ", ");
    }

    public void printInOrder(Node node)
    {
        if(node == null)
            return;

        printInOrder(node.getLeft());

        System.out.print(node.getKey() + ", ");

        printInOrder(node.getRight());
    }

    public void printPreOrder(Node node)
    {
        if(node == null)
            return;

        System.out.print(node.getKey() + ", ");

        printPreOrder(node.getLeft());

        printPreOrder(node.getRight());
    }

    public void printPostOrder()
    {
        printPostOrder(root);
    }

    public void printInOrder()
    {
        printInOrder(root);
    }

    public void printPreOrder()
    {
        printPreOrder(root);
    }
}

Any and all help is much appreciated if you need more information please let me know.

Body:
whats up ?
your code is wrong in the class node in method getKey change your return String to Node  and your if equals and return to this.

Ex:.

public Node getKey(String entry)
{
    if(this.key.equals(entry))
    {
        return this;
    }
}

if you change this your code work.

Full class BinarySearchTree tested ok

 public class BinarySearchTree
 {
    Node root;

    public BinarySearchTree()
    {
        root = null;
    }

    public void insert(String key)
    {
        root = insertRec(root, key);
    }

    public Node insertRec(Node root, String key)
    {
        if(root == null)
        {
            root = new Node(key);
            return root;
        }

        if(key.compareTo(root.toString()) == -1)
        {
            root.setLeft(insertRec(root.getLeft(), key));
        }
        else if(key.compareTo(root.toString()) == 1)
        {
            root.setRight(insertRec(root.getRight(), key));
        }

        return root;
    }

    public Node search(String key)
    {
        return root == null ? null : root.getKey(key);
    }

    public void printPostOrder(Node node)
    {
        if(node == null)
            return;

        printPostOrder(root.getLeft());

        printPostOrder(node.getRight());

        System.out.print(node.getKey("") + ", ");
    }

    public void printInOrder(Node node)
    {
        if(node == null)
            return;

        printInOrder(node.getLeft());

        System.out.print(node.getKey("") + ", ");

        printInOrder(node.getRight());
    }

    public void printPreOrder(Node node)
    {
        if(node == null)
            return;

        System.out.print(node.getKey("") + ", ");

        printPreOrder(node.getLeft());

        printPreOrder(node.getRight());
    }

    public void printPostOrder()
    {
        printPostOrder(root);
    }

    public void printInOrder()
    {
        printInOrder(root);
    }

    public void printPreOrder()
    {
        printPreOrder(root);
    }

    public static void main (String args[]){
        BinarySearchTree bs = new BinarySearchTree();
        bs.insert("A");
        bs.search("A");
    }
 }

and Node complete

public class Node
{
    String key;
    Node left, right;

    public Node(String entry)
    {
        key = entry;
        left = right = null;
    }

    public Node getLeft()
    {
        return left;
    }

    public Node getRight()
    {
        return right;
    }

    public Node getKey(String entry)
    {
        if(this.key.equals(key))
        {
            return this;
        }

        if(entry.compareTo(this.key) < 0)
        {
            return left == null ? null : left.getKey(entry);
        }
        else
        {
            return right == null ? null : right.getKey(entry);
        }
    }

    public void setLeft(Node left)
    {
        this.left = left;
    }

    public void setRight(Node right)
    {
        this.right = right;
    }
}