问:
What should be the vertex and fragment shaders to draw a cube with texture in version 440 core
I am following "Interactive Computer Graphics" by Ed Angel, specifically the code for rotating cube with texture. The vertex shader for this (as in the book) is as follows:

```<code>#version 150
in vec4 vPosition;
in vec4 vColor;
in vec2 vTexCoord;

out vec4 color;
out vec2 texCoord;
uniform vec3 theta;
void main()
{
........
........
// code for rotation
........
color = vColor;
texCoord = vTexCoord;
gl_Position = rz * ry * rx * vPosition;
}
</code>```

And the fragment shader code is:

```<code>#version 150
in vec4 color;
in vec2 texCoord;
out vec4 fColor;
uniform sampler2D texture;
void main()
{
fColor = color * texture2D( texture, texCoord );
}
</code>```

[The link for the complete code is here. Just look at the code for example 8.

I am trying to implement this using #version 440 core. When I run this, I get only a black cube. The texture is not shown.

What change to the above code should I make to display the texture correctly?

答:
This line in the cpp code:

```<code>glutInitContextVersion( 3, 2 );
</code>```

is your problem. glsl version 440 requires an OpenGL 4.4 context. Change it to :

```<code>glutInitContextVersion( 4, 4 );
</code>```

And modernise your shader code according to:

GLSL Specification

And it should work fine.

Body:
I am following "Interactive Computer Graphics" by Ed Angel, specifically the code for rotating cube with texture. The vertex shader for this (as in the book) is as follows:

#version 150
in vec4 vPosition;
in vec4 vColor;
in vec2 vTexCoord;

out vec4 color;
out vec2 texCoord;
uniform vec3 theta;
void main()
{
........
........
// code for rotation
........
color = vColor;
texCoord = vTexCoord;
gl_Position = rz * ry * rx * vPosition;
}

And the fragment shader code is:

#version 150
in vec4 color;
in vec2 texCoord;
out vec4 fColor;
uniform sampler2D texture;
void main()
{
fColor = color * texture2D( texture, texCoord );
}

[The link for the complete code is here. Just look at the code for example 8.

I am trying to implement this using #version 440 core. When I run this, I get only a black cube. The texture is not shown.

What change to the above code should I make to display the texture correctly?

Body:
This line in the cpp code:

glutInitContextVersion( 3, 2 );

is your problem. glsl version 440 requires an OpenGL 4.4 context. Change it to :

glutInitContextVersion( 4, 4 );

And modernise your shader code according to:

GLSL Specification

And it should work fine.


来源: stackexchange

问:
Input Dates to an SQL Query through R
Hello I am trying to paste dates into an SQL query within R. MY code is as follows:

```<code>Date1<-'20171031'
Date2<-'20170731'

SQLCommand<- data.frame(sqlQuery(myConn, "SELECT fc.[FactSet Fund Code], fc.FactsetDate,  fc.[Asset Class], fc.[Fund Manager], d.Id AS DeskID, d.[Name] AS DeskName, c.ClosingDate, m.NumericGrossPerformanceTarget, fc.[% Factor Risk], fc.[Predicted Tracking Error], fc.[Portfolio Predicted Beta]
                             FROM [PortfolioAnalytics].[Data_Factset].[FundChar] fc
                             LEFT OUTER JOIN Data_Axioma.FactSetAccount fsa ON fc.FactsetAccountCode = REPLACE(fsa.Code, '_', '')
                             LEFT OUTER JOIN dbo.Portfolio p ON fsa.PortfolioId = p.Id
                             LEFT OUTER JOIN dbo.Mandate m ON p.UnderlyingId = m.id
                             INNER JOIN dbo.Mandate c ON p.UnderlyingId = c.id
                             LEFT OUTER JOIN dbo.Desk d ON m.DeskId = d.Id
                             WHERE IncludesCash = 1
                             AND [FactSet Fund Code] IS NOT NULL
                             AND [Fund Manager] IS NOT NULL
                             AND [Asset Class] IS NOT NULL
                             AND FactsetDate IN ("Date1, Date2")
                             ORDER BY [Predicted Tracking Error] DESC"))
</code>```

I get an unexpected symbol error.

答:
To do this with string manipulation </p>

```<code>Date1 <- "20171031"
Date2 <- "20170731"

query <- sprintf("select * from yourtable
                  where column between '%s' and '%s'", Date1, Date2)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Input Dates to an SQL Query through R

Body:
Hello I am trying to paste dates into an SQL query within R. MY code is as follows:

Date1<-'20171031'
Date2<-'20170731'

SQLCommand<- data.frame(sqlQuery(myConn, "SELECT fc.[FactSet Fund Code], fc.FactsetDate,  fc.[Asset Class], fc.[Fund Manager], d.Id AS DeskID, d.[Name] AS DeskName, c.ClosingDate, m.NumericGrossPerformanceTarget, fc.[% Factor Risk], fc.[Predicted Tracking Error], fc.[Portfolio Predicted Beta]
                             FROM [PortfolioAnalytics].[Data_Factset].[FundChar] fc
                             LEFT OUTER JOIN Data_Axioma.FactSetAccount fsa ON fc.FactsetAccountCode = REPLACE(fsa.Code, '_', '')
                             LEFT OUTER JOIN dbo.Portfolio p ON fsa.PortfolioId = p.Id
                             LEFT OUTER JOIN dbo.Mandate m ON p.UnderlyingId = m.id
                             INNER JOIN dbo.Mandate c ON p.UnderlyingId = c.id
                             LEFT OUTER JOIN dbo.Desk d ON m.DeskId = d.Id
                             WHERE IncludesCash = 1
                             AND [FactSet Fund Code] IS NOT NULL
                             AND [Fund Manager] IS NOT NULL
                             AND [Asset Class] IS NOT NULL
                             AND FactsetDate IN ("Date1, Date2")
                             ORDER BY [Predicted Tracking Error] DESC"))

I get an unexpected symbol error.

Body:
To do this with string manipulation

Date1 <- "20171031"
Date2 <- "20170731"

query <- sprintf("select * from yourtable
                  where column between '%s' and '%s'", Date1, Date2)


问:
Don't show FormArray if it is empty or undefined in a Reactive Form
I've just started to learn Angular 4 doing my first project.

I have created a Reactive Form to show a form with the following structure:

```<code>Form (FormGroup)
  |
  --> aggLevels (FormArray)
       |
       --> aggregationLevelName (FormControl? I show it in a label)
       |
       --> variableDataForLevel (FormArray)
            |
            --> variableDataId (FormControl)
            |
            --> value (FormControl)
</code>```

This is the component HTML:

```<code><form [formGroup]="varDataForm" (ngSubmit)="onSubmit()" novalidate>
    <div formArrayName="aggLevels"
         *ngFor="let agLevel of varDataForm.get('aggLevels')?.controls; let aggLevelId = index;">
        <div [formGroupName]="aggLevelId">
            <label>{{agLevel?.get('aggregationLevelName')?.value}}</label>
            <div formArrayName="variableDataForLevel"
                 *ngFor="let vardata of varDataForm.get('aggLevels')?.controls[0]?.get('variableDataForLevel')?.controls; let rowIndex = index;">
                <div [formGroupName]="rowIndex">
                    <select formControlName="variableDataId">
                        <option *ngFor="let gs1 of gs1AIs" [value]="gs1.Id">{{gs1.description}}</option>
                    </select>
                    <input formControlName="value" placeholder="Valor">
                    <div class="error" *ngIf="vardata.get('value').hasError('required') && vardata.get('value').touched">
                        Obligatorio
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>
</code>```

My problem here is when there isn't any element in variableDataForLevel FormArray. I get this message:

ng:///AppModuleShared/VarDataComponent.ngfactory.js:49 ERROR Error:
  Cannot find control with path: 'aggLevels -> 1 -> variableDataForLevel
  -> 0'

I have tried to add safe navigation operator ? at the end of all elements:

```<code>varDataForm.get('aggLevels')?.controls[0]?.get('variableDataForLevel')?.controls
</code>```

But I still get the problem. FormArray aggLevels and variableDataForLevel aren't undefined because when I create it I instance it.

What can I do to don't show the FormArray if is empty?

I new with Angular and I have few knowledge about how to fix it.

This is the component typescript class for this component:

```<code>import { Component, Inject } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl, Validators } from '@angular/forms';
import { Http, RequestOptions, Headers } from '@angular/http';
import { IProductionOrder } from '../../interfaces/productionorder.interface';
import { IAggLevel } from '../../interfaces/aglevel.interface';
import { IGS1 } from '../../interfaces/gs1.interface';
import { IVarData } from '../../interfaces/vardata.interface';

@Component({
    selector: 'vardata',
    templateUrl: './vardata.component.html'
})

export class VarDataComponent {
    public productionorders: IProductionOrder[];
    public gs1AIs: IGS1[];

    public varDataForm: FormGroup = new FormGroup({});
    public selectedProductionOrder: string;

    constructor(private http: Http,
        @Inject('BASE_URL') private baseUrl: string,
        @Inject(FormBuilder) private fb: FormBuilder) {

        this.selectedProductionOrder = '';

        http.get(baseUrl + 'api/ProductionOrder/0').subscribe(result => {
            this.productionorders = result.json() as IProductionOrder[];

            console.log(this.productionorders);
        }, error => console.error(error));
    }

    productionOrderChanges() {
        if (this.selectedProductionOrder != '') {
            let urlVarData: string = this.baseUrl + 'api/VariableData/' + this.selectedProductionOrder;
            let urlAggLevel: string = this.baseUrl + 'api/AggregationLevelConfiguration/' + this.selectedProductionOrder;

            this.http.get(urlAggLevel).subscribe(result => {
                let aggLevels: IAggLevel[] = result.json() as IAggLevel[];

                console.log('niveles');
                console.log(aggLevels);

                if ((aggLevels != null) && (aggLevels.length > 0)) {

                    this.http.get(urlVarData).subscribe(result => {
                        let varDatas: IVarData[] = result.json() as IVarData[];

                        console.log('variable data');
                        console.log(varDatas);

                        this.varDataForm = this.fb.group({
                            aggLevels: this.fb.array(this.createForm(aggLevels, varDatas))
                        });

                    }, error => console.error(error));
                }

            }, error => console.error(error));
        }
        else
            this.varDataForm = new FormGroup({});
    }

    createForm(aggLevels: IAggLevel[], varDatas: IVarData[]): any[] {
        let array: any[] = [];

        for (let level of aggLevels) {
            let group: FormGroup;
            let varDataForLevel: IVarData[] =
                varDatas.filter(v => v.aggregationLevelConfigurationId == level.aggregationLevelConfigurationId);

            group = this.createFormGroupForLevel(level, varDataForLevel);
            array.push(group);
        }

        return array;
    }

    createFormGroupForLevel(level: IAggLevel, varDatas: IVarData[]): FormGroup {
        let group: FormGroup;

        group = this.fb.group({
            aggregationLevelName: level.name,
            variableDataForLevel: this.fb.array(this.createVarDataControls(varDatas))
        });

        return group;
    }

    createVarDataControls(varData: IVarData[]): any[] {
        let array: any[] = [];

        for (let vData of varData) {
            let group: FormGroup;

            group = this.fb.group({
                variableDataId: vData.variableDataId,
                value: vData.value
            });

            array.push(group);
        }

        return array;
    }

    disableSubmit() {
        return (!this.varDataForm.valid);
    }

    onSubmit() {
    }
}
</code>```

I think the problem is here:

```<code>createVarDataControls(varData: IVarData[]): any[] {
    let array: any[] = [];

    for (let vData of varData) {
        let group: FormGroup;

        group = this.fb.group({
            variableDataId: vData.variableDataId,
            value: vData.value
        });

        array.push(group);
    }

    return array;
}
</code>```

if varData is empty it will return a Any[], but I don't think return this is an error because I don't want to show something empty on the form.

I have edited method createVarDataControls to return a FormGroup if varData is empty. This let me continue but I don't think it answers my question:

```<code>createVarDataControls(varData: IVarData[]): any[] {
    let array: any[] = [];

    if ((varData == null) || (varData.length == 0)) {
        let group: FormGroup;

        group = this.fb.group({
            variableDataId: '',
            value: ''
        });

        array.push(group);
    }
    else {
        for (let vData of varData) {
            let group: FormGroup;

            group = this.fb.group({
                variableDataId: vData.variableDataId,
                value: vData.value
            });

            array.push(group);
        }
    }

    return array;
}
</code>```

With it I don't get any exception but it shows two empty controls, and I don't want that. This is only useful to identify the problem.

答:
I have found the problem. I would like my solution if it can helps someone.

In the second FormArray loop:

```<code><div formArrayName="variableDataForLevel"
                 *ngFor="let vardata of varDataForm.get('aggLevels')?.controls[0]?.get('variableDataForLevel')?.controls; let rowIndex = index;">
</code>```

But the correct one is:

```<code><div formArrayName="variableDataForLevel"
        *ngFor="let vardata of agLevel.get('variableDataForLevel')?.controls; let rowIndex = index;">
</code>```

I have changed varDataForm.get('aggLevels')?.controls[0]? with agLevel.

And also I have changed the method createVarDataControls to return undefined when there aren't variable data to show on it:

```<code>createVarDataControls(varData: IVarData[]): any[] | undefined {
    let array: any[] = [];

    if ((varData == null) || (varData.length == 0)) {
        return undefined;
    }
    else {
        for (let vData of varData) {
            let group: FormGroup;

            group = this.fb.group({
                aggregationLevelConfigurationId: vData.aggregationLevelConfigurationId,
                productionOrderId: vData.productionOrderId,
                variableDataId: vData.variableDataId,
                value: vData.value
            });

            array.push(group);
        }

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

Try and failure until find the solution!

Body:
I've just started to learn Angular 4 doing my first project.

I have created a Reactive Form to show a form with the following structure:

Form (FormGroup)
  |
  --> aggLevels (FormArray)
       |
       --> aggregationLevelName (FormControl? I show it in a label)
       |
       --> variableDataForLevel (FormArray)
            |
            --> variableDataId (FormControl)
            |
            --> value (FormControl)

This is the component HTML:

<form [formGroup]="varDataForm" (ngSubmit)="onSubmit()" novalidate>

            {{agLevel?.get('aggregationLevelName')?.value}}

                    <select formControlName="variableDataId">
                        <option *ngFor="let gs1 of gs1AIs" [value]="gs1.Id">{{gs1.description}}</option>
                    </select>
                    <input formControlName="value" placeholder="Valor">

                        Obligatorio

</form>

My problem here is when there isn't any element in variableDataForLevel FormArray. I get this message:

ng:///AppModuleShared/VarDataComponent.ngfactory.js:49 ERROR Error:
  Cannot find control with path: 'aggLevels -> 1 -> variableDataForLevel
  -> 0'

I have tried to add safe navigation operator ? at the end of all elements:

varDataForm.get('aggLevels')?.controls[0]?.get('variableDataForLevel')?.controls

But I still get the problem. FormArray aggLevels and variableDataForLevel aren't undefined because when I create it I instance it.

What can I do to don't show the FormArray if is empty?

I new with Angular and I have few knowledge about how to fix it.

This is the component typescript class for this component:

import { Component, Inject } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl, Validators } from '@angular/forms';
import { Http, RequestOptions, Headers } from '@angular/http';
import { IProductionOrder } from '../../interfaces/productionorder.interface';
import { IAggLevel } from '../../interfaces/aglevel.interface';
import { IGS1 } from '../../interfaces/gs1.interface';
import { IVarData } from '../../interfaces/vardata.interface';

@Component({
    selector: 'vardata',
    templateUrl: './vardata.component.html'
})

export class VarDataComponent {
    public productionorders: IProductionOrder[];
    public gs1AIs: IGS1[];

    public varDataForm: FormGroup = new FormGroup({});
    public selectedProductionOrder: string;

    constructor(private http: Http,
        @Inject('BASE_URL') private baseUrl: string,
        @Inject(FormBuilder) private fb: FormBuilder) {

        this.selectedProductionOrder = '';

        http.get(baseUrl + 'api/ProductionOrder/0').subscribe(result => {
            this.productionorders = result.json() as IProductionOrder[];

            console.log(this.productionorders);
        }, error => console.error(error));
    }

    productionOrderChanges() {
        if (this.selectedProductionOrder != '') {
            let urlVarData: string = this.baseUrl + 'api/VariableData/' + this.selectedProductionOrder;
            let urlAggLevel: string = this.baseUrl + 'api/AggregationLevelConfiguration/' + this.selectedProductionOrder;

            this.http.get(urlAggLevel).subscribe(result => {
                let aggLevels: IAggLevel[] = result.json() as IAggLevel[];

                console.log('niveles');
                console.log(aggLevels);

                if ((aggLevels != null) && (aggLevels.length > 0)) {

                    this.http.get(urlVarData).subscribe(result => {
                        let varDatas: IVarData[] = result.json() as IVarData[];

                        console.log('variable data');
                        console.log(varDatas);

                        this.varDataForm = this.fb.group({
                            aggLevels: this.fb.array(this.createForm(aggLevels, varDatas))
                        });

                    }, error => console.error(error));
                }

            }, error => console.error(error));
        }
        else
            this.varDataForm = new FormGroup({});
    }

    createForm(aggLevels: IAggLevel[], varDatas: IVarData[]): any[] {
        let array: any[] = [];

        for (let level of aggLevels) {
            let group: FormGroup;
            let varDataForLevel: IVarData[] =
                varDatas.filter(v => v.aggregationLevelConfigurationId == level.aggregationLevelConfigurationId);

            group = this.createFormGroupForLevel(level, varDataForLevel);
            array.push(group);
        }

        return array;
    }

    createFormGroupForLevel(level: IAggLevel, varDatas: IVarData[]): FormGroup {
        let group: FormGroup;

        group = this.fb.group({
            aggregationLevelName: level.name,
            variableDataForLevel: this.fb.array(this.createVarDataControls(varDatas))
        });

        return group;
    }

    createVarDataControls(varData: IVarData[]): any[] {
        let array: any[] = [];

        for (let vData of varData) {
            let group: FormGroup;

            group = this.fb.group({
                variableDataId: vData.variableDataId,
                value: vData.value
            });

            array.push(group);
        }

        return array;
    }

    disableSubmit() {
        return (!this.varDataForm.valid);
    }

    onSubmit() {
    }
}

I think the problem is here:

createVarDataControls(varData: IVarData[]): any[] {
    let array: any[] = [];

    for (let vData of varData) {
        let group: FormGroup;

        group = this.fb.group({
            variableDataId: vData.variableDataId,
            value: vData.value
        });

        array.push(group);
    }

    return array;
}

if varData is empty it will return a Any[], but I don't think return this is an error because I don't want to show something empty on the form.

I have edited method createVarDataControls to return a FormGroup if varData is empty. This let me continue but I don't think it answers my question:

createVarDataControls(varData: IVarData[]): any[] {
    let array: any[] = [];

    if ((varData == null) || (varData.length == 0)) {
        let group: FormGroup;

        group = this.fb.group({
            variableDataId: '',
            value: ''
        });

        array.push(group);
    }
    else {
        for (let vData of varData) {
            let group: FormGroup;

            group = this.fb.group({
                variableDataId: vData.variableDataId,
                value: vData.value
            });

            array.push(group);
        }
    }

    return array;
}

With it I don't get any exception but it shows two empty controls, and I don't want that. This is only useful to identify the problem.

Body:
I have found the problem. I would like my solution if it can helps someone.

In the second FormArray loop:

<div formArrayName="variableDataForLevel"
                 *ngFor="let vardata of varDataForm.get('aggLevels')?.controls[0]?.get('variableDataForLevel')?.controls; let rowIndex = index;">

But the correct one is:

<div formArrayName="variableDataForLevel"
        *ngFor="let vardata of agLevel.get('variableDataForLevel')?.controls; let rowIndex = index;">

I have changed varDataForm.get('aggLevels')?.controls[0]? with agLevel.

And also I have changed the method createVarDataControls to return undefined when there aren't variable data to show on it:

createVarDataControls(varData: IVarData[]): any[] | undefined {
    let array: any[] = [];

    if ((varData == null) || (varData.length == 0)) {
        return undefined;
    }
    else {
        for (let vData of varData) {
            let group: FormGroup;

            group = this.fb.group({
                aggregationLevelConfigurationId: vData.aggregationLevelConfigurationId,
                productionOrderId: vData.productionOrderId,
                variableDataId: vData.variableDataId,
                value: vData.value
            });

            array.push(group);
        }

        return array;
    }
}

Try and failure until find the solution!


问:
Does PHP have static or dynamic scoping?
Static scoping : The function sees the variable from parent function first.
Dynamic scoping : The function sees the variable from the function that calls the current function first.

Is there these kind of concepts in PHP? Thank you for your reply!

答:
These concepts do not exist in PHP. Every function has its own scope.

Therefore PHP has a function scope.
That means: functions do only have access to their own variables (the variables declared inside the function, or function params) and code outside of functions does only have access to variables that are declared outside functions.
(You can declare variables global to access them inside functions - but thats not recommended.)

If you want to know more about the PHP variable scope read this answer from deceze. He made a good job explaining this topic here: https://stackoverflow.com/a/16959577

ContentLicense: CC BY-SA 4.0


问:
Array in VBA + Excel
I have written a macro, which should read the value in every sheet (Row and Column) based on the value given it should Lock the cell or leave it unlocked. The way the code is written right now it takes forever to compute. I was suggested it be done using arrays. However the array are also not working

My excel file has got 15 sheets.
My Code is below.

```<code>Private Sub Workbook_Open()

    Dim sh As Object
    Dim sheetnames As String
    Dim i As Integer
    Dim col As Range
    Dim rng As Variant: Set rng = Application.Range("I16:BI300") 'Value Lock & Unlock is in Column Range I16 to BI16 and Row Range B16 to B300
    Dim rngCell As Variant

    Application.ScreenUpdating = False

        For Each sh In Sheets 'First Each

            If sh.Name <> "Configuration" Then 'Configuration If
                sheetnames = sh.Name
                Worksheets(sheetnames).Activate
                ActiveSheet.Unprotect Password:="sos"

                For Each rngCell In Range("I22:BI300")

                    If (Cells(1, rngCell.Column) = "Lock" And Cells(rngCell.Row, 1) = "Lock") Or (Cells(1, rngCell.Column) = "UnLock" And Cells(rngCell.Row, 1) = "Lock") Or (Cells(1, rngCell.Column) = "Lock" And Cells(rngCell.Row, 1) = "Unlock") Then
                        rngCell.Locked = True
                        rngCell.Font.Color = -16776961
                    Else
                        rngCell.Locked = False
                        rngCell.Font.ColorIndex = xlAutomatic
                    End If

                Next rngCell

                ActiveSheet.Protect Password:="sos"
            End If 'End of Configuration If

        Next sh 'End of First Each

    Sheets(1).Select

End Sub
</code>```

Based on a combination of values in Column and Rows the result should produce values.

```<code>Column  Row Value
Lock    Lock    Lock
Unlock  Lock    Lock
Lock    Unlock  Lock
Unlock  Unlock  Unlock
</code>```

答:
I'm not sure how arrays would speed this up as really it is the locking/unlocking of cells which is causing the main speed issue (Although arrays could improve the read time). Anyway, I'd suggest setting the values you wish to lock/unlock to a range and then doing them all in one go instead of individually as that will be where your main performance impact is.</p>

```<code>Private Sub Workbook_Open()
    Dim sh As Object
    Dim sheetnames As String
    Dim i As Integer
    Dim col As Range, LockRng As Range, UnLockRng As Range
    Dim rng As Variant: Set rng = Application.Range("I16:BI300") 'Value Lock & Unlock is in Column Range I16 to BI16 and Row Range B16 to B300
    Dim rngCell     As Variant
    Application.ScreenUpdating = False
        For Each sh In Sheets   'First Each
            ' Reset Ranges for each sheet
            Set LockRng = Nothing
            Set UnLockRng = Nothing

            If sh.Name <> "Configuration" Then      'Configuration If
                sheetnames = sh.Name
                Worksheets(sheetnames).Activate
                ActiveSheet.Unprotect Password:="sos"
                For Each rngCell In Range("I22:BI300")
                    If (Cells(1, rngCell.Column) = "Lock" And Cells(rngCell.Row, 1) = "Lock") _
                        Or (Cells(1, rngCell.Column) = "UnLock" And Cells(rngCell.Row, 1) = "Lock") _
                        Or (Cells(1, rngCell.Column) = "Lock" And Cells(rngCell.Row, 1) = "Unlock") Then
                            ' Create LockRng
                            If LockRng Is Nothing Then
                                Set LockRng = rngCell
                            Else
                                Set LockRng = Union(LockRng, rngCell)
                            End If
                    Else
                        ' Create UnLockRng
                        If UnLockRng Is Nothing Then
                            Set UnLockRng = rngCell
                        Else
                            Set UnLockRng = Union(UnLockRng, rngCell)
                        End If
                    End If
                Next rngCell
                ActiveSheet.Protect Password:="sos"
            End If                      'End of Configuration If
            ' Lock all cells in LockRng
            If Not LockRng Is Nothing Then
                LockRng.Locked = True
                LockRng.Font.Color = -16776961
            End If
            ' Unlock all cells in UnLockRng
            If Not UnLockRng Is Nothing Then
                UnLockRng.Locked = False
                UnLockRng.Font.ColorIndex = xlAutomatic
            End If
        Next sh     'End of First Each
    Sheets(1).Select
End Sub
</code>```

Title: Array in VBA + Excel

Body:
I have written a macro, which should read the value in every sheet (Row and Column) based on the value given it should Lock the cell or leave it unlocked. The way the code is written right now it takes forever to compute. I was suggested it be done using arrays. However the array are also not working

My excel file has got 15 sheets.
My Code is below.

Private Sub Workbook_Open()

    Dim sh As Object
    Dim sheetnames As String
    Dim i As Integer
    Dim col As Range
    Dim rng As Variant: Set rng = Application.Range("I16:BI300") 'Value Lock & Unlock is in Column Range I16 to BI16 and Row Range B16 to B300
    Dim rngCell As Variant

    Application.ScreenUpdating = False

        For Each sh In Sheets 'First Each

            If sh.Name <> "Configuration" Then 'Configuration If
                sheetnames = sh.Name
                Worksheets(sheetnames).Activate
                ActiveSheet.Unprotect Password:="sos"

                For Each rngCell In Range("I22:BI300")

                    If (Cells(1, rngCell.Column) = "Lock" And Cells(rngCell.Row, 1) = "Lock") Or (Cells(1, rngCell.Column) = "UnLock" And Cells(rngCell.Row, 1) = "Lock") Or (Cells(1, rngCell.Column) = "Lock" And Cells(rngCell.Row, 1) = "Unlock") Then
                        rngCell.Locked = True
                        rngCell.Font.Color = -16776961
                    Else
                        rngCell.Locked = False
                        rngCell.Font.ColorIndex = xlAutomatic
                    End If

                Next rngCell

                ActiveSheet.Protect Password:="sos"
            End If 'End of Configuration If

        Next sh 'End of First Each

    Sheets(1).Select

End Sub

Based on a combination of values in Column and Rows the result should produce values.

Column  Row Value
Lock    Lock    Lock
Unlock  Lock    Lock
Lock    Unlock  Lock
Unlock  Unlock  Unlock

Body:
I'm not sure how arrays would speed this up as really it is the locking/unlocking of cells which is causing the main speed issue (Although arrays could improve the read time). Anyway, I'd suggest setting the values you wish to lock/unlock to a range and then doing them all in one go instead of individually as that will be where your main performance impact is.

Private Sub Workbook_Open()
    Dim sh As Object
    Dim sheetnames As String
    Dim i As Integer
    Dim col As Range, LockRng As Range, UnLockRng As Range
    Dim rng As Variant: Set rng = Application.Range("I16:BI300") 'Value Lock & Unlock is in Column Range I16 to BI16 and Row Range B16 to B300
    Dim rngCell     As Variant
    Application.ScreenUpdating = False
        For Each sh In Sheets   'First Each
            ' Reset Ranges for each sheet
            Set LockRng = Nothing
            Set UnLockRng = Nothing

            If sh.Name <> "Configuration" Then      'Configuration If
                sheetnames = sh.Name
                Worksheets(sheetnames).Activate
                ActiveSheet.Unprotect Password:="sos"
                For Each rngCell In Range("I22:BI300")
                    If (Cells(1, rngCell.Column) = "Lock" And Cells(rngCell.Row, 1) = "Lock") _
                        Or (Cells(1, rngCell.Column) = "UnLock" And Cells(rngCell.Row, 1) = "Lock") _
                        Or (Cells(1, rngCell.Column) = "Lock" And Cells(rngCell.Row, 1) = "Unlock") Then
                            ' Create LockRng
                            If LockRng Is Nothing Then
                                Set LockRng = rngCell
                            Else
                                Set LockRng = Union(LockRng, rngCell)
                            End If
                    Else
                        ' Create UnLockRng
                        If UnLockRng Is Nothing Then
                            Set UnLockRng = rngCell
                        Else
                            Set UnLockRng = Union(UnLockRng, rngCell)
                        End If
                    End If
                Next rngCell
                ActiveSheet.Protect Password:="sos"
            End If                      'End of Configuration If
            ' Lock all cells in LockRng
            If Not LockRng Is Nothing Then
                LockRng.Locked = True
                LockRng.Font.Color = -16776961
            End If
            ' Unlock all cells in UnLockRng
            If Not UnLockRng Is Nothing Then
                UnLockRng.Locked = False
                UnLockRng.Font.ColorIndex = xlAutomatic
            End If
        Next sh     'End of First Each
    Sheets(1).Select
End Sub


问:
Fix CORS header Access-Control-Allow-Origin missing on plugin development on eclipse

 -I am try to make a modular application using eclipse plugin development and  using jax-rs.

 -I want to access an event source created by jetty server and translate each event in time.

-When i try to access the event i am get this error in firefox that run my client html 5 page :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9050/services/events. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

-I know that i must configure the server , but i don't have .htaccess and no web-inf dir.

 -Is there any to declare this file in the vm arguments using eclipse ?
 -Is there any other way to do it ?

-I don't have WEB-INF directory and i don't know if it supported in this plugin development approach.

 -I don't have main function I have only bundles (activator, ect.) and I don't have main function .

-I also have manifest.mf file

Any help is accepted.Thanks in advance!

答:
Try implementing a response filter which would add your needed headers to the response.

```<code>@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        // the wildcard char `*` will allow any origin
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        // add anything and everything you need
        responseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type");
        responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        // etc
    }
}
</code>```

Don't forget to register it.

Body:
Try implementing a response filter which would add your needed headers to the response.

@Provider
public class CORSFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException {
        // the wildcard char `*` will allow any origin
        responseContext.getHeaders().add("Access-Control-Allow-Origin", "*");
        // add anything and everything you need
        responseContext.getHeaders().add("Access-Control-Allow-Headers", "origin, content-type");
        responseContext.getHeaders().add("Access-Control-Allow-Credentials", "true");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
        // etc
    }
}

Don't forget to register it.


问:
Missing App Store Icon. iOS Apps must include a 1024x1024px App Store > Icon in PNG format
when I try to submit the app

Missing App Store Icon. iOS Apps must include a 1024x1024px App Store
  Icon in PNG format. Without providing the icon in the Asset Catalog or
  via iTunes Connect, apps cannot be submitted for App Review or Beta
  App Review

I'm providing App Store Icon with 1024px*1024px PNG format in iTunes Connect but still getting this error

答:
I'll quote just what Claude31 said here: https://forums.developer.apple.com/thread/90543

May be useless question, but have you check the exact size of png image (in finder information) ?

In my case, the client sent an image to me called xxxx1024x1024.png, and the real size was 4000 x 4000. So, if you didn't create the image, is worth checking it.


问:
Using a color from a dataframe as the color of a line for seaborn's pointplot
I currently have a large pandas dataframe which has columns which I have structured as:

```<code>Groups  variable  value  method  color
</code>```

I then use pointplot to create a multiple lineplot with each line as a different color. Originally I used hue to do this over the method values, however I end up having to create a few of these dataframes, each with a different order in how I put the method in (because I sort over one method, then make that chunk of data the first entries into the dataframe, and do this for several different methods). I want each method to be associated with only one color, so that it is consistent across all of the pointplots that I make. So, I created a new column called color which holds the RGB value that I want to be associated to that method. I come across some issues, however, when I try to plot this:

```<code>g = sns.pointplot(x="Groups",jitter=0.3,alpha=0.7,size=15,y="value", color=result1['color'],data=result1[result1['variable']=="Accuracy"])
</code>```

This causes a TypeError, though, as Series objects are mutable, thus cannot be hashed. Is there a proper way of doing this?

答:
You want to use palette, instead of color if you are specifying multiple colors from Seaborn Docs</p>

```<code>g = sns.pointplot(x="Groups",jitter=0.3,alpha=0.7,size=15,y="value", palette=result1['color'],data=result1[result1['variable']=="Accuracy"])
</code>```

Body:
I currently have a large pandas dataframe which has columns which I have structured as:

Groups  variable  value  method  color

I then use pointplot to create a multiple lineplot with each line as a different color. Originally I used hue to do this over the method values, however I end up having to create a few of these dataframes, each with a different order in how I put the method in (because I sort over one method, then make that chunk of data the first entries into the dataframe, and do this for several different methods). I want each method to be associated with only one color, so that it is consistent across all of the pointplots that I make. So, I created a new column called color which holds the RGB value that I want to be associated to that method. I come across some issues, however, when I try to plot this:

g = sns.pointplot(x="Groups",jitter=0.3,alpha=0.7,size=15,y="value", color=result1['color'],data=result1[result1['variable']=="Accuracy"])

This causes a TypeError, though, as Series objects are mutable, thus cannot be hashed. Is there a proper way of doing this?

Body:
You want to use palette, instead of color if you are specifying multiple colors from Seaborn Docs

g = sns.pointplot(x="Groups",jitter=0.3,alpha=0.7,size=15,y="value", palette=result1['color'],data=result1[result1['variable']=="Accuracy"])


问:
Select, default value in AngularJS
Hey I have problem with set default value in select problem is started when I set inside array objects. How can I fix this problem??

HTML

```<code><div ng-app="select" ng-controller="checking">
  <select ng-model="lala" ng-options="item.name for item in arrayName">
  </select>
</div>
</code>```

JavaScript

```<code>var app = angular.module('select', []);

app.controller('checking', ($scope)=> {
  $scope.arrayName = [{'name':'first'}, {'name':'second'}, {'name':'third'}];
  $scope.lala = "first";
});
</code>```

https://codepen.io/Turqus/pen/EbvGzv?editors=1111

答:
Well you can achieve it by using ng-init as below

```<code><div ng-app="select" ng-controller="checking">

  <select ng-init="lala = arrayName[0]" ng-model="lala" ng-options="item.name for item in arrayName"  >

  </select>
</div>

<script>
    var app = angular.module('select', []);

    app.controller('checking', ($scope)=> {
      $scope.arrayName = [{'name':'first'}, {'name':'second'}, {'name':'third'}];
      $scope.lala = "first";
    });
<script>
</code>```

here is the codepen example and hope it will help.

Title: Select, default value in AngularJS

Body:
Hey I have problem with set default value in select problem is started when I set inside array objects. How can I fix this problem??

HTML

  <select ng-model="lala" ng-options="item.name for item in arrayName">
  </select>

JavaScript

var app = angular.module('select', []);

app.controller('checking', ($scope)=> {
  $scope.arrayName = [{'name':'first'}, {'name':'second'}, {'name':'third'}];
  $scope.lala = "first";
});

https://codepen.io/Turqus/pen/EbvGzv?editors=1111

Body:
Well you can achieve it by using ng-init as below

<div ng-app="select" ng-controller="checking">

  <select ng-init="lala = arrayName[0]" ng-model="lala" ng-options="item.name for item in arrayName"  >

  </select>
</div>

<script>
    var app = angular.module('select', []);

    app.controller('checking', ($scope)=> {
      $scope.arrayName = [{'name':'first'}, {'name':'second'}, {'name':'third'}];
      $scope.lala = "first";
    });
<script>

here is the codepen example and hope it will help.


问:
How can I run something Async in OncreateView?
I have a problem with my app. Firstly, I made two Tabs using fragments which inflates an activity. The tabs implemented is working fine. Secondly i have  displayed the XAML right.

However, I now need to run something asynchronously in
OnCreateView in the Fragment. How can i manage this without getting errors?

Any help is greatly appreciated! Thanks

Here is my Fragment:

```<code>public class FragmentSettings : SupportFragment
{
    private Button mBtnOk;

    public FragmentSettings(Context context)
    {
        mContext = context;
    }

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        //Inflate the fragment XML
        View view = inflater.Inflate(Resource.Layout.FragmentSettings, container, false);

        //Grab the butten from the inflated fragment
        mBtnOk = view.FindViewById<Button>(Resource.Id.mBtnOk);
        mBtnOk.Click += (object sender, EventArgs e) =>
        {
            //DO stuff
        };
        //=====================================
        //Want to do something async stuff here
        //=====================================

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

答:
I would just use a Backgroundworker, if you need stuff done in the background:

```<code>BackgroundWorker bworker;

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    //Inflate the fragment XML
    View view = inflater.Inflate(Resource.Layout.FragmentSettings, container, false);

    //Grab the butten from the inflated fragment
    mBtnOk = view.FindViewById<Button>(Resource.Id.mBtnOk);
    mBtnOk.Click += (object sender, EventArgs e) =>
    {
        //DO stuff
    };

    //Start background task
    bworker = new BackgroundWorker();
    bworker.DoWork += Bworker_DoWork;
    bworker.RunWorkerCompleted += Bworker_RunWorkerCompleted;
    bworker.RunWorkerAsync();

    return view;
}

private void Bworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
   //Do stuff when the operation is completed
    bworker.RunWorkerAsync();
}

private void Bworker_DoWork(object sender, DoWorkEventArgs e)
{
    //Do the work in the background
}
</code>```

EDIT: To make it run continuously, you can start the backgroundworker agin in the Bworker_RunWorkerCompleted method. (see the method)

I just dont think it is a good way implement a continuous thread, since i got the feeling it will take up alot of memory. You can try though.

Body:
I have a problem with my app. Firstly, I made two Tabs using fragments which inflates an activity. The tabs implemented is working fine. Secondly i have  displayed the XAML right.

However, I now need to run something asynchronously in
OnCreateView in the Fragment. How can i manage this without getting errors?

Any help is greatly appreciated! Thanks

Here is my Fragment:

public class FragmentSettings : SupportFragment
{
    private Button mBtnOk;

    public FragmentSettings(Context context)
    {
        mContext = context;
    }

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        //Inflate the fragment XML
        View view = inflater.Inflate(Resource.Layout.FragmentSettings, container, false);

        //Grab the butten from the inflated fragment
        mBtnOk = view.FindViewById<Button>(Resource.Id.mBtnOk);
        mBtnOk.Click += (object sender, EventArgs e) =>
        {
            //DO stuff
        };
        //=====================================
        //Want to do something async stuff here
        //=====================================

        return view;
    }
}

Body:
I would just use a Backgroundworker, if you need stuff done in the background:

BackgroundWorker bworker;

public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    //Inflate the fragment XML
    View view = inflater.Inflate(Resource.Layout.FragmentSettings, container, false);

    //Grab the butten from the inflated fragment
    mBtnOk = view.FindViewById<Button>(Resource.Id.mBtnOk);
    mBtnOk.Click += (object sender, EventArgs e) =>
    {
        //DO stuff
    };

    //Start background task
    bworker = new BackgroundWorker();
    bworker.DoWork += Bworker_DoWork;
    bworker.RunWorkerCompleted += Bworker_RunWorkerCompleted;
    bworker.RunWorkerAsync();

    return view;
}

private void Bworker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
   //Do stuff when the operation is completed
    bworker.RunWorkerAsync();
}

private void Bworker_DoWork(object sender, DoWorkEventArgs e)
{
    //Do the work in the background
}

EDIT: To make it run continuously, you can start the backgroundworker agin in the Bworker_RunWorkerCompleted method. (see the method)

I just dont think it is a good way implement a continuous thread, since i got the feeling it will take up alot of memory. You can try though.


问:
Relative layout disperse on real device
In  android studio3.0 in design  tab have this kind of layout

But on real  device i have this crap:

What i do wrong?  Please help.

答:
the layout:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        android:id="@+id/view">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar_add_todo"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:elevation="4dp"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    </android.support.design.widget.AppBarLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/view"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin">

        <!--task label-->
        <TextView
            android:id="@+id/TitleLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:focusableInTouchMode="true"
            android:text="@string/title_string"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/colorAccent"
            android:textSize="@dimen/label_size"/>

        <EditText
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/TitleLabel"
            android:hint="@string/enter_title_string"
            android:inputType="textShortMessage"
            android:text=""
            android:textAppearance="?android:attr/textAppearanceLarge"/>
            <requestFocus />

        <!-- Description -->
        <TextView
            android:id="@+id/DescriptionLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/title"
            android:text="@string/description_string"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/colorAccent"
            android:textSize="@dimen/label_size"/>

        <EditText
            android:id="@+id/description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/DescriptionLabel"
            android:hint="@string/enter_description_string"
            android:inputType="textEmailAddress|textMultiLine"
            android:lines="10"
            android:minLines="2"
            android:scrollbars="vertical"
            android:singleLine="false"
            android:text=""
            android:textAppearance="?android:attr/textAppearanceLarge">
        </EditText>

        <!--Deadline time-->
        <!-- Time and Date -->
        <TextView
            android:id="@+id/time_and_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/description"
            android:text="@string/time_and_date_string"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/colorAccent" />

        <TextView
            android:id="@+id/date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/time_and_date"
            android:layout_toRightOf="@+id/time_and_date"
            android:layout_marginLeft="10dp"
            android:text="@string/no_date_set_string"
            android:textColor="@color/colorAccent"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/time_and_date"
            android:layout_toRightOf="@+id/date"
            android:layout_marginLeft="50dp"
            android:text="@string/no_time_set_string"
            android:textColor="@color/colorAccent"
            android:textSize="20dp" />

        <Button
            android:id="@+id/date_picker"
            style="@style/AppTheme.AppBarOverlay"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/date"
            android:layout_toRightOf="@+id/time_and_date"
            android:textSize="15sp"
            android:text="@string/choose_date_string" />

        <Button
            android:id="@+id/time_picker"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/date"
            android:layout_below="@id/time"
            android:textSize="15sp"
            android:text="@string/choose_time_string" />

        <TextView
            android:id="@+id/alarm_me"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignStart="@+id/time_and_date"
            android:layout_below="@+id/date_picker"
            android:layout_marginTop="15dp"
            android:text="@string/alarm_me_string"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/colorAccent" />

        <CheckBox
            android:id="@+id/alarmCheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/alarm_me"
            android:layout_toEndOf="@+id/DescriptionLabel"
            android:hint="@string/alarm_hint"
            android:textColor="@color/colorPrimaryDark"></CheckBox>

        <TextView
            android:id="@+id/complete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignEnd="@+id/alarm_me"
            android:layout_alignStart="@+id/alarm_me"
            android:layout_below="@+id/alarm_me"
            android:layout_marginTop="15dp"
            android:text="@string/complete_string"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/colorAccent" />

        <CheckBox
            android:id="@+id/completeCheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/complete"
            android:layout_alignStart="@+id/alarmCheckBox"
            android:layout_toEndOf="@+id/DescriptionLabel"
            android:textColor="@color/colorPrimaryDark"></CheckBox>

        <Button
            android:id="@+id/cancelButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/completeCheckBox"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="30dp"
            android:layout_toStartOf="@+id/completeCheckBox"
            android:text="@string/cancel_string" />

        <Button
            android:id="@+id/submitButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignEnd="@+id/alarmCheckBox"
            android:layout_alignTop="@+id/cancelButton"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:text="@string/submit_string" />

    </RelativeLayout>

</RelativeLayout>
</code>```

Title: Relative layout disperse on real device

Body:
the layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        android:id="@+id/view">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar_add_todo"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            android:elevation="4dp"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    </android.support.design.widget.AppBarLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/view"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin">

        <!--task label-->
        <TextView
            android:id="@+id/TitleLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:focusableInTouchMode="true"
            android:text="@string/title_string"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/colorAccent"
            android:textSize="@dimen/label_size"/>

        <EditText
            android:id="@+id/title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/TitleLabel"
            android:hint="@string/enter_title_string"
            android:inputType="textShortMessage"
            android:text=""
            android:textAppearance="?android:attr/textAppearanceLarge"/>
            <requestFocus />

        <!-- Description -->
        <TextView
            android:id="@+id/DescriptionLabel"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/title"
            android:text="@string/description_string"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/colorAccent"
            android:textSize="@dimen/label_size"/>

        <EditText
            android:id="@+id/description"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/DescriptionLabel"
            android:hint="@string/enter_description_string"
            android:inputType="textEmailAddress|textMultiLine"
            android:lines="10"
            android:minLines="2"
            android:scrollbars="vertical"
            android:singleLine="false"
            android:text=""
            android:textAppearance="?android:attr/textAppearanceLarge">
        </EditText>

        <!--Deadline time-->
        <!-- Time and Date -->
        <TextView
            android:id="@+id/time_and_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/description"
            android:text="@string/time_and_date_string"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/colorAccent" />

        <TextView
            android:id="@+id/date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/time_and_date"
            android:layout_toRightOf="@+id/time_and_date"
            android:layout_marginLeft="10dp"
            android:text="@string/no_date_set_string"
            android:textColor="@color/colorAccent"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/time"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBaseline="@+id/time_and_date"
            android:layout_toRightOf="@+id/date"
            android:layout_marginLeft="50dp"
            android:text="@string/no_time_set_string"
            android:textColor="@color/colorAccent"
            android:textSize="20dp" />

        <Button
            android:id="@+id/date_picker"
            style="@style/AppTheme.AppBarOverlay"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/date"
            android:layout_toRightOf="@+id/time_and_date"
            android:textSize="15sp"
            android:text="@string/choose_date_string" />

        <Button
            android:id="@+id/time_picker"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@+id/date"
            android:layout_below="@id/time"
            android:textSize="15sp"
            android:text="@string/choose_time_string" />

        <TextView
            android:id="@+id/alarm_me"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignStart="@+id/time_and_date"
            android:layout_below="@+id/date_picker"
            android:layout_marginTop="15dp"
            android:text="@string/alarm_me_string"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/colorAccent" />

        <CheckBox
            android:id="@+id/alarmCheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/alarm_me"
            android:layout_toEndOf="@+id/DescriptionLabel"
            android:hint="@string/alarm_hint"
            android:textColor="@color/colorPrimaryDark"></CheckBox>

        <TextView
            android:id="@+id/complete"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignEnd="@+id/alarm_me"
            android:layout_alignStart="@+id/alarm_me"
            android:layout_below="@+id/alarm_me"
            android:layout_marginTop="15dp"
            android:text="@string/complete_string"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textColor="@color/colorAccent" />

        <CheckBox
            android:id="@+id/completeCheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/complete"
            android:layout_alignStart="@+id/alarmCheckBox"
            android:layout_toEndOf="@+id/DescriptionLabel"
            android:textColor="@color/colorPrimaryDark"></CheckBox>

        <Button
            android:id="@+id/cancelButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/completeCheckBox"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginTop="30dp"
            android:layout_toStartOf="@+id/completeCheckBox"
            android:text="@string/cancel_string" />

        <Button
            android:id="@+id/submitButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignEnd="@+id/alarmCheckBox"
            android:layout_alignTop="@+id/cancelButton"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:text="@string/submit_string" />

    </RelativeLayout>

</RelativeLayout>


问:
mod rewrite Rule for Image + String to Imagefolder Rewrite
I have got some images on my server, which were always generated on the fly and requested right here:
http://www.mydomain.com/en/images.png?domain=test.com

They are now cached in
http://www.mydomain.com/images/test.com.png

I tried the following rule in my htaccess, but it doesn't work:

RewriteRule ^(en|de)?/images.png\?domain=(.*) /images/$2.png   [QSA,L]

Any clue what's wrong?

答:
At first glance, you probably need to escape the question mark that is part of the URL.</p>

```<code>RewriteRule ^(en|de)?/images.png\?domain=(.*) /images/$2.png [QSA,L]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
At first glance, you probably need to escape the question mark that is part of the URL.

RewriteRule ^(en|de)?/images.png\?domain=(.*) /images/$2.png [QSA,L]


问:
open url function not called in AppDelegate when trying to grab token from oauth url
I'm trying to implement an OAuth flow on iOS - Swift 3, in order to query a REST API (Strava).

I do this in my VC handling the auth flow:

```<code>@IBAction func tappedStartAuth(_ sender: Any) {

    let authUrlStr = "http://www.strava.com/oauth/authorize?client_id=12345&response_type=code&redirect_uri=http://localhost/exchange_token&approval_prompt=force&scope=view_private,write"

    // but instead 12345 I have my real cientID of course

    UIApplication.shared.openURL(URL(string:authUrlStr)!)

    // Did not work with SFVC either:
    //safariViewController = SFSafariViewController(url: URL(string: authUrlStr)!)
    //safariViewController?.delegate = self
    //present(safariViewController!, animated: true, completion: nil)
</code>```

}

In my AppDelegate:

```<code>func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

    print("opened url, [code] checking should follow, but this won't get called")

    // would do some stuff here...

    return true
}
</code>```

And I added my url scheme in the plist:

```<code><key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLName</key>
        <string>org.my.bundle.id</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>localhost</string>
        </array>
    </dict>
</array>
</code>```

However, I can't get the application(_:open:options:) function in my AppDelegate to be called.

(The browser is popped up allright, I can login to Strava, and I see that the valid URL is returned including the access token in the "code=..." piece, that I would like to extract, but I can't move on to that part.)

I've tried:

with the built-in Safari browser (leaving the app)

with SFSafariViewController

on iOS 9 instead of 11 (I know that on 11 apple has introduced
SFAuthenticationSession, as described here. I have not looked
into that yet, but I would need my app on pre-11 too).

My application(_:didFinishLaunchingWithOptions:) function is
returning true and I'm not implementing
application(_:willFinishLaunchingWithOptions:) as described in the discussion part of the function's docs.

Any ideas what I could be missing?

Cheers

答:
So it was actually a mixture of things that I did not notice...

The URL I was trying to use there was wrong: It should not be
http:// but yourApp:// since you want yourApp to handle the
callback.  On some forum I read that Strava only allows http redirect
uris, which made me try it that way, but that's actually wrong, as
the documentation states:

URL to which the user will be redirected with the authorization code, must be to the callback domain associated with the application, or its sub-domain, localhost and 127.0.0.1 are white-listed.

And we got to the next thing, namely:

You should check what you name your application on the Strava admin page at Settings/My Api Application.
Following the yourApp example, it should be something like this:

(My mistake was, that I did not provide a valid/matching callback domain.)

Finally, your plist file should be also set accordingly:

        <key>CFBundleURLTypes</key>
        <array>
            <dict>
                <key>CFBundleURLName</key>
                <string>com.yourdomain.yourApp</string>
                <key>CFBundleURLSchemes</key>
                <array>
                    <string>yourApp</string>
                </array>
            </dict>
        </array>
```

And it works like charm: it does not actually matter if it's iOS 9 or 11, or you use SFSafariViewController VS you leave the app with UIApplication.shared.openURL() etc...

Good luck ;)

Body:
I'm trying to implement an OAuth flow on iOS - Swift 3, in order to query a REST API (Strava).

I do this in my VC handling the auth flow:

@IBAction func tappedStartAuth(_ sender: Any) {

    let authUrlStr = "http://www.strava.com/oauth/authorize?client_id=12345&response_type=code&redirect_uri=http://localhost/exchange_token&approval_prompt=force&scope=view_private,write"

    // but instead 12345 I have my real cientID of course

    UIApplication.shared.openURL(URL(string:authUrlStr)!)

    // Did not work with SFVC either:
    //safariViewController = SFSafariViewController(url: URL(string: authUrlStr)!)
    //safariViewController?.delegate = self
    //present(safariViewController!, animated: true, completion: nil)

}

In my AppDelegate:

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

    print("opened url, [code] checking should follow, but this won't get called")

    // would do some stuff here...

    return true
}

And I added my url scheme in the plist:

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLName</key>
        <string>org.my.bundle.id</string>
        <key>CFBundleURLSchemes</key>
        <array>
            <string>localhost</string>
        </array>
    </dict>
</array>

However, I can't get the application(_:open:options:) function in my AppDelegate to be called.

(The browser is popped up allright, I can login to Strava, and I see that the valid URL is returned including the access token in the "code=..." piece, that I would like to extract, but I can't move on to that part.)

I've tried:

with the built-in Safari browser (leaving the app)

with SFSafariViewController

on iOS 9 instead of 11 (I know that on 11 apple has introduced
SFAuthenticationSession, as described here. I have not looked
into that yet, but I would need my app on pre-11 too).

My application(_:didFinishLaunchingWithOptions:) function is
returning true and I'm not implementing
application(_:willFinishLaunchingWithOptions:) as described in the discussion part of the function's docs.

Any ideas what I could be missing?

Cheers

Body:
So it was actually a mixture of things that I did not notice...

The URL I was trying to use there was wrong: It should not be
http:// but yourApp:// since you want yourApp to handle the
callback.  On some forum I read that Strava only allows http redirect
uris, which made me try it that way, but that's actually wrong, as
the documentation states:

URL to which the user will be redirected with the authorization code, must be to the callback domain associated with the application, or its sub-domain, localhost and 127.0.0.1 are white-listed.

And we got to the next thing, namely:

You should check what you name your application on the Strava admin page at Settings/My Api Application.
Following the yourApp example, it should be something like this:

(My mistake was, that I did not provide a valid/matching callback domain.)

Finally, your plist file should be also set accordingly:

        <key>CFBundleURLTypes</key>
        <array>
            <dict>
                <key>CFBundleURLName</key>
                <string>com.yourdomain.yourApp</string>
                <key>CFBundleURLSchemes</key>
                <array>
                    <string>yourApp</string>
                </array>
            </dict>
        </array>

And it works like charm: it does not actually matter if it's iOS 9 or 11, or you use SFSafariViewController VS you leave the app with UIApplication.shared.openURL() etc...

Good luck ;)


问:
TYPO3 v8 how can i change default rte from ckeditor back to rtehtmlarea?
I installed rtehtmlarea from https://github.com/FriendsOfTYPO3/rtehtmlarea (i use typo3 v8.7.8). Now, how do i set it to be default rte ? In my User Settings -> Edit and Advanced functions -> Enable Rich Text Editor (if available) is checked. Also i tried changing RTE.default.disabled = 1 as in documentation without success. Is it relevant, or is there other settings i need to be looking at?

答:
a) Unload extension rte_ckeditor - rtehtmlarea will then kick in

b) Raise the priority of $GLOBALS['TYPO3_CONF_VARS']['SYS']['formEngine']['nodeResolver'][1480314091]['priority'] (this is the htmlarea element resolver) above 50 (higher than the ckeditor resolver priority which is 50) to take precendence - see the two form element resolver registrations in ext_localconf.php of ext:rtehtmlarea and ext:rte_ckeditor

c) If you want ckeditor in some places and htmlarea in others depending on edited element (table / record type / ...): Add an own resolver with priority higher than 50 and do your magic in there. See \TYPO3\CMS\RteCKEditor\Form\Resolver\RichTextNodeResolver and \TYPO3\CMS\Rtehtmlarea\Form\Resolver\RichTextNodeResolver as examples on how to do that.

The FormEngine resolvers are also documented at https://docs.typo3.org/typo3cms/CoreApiReference/ApiOverview/FormEngine/Rendering/Index.html#nodefactory


问:
UICollectionView inside CustomTableCell
I have some problem when trying to implement UICollectionView with custom cell inside custom cell in tableView.
I have custom table view cell which works fine, showing my label as I want.

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    TemperatureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath: indexPath];
    Node *node = [[Node alloc] init];
    if(_nodes != nil){
        node = [_nodes objectAtIndex:indexPath.row];
        if(_tempSensorsDictionary.count > 0){
            NSArray *allSensors = [_tempSensorsDictionary objectForKey:node.number];
            TemperatureSensor *ts = allSensors[0];
            if(node.name != nil && ![node.name  isEqual: @""]){
                cell.unitNameLabel.text = node.name;
            } else {
                cell.unitNameLabel.text = node.number;
            }
            cell.collection = [_tempSensorsDictionary objectForKey:node.number];
        }
    }
    return cell;
}
</code>```

I have set up CollectionView background to gray colour and I can see this "box". So I guess that CollectionView is initialised properly in my TemperatureTaleViewCell class where I putted:

```<code>@implementation TemperatureTableViewCell
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

    if (!(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) return nil;

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    [flowLayout setItemSize:CGSizeMake(50, 50)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.collectionView = [[CollectionView alloc] initWithFrame: CGRectZero collectionViewLayout:flowLayout];
    [self.collectionView registerClass:[TemperatureItemCollectionViewCell class] forCellWithReuseIdentifier:@"TemperatureItemCollectionCell"];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;

    [self.collectionView reloadData];
    [self.contentView addSubview:self.collectionView];
    return self;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 2;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    TemperatureItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TemperatureItemCollectionCell" forIndexPath:indexPath];
    cell.tempValTempCollViewCell.text = @"21oC";
    cell.backgroundColor = [UIColor redColor];

    return cell;

}
@end
</code>```

But then my table view looks like this:

What is wrong in my code and where is wrong direction?

答:
Need to reload collection view data inside tableview cellForRowAtIndexPath method.

```<code>-(void)tableView:(UITableView *)tableView willDisplayCell:(CategoryCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell setCollectionViewDelegate:self indexPath:indexPath];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    TemperatureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath: indexPath];
    Node *node = [[Node alloc] init];
    if(_nodes != nil){
        node = [_nodes objectAtIndex:indexPath.row];
        if(_tempSensorsDictionary.count > 0){
            NSArray *allSensors = [_tempSensorsDictionary objectForKey:node.number];
            TemperatureSensor *ts = allSensors[0];
            if(node.name != nil && ![node.name  isEqual: @""]){
                cell.unitNameLabel.text = node.name;
            } else {
                cell.unitNameLabel.text = node.number;
            }
            cell.collection = [_tempSensorsDictionary objectForKey:node.number];

            //Reload collection view data
            [cell.collectionView reloadData];
        }
    }
    return cell;
}
</code>```

Use awakeFromNib method insted of table view initWithStyle method.

```<code>- (void)awakeFromNib
{
    [super awakeFromNib];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    [flowLayout setItemSize:CGSizeMake(50, 50)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.collectionView = [[CollectionView alloc] initWithFrame: CGRectZero collectionViewLayout:flowLayout];
    [self.collectionView registerClass:[TemperatureItemCollectionViewCell class] forCellWithReuseIdentifier:@"TemperatureItemCollectionCell"];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;

    [self.contentView addSubview:self.collectionView];
}
</code>```

Set delegate of collection view inside TemperatureTaleViewCell class

```<code>- (void)setCollectionViewDelegate:(id)dataSourceDelegate indexPath:(NSIndexPath *)indexPath
{
    self.collectionView.delegate = dataSourceDelegate;
}
</code>```

Title: UICollectionView inside CustomTableCell

Body:
I have some problem when trying to implement UICollectionView with custom cell inside custom cell in tableView.
I have custom table view cell which works fine, showing my label as I want.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    TemperatureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath: indexPath];
    Node *node = [[Node alloc] init];
    if(_nodes != nil){
        node = [_nodes objectAtIndex:indexPath.row];
        if(_tempSensorsDictionary.count > 0){
            NSArray *allSensors = [_tempSensorsDictionary objectForKey:node.number];
            TemperatureSensor *ts = allSensors[0];
            if(node.name != nil && ![node.name  isEqual: @""]){
                cell.unitNameLabel.text = node.name;
            } else {
                cell.unitNameLabel.text = node.number;
            }
            cell.collection = [_tempSensorsDictionary objectForKey:node.number];
        }
    }
    return cell;
}

I have set up CollectionView background to gray colour and I can see this "box". So I guess that CollectionView is initialised properly in my TemperatureTaleViewCell class where I putted:

@implementation TemperatureTableViewCell
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {

    if (!(self = [super initWithStyle:style reuseIdentifier:reuseIdentifier])) return nil;

    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    [flowLayout setItemSize:CGSizeMake(50, 50)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.collectionView = [[CollectionView alloc] initWithFrame: CGRectZero collectionViewLayout:flowLayout];
    [self.collectionView registerClass:[TemperatureItemCollectionViewCell class] forCellWithReuseIdentifier:@"TemperatureItemCollectionCell"];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;

    [self.collectionView reloadData];
    [self.contentView addSubview:self.collectionView];
    return self;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return 2;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    TemperatureItemCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"TemperatureItemCollectionCell" forIndexPath:indexPath];
    cell.tempValTempCollViewCell.text = @"21oC";
    cell.backgroundColor = [UIColor redColor];

    return cell;

}
@end

But then my table view looks like this:

What is wrong in my code and where is wrong direction?

Body:
Need to reload collection view data inside tableview cellForRowAtIndexPath method.

-(void)tableView:(UITableView *)tableView willDisplayCell:(CategoryCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [cell setCollectionViewDelegate:self indexPath:indexPath];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath {
    TemperatureTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath: indexPath];
    Node *node = [[Node alloc] init];
    if(_nodes != nil){
        node = [_nodes objectAtIndex:indexPath.row];
        if(_tempSensorsDictionary.count > 0){
            NSArray *allSensors = [_tempSensorsDictionary objectForKey:node.number];
            TemperatureSensor *ts = allSensors[0];
            if(node.name != nil && ![node.name  isEqual: @""]){
                cell.unitNameLabel.text = node.name;
            } else {
                cell.unitNameLabel.text = node.number;
            }
            cell.collection = [_tempSensorsDictionary objectForKey:node.number];

            //Reload collection view data
            [cell.collectionView reloadData];
        }
    }
    return cell;
}

Use awakeFromNib method insted of table view initWithStyle method.

- (void)awakeFromNib
{
    [super awakeFromNib];
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    [flowLayout setItemSize:CGSizeMake(50, 50)];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    self.collectionView = [[CollectionView alloc] initWithFrame: CGRectZero collectionViewLayout:flowLayout];
    [self.collectionView registerClass:[TemperatureItemCollectionViewCell class] forCellWithReuseIdentifier:@"TemperatureItemCollectionCell"];
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;

    [self.contentView addSubview:self.collectionView];
}

Set delegate of collection view inside TemperatureTaleViewCell class

- (void)setCollectionViewDelegate:(id)dataSourceDelegate indexPath:(NSIndexPath *)indexPath
{
    self.collectionView.delegate = dataSourceDelegate;
}


问:
NavigationView can not to respond to interaction
When I add a custom title bar, it does not respond to user actions.

But remove TextBlock, It is OK.

I have added these code in app.xaml.cs OnLaunched():

//draw into the title bar
CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;

//remove the solid-colored backgrounds behind the caption controls and system back button
ApplicationViewTitleBar titleBar = ApplicationView.GetForCurrentView().TitleBar;
titleBar.ButtonBackgroundColor = Colors.Transparent;
titleBar.ButtonInactiveBackgroundColor = Colors.Transparent;
titleBar.ButtonForegroundColor = Colors.Black;
```

<p>Xaml:</p>

<pre class="lang-xml prettyprint-override"><code><Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <NavigationView x:Name="NavView" AlwaysShowHeader="False" SelectionChanged="NavView_SelectionChanged" DisplayModeChanged="NavView_DisplayModeChanged">

        <NavigationView.MenuItems>
            <NavigationViewItem Content="Home" Tag="home">
                <NavigationViewItem.Icon>
                    <FontIcon Glyph=""/>
                </NavigationViewItem.Icon>
            </NavigationViewItem>
        </NavigationView.MenuItems>

        <NavigationView.AutoSuggestBox>
            <AutoSuggestBox x:Name="ASB" QueryIcon="Find"/>
        </NavigationView.AutoSuggestBox>

        <Frame x:Name="ContentFrame" Margin="24">
            <Frame.ContentTransitions>
                <TransitionCollection>
                    <NavigationThemeTransition/>
                </TransitionCollection>
            </Frame.ContentTransitions>
        </Frame>
    </NavigationView>
    <TextBlock x:Name="AppTitle" Style="{StaticResource CaptionTextBlockStyle}" Text="Test"/>
</Grid>
</code>```

答:
Well, the issue is quite trivial.

Issue:

The reason why you can't interact with your NavigationView when the Textblock is present is because the Textbox is visually on top of the NavigationView. So when you click anywhere on the app, the click is registered on to the Textblock and not the NavigationView.

Consider it like this, the Textbock has a transparent background hence you can't see it being visually covering the whole app area but in your visual studio designer you can see that when you click on the Textblock the selection goes to the whole app area instead of the small section on the text.

Solution:

Well it's quite simple, give your Textbox a Height or Width or some kind of an Alignment (horizontal or vertical), like below:

```<code><TextBlock x:Name="AppTitle" Style="{StaticResource CaptionTextBlockStyle}" VerticalAlignment="Top" HorizontalAlignment="Center" Text="Test"/>
</code>```

Please note: I would highly recommend you use Grid.RowDefinitions and Grid.ColumnDefinitions of the parent grid and Grid.Row and Grid.Column with VerticalAlignment and HorizontalAlignment of your Textblock to align your textbox to keep it more adaptive. Refer to my answer here to have a deeper understanding on keeping your UI adaptive

I hope this helps, please do let me know in case of any queries

Body:
When I add a custom title bar, it does not respond to user actions.

But remove TextBlock, It is OK.

I have added these code in app.xaml.cs OnLaunched():

//draw into the title bar
CoreApplication.GetCurrentView().TitleBar.ExtendViewIntoTitleBar = true;

//remove the solid-colored backgrounds behind the caption controls and system back button
ApplicationViewTitleBar titleBar = ApplicationView.GetForCurrentView().TitleBar;
titleBar.ButtonBackgroundColor = Colors.Transparent;
titleBar.ButtonInactiveBackgroundColor = Colors.Transparent;
titleBar.ButtonForegroundColor = Colors.Black;

Xaml:

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <NavigationView x:Name="NavView" AlwaysShowHeader="False" SelectionChanged="NavView_SelectionChanged" DisplayModeChanged="NavView_DisplayModeChanged">

        <NavigationView.MenuItems>
            <NavigationViewItem Content="Home" Tag="home">
                <NavigationViewItem.Icon>
                    <FontIcon Glyph=""/>
                </NavigationViewItem.Icon>
            </NavigationViewItem>
        </NavigationView.MenuItems>

        <NavigationView.AutoSuggestBox>
            <AutoSuggestBox x:Name="ASB" QueryIcon="Find"/>
        </NavigationView.AutoSuggestBox>

        <Frame x:Name="ContentFrame" Margin="24">
            <Frame.ContentTransitions>
                <TransitionCollection>
                    <NavigationThemeTransition/>
                </TransitionCollection>
            </Frame.ContentTransitions>
        </Frame>
    </NavigationView>
    <TextBlock x:Name="AppTitle" Style="{StaticResource CaptionTextBlockStyle}" Text="Test"/>
</Grid>

Body:
Well, the issue is quite trivial.

Issue:

The reason why you can't interact with your NavigationView when the Textblock is present is because the Textbox is visually on top of the NavigationView. So when you click anywhere on the app, the click is registered on to the Textblock and not the NavigationView.

Consider it like this, the Textbock has a transparent background hence you can't see it being visually covering the whole app area but in your visual studio designer you can see that when you click on the Textblock the selection goes to the whole app area instead of the small section on the text.

Solution:

Well it's quite simple, give your Textbox a Height or Width or some kind of an Alignment (horizontal or vertical), like below:

<TextBlock x:Name="AppTitle" Style="{StaticResource CaptionTextBlockStyle}" VerticalAlignment="Top" HorizontalAlignment="Center" Text="Test"/>

Please note: I would highly recommend you use Grid.RowDefinitions and Grid.ColumnDefinitions of the parent grid and Grid.Row and Grid.Column with VerticalAlignment and HorizontalAlignment of your Textblock to align your textbox to keep it more adaptive. Refer to my answer here to have a deeper understanding on keeping your UI adaptive

I hope this helps, please do let me know in case of any queries


问:
POST immediately after select a file
I have the following HTML code

```<code><form action="/script/upload_key.py" method="POST" enctype="multipart/form-data">
    Key filename: <input name="file_1" type="file">
    <input name="submit" type="submit">
</form>
</code>```

which gives me the following stuff.

I was wondering

How I can use JavaScript, to eliminate the need of Submit button. That's mean, once I Choose File, the selected file will be uploaded immediately?

How can I make sure the field to display selected file name is long enough, so that ... will not be shown?

答:
For the first one:

```<code><input name="file_1" type="file" onchange="this.form.submit()">
</code>```

I'm not sure about making the field wide enough though. Sometimes CSS is crippled on file upload fields to prevent exploits.

Title: POST immediately after select a file

Body:
I have the following HTML code

<form action="/script/upload_key.py" method="POST" enctype="multipart/form-data">
    Key filename: <input name="file_1" type="file">
    <input name="submit" type="submit">
</form>

which gives me the following stuff.

I was wondering

How I can use JavaScript, to eliminate the need of Submit button. That's mean, once I Choose File, the selected file will be uploaded immediately?

How can I make sure the field to display selected file name is long enough, so that ... will not be shown?

Body:
For the first one:

<input name="file_1" type="file" onchange="this.form.submit()">

I'm not sure about making the field wide enough though. Sometimes CSS is crippled on file upload fields to prevent exploits.


问:
Knex query event logs to winston file.
I would like save all knex query event to winston file. I found somthing like this
http://knexjs.org/#Interfaces-Events . Its work good for my but now i have to add

```<code> .on('query-response', function(response, obj, builder)...
</code>```

for each knex query.

I would like add one global function for all qnex query. It is possible?

答:
You can export your knex object from a separate dbConnection file and import it in other file where you need. In your dbConnection file add event listener to knex. Like here:
In your dbConnection file write this:

```<code>const knex = require('knex')({
    //Your db configuration here
});

knex.on('query', console.log);

module.exports = knex;
</code>```

In your other file require it and use it.

```<code>const knex = require('/dbConnection');
</code>```

Title: Knex query event logs to winston file.

Body:
I would like save all knex query event to winston file. I found somthing like this
http://knexjs.org/#Interfaces-Events . Its work good for my but now i have to add

 .on('query-response', function(response, obj, builder)...

for each knex query.

I would like add one global function for all qnex query. It is possible?

Body:
You can export your knex object from a separate dbConnection file and import it in other file where you need. In your dbConnection file add event listener to knex. Like here:
In your dbConnection file write this:

const knex = require('knex')({
    //Your db configuration here
});

knex.on('query', console.log);

module.exports = knex;

In your other file require it and use it.

const knex = require('/dbConnection');