问:
ERROR TypeError: Cannot set property 'username' of undefined
I need to request my api (https://myurl.com/login) for login (username + password) in angular 7.3. When i use POST without user.models.ts i received a bad request error. When I use this model I have this error : "ERROR TypeError: Cannot set property 'username' of undefined."

user.model.ts

```<code>export class User {
constructor(public username: string,
            public password: string) {
    }
}
</code>```

login.component.ts:

```<code>import {Component, OnInit} from '@angular/core';
import {NgForm} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {LoginService} from '../services/login.service';
import {User} from '../models/user.model';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
    user: User;
    constructor(private httpClient: HttpClient, private loginService:
LoginService) { }
    ngOnInit() {
    }
    onSubmit(form: NgForm) {
        this.user.username = form.value['login'];
        this.user.password = form.value['password'];
        this.loginService.LoginUser(this.user).subscribe(res => {
            console.log(res);
        });
    }
}
</code>```

login.service.ts:

```<code>import {User} from '../models/user.model';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import {Injectable} from '@angular/core';

@Injectable()
export class LoginService {
    constructor(private http: HttpClient) { }

    LoginUser(user: User): Observable<User> {
        return this.http.post<User>('https://captn-boat-api.herokuapp.com/login', user)
        ;
    }
}
</code>```

login.component.html

```<code><div class="login--already-registered">
      <span class="login--screen-title">J'ai déjà un compte</span>

      <form class="login" method="GET" action="login" (ngSubmit)="onSubmit(f)" #f="ngForm">

        <div class="input--field text dark">
          <label for="login" class="control-label"><svg class="icon icon-envelope"><use xlink:href="#icon-envelope"></use></svg> E-mail</label>
          <input id="login" name="login" type="text" placeholder="" value="" ngModel>

        </div>

        <div class="input--field password dark">
          <label for="password" class="control-label"><svg class="icon icon-lock"><use xlink:href="#icon-lock"></use></svg> Mot de passe</label>
          <input id="password" name="password" type="password" placeholder="" value="" ngModel>

        </div>

        <div class="input--field checkbox dark">
          <label for="session"><input id="session" name="" value="session" type="checkbox"> se souvenir de moi</label>
        </div>

        <div class="login--submit">

          <button class="button button btn-submit" type="submit">
</code>```

答:
You never instantiate user..... You can change your onSubmit as follows

instead of:

```<code>this.user.username = form.value['login'];
this.user.password = form.value['password'];
</code>```

do this....

```<code>this.user = new User(form.value['login'], form.value['password']);
</code>```

but do you really need the User class? why not just define an IUser interface instead of a User class and do...

```<code>this.user = form.value;
this.loginService.LoginUser(this.user).subscribe(res => {
        console.log(res);
    });
</code>```

Best way, with formGroup....

in the html.... make the following changes (this includes required validation for username and password, and disabled submit button if form is invalid)....

```<code><form class="login" method="GET" action="login" (ngSubmit)="onSubmit(f)" [formGroup]="formGroup">

<input id="login" name="login" type="text" formControlName="username">
<input id="password" name="password" type="password" formControlName="password">

<button class="button button btn-submit" type="submit" [disabled]="!formGroup.valid">
</code>```

Then, in the component ts file....

```<code>formGroup: FormGroup = new FormGroup({
    username: new FormControl(null, Validators.required),
    password: new FormControl(null, Validators.required)
});
</code>```

and in your OnSubmit function....

```<code>this.user = this.formGroup.value;
this.loginService.LoginUser(this.user).subscribe(res => {
    console.log(res);
});
</code>```

Body:
I need to request my api (https://myurl.com/login) for login (username + password) in angular 7.3. When i use POST without user.models.ts i received a bad request error. When I use this model I have this error : "ERROR TypeError: Cannot set property 'username' of undefined."

user.model.ts

export class User {
constructor(public username: string,
            public password: string) {
    }
}

login.component.ts:

import {Component, OnInit} from '@angular/core';
import {NgForm} from '@angular/forms';
import {HttpClient} from '@angular/common/http';
import {LoginService} from '../services/login.service';
import {User} from '../models/user.model';

@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {
    user: User;
    constructor(private httpClient: HttpClient, private loginService:
LoginService) { }
    ngOnInit() {
    }
    onSubmit(form: NgForm) {
        this.user.username = form.value['login'];
        this.user.password = form.value['password'];
        this.loginService.LoginUser(this.user).subscribe(res => {
            console.log(res);
        });
    }
}

login.service.ts:

import {User} from '../models/user.model';
import { HttpClient, HttpHeaders} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import {Injectable} from '@angular/core';

@Injectable()
export class LoginService {
    constructor(private http: HttpClient) { }

    LoginUser(user: User): Observable<User> {
        return this.http.post<User>('https://captn-boat-api.herokuapp.com/login', user)
        ;
    }
}

login.component.html

      J'ai déjà un compte

      <form class="login" method="GET" action="login" (ngSubmit)="onSubmit(f)" #f="ngForm">

          <svg class="icon icon-envelope"><use xlink:href="#icon-envelope"></use></svg> E-mail
          <input id="login" name="login" type="text" placeholder="" value="" ngModel>

          <svg class="icon icon-lock"><use xlink:href="#icon-lock"></use></svg> Mot de passe
          <input id="password" name="password" type="password" placeholder="" value="" ngModel>

          <input id="session" name="" value="session" type="checkbox"> se souvenir de moi

          <button class="button button btn-submit" type="submit">

Body:
You never instantiate user..... You can change your onSubmit as follows

instead of:

this.user.username = form.value['login'];
this.user.password = form.value['password'];

do this....

this.user = new User(form.value['login'], form.value['password']);

but do you really need the User class? why not just define an IUser interface instead of a User class and do...

this.user = form.value;
this.loginService.LoginUser(this.user).subscribe(res => {
        console.log(res);
    });

Best way, with formGroup....

in the html.... make the following changes (this includes required validation for username and password, and disabled submit button if form is invalid)....

<form class="login" method="GET" action="login" (ngSubmit)="onSubmit(f)" [formGroup]="formGroup">

<input id="login" name="login" type="text" formControlName="username">
<input id="password" name="password" type="password" formControlName="password">

<button class="button button btn-submit" type="submit" [disabled]="!formGroup.valid">

Then, in the component ts file....

formGroup: FormGroup = new FormGroup({
    username: new FormControl(null, Validators.required),
    password: new FormControl(null, Validators.required)
});

and in your OnSubmit function....

this.user = this.formGroup.value;
this.loginService.LoginUser(this.user).subscribe(res => {
    console.log(res);
});


来源: stackexchange

问:
How can I decide what objects should be detected and what should be ignored by raycast and how?
I have two main problems in this case :

NAVI is child of the player (FPSController) and therefore the NAVI is moving along with the player. But NAVI is also position a bit in front of the player and the result is that the raycast is hitting first time all the time the NAVI instead hitting the Interactable object.

If there is a door between the player and some Interactable object it will detect the object. But if there is a door and other objects between the player and the interactable object/s it should not detect them. The player not see them but yet it's detecting.

This script is attached to the plaher (FPSController) :

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DetectInteractable : UnityEngine.MonoBehaviour
{
    public Camera cam;
    public float distanceToSee;
    public string objectHit;
    public bool interactableObject = false;
    public Transform parentToSearch;
    public Scaling scaling;
    public int spinX = 0;
    public int spinY = 0;
    public int spinZ = 0;
    public GameObject navi;
    public GameObject itemsDescriptionCanvas;
    public Text itemsDescriptionText;

    private RaycastHit whatObjectHit;
    private Transform[] childrenToSearhc;

    private void Start()
    {
        childrenToSearhc = parentToSearch.GetComponentsInChildren<Transform>();
    }

    private void Update()
    {
        if (cam.enabled == true)
        {
            if (Input.GetMouseButtonDown(0) && !scaling.scaleUp)
            {
                if (whatObjectHit.collider != null)
                    ExecuteActions(whatObjectHit.collider.gameObject);
            }

            Debug.DrawRay(cam.transform.position, cam.transform.forward * distanceToSee, Color.magenta);
            if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee))
            {
                objectHit = whatObjectHit.collider.gameObject.name;
                interactableObject = true;
                print("Hit ! " + whatObjectHit.collider.gameObject.name);

                if (scaling.objectToScale.transform.localScale == scaling.minSize)
                {
                    scaling.objectToScale.transform.Rotate(spinX, spinY, spinZ);
                }
                ProcessItemsDescripations();
                itemsDescriptionCanvas.SetActive(true);
            }
            else
            {
                if (scaling.objectToScale.transform.localScale == scaling.minSize)
                {
                    navi.transform.rotation = new Quaternion(0, 0, 0, 0);
                }
                itemsDescriptionCanvas.SetActive(false);
                print("Not Hit !");
            }
        }
    }

    private void ExecuteActions(GameObject go)
    {
        var ia = go.GetComponent<ItemAction>();
        if (ia != null)
        {
            ia.ItemMove();
        }
    }

    void ProcessItemsDescripations()
    {
        foreach (Transform child in childrenToSearhc)
        {
            if (child.GetComponent<ItemInformation>() != null)
            {
                ItemInformation iteminformation = child.GetComponent<ItemInformation>();
                if (child.name == objectHit)
                {
                    itemsDescriptionText.text = iteminformation.description;
                }
            }
        }
    }

    public class ViewableObject : UnityEngine.MonoBehaviour
    {
        public string displayText;
        public bool isInteractable;
    }
}
</code>```

And this small script is attach to each Interactable object :

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemInformation : UnityEngine.MonoBehaviour
{
    [TextArea]
    public string description;
}
</code>```

This is a screenshot of the player (FPSController) Inspector settings :

This screenshot is of the NAVI that is child of the player :
You can see the NAVI at the left game window and scene window :

This is a screenshot example of the window. The window should be Interactable object and should be detected by the raycast :

The window Tag is set to Untagged and the Layer to Default

This is a screenshot while the game is working a situation when the player is standing behind a door in the other side of the door there is a room with the Interactable window. Nothing will prevent from the raycast to pas through the door and detect the window. And that's not logic. The player can't see the window. So the window should not be detected :

On the left the top the magenta color of the raycast pass through the door to the window. On the bottom left the player is standing behind the door and see the window at all but it's detecting the window :

But when using a breakpoint you can see that what was really hit is the NAVI not the door not the window but the NAVI since the NAVI is always standing in front of the player :

Before all that I tried to use raycast mask layer in my script and then changed the window layer to be Interactable and then I saw it's detecting through the door.

At the end the main goal is :

To detect Interactable objects in the game but not to detect the NAVI he is not Interactable object so somehow to make that NAVI will not block the raycast !

And to be able to detect bject only when there is a logic view of the player to the objects. And not to detect objects from behind doors or walls or other objects.

答:
You can use the additional optional parameter layerMask of Physics.Raycast

A Layer mask that is used to selectively ignore Colliders when casting a ray.

I would recommned to use a LayerMask

```<code>public LayerMask targetLayer;
</code>```

configure the wanted layers using the Unity Inspector (select every Layer you want to hit) and finally pass it to the raycast like

```<code>if(Physics.Raycast(
    cam.transform.position,
    cam.transform.forward,
    out whatObjectHit,
    distanceToSee,
    <b>targetLayer.value</b>))
{
    ...
}```

In the example Unity used a bitmask directly (btw. in a very unefficient way in Update):

```<code>// Bit shift the index of the layer (8) to get a bit mask
int layerMask = 1 << 8;

// This would cast rays only against colliders in layer 8.
// But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
layerMask = ~layerMask;
</code>```

as said I didn't like this way of hardcoding it. Additionally you now only exclude the layer 8 but hit everything else.

To rather include only exactly one specific layer remove the line

```<code>layerMask = ~layerMask;
</code>```

so you only hit layer 8.

Anyway using my way from before is way more flexible and you rather select those layers you actually want to hit instead of excluding one. And using the LayerMask is way easier than having to code some bitmask operations in order to construct the layermask you want.

ContentLicense: CC BY-SA 4.0

Body:
I have two main problems in this case :

NAVI is child of the player (FPSController) and therefore the NAVI is moving along with the player. But NAVI is also position a bit in front of the player and the result is that the raycast is hitting first time all the time the NAVI instead hitting the Interactable object.

If there is a door between the player and some Interactable object it will detect the object. But if there is a door and other objects between the player and the interactable object/s it should not detect them. The player not see them but yet it's detecting.

This script is attached to the plaher (FPSController) :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DetectInteractable : UnityEngine.MonoBehaviour
{
    public Camera cam;
    public float distanceToSee;
    public string objectHit;
    public bool interactableObject = false;
    public Transform parentToSearch;
    public Scaling scaling;
    public int spinX = 0;
    public int spinY = 0;
    public int spinZ = 0;
    public GameObject navi;
    public GameObject itemsDescriptionCanvas;
    public Text itemsDescriptionText;

    private RaycastHit whatObjectHit;
    private Transform[] childrenToSearhc;

    private void Start()
    {
        childrenToSearhc = parentToSearch.GetComponentsInChildren<Transform>();
    }

    private void Update()
    {
        if (cam.enabled == true)
        {
            if (Input.GetMouseButtonDown(0) && !scaling.scaleUp)
            {
                if (whatObjectHit.collider != null)
                    ExecuteActions(whatObjectHit.collider.gameObject);
            }

            Debug.DrawRay(cam.transform.position, cam.transform.forward * distanceToSee, Color.magenta);
            if (Physics.Raycast(cam.transform.position, cam.transform.forward, out whatObjectHit, distanceToSee))
            {
                objectHit = whatObjectHit.collider.gameObject.name;
                interactableObject = true;
                print("Hit ! " + whatObjectHit.collider.gameObject.name);

                if (scaling.objectToScale.transform.localScale == scaling.minSize)
                {
                    scaling.objectToScale.transform.Rotate(spinX, spinY, spinZ);
                }
                ProcessItemsDescripations();
                itemsDescriptionCanvas.SetActive(true);
            }
            else
            {
                if (scaling.objectToScale.transform.localScale == scaling.minSize)
                {
                    navi.transform.rotation = new Quaternion(0, 0, 0, 0);
                }
                itemsDescriptionCanvas.SetActive(false);
                print("Not Hit !");
            }
        }
    }

    private void ExecuteActions(GameObject go)
    {
        var ia = go.GetComponent<ItemAction>();
        if (ia != null)
        {
            ia.ItemMove();
        }
    }

    void ProcessItemsDescripations()
    {
        foreach (Transform child in childrenToSearhc)
        {
            if (child.GetComponent<ItemInformation>() != null)
            {
                ItemInformation iteminformation = child.GetComponent<ItemInformation>();
                if (child.name == objectHit)
                {
                    itemsDescriptionText.text = iteminformation.description;
                }
            }
        }
    }

    public class ViewableObject : UnityEngine.MonoBehaviour
    {
        public string displayText;
        public bool isInteractable;
    }
}

And this small script is attach to each Interactable object :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemInformation : UnityEngine.MonoBehaviour
{
    [TextArea]
    public string description;
}

This is a screenshot of the player (FPSController) Inspector settings :

This screenshot is of the NAVI that is child of the player :
You can see the NAVI at the left game window and scene window :

This is a screenshot example of the window. The window should be Interactable object and should be detected by the raycast :

The window Tag is set to Untagged and the Layer to Default

This is a screenshot while the game is working a situation when the player is standing behind a door in the other side of the door there is a room with the Interactable window. Nothing will prevent from the raycast to pas through the door and detect the window. And that's not logic. The player can't see the window. So the window should not be detected :

On the left the top the magenta color of the raycast pass through the door to the window. On the bottom left the player is standing behind the door and see the window at all but it's detecting the window :

But when using a breakpoint you can see that what was really hit is the NAVI not the door not the window but the NAVI since the NAVI is always standing in front of the player :

Before all that I tried to use raycast mask layer in my script and then changed the window layer to be Interactable and then I saw it's detecting through the door.

At the end the main goal is :

To detect Interactable objects in the game but not to detect the NAVI he is not Interactable object so somehow to make that NAVI will not block the raycast !

And to be able to detect bject only when there is a logic view of the player to the objects. And not to detect objects from behind doors or walls or other objects.

Body:
You can use the additional optional parameter layerMask of Physics.Raycast

A Layer mask that is used to selectively ignore Colliders when casting a ray.

I would recommned to use a LayerMask

public LayerMask targetLayer;

configure the wanted layers using the Unity Inspector (select every Layer you want to hit) and finally pass it to the raycast like

if(Physics.Raycast(
    cam.transform.position,
    cam.transform.forward,
    out whatObjectHit,
    distanceToSee,
    targetLayer.value))
{
    ...
}

In the example Unity used a bitmask directly (btw. in a very unefficient way in Update):

// Bit shift the index of the layer (8) to get a bit mask
int layerMask = 1 << 8;

// This would cast rays only against colliders in layer 8.
// But instead we want to collide against everything except layer 8. The ~ operator does this, it inverts a bitmask.
layerMask = ~layerMask;

as said I didn't like this way of hardcoding it. Additionally you now only exclude the layer 8 but hit everything else.

To rather include only exactly one specific layer remove the line

layerMask = ~layerMask;

so you only hit layer 8.

Anyway using my way from before is way more flexible and you rather select those layers you actually want to hit instead of excluding one. And using the LayerMask is way easier than having to code some bitmask operations in order to construct the layermask you want.


问:
How to select from table one with all records from table 2
I am trying to display all records that table 1 contains, each record with all the records from table 2 :</p>

```<code>Table 1

company  adress
------------------
 A        AdressX
 B        AdressY
 C        AdressZ

Table 2

Product   Price
----------------
 P1        50
 P2        60

Result :

company  Product
----------------
 A        P1
 A        P2
 B        P1
 B        P2
 C        P1
 C        P2
</code>```

答:
The following query will select all data from both tables (not linked or related).

```<code>SELECT *
FROM TABLE 1
OUTER APPLY
(
SELECT *
FROM Table 2
) AS Table 2
</code>```

If there is a foreign key, you can use a LEFT JOIN (SELECT)

Body:
I am trying to display all records that table 1 contains, each record with all the records from table 2 :

Table 1

company  adress
------------------
 A        AdressX
 B        AdressY
 C        AdressZ

Table 2

Product   Price
----------------
 P1        50
 P2        60

Result :

company  Product
----------------
 A        P1
 A        P2
 B        P1
 B        P2
 C        P1
 C        P2

Body:
The following query will select all data from both tables (not linked or related).

SELECT *
FROM TABLE 1
OUTER APPLY
(
SELECT *
FROM Table 2
) AS Table 2

If there is a foreign key, you can use a LEFT JOIN (SELECT)


问:
Can a thread be accessed from two forms in a Windows forms application
I wish to run a thread to update the Image in the picturebox . The image is streamed form the camera.
I require to stream images to two pictureboxes in two different forms, but one at a time.
Is it possible to create a single thread which can be accessed by both forms.

I think a backgroundworker would be appropriate. But how do I update the images in the picturebox of the respective forms?

I am using VC++ CLI/CLR

答:
A Thread is an object which represent an independent path of execution (often run in parallel to another).  I'm not really sure what you mean by "calling" a Thread but you can instantiate separate threads and run methods on them.  Then between the Threads you have created you can use some kind of synchronisation such as Monitors, Mutexes and Events and a shared resource (being careful with cross-thread access).

For your problem I would be more tempted to use some kind of subscription pattern where the class which receives the images from the camera can update any observers of the camera.  You may want an interface called ICameraObeserver with a method such as ReceiveImage, then any class could register with your camera class via some kind of method:

public void Register(ICameraObserver ico)

Then when the camera receives a new image, it can iterate through any subscribers of type ICameraObserver and call ReceiveImage passing the image it just received.

Just an idea.  Be careful with updating the UI if you have multiple threads running - there is lots of information on this.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
How to use filtered range into SUMIF function
I want to use a filtered range into SUMIF function. I have some Named Range in my WB ("uselist" in Sheet1 is a column of item and "aliquotes" in Sheet2 is a column of quantity, "dates" in Sheet2 is a column of date yyyy-mm-dd).

This formula in my code works as expected (i.e. sum the quantities in "aliquotes" that have the item=cell.Value in "uselist" column):

```<code>Cells(cell.Row, "K") = Application.SumIf(Range("uselist"), cell.Value, Range("aliquotes"))
</code>```

But now I want limit the sum to those rows that have in "dates" column a date between the date reported in Column "O" in Sheet1 and Now. The "cell" I'm working are in Sheet1. I modified the code, but I have some problem:

```<code>Sub FilterSum()
On Error Resume Next

Dim MyRangeI As Range
Dim MyRangeO As Range
Dim cell As Range
Dim XNEWRANGE As Range
Dim wsI As Worksheet
Dim wsO As Worksheet

Set wsI = ThisWorkbook.Sheets("Sheet1")
Set wsO = ThisWorkbook.Sheets("Sheet2")

With wsI.UsedRange 'don't consider headers
    Set MyRangeI = Range(.Cells(2, 1), .Cells(1, 1).Offset(.Rows.Count - 1, .Columns.Count - 1))
    MyRangeI.Select
End With

With wsO.UsedRange 'don't consider headers
    Set MyRangeO = Range(.Cells(2, 1), .Cells(1, 1).Offset(.Rows.Count - 1, .Columns.Count - 1))
    MyRangeO.Select
End With

Application.ScreenUpdating = False

For Each cell In MyRangeI.Columns("A").Cells

MyRangeO.AutoFilter Field:=9, Criteria1:=">=" & MyRangeI.Cells(cell.Row, "O"), Operator:=xlAnd, Criteria2:="<=" & Now 'Field 9 is tha same of the Named Range "dates"

Set XNEWRANGE = MyRangeO.SpecialCells(xlCellTypeVisible)

MyRangeI.Cells(cell.Row, "K") = Application.SumIf(XNEWRANGE, MyRangeI.cell.Value, Range("aliquotes"))

Next cell

Application.ScreenUpdating = True
End Sub
</code>```

In my opinion there is a problem with the two different sheets I want use for the macro.

答:
Try this:

But beware about your MyRange because it is not declared on the procedure:

```<code>Option Explicit
Sub FilterSum()

    'ActiveSheet.UsedRange.Select 'avoid using select

    Dim cell As Range
    Dim XNEWRANGE As Range
    Dim ws As Worksheet 'reference your sheets to avoid using select

    Set ws = ThisWorkbook.Sheets("MySheet") 'change MySheet for your working sheet name

    Application.ScreenUpdating = False
    With ws
        For Each cell In MyRange.Columns("A") 'MyRange isn't declared or it's value given anywhere
            'Add your filters first
            .Range("dates").AutoFilter Field:=1, Criteria1:=">=" & Cells(cell.Row, "O"), Operator:=xlAnd, Criteria2:="<=" & Now
            'Set your range using the visible cells from A2 to last row visible on column A
            Set XNEWRANGE = .Range("A2", .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1)).SpecialCells(xlCellTypeVisible)
            .Cells(cell.Row, "K") = Application.SumIf(XNEWRANGE, cell.Value, Range("aliquotes"))
        Next cell
    End With
    Application.ScreenUpdating = True

End Sub
</code>```

Body:
I want to use a filtered range into SUMIF function. I have some Named Range in my WB ("uselist" in Sheet1 is a column of item and "aliquotes" in Sheet2 is a column of quantity, "dates" in Sheet2 is a column of date yyyy-mm-dd).

This formula in my code works as expected (i.e. sum the quantities in "aliquotes" that have the item=cell.Value in "uselist" column):

Cells(cell.Row, "K") = Application.SumIf(Range("uselist"), cell.Value, Range("aliquotes"))

But now I want limit the sum to those rows that have in "dates" column a date between the date reported in Column "O" in Sheet1 and Now. The "cell" I'm working are in Sheet1. I modified the code, but I have some problem:

Sub FilterSum()
On Error Resume Next

Dim MyRangeI As Range
Dim MyRangeO As Range
Dim cell As Range
Dim XNEWRANGE As Range
Dim wsI As Worksheet
Dim wsO As Worksheet

Set wsI = ThisWorkbook.Sheets("Sheet1")
Set wsO = ThisWorkbook.Sheets("Sheet2")

With wsI.UsedRange 'don't consider headers
    Set MyRangeI = Range(.Cells(2, 1), .Cells(1, 1).Offset(.Rows.Count - 1, .Columns.Count - 1))
    MyRangeI.Select
End With

With wsO.UsedRange 'don't consider headers
    Set MyRangeO = Range(.Cells(2, 1), .Cells(1, 1).Offset(.Rows.Count - 1, .Columns.Count - 1))
    MyRangeO.Select
End With

Application.ScreenUpdating = False

For Each cell In MyRangeI.Columns("A").Cells

MyRangeO.AutoFilter Field:=9, Criteria1:=">=" & MyRangeI.Cells(cell.Row, "O"), Operator:=xlAnd, Criteria2:="<=" & Now 'Field 9 is tha same of the Named Range "dates"

Set XNEWRANGE = MyRangeO.SpecialCells(xlCellTypeVisible)

MyRangeI.Cells(cell.Row, "K") = Application.SumIf(XNEWRANGE, MyRangeI.cell.Value, Range("aliquotes"))

Next cell

Application.ScreenUpdating = True
End Sub

In my opinion there is a problem with the two different sheets I want use for the macro.

Body:
Try this:

But beware about your MyRange because it is not declared on the procedure:

Option Explicit
Sub FilterSum()

    'ActiveSheet.UsedRange.Select 'avoid using select

    Dim cell As Range
    Dim XNEWRANGE As Range
    Dim ws As Worksheet 'reference your sheets to avoid using select

    Set ws = ThisWorkbook.Sheets("MySheet") 'change MySheet for your working sheet name

    Application.ScreenUpdating = False
    With ws
        For Each cell In MyRange.Columns("A") 'MyRange isn't declared or it's value given anywhere
            'Add your filters first
            .Range("dates").AutoFilter Field:=1, Criteria1:=">=" & Cells(cell.Row, "O"), Operator:=xlAnd, Criteria2:="<=" & Now
            'Set your range using the visible cells from A2 to last row visible on column A
            Set XNEWRANGE = .Range("A2", .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1)).SpecialCells(xlCellTypeVisible)
            .Cells(cell.Row, "K") = Application.SumIf(XNEWRANGE, cell.Value, Range("aliquotes"))
        Next cell
    End With
    Application.ScreenUpdating = True

End Sub


问:
PyAutoGui finds button but only when plugged into my monitor
PyAutoGui finds the button perfectly when plugged into my monitor, which I code on, but fails to find the image on screen while on my laptop.

Context: I'm simply automating running through Clean My Mac automatically.

Here's the code:

```<code>import pyautogui
import subprocess
import time
import cv2
from termcolor import colored

print('Starting'.format(), end='\r')
subprocess.call(
    ["/usr/bin/open", "/Applications/CleanMyMac.app"]
    )
time.sleep(3)

print('Starting'.format(), end='\r')
scanButton = None
scanButton = pyautogui.locateOnScreen('scan.png', grayscale = True,
confidence = .9)

scan = None
scan = pyautogui.center(scanButton)

pyautogui.moveTo(scan)
pyautogui.click(scan)

runButton = None

while runButton == None:

    try:

    runButton = pyautogui.locateOnScreen('run.png', grayscale = True, confidence = .9)
    clean = None
    clean = pyautogui.center(runButton)
    print(('Scan'), ('['), colored('Complete','green'), (']'))

except TypeError:
    runButton = None
    print('Scanning...'.format(), end='\r')

pyautogui.moveTo(clean)
pyautogui.click(clean)

ignoreButton = None

time.sleep(3)
while ignoreButton == None:
try:
    print('Ignoring Chrome [running]'.format(), end='\r')
    ignoreButton = pyautogui.locateOnScreen('ignore.png', grayscale = True, confidence = .9)
    ignore = None
    ignore = pyautogui.center(ignoreButton)
    print(('Ignoring Chrome'), ('['), colored('Complete','green'), (']'))
    pyautogui.moveTo(ignore)
    pyautogui.click(ignore)

except TypeError:
    ignoreButton = True
    print(('Ignoring Chrome'), ('['), colored('Not Required','green'), (']'))

completeButton = None

while completeButton == None:
try:
    completeButton = pyautogui.locateOnScreen('complete.png', grayscale = True, confidence = .9)
    complete = None
    complete = pyautogui.center(completeButton)
except TypeError:
    completeButton = None
    print('Optimizing System...'.format(), end='\r')

print(('System Status'), ('['), colored('Optimized','green'), (']'))
print('All Systems Go, Captain!')

closeButton = pyautogui.locateOnScreen('close.png')#, grayscale = True, confidence = .8)
close = pyautogui.center(closeButton)
pyautogui.moveTo(close)
pyautogui.click(close)
</code>```

I'm wondering if it's because the pixels are a bit off between them but I'm also using grayscale, which should help with that.

答: The button is probably scaling when changing from monitor to laptop, so pyautogui can't find the smaller image. you will need to create a check (most likely pyautogui.size()) to see if you're on your laptop and use a smaller image.</p>

Body:
PyAutoGui finds the button perfectly when plugged into my monitor, which I code on, but fails to find the image on screen while on my laptop.

Context: I'm simply automating running through Clean My Mac automatically.

Here's the code:

import pyautogui
import subprocess
import time
import cv2
from termcolor import colored

print('Starting'.format(), end='\r')
subprocess.call(
    ["/usr/bin/open", "/Applications/CleanMyMac.app"]
    )
time.sleep(3)

print('Starting'.format(), end='\r')
scanButton = None
scanButton = pyautogui.locateOnScreen('scan.png', grayscale = True,
confidence = .9)

scan = None
scan = pyautogui.center(scanButton)

pyautogui.moveTo(scan)
pyautogui.click(scan)

runButton = None

while runButton == None:

    try:

    runButton = pyautogui.locateOnScreen('run.png', grayscale = True, confidence = .9)
    clean = None
    clean = pyautogui.center(runButton)
    print(('Scan'), ('['), colored('Complete','green'), (']'))

except TypeError:
    runButton = None
    print('Scanning...'.format(), end='\r')

pyautogui.moveTo(clean)
pyautogui.click(clean)

ignoreButton = None

time.sleep(3)
while ignoreButton == None:
try:
    print('Ignoring Chrome [running]'.format(), end='\r')
    ignoreButton = pyautogui.locateOnScreen('ignore.png', grayscale = True, confidence = .9)
    ignore = None
    ignore = pyautogui.center(ignoreButton)
    print(('Ignoring Chrome'), ('['), colored('Complete','green'), (']'))
    pyautogui.moveTo(ignore)
    pyautogui.click(ignore)

except TypeError:
    ignoreButton = True
    print(('Ignoring Chrome'), ('['), colored('Not Required','green'), (']'))

completeButton = None

while completeButton == None:
try:
    completeButton = pyautogui.locateOnScreen('complete.png', grayscale = True, confidence = .9)
    complete = None
    complete = pyautogui.center(completeButton)
except TypeError:
    completeButton = None
    print('Optimizing System...'.format(), end='\r')

print(('System Status'), ('['), colored('Optimized','green'), (']'))
print('All Systems Go, Captain!')

closeButton = pyautogui.locateOnScreen('close.png')#, grayscale = True, confidence = .8)
close = pyautogui.center(closeButton)
pyautogui.moveTo(close)
pyautogui.click(close)

I'm wondering if it's because the pixels are a bit off between them but I'm also using grayscale, which should help with that.


问:
Passing commandline argument to qml
I want to call a qml-script from linux shell and pass a text as parameter, like

```<code>./message.qml "hello this is a message"
</code>```

or

```<code>/usr/bin/qt5/qml ./message.qml "hello this is a message"
</code>```

The qml script should display that text.

The example qml script below works, but the text which is displayed ("hello") is static, of course. Is it possible to query command line arguments in the qml?

```<code>#!/usr/bin/qt5/qml

import QtQuick 2.2

Rectangle {
    width: 1024
    height: 600
    Text {
        anchors.centerIn: parent
        text: "Hello" // here I want to have a text which is set in the call
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit()
        }
    }
}
</code>```

答:
You can access the command line arguments using Qt.application.arguments, for example in my case if I execute:

```<code>/usr/bin/qml message.qml "hello this is a message"
</code>```

```<code>#!/usr/bin/qt5/qml

import QtQuick 2.2

Rectangle {
    width: 1024
    height: 600
    Text {
        anchors.centerIn: parent
        text: Qt.application.arguments[2] // here I want to have a text which is set in the call
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit()
        }
    }
}
</code>```

The index in Qt.application.arguments[index] may vary depending on how you invoke the execution of the qml.

Title: Passing commandline argument to qml

Body:
I want to call a qml-script from linux shell and pass a text as parameter, like

./message.qml "hello this is a message"

or

/usr/bin/qt5/qml ./message.qml "hello this is a message"

The qml script should display that text.

The example qml script below works, but the text which is displayed ("hello") is static, of course. Is it possible to query command line arguments in the qml?

#!/usr/bin/qt5/qml

import QtQuick 2.2

Rectangle {
    width: 1024
    height: 600
    Text {
        anchors.centerIn: parent
        text: "Hello" // here I want to have a text which is set in the call
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit()
        }
    }
}

Body:
You can access the command line arguments using Qt.application.arguments, for example in my case if I execute:

/usr/bin/qml message.qml "hello this is a message"

#!/usr/bin/qt5/qml

import QtQuick 2.2

Rectangle {
    width: 1024
    height: 600
    Text {
        anchors.centerIn: parent
        text: Qt.application.arguments[2] // here I want to have a text which is set in the call
    }
    MouseArea {
        anchors.fill: parent
        onClicked: {
            Qt.quit()
        }
    }
}

The index in Qt.application.arguments[index] may vary depending on how you invoke the execution of the qml.


问:
Download large data directly from url to google cloud storage Bucket
I want to download a large dataset from URL "https" directly to google cloud storage(Bucket).

I have used gsutil stream command. via google cloud shell

curl -L https://../../..velodyne.zip | gsutil cp - gs://###/##/velodyne.zip

the result is

We've detected excessive egress network traffic in your Google Cloud Shell session. Discontinue or decrease this traffic or your session will be terminated.

答:
This is because you're downloading to your local environment (the cloud shell) with curl and then sending to GCS.

The way to do this is to use the Storage Transfer Service.

There is one option of giving the transfer service a URL list, and the service itself will download all the data to the bucket.


问:
Left swipe for delete and edit,delete
I am not able to find a way around this. Is it possible to have delete option using left swipe and also using edit and delete.

I have edit button on the left of the navigation bar.

```<code>self.navigationItem.leftBarButtonItem = self.editButtonItem;
</code>```

and commitEditingStyle method as below

```<code>- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
//delete code here
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
</code>```

}

After using this, the left swipe is not being detected at all. the only way to delete seems to be by going to the edit mode and deleting from there.
help would be appreciated.

I am a newbie so please go easy with me :)

答:
```<code>- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
//delete code here
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
</code>```

once you write above method in your delegate you will be able to use swipe gestures.... and in this method you will handle the subsequent actions that you want to perform.

thanks.....

Title: Left swipe for delete and edit,delete

Body:
I am not able to find a way around this. Is it possible to have delete option using left swipe and also using edit and delete.

I have edit button on the left of the navigation bar.

self.navigationItem.leftBarButtonItem = self.editButtonItem;

and commitEditingStyle method as below

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
//delete code here
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }

}

After using this, the left swipe is not being detected at all. the only way to delete seems to be by going to the edit mode and deleting from there.
help would be appreciated.

I am a newbie so please go easy with me :)

Body:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    if (editingStyle == UITableViewCellEditingStyleDelete) {
//delete code here
    }
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }

once you write above method in your delegate you will be able to use swipe gestures.... and in this method you will handle the subsequent actions that you want to perform.

thanks.....


问:
How to delete duplicate from this result
How to delete duplicate from this result

```<code>select *,
       row_number() over (order by (select null)) as seqnum
from [elo].[dbo].[objkeys]
where parentid in (select parentid
                   from [elo].[dbo].[objekte]
                   inner join [elo].[dbo].[objkeys] on objid = parentid
                   where objmask like 26 and okeydata like 'yes'
                   )
</code>```

output is

```<code>parentid   okeyname  okeydata
  1          name   a
  1      number     1
  1        yes_no   yes
  2          name   a
  2      number     1
  2        yes_no   yes
  3          name   a
  3      number     1
  3        yes_no   no
  4          name   a
  4      number     2
  4          yes_no no
  5          name   b
  5      number     3
  5          yes_no yes
  6          name   b
  6      number     3
  6          yes_no yes
  7          name   b
  7      number     3
  7          yes_no no
  8          name   b
  8      number     3
  8          yes_no no

</code>```

need to be like this

```<code>parentid   okeyname  okeydata
  1          name   a
  1      number     1
  1          yes_no yes

  3          name   a
  3      number     1
  3          yes_no no

  5          name   b
  5      number     3
  5          yes_no yes

  7          name   b
  7      number     3
  7          yes_no no
</code>```

答:
Try below -</p>

```<code>select * from
(
      select *,row_number() over (partition by okeyname,okeydata order by parentid) as seqnum
      from [elo].[dbo].[objkeys] inner join [elo].[dbo].[objekte]
      on objid = parentid
      where objmask like 26 and okeydata like 'yes'
)A where seqnum=1
</code>```

Body:
How to delete duplicate from this result

select *,
       row_number() over (order by (select null)) as seqnum
from [elo].[dbo].[objkeys]
where parentid in (select parentid
                   from [elo].[dbo].[objekte]
                   inner join [elo].[dbo].[objkeys] on objid = parentid
                   where objmask like 26 and okeydata like 'yes'
                   )

output is

parentid   okeyname  okeydata
  1          name   a
  1      number     1
  1        yes_no   yes
  2          name   a
  2      number     1
  2        yes_no   yes
  3          name   a
  3      number     1
  3        yes_no   no
  4          name   a
  4      number     2
  4          yes_no no
  5          name   b
  5      number     3
  5          yes_no yes
  6          name   b
  6      number     3
  6          yes_no yes
  7          name   b
  7      number     3
  7          yes_no no
  8          name   b
  8      number     3
  8          yes_no no

need to be like this

parentid   okeyname  okeydata
  1          name   a
  1      number     1
  1          yes_no yes

  3          name   a
  3      number     1
  3          yes_no no

  5          name   b
  5      number     3
  5          yes_no yes

  7          name   b
  7      number     3
  7          yes_no no

Body:
Try below -

select * from
(
      select *,row_number() over (partition by okeyname,okeydata order by parentid) as seqnum
      from [elo].[dbo].[objkeys] inner join [elo].[dbo].[objekte]
      on objid = parentid
      where objmask like 26 and okeydata like 'yes'
)A where seqnum=1


问:
Text mispositioned on some react cards
I have an app that fetches videos, and it creates a card for each video that it fetches, on the card there is also the video title, video creator, video link, video download link, views, and the upload date.

I am fetching all of these things with no problems and they all display the way I want it to, for the most part.

The strange thing is for some cards, the text for download and view video is mispositioned, and is higher than it is supposed to be.

Here you can see the problem I'm experiencing, basically the first and third cards are displaying correctly but you can see that the middle card's text for download and view is higher for some reason.

the following is my css for the cards

```<code>.card {
    background-color: $secondaryColor;
    border: 3px solid #fff;
    outline: black solid thin;
}

.authorInfo {
    display: flex;
}

.card-body {
    display: flex;
    justify-content: space-between;
    margin-bottom: -10px;
}

.card-footer {
    display: flex;
    justify-content: space-between;
}

.watchComp {
    display: flex;
}

.dlComp {
    display: flex;
}

.card-deck {
    padding-bottom: 1.5rem;
}
</code>```

the dl comp consists of the icon and the link, same with the watch comp. I have tried altering the positioning styling in the inspect element when this happens but nothing has worked.

Any ideas on what could be causing this? the cards I'm using is from react-bootstrap, if that matters.

答:
Watch Clip and Download Clip in the second screenshot snaps top because title has only one line toxic. You can wrap that row in a
 tag or use align-items: center style.

Title: Text mispositioned on some react cards

Body:
I have an app that fetches videos, and it creates a card for each video that it fetches, on the card there is also the video title, video creator, video link, video download link, views, and the upload date.

I am fetching all of these things with no problems and they all display the way I want it to, for the most part.

The strange thing is for some cards, the text for download and view video is mispositioned, and is higher than it is supposed to be.

Here you can see the problem I'm experiencing, basically the first and third cards are displaying correctly but you can see that the middle card's text for download and view is higher for some reason.

the following is my css for the cards

.card {
    background-color: $secondaryColor;
    border: 3px solid #fff;
    outline: black solid thin;
}

.authorInfo {
    display: flex;
}

.card-body {
    display: flex;
    justify-content: space-between;
    margin-bottom: -10px;
}

.card-footer {
    display: flex;
    justify-content: space-between;
}

.watchComp {
    display: flex;
}

.dlComp {
    display: flex;
}

.card-deck {
    padding-bottom: 1.5rem;
}

the dl comp consists of the icon and the link, same with the watch comp. I have tried altering the positioning styling in the inspect element when this happens but nothing has worked.

Any ideas on what could be causing this? the cards I'm using is from react-bootstrap, if that matters.

Body: Watch Clip and Download Clip in the second screenshot snaps top because title has only one line toxic. You can wrap that row in a <div> tag or use align-items: center style.


答:
it does not seems there any duplicate records but from the resut set it seems you need minimum parentid and try like below</p>

```<code>    with cte as
    (
    your query output
    ) select min(parentid),okeyname,okeydata
   from cte group by okeyname,okeydata
</code>```

Title: How to delete duplicate from this result

Body:
it does not seems there any duplicate records but from the resut set it seems you need minimum parentid and try like below

    with cte as
    (
    your query output
    ) select min(parentid),okeyname,okeydata
   from cte group by okeyname,okeydata


问:
Shifting from iterator to for each
I have a panel1 function that returns an iterator that works with the following program:

```<code>public static void main(String[] args) {

     Iterator<Integer> it = panel1(1,5);
     for(;it.hasNext();)
        System.out.println(it.next()); // return 1 2 3 4 5
}
</code>```

For simplicity, I want to facilitate this by using the Java foreach syntax as shown in the following example.

```<code>for(int i:panel2(1,5))
    System.out.println(i); // would return 1 2 3 4 5
</code>```

Here is the Panel class I did so far with an anonym class:

```<code>import java.util.Iterator;
import java.util.NoSuchElementException;

public class Panel{

    public static Iterator<Integer> panel1(final int begin,final int end){
        Iterator<Integer> it = new Iterator<Integer>(){

            private int nextValue = begin;
            private final int max = end;

            public boolean hasNext() {
                return nextValue <= max;
            }

            public Integer next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                return Integer.valueOf(nextValue++);
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
        return it;
    }

    public static void main(String[] args) {

         Iterator<Integer> it = panel1(1,5);
         for(;it.hasNext();)
            System.out.println(it.next()); // affiche 1 2 3 4 5
    }
}
</code>```

答:
You can use real ints, with IntStream:

```<code>IntStream.rangeClosed(1, 5)
    .forEach(System::println):

IntStream.rangeClosed(1, 5)
    .forEach(i -> System.println(i)):

IntStream.rangeClosed(1, 5)
    .forEach(i -> System.println(i)):

IntStream.rangeClosed(1, 5)
    .forEach(i -> {
         System.println(i);
}):

1
2
:
5
</code>```

This uses Streams, with the even newer forEach construct.

IntStream.range(1, 6) would be equivalent, 6 being the exclusive upper bound.

Title: Shifting from iterator to for each

Body:
I have a panel1 function that returns an iterator that works with the following program:

public static void main(String[] args) {

     Iterator<Integer> it = panel1(1,5);
     for(;it.hasNext();)
        System.out.println(it.next()); // return 1 2 3 4 5
}

For simplicity, I want to facilitate this by using the Java foreach syntax as shown in the following example.

for(int i:panel2(1,5))
    System.out.println(i); // would return 1 2 3 4 5

Here is the Panel class I did so far with an anonym class:

import java.util.Iterator;
import java.util.NoSuchElementException;

public class Panel{

    public static Iterator<Integer> panel1(final int begin,final int end){
        Iterator<Integer> it = new Iterator<Integer>(){

            private int nextValue = begin;
            private final int max = end;

            public boolean hasNext() {
                return nextValue <= max;
            }

            public Integer next() {
                if (!hasNext()) {
                    throw new NoSuchElementException();
                }
                return Integer.valueOf(nextValue++);
            }

            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
        return it;
    }

    public static void main(String[] args) {

         Iterator<Integer> it = panel1(1,5);
         for(;it.hasNext();)
            System.out.println(it.next()); // affiche 1 2 3 4 5
    }
}

Body:
You can use real ints, with IntStream:

IntStream.rangeClosed(1, 5)
    .forEach(System::println):

IntStream.rangeClosed(1, 5)
    .forEach(i -> System.println(i)):

IntStream.rangeClosed(1, 5)
    .forEach(i -> System.println(i)):

IntStream.rangeClosed(1, 5)
    .forEach(i -> {
         System.println(i);
}):

1
2
:
5

This uses Streams, with the even newer forEach construct.

IntStream.range(1, 6) would be equivalent, 6 being the exclusive upper bound.


问:
How to get datatable row values and route to another function?
If I use arrow functions I am able to route to another component, but I am unable to get datatable values, below is the code:

$('#list-country tbody').on('click', '.fa-edit', function() {
  var tr = $(this).closest("tr");
  var data = $("#list-country").DataTable().row(tr).data();
  console.log(data);
  this.router.navigate(['/apps/edit-country']);
  this.routePage();
});
```

<p>If I use normal functions I am able to fetch values , but i am unable to route, below is the code:</p>

```$('#list-country tbody').on('click', '.fa-edit', () => {

  var tr = $(this).closest("tr");
  var data = $("#list-country").DataTable().row(tr).data();
  console.log(data);
  this.routePage();
});
```

These functions are inside ngInit().

答:
```<code>// event use direct "currentTarget"

$('#list-country tbody').on('click', '.fa-edit', event => {
  var tr = $(event.currentTarget).closest('tr')
  var data = $('#list-country')
    .DataTable()
    .row(tr)
    .data()

  this.router.navigate(['/apps/edit-country']);
  this.routePage()
})
</code>```

Body:
If I use arrow functions I am able to route to another component, but I am unable to get datatable values, below is the code:

$('#list-country tbody').on('click', '.fa-edit', function() {
  var tr = $(this).closest("tr");
  var data = $("#list-country").DataTable().row(tr).data();
  console.log(data);
  this.router.navigate(['/apps/edit-country']);
  this.routePage();
});

If I use normal functions I am able to fetch values , but i am unable to route, below is the code:

$('#list-country tbody').on('click', '.fa-edit', () => {

  var tr = $(this).closest("tr");
  var data = $("#list-country").DataTable().row(tr).data();
  console.log(data);
  this.routePage();
});

These functions are inside ngInit().


问:
Recursive search and filtering in a menu
I have an angular app that I'm working on.
my problem is this:
I have a navigation menu on the side with the option to search inside the menu.
this is the JSON for the menu:

```<code>menuItems: [
{
    name: "Dashboard",
    iconPath: "Dash@board.png",
    routingPath: "",
    children: [
        {
            name: "Version 1",
            iconPath: "",
            routingPath: "",
            children: [
                {
                    name: "Version 1.1 abc",
                    iconPath: "",
                    routingPath: "",
                    children: [
                        {
                            name: "Version 1.1.1 ccc",
                            iconPath: "",
                            routingPath: "",
                            children: [
                                {
                                    name: "Version 1.1.1.1 hello",
                                    iconPath: "",
                                    routingPath: "",
                                    children: []
                                },
                                {
                                    name: "Version 1.1.2.1",
                                    iconPath: "",
                                    routingPath: "",
                                    children: []
                                },
                                {
                                    name: "Version 1.1.3.1 sdfsdf",
                                    iconPath: "",
                                    routingPath: "",
                                    children: []
                                }
                            ]
                        },
                        {
                            name: "Version 1.1.2",
                            iconPath: "",
                            routingPath: "",
                            children: []
                        },
                        {
                            name: "Version 1.1.3",
                            iconPath: "",
                            routingPath: "",
                            children: []
                        }
                    ]
                },
                {
                    name: "Version 1.2",
                    iconPath: "",
                    routingPath: "",
                    children: []
                }
            ]
        },
        {
            name: "Version 2",
            iconPath: "",
            routingPath: "",
            children: []
        },
        {
            name: "Version 3",
            iconPath: "",
            routingPath: "",
            children: [
                {
                    name: "Version 3.1",
                    iconPath: "",
                    routingPath: "",
                    children: []
                },
                {
                    name: "Version 3.2",
                    iconPath: "",
                    routingPath: "",
                    children: []
                },
                {
                    name: "Version 3.3",
                    iconPath: "",
                    routingPath: "",
                    children: []
                }
            ]
        }
    ]
},
{
    name: "Pages",
    iconPath: "Pa@ges.png",
    routingPath: "",
    children: [
        {
            name: "ZZZ Page 1",
            iconPath: "",
            routingPath: "",
            children: []
        }
    ]
},]
</code>```

this is an example for the menu.
what I'm trying to achieve is this:
if someone searches hello, I need to display this (I Only display the name but I need all of the data inside the object):

But it doesn't work.
I have tried this code:

```<code>private performFiltering() {
    const searchValue: string = this.searchBarInput.nativeElement.value.toLowerCase();

    if (searchValue.length > 0) {
        this.filteredMenu.menuItems = this.fullMenu.menuItems.filter((item) => {
            return this.recursiveSearchInMenu(item, searchValue);
        });
}}

private recursiveSearchInMenu(menu: MenuItemModel, searchValue) {
    let found = menu.children.find((item) => item.name.toLowerCase().includes(searchValue));
    if (!found) {
        let i = 0;
        while (!found && i < menu.children.length) {
            if (menu.children[i].children && menu.children[i].children.length) {
                found = this.recursiveSearchInMenu(menu.children[i], searchValue);
            }
            i++;
        }
    }
    return found;
}
</code>```

This is my result:

any ideas how to do this?

答:
I've got it...

this is my current answer:

```<code>private performFiltering(): boolean {
    const searchValue: string = this.searchBarInput.nativeElement.value.toLowerCase();
    const isFiltered = searchValue.length > 0;

    this.showSearchButton(isFiltered);

    if (isFiltered) {
        this.filteredMenu.menuItems = this.recursiveSearchInMenu(
            JSON.parse(JSON.stringify(this.fullMenu.menuItems)),
            searchValue
        );
    } else {
        this.filteredMenu.menuItems = this.fullMenu.menuItems;
    }

    return isFiltered;
}

private recursiveSearchInMenu(menuItems: MenuItemModel[], searchValue: string): MenuItemModel[] {
    const matchingMenuItems: MenuItemModel[] = [];

    menuItems.forEach((menuItem) => {
        if (menuItem.name.toLowerCase().includes(searchValue)) {
            matchingMenuItems.push(menuItem);
        } else {
            const matchingChildren = this.recursiveSearchInMenu(menuItem.children, searchValue);

            if (matchingChildren.length > 0) {
                menuItem.children = matchingChildren;
                matchingMenuItems.push(menuItem);
            }
        }
    });

    return matchingMenuItems;
}
</code>```

if you have any suggestions on how to improve it I would love to get your opinion.

Body:
I have an angular app that I'm working on.
my problem is this:
I have a navigation menu on the side with the option to search inside the menu.
this is the JSON for the menu:

menuItems: [
{
    name: "Dashboard",
    iconPath: "Dash@board.png",
    routingPath: "",
    children: [
        {
            name: "Version 1",
            iconPath: "",
            routingPath: "",
            children: [
                {
                    name: "Version 1.1 abc",
                    iconPath: "",
                    routingPath: "",
                    children: [
                        {
                            name: "Version 1.1.1 ccc",
                            iconPath: "",
                            routingPath: "",
                            children: [
                                {
                                    name: "Version 1.1.1.1 hello",
                                    iconPath: "",
                                    routingPath: "",
                                    children: []
                                },
                                {
                                    name: "Version 1.1.2.1",
                                    iconPath: "",
                                    routingPath: "",
                                    children: []
                                },
                                {
                                    name: "Version 1.1.3.1 sdfsdf",
                                    iconPath: "",
                                    routingPath: "",
                                    children: []
                                }
                            ]
                        },
                        {
                            name: "Version 1.1.2",
                            iconPath: "",
                            routingPath: "",
                            children: []
                        },
                        {
                            name: "Version 1.1.3",
                            iconPath: "",
                            routingPath: "",
                            children: []
                        }
                    ]
                },
                {
                    name: "Version 1.2",
                    iconPath: "",
                    routingPath: "",
                    children: []
                }
            ]
        },
        {
            name: "Version 2",
            iconPath: "",
            routingPath: "",
            children: []
        },
        {
            name: "Version 3",
            iconPath: "",
            routingPath: "",
            children: [
                {
                    name: "Version 3.1",
                    iconPath: "",
                    routingPath: "",
                    children: []
                },
                {
                    name: "Version 3.2",
                    iconPath: "",
                    routingPath: "",
                    children: []
                },
                {
                    name: "Version 3.3",
                    iconPath: "",
                    routingPath: "",
                    children: []
                }
            ]
        }
    ]
},
{
    name: "Pages",
    iconPath: "Pa@ges.png",
    routingPath: "",
    children: [
        {
            name: "ZZZ Page 1",
            iconPath: "",
            routingPath: "",
            children: []
        }
    ]
},]

this is an example for the menu.
what I'm trying to achieve is this:
if someone searches hello, I need to display this (I Only display the name but I need all of the data inside the object):

But it doesn't work.
I have tried this code:

private performFiltering() {
    const searchValue: string = this.searchBarInput.nativeElement.value.toLowerCase();

    if (searchValue.length > 0) {
        this.filteredMenu.menuItems = this.fullMenu.menuItems.filter((item) => {
            return this.recursiveSearchInMenu(item, searchValue);
        });
}}

private recursiveSearchInMenu(menu: MenuItemModel, searchValue) {
    let found = menu.children.find((item) => item.name.toLowerCase().includes(searchValue));
    if (!found) {
        let i = 0;
        while (!found && i < menu.children.length) {
            if (menu.children[i].children && menu.children[i].children.length) {
                found = this.recursiveSearchInMenu(menu.children[i], searchValue);
            }
            i++;
        }
    }
    return found;
}

This is my result:

any ideas how to do this?

Body:
I've got it...

this is my current answer:

private performFiltering(): boolean {
    const searchValue: string = this.searchBarInput.nativeElement.value.toLowerCase();
    const isFiltered = searchValue.length > 0;

    this.showSearchButton(isFiltered);

    if (isFiltered) {
        this.filteredMenu.menuItems = this.recursiveSearchInMenu(
            JSON.parse(JSON.stringify(this.fullMenu.menuItems)),
            searchValue
        );
    } else {
        this.filteredMenu.menuItems = this.fullMenu.menuItems;
    }

    return isFiltered;
}

private recursiveSearchInMenu(menuItems: MenuItemModel[], searchValue: string): MenuItemModel[] {
    const matchingMenuItems: MenuItemModel[] = [];

    menuItems.forEach((menuItem) => {
        if (menuItem.name.toLowerCase().includes(searchValue)) {
            matchingMenuItems.push(menuItem);
        } else {
            const matchingChildren = this.recursiveSearchInMenu(menuItem.children, searchValue);

            if (matchingChildren.length > 0) {
                menuItem.children = matchingChildren;
                matchingMenuItems.push(menuItem);
            }
        }
    });

    return matchingMenuItems;
}

if you have any suggestions on how to improve it I would love to get your opinion.


问:
Passing string resource from interactor to view in android MVP
So, I am currently trying to implement MVP approach in android, which I am new to. Now, it states that neither presenter nor the interactor class should have knowledge about android classes or components.

Makes sense to decouple the business logic from framework.
Good so far.

However I have an presenter that implements a callback to login in interactor, that passes a string resource id. The presenter passes the string res id to the view that displays error message in some form (whether a toast or a dialog).

Interactor:

```<code>public interface SignInteractor {

void login(String email, String password, OnLoginListener loginListener);

interface OnLoginListener {

    void onLoginSuccess();

    void onLoginFail(int error);

   }
}
</code>```

Presenter:

```<code>public interface SignInPresenterImpl {
private SignInteractorImpl mInteractor; // interactor implementation
private SignInView mSignInView; // view reference

// additional code

    void login(String email, String password){

        mInteractor.login(email,password, new SignInteractor.OnLoginListener(){

        @Override
        public void onLoginSuccess() {
            if (mSignInView != null) {
                mSignInView.signInSuccess();
            }
        }

        @Override
        public void onLoginFail(final int error) {
            if (mSignInView != null) {
                mSignInView.showError(R.string.error);
            }
        }
        })
    }

}
</code>```

Activity View:

```<code>SignInViewActivity implements SignInView{
   // additional code

   void showError(int resId){
    Toast.makeText(this, getString(resId), Toast.LENGTH_SHORT).show();
   }
}
</code>```

However, since R file is a part of android framework, this renders the presenter and interactor to not be usable in pure java apps.

I have gone through a lot of articles and discussions on various forums which provide various ways to achieve this.

Solutions :

view should use method like showLoginError() and decide itself how handle the view logic. In this way presenter has no knowledge of android related stuff.

However, string manipulation from interactor is not possible.

Create specific methods in view handling all cases eg showinvalidEmail(), showinvalidPassword() etc.

too many methods, difficult in complex cases.

using enum for error type and passing to view view.showError(ErrorTypes.INVALID_EMAIL)
-still confused about #enumsmatter :)

https://www.reddit.com/r/androiddev/comments/4v4urs/mvp_question_how_do_you_populate_your_textviews/

Use a resource abstraction or wrapper class that provides the required string.

difficult when there are large number of strings to be used.

https://medium.com/@daptronic/android-mvp-the-curious-case-of-resources-ddca39c1fccd

use library that provides api implementation for each string in strings.xml

still in beta stage

https://github.com/Comcast/resourceprovider

Please suggest what is the best approach to attain this as to not violate the principles of mvp or clean architecture.

答:
you can create an enumeration class like

```<code> enum class AuthError {
        INPUT_EMAIL_INVALID,
        INPUT_PASSWORD_INVALID,
        RESPONSE_EMAIL_DOES_NOT_EXIST
 }
</code>```

Then you can pass it to view like this

```<code>AuthView.someError(AuthError.INPUT_EMAIL_INVALID)
</code>```

You can check the type of the error by checking the type of the AuthError from there you can call R.string.error_message

This would remove the Presenter with Android Specific code.

Body:
So, I am currently trying to implement MVP approach in android, which I am new to. Now, it states that neither presenter nor the interactor class should have knowledge about android classes or components.

Makes sense to decouple the business logic from framework.
Good so far.

However I have an presenter that implements a callback to login in interactor, that passes a string resource id. The presenter passes the string res id to the view that displays error message in some form (whether a toast or a dialog).

Interactor:

public interface SignInteractor {

void login(String email, String password, OnLoginListener loginListener);

interface OnLoginListener {

    void onLoginSuccess();

    void onLoginFail(int error);

   }
}

Presenter:

public interface SignInPresenterImpl {
private SignInteractorImpl mInteractor; // interactor implementation
private SignInView mSignInView; // view reference

// additional code

    void login(String email, String password){

        mInteractor.login(email,password, new SignInteractor.OnLoginListener(){

        @Override
        public void onLoginSuccess() {
            if (mSignInView != null) {
                mSignInView.signInSuccess();
            }
        }

        @Override
        public void onLoginFail(final int error) {
            if (mSignInView != null) {
                mSignInView.showError(R.string.error);
            }
        }
        })
    }

}

Activity View:

SignInViewActivity implements SignInView{
   // additional code

   void showError(int resId){
    Toast.makeText(this, getString(resId), Toast.LENGTH_SHORT).show();
   }
}

However, since R file is a part of android framework, this renders the presenter and interactor to not be usable in pure java apps.

I have gone through a lot of articles and discussions on various forums which provide various ways to achieve this.

Solutions :

view should use method like showLoginError() and decide itself how handle the view logic. In this way presenter has no knowledge of android related stuff.

However, string manipulation from interactor is not possible.

Create specific methods in view handling all cases eg showinvalidEmail(), showinvalidPassword() etc.

too many methods, difficult in complex cases.

using enum for error type and passing to view view.showError(ErrorTypes.INVALID_EMAIL)
-still confused about #enumsmatter :)

https://www.reddit.com/r/androiddev/comments/4v4urs/mvp_question_how_do_you_populate_your_textviews/

Use a resource abstraction or wrapper class that provides the required string.

difficult when there are large number of strings to be used.

https://medium.com/@daptronic/android-mvp-the-curious-case-of-resources-ddca39c1fccd

use library that provides api implementation for each string in strings.xml

still in beta stage

https://github.com/Comcast/resourceprovider

Please suggest what is the best approach to attain this as to not violate the principles of mvp or clean architecture.

Body:
you can create an enumeration class like

 enum class AuthError {
        INPUT_EMAIL_INVALID,
        INPUT_PASSWORD_INVALID,
        RESPONSE_EMAIL_DOES_NOT_EXIST
 }

Then you can pass it to view like this

AuthView.someError(AuthError.INPUT_EMAIL_INVALID)

You can check the type of the error by checking the type of the AuthError from there you can call R.string.error_message

This would remove the Presenter with Android Specific code.


问:
FFMPEG wmv conversion to flv
anyone using ffmpeg

I have a fairly simple wmv exported by a user from movie maker with standard output and want to convert to .flv using

C:>ffmpeg -i "E:\Jab Core 4 Recounters.wmv" -vcodec flv "C:\Net Projects\SVN\IntegratedAlgorithmics\src\MediaAdmin\MediaAdmin\bin\Debug\Movies\Jab Core 4 Recounters.flv" -ar 44100

the output / error i receive is

```<code>FFmpeg version 0.5, Copyright (c) 2000-2009 Fabrice Bellard, et al.
  configuration: --enable-gpl --enable-postproc --enable-swscale --enable-avfilt
er --enable-avfilter-lavf --enable-pthreads --enable-avisynth --enable-libfaac -
-enable-libfaad --enable-libmp3lame --enable-libspeex --enable-libtheora --enabl
e-libvorbis --enable-libxvid --enable-libx264 --enable-memalign-hack
  libavutil     49.15. 0 / 49.15. 0
  libavcodec    52.20. 0 / 52.20. 0
  libavformat   52.31. 0 / 52.31. 0
  libavdevice   52. 1. 0 / 52. 1. 0
  libavfilter    0. 4. 0 /  0. 4. 0
  libswscale     0. 7. 1 /  0. 7. 1
  libpostproc   51. 2. 0 / 51. 2. 0
  built on Mar 16 2009 16:09:18, gcc: 4.2.4 [Sherpya]
[wmv3 @ 0x1c0d490]Extra data: 8 bits left, value: 0

Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000
/1) -> 30.00 (30/1)
Input #0, asf, from 'E:\Jab Core 4 Recounters.wmv':
  Duration: 00:01:55.99, start: 5.000000, bitrate: 813 kb/s
    Stream #0.0: Audio: wmav2, 48000 Hz, stereo, s16, 192 kb/s
    Stream #0.1: Video: wmv3, yuv420p, 640x480, 586 kb/s, 30 tbr, 1k tbn, 1k tbc

Output #0, flv, to 'C:\Net Projects\SVN\IntegratedAlgorithmics\src\MediaAdmin\Me
diaAdmin\bin\Debug\Movies\Jab Core 4 Recounters.flv':
    Stream #0.0: Video: flv, yuv420p, 640x480, q=2-31, 200 kb/s, 90k tbn, 30 tbc

    Stream #0.1: Audio: libmp3lame, 48000 Hz, stereo, s16, 64 kb/s
Stream mapping:
  Stream #0.1 -> #0.0
  Stream #0.0 -> #0.1
[wmv3 @ 0x1c0d490]Extra data: 8 bits left, value: 0
[libmp3lame @ 0x1c0d8d0]flv does not support that sample rate, choose from (4410
0, 22050, 11025).
Could not write header for output file #0 (incorrect codec parameters ?)
</code>```

i added th -ar switch when i got the error the first time

the codec info i have on the file is as follows

```<code>General
Complete name                    : E:\Jab Core 4 Recounters.wmv
Format                           : Windows Media
File size                        : 11.3 MiB
Duration                         : 2mn 0s
Overall bit rate mode            : Variable
Overall bit rate                 : 780 Kbps
Maximum Overall bit rate         : 949 Kbps
Encoded date                     : UTC 2009-03-07 07:02:41.121
Writing application              :  6.0.6000.16386 / Windows Movie Maker
Application                      : Windows Movie Maker 6.0.6000.16386

Video
ID                               : 2
Format                           : VC-1
Format profile                   : MP@ML
Codec ID                         : WMV3
Codec ID/Info                    : Windows Media Video 9
Codec ID/Hint                    : WMV3
Duration                         : 2mn 0s
Bit rate mode                    : Variable
Bit rate                         : 587 Kbps
Width                            : 640 pixels
Height                           : 480 pixels
Display aspect ratio             : 4/3
Frame rate                       : 30.000 fps
Resolution                       : 24 bits
Scan type                        : Progressive
Bits/(Pixel*Frame)               : 0.064
Stream size                      : 8.46 MiB (75%)
Language                         : en-us

Audio
ID                               : 1
Format                           : WMA2
Format profile                   : L3
Codec ID                         : 161
Codec ID/Info                    : Windows Media Audio 2
Description of the codec         : Windows Media Audio 9.2 - VBR Quality 90, 48 kHz, stereo 1-pass VBR
Duration                         : 2mn 0s
Bit rate mode                    : Variable
Bit rate                         : 186 Kbps
Channel(s)                       : 2 channels
Sampling rate                    : 48.0 KHz
Resolution                       : 16 bits
Stream size                      : 2.68 MiB (24%)
Language                         : en-us
</code>```

i see alot of people with this issue with so solution or cause

any ideas would be helpful
thanks in advance

答:
More precisely: in ffmpeg, options must prefix the output file they relate to.
 Move -ar 44100 to the front of the output filename and it will work.

Title: FFMPEG wmv conversion to flv

Body:
anyone using ffmpeg

I have a fairly simple wmv exported by a user from movie maker with standard output and want to convert to .flv using

C:>ffmpeg -i "E:\Jab Core 4 Recounters.wmv" -vcodec flv "C:\Net Projects\SVN\IntegratedAlgorithmics\src\MediaAdmin\MediaAdmin\bin\Debug\Movies\Jab Core 4 Recounters.flv" -ar 44100

the output / error i receive is

FFmpeg version 0.5, Copyright (c) 2000-2009 Fabrice Bellard, et al.
  configuration: --enable-gpl --enable-postproc --enable-swscale --enable-avfilt
er --enable-avfilter-lavf --enable-pthreads --enable-avisynth --enable-libfaac -
-enable-libfaad --enable-libmp3lame --enable-libspeex --enable-libtheora --enabl
e-libvorbis --enable-libxvid --enable-libx264 --enable-memalign-hack
  libavutil     49.15. 0 / 49.15. 0
  libavcodec    52.20. 0 / 52.20. 0
  libavformat   52.31. 0 / 52.31. 0
  libavdevice   52. 1. 0 / 52. 1. 0
  libavfilter    0. 4. 0 /  0. 4. 0
  libswscale     0. 7. 1 /  0. 7. 1
  libpostproc   51. 2. 0 / 51. 2. 0
  built on Mar 16 2009 16:09:18, gcc: 4.2.4 [Sherpya]
[wmv3 @ 0x1c0d490]Extra data: 8 bits left, value: 0

Seems stream 1 codec frame rate differs from container frame rate: 1000.00 (1000
/1) -> 30.00 (30/1)
Input #0, asf, from 'E:\Jab Core 4 Recounters.wmv':
  Duration: 00:01:55.99, start: 5.000000, bitrate: 813 kb/s
    Stream #0.0: Audio: wmav2, 48000 Hz, stereo, s16, 192 kb/s
    Stream #0.1: Video: wmv3, yuv420p, 640x480, 586 kb/s, 30 tbr, 1k tbn, 1k tbc

Output #0, flv, to 'C:\Net Projects\SVN\IntegratedAlgorithmics\src\MediaAdmin\Me
diaAdmin\bin\Debug\Movies\Jab Core 4 Recounters.flv':
    Stream #0.0: Video: flv, yuv420p, 640x480, q=2-31, 200 kb/s, 90k tbn, 30 tbc

    Stream #0.1: Audio: libmp3lame, 48000 Hz, stereo, s16, 64 kb/s
Stream mapping:
  Stream #0.1 -> #0.0
  Stream #0.0 -> #0.1
[wmv3 @ 0x1c0d490]Extra data: 8 bits left, value: 0
[libmp3lame @ 0x1c0d8d0]flv does not support that sample rate, choose from (4410
0, 22050, 11025).
Could not write header for output file #0 (incorrect codec parameters ?)

i added th -ar switch when i got the error the first time

the codec info i have on the file is as follows

General
Complete name                    : E:\Jab Core 4 Recounters.wmv
Format                           : Windows Media
File size                        : 11.3 MiB
Duration                         : 2mn 0s
Overall bit rate mode            : Variable
Overall bit rate                 : 780 Kbps
Maximum Overall bit rate         : 949 Kbps
Encoded date                     : UTC 2009-03-07 07:02:41.121
Writing application              :  6.0.6000.16386 / Windows Movie Maker
Application                      : Windows Movie Maker 6.0.6000.16386

Video
ID                               : 2
Format                           : VC-1
Format profile                   : MP@ML
Codec ID                         : WMV3
Codec ID/Info                    : Windows Media Video 9
Codec ID/Hint                    : WMV3
Duration                         : 2mn 0s
Bit rate mode                    : Variable
Bit rate                         : 587 Kbps
Width                            : 640 pixels
Height                           : 480 pixels
Display aspect ratio             : 4/3
Frame rate                       : 30.000 fps
Resolution                       : 24 bits
Scan type                        : Progressive
Bits/(Pixel*Frame)               : 0.064
Stream size                      : 8.46 MiB (75%)
Language                         : en-us

Audio
ID                               : 1
Format                           : WMA2
Format profile                   : L3
Codec ID                         : 161
Codec ID/Info                    : Windows Media Audio 2
Description of the codec         : Windows Media Audio 9.2 - VBR Quality 90, 48 kHz, stereo 1-pass VBR
Duration                         : 2mn 0s
Bit rate mode                    : Variable
Bit rate                         : 186 Kbps
Channel(s)                       : 2 channels
Sampling rate                    : 48.0 KHz
Resolution                       : 16 bits
Stream size                      : 2.68 MiB (24%)
Language                         : en-us

i see alot of people with this issue with so solution or cause

any ideas would be helpful
thanks in advance


问:
How to swap a long variable present in list of a class with swap method
I have a list public List<ArticleWarehouseLocations> ArticleWarehouseLocationsList. In this list I have a property called Position.

```<code>`Swap<long>(ref ArticleWarehouseLocationsList[currentIndex].Position, ref ArticleWarehouseLocationsList[currentIndex - 1].Position);`
    public void Swap<T>(ref T lhs, ref T rhs)
     {
       T temp = lhs;
       lhs = rhs;
       rhs = temp;
      }
</code>```

I'm trying to do something like this. It's giving me an error property or index may not be passed as ref or out.

I can use a local variable and assign it the value and use it but I'm looking for a global solution.

答:
I believe the tuple swap (x, y) = (y, x) proposed in comments is the way to go, but wanted to share yet another aproach with LINQ Expressions (a bit too long for a comment, so posting as an answer)

public static void SwapProperties<T>(T lhs, T rhs, Expression<Func<T, object>> propExpression)
{
    var prop = GetPropertyInfo(propExpression);
    var lhsValue = prop.GetValue(lhs);
    var rhsValue = prop.GetValue(rhs);
    prop.SetValue(lhs, rhsValue);
    prop.SetValue(rhs, lhsValue);
}

private static PropertyInfo GetPropertyInfo<T>(Expression<Func<T, object>> propExpression)
{
    PropertyInfo prop;
    if (propExpression.Body is MemberExpression memberExpression)
    {
        prop = (PropertyInfo) memberExpression.Member;
    }
    else
    {
        var op = ((UnaryExpression) propExpression.Body).Operand;
        prop = (PropertyInfo) ((MemberExpression) op).Member;
    }
    return prop;
}

class Obj
{
    public long Position { get; set; }
    public string Name { get; set; }
}

public static void Main(string[] args)
{
    var a1 = new Obj()
    {
        Position = 10,
        Name = "a1"
    };
    var a2 = new Obj()
    {
        Position = 20,
        Name = "a2"
    };
    SwapProperties(a1, a2, obj => obj.Position);
    SwapProperties(a1, a2, obj => obj.Name);

    Console.WriteLine(a1.Position);
    Console.WriteLine(a2.Position);

    Console.WriteLine(a1.Name);
    Console.WriteLine(a2.Name);
}

```

Body:
I have a list public List<ArticleWarehouseLocations> ArticleWarehouseLocationsList. In this list I have a property called Position.

`Swap<long>(ref ArticleWarehouseLocationsList[currentIndex].Position, ref ArticleWarehouseLocationsList[currentIndex - 1].Position);`
    public void Swap<T>(ref T lhs, ref T rhs)
     {
       T temp = lhs;
       lhs = rhs;
       rhs = temp;
      }

I'm trying to do something like this. It's giving me an error property or index may not be passed as ref or out.

I can use a local variable and assign it the value and use it but I'm looking for a global solution.


问:
I am getting error when creating stored procedure with while loop in mysql
i have created one stored procedure for sum of perticular condition but getting syntax error.

create table script :

```<code>CREATE TABLE count_smaller_coverage (count_records INT(11) ,block_id INT(11))
</code>```

insert data :

```<code>INSERT INTO count_smaller_coverage
SELECT '114000','1' UNION
SELECT '112000','2' UNION
SELECT '98765','3' UNION
SELECT '78965','4' UNION
SELECT '4125','5' UNION
SELECT '123654','6' UNION
SELECT '78999','7' UNION
SELECT '89888','8' UNION
SELECT '99654','9' UNION
SELECT '75365','10' UNION
SELECT '25638','11' UNION
SELECT '85236','12' UNION
SELECT '65478','13' UNION
SELECT '65478','14' UNION
SELECT '85236','15'
</code>```

Stored Procedure :

```<code>DELIMITER $$
DROP PROCEDURE IF EXISTS test_mysql_while_loop$$
CREATE PROCEDURE test_mysql_while_loop()
BEGIN
DECLARE strat INT;
DECLARE END INT;
DECLARE SumofCount BIGINT;
DECLARE block_id VARCHAR(2000);
SET strat=(SELECT MIN(block_id) FROM count_smaller_coverage);
SET END =(SELECT MAX(block_id) FROM count_smaller_coverage);
CREATE TABLE blocks_parts (block_id VARCHAR(2000), Counts BIGINT);

test: WHILE strat<=END DO

BEGIN

IF SumofCount > 800000 THEN
SET SumofCount=0;
SET block_id = NULL;
END IF;

SET SumofCount=COALESCE(SumofCount,0)+(SELECT count_records FROM count_smaller_coverage WHERE block_id=strat);
SELECT block_id = (COALESCE(block_id + ',', '') + CAST(block_id AS CHAR)) AS id FROM count_smaller_coverage WHERE block_id=strat;

IF SumofCount BETWEEN 800000 AND 1000000 THEN
INSERT INTO blocks_parts(block_id,Counts) VALUES (block_id,SumofCount);
END IF;

IF SumofCount BETWEEN 800000 AND 100000 THEN
    LEAVE test;
END IF;

SET strat=strat+1;

END test;
END$$
DELIMITER ;
</code>```

Error :

Query: CREATE PROCEDURE test_mysql_while_loop() BEGIN DECLARE strat INT; DECLARE end INT; DECLARE SumofCount BIGINT; DECLARE block_id V...

Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'test;
END' at line 33

Execution Time : 0 sec
Transfer Time  : 0 sec
Total Time     : 0.060 sec

答:
You have a couple of issues in your procedure. Firstly, you have an unnecessary BEGIN after the DO in your WHILE statement. You can either remove that or match it with an END. Secondly, you need to end the WHILE loop with an END WHILE, in your case adding the test label to that statement. This should work:

```<code>test: WHILE strat<=END DO
    -- BEGIN -- if you put BEGIN here ...
    IF SumofCount > 800000 THEN
    SET SumofCount=0;
    SET block_id = NULL;
    END IF;

    SET SumofCount=COALESCE(SumofCount,0)+(SELECT count_records FROM count_smaller_coverage WHERE block_id=strat);
    SELECT block_id = (COALESCE(block_id + ',', '') + CAST(block_id AS CHAR)) AS id FROM count_smaller_coverage WHERE block_id=strat;

    IF SumofCount BETWEEN 800000 AND 1000000 THEN
    INSERT INTO blocks_parts(block_id,Counts) VALUES (block_id,SumofCount);
    END IF;

    IF SumofCount BETWEEN 800000 AND 100000 THEN
        LEAVE test;
    END IF;

    SET strat=strat+1;
    -- END -- ... you must put END here
END WHILE test;
</code>```

Body:
i have created one stored procedure for sum of perticular condition but getting syntax error.

create table script :

CREATE TABLE count_smaller_coverage (count_records INT(11) ,block_id INT(11))

insert data :

INSERT INTO count_smaller_coverage
SELECT '114000','1' UNION
SELECT '112000','2' UNION
SELECT '98765','3' UNION
SELECT '78965','4' UNION
SELECT '4125','5' UNION
SELECT '123654','6' UNION
SELECT '78999','7' UNION
SELECT '89888','8' UNION
SELECT '99654','9' UNION
SELECT '75365','10' UNION
SELECT '25638','11' UNION
SELECT '85236','12' UNION
SELECT '65478','13' UNION
SELECT '65478','14' UNION
SELECT '85236','15'

Stored Procedure :

DELIMITER $$
DROP PROCEDURE IF EXISTS test_mysql_while_loop$$
CREATE PROCEDURE test_mysql_while_loop()
BEGIN
DECLARE strat INT;
DECLARE END INT;
DECLARE SumofCount BIGINT;
DECLARE block_id VARCHAR(2000);
SET strat=(SELECT MIN(block_id) FROM count_smaller_coverage);
SET END =(SELECT MAX(block_id) FROM count_smaller_coverage);
CREATE TABLE blocks_parts (block_id VARCHAR(2000), Counts BIGINT);

test: WHILE strat<=END DO

BEGIN

IF SumofCount > 800000 THEN
SET SumofCount=0;
SET block_id = NULL;
END IF;

SET SumofCount=COALESCE(SumofCount,0)+(SELECT count_records FROM count_smaller_coverage WHERE block_id=strat);
SELECT block_id = (COALESCE(block_id + ',', '') + CAST(block_id AS CHAR)) AS id FROM count_smaller_coverage WHERE block_id=strat;

IF SumofCount BETWEEN 800000 AND 1000000 THEN
INSERT INTO blocks_parts(block_id,Counts) VALUES (block_id,SumofCount);
END IF;

IF SumofCount BETWEEN 800000 AND 100000 THEN
    LEAVE test;
END IF;

SET strat=strat+1;

END test;
END$$
DELIMITER ;

Error :

Query: CREATE PROCEDURE test_mysql_while_loop() BEGIN DECLARE strat INT; DECLARE end INT; DECLARE SumofCount BIGINT; DECLARE block_id V...

Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'test;
END' at line 33

Execution Time : 0 sec
Transfer Time  : 0 sec
Total Time     : 0.060 sec

Body:
You have a couple of issues in your procedure. Firstly, you have an unnecessary BEGIN after the DO in your WHILE statement. You can either remove that or match it with an END. Secondly, you need to end the WHILE loop with an END WHILE, in your case adding the test label to that statement. This should work:

test: WHILE strat<=END DO
    -- BEGIN -- if you put BEGIN here ...
    IF SumofCount > 800000 THEN
    SET SumofCount=0;
    SET block_id = NULL;
    END IF;

    SET SumofCount=COALESCE(SumofCount,0)+(SELECT count_records FROM count_smaller_coverage WHERE block_id=strat);
    SELECT block_id = (COALESCE(block_id + ',', '') + CAST(block_id AS CHAR)) AS id FROM count_smaller_coverage WHERE block_id=strat;

    IF SumofCount BETWEEN 800000 AND 1000000 THEN
    INSERT INTO blocks_parts(block_id,Counts) VALUES (block_id,SumofCount);
    END IF;

    IF SumofCount BETWEEN 800000 AND 100000 THEN
        LEAVE test;
    END IF;

    SET strat=strat+1;
    -- END -- ... you must put END here
END WHILE test;


问:
Scroll to top/bottom using percentage in jquery?
I've made a page navigation with a scroll to top and to bottom button. The problem is: using simple values except of percentages one of my buttons won't appear because of less content.

So my question is how to change the code so that the button will change if you reach e.g. 60% or less than 60% of the page?

I've read different posts for example this post or this post but the code doesn't fit my needs or I don't know how to use them for my custom code.

jQuery(function($){

$(document).scroll(function() {
  var y = $(document).scrollTop();
  if (y > 1500) {
      $(this).find('.icon-arrow-m').removeClass('icon-arrow-m');
      $('a.scroll:nth-child(1) > i:nth-child(1)').addClass("icon-arrow-up");
  } else if (y <= 1500){
      $(this).find('.icon-arrow-up').removeClass('icon-arrow-up');
      $('a.scroll:nth-child(1) > i:nth-child(1)').addClass('icon-arrow-m');
  }
});

 $(".scroll").click(function(event){
    var y = $(document).scrollTop();
    var down = y+4800;
   if($(this).find('.icon-arrow-up').hasClass('icon-arrow-up')) {
     $('html, body').animate({scrollTop: '0'}, 800);
    } else {
     $('html, body').animate({scrollTop: down}, 800);
    }

 });
});```
</div>
</div>
</p>

<p>To test the code, you can go my main page where I'm using this script.</p>

<p><strong>Updated code - fixed scroll to bottom</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code> jQuery(function($){

$(document).scroll(function() {
  var y = $(document).scrollTop();
  if (y > 1500) {
      $(this).find('.icon-arrow-m').removeClass('icon-arrow-m');
      $('a.scroll:nth-child(1) > i:nth-child(1)').addClass("icon-arrow-up");
  } else if (y <= 1500){
      $(this).find('.icon-arrow-up').removeClass('icon-arrow-up');
      $('a.scroll:nth-child(1) > i:nth-child(1)').addClass('icon-arrow-m');
  }
});

 $(".scroll").click(function(event){
    var y = $(document).scrollTop();
    var down = y+4800;
   if($(this).find('.icon-arrow-up').hasClass('icon-arrow-up')) {
     $('html, body').animate({scrollTop: '0'}, 800);
    } else {
     $('html, body').animate({scrollTop:  $(document).height()}, 800);
    }

 });
});</code>```

答:
You can calculate 50% dividing by 2 the height of the page (see var x in code snippet):

 jQuery(function($){

$(document).scroll(function() {

  var y = $(document).scrollTop(); // AMOUNT OF SCROLL FROM TOP
  var x = $(document).height() / 2; // HALF OF PAGE HEIGHT

  if (y > x) { // SCROLL IS OVER 50% OF PAGE HEIGHT
      $(this).find('.icon-arrow-m').removeClass('icon-arrow-m');
      $('a.scroll:nth-child(1) > i:nth-child(1)').addClass("icon-arrow-up");
  } else { // SCROLL IS LESS THAN 50% OF PAGE HEIGHT
      $(this).find('.icon-arrow-up').removeClass('icon-arrow-up');
      $('a.scroll:nth-child(1) > i:nth-child(1)').addClass('icon-arrow-m');
  }
});

 $(".scroll").click(function(event){
   if($(this).find('.icon-arrow-up').hasClass('icon-arrow-up')) {
     $('html, body').animate({scrollTop: '0'}, 800);
    } else {
     $('html, body').animate({scrollTop:  $(document).height()}, 800);
    }

 });
});```

Body:
I've made a page navigation with a scroll to top and to bottom button. The problem is: using simple values except of percentages one of my buttons won't appear because of less content.

So my question is how to change the code so that the button will change if you reach e.g. 60% or less than 60% of the page?

I've read different posts for example this post or this post but the code doesn't fit my needs or I don't know how to use them for my custom code.

jQuery(function($){

$(document).scroll(function() {
  var y = $(document).scrollTop();
  if (y > 1500) {
      $(this).find('.icon-arrow-m').removeClass('icon-arrow-m');
      $('a.scroll:nth-child(1) > i:nth-child(1)').addClass("icon-arrow-up");
  } else if (y <= 1500){
      $(this).find('.icon-arrow-up').removeClass('icon-arrow-up');
      $('a.scroll:nth-child(1) > i:nth-child(1)').addClass('icon-arrow-m');
  }
});

 $(".scroll").click(function(event){
    var y = $(document).scrollTop();
    var down = y+4800;
   if($(this).find('.icon-arrow-up').hasClass('icon-arrow-up')) {
     $('html, body').animate({scrollTop: '0'}, 800);
    } else {
     $('html, body').animate({scrollTop: down}, 800);
    }

 });
});

To test the code, you can go my main page where I'm using this script.

Updated code - fixed scroll to bottom

 jQuery(function($){

$(document).scroll(function() {
  var y = $(document).scrollTop();
  if (y > 1500) {
      $(this).find('.icon-arrow-m').removeClass('icon-arrow-m');
      $('a.scroll:nth-child(1) > i:nth-child(1)').addClass("icon-arrow-up");
  } else if (y <= 1500){
      $(this).find('.icon-arrow-up').removeClass('icon-arrow-up');
      $('a.scroll:nth-child(1) > i:nth-child(1)').addClass('icon-arrow-m');
  }
});

 $(".scroll").click(function(event){
    var y = $(document).scrollTop();
    var down = y+4800;
   if($(this).find('.icon-arrow-up').hasClass('icon-arrow-up')) {
     $('html, body').animate({scrollTop: '0'}, 800);
    } else {
     $('html, body').animate({scrollTop:  $(document).height()}, 800);
    }

 });
});


问:
Prevent redirection to root url
i am trying to access a webpage. I manage to get the redirect webpage session id as shown:
http://www.sbstransit.com.sg/mobileiris/(tqkjtlnqkh2lw5v4rz4yurzf)/mobresult_svclist.aspx?stopcode=16101

I added mobresult_svclist.aspx?stopcode=16101 after the session id to retrieve the information.

However, i could not access the page and keep been redirected to the root url: http://www.sbstransit.com.sg/mobileiris/(tqkjtlnqkh2lw5v4rz4yurzf)/index_nextbus.aspx?__redir=1.

Do anyone know how to prevent that redirection to the root url using php or any other codes? Thanks.

答: You cannot. If the server sends a redirect header, you can of course choose not to follow it, but the page body would still be empty if the server side doesn't generate it.</p>

Title: Prevent redirection to root url