问:
C++ Programming Homework Assignment (do...while loops)
One of my programming assignments is as follows:

The population of a town A is less than the population of town B. However, the population of town A is growing faster than the population of town B. Write a program that prompts the user to enter the population and growth rate of each town. The program outputs after how many years the population of town A will be greater than or equal to the population of town B and the populations of both the towns at that time. (A sample input is: Population of town A = 5000, growth rate of town A = 4%, population of town B = 8000, and growth rate of town B = 2%.)

I have the main part of the assignment down, input the population and growth rate and calculate the population after x years, but I can't figure out how to compare the final population of town A with the final population of town B and the combined total. Any tips would be appreciated.

```<code>#include <iostream>

using namespace std;

int main()
{
    int popA, popB, year = 1;
    double growth_rateA, growth_rateB;

    cout << "Enter the population and growth rate of Town A: ";
    cin >> popA >> growth_rateA;
    cout << endl;

    cout << "Enter the population and growth rate of Town B: ";
    cin >> popB >> growth_rateB;
    cout << endl;

    if (popA < popB && growth_rateA > growth_rateB)
    {
        {
        do {
                (popA = ((growth_rateA / 100) * popA) + popA); // calculates population growth in one year
                (popB = ((growth_rateB / 100) * popB) + popB);
                year++;
            }

            while (popA < popB);

            cout << "Town A will surpass Town B in population after " << year << " years.\n" << endl;
            cout << "The final population of Town A is: " << popA << ".\n" << endl;
            cout << "The final population of Town B is: " << popB << ".\n" << endl;
        }
    }
    else
    {
        cout << "Invalid Data.";
    }

    system("pause");
    return 0;
}
</code>```

答:
Bettorun said it: because popA and popB were declared outside the do-while loop, they will retain their final values after you’ve exited that loop, and you can use them to perform other calculations on them.

Here’s your code with my addition. I also got rid of one level of nesting that wasn’t necessary and start the year at 0 instead of 1.

```<code>#include <iostream>

using namespace std;

int main()
{
    int popA, popB, year = 0;
    double growth_rateA, growth_rateB;

    cout << "Enter the population and growth rate of Town A: ";
    cin >> popA >> growth_rateA;
    cout << endl;

    cout << "Enter the population and growth rate of Town B: ";
    cin >> popB >> growth_rateB;
    cout << endl;

    if (popA < popB && growth_rateA > growth_rateB) {
        do {
            (popA = ((growth_rateA / 100) * popA) + popA); // calculates population growth in one year
            (popB = ((growth_rateB / 100) * popB) + popB);
            year++;
        } while (popA < popB);

        int popDifference = popA - popB;
        int popTotal = popA + popB;
        cout << "Town A will surpass Town B in population after " << year << " years.\n" ;
        cout << "The final population of Town A is: " << popA << ".\n";
        cout << "The final population of Town B is: " << popB << ".\n";
        cout << "In year " << year << ", Town A has " << popDifference << " more people than town B.\n";
        cout << "The total population of both Town A and Town B is " << popTotal << ".\n";
    } else {
        cout << "Invalid Data.";
    }

    system("pause");
    return 0;
}
</code>```

Body:
One of my programming assignments is as follows:

The population of a town A is less than the population of town B. However, the population of town A is growing faster than the population of town B. Write a program that prompts the user to enter the population and growth rate of each town. The program outputs after how many years the population of town A will be greater than or equal to the population of town B and the populations of both the towns at that time. (A sample input is: Population of town A = 5000, growth rate of town A = 4%, population of town B = 8000, and growth rate of town B = 2%.)

I have the main part of the assignment down, input the population and growth rate and calculate the population after x years, but I can't figure out how to compare the final population of town A with the final population of town B and the combined total. Any tips would be appreciated.

#include <iostream>

using namespace std;

int main()
{
    int popA, popB, year = 1;
    double growth_rateA, growth_rateB;

    cout << "Enter the population and growth rate of Town A: ";
    cin >> popA >> growth_rateA;
    cout << endl;

    cout << "Enter the population and growth rate of Town B: ";
    cin >> popB >> growth_rateB;
    cout << endl;

    if (popA < popB && growth_rateA > growth_rateB)
    {
        {
        do {
                (popA = ((growth_rateA / 100) * popA) + popA); // calculates population growth in one year
                (popB = ((growth_rateB / 100) * popB) + popB);
                year++;
            }

            while (popA < popB);

            cout << "Town A will surpass Town B in population after " << year << " years.\n" << endl;
            cout << "The final population of Town A is: " << popA << ".\n" << endl;
            cout << "The final population of Town B is: " << popB << ".\n" << endl;
        }
    }
    else
    {
        cout << "Invalid Data.";
    }

    system("pause");
    return 0;
}

Body:
Bettorun said it: because popA and popB were declared outside the do-while loop, they will retain their final values after you’ve exited that loop, and you can use them to perform other calculations on them.

Here’s your code with my addition. I also got rid of one level of nesting that wasn’t necessary and start the year at 0 instead of 1.

#include <iostream>

using namespace std;

int main()
{
    int popA, popB, year = 0;
    double growth_rateA, growth_rateB;

    cout << "Enter the population and growth rate of Town A: ";
    cin >> popA >> growth_rateA;
    cout << endl;

    cout << "Enter the population and growth rate of Town B: ";
    cin >> popB >> growth_rateB;
    cout << endl;

    if (popA < popB && growth_rateA > growth_rateB) {
        do {
            (popA = ((growth_rateA / 100) * popA) + popA); // calculates population growth in one year
            (popB = ((growth_rateB / 100) * popB) + popB);
            year++;
        } while (popA < popB);

        int popDifference = popA - popB;
        int popTotal = popA + popB;
        cout << "Town A will surpass Town B in population after " << year << " years.\n" ;
        cout << "The final population of Town A is: " << popA << ".\n";
        cout << "The final population of Town B is: " << popB << ".\n";
        cout << "In year " << year << ", Town A has " << popDifference << " more people than town B.\n";
        cout << "The total population of both Town A and Town B is " << popTotal << ".\n";
    } else {
        cout << "Invalid Data.";
    }

    system("pause");
    return 0;
}

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Query a chain of one to many and many to one
I currently have 3 tables roughly described as the following SQLAlchemy mapping:

```<code>class Task(BASE):
    __tablename__ = 'tasks'
    id = Column(Integer, primary_key=True)

    service_id = Column(Integer, ForeignKey('services.id'))
    service = relationship('Service', back_populates="tasks")

    updates = relationship("TaskUpdate")

class TaskUpdate(BASE):
    __tablename__ = 'task_updates'

    id = Column(Integer, primary_key=True)
    external_status = Column(String(32))
    external_updated_at = Column(DateTime(timezone=True))

    task_id = Column(Integer, ForeignKey('tasks.id'))
    task = relationship('Task', back_populates="updates")

class Service(BASE):
    __tablename__ = 'services'

    id = Column(Integer, primary_key=True)

    client_id = Column(Integer, ForeignKey('clients.id'))
    client = relationship('Client', back_populates='services')
</code>```

So I have one-to-many relationship from Task to TaskUpdates and a many-to-one from Task to Service.

I'm trying to create a query to get all Tasks where their latest TaskUpdate (by timestamp) has an external_status that is "New", or "Open."

Here's what I got:

```<code>sub = SESSION.query(
        TaskUpdate.task_id,
        TaskUpdate.external_status.label('last_status'),
        func.max(TaskUpdate.external_updated_at).label('last_update')
        ).group_by(TaskUpdate.task_id
        ).subquery()
tasks = SESSION.query(Task
        ).join(Service
        ).filter(Service.client_id == client_id
        ).join((sub, sub.c.task_id == Task.id)
        ).filter(sub.c.last_status.in_(['New', 'Open']))
</code>```

When I run this, I get this error:

```<code>ProgrammingError: (psycopg2.ProgrammingError) column "task_updates.external_status" must appear in the GROUP BY clause or be used in an aggregate function
</code>```

I'd appreciate any help you can give. This is important.

Update 1 (this is the SQL that ended up working (as far as I can tell, I can't test the frontend until I get this working in SQLAlchemy though:

```<code>SELECT t.* FROM (
  SELECT DISTINCT ON (task_id) task_id, external_status
  FROM task_updates
  ORDER BY task_id, external_updated_at DESC NULLS LAST) tu
JOIN tasks t ON t.id = tu.task_id
JOIN services s ON s.id = t.service_id
WHERE s.client_id = '" + str(client_id) + "'
AND tu.external_status IN ('New', 'Open');
</code>```

Here's my conversion attempt, still not working:

```<code>sub = SESSION.query(TaskUpdate).distinct(TaskUpdate.task_id).order_by(TaskUpdate.task_id.desc().nullslast(), TaskUpdate.external_updated_at.desc().nullslast()).subquery()
tasks = SESSION.query(Task).join(Service).join(sub.c.task_id==Task.id).filter(TaskUpdate.external_status.in_(['New', 'Open']))
</code>```

Update 2: The query I have below works, but when I do .count() it returns the total number of TaskUpdates, not tasks and I suspect the query will need to be redone a different way, unless someone knows a way to handle this?

答:
I'm giving credit to Erwin since he put me onto the the right trail, but this is what I ended up using in the end. Works well enough. Will optimize later once I actually have an engineer or several working with me. :)

Thanks!

```<code>sub = SESSION.query(TaskUpdate.task_id, TaskUpdate.external_status).distinct(TaskUpdate.task_id).order_by(TaskUpdate.task_id.desc().nullslast(), TaskUpdate.external_updated_at.desc().nullslast()).subquery()
tasks = SESSION.query(Task).join(Service).join((sub, sub.c.task_id==Task.id)).filter(sub.c.external_status.in_(['New', 'Open', 'Pending']))
</code>```

Maybe I converted this incorrectly, but when I do a count, it gives me the number of TaskUpdates, not Tasks. This causes problems in my app.

ContentLicense: CC BY-SA 3.0

Body:
I currently have 3 tables roughly described as the following SQLAlchemy mapping:

class Task(BASE):
    __tablename__ = 'tasks'
    id = Column(Integer, primary_key=True)

    service_id = Column(Integer, ForeignKey('services.id'))
    service = relationship('Service', back_populates="tasks")

    updates = relationship("TaskUpdate")

class TaskUpdate(BASE):
    __tablename__ = 'task_updates'

    id = Column(Integer, primary_key=True)
    external_status = Column(String(32))
    external_updated_at = Column(DateTime(timezone=True))

    task_id = Column(Integer, ForeignKey('tasks.id'))
    task = relationship('Task', back_populates="updates")

class Service(BASE):
    __tablename__ = 'services'

    id = Column(Integer, primary_key=True)

    client_id = Column(Integer, ForeignKey('clients.id'))
    client = relationship('Client', back_populates='services')

So I have one-to-many relationship from Task to TaskUpdates and a many-to-one from Task to Service.

I'm trying to create a query to get all Tasks where their latest TaskUpdate (by timestamp) has an external_status that is "New", or "Open."

Here's what I got:

sub = SESSION.query(
        TaskUpdate.task_id,
        TaskUpdate.external_status.label('last_status'),
        func.max(TaskUpdate.external_updated_at).label('last_update')
        ).group_by(TaskUpdate.task_id
        ).subquery()
tasks = SESSION.query(Task
        ).join(Service
        ).filter(Service.client_id == client_id
        ).join((sub, sub.c.task_id == Task.id)
        ).filter(sub.c.last_status.in_(['New', 'Open']))

When I run this, I get this error:

ProgrammingError: (psycopg2.ProgrammingError) column "task_updates.external_status" must appear in the GROUP BY clause or be used in an aggregate function

I'd appreciate any help you can give. This is important.

Update 1 (this is the SQL that ended up working (as far as I can tell, I can't test the frontend until I get this working in SQLAlchemy though:

SELECT t.* FROM (
  SELECT DISTINCT ON (task_id) task_id, external_status
  FROM task_updates
  ORDER BY task_id, external_updated_at DESC NULLS LAST) tu
JOIN tasks t ON t.id = tu.task_id
JOIN services s ON s.id = t.service_id
WHERE s.client_id = '" + str(client_id) + "'
AND tu.external_status IN ('New', 'Open');

Here's my conversion attempt, still not working:

sub = SESSION.query(TaskUpdate).distinct(TaskUpdate.task_id).order_by(TaskUpdate.task_id.desc().nullslast(), TaskUpdate.external_updated_at.desc().nullslast()).subquery()
tasks = SESSION.query(Task).join(Service).join(sub.c.task_id==Task.id).filter(TaskUpdate.external_status.in_(['New', 'Open']))

Update 2: The query I have below works, but when I do .count() it returns the total number of TaskUpdates, not tasks and I suspect the query will need to be redone a different way, unless someone knows a way to handle this?

Body:
I'm giving credit to Erwin since he put me onto the the right trail, but this is what I ended up using in the end. Works well enough. Will optimize later once I actually have an engineer or several working with me. :)

Thanks!

sub = SESSION.query(TaskUpdate.task_id, TaskUpdate.external_status).distinct(TaskUpdate.task_id).order_by(TaskUpdate.task_id.desc().nullslast(), TaskUpdate.external_updated_at.desc().nullslast()).subquery()
tasks = SESSION.query(Task).join(Service).join((sub, sub.c.task_id==Task.id)).filter(sub.c.external_status.in_(['New', 'Open', 'Pending']))

Maybe I converted this incorrectly, but when I do a count, it gives me the number of TaskUpdates, not Tasks. This causes problems in my app.


问:
How to check for empty cells in range if empty then check in selection VBA?
I have the below code that will filter the table by the user selection.

I would like to first check range A3:T3 if they have values in and if they do i will add to my array and start filtering by that and ignore all empty cells in Range A3:T3.

If range A3:T3 is empty then filter by user selection.

I notice there is a bug where if i filter by a cell and that cell has 2 rows with data 1 will show and 1 not because there is a space in front of it i think its a ChrW is there any way to make the filter take partial match to include both versions? I know i can replace the ChrW and replace it but data will be always pasted from outlook so the occurrence will be frequent so if i can take a partial match that will probably solve a lot of the problems.

Any help would be much appreciated.

```<code>Sub advancedMultipleCriteriaFilter()

  Dim cellRng As Range, tableObject As Range, subSelection As Range
  Dim filterCriteria() As String, filterFields() As Integer
  Dim i As Integer

  Application.ScreenUpdating = False
  'Call removeSpace

  If Selection.Rows.Count > 1 Then
    MsgBox "Cannot apply filter to multiple rows within the same column. Please make another selection and try again.", vbInformation, "Selection Error!"
    Exit Sub
  End If

  i = 1
  ReDim filterCriteria(1 To Selection.Cells.Count) As String
  ReDim filterFields(1 To Selection.Cells.Count) As Integer

  Set tableObject = Selection.CurrentRegion
  For Each subSelection In Selection.Areas
    For Each cellRng In subSelection
      filterCriteria(i) = cellRng.Text
      filterFields(i) = cellRng.Column - tableObject.Cells(1, 1).Column + 1
      i = i + 1
    Next cellRng
  Next subSelection

  With tableObject
    For i = 1 To UBound(filterCriteria)
      .AutoFilter field:=filterFields(i), Criteria1:=filterCriteria(i)
    Next i
  End With

  Call GetLastRow

  Set tableObject = Nothing
  Application.ScreenUpdating = True

End Sub

Sub resetFilters()

  Dim sht As Worksheet
  Dim LastRow As Range

  Application.ScreenUpdating = False

  On Error Resume Next
  If ActiveSheet.FilterMode Then
    ActiveSheet.ShowAllData
  End If

  Range("A3:T3").ClearContents
  Application.ScreenUpdating = True
  Call GetLastRow

End Sub

Private Sub GetLastRow()

  'Step 1: Declare Your Variables.
  Dim LastRow As Long

  'Step 2: Capture the last used row number.
  LastRow = Cells(Rows.Count, 8).End(xlUp).Row

  'Step 3: Select the next row down
  Cells(LastRow, 8).Offset(1, 0).Select

 End Sub
</code>```

答:
If you want to filter multi-criteria in a single field, you will need array as below:

```<code>.AutoFilter Field:=1, Criteria1:=Array("val 2", "val 3", "val 4"), Operator:=xlFilterValues
</code>```

so filterCriteria(i) must be an Array, you can just do it as below:

```<code>filterCriteria(i) = Array("item1","item2")
.AutoFilter Field:=filterFields(i), Criteria1:=filterCriteria(i), Operator:=xlFilterValues
</code>```

Body:
I have the below code that will filter the table by the user selection.

I would like to first check range A3:T3 if they have values in and if they do i will add to my array and start filtering by that and ignore all empty cells in Range A3:T3.

If range A3:T3 is empty then filter by user selection.

I notice there is a bug where if i filter by a cell and that cell has 2 rows with data 1 will show and 1 not because there is a space in front of it i think its a ChrW is there any way to make the filter take partial match to include both versions? I know i can replace the ChrW and replace it but data will be always pasted from outlook so the occurrence will be frequent so if i can take a partial match that will probably solve a lot of the problems.

Any help would be much appreciated.

Sub advancedMultipleCriteriaFilter()

  Dim cellRng As Range, tableObject As Range, subSelection As Range
  Dim filterCriteria() As String, filterFields() As Integer
  Dim i As Integer

  Application.ScreenUpdating = False
  'Call removeSpace

  If Selection.Rows.Count > 1 Then
    MsgBox "Cannot apply filter to multiple rows within the same column. Please make another selection and try again.", vbInformation, "Selection Error!"
    Exit Sub
  End If

  i = 1
  ReDim filterCriteria(1 To Selection.Cells.Count) As String
  ReDim filterFields(1 To Selection.Cells.Count) As Integer

  Set tableObject = Selection.CurrentRegion
  For Each subSelection In Selection.Areas
    For Each cellRng In subSelection
      filterCriteria(i) = cellRng.Text
      filterFields(i) = cellRng.Column - tableObject.Cells(1, 1).Column + 1
      i = i + 1
    Next cellRng
  Next subSelection

  With tableObject
    For i = 1 To UBound(filterCriteria)
      .AutoFilter field:=filterFields(i), Criteria1:=filterCriteria(i)
    Next i
  End With

  Call GetLastRow

  Set tableObject = Nothing
  Application.ScreenUpdating = True

End Sub

Sub resetFilters()

  Dim sht As Worksheet
  Dim LastRow As Range

  Application.ScreenUpdating = False

  On Error Resume Next
  If ActiveSheet.FilterMode Then
    ActiveSheet.ShowAllData
  End If

  Range("A3:T3").ClearContents
  Application.ScreenUpdating = True
  Call GetLastRow

End Sub

Private Sub GetLastRow()

  'Step 1: Declare Your Variables.
  Dim LastRow As Long

  'Step 2: Capture the last used row number.
  LastRow = Cells(Rows.Count, 8).End(xlUp).Row

  'Step 3: Select the next row down
  Cells(LastRow, 8).Offset(1, 0).Select

 End Sub

Body:
If you want to filter multi-criteria in a single field, you will need array as below:

.AutoFilter Field:=1, Criteria1:=Array("val 2", "val 3", "val 4"), Operator:=xlFilterValues

so filterCriteria(i) must be an Array, you can just do it as below:

filterCriteria(i) = Array("item1","item2")
.AutoFilter Field:=filterFields(i), Criteria1:=filterCriteria(i), Operator:=xlFilterValues


问:
Change values of array that is a copy of argument array
I am trying to change the values inside an array that is a copy of arguments array ("$@"). Let's say I execute the script as follows: $ sh script.sh 1 2 3

This is the script:

```<code>list="$@"
echo ${list[*]}
list[1]=4
echo ${list[*]}
</code>```

Expected output:

```<code>1 2 3
1 4 3
</code>```

What I actually get:

```<code>1 2 3
1 2 3 4
</code>```

Any idea what causes this behavior and how can I fix it?

答:
Just found this answer. Command line arguments array is not quite a normal array and has to be converted to an actual array first as follows:</p>

```<code>list=("$@")
</code>```

Body:
I am trying to change the values inside an array that is a copy of arguments array ("$@"). Let's say I execute the script as follows: $ sh script.sh 1 2 3

This is the script:

list="$@"
echo ${list[*]}
list[1]=4
echo ${list[*]}

Expected output:

1 2 3
1 4 3

What I actually get:

1 2 3
1 2 3 4

Any idea what causes this behavior and how can I fix it?

Body:
Just found this answer. Command line arguments array is not quite a normal array and has to be converted to an actual array first as follows:

list=("$@")


问:
Swift Binary Search Tree Search
I am trying to implement a BST that stores a list of words. I know that my tree structure is correct because when I try to traverse and print in order, the list prints alphabetically. However, my search function for looking for an element in a tree returns false each time.

```<code>func search(searchValue: String) -> Bool? {
    if searchValue == value as! String{
        return true
    }

    if searchValue < value as! String {
        return left?.search(searchValue: searchValue)
    }
    if searchValue > value as! String{
        return right?.search(searchValue: searchValue)
    }

    return false

}
</code>```

The function is called in this loop. Every word not in the BST should be appended to an array misspelled. Currently no words are appended to the array. Input array is an array of all the words to be checked against the BST.

```<code> for item in arrayInput
        {
            let target = item.lowercased()//reversed
            let inTree = tree.search(searchValue: target)
            if inTree == false
            {
                misspelled.append(item)
            }
        }
</code>```

More BST class for context:

```<code>  public class BinarySearchTree<T: Comparable> {
        fileprivate(set) public var value: T
        fileprivate(set) public var parent: BinarySearchTree?
        fileprivate(set) public var left: BinarySearchTree?
        fileprivate(set) public var right: BinarySearchTree?

        public init(value: T) {
            self.value = value
        }

        public convenience init(array: [T]) {
            precondition(array.count > 0)
            self.init(value: array.first!)
            for v in array.dropFirst() {
                insert(value: v)
            }
        }

        }
     public func insert(value: T) {
            if value < self.value {
                if let left = left {
                    left.insert(value: value)
                } else {
                    left = BinarySearchTree(value: value)
                    left?.parent = self
                }
            } else {
                if let right = right {
                    right.insert(value: value)
                } else {
                    right = BinarySearchTree(value: value)
                    right?.parent = self
                }
            }
        }
</code>```

答:
I've made some improvements to your code, take a look:</p>

```<code>public class BinarySearchTree<T: Comparable> {
    fileprivate(set) public var value: T
    fileprivate(set) public var parent: BinarySearchTree?
    fileprivate(set) public var left: BinarySearchTree?
    fileprivate(set) public var right: BinarySearchTree?

    public init(value: T) {
        self.value = value
    }

    public convenience init(array: [T]) {
        precondition(array.count > 0)
        self.init(value: array.first!)
        for v in array.dropFirst() {
            insert(value: v)
        }
    }

    // Refactored out common code to reduce duplicaiton
    public func insert(value: T) {
        let nodeToModify = value < self.value ? left : right

        if let nodeToModify = nodeToModify {
            nodeToModify.insert(value: value)
        }
        else {
            let subtree = BinarySearchTree(value: value)
            subtree.parent = self
            self.left = subtree
        }
    }

    // Why constrain searching to just Strings? Keep it generic to all T: Comparable
    func search(for searchValue: T) -> Bool {
        if searchValue == value { return true }

        if searchValue < value {
            return left?.search(for: searchValue) ?? false
        }
        if searchValue > value {
            return right?.search(for: searchValue) ?? false
        }

        return false
    }
}

// Move the `search` function outside of the class, and into an extension
// with the constaint that `T == String`
extension BinarySearchTree where T == String {
    func search(for searchValue: String) -> Bool {
        if searchValue == value { return true }

        if searchValue < value {
            return left?.search(for: searchValue) ?? false
        }
        if searchValue > value {
            return right?.search(for: searchValue) ?? false
        }

        return false
    }
}
</code>```

Title: Swift Binary Search Tree Search

Body:
I am trying to implement a BST that stores a list of words. I know that my tree structure is correct because when I try to traverse and print in order, the list prints alphabetically. However, my search function for looking for an element in a tree returns false each time.

func search(searchValue: String) -> Bool? {
    if searchValue == value as! String{
        return true
    }

    if searchValue < value as! String {
        return left?.search(searchValue: searchValue)
    }
    if searchValue > value as! String{
        return right?.search(searchValue: searchValue)
    }

    return false

}

The function is called in this loop. Every word not in the BST should be appended to an array misspelled. Currently no words are appended to the array. Input array is an array of all the words to be checked against the BST.

 for item in arrayInput
        {
            let target = item.lowercased()//reversed
            let inTree = tree.search(searchValue: target)
            if inTree == false
            {
                misspelled.append(item)
            }
        }

More BST class for context:

  public class BinarySearchTree<T: Comparable> {
        fileprivate(set) public var value: T
        fileprivate(set) public var parent: BinarySearchTree?
        fileprivate(set) public var left: BinarySearchTree?
        fileprivate(set) public var right: BinarySearchTree?

        public init(value: T) {
            self.value = value
        }

        public convenience init(array: [T]) {
            precondition(array.count > 0)
            self.init(value: array.first!)
            for v in array.dropFirst() {
                insert(value: v)
            }
        }

        }
     public func insert(value: T) {
            if value < self.value {
                if let left = left {
                    left.insert(value: value)
                } else {
                    left = BinarySearchTree(value: value)
                    left?.parent = self
                }
            } else {
                if let right = right {
                    right.insert(value: value)
                } else {
                    right = BinarySearchTree(value: value)
                    right?.parent = self
                }
            }
        }

Body:
I've made some improvements to your code, take a look:

public class BinarySearchTree<T: Comparable> {
    fileprivate(set) public var value: T
    fileprivate(set) public var parent: BinarySearchTree?
    fileprivate(set) public var left: BinarySearchTree?
    fileprivate(set) public var right: BinarySearchTree?

    public init(value: T) {
        self.value = value
    }

    public convenience init(array: [T]) {
        precondition(array.count > 0)
        self.init(value: array.first!)
        for v in array.dropFirst() {
            insert(value: v)
        }
    }

    // Refactored out common code to reduce duplicaiton
    public func insert(value: T) {
        let nodeToModify = value < self.value ? left : right

        if let nodeToModify = nodeToModify {
            nodeToModify.insert(value: value)
        }
        else {
            let subtree = BinarySearchTree(value: value)
            subtree.parent = self
            self.left = subtree
        }
    }

    // Why constrain searching to just Strings? Keep it generic to all T: Comparable
    func search(for searchValue: T) -> Bool {
        if searchValue == value { return true }

        if searchValue < value {
            return left?.search(for: searchValue) ?? false
        }
        if searchValue > value {
            return right?.search(for: searchValue) ?? false
        }

        return false
    }
}

// Move the `search` function outside of the class, and into an extension
// with the constaint that `T == String`
extension BinarySearchTree where T == String {
    func search(for searchValue: String) -> Bool {
        if searchValue == value { return true }

        if searchValue < value {
            return left?.search(for: searchValue) ?? false
        }
        if searchValue > value {
            return right?.search(for: searchValue) ?? false
        }

        return false
    }
}


问:
Qt: QIcon disappears when clicked; QIcon::Mode not being respected
I have a png format image of a play button in  which I have stored as an embedded resource in my application.

```<code><!DOCTYPE RCC><RCC version="1.0">
  <qresource prefix="icon">
    <file>play.png</file>
  </qresource>
</RCC>
</code>```

I have created a QIcon with the same source image set for both Normal and Active modes

```<code>QIcon play;
play.addFile(":icon/play.png", QSize(), QIcon::Normal);
play.addFile(":icon/play.png", QSize(), QIcon::Active);
</code>```

From what I understand, this should display the icon when unclicked (Normal mode), and continue doing so when clicked (Active mode)

QIcon::Normal: Display the pixmap when the user is not interacting with the icon, but the functionality represented by the icon is available.

QIcon::Active: Display the pixmap when the functionality represented by the icon is available and the user is interacting with the icon, for example, moving the mouse over it or clicking it.

However, when I click on it it disappears (a blank box being displayed instead).

Here is the icon unclicked

Here is the icon clicked

Minimal working example:

I have created a minimal example replicating the behaviour I see

```<code>#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>

void initIcons()
{
    Q_INIT_RESOURCE(view);
}

int main(int argc, char** argv)
{
    QApplication* app = new QApplication(argc, argv);
    QMainWindow*  window = new QMainWindow();

    QMenuBar* menu = new QMenuBar();
    window->setMenuBar(menu);

    QIcon play;
    play.addFile(":icon/play.png", QSize(), QIcon::Normal);
    play.addFile(":icon/play.png", QSize(), QIcon::Active);

    QAction* action = new QAction(play, "", nullptr);
    menu->addAction(action);

    window->show();
    return app->exec();
}
</code>```

Update:

I have also tried every combination of Mode and State with no change in behaviour:

```<code>play.addFile(":icon/play.png", QSize(), QIcon::Normal,   QIcon::On);
play.addFile(":icon/play.png", QSize(), QIcon::Normal,   QIcon::Off);
play.addFile(":icon/play.png", QSize(), QIcon::Selected, QIcon::On);
play.addFile(":icon/play.png", QSize(), QIcon::Selected, QIcon::Off);
play.addFile(":icon/play.png", QSize(), QIcon::Active,   QIcon::On);
play.addFile(":icon/play.png", QSize(), QIcon::Active,   QIcon::Off);
</code>```

I also tried addPixmap

```<code>QIcon play;
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Normal,   QIcon::On);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Normal,   QIcon::Off);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Selected, QIcon::On);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Selected, QIcon::Off);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Active,   QIcon::On);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Active,   QIcon::Off);
</code>```

None of these alter the behaviour at all unfortunately.

答:
maybe you can add icon in SLOT:</p>

```<code>connect({your_action_name},&QAction::toggled,[=](){
your_action_name.setIcon("icon_path_file.ico");
})
</code>```

Body:
I have a png format image of a play button in  which I have stored as an embedded resource in my application.

<!DOCTYPE RCC><RCC version="1.0">
  <qresource prefix="icon">
    <file>play.png</file>
  </qresource>
</RCC>

I have created a QIcon with the same source image set for both Normal and Active modes

QIcon play;
play.addFile(":icon/play.png", QSize(), QIcon::Normal);
play.addFile(":icon/play.png", QSize(), QIcon::Active);

From what I understand, this should display the icon when unclicked (Normal mode), and continue doing so when clicked (Active mode)

QIcon::Normal: Display the pixmap when the user is not interacting with the icon, but the functionality represented by the icon is available.

QIcon::Active: Display the pixmap when the functionality represented by the icon is available and the user is interacting with the icon, for example, moving the mouse over it or clicking it.

However, when I click on it it disappears (a blank box being displayed instead).

Here is the icon unclicked

Here is the icon clicked

Minimal working example:

I have created a minimal example replicating the behaviour I see

#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>

void initIcons()
{
    Q_INIT_RESOURCE(view);
}

int main(int argc, char** argv)
{
    QApplication* app = new QApplication(argc, argv);
    QMainWindow*  window = new QMainWindow();

    QMenuBar* menu = new QMenuBar();
    window->setMenuBar(menu);

    QIcon play;
    play.addFile(":icon/play.png", QSize(), QIcon::Normal);
    play.addFile(":icon/play.png", QSize(), QIcon::Active);

    QAction* action = new QAction(play, "", nullptr);
    menu->addAction(action);

    window->show();
    return app->exec();
}

Update:

I have also tried every combination of Mode and State with no change in behaviour:

play.addFile(":icon/play.png", QSize(), QIcon::Normal,   QIcon::On);
play.addFile(":icon/play.png", QSize(), QIcon::Normal,   QIcon::Off);
play.addFile(":icon/play.png", QSize(), QIcon::Selected, QIcon::On);
play.addFile(":icon/play.png", QSize(), QIcon::Selected, QIcon::Off);
play.addFile(":icon/play.png", QSize(), QIcon::Active,   QIcon::On);
play.addFile(":icon/play.png", QSize(), QIcon::Active,   QIcon::Off);

I also tried addPixmap

QIcon play;
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Normal,   QIcon::On);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Normal,   QIcon::Off);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Selected, QIcon::On);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Selected, QIcon::Off);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Active,   QIcon::On);
play.addPixmap(QPixmap(":icon/play.png"), QIcon::Active,   QIcon::Off);

None of these alter the behaviour at all unfortunately.

Body:
maybe you can add icon in SLOT:

connect({your_action_name},&QAction::toggled,[=](){
your_action_name.setIcon("icon_path_file.ico");
})


问:
How can I set topic when I use ConcurrentKafkaListenerContainerFactory?
Is there any way I can set the topic when I use concurrentKafkaListenerContainerFactory? I don't want to any annotation at all. </p>

答:
If you are not going to use @KafkaListener, you don't need to worry about that factory. The target ConcurrentKafkaListenerContainer is enough for you.

There you can find ContainerProperties for configuration.


问:
C opening file from console
I have a simple code that opens a file from hdd in read mode, but the path of the file is already given in the code.I want the user to manually provide the file name,path and file open type through console. What do I have to do for that? </p>

```<code>#include<stdio.h>

int main() {
   FILE *fp;
   fp = fopen("D:\\samplefile.txt","r");
   if(fp != NULL) {
      printf("File has been opened");
      fclose(fp);
   }
   else printf("File not found");
   return 0;
}
</code>```

答:
```<code>// Use of function scanf is done here as an simple use. There are other ways also to get input from user
#include<stdio.h>
int main()
{
  FILE *fp;
  char filePath[100];
  printf("Enter Path name: ");
  scanf("%s", filePath);
  printf("value is %s",filePath);
   fp = fopen(filePath,"r");
    if(fp != NULL) {
      printf("File has been opened");
      fclose(fp);
   }
   else printf("File not found");
   return 0;
}
</code>```

Title: C opening file from console

Body:
I have a simple code that opens a file from hdd in read mode, but the path of the file is already given in the code.I want the user to manually provide the file name,path and file open type through console. What do I have to do for that?

#include<stdio.h>

int main() {
   FILE *fp;
   fp = fopen("D:\\samplefile.txt","r");
   if(fp != NULL) {
      printf("File has been opened");
      fclose(fp);
   }
   else printf("File not found");
   return 0;
}


问:
User inputs multiple values and names and data is stored in text file
Currently having some problems, I want the user to input data such as names and numbers and I would like all the information printed into a text file and also be able to read the info from said file when needed. Not sure what to do to make this happen the way I want,</p>

```<code>#include <iostream>
#include <windows.h>
#include <string>
#include <fstream>

class Data{
    public:
    std::string name;
    int points;

    void Input();
    void Writetofile();
};

void Data::Input(){
    std::cout << "Enter a team \n";
    std::cin >> name;
    std::cout << "Enter  average points \n";
    std::cin >> points;
    std::cout << "Enter another team \n";
    std::cin >> name;
    std::cout << "Enter  average points \n";
    std::cin >> points;
    std::cout << std::endl;
    Writetofile();
}

void Data::Writetofile(){
    std::ofstream outtext ("data.txt");
    outtext <<  name  << std::cout << "    \n" << points;
    outtext.close();
}

int main(){
    Data db;
    db.Input();

}
</code>```

答:
Your first problem with your code is that you are overwriting the name and points of the first team when you read in for the second team. You should consider using four different variables total for the two teams.

Your second problem is that you are trying to print points to cout when it should really be printed to outtext.

Body:
Currently having some problems, I want the user to input data such as names and numbers and I would like all the information printed into a text file and also be able to read the info from said file when needed. Not sure what to do to make this happen the way I want,

#include <iostream>
#include <windows.h>
#include <string>
#include <fstream>

class Data{
    public:
    std::string name;
    int points;

    void Input();
    void Writetofile();
};

void Data::Input(){
    std::cout << "Enter a team \n";
    std::cin >> name;
    std::cout << "Enter  average points \n";
    std::cin >> points;
    std::cout << "Enter another team \n";
    std::cin >> name;
    std::cout << "Enter  average points \n";
    std::cin >> points;
    std::cout << std::endl;
    Writetofile();
}

void Data::Writetofile(){
    std::ofstream outtext ("data.txt");
    outtext <<  name  << std::cout << "    \n" << points;
    outtext.close();
}

int main(){
    Data db;
    db.Input();

}


答:
list="$@" sets list to a plain variable, not an array. Use list=("$@") to store it as an array instead. BTW, you should generally use "${list[@]}" to get the elements of an array, instead of ${list[*]} to avoid problems with whitespace in elements, wildcards getting expanded to lists of matching files, etc.

In general, this is the proper way to copy an array:

```<code>copyarray=("${oldarray[@]}")
</code>```

Title: Change values of array that is a copy of argument array

Body:
list="$@" sets list to a plain variable, not an array. Use list=("$@") to store it as an array instead. BTW, you should generally use "${list[@]}" to get the elements of an array, instead of ${list[*]} to avoid problems with whitespace in elements, wildcards getting expanded to lists of matching files, etc.

In general, this is the proper way to copy an array:

copyarray=("${oldarray[@]}")


问:
C#: Is it necessary to dispose of a graphics element inside a custom control?
I've created a custom control, overridden it's paint event. When I try to dispose of the graphics I create they just disappear from the screen. Don't I need to use dispose in custom controls?

EDIT: I've included a code snippet. Why can't i dispose the dc graphics object, created from the PaintEventArgs? Do i need to dispose it?

```<code>class canvas : Control
    {

        PointF mouseDown;

        float newX;
        float newY;
        float zoomFactor = 1F;

        Graphics _dc;

        public canvas()
        {
            this.DoubleBuffered = true;
            mouseDown = new PointF(0F, 0F);
            this.Paint += new PaintEventHandler(ctrl_Paint);
        }

        private void ctrl_Paint(object sender, PaintEventArgs e)
        {

            Graphics dc = e.Graphics;
            _dc = dc;

            dc.SmoothingMode = SmoothingMode.AntiAlias;

            Color gridColor = Color.FromArgb(230, 230, 230);
            Pen gridPen = new Pen(gridColor, 1);

            float offX = (float)((Math.Sqrt(Math.Pow(newX, 2)) % (30 * zoomFactor)));
            float offY = (float)((Math.Sqrt(Math.Pow(newY, 2)) % (30 * zoomFactor)));

            for (float y = offY; y < this.Height; y = y + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, 0, y, this.Width, y);
            }
            for (float x = offX; x < this.Width; x = x + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, x, 0, x, this.Height);
            }

            dc.TranslateTransform(newX, newY);
            dc.ScaleTransform(zoomFactor, zoomFactor, MatrixOrder.Prepend);

            float XPosition = 10;
            float YPosition = 10;
            float CornerRadius = 5;
            float Width = 50;
            float Height = 50;

            Color BoxColor = Color.FromArgb(0, 0, 0);
            Pen BoxPen = new Pen(BoxColor, 2);

            GraphicsPath Path = new GraphicsPath();

            Path.AddLine(XPosition + CornerRadius, YPosition, XPosition + Width - (CornerRadius * 2), YPosition);
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition, CornerRadius * 2, CornerRadius * 2, 270, 90);
            Path.AddLine(XPosition + Width, YPosition + CornerRadius, XPosition + Width, YPosition + Height - (CornerRadius * 2));
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 0, 90);
            Path.AddLine(XPosition + Width - (CornerRadius * 2), YPosition + Height, XPosition + CornerRadius, YPosition + Height);
            Path.AddArc(XPosition, YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 90, 90);
            Path.AddLine(XPosition, YPosition + Height - (CornerRadius * 2), XPosition, YPosition + CornerRadius);
            Path.AddArc(XPosition, YPosition, CornerRadius * 2, CornerRadius * 2, 180, 90);

            Path.CloseFigure();

            dc.DrawPath(BoxPen, Path);

            LinearGradientBrush lgb = new LinearGradientBrush(new PointF(XPosition + (Width / 2), YPosition), new PointF(XPosition + (Width / 2), YPosition + Height), Color.RosyBrown, Color.Red);

            dc.FillPath(lgb, Path);

        }
}
</code>```

答:
If you did not create the graphics object you should not dispose it, so if you function signature is protected override void OnPaint(PaintEventArgs e) you would NOT dispose e.Graphics.

However if you create a graphics object in the OnPaint handler you will need to dispose it.

General rule of thumb (and it is a rule of thumb not a law) if you did not get your object from a Graphics.FromXxxxx() you do not need to call Dispose.

EDIT to reflect code you have posted

You do not need to dispose of the Grapics object because it was passed to you as a argument, however you are not actually overriding the paint event for your controll. This is the correct way to do it.

```<code>class canvas : Control
    {

        PointF mouseDown;

        float newX;
        float newY;
        float zoomFactor = 1F;

        public canvas()
        {
            this.DoubleBuffered = true;
            mouseDown = new PointF(0F, 0F);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics dc = e.Graphics;

            dc.SmoothingMode = SmoothingMode.AntiAlias;

            Color gridColor = Color.FromArgb(230, 230, 230);
            Pen gridPen = new Pen(gridColor, 1);

            float offX = (float)((Math.Sqrt(Math.Pow(newX, 2)) % (30 * zoomFactor)));
            float offY = (float)((Math.Sqrt(Math.Pow(newY, 2)) % (30 * zoomFactor)));

            for (float y = offY; y < this.Height; y = y + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, 0, y, this.Width, y);
            }
            for (float x = offX; x < this.Width; x = x + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, x, 0, x, this.Height);
            }

            dc.TranslateTransform(newX, newY);
            dc.ScaleTransform(zoomFactor, zoomFactor, MatrixOrder.Prepend);

            float XPosition = 10;
            float YPosition = 10;
            float CornerRadius = 5;
            float Width = 50;
            float Height = 50;

            Color BoxColor = Color.FromArgb(0, 0, 0);
            Pen BoxPen = new Pen(BoxColor, 2);

            GraphicsPath Path = new GraphicsPath();

            Path.AddLine(XPosition + CornerRadius, YPosition, XPosition + Width - (CornerRadius * 2), YPosition);
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition, CornerRadius * 2, CornerRadius * 2, 270, 90);
            Path.AddLine(XPosition + Width, YPosition + CornerRadius, XPosition + Width, YPosition + Height - (CornerRadius * 2));
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 0, 90);
            Path.AddLine(XPosition + Width - (CornerRadius * 2), YPosition + Height, XPosition + CornerRadius, YPosition + Height);
            Path.AddArc(XPosition, YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 90, 90);
            Path.AddLine(XPosition, YPosition + Height - (CornerRadius * 2), XPosition, YPosition + CornerRadius);
            Path.AddArc(XPosition, YPosition, CornerRadius * 2, CornerRadius * 2, 180, 90);

            Path.CloseFigure();

            dc.DrawPath(BoxPen, Path);

            LinearGradientBrush lgb = new LinearGradientBrush(new PointF(XPosition + (Width / 2), YPosition), new PointF(XPosition + (Width / 2), YPosition + Height), Color.RosyBrown, Color.Red);

            dc.FillPath(lgb, Path);

        }
}
</code>```

I also removed _dc as you should not be editing the Graphics object when you are not inside the OnPaint function.

Body:
I've created a custom control, overridden it's paint event. When I try to dispose of the graphics I create they just disappear from the screen. Don't I need to use dispose in custom controls?

EDIT: I've included a code snippet. Why can't i dispose the dc graphics object, created from the PaintEventArgs? Do i need to dispose it?

class canvas : Control
    {

        PointF mouseDown;

        float newX;
        float newY;
        float zoomFactor = 1F;

        Graphics _dc;

        public canvas()
        {
            this.DoubleBuffered = true;
            mouseDown = new PointF(0F, 0F);
            this.Paint += new PaintEventHandler(ctrl_Paint);
        }

        private void ctrl_Paint(object sender, PaintEventArgs e)
        {

            Graphics dc = e.Graphics;
            _dc = dc;

            dc.SmoothingMode = SmoothingMode.AntiAlias;

            Color gridColor = Color.FromArgb(230, 230, 230);
            Pen gridPen = new Pen(gridColor, 1);

            float offX = (float)((Math.Sqrt(Math.Pow(newX, 2)) % (30 * zoomFactor)));
            float offY = (float)((Math.Sqrt(Math.Pow(newY, 2)) % (30 * zoomFactor)));

            for (float y = offY; y < this.Height; y = y + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, 0, y, this.Width, y);
            }
            for (float x = offX; x < this.Width; x = x + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, x, 0, x, this.Height);
            }

            dc.TranslateTransform(newX, newY);
            dc.ScaleTransform(zoomFactor, zoomFactor, MatrixOrder.Prepend);

            float XPosition = 10;
            float YPosition = 10;
            float CornerRadius = 5;
            float Width = 50;
            float Height = 50;

            Color BoxColor = Color.FromArgb(0, 0, 0);
            Pen BoxPen = new Pen(BoxColor, 2);

            GraphicsPath Path = new GraphicsPath();

            Path.AddLine(XPosition + CornerRadius, YPosition, XPosition + Width - (CornerRadius * 2), YPosition);
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition, CornerRadius * 2, CornerRadius * 2, 270, 90);
            Path.AddLine(XPosition + Width, YPosition + CornerRadius, XPosition + Width, YPosition + Height - (CornerRadius * 2));
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 0, 90);
            Path.AddLine(XPosition + Width - (CornerRadius * 2), YPosition + Height, XPosition + CornerRadius, YPosition + Height);
            Path.AddArc(XPosition, YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 90, 90);
            Path.AddLine(XPosition, YPosition + Height - (CornerRadius * 2), XPosition, YPosition + CornerRadius);
            Path.AddArc(XPosition, YPosition, CornerRadius * 2, CornerRadius * 2, 180, 90);

            Path.CloseFigure();

            dc.DrawPath(BoxPen, Path);

            LinearGradientBrush lgb = new LinearGradientBrush(new PointF(XPosition + (Width / 2), YPosition), new PointF(XPosition + (Width / 2), YPosition + Height), Color.RosyBrown, Color.Red);

            dc.FillPath(lgb, Path);

        }
}

Body:
If you did not create the graphics object you should not dispose it, so if you function signature is protected override void OnPaint(PaintEventArgs e) you would NOT dispose e.Graphics.

However if you create a graphics object in the OnPaint handler you will need to dispose it.

General rule of thumb (and it is a rule of thumb not a law) if you did not get your object from a Graphics.FromXxxxx() you do not need to call Dispose.

EDIT to reflect code you have posted

You do not need to dispose of the Grapics object because it was passed to you as a argument, however you are not actually overriding the paint event for your controll. This is the correct way to do it.

class canvas : Control
    {

        PointF mouseDown;

        float newX;
        float newY;
        float zoomFactor = 1F;

        public canvas()
        {
            this.DoubleBuffered = true;
            mouseDown = new PointF(0F, 0F);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics dc = e.Graphics;

            dc.SmoothingMode = SmoothingMode.AntiAlias;

            Color gridColor = Color.FromArgb(230, 230, 230);
            Pen gridPen = new Pen(gridColor, 1);

            float offX = (float)((Math.Sqrt(Math.Pow(newX, 2)) % (30 * zoomFactor)));
            float offY = (float)((Math.Sqrt(Math.Pow(newY, 2)) % (30 * zoomFactor)));

            for (float y = offY; y < this.Height; y = y + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, 0, y, this.Width, y);
            }
            for (float x = offX; x < this.Width; x = x + 30 * zoomFactor)
            {
                dc.DrawLine(gridPen, x, 0, x, this.Height);
            }

            dc.TranslateTransform(newX, newY);
            dc.ScaleTransform(zoomFactor, zoomFactor, MatrixOrder.Prepend);

            float XPosition = 10;
            float YPosition = 10;
            float CornerRadius = 5;
            float Width = 50;
            float Height = 50;

            Color BoxColor = Color.FromArgb(0, 0, 0);
            Pen BoxPen = new Pen(BoxColor, 2);

            GraphicsPath Path = new GraphicsPath();

            Path.AddLine(XPosition + CornerRadius, YPosition, XPosition + Width - (CornerRadius * 2), YPosition);
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition, CornerRadius * 2, CornerRadius * 2, 270, 90);
            Path.AddLine(XPosition + Width, YPosition + CornerRadius, XPosition + Width, YPosition + Height - (CornerRadius * 2));
            Path.AddArc(XPosition + Width - (CornerRadius * 2), YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 0, 90);
            Path.AddLine(XPosition + Width - (CornerRadius * 2), YPosition + Height, XPosition + CornerRadius, YPosition + Height);
            Path.AddArc(XPosition, YPosition + Height - (CornerRadius * 2), CornerRadius * 2, CornerRadius * 2, 90, 90);
            Path.AddLine(XPosition, YPosition + Height - (CornerRadius * 2), XPosition, YPosition + CornerRadius);
            Path.AddArc(XPosition, YPosition, CornerRadius * 2, CornerRadius * 2, 180, 90);

            Path.CloseFigure();

            dc.DrawPath(BoxPen, Path);

            LinearGradientBrush lgb = new LinearGradientBrush(new PointF(XPosition + (Width / 2), YPosition), new PointF(XPosition + (Width / 2), YPosition + Height), Color.RosyBrown, Color.Red);

            dc.FillPath(lgb, Path);

        }
}

I also removed _dc as you should not be editing the Graphics object when you are not inside the OnPaint function.

ContentLicense: CC BY-SA 2.5


问:
Speeding up a transfer of a file to Google Cloud VM
I am uploading a file to my Google Cloud Platform VM using scp on Linux. However, after initially uploading it at a speed of 900 kb/s it quickly falls to 20kb/s. My internet upload speed should be around 20mbps. I wanted to upload an SQLite database clocking in at 20gb, but this is unfeasible at this point.

Right now I used 54 minutes to upload a 94 MB file. It cannot be that slow?

答:
I had the same issue multiple times with GCP, the solution I use is to compress all my files, upload it to dropbox and then wget the file from there. The speeds should go back to normal.

This answer should help you ae well, though I don't know if your paticular issue is related to gcp , scp or both.

https://askubuntu.com/questions/760509/how-to-make-scp-go-faster


问:
Why is my boolean returning an integer?
I'm fairly new to the programming world and I had a school assignment to create a simple program containing an if loop.
Basically, I want my code to return true if a is greater than 18, and false if a is less than 18. I also want a to increase by one each time canTakeRoadtest returns false. When I run my code all I get is

"I am 0 years old.

I can take my road test. 0"

I'm wondering why bool canTakeRoadtest is returning an integer, and why a isn't incrementing. Any help would be appreciated and I apologize for the simple question but we all start somewhere!

My coding environment is Eclipse Neon if it makes any difference.

```<code>#include <iostream>

using namespace std;

int main() {
//Local Variables
    int a = 0;
    bool canTakeRoadtest = false;
//If Loop
    if (a >= 18) {
        canTakeRoadtest = true;
        cout << "I'm ready!\n";
    } else {
        canTakeRoadtest = false;
        cout << "I am " << a << " years old.\n";
        cout << "I can take my road test. " << canTakeRoadtest << endl;
        a++;

    }

    //return 0;

}
</code>```

答:
Behind the scenes, every variable type in C++ has a number representation.  This makes sense because at the base level of a computer, all there is is numbers.  There are two main primitive data types that are (usually) represented as something other than a number, but are really just numbers.  The first one is bool, and the second one is char.

For example, if you set

```<code>bool myBool = true;
</code>```

behind the scenes, it is really setting your variable to 1.  Similarly, if you set

```<code>myBool = false;
</code>```

it will be 0 behind the scenes.  The same rule applies for chars.  If you set

```<code>char myChar = 'a';
</code>```

it really is setting the char to 97.  Every character has a number representation, and you can see these if you look at this table.

So, as to why cout is displaying the number representation of a bool rather than in "English", this is simply because whoever coded iostream decided that when you give it a bool it displays the number representation instead of the "English" representation.  The same does not apply for chars, however.  They will be represented as a character by iostream.

To fix iostream from printing out the incorrect representation, change your code from

```<code>cout << "I can take my road test. " << canTakeRoadtest << endl;
</code>```

to

```<code>cout << "I can take my road test. false" << endl;
</code>```

You could also use boolalpha, as Lovelace42 stated.

Title: Why is my boolean returning an integer?

Body:
I'm fairly new to the programming world and I had a school assignment to create a simple program containing an if loop.
Basically, I want my code to return true if a is greater than 18, and false if a is less than 18. I also want a to increase by one each time canTakeRoadtest returns false. When I run my code all I get is

"I am 0 years old.

I can take my road test. 0"

I'm wondering why bool canTakeRoadtest is returning an integer, and why a isn't incrementing. Any help would be appreciated and I apologize for the simple question but we all start somewhere!

My coding environment is Eclipse Neon if it makes any difference.

#include <iostream>

using namespace std;

int main() {
//Local Variables
    int a = 0;
    bool canTakeRoadtest = false;
//If Loop
    if (a >= 18) {
        canTakeRoadtest = true;
        cout << "I'm ready!\n";
    } else {
        canTakeRoadtest = false;
        cout << "I am " << a << " years old.\n";
        cout << "I can take my road test. " << canTakeRoadtest << endl;
        a++;

    }

    //return 0;

}

Body:
Behind the scenes, every variable type in C++ has a number representation.  This makes sense because at the base level of a computer, all there is is numbers.  There are two main primitive data types that are (usually) represented as something other than a number, but are really just numbers.  The first one is bool, and the second one is char.

For example, if you set

bool myBool = true;

behind the scenes, it is really setting your variable to 1.  Similarly, if you set

myBool = false;

it will be 0 behind the scenes.  The same rule applies for chars.  If you set

char myChar = 'a';

it really is setting the char to 97.  Every character has a number representation, and you can see these if you look at this table.

So, as to why cout is displaying the number representation of a bool rather than in "English", this is simply because whoever coded iostream decided that when you give it a bool it displays the number representation instead of the "English" representation.  The same does not apply for chars, however.  They will be represented as a character by iostream.

To fix iostream from printing out the incorrect representation, change your code from

cout << "I can take my road test. " << canTakeRoadtest << endl;

to

cout << "I can take my road test. false" << endl;

You could also use boolalpha, as Lovelace42 stated.


问:
What is the folder add in rxjs 5 for?
When looking through the rxjs directory structure, there seems to be two copies of the observable and operator folders - one inside the add folder as well as outside add.

Can someone explain why those two copies exist?

答:
The two sets of directories serve slightly different purposes. The actual source for the instance and class operators are stored in the operator and observable folders that exist outside the add folder. So, for eg, when you use stream$.map, the javascript code for that map operator will exist in the non-add operator folder.

By default, RxJS comes with a ton of instance and class operators to do a whole bunch of things. Most users of the library, however, will only use a fraction of those operators. Thus, through using the right import, RxJS allows for you to create your Observable class without any operators at all, and then add only those operators that you want to use to the Observable type.

That second use case is the reason for the add folder.

So, for eg, you can:

```<code>// get the basic Observable type with no operators added at all
import {Observable} from 'rxjs/Observable';

// add the map instance operator so you can do observableInstance.map
import 'rxjs/add/operator/map';

// add the Observable.of class operator so you can do Observable.of
import 'rxjs/add/observable/of';
</code>```

If you look at the source code for anything in that add folder, you see it delegates most of the work to the non-add versions - it just patches the base Observable type to add the operator in question.

All the credit to @Eye on this:

Why do we bother to split the code out this way? It's done done primarily for client side code's efficiency, specifically to reduce the size of the code that must be sent from the server to the browser. So, instead of importing the entire library with tons of code you will not use, you just import the code observables/observers as well as operators that you need. When doing so the client side bundle size will drastically reduce.

Title: What is the folder add in rxjs 5 for?

Body:
The two sets of directories serve slightly different purposes. The actual source for the instance and class operators are stored in the operator and observable folders that exist outside the add folder. So, for eg, when you use stream$.map, the javascript code for that map operator will exist in the non-add operator folder.

By default, RxJS comes with a ton of instance and class operators to do a whole bunch of things. Most users of the library, however, will only use a fraction of those operators. Thus, through using the right import, RxJS allows for you to create your Observable class without any operators at all, and then add only those operators that you want to use to the Observable type.

That second use case is the reason for the add folder.

So, for eg, you can:

// get the basic Observable type with no operators added at all
import {Observable} from 'rxjs/Observable';

// add the map instance operator so you can do observableInstance.map
import 'rxjs/add/operator/map';

// add the Observable.of class operator so you can do Observable.of
import 'rxjs/add/observable/of';

If you look at the source code for anything in that add folder, you see it delegates most of the work to the non-add versions - it just patches the base Observable type to add the operator in question.

All the credit to @Eye on this:

Why do we bother to split the code out this way? It's done done primarily for client side code's efficiency, specifically to reduce the size of the code that must be sent from the server to the browser. So, instead of importing the entire library with tons of code you will not use, you just import the code observables/observers as well as operators that you need. When doing so the client side bundle size will drastically reduce.


问:
PHP: Is it better to concatenate on 1 line or multiple lines? Or is there a difference?
Is there a difference or is one better than the other of the following:

```<code>$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';
</code>```

Or

```<code>$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';
</code>```

Is there a speed difference or is there a reason why you'd pick one over the other?

答:
The fastest way to get a large amount of data into a single string, is output buffering to capture echo'd output.

```<code>ob_start();
/* many echos. For example, in a loop */
$outString = ob_get_contents(); // get the complete string
ob_end_clean();
</code>```

In general, it's unlikely to make a significant difference to the speed of your program, so make it look obvious what you are doing, since you have to come back to fix/update it later anyhow. Readability is king.

OwnerDisplayName: Darryl Hein

Body:
Is there a difference or is one better than the other of the following:

$var = '';
...
$var .= 'blah blah';
$var .= $var2;
$var .= 'blah blah';

Or

$var = '';
...
$var .= 'blah blah' . $var2 . 'blah blah';

Is there a speed difference or is there a reason why you'd pick one over the other?

LastEditorDisplayName: Paul Dixon

Body:
The fastest way to get a large amount of data into a single string, is output buffering to capture echo'd output.

ob_start();
/* many echos. For example, in a loop */
$outString = ob_get_contents(); // get the complete string
ob_end_clean();

In general, it's unlikely to make a significant difference to the speed of your program, so make it look obvious what you are doing, since you have to come back to fix/update it later anyhow. Readability is king.

OwnerDisplayName: Topbit


问:
2 contentEditable containers inside each other; possible bug?

hi

If you try to edit the inner contentEditable div, which is practically when you click on it, you'll get stuck to it and can't insert anything outside it unless you remove the child contentEditable by backspace. Clicking outside the inner div doesn't help even if the outer div is bigger. This happens on FF & Webkit.

Is this a bug or is it the way it's used to work? Any solution to change this behavior? e.g. when you click outside the inner div, you start to edit the outer one.

Cheers

Parsa

答:
I got the same here,

```<code><div contenteditable="true"> father
    <div contenteditable="false"> child </div>
</div>
</code>```

If I select the child div I am able to delete the text child but not edit it.
The text father I'm able to delete and edit.

I think the logic is correct and make sense. If you change the child div to true then you can delete and edit the tag.

the problem is: you can not see the div tag father and child when the content was deleted. then you only suppose the first one is father div and the second is child.

Good post!

Body:
I got the same here,

<div contenteditable="true"> father
    <div contenteditable="false"> child </div>
</div>

If I select the child div I am able to delete the text child but not edit it.
The text father I'm able to delete and edit.

I think the logic is correct and make sense. If you change the child div to true then you can delete and edit the tag.

the problem is: you can not see the div tag father and child when the content was deleted. then you only suppose the first one is father div and the second is child.

Good post!


问:
ASP.NET Core - 2 @model binding
I have problem with binding 2 models in 1 view. Here is my view code:

```<code>@model IEnumerable<PEMCOLoan.DAL.Entities.Models.Employee>
@model PEMCOLoan.DAL.Entities.Models.Employee
</code>```

The IEnumerable uses to generate all employees into tables and the other one will be used to add/edit/delete... I already have functionalities on those operator how ever when viewing data I got error.

Is there anyway that I could bind 2 the same model with different function at the same time in 1 view?

答:
Is there anyway that I could bind 2 the same model with different
  function at the same time in 1 view?

No.

Create one view-model that has both as properties.

```<code>public class MyViewModel {
    public IEnumerable<PEMCOLoan.DAL.Entities.Models.Employee> Employees { get; set;}
    public PEMCOLoan.DAL.Entities.Models.Employee Employee { get; set;}
}
</code>```

that way when populated and passed to the view you can access them both via the wrapping model.

```<code>@model MyViewModel

@foreach(var e in Model.Employees) {
  <p>@e.Property</p>
}

<p>@Model.Employee.Property</p>
</code>```

Title: ASP.NET Core - 2 @model binding

Body:
I have problem with binding 2 models in 1 view. Here is my view code:

@model IEnumerable<PEMCOLoan.DAL.Entities.Models.Employee>
@model PEMCOLoan.DAL.Entities.Models.Employee

The IEnumerable uses to generate all employees into tables and the other one will be used to add/edit/delete... I already have functionalities on those operator how ever when viewing data I got error.

Is there anyway that I could bind 2 the same model with different function at the same time in 1 view?

Body:
Is there anyway that I could bind 2 the same model with different
  function at the same time in 1 view?

No.

Create one view-model that has both as properties.

public class MyViewModel {
    public IEnumerable<PEMCOLoan.DAL.Entities.Models.Employee> Employees { get; set;}
    public PEMCOLoan.DAL.Entities.Models.Employee Employee { get; set;}
}

that way when populated and passed to the view you can access them both via the wrapping model.

@model MyViewModel

@foreach(var e in Model.Employees) {
  <p>@e.Property</p>
}

<p>@Model.Employee.Property</p>


问:
Error:(1772) No resource found that matches the given name: attr 'padding'
I am getting the error in the title. Here is the error log:

答:
Always qualify system resources with android , you had padding WHICH is not recognized as being apart of the android schema definition in XML, therefore resource qualification such as height, width, id, padding  and margin requires the android:resource-name qualification.

Happy Coding:)


问:
AngularJS - (using Ionic framework) - data binding on header title not working
I'm using an AngularJS-based library called "Ionic" (http://ionicframework.com/).

This seems simple, but it isn't working for me.

In one of my views, I have the following

```<code><view title="content.title">
  <content has-header="true" padding="true">
    <p>{{ content.description }}</p>
    <p><a class="button button-small icon ion-arrow-left-b" href="#/tab/pets"> Back to home</a></p>
  </content>
</view>
</code>```

In the controller for the above view, I have

```<code>angular.module('App', []).controller('DetailCtrl', function($scope, $stateParams, MyService) {

  MyService.get($stateParams.petId).then(function(content) {
    $scope.content = content[0];
    console.log($scope.content.title); // this works!
  });
});
</code>```

The data for this view is loaded via a simple HTTP GET service (called MyService).

The problem is that when I view this page,

```<code><view title="content.title">
</code>```

Doesn't display the title. It's just a blank. According to the Ionic documentation (http://ionicframework.com/docs/angularjs/controllers/view-state/), I think I'm doing the right thing.

It's strange that {{content.description}} part works, but content.title doesn't work?

Also, is it because I'm loading the content dynamically (via HTTP GET)?

答:
I m using ionic v1.3.3 with side menus based template. I tried all solutions given above but no luck.
I used the delegate from $ionicNavBarDelegate:
http://ionicframework.com/docs/v1/api/service/$ionicNavBarDelegate/

I created a function inside my angular controller to set the title :

```<code>angular.module('app.controllers').controller('contributionsCtrl',  contributionsCtrl);

function contributionsCtrl($scope, $ionicNavBarDelegate) {

    vm.setNavTitle = setNavTitle;

    function setNavTitle() {
        var title = "<span class='smc_color'> <i class='icon ion-images'></i> Your Title </span>"
        $ionicNavBarDelegate.title(title);
    }
}
</code>```

Then inside my html just called the function vm.setNavTitle

```<code> <ion-view overflow-scroll=true ng-init="vm.setNavTitle()">
    <ion-content></ion-content>
 </ion-view>
</code>```

Body:
I'm using an AngularJS-based library called "Ionic" (http://ionicframework.com/).

This seems simple, but it isn't working for me.

In one of my views, I have the following

<view title="content.title">
  <content has-header="true" padding="true">

{{ content.description }}

 Back to home

  </content>
</view>

In the controller for the above view, I have

angular.module('App', []).controller('DetailCtrl', function($scope, $stateParams, MyService) {

  MyService.get($stateParams.petId).then(function(content) {
    $scope.content = content[0];
    console.log($scope.content.title); // this works!
  });
});

The data for this view is loaded via a simple HTTP GET service (called MyService).

The problem is that when I view this page,

<view title="content.title">

Doesn't display the title. It's just a blank. According to the Ionic documentation (http://ionicframework.com/docs/angularjs/controllers/view-state/), I think I'm doing the right thing.

It's strange that {{content.description}} part works, but content.title doesn't work?

Also, is it because I'm loading the content dynamically (via HTTP GET)?

Body:
I m using ionic v1.3.3 with side menus based template. I tried all solutions given above but no luck.
I used the delegate from $ionicNavBarDelegate:
http://ionicframework.com/docs/v1/api/service/$ionicNavBarDelegate/

I created a function inside my angular controller to set the title :

angular.module('app.controllers').controller('contributionsCtrl',  contributionsCtrl);

function contributionsCtrl($scope, $ionicNavBarDelegate) {

    vm.setNavTitle = setNavTitle;

    function setNavTitle() {
        var title = "<span class='smc_color'> <i class='icon ion-images'></i> Your Title </span>"
        $ionicNavBarDelegate.title(title);
    }
}

Then inside my html just called the function vm.setNavTitle

 <ion-view overflow-scroll=true ng-init="vm.setNavTitle()">
    <ion-content></ion-content>
 </ion-view>


问:
How to precisely test if CSS final computed values have changed anywhere on a page?
I have a situation where I need to merge several classes manually.  They contain a huge amount of overrides within an 18,000 line CSS file.

I started making some changes to the huge CSS file and I realize that CSS loads the last case of a property so I did this all very carefully.  For the most part things worked well.  But, I did find one icon that was wrong and one text link that was the wrong font.  So I thought, is there a way that I can compare the before and after state of this work precisely.  I don't mean visually.  But instead like two full text output files of the results of the computed CSS for the entire current page so I can run a compare on them in notepad++

Sorry if this is an ignorant question as I am a self taught web novice.

答:
You can use notepad ++ to compare two files. You will need a compare plugin to be installed in notepad ++. Please follow the steps below:

Install the Compare Plugin
1. Launch Notepad++.

Click the “Plugins” menu, select “Plugin Manager” and click “Show Plugin Manager.” A list of currently available plugins populates the plugin manager screen.

Check the box next to “Compare.”

Click the “Install” button at the bottom of the screen. The Compare plugin will download and install. If an administrator authentication dialog appears, click the “Allow” button.

Using the Notepad++ Compare Plugin
1. Launch Notepad++ and open the two files you wish to run a comparison check on.

Click the “Plugins” menu, select “Compare” and click “Compare.” The plugin will run a comparison check and display the two files side by side, with any differences in the text highlighted.

Reset to the original window configuration and appearance by clicking the “Plugins” menu, selecting “Compare” and clicking “Clear Results.”

For reference click here


问:
Why is my new schema not showing in the table properites pane?
I am using SQL Server 2008 Express and Sql Server Management Studio 2008.

I am trying to associate a database table with a new schema.

I have created a new Schema by navigating to Security->Schemas in object explorer. I right clicked on the folder and created a new schema called 'People' and set the owner as db_owner. This new Schema now appears in object explorer.

I would now like to associate a table with this schema. I open the table in design view and click on the drop down list in the table Properties pane which contains the available schemas but my newly created schema is not visible.

I have tried refreshing everything throughout object explorer. Closing design view and reopening etc. but still it isn't there.

Am I doing something wrong?

Can anyone point me in the right direction please?

答:
I am not following you when you say "open the table in design mode then click on the drop down list".  I must be overlooking the list on my SQL Express.

Have you tried to change the schema via TSQL?  The command is short:

```<code>ALTER SCHEMA "target schema" TRANSFER "source schema"."table name";
GO
</code>```

Replace target and source schema with your schema names.

Body:
I am not following you when you say "open the table in design mode then click on the drop down list".  I must be overlooking the list on my SQL Express.

Have you tried to change the schema via TSQL?  The command is short:

ALTER SCHEMA "target schema" TRANSFER "source schema"."table name";
GO

Replace target and source schema with your schema names.


问:
PHP Application works fine on webhotel but not on local server (WAMP)
I am currently working a little with PHP and taking over a project that wasn't created by me. The tricky things is that on the server/webhotel the application is working like expected, however in my local test environment (WAMP 3.0.6 64bit, PHP 5.6.25, Apache 2.4.23, MySQL 5.7.14) it isn't working. The error message that is being output by PHP is :

Notice: Undefined index: ... line 110

which is directed at this snippet:

```<code>$bVal += $values[substr(utf8_decode(mb_strtolower($line)),$j,1)];.
</code>```

Thing is, I have copied all files as is from the server including all the files it rely on. I only have to make small tweaks (Change the text files the php script reads from) but it won't even work with the original ones. Is there a common issue between platforms versions for PHP, Apache etc? As far as I can tell the XHTTP request is acting normally and I feel like I shouldn't be having these issues, this may come from my inexperience with PHP though.

Code will be posted below and thank you in advance for even taking a look at it!

Code: https://pastebin.com/M6y9rfRa

答:
Change your code to this and see how it goes </p>

```<code><script>
    function doSomething()
    {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function()
        {
            if (xhttp.readyState == 4)
            {
                if (xhttp.status == 200)
                    document.getElementById("calContent").innerHTML = xhttp.responseText;
            }
        }
        xhttp.open("GET", "/num/ns.php?number=" + jQuery("#nInput").val() + "$$$" + jQuery('input[name=switcher]:checked').val(), true);
        xhttp.send();
    }
    function doSomethingElse()
    {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function()
        {
            if (xhttp.readyState == 4)
            {
                if (xhttp.status == 200)
                    document.getElementById("calContent").innerHTML = xhttp.responseText;
            }
        }
        xhttp.open("GET", "/num/ns.php?number2=" + jQuery("#nInput2").val() + "$$$" + jQuery('input[name=switcher2]:checked').val(), true);
        xhttp.send();
    }
</script>
<style>
    .calOut {
        position: relative;
        float: left;
        margin-right: 18px;
    }
</style>
<style media="print">
    #calContent { display: none; }
</style>
<div id="calContent" style="margin-top: 0px; margin-bottom: 50px; color:black;" class="contact_form" >

<?php
    $numname = "number";
    if (isset($_GET["number"])) {
        echo "<div><input type='text' id='nInput' name='nInput' value='" . explode("$$$", $_GET["number"])[0] . "' />";
        echo "<br /><input type='radio' name='switcher' value='female' "; if (explode("$$$", $_GET["number"])[1] == "female") echo "checked"; echo ">Female  ";
        echo "<input type='radio' name='switcher' value='male' " . (explode("$$$", $_GET["number"])[1] == "male" ? "checked" : "") . ">Male  ";
        echo "<input type='radio' name='switcher' value='last' " . (explode("$$$", $_GET["number"])[1] == "last" ? "checked" : "") . ">Last name  ";
    }
    else {
        echo "<div><input placeholder='Enter vibration' type='text' id='nInput' name='nInput' />";
        echo "<br /><input type='radio' name='switcher' value='female' checked>Female  <input type='radio' name='switcher' value='male' >Male  ";
        echo "<input type='radio' name='switcher' value='last' />Last name";
    }
    echo "<br /><input type='submit' id='nForm' value='Generate names' onclick='doSomething()' class='qbutton' style='margin-bottom: 45px;'/><br /></div>";

    if (isset($_GET["number2"])) {
        echo "<div><input type='text' id='nInput2' name='nInput2' value='" . explode("$$$", $_GET["number2"])[0] . "' />";
        echo "<br /><input type='radio' name='switcher2' value='female' "; if (explode("$$$", $_GET["number2"])[1] == "female") echo "checked"; echo ">Female  ";
        echo "<input type='radio' name='switcher2' value='male' " . (explode("$$$", $_GET["number2"])[1] == "male" ? "checked" : "") . ">Male  ";
        echo "<input type='radio' name='switcher2' value='last' " . (explode("$$$", $_GET["number2"])[1] == "last" ? "checked" : "") . ">Last name  ";
        $numname = "number2";
    }
    else {
        echo "<div><input placeholder='Enter vibration and number, eg. Lisa 17/8' type='text' id='nInput2' name='nInput' />";
        echo "<br /><input type='radio' name='switcher2' value='female' checked>Female  <input type='radio' name='switcher2' value='male' >Male  ";
        echo "<input type='radio' name='switcher2' value='last' />Last name";
    }

    echo "<br /><input type='submit' id='nForm2' value='Generate names' onclick='doSomethingElse()' class='qbutton' /><br /></div>";

    //echo $_SERVER['HTTP_REFERER'];
    //echo "<br />";
    //if ($_SERVER['REMOTE_ADDR'] == "93.176.86.170" || $_SERVER['REMOTE_ADDR'] == "86.52.165.122")
    //  echo $_SERVER['REQUEST_URI'];

    $values = [
        "a" => 1, "i" => 1, "j" => 1, "q" => 1, "y" => 1, "å" => 1, "á" => 1, "à" => 1,
        "b" => 2, "k" => 2, "r" => 2,
        "c" => 3, "g" => 3, "l" => 3, "s" => 3, "ç" => 3,
        "d" => 4, "m" => 4, "t" => 4,
        "e" => 5, "h" => 5, "n" => 5, "x" => 5, "é" => 5, "è" => 5, "è" => "5",
        "u" => 6, "v" => 6, "w" => 6, "æ" => 6,
        "o" => 7, "z" => 7, "ø" => 7, "ô" => 7, "ó" => 7, "ò" => 7, "ö" => 7,
        "f" => 8, "p" => 8];
?>
<br />
<?php

//ini_set('memory_limit', '2048M');
error_reporting(0);
ini_set("display_errors", 0);
ini_set("log_errors", 0);
ini_set("error_reporting", 0);

    if (isset($_GET[$numname]))
    {
        $namecount = 0;
        if (is_numeric(explode("/", explode("$$$", $_GET["number"])[0])[0]))
        {
            echo "<br />";
            if (explode("$$$", $_GET[$numname])[1] == "male")
                $handle = fopen("./malenames.txt", "r");
            else if (explode("$$$", $_GET[$numname])[1] == "female")
                $handle = fopen("./femalenames.txt", "r");
            else
                $handle = fopen("./surnames.txt", "r");
            $output = Array();
            if ($handle)
            {
                while (($line = fgets($handle)) !== false)
                {
                    $bVal = 0;
                    for($j=0;$j<=strlen(utf8_decode($line));$j++)
                    {
                        $bVal += $values[substr(utf8_decode(mb_strtolower($line)),$j,1)];
                    }
                    if ($bVal==explode("/", explode("$$$", $_GET[$numname])[0])[0] || explode("/", explode("$$$", $_GET[$numname])[0])[0] == (1+(($bVal-1)%9)) )
                    {
                        //echo $line . "<br />";
                        $output[$namecount] = $line . " (" . $bVal . "/" . (1+(($bVal-1)%9)) . ")<br />";
                        $namecount++;
                    }
                    //echo $line . "<br />";
                }
                fclose($handle);
                echo "<p id='numcount'>Found " . $namecount . " names</p>";
                echo "<br />";
                for ($i=0;$i<count($output);$i++)
                    echo $output[$i];
                unset($output);
            }
        }
        else if (is_numeric(explode(" ", explode("/", explode("$$$", $_GET[$numname])[0])[0])[1]))
        {
            $parm1 = explode(" ", explode("$$$", $_GET[$numname])[0]);
            $oldname = utf8_decode($parm1[0]);
            $num = explode("/", $parm1[1])[0];
            //echo "<p>" . $parm1 . "</p>";
            //echo "<p>" . $oldname . "</p>";
            //echo "<p>" . $num . "</p>";
            echo "<br />";
            if (explode("$$$", $_GET[$numname])[1] == "male")
                $handle = fopen("./malenames.txt", "r");
            else if (explode("$$$", $_GET[$numname])[1] == "female")
                $handle = fopen("./femalenames.txt", "r");
            else
                $handle = fopen("./surnames.txt", "r");
            $output = Array();
            if ($handle)
            {
                while (($line = fgets($handle)) !== false)
                {
                    $linex = $parm1[0] . mb_strtolower($line);//utf8_decode(mb_strtolower($oldname . mb_strtolower($line)));
                    $bVal = 0;
                    for($j=0;$j<=strlen(utf8_decode($linex));$j++)
                    {
                        $bVal += $values[substr(utf8_decode(mb_strtolower($linex)),$j,1)];
                    }
                    if ($bVal==$num || $num == (1+(($bVal-1)%9)) )
                    {
                        //echo $line . "<br />";
                        $output[$namecount] = $linex . " (" . $bVal . "/" . (1+(($bVal-1)%9)) . ")<br />";
                        $namecount++;
                    }
                    //echo $line . "<br />";
                }
                fclose($handle);
                echo "<p id='numcount'>Found " . $namecount . " names</p>";
                echo "<br />";
                for ($i=0;$i<count($output);$i++)
                    echo $output[$i];
                unset($output);
            }
        }
        else
        {
            echo "<br />Error in input";
        }
        echo "<div style='clear:both;'></div>";
    }
?>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>
</code>```

Body:
I am currently working a little with PHP and taking over a project that wasn't created by me. The tricky things is that on the server/webhotel the application is working like expected, however in my local test environment (WAMP 3.0.6 64bit, PHP 5.6.25, Apache 2.4.23, MySQL 5.7.14) it isn't working. The error message that is being output by PHP is :

Notice: Undefined index: ... line 110

which is directed at this snippet:

$bVal += $values[substr(utf8_decode(mb_strtolower($line)),$j,1)];.

Thing is, I have copied all files as is from the server including all the files it rely on. I only have to make small tweaks (Change the text files the php script reads from) but it won't even work with the original ones. Is there a common issue between platforms versions for PHP, Apache etc? As far as I can tell the XHTTP request is acting normally and I feel like I shouldn't be having these issues, this may come from my inexperience with PHP though.

Code will be posted below and thank you in advance for even taking a look at it!

Code: https://pastebin.com/M6y9rfRa

Body:
Change your code to this and see how it goes

<script>
    function doSomething()
    {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function()
        {
            if (xhttp.readyState == 4)
            {
                if (xhttp.status == 200)
                    document.getElementById("calContent").innerHTML = xhttp.responseText;
            }
        }
        xhttp.open("GET", "/num/ns.php?number=" + jQuery("#nInput").val() + "$$$" + jQuery('input[name=switcher]:checked').val(), true);
        xhttp.send();
    }
    function doSomethingElse()
    {
        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function()
        {
            if (xhttp.readyState == 4)
            {
                if (xhttp.status == 200)
                    document.getElementById("calContent").innerHTML = xhttp.responseText;
            }
        }
        xhttp.open("GET", "/num/ns.php?number2=" + jQuery("#nInput2").val() + "$$$" + jQuery('input[name=switcher2]:checked').val(), true);
        xhttp.send();
    }
</script>
<style>
    .calOut {
        position: relative;
        float: left;
        margin-right: 18px;
    }
</style>
<style media="print">
    #calContent { display: none; }
</style>
<div id="calContent" style="margin-top: 0px; margin-bottom: 50px; color:black;" class="contact_form" >

<?php
    $numname = "number";
    if (isset($_GET["number"])) {
        echo "<div><input type='text' id='nInput' name='nInput' value='" . explode("$$$", $_GET["number"])[0] . "' />";
        echo "<br /><input type='radio' name='switcher' value='female' "; if (explode("$$$", $_GET["number"])[1] == "female") echo "checked"; echo ">Female&nbsp;&nbsp;";
        echo "<input type='radio' name='switcher' value='male' " . (explode("$$$", $_GET["number"])[1] == "male" ? "checked" : "") . ">Male&nbsp;&nbsp;";
        echo "<input type='radio' name='switcher' value='last' " . (explode("$$$", $_GET["number"])[1] == "last" ? "checked" : "") . ">Last name&nbsp;&nbsp;";
    }
    else {
        echo "<div><input placeholder='Enter vibration' type='text' id='nInput' name='nInput' />";
        echo "<br /><input type='radio' name='switcher' value='female' checked>Female&nbsp;&nbsp;<input type='radio' name='switcher' value='male' >Male&nbsp;&nbsp;";
        echo "<input type='radio' name='switcher' value='last' />Last name";
    }
    echo "<br /><input type='submit' id='nForm' value='Generate names' onclick='doSomething()' class='qbutton' style='margin-bottom: 45px;'/><br /></div>";

    if (isset($_GET["number2"])) {
        echo "<div><input type='text' id='nInput2' name='nInput2' value='" . explode("$$$", $_GET["number2"])[0] . "' />";
        echo "<br /><input type='radio' name='switcher2' value='female' "; if (explode("$$$", $_GET["number2"])[1] == "female") echo "checked"; echo ">Female&nbsp;&nbsp;";
        echo "<input type='radio' name='switcher2' value='male' " . (explode("$$$", $_GET["number2"])[1] == "male" ? "checked" : "") . ">Male&nbsp;&nbsp;";
        echo "<input type='radio' name='switcher2' value='last' " . (explode("$$$", $_GET["number2"])[1] == "last" ? "checked" : "") . ">Last name&nbsp;&nbsp;";
        $numname = "number2";
    }
    else {
        echo "<div><input placeholder='Enter vibration and number, eg. Lisa 17/8' type='text' id='nInput2' name='nInput' />";
        echo "<br /><input type='radio' name='switcher2' value='female' checked>Female&nbsp;&nbsp;<input type='radio' name='switcher2' value='male' >Male&nbsp;&nbsp;";
        echo "<input type='radio' name='switcher2' value='last' />Last name";
    }

    echo "<br /><input type='submit' id='nForm2' value='Generate names' onclick='doSomethingElse()' class='qbutton' /><br /></div>";

    //echo $_SERVER['HTTP_REFERER'];
    //echo "<br />";
    //if ($_SERVER['REMOTE_ADDR'] == "93.176.86.170" || $_SERVER['REMOTE_ADDR'] == "86.52.165.122")
    //  echo $_SERVER['REQUEST_URI'];

    $values = [
        "a" => 1, "i" => 1, "j" => 1, "q" => 1, "y" => 1, "å" => 1, "á" => 1, "à" => 1,
        "b" => 2, "k" => 2, "r" => 2,
        "c" => 3, "g" => 3, "l" => 3, "s" => 3, "ç" => 3,
        "d" => 4, "m" => 4, "t" => 4,
        "e" => 5, "h" => 5, "n" => 5, "x" => 5, "é" => 5, "è" => 5, "è" => "5",
        "u" => 6, "v" => 6, "w" => 6, "æ" => 6,
        "o" => 7, "z" => 7, "ø" => 7, "ô" => 7, "ó" => 7, "ò" => 7, "ö" => 7,
        "f" => 8, "p" => 8];
?>
<br />
<?php

//ini_set('memory_limit', '2048M');
error_reporting(0);
ini_set("display_errors", 0);
ini_set("log_errors", 0);
ini_set("error_reporting", 0);

    if (isset($_GET[$numname]))
    {
        $namecount = 0;
        if (is_numeric(explode("/", explode("$$$", $_GET["number"])[0])[0]))
        {
            echo "<br />";
            if (explode("$$$", $_GET[$numname])[1] == "male")
                $handle = fopen("./malenames.txt", "r");
            else if (explode("$$$", $_GET[$numname])[1] == "female")
                $handle = fopen("./femalenames.txt", "r");
            else
                $handle = fopen("./surnames.txt", "r");
            $output = Array();
            if ($handle)
            {
                while (($line = fgets($handle)) !== false)
                {
                    $bVal = 0;
                    for($j=0;$j<=strlen(utf8_decode($line));$j++)
                    {
                        $bVal += $values[substr(utf8_decode(mb_strtolower($line)),$j,1)];
                    }
                    if ($bVal==explode("/", explode("$$$", $_GET[$numname])[0])[0] || explode("/", explode("$$$", $_GET[$numname])[0])[0] == (1+(($bVal-1)%9)) )
                    {
                        //echo $line . "<br />";
                        $output[$namecount] = $line . " (" . $bVal . "/" . (1+(($bVal-1)%9)) . ")<br />";
                        $namecount++;
                    }
                    //echo $line . "<br />";
                }
                fclose($handle);
                echo "<p id='numcount'>Found " . $namecount . " names</p>";
                echo "<br />";
                for ($i=0;$i<count($output);$i++)
                    echo $output[$i];
                unset($output);
            }
        }
        else if (is_numeric(explode(" ", explode("/", explode("$$$", $_GET[$numname])[0])[0])[1]))
        {
            $parm1 = explode(" ", explode("$$$", $_GET[$numname])[0]);
            $oldname = utf8_decode($parm1[0]);
            $num = explode("/", $parm1[1])[0];
            //echo "<p>" . $parm1 . "</p>";
            //echo "<p>" . $oldname . "</p>";
            //echo "<p>" . $num . "</p>";
            echo "<br />";
            if (explode("$$$", $_GET[$numname])[1] == "male")
                $handle = fopen("./malenames.txt", "r");
            else if (explode("$$$", $_GET[$numname])[1] == "female")
                $handle = fopen("./femalenames.txt", "r");
            else
                $handle = fopen("./surnames.txt", "r");
            $output = Array();
            if ($handle)
            {
                while (($line = fgets($handle)) !== false)
                {
                    $linex = $parm1[0] . mb_strtolower($line);//utf8_decode(mb_strtolower($oldname . mb_strtolower($line)));
                    $bVal = 0;
                    for($j=0;$j<=strlen(utf8_decode($linex));$j++)
                    {
                        $bVal += $values[substr(utf8_decode(mb_strtolower($linex)),$j,1)];
                    }
                    if ($bVal==$num || $num == (1+(($bVal-1)%9)) )
                    {
                        //echo $line . "<br />";
                        $output[$namecount] = $linex . " (" . $bVal . "/" . (1+(($bVal-1)%9)) . ")<br />";
                        $namecount++;
                    }
                    //echo $line . "<br />";
                }
                fclose($handle);
                echo "<p id='numcount'>Found " . $namecount . " names</p>";
                echo "<br />";
                for ($i=0;$i<count($output);$i++)
                    echo $output[$i];
                unset($output);
            }
        }
        else
        {
            echo "<br />Error in input";
        }
        echo "<div style='clear:both;'></div>";
    }
?>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>