问:
How to use the heightForRowAtIndexPath method?
I am trying to use the heightForRowAtIndexPath method in my UITableViewController. But when I try to override the method it says that it does not override any methods from its superclass.

Googling has led me to protocols, which seem to potentially be some part of the puzzle, but I'm still trying to understand how to use a protocol to use this method.

Any help would be greatly appreciated. Here's the code: (the problem method is at the very bottom)

```<code>import UIKit
import Firebase

class FruitsTableViewController: UITableViewController {
    let rootRef = FIRDatabase.database().reference()

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 15
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)

        let busRef = rootRef.child("buses")
        busRef.observeSingleEvent(of: .value, with: {(snapshot) in
            if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
                let bus = snapshots[Int(indexPath.row)].key
                let busval = snapshots[Int(indexPath.row)].value as! String
                cell.textLabel?.text = "Bus \(bus) ------- \(busval)"
            }
        })

        return cell
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Section \(section)"
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 40.0
    }
}
</code>```

答:
Use following code </p>

```<code>func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
    return 50.0
}
</code>```

Body:
I am trying to use the heightForRowAtIndexPath method in my UITableViewController. But when I try to override the method it says that it does not override any methods from its superclass.

Googling has led me to protocols, which seem to potentially be some part of the puzzle, but I'm still trying to understand how to use a protocol to use this method.

Any help would be greatly appreciated. Here's the code: (the problem method is at the very bottom)

import UIKit
import Firebase

class FruitsTableViewController: UITableViewController {
    let rootRef = FIRDatabase.database().reference()

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 15
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LabelCell", for: indexPath)

        let busRef = rootRef.child("buses")
        busRef.observeSingleEvent(of: .value, with: {(snapshot) in
            if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
                let bus = snapshots[Int(indexPath.row)].key
                let busval = snapshots[Int(indexPath.row)].value as! String
                cell.textLabel?.text = "Bus \(bus) ------- \(busval)"
            }
        })

        return cell
    }

    override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Section \(section)"
    }

    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 40.0
    }
}

Body:
Use following code

func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
    return 50.0
}


来源: stackexchange

问:
Trying to avoid nesting Select statements but getting error "Conversion failed when converting the varchar value to datatype int"
The first part of my code below defines the field 'LCO'.  I am trying to use that field in the second part to check if result of the SELECT is greater than the 'LCO' corresponding field.

```<code>SELECT
    Jobs.jmpPartID,
    Jobs.jmpJobID,
    Jobs.ujmpProjRelReference,
    Jobs.jmpCustomerOrganizationID,
    Jobs.jmpProductionQuantity,
    Jobs.jmpProductionDueDate,
    (SELECT
         ISNULL((SELECT TOP 1 JobOperations.jmoJobOperationID
                 FROM M1_HB.dbo.JobOperations JobOperations
                 WHERE JobOperations.jmoJobID = Jobs.jmpJobID
                   AND JobOperations.jmoProductionComplete = -1
                 ORDER BY JobOperations.jmoJobOperationID DESC), 0)) AS 'LCO',
    (SELECT TOP 1 WorkCenters.xawProductionDepartmentID
    FROM M1_HB.dbo.WorkCenters WorkCenters,
         M1_Hb.dbo.JobOperations JobOperations
    WHERE WorkCenters.xawWorkCenterID = JobOperations.jmoWorkCenterID
      AND JobOperations.jmoProductionComplete=0
      AND JobOperations.jmoJobID =Jobs.jmpJobID
      AND JobOperations.jmoJobOperationID > 'LCO'
    ORDER BY JobOperations.jmoJobOperationID) AS 'Dept'
FROM
    M1_HB.dbo.Jobs Jobs
WHERE
    (Jobs.jmpProductionComplete = 0)
ORDER BY
    Jobs.jmpPartID, Jobs.jmpJobID
</code>```

I am getting an error

Conversion failed when converting the varchar value to datatype int

If I nest the first SELECT into the second (ie replace > 'LCO' with > (Select Isnull((Select Top 1 .....)) like below then it works.

```<code>SELECT
    Jobs.jmpPartID,
    Jobs.jmpJobID,
    Jobs.ujmpProjRelReference,
    Jobs.jmpCustomerOrganizationID,
    Jobs.jmpProductionQuantity,
    Jobs.jmpProductionDueDate,
    (SELECT ISNULL((SELECT TOP 1 JobOperations.jmoJobOperationID
                    FROM M1_HB.dbo.JobOperations JobOperations
                    WHERE JobOperations.jmoJobID = Jobs.jmpJobID
                      AND JobOperations.jmoProductionComplete = -1
                    ORDER BY JobOperations.jmoJobOperationID DESC), 0)) AS 'LCO',
    (SELECT TOP 1 WorkCenters.xawProductionDepartmentID
     FROM M1_HB.dbo.WorkCenters WorkCenters,
          M1_Hb.dbo.JobOperations JobOperations
     WHERE WorkCenters.xawWorkCenterID = JobOperations.jmoWorkCenterID
       AND JobOperations.jmoProductionComplete = 0
       AND JobOperations.jmoJobID = Jobs.jmpJobID
       AND JobOperations.jmoJobOperationID > (SELECT ISNULL((SELECT TOP 1 JobOperations.jmoJobOperationID
                                                             FROM M1_HB.dbo.JobOperations JobOperations
                                                             WHERE JobOperations.jmoJobID = Jobs.jmpJobID
                                                               AND JobOperations.jmoProductionComplete = -1
                                                             ORDER BY JobOperations.jmoJobOperationID DESC), 0))
     ORDER BY
         JobOperations.jmoJobOperationID) AS 'Dept'
FROM
    M1_HB.dbo.Jobs Jobs
WHERE
    (Jobs.jmpProductionComplete = 0)
ORDER BY
    Jobs.jmpPartID, Jobs.jmpJobID
</code>```

What do I need to do to my first code to make it work?  I tried using CAST() in various ways, but without success

答:
Basically, here you need to add two colums to a table in succession.
I would use CTE:</p>

```<code>;WITH Jobs AS (
  SELECT
       jmpPartID,
       jmpJobID,
       ujmpProjRelReference,
       jmpCustomerOrganizationID,
       jmpProductionQuantity,
       jmpProductionDueDate,
      (SELECT isnull(
                   (SELECT top 1 JobOperations.jmoJobOperationID
                    FROM M1_HB.dbo.JobOperations JobOperations
                    WHERE JobOperations.jmoJobID = Jobs.jmpJobID
                      AND JobOperations.jmoProductionComplete = -1
                    ORDER BY JobOperations.jmoJobOperationID DESC)
      ,0)) AS LCO --< Step 1: add LCO column into Jobs CTE
  FROM M1_HB.dbo.Jobs
  WHERE jmpProductionComplete = 0
)
SELECT *,
  (SELECT Top 1 WorkCenters.xawProductionDepartmentID
   FROM M1_HB.dbo.WorkCenters WorkCenters,
        M1_Hb.dbo.JobOperations JobOperations
   WHERE WorkCenters.xawWorkCenterID = JobOperations.jmoWorkCenterID
     AND JobOperations.jmoProductionComplete = 0
     AND JobOperations.jmoJobID = Jobs.jmpJobID
     AND JobOperations.jmoJobOperationID > Jobs.LCO --< Now we do have LCO in Jobs
   ORDER BY JobOperations.jmoJobOperationID) AS Dept --< ... and can add dependent column
FROM Jobs
ORDER BY jmpPartID, jmpJobID
</code>```

ContentLicense: CC BY-SA 3.0

Body:
The first part of my code below defines the field 'LCO'.  I am trying to use that field in the second part to check if result of the SELECT is greater than the 'LCO' corresponding field.

SELECT
    Jobs.jmpPartID,
    Jobs.jmpJobID,
    Jobs.ujmpProjRelReference,
    Jobs.jmpCustomerOrganizationID,
    Jobs.jmpProductionQuantity,
    Jobs.jmpProductionDueDate,
    (SELECT
         ISNULL((SELECT TOP 1 JobOperations.jmoJobOperationID
                 FROM M1_HB.dbo.JobOperations JobOperations
                 WHERE JobOperations.jmoJobID = Jobs.jmpJobID
                   AND JobOperations.jmoProductionComplete = -1
                 ORDER BY JobOperations.jmoJobOperationID DESC), 0)) AS 'LCO',
    (SELECT TOP 1 WorkCenters.xawProductionDepartmentID
    FROM M1_HB.dbo.WorkCenters WorkCenters,
         M1_Hb.dbo.JobOperations JobOperations
    WHERE WorkCenters.xawWorkCenterID = JobOperations.jmoWorkCenterID
      AND JobOperations.jmoProductionComplete=0
      AND JobOperations.jmoJobID =Jobs.jmpJobID
      AND JobOperations.jmoJobOperationID > 'LCO'
    ORDER BY JobOperations.jmoJobOperationID) AS 'Dept'
FROM
    M1_HB.dbo.Jobs Jobs
WHERE
    (Jobs.jmpProductionComplete = 0)
ORDER BY
    Jobs.jmpPartID, Jobs.jmpJobID

I am getting an error

Conversion failed when converting the varchar value to datatype int

If I nest the first SELECT into the second (ie replace > 'LCO' with > (Select Isnull((Select Top 1 .....)) like below then it works.

SELECT
    Jobs.jmpPartID,
    Jobs.jmpJobID,
    Jobs.ujmpProjRelReference,
    Jobs.jmpCustomerOrganizationID,
    Jobs.jmpProductionQuantity,
    Jobs.jmpProductionDueDate,
    (SELECT ISNULL((SELECT TOP 1 JobOperations.jmoJobOperationID
                    FROM M1_HB.dbo.JobOperations JobOperations
                    WHERE JobOperations.jmoJobID = Jobs.jmpJobID
                      AND JobOperations.jmoProductionComplete = -1
                    ORDER BY JobOperations.jmoJobOperationID DESC), 0)) AS 'LCO',
    (SELECT TOP 1 WorkCenters.xawProductionDepartmentID
     FROM M1_HB.dbo.WorkCenters WorkCenters,
          M1_Hb.dbo.JobOperations JobOperations
     WHERE WorkCenters.xawWorkCenterID = JobOperations.jmoWorkCenterID
       AND JobOperations.jmoProductionComplete = 0
       AND JobOperations.jmoJobID = Jobs.jmpJobID
       AND JobOperations.jmoJobOperationID > (SELECT ISNULL((SELECT TOP 1 JobOperations.jmoJobOperationID
                                                             FROM M1_HB.dbo.JobOperations JobOperations
                                                             WHERE JobOperations.jmoJobID = Jobs.jmpJobID
                                                               AND JobOperations.jmoProductionComplete = -1
                                                             ORDER BY JobOperations.jmoJobOperationID DESC), 0))
     ORDER BY
         JobOperations.jmoJobOperationID) AS 'Dept'
FROM
    M1_HB.dbo.Jobs Jobs
WHERE
    (Jobs.jmpProductionComplete = 0)
ORDER BY
    Jobs.jmpPartID, Jobs.jmpJobID

What do I need to do to my first code to make it work?  I tried using CAST() in various ways, but without success

Body:
Basically, here you need to add two colums to a table in succession.
I would use CTE:

;WITH Jobs AS (
  SELECT
       jmpPartID,
       jmpJobID,
       ujmpProjRelReference,
       jmpCustomerOrganizationID,
       jmpProductionQuantity,
       jmpProductionDueDate,
      (SELECT isnull(
                   (SELECT top 1 JobOperations.jmoJobOperationID
                    FROM M1_HB.dbo.JobOperations JobOperations
                    WHERE JobOperations.jmoJobID = Jobs.jmpJobID
                      AND JobOperations.jmoProductionComplete = -1
                    ORDER BY JobOperations.jmoJobOperationID DESC)
      ,0)) AS LCO --< Step 1: add LCO column into Jobs CTE
  FROM M1_HB.dbo.Jobs
  WHERE jmpProductionComplete = 0
)
SELECT *,
  (SELECT Top 1 WorkCenters.xawProductionDepartmentID
   FROM M1_HB.dbo.WorkCenters WorkCenters,
        M1_Hb.dbo.JobOperations JobOperations
   WHERE WorkCenters.xawWorkCenterID = JobOperations.jmoWorkCenterID
     AND JobOperations.jmoProductionComplete = 0
     AND JobOperations.jmoJobID = Jobs.jmpJobID
     AND JobOperations.jmoJobOperationID > Jobs.LCO --< Now we do have LCO in Jobs
   ORDER BY JobOperations.jmoJobOperationID) AS Dept --< ... and can add dependent column
FROM Jobs
ORDER BY jmpPartID, jmpJobID


问:
How to disable a button dynamically
I want to gray out a button dynamically. How to do that?</p>

答: Set its IsEnabled property to false. You can do this either in code-behind or with triggers/styles, depending on your needs there.

ContentLicense: CC BY-SA 2.5

Title: How to disable a button dynamically


问:
sql bulk insert c# in asp.net
i want to insert 10000+ rows in my database fast (I tried with linqtosql and it took me more than 2 minutes) and after a research on the internet I found out about SQL Bulk Copy, but I am don't really understand it. Can someone give me a good example in my case?
I fill a list from a .csv file so all my data are in this

```<code>List<myTable> datalist = new List<myTable>();
</code>```

and I also have a context in order to execute SQL transactions.

答:
To use SqlBulkCopy you need either DataTable or an IDataReader. If you have a List<T>, that can still work - via tools like FastMember which makes an IDataReader from a sequence of objects, for example:

```<code>using(var bcp = new SqlBulkCopy(connection))
using(var reader = ObjectReader.Create(data, "Id", "Name", "Description"))
{
  bcp.DestinationTableName = "SomeTable";
  bcp.WriteToServer(reader);
}
</code>```

(obviously use datalist in place of data; the strings afterwards are the members to map into columns - you could use nameof here in recent versions of C#, i.e. nameof(myTable.Id) in place of "Id")

If you want to work directly from the CSV without the List<T> in the middle, CsvReader would be more appropriate.

Title: sql bulk insert c# in asp.net

Body:
i want to insert 10000+ rows in my database fast (I tried with linqtosql and it took me more than 2 minutes) and after a research on the internet I found out about SQL Bulk Copy, but I am don't really understand it. Can someone give me a good example in my case?
I fill a list from a .csv file so all my data are in this

List<myTable> datalist = new List<myTable>();

and I also have a context in order to execute SQL transactions.

Body:
To use SqlBulkCopy you need either DataTable or an IDataReader. If you have a List<T>, that can still work - via tools like FastMember which makes an IDataReader from a sequence of objects, for example:

using(var bcp = new SqlBulkCopy(connection))
using(var reader = ObjectReader.Create(data, "Id", "Name", "Description"))
{
  bcp.DestinationTableName = "SomeTable";
  bcp.WriteToServer(reader);
}

(obviously use datalist in place of data; the strings afterwards are the members to map into columns - you could use nameof here in recent versions of C#, i.e. nameof(myTable.Id) in place of "Id")

If you want to work directly from the CSV without the List<T> in the middle, CsvReader would be more appropriate.


问:
How to check if columns in dataframe are identical in R [produce matrix]
I have a large dataframe ncol =220 I want to compare the columns to see  if they may be identical and produce a matrix for ease of identification.

So what I have is

```<code>      x    y   z
1   dog   dog   cat
2   dog   dog   dog
3   cat   cat   cat
</code>```

What I want

```<code>     x     y     z
x   -     True   False
y   True     -   False
z   False False   -
</code>```

Is there a way to do this using identical() in R?

答:
To compliment @Cath's comment about stringdist, it is as easy as,

```<code>library(stringdist)

stringdistmatrix(df, df) == 0

#      [,1]  [,2]  [,3]
#[1,]  TRUE  TRUE FALSE
#[2,]  TRUE  TRUE FALSE
#[3,] FALSE FALSE  TRUE
</code>```

Body:
I have a large dataframe ncol =220 I want to compare the columns to see  if they may be identical and produce a matrix for ease of identification.

So what I have is

      x    y   z
1   dog   dog   cat
2   dog   dog   dog
3   cat   cat   cat

What I want

     x     y     z
x   -     True   False
y   True     -   False
z   False False   -

Is there a way to do this using identical() in R?

Body:
To compliment @Cath's comment about stringdist, it is as easy as,

library(stringdist)

stringdistmatrix(df, df) == 0

#      [,1]  [,2]  [,3]
#[1,]  TRUE  TRUE FALSE
#[2,]  TRUE  TRUE FALSE
#[3,] FALSE FALSE  TRUE


问:
renaming uploaded file nodejs and multer

problem with file name in Multer

i am using express.js and multer to upload images to server. i act like this:

```<code>var storage = multer.diskStorage({
        destination: function (req, file, callback) {
            callback(null, "../client/member/upload");
        },
        filename: function (req, file, callback) {
            console.log('1', 1);
            callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
        }
    });
    var upload = multer({ storage : storage}).single('userPhoto');
</code>```

but the problem is that never file name changes.
my uploader handler:

```<code>function memberUpload(request, response) {

    var storage = multer.diskStorage({
        destination: function (req, file, callback) {
            callback(null, "../client/member/upload");
        },
        filename: function (req, file, callback) {
            console.log('1', 1);
            callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
        }
    });
    var upload = multer({ storage : storage}).single('userPhoto');

    var folderName = path.join(__dirname, '../', 'client/member/upload');

    if (!fs.existsSync(folderName)) {
        fs.mkdir(folderName, function (err) {
            if (err) {
                return response.status(500).send(err);
            }
            else {
                upload(request, response, function (err) {
                    if (err) {
                        return response.status(400)
                            .send('No files were uploaded.');
                    }
                    var sentFile = request.files.file,
                        fileName = (request.files.file && request.files.file.name) ? request.files.file.name : 'test';

                    sentFile.mv(path.join(__dirname, '../', 'client/member/upload/', fileName), function (err) {
                        mime.lookup(path.join(__dirname, '../', 'client/member/upload/', fileName));         // => 'text/plain'
                        if (err) {
                            return response.status(500)
                                .send(err);
                        }
                        response.send({'location': '../member/upload/' + fileName});
                    });
                });
            }
        });
    }
    else {
        upload(request, response, function (err) {
            if (err) {
                return response.status(400)
                    .send('No files were uploaded.');
            }
            var sentFile = request.files.file,
                fileName = (request.files.file && request.files.file.name) ? request.files.file.name : 'test';

            sentFile.mv(path.join(__dirname, '../', 'client/member/upload/', fileName), function (err) {
                mime.lookup(path.join(__dirname, '../', 'client/member/upload/', fileName));         // => 'text/plain'
                if (err) {
                    return response.status(500)
                        .send(err);
                }
                response.send({'location': '../member/upload/' + fileName});
            });
        });
    }
}
</code>```

the file save into correct directory with name "blobid0.jpeg", "blobid1.png" and so on ...
what is my fault?

答:
Here is my code for uploading any file(pdf, txt, png) to server.Hope this will help you.    </p>

```<code>exports.saveMedia = ((req, res) => {
        const storage = multer.diskStorage({
            destination: (req, file, callback) => {
                callback(null, (config.const.path.base + config.const.path.productReviewMedia));
            },
            filename: (req, file, callback) => {
                callback(null, Date.now() + '-' + file.originalname);

            }
        });

        const upload = multer({storage: storage}).any('file');

        upload(req, res, (err) => {
            if (err) {
                return res.status(400).send({
                    message: helper.getErrorMessage(err)
                });
            }
            let results = req.files.map((file) => {
                return {
                    mediaName: file.filename,
                    origMediaName: file.originalname,
                    mediaSource: 'http://' + req.headers.host + config.const.path.productReviewMedia + file.filename
                }
            });
            res.status(200).json(results);
        });
    });
</code>```

Body:
problem with file name in Multer

i am using express.js and multer to upload images to server. i act like this:

var storage = multer.diskStorage({
        destination: function (req, file, callback) {
            callback(null, "../client/member/upload");
        },
        filename: function (req, file, callback) {
            console.log('1', 1);
            callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
        }
    });
    var upload = multer({ storage : storage}).single('userPhoto');

but the problem is that never file name changes.
my uploader handler:

function memberUpload(request, response) {

    var storage = multer.diskStorage({
        destination: function (req, file, callback) {
            callback(null, "../client/member/upload");
        },
        filename: function (req, file, callback) {
            console.log('1', 1);
            callback(null, file.fieldname + "_" + Date.now() + "_" + file.originalname);
        }
    });
    var upload = multer({ storage : storage}).single('userPhoto');

    var folderName = path.join(__dirname, '../', 'client/member/upload');

    if (!fs.existsSync(folderName)) {
        fs.mkdir(folderName, function (err) {
            if (err) {
                return response.status(500).send(err);
            }
            else {
                upload(request, response, function (err) {
                    if (err) {
                        return response.status(400)
                            .send('No files were uploaded.');
                    }
                    var sentFile = request.files.file,
                        fileName = (request.files.file && request.files.file.name) ? request.files.file.name : 'test';

                    sentFile.mv(path.join(__dirname, '../', 'client/member/upload/', fileName), function (err) {
                        mime.lookup(path.join(__dirname, '../', 'client/member/upload/', fileName));         // => 'text/plain'
                        if (err) {
                            return response.status(500)
                                .send(err);
                        }
                        response.send({'location': '../member/upload/' + fileName});
                    });
                });
            }
        });
    }
    else {
        upload(request, response, function (err) {
            if (err) {
                return response.status(400)
                    .send('No files were uploaded.');
            }
            var sentFile = request.files.file,
                fileName = (request.files.file && request.files.file.name) ? request.files.file.name : 'test';

            sentFile.mv(path.join(__dirname, '../', 'client/member/upload/', fileName), function (err) {
                mime.lookup(path.join(__dirname, '../', 'client/member/upload/', fileName));         // => 'text/plain'
                if (err) {
                    return response.status(500)
                        .send(err);
                }
                response.send({'location': '../member/upload/' + fileName});
            });
        });
    }
}

the file save into correct directory with name "blobid0.jpeg", "blobid1.png" and so on ...
what is my fault?

Body:
Here is my code for uploading any file(pdf, txt, png) to server.Hope this will help you.

exports.saveMedia = ((req, res) => {
        const storage = multer.diskStorage({
            destination: (req, file, callback) => {
                callback(null, (config.const.path.base + config.const.path.productReviewMedia));
            },
            filename: (req, file, callback) => {
                callback(null, Date.now() + '-' + file.originalname);

            }
        });

        const upload = multer({storage: storage}).any('file');

        upload(req, res, (err) => {
            if (err) {
                return res.status(400).send({
                    message: helper.getErrorMessage(err)
                });
            }
            let results = req.files.map((file) => {
                return {
                    mediaName: file.filename,
                    origMediaName: file.originalname,
                    mediaSource: 'http://' + req.headers.host + config.const.path.productReviewMedia + file.filename
                }
            });
            res.status(200).json(results);
        });
    });


问:
How to request the greatest version with FIND_PACKAGE in CMAKE
I have a folder containing a list of libraries:

```<code>libs\libA-1.0
    \libB-1.2
    \libB-1.4
    \libB-1.6
</code>```

I am loading such libraries in my cmake scripts using for example

```<code>FIND_PACKAGE(libB CONFIG)
</code>```

CMAKE in this case simply loads the first acceptable version present in the libs folder (in this case libB-1.2 since it is the first found in the folder)

I know that I could request a specific library version using

```<code>FIND_PACKAGE(libB 1.6 CONFIG)
</code>```

but I would like to recover the library with the greatest version number (or at least the latest in lexicographic order), without specifying it (so that I can update the libraries without modify all my cmake scripts).

Is this possible?

答:
Since CMAKE 3.7.0 this is now possible

To control the order in which find_package checks for compatibiliy use
  the two variables CMAKE_FIND_PACKAGE_SORT_ORDER and
  CMAKE_FIND_PACKAGE_SORT_DIRECTION.
  For instance in order to select the highest version one can set:

```<code>SET(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL)
SET(CMAKE_FIND_PACKAGE_SORT_DIRECTION DEC)
</code>```

Body:
I have a folder containing a list of libraries:

libs\libA-1.0
    \libB-1.2
    \libB-1.4
    \libB-1.6

I am loading such libraries in my cmake scripts using for example

FIND_PACKAGE(libB CONFIG)

CMAKE in this case simply loads the first acceptable version present in the libs folder (in this case libB-1.2 since it is the first found in the folder)

I know that I could request a specific library version using

FIND_PACKAGE(libB 1.6 CONFIG)

but I would like to recover the library with the greatest version number (or at least the latest in lexicographic order), without specifying it (so that I can update the libraries without modify all my cmake scripts).

Is this possible?

Body:
Since CMAKE 3.7.0 this is now possible

To control the order in which find_package checks for compatibiliy use
  the two variables CMAKE_FIND_PACKAGE_SORT_ORDER and
  CMAKE_FIND_PACKAGE_SORT_DIRECTION.
  For instance in order to select the highest version one can set:

SET(CMAKE_FIND_PACKAGE_SORT_ORDER NATURAL)
SET(CMAKE_FIND_PACKAGE_SORT_DIRECTION DEC)


问:
"Could Not Find Developer Disk Image" Xcode 7.1
My Xcode is telling me:

"Could not find developer disk image,"

when I am trying to load the app onto an iPhone 6 running ios 9.2 and my Xcode is Version 7.1 (7B91b)

答: Older XCode version has no developer disk image for newer iOS version. If you don't want upgrade XCode you can find ready developer disk images for latest versions in this answer: https://stackoverflow.com/a/39865199/286361</p>

ContentLicense: CC BY-SA 4.0


问:
Spring Integration with multiple http outbound gateway does not clear the header
In a situation where I have:

```<code><int-http:outbound-gateway request-channel="dataHubRawDataUploadChannel"
        id="raw" url-expression="headers['rawUrl']" http-method="POST"
        extract-request-payload="true" header-mapper="headerMapper"
        reply-channel="rawDataUploadResponseChannel" expected-response-type="java.lang.String"
         error-handler="rawResponseErrorHandler" />

    <int-http:outbound-gateway request-channel="canonicalHttpChannel"
        id="canonical" url-expression="headers['canonicalUrl']"
        http-method="POST" header-mapper="headerMapper" reply-channel="targetDataUploadChannel"
        expected-response-type="java.lang.String"    rest-template="customRestTemplate"/>

    <int-http:outbound-gateway request-channel="targetHttpChannel"
        id="target" url-expression="headers['targetUrl']"
        http-method="POST" header-mapper="headerMapper" reply-channel="targetUploadResponseProcessor"
        expected-response-type="java.lang.String" />
</code>```

I face the following problem:

The headers of the first and second request are not cleared when sending the third request , resulting in a Http 400 response.

I tried to clean the headers but the only solution I found is to override the RestTemplate class responsible for the actual HTTP request and clear the headers there, which is an ugly solution.

Do you have a better way to do it with Spring Integration?

答:
The DefaultHttpHeaderMapper has a method setExcludedOutboundStandardRequestHeaderNames where you can pass it an array of header names that you don't want propagated from the outbound message.

See this answer for an example.

EDIT

If you are using Java configuration, simply define that mapper as a @Bean as shown in that answer.

If you are using XML configuration:

```<code><bean id="mapper" class="org.springframework.integration.http.support.DefaultHttpHeaderMapper"
        factory-method="outboundMapper">
    <property name="excludedInboundStandardResponseHeaderNames">
        <array>
            <value>Host</value>
            <value>User-Agent</value>
        </array>
    </property>
</bean>
</code>```

Body:
In a situation where I have:

<int-http:outbound-gateway request-channel="dataHubRawDataUploadChannel"
        id="raw" url-expression="headers['rawUrl']" http-method="POST"
        extract-request-payload="true" header-mapper="headerMapper"
        reply-channel="rawDataUploadResponseChannel" expected-response-type="java.lang.String"
         error-handler="rawResponseErrorHandler" />

    <int-http:outbound-gateway request-channel="canonicalHttpChannel"
        id="canonical" url-expression="headers['canonicalUrl']"
        http-method="POST" header-mapper="headerMapper" reply-channel="targetDataUploadChannel"
        expected-response-type="java.lang.String"    rest-template="customRestTemplate"/>

    <int-http:outbound-gateway request-channel="targetHttpChannel"
        id="target" url-expression="headers['targetUrl']"
        http-method="POST" header-mapper="headerMapper" reply-channel="targetUploadResponseProcessor"
        expected-response-type="java.lang.String" />

I face the following problem:

The headers of the first and second request are not cleared when sending the third request , resulting in a Http 400 response.

I tried to clean the headers but the only solution I found is to override the RestTemplate class responsible for the actual HTTP request and clear the headers there, which is an ugly solution.

Do you have a better way to do it with Spring Integration?

Body:
The DefaultHttpHeaderMapper has a method setExcludedOutboundStandardRequestHeaderNames where you can pass it an array of header names that you don't want propagated from the outbound message.

See this answer for an example.

EDIT

If you are using Java configuration, simply define that mapper as a @Bean as shown in that answer.

If you are using XML configuration:

<bean id="mapper" class="org.springframework.integration.http.support.DefaultHttpHeaderMapper"
        factory-method="outboundMapper">
    <property name="excludedInboundStandardResponseHeaderNames">
        <array>
            <value>Host</value>
            <value>User-Agent</value>
        </array>
    </property>
</bean>


问:
How much data will be transferred from memory to CPU in a single call
As memory is much slower to CPU, It should send the data in blocks of some 'x'Bytes.

How much would be the size of this 'x'?

Do the data line b/n memory and CPU is also a x*8 bit lane?

If I access an address 'A' on memory, would it be sending all the next x-1 memory addresses to the cache?

What is the Approx frequency a memory bus would be working?

SIMD - Do SSE and MMX extensions somehow leverage this bulk reading feature?

Please feel free to provide any references.

Thanks in advance.

答:
The size 'x' is generally the size of a cache line. Cache line size depends on the architecture, but Intel and AMD use 64 byte.

At least . If you have more channels, you can fetch more data from different channels.

Not exactly the next x-1 memory addresses. You can think of the memory, divided into 64 byte chunks. Every time you want to access even one byte, you will bring the chunk your address belongs. Lets assume you want to access the address 123 (decimal). The start of the address should be 64 to 127. So, you will bring that whole chunk. Which means, you do not only bring the following ones, but the previous addresses as well, depending on the address you access of course.

That depends the version of DDR you CPU supports. You can check some numbers in here: https://en.wikipedia.org/wiki/Double_data_rate

Yes, they do. When you bring a data from memory to caches, you bring one cache line, and SIMD extensions work on multiple data elements in a single instruction. Which means if you want to add 4 values in one instruction, the data you are looking for would be in the cache (since you brought the whole chunk) and you just read it from cache.


问:
SQLite3::query(): Unable to prepare statement: 1, unrecognized token ""
I am trying to create a PHP search query that searches by each word from the database. But i get this error when search query is submitted.

Warning: SQLite3::query(): Unable to prepare statement: 1, unrecognized token: "'%export%" in C:\xampp\htdocs\xport\searchresult.php on line 107

Below is my code.

For the search page

```<code>if (isset($_POST['mainSearch']))
{

if (!empty($_POST['mainSearch']))
{
    $searchquery = $_POST['mainSearch'];

    $query = str_replace(" ", "+", $_POST['mainSearch']);
    header("Location: searchresult.php?mainSearch=" . $query);

}

}
</code>```

Page to display search result.

```<code>if (isset($_GET["mainSearch"]))
{
  $condition = '';
  $query = explode(" ", $_GET['mainSearch']);

  foreach ($query as $text)
  {
      $condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%'";
  }
  $condition = substr($condition, 0, -4);

  $sql_query = "SELECT * FROM questions WHERE " . $condition;
  $result = $db->query($sql_query);

  if ($result)
  {
      while ($row = $result->fetchArray(SQLITE3_ASSOC))
      {
           echo '<div class="quesbox_2">
            <div class="questitle">
                <h2>'.$row["question"].'</h2>
            </div>
            <div class="quesanswer">'.$row["answer"].'</div>
        </div>';
      }
  }
  else
  {

  }
  }
</code>```

What is the reason for this error. I think its because the string is not properly escaped, if this is the reason how do i mysqli_real_escape_string() in SQLite3 (this is the database i am using). If not, Please how do i fix this.

答:
Seems you need an OR condition in your WHERE clause that will fetch all results matching any of the words. Just add OR at the end of your query part and you should be fine.

```<code>foreach ($query as $text)
{
    $condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
// Will chop 4 characters ' OR ' from end of the string
$condition = substr($condition, 0, -4);
</code>```

To make it little clean, you can escapeString once when retrieved from the parameter to avoid escaping it again and again in the loop.

```<code>$mainSearch = SQLite3::escapeString($_GET['mainSearch']);
$query = explode(" ", $mainSearch);

foreach ($query as $text)
{
    $condition .= "question LIKE '%$text%' OR answer LIKE '%$text%' OR ";
}
// Will chop 4 characters ' OR ' from end of the string
$condition = substr($condition, 0, -4);
</code>```

Body:
I am trying to create a PHP search query that searches by each word from the database. But i get this error when search query is submitted.

Warning: SQLite3::query(): Unable to prepare statement: 1, unrecognized token: "'%export%" in C:\xampp\htdocs\xport\searchresult.php on line 107

Below is my code.

For the search page

if (isset($_POST['mainSearch']))
{

if (!empty($_POST['mainSearch']))
{
    $searchquery = $_POST['mainSearch'];

    $query = str_replace(" ", "+", $_POST['mainSearch']);
    header("Location: searchresult.php?mainSearch=" . $query);

}

}

Page to display search result.

if (isset($_GET["mainSearch"]))
{
  $condition = '';
  $query = explode(" ", $_GET['mainSearch']);

  foreach ($query as $text)
  {
      $condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%'";
  }
  $condition = substr($condition, 0, -4);

  $sql_query = "SELECT * FROM questions WHERE " . $condition;
  $result = $db->query($sql_query);

  if ($result)
  {
      while ($row = $result->fetchArray(SQLITE3_ASSOC))
      {
           echo '

'.$row["question"].'

'.$row["answer"].'

';
      }
  }
  else
  {

  }
  }

What is the reason for this error. I think its because the string is not properly escaped, if this is the reason how do i mysqli_real_escape_string() in SQLite3 (this is the database i am using). If not, Please how do i fix this.

Body:
Seems you need an OR condition in your WHERE clause that will fetch all results matching any of the words. Just add OR at the end of your query part and you should be fine.

foreach ($query as $text)
{
    $condition .= "question LIKE '%".SQLite3::escapeString($text)."%' OR answer LIKE '%".SQLite3::escapeString($text)."%' OR ";
}
// Will chop 4 characters ' OR ' from end of the string
$condition = substr($condition, 0, -4);

To make it little clean, you can escapeString once when retrieved from the parameter to avoid escaping it again and again in the loop.

$mainSearch = SQLite3::escapeString($_GET['mainSearch']);
$query = explode(" ", $mainSearch);

foreach ($query as $text)
{
    $condition .= "question LIKE '%$text%' OR answer LIKE '%$text%' OR ";
}
// Will chop 4 characters ' OR ' from end of the string
$condition = substr($condition, 0, -4);


问:
How to change a text based onclick with JavaScript?
Good evening everybody!

Well, I am studying JavaScript at the moment, and I reachead the point in where I need, based on clicked text (button, ... it doesn't matter, I guess).

For example:

This message should be edited.

Two choices: ES - EN

If choice "ES" is clicked/selected, then:

This message has been edited to ES.

Otherwise, if choice "EN" is clicked/selected, then:

This message has been edited to EN.

I think this could have been achieved with an if in a script, but the problem is how to tell the script which option has been chosen, if "ES" or "EN".

I have this:

```<code><p id="demo">This message should be edited.<p>
<a href="#" id="ES" onclick="func();">ES</a> - <a href="#" id="EN" onclick="func();">EN</a> - <a href="#" id="JP" onclick="func();">JP</a>
</code>```

And as I said, the problem is that I don't know how to tell the script what has been clicked/selected.

Thank you for any help you may give me (if possible, an explanation with or over a solution would be amazing because I want to learn and understand, not to solve this problem without being able to solve the same thing or similar in a future).

答:
var text = 'This message has been edited to ';

function func(e){
 document.getElementById('demo').innerHTML = text+e.id+'.';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p id="demo">This message should be edited.<p>
ES - EN - JP</code>```

you can pass this which works as an clicked event, from there get value and add to your result

Body:
Good evening everybody!

Well, I am studying JavaScript at the moment, and I reachead the point in where I need, based on clicked text (button, ... it doesn't matter, I guess).

For example:

This message should be edited.

Two choices: ES - EN

If choice "ES" is clicked/selected, then:

This message has been edited to ES.

Otherwise, if choice "EN" is clicked/selected, then:

This message has been edited to EN.

I think this could have been achieved with an if in a script, but the problem is how to tell the script which option has been chosen, if "ES" or "EN".

I have this:

This message should be edited.

ES - EN - JP

And as I said, the problem is that I don't know how to tell the script what has been clicked/selected.

Thank you for any help you may give me (if possible, an explanation with or over a solution would be amazing because I want to learn and understand, not to solve this problem without being able to solve the same thing or similar in a future).

Body:
var text = 'This message has been edited to ';

function func(e){
 document.getElementById('demo').innerHTML = text+e.id+'.';
}

<p id="demo">This message should be edited.<p>
<a href="#" id="ES" onclick="func(this);">ES</a> - <a href="#" id="EN" onclick="func(this);">EN</a> - <a href="#" id="JP" onclick="func(this);">JP</a>

you can pass this which works as an clicked event, from there get value and add to your result


问:
Why does my Html.DropDownList give me a list populated with "System.Web.Mvc.SelectListItem" strings?
I researched this problem on this site and found several similar questions. I tried all of the suggestions offered but apparently, there's something about my implementation or my understanding of the explanations that causes those solutions to not work. I would appreciate some guidance on how to fix this problem.

My project consists of the following ViewModel:

```<code> public SelectList MonthList { get; set; }

 public SelectList ReverseMonthsLists()
{
    var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();
    var list = new List<SelectListItem>();
    list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });

     for (int i = 1; i < stringViewOfDates.Count(); i++)
    {
        list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
    }

    var selectList = new SelectList(list);
    return selectList;
}

 public static IEnumerable<DateTime> GetDates()
{
    DateTime startDate = new DateTime(2017, 6, 1).Date;
    var currentDate = DateTime.Now.Date;

    int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;

    if (numberOfMonthsToShow == 0)
        numberOfMonthsToShow = 1;

    var dates = new List<DateTime>(numberOfMonthsToShow);
    for (int i = 0; i < numberOfMonthsToShow; i++)
    {
        dates.Add(currentDate);
        currentDate = currentDate.AddMonths(-1);
    }
    return dates;
}
</code>```

My Html view contains this statement:

```<code>@Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month
Selector")
</code>```

What am I doning wrong that's causing my dropdown list to fill with nothing but "System.Web.Mvc.SelectListItem"?

答:
did you try to set data and text fields?

ASP.NET MVC Dropdown List From SelectList

```<code>var selectList = new SelectList(list, "Value" , "Text");
</code>```

Body:
I researched this problem on this site and found several similar questions. I tried all of the suggestions offered but apparently, there's something about my implementation or my understanding of the explanations that causes those solutions to not work. I would appreciate some guidance on how to fix this problem.

My project consists of the following ViewModel:

 public SelectList MonthList { get; set; }

 public SelectList ReverseMonthsLists()
{
    var stringViewOfDates = GetDates().Select(_ => _.ToString("MMM yyyy")).ToList();
    var list = new List<SelectListItem>();
    list.Add(new SelectListItem { Selected = true, Text = stringViewOfDates[0], Value = stringViewOfDates[0] });

     for (int i = 1; i < stringViewOfDates.Count(); i++)
    {
        list.Add(new SelectListItem { Selected = false, Text = stringViewOfDates[i], Value = stringViewOfDates[i] });
    }

    var selectList = new SelectList(list);
    return selectList;
}

 public static IEnumerable<DateTime> GetDates()
{
    DateTime startDate = new DateTime(2017, 6, 1).Date;
    var currentDate = DateTime.Now.Date;

    int numberOfMonthsToShow = (currentDate.Year - startDate.Year) * 12 + currentDate.Month - startDate.Month;

    if (numberOfMonthsToShow == 0)
        numberOfMonthsToShow = 1;

    var dates = new List<DateTime>(numberOfMonthsToShow);
    for (int i = 0; i < numberOfMonthsToShow; i++)
    {
        dates.Add(currentDate);
        currentDate = currentDate.AddMonths(-1);
    }
    return dates;
}

My Html view contains this statement:

@Html.DropDownList("selectList", Model.ReverseMonthsLists(), "Month
Selector")

What am I doning wrong that's causing my dropdown list to fill with nothing but "System.Web.Mvc.SelectListItem"?

Body:
did you try to set data and text fields?

ASP.NET MVC Dropdown List From SelectList

var selectList = new SelectList(list, "Value" , "Text");


问:
How to set a window icon with PyQt5?
```<code>from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Application(QMainWindow):
    def __init__(self):
        super(Application, self).__init__()
        self.setWindowIcon(QtGui.QIcon('icon.png'))
</code>```

I am trying to set a window icon (top left of the window) but the normal icon disappeared instead.

I tried with many icon resolutions (8x8, 16x16, 32x32, 64x64) and extensions (.png and .ico).

What am I doing wrong?

答:
The answer has been given by the asker (invisible icon). I wanted to add that the script may not be executed in the script directory. In any case, to be safe, you may want to make sure the icon is loaded relative to the directory in which the script resides:</p>

```<code>import os
# [...]
scriptDir = os.path.dirname(os.path.realpath(__file__))
self.setWindowIcon(QtGui.QIcon(scriptDir + os.path.sep + 'logo.png'))
</code>```

Title: How to set a window icon with PyQt5?

Body:
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Application(QMainWindow):
    def __init__(self):
        super(Application, self).__init__()
        self.setWindowIcon(QtGui.QIcon('icon.png'))

I am trying to set a window icon (top left of the window) but the normal icon disappeared instead.

I tried with many icon resolutions (8x8, 16x16, 32x32, 64x64) and extensions (.png and .ico).

What am I doing wrong?

Body:
The answer has been given by the asker (invisible icon). I wanted to add that the script may not be executed in the script directory. In any case, to be safe, you may want to make sure the icon is loaded relative to the directory in which the script resides:

import os
# [...]
scriptDir = os.path.dirname(os.path.realpath(__file__))
self.setWindowIcon(QtGui.QIcon(scriptDir + os.path.sep + 'logo.png'))


问:
Logging response time of Zulu Proxy Request
We would like to capture the response time of every request that is handled by a Zuul Proxy Server to be used for performance monitoring. A Zuul Filter seems like the logical way of doing it but given the structure of the Zuul Filter there doesn't seem an easy way of capturing elapsed time.
Can anyone shed some light on how we could achieve this?</p>

答:
I also struggled with Zuul filters to get basic metrics.

Spring Actuator trace gives a lot of info out the box. Simply use "/trace" to view the :

timestamp

timeTaken

HTTP status code

It's prefect for Zuul

```<code>[
    {
        "timestamp": 1499429507097,
        "info": {
            "method": "GET",
            "path": "/index.html",
            "headers": {
                "request": {
                    "host": "localhost:8765",
                    "connection": "keep-alive",
                    "upgrade-insecure-requests": "1",
                    "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/58.0.3029.110 Chrome/58.0.3029.110 Safari/537.36",
                    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                    "accept-encoding": "gzip, deflate, sdch, br",
                    "accept-language": "en-US,en;q=0.8",
                    "cookie": "zbx_sessionid=02ac46186474dbd668d7abe0f78705c9"
                },
                "response": {
                    "X-Application-Context": "application:8765",
                    "Last-Modified": "Fri, 07 Jul 2017 10:52:42 GMT",
                    "Cache-Control": "no-store",
                    "Accept-Ranges": "bytes",
                    "Content-Type": "text/html",
                    "Content-Length": "446",
                    "Date": "Fri, 07 Jul 2017 12:11:47 GMT",
                    "status": "200"
                }
            },
            "timeTaken": "3"
        }
    },
</code>```

However, the standard InMemoryTraceRepository gave me stats on "/health" and even "/trace", but I am only interested in POSTS that go to Zuul. So I just extended InMemoryTraceRepository and provided it as a @Bean.

```<code>import org.springframework.boot.actuate.trace.InMemoryTraceRepository;
import org.springframework.boot.actuate.trace.Trace;

public class ZuulInMemoryTraceRepository extends InMemoryTraceRepository {

  public ZuulInMemoryTraceRepository(int maxSize) {
    setCapacity(maxSize);
  }

  public Collection<DateTimeTaken> getStats(){
    return fifo;
  }

  public void setReverse(boolean reverse) {
    super.setReverse(reverse);
  }

  @Override
  public void setCapacity(int capacity) {
    super.setCapacity(capacity);
  }

  @Override
  public List<Trace> findAll() {
    return super.findAll();
  }

  @Override
  public void add(Map<String, Object> map) {

    Object method = map.get("method");
    if (!"POST".equals(method)) {
      return;
    }
    Object timeTaken = map.get("timeTaken");//timeTaken is a String
    //log timeTaken
    super.add(map);
  }
}
</code>```

In my @Configuration I added:

```<code>@Bean
public ZuulInMemoryTraceRepository myZuulInMemoryTraceRepository() {
  return new ZuulInMemoryTraceRepository(10000);
}
</code>```

Alternatively you can add a custom object to a EvictingQueue of a fixed size in ZuulInMemoryTraceRepository. Finally expose a restful webservice to expose a the EvictingQueue like my getStats(). This json can then be used to draw a pretty response time graph.

```<code>@Override
public void add(Map<String, Object> map) {
  super.add(map);
  Object method = map.get("method");
  if (!"POST".equals(method)) {
    return;
  }
  Object timeTaken = map.get("timeTaken");//timeTaken is a String
  if (timeTaken != null) {
    synchronized (fifo) {
      //Make your own DateTimeTaken
      fifo.add(new DateTimeTaken(new Date(), timeTaken.toString()));
    }
  }
}
</code>```

In my stats @RestController:

```<code>@Autowired
ZuulInMemoryTraceRepository zuulInMemoryTraceRepository;

@RequestMapping("/stats")
public Collection<DateTimeTaken> getAll() {
  return zuulInMemoryTraceRepository.getStats();
}
</code>```

Body:
I also struggled with Zuul filters to get basic metrics.

Spring Actuator trace gives a lot of info out the box. Simply use "/trace" to view the :

timestamp

timeTaken

HTTP status code

It's prefect for Zuul

[
    {
        "timestamp": 1499429507097,
        "info": {
            "method": "GET",
            "path": "/index.html",
            "headers": {
                "request": {
                    "host": "localhost:8765",
                    "connection": "keep-alive",
                    "upgrade-insecure-requests": "1",
                    "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/58.0.3029.110 Chrome/58.0.3029.110 Safari/537.36",
                    "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
                    "accept-encoding": "gzip, deflate, sdch, br",
                    "accept-language": "en-US,en;q=0.8",
                    "cookie": "zbx_sessionid=02ac46186474dbd668d7abe0f78705c9"
                },
                "response": {
                    "X-Application-Context": "application:8765",
                    "Last-Modified": "Fri, 07 Jul 2017 10:52:42 GMT",
                    "Cache-Control": "no-store",
                    "Accept-Ranges": "bytes",
                    "Content-Type": "text/html",
                    "Content-Length": "446",
                    "Date": "Fri, 07 Jul 2017 12:11:47 GMT",
                    "status": "200"
                }
            },
            "timeTaken": "3"
        }
    },

However, the standard InMemoryTraceRepository gave me stats on "/health" and even "/trace", but I am only interested in POSTS that go to Zuul. So I just extended InMemoryTraceRepository and provided it as a @Bean.

import org.springframework.boot.actuate.trace.InMemoryTraceRepository;
import org.springframework.boot.actuate.trace.Trace;

public class ZuulInMemoryTraceRepository extends InMemoryTraceRepository {

  public ZuulInMemoryTraceRepository(int maxSize) {
    setCapacity(maxSize);
  }

  public Collection<DateTimeTaken> getStats(){
    return fifo;
  }

  public void setReverse(boolean reverse) {
    super.setReverse(reverse);
  }

  @Override
  public void setCapacity(int capacity) {
    super.setCapacity(capacity);
  }

  @Override
  public List<Trace> findAll() {
    return super.findAll();
  }

  @Override
  public void add(Map<String, Object> map) {

    Object method = map.get("method");
    if (!"POST".equals(method)) {
      return;
    }
    Object timeTaken = map.get("timeTaken");//timeTaken is a String
    //log timeTaken
    super.add(map);
  }
}

In my @Configuration I added:

@Bean
public ZuulInMemoryTraceRepository myZuulInMemoryTraceRepository() {
  return new ZuulInMemoryTraceRepository(10000);
}

Alternatively you can add a custom object to a EvictingQueue of a fixed size in ZuulInMemoryTraceRepository. Finally expose a restful webservice to expose a the EvictingQueue like my getStats(). This json can then be used to draw a pretty response time graph.

@Override
public void add(Map<String, Object> map) {
  super.add(map);
  Object method = map.get("method");
  if (!"POST".equals(method)) {
    return;
  }
  Object timeTaken = map.get("timeTaken");//timeTaken is a String
  if (timeTaken != null) {
    synchronized (fifo) {
      //Make your own DateTimeTaken
      fifo.add(new DateTimeTaken(new Date(), timeTaken.toString()));
    }
  }
}

In my stats @RestController:

@Autowired
ZuulInMemoryTraceRepository zuulInMemoryTraceRepository;

@RequestMapping("/stats")
public Collection<DateTimeTaken> getAll() {
  return zuulInMemoryTraceRepository.getStats();
}


问:
Edittext - The limit to number of characters as a function of screen size. Is it possible?
I'd like to have different limits to number of characters in Edittext. That limit must depend upon the screen size. Is it possible to do so? If yes, please share your idea.</p>

答:
Based on @idunnololz's answer I made some changes, as that version doesn't seem to work well if the cursor is not at the end of the text, nor does is account for overwriting a text selection.
I also added optionally a maximum amount of characters (so the text will not exceed the view size, nor a limited amount of characters, which ever comes first).</p>

```<code>public class TextLengthFilter implements InputFilter {

    private final static int NO_MAX_CHARACTERS = -1;

    private Paint p;
    private int maxWidth;
    private int maxCharacters;

    /**
     * A filter based on the maxWidth of the text.
     * @param p Paint used by the View
     * @param maxWidth Max width of the text (in pixels)
     */
    public TextLengthFilter(Paint p, int maxWidth) {
        this(p, maxWidth, NO_MAX_CHARACTERS);
    }

    /**
     * A filter based on the maxWidth of the text.
     * @param p Paint used by the View
     * @param maxWidth Max width of the text (in pixels)
     * @param maxCharacters Max amount of characters for the text
     */
    public TextLengthFilter(Paint p, int maxWidth, int maxCharacters) {
        this.p = p;
        this.maxWidth = maxWidth;
        this.maxCharacters = maxCharacters;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        float originalW = p.measureText(dest, 0, dest.length());
        //Calculate the amount of space that is being reclaimed by characters that are replaced
        int toBeReplacedWidth = p.breakText(dest, dstart, dend, true, originalW, null);
        float spaceLeft = (maxWidth - originalW) + toBeReplacedWidth;
        int selectionLength = (dend - dstart); //The amount of characters that are going to be replaced
        int changeLength = (end - start);

        //Check if there are more characters after the change than before.
        if (maxCharacters != NO_MAX_CHARACTERS && changeLength > selectionLength) {
            //If the length of the original text was already too many characters don't allow more to be added.
            if (dest.length() > maxCharacters) {
                return "";
            }
            int finalLength = dest.length() + changeLength - selectionLength;
            //Check if the final length, after the replacement, doesn't exceed the maximum characters
            if (finalLength > maxCharacters) {
                //if it does limit the characters to be added to not exceed the maximum
                end =  end - (finalLength - maxCharacters);
            }
        }
        //Check if the size of the characters does not exceed the maximum view width
        if (spaceLeft > 0) {
            int w = p.breakText(source, start, end, true, spaceLeft, null) ;
            //If not all characters would fit only allow the ones that do fit
            if (w != source.length())
                return source.subSequence(0, start + w);
        }
        else {
            return "";
        }

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

Body:
Based on @idunnololz's answer I made some changes, as that version doesn't seem to work well if the cursor is not at the end of the text, nor does is account for overwriting a text selection.
I also added optionally a maximum amount of characters (so the text will not exceed the view size, nor a limited amount of characters, which ever comes first).

public class TextLengthFilter implements InputFilter {

    private final static int NO_MAX_CHARACTERS = -1;

    private Paint p;
    private int maxWidth;
    private int maxCharacters;

    /**
     * A filter based on the maxWidth of the text.
     * @param p Paint used by the View
     * @param maxWidth Max width of the text (in pixels)
     */
    public TextLengthFilter(Paint p, int maxWidth) {
        this(p, maxWidth, NO_MAX_CHARACTERS);
    }

    /**
     * A filter based on the maxWidth of the text.
     * @param p Paint used by the View
     * @param maxWidth Max width of the text (in pixels)
     * @param maxCharacters Max amount of characters for the text
     */
    public TextLengthFilter(Paint p, int maxWidth, int maxCharacters) {
        this.p = p;
        this.maxWidth = maxWidth;
        this.maxCharacters = maxCharacters;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        float originalW = p.measureText(dest, 0, dest.length());
        //Calculate the amount of space that is being reclaimed by characters that are replaced
        int toBeReplacedWidth = p.breakText(dest, dstart, dend, true, originalW, null);
        float spaceLeft = (maxWidth - originalW) + toBeReplacedWidth;
        int selectionLength = (dend - dstart); //The amount of characters that are going to be replaced
        int changeLength = (end - start);

        //Check if there are more characters after the change than before.
        if (maxCharacters != NO_MAX_CHARACTERS && changeLength > selectionLength) {
            //If the length of the original text was already too many characters don't allow more to be added.
            if (dest.length() > maxCharacters) {
                return "";
            }
            int finalLength = dest.length() + changeLength - selectionLength;
            //Check if the final length, after the replacement, doesn't exceed the maximum characters
            if (finalLength > maxCharacters) {
                //if it does limit the characters to be added to not exceed the maximum
                end =  end - (finalLength - maxCharacters);
            }
        }
        //Check if the size of the characters does not exceed the maximum view width
        if (spaceLeft > 0) {
            int w = p.breakText(source, start, end, true, spaceLeft, null) ;
            //If not all characters would fit only allow the ones that do fit
            if (w != source.length())
                return source.subSequence(0, start + w);
        }
        else {
            return "";
        }

        return null;
    }
}


问:
Jquery Click this or that and toggle class
Im stuck on toggeling a class when there is a click event on either the parent or child item. It is about a navigation menu that can be clickable on the entire bar or just the icon.

Current situation: (according to the fiddle)
When you click on the red block, the class is-active will be toggled on the .hamburger-menu class. Allowing the icon to transition via CSS.
But when you click on the hamburger icon it does not toggle the class.

How can the class is-active be toggled when there is a click event on either the #menuContainer or the .hamburger-menu div?

jQuery(function($) {
  $(document).ready(function() {
    $("#menuContainer, .hamburger-menu").click(function() {
      $(".hamburger-menu").toggleClass("is-active");
    });
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.menu_container {
  display: block;
  position: absolute;
  left: 45%;
  top: 45%;
  width: 100px;
  height: 100px;
  background-color: red;
  cursor: pointer;
}

.menu_container .menu-active {
  background-color: blue;
}

.hamburger-menu {
  display: inline-block;
  position: absolute;
  left: 35%;
  top: 45%;
  margin: 0 auto;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu:hover {
  cursor: pointer;
}

.hamburger-menu span {
  display: block;
  width: 40px;
  max-width: 100%;
  height: 3px;
  background-color: #414042;
  margin-bottom: 5px;
  border-radius: 5px;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu.is-active span:nth-child(2) {
  display: none;
}

.hamburger-menu.is-active span:nth-child(1) {
  -webkit-transform: translateY(4.5px) rotate(45deg);
  -ms-transform: translateY(4.5px) rotate(45deg);
  -o-transform: translateY(4.5px) rotate(45deg);
  transform: translateY(4.5px) rotate(45deg);
}

.hamburger-menu.is-active span:nth-child(3) {
  -webkit-transform: translateY(-4.5px) rotate(-45deg);
  -ms-transform: translateY(-4.5px) rotate(-45deg);
  -o-transform: translateY(-4.5px) rotate(-45deg);
  transform: translateY(-4.5px) rotate(-45deg);
}</code>```

```

答:
The problem is that the event is propagating up to the parent when you click on the hamburger menu causing the class to toggle twice and make it look like it's not working. To fix this, you need to add e.stopPropagation(); to the click function.

jQuery(function($) {
  $(document).ready(function() {
    $("#menuContainer, .hamburger-menu").click(function(e) {
      $(".hamburger-menu").toggleClass("is-active");
      e.stopPropagation();
    });
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.menu_container {
  display: block;
  position: absolute;
  left: 45%;
  top: 45%;
  width: 100px;
  height: 100px;
  background-color: red;
  cursor: pointer;
}

.menu_container .menu-active {
  background-color: blue;
}

.hamburger-menu {
  display: inline-block;
  position: absolute;
  left: 35%;
  top: 45%;
  margin: 0 auto;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu:hover {
  cursor: pointer;
}

.hamburger-menu span {
  display: block;
  width: 40px;
  max-width: 100%;
  height: 3px;
  background-color: #414042;
  margin-bottom: 5px;
  border-radius: 5px;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu.is-active span:nth-child(2) {
  display: none;
}

.hamburger-menu.is-active span:nth-child(1) {
  -webkit-transform: translateY(4.5px) rotate(45deg);
  -ms-transform: translateY(4.5px) rotate(45deg);
  -o-transform: translateY(4.5px) rotate(45deg);
  transform: translateY(4.5px) rotate(45deg);
}

.hamburger-menu.is-active span:nth-child(3) {
  -webkit-transform: translateY(-4.5px) rotate(-45deg);
  -ms-transform: translateY(-4.5px) rotate(-45deg);
  -o-transform: translateY(-4.5px) rotate(-45deg);
  transform: translateY(-4.5px) rotate(-45deg);
}</code>```

```

Body:
Im stuck on toggeling a class when there is a click event on either the parent or child item. It is about a navigation menu that can be clickable on the entire bar or just the icon.

Current situation: (according to the fiddle)
When you click on the red block, the class is-active will be toggled on the .hamburger-menu class. Allowing the icon to transition via CSS.
But when you click on the hamburger icon it does not toggle the class.

How can the class is-active be toggled when there is a click event on either the #menuContainer or the .hamburger-menu div?

jQuery(function($) {
  $(document).ready(function() {
    $("#menuContainer, .hamburger-menu").click(function() {
      $(".hamburger-menu").toggleClass("is-active");
    });
  });
});

.menu_container {
  display: block;
  position: absolute;
  left: 45%;
  top: 45%;
  width: 100px;
  height: 100px;
  background-color: red;
  cursor: pointer;
}

.menu_container .menu-active {
  background-color: blue;
}

.hamburger-menu {
  display: inline-block;
  position: absolute;
  left: 35%;
  top: 45%;
  margin: 0 auto;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu:hover {
  cursor: pointer;
}

.hamburger-menu span {
  display: block;
  width: 40px;
  max-width: 100%;
  height: 3px;
  background-color: #414042;
  margin-bottom: 5px;
  border-radius: 5px;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu.is-active span:nth-child(2) {
  display: none;
}

.hamburger-menu.is-active span:nth-child(1) {
  -webkit-transform: translateY(4.5px) rotate(45deg);
  -ms-transform: translateY(4.5px) rotate(45deg);
  -o-transform: translateY(4.5px) rotate(45deg);
  transform: translateY(4.5px) rotate(45deg);
}

.hamburger-menu.is-active span:nth-child(3) {
  -webkit-transform: translateY(-4.5px) rotate(-45deg);
  -ms-transform: translateY(-4.5px) rotate(-45deg);
  -o-transform: translateY(-4.5px) rotate(-45deg);
  transform: translateY(-4.5px) rotate(-45deg);
}

Body:
The problem is that the event is propagating up to the parent when you click on the hamburger menu causing the class to toggle twice and make it look like it's not working. To fix this, you need to add e.stopPropagation(); to the click function.

jQuery(function($) {
  $(document).ready(function() {
    $("#menuContainer, .hamburger-menu").click(function(e) {
      $(".hamburger-menu").toggleClass("is-active");
      e.stopPropagation();
    });
  });
});

.menu_container {
  display: block;
  position: absolute;
  left: 45%;
  top: 45%;
  width: 100px;
  height: 100px;
  background-color: red;
  cursor: pointer;
}

.menu_container .menu-active {
  background-color: blue;
}

.hamburger-menu {
  display: inline-block;
  position: absolute;
  left: 35%;
  top: 45%;
  margin: 0 auto;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu:hover {
  cursor: pointer;
}

.hamburger-menu span {
  display: block;
  width: 40px;
  max-width: 100%;
  height: 3px;
  background-color: #414042;
  margin-bottom: 5px;
  border-radius: 5px;
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.hamburger-menu.is-active span:nth-child(2) {
  display: none;
}

.hamburger-menu.is-active span:nth-child(1) {
  -webkit-transform: translateY(4.5px) rotate(45deg);
  -ms-transform: translateY(4.5px) rotate(45deg);
  -o-transform: translateY(4.5px) rotate(45deg);
  transform: translateY(4.5px) rotate(45deg);
}

.hamburger-menu.is-active span:nth-child(3) {
  -webkit-transform: translateY(-4.5px) rotate(-45deg);
  -ms-transform: translateY(-4.5px) rotate(-45deg);
  -o-transform: translateY(-4.5px) rotate(-45deg);
  transform: translateY(-4.5px) rotate(-45deg);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="menuContainer" class="menu-trigger menu_container">
  <div class="hamburger-menu">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>


答:
You can pass a argument to the function for example

```<code>function fun(lang){
    If(lang === "ES"){
        Do something
    }else If(lang === "EN"){
        Do something
    }
}
</code>```

And when you call your function put something like this:

onClick="fun('ES')" or onClick="fun('EN')

NOTE: instead of If 's you could use switch statement inside your function fun(lang)

Title: How to change a text based onclick with JavaScript?

Body:
You can pass a argument to the function for example

function fun(lang){
    If(lang === "ES"){
        Do something
    }else If(lang === "EN"){
        Do something
    }
}

And when you call your function put something like this:

onClick="fun('ES')" or onClick="fun('EN')

NOTE: instead of If 's you could use switch statement inside your function fun(lang)


问:
Arangodb Tarball distribution
Is there a tarball distribution for arangoDB , to use on centos 7 ?

can I use  the github 3.1 tarball distibution? as an installation ?

any response is appreciated thank you

答:
Yes, the "Github icon" download button in arangodb.com's download area will take you to the source files (https://www.arangodb.com/download-major/source/).
You should be able to compile these on your Centos installation.

You can of course also do a git clone git://github.com/arangodb/arangodb.git, check out the branch or tag that you need and compile from there.

Title: Arangodb Tarball distribution


问:
data lookup from web service isn't displayed correctly in label
I have two calls that are being made to web services which I am attempting to display in a label on a secondary view.

First lookup or call occurs during the load of the main view controller as follows:

```<code>override func viewDidLoad() {
    super.viewDidLoad()
getAddress()
}

func getAddress() {
    let URL_GET_ADDR:String = "http://www.webserver.com/apps/getmailingaddr.php"
    let requestURL = NSURL(string: URL_GET_ADDR)
    let request = NSMutableURLRequest(url: requestURL! as URL)
    request.httpMethod = "POST"
    let task = URLSession.shared.dataTask(with: request as URLRequest){
        data, response, error in
        //exiting if there is some error
        if error != nil{
            print("error is \(error)")
            return;
        }
        //parsing the response
        do {
            //converting resonse to NSDictionary
            //var teamJSON: NSDictionary!
            self.teamJSON =  try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            //getting the JSON array teams from the response
            let address: NSArray = self.teamJSON["mailing"] as! NSArray

            //looping through all the json objects in the array teams
            for i in 0 ..< address.count{

                //getting the data at each index
                let addrName:String = (address[i] as! NSDictionary)["name"] as! String!
                let addrAddr1:String = (address[i] as! NSDictionary) ["address1"] as! String!
                let addrAddr2:String = (address[i] as! NSDictionary)["address2"] as! String!
                let addrCity:String = (address[i] as! NSDictionary)["city"] as! String!
                let addrState:String = (address[i] as! NSDictionary)["state"] as! String!
                let addrZipcode:Int = (address[i] as! NSDictionary)["zipcode"] as! Int!
            }

        } catch {
            print(error)
        }
    }
    task.resume()
}
</code>```

I am passing this data to the contacts view controller with the following:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if let ContactsViewController = segue.destination as? ContactsViewController {
   ContactsViewController.myAddress = teamJSON
}
</code>```

All is good so far.  Now in the contacts view controller I am performing a lookup of the contacts with the following:

```<code>override func viewDidLoad() {
   super.viewDidLoad()
   myLabel = ""
   // Do any additional setup after loading the view, typically from a nib.
   contactsLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
   //created NSURL
    let requestURL = NSURL(string: URL_GET_TEAMS)
    //creating NSMutableURLRequest
    let request = NSMutableURLRequest(url: requestURL! as URL)
    //setting the method to post
    request.httpMethod = "POST"
    //creating a task to send the post request
    let task = URLSession.shared.dataTask(with: request as URLRequest){
        data, response, error in
        //exiting if there is some error
        if error != nil{
            print("error is \(error)")
            return;
        }
        //parsing the response
        do {
            //converting resonse to NSDictionary
            var teamJSON: NSDictionary!
            teamJSON =  try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
            //getting the JSON array teams from the response
            let teams: NSArray = teamJSON["contacts"] as! NSArray
            //looping through all the json objects in the array teams
            for i in 0 ..< teams.count{
                //getting the data at each index
                let teamId:String = (teams[i] as! NSDictionary)["title"] as! String!
                let teamName:String = (teams[i] as! NSDictionary) ["name"] as! String!
                //displaying the data
                //print("id -> ", teamId)
                //print("name -> ", teamName)
                //print("===================")
                //print("")
                self.myLabel = self.myLabel + "<font size='5'><b>" + teamId + "</font>:</b> " + "<font size='5'>" + teamName + "</font><br /><br />"
            }
        } catch {
            print(error)
        }
        DispatchQueue.main.async {
            let attrStr = try! NSAttributedString(data: self.myLabel.data(using: String.Encoding.unicode,allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
            self.contactsLabel.attributedText = attrStr
            self.contactsLabel.sizeToFit()
        }
    }
    //executing the task
    task.resume()

    let attrStr = try! NSAttributedString(data: myLabel.data(using: String.Encoding.unicode,allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
    contactsLabel.attributedText = attrStr
    contactsLabel.sizeToFit()
    getAddress()
}
</code>```

The getAddress function call here takes the data that was passed in and adds it to the label:

```<code>func getAddress() {
    //getting the JSON array teams from the response
    let address: NSArray = myAddress["mailing"] as! NSArray
    //looping through all the json objects in the array teams
    for i in 0 ..< address.count{

        //getting the data at each index
        let addrName:String = (address[i] as! NSDictionary)["name"] as! String!
        let addrAddr1:String = (address[i] as! NSDictionary) ["address1"] as! String!
        let addrAddr2:String = (address[i] as! NSDictionary)["address2"] as! String!
        let addrCity:String = (address[i] as! NSDictionary)["city"] as! String!
        let addrState:String = (address[i] as! NSDictionary)["state"] as! String!
        let addrZipcode:Int = (address[i] as! NSDictionary)["zipcode"] as! Int!

        let myCityStateZip : String = addrCity + ", " + addrState + " " + String(addrZipcode)

        let myName : String = addrName + "<br />" + addrAddr1 + "<br />" + addrAddr2

        let myDescription : String = "*All Correspondence for the Board / Assoc.<br /> should be directed to the following address:<br /><br />"

        self.myLabel = self.myLabel + "<b><font size='5'>" + myDescription + "</font></b>"
        self.myLabel = self.myLabel + "<font size='4'>" + myName + "</font>"
        self.myLabel = self.myLabel + "<font size='4'>" + myCityStateZip + "</font>"
        self.myLabel = self.myLabel + "<br /><br />"

        let attrStr = try! NSAttributedString(data: myLabel.data(using: String.Encoding.unicode,allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
        contactsLabel.attributedText = attrStr
        contactsLabel.sizeToFit()
    }
}
</code>```

Here is the problem, first time through it works perfectly displays the data correctly and in the correct order.  If you go back out and then back into the contacts page, the address ends up at the top of the label with the contacts following.  I can't seem to figure out why this is happening.  Any ideas?

答: I would move both lookups to the front end (main view controller's viewDidLoad function) and pass them as values to the second controller.  That way your second controller only has to be concerned with formatting the data for display.</p>

Body:
I have two calls that are being made to web services which I am attempting to display in a label on a secondary view.

First lookup or call occurs during the load of the main view controller as follows:

override func viewDidLoad() {
    super.viewDidLoad()
getAddress()
}

func getAddress() {
    let URL_GET_ADDR:String = "http://www.webserver.com/apps/getmailingaddr.php"
    let requestURL = NSURL(string: URL_GET_ADDR)
    let request = NSMutableURLRequest(url: requestURL! as URL)
    request.httpMethod = "POST"
    let task = URLSession.shared.dataTask(with: request as URLRequest){
        data, response, error in
        //exiting if there is some error
        if error != nil{
            print("error is \(error)")
            return;
        }
        //parsing the response
        do {
            //converting resonse to NSDictionary
            //var teamJSON: NSDictionary!
            self.teamJSON =  try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            //getting the JSON array teams from the response
            let address: NSArray = self.teamJSON["mailing"] as! NSArray

            //looping through all the json objects in the array teams
            for i in 0 ..< address.count{

                //getting the data at each index
                let addrName:String = (address[i] as! NSDictionary)["name"] as! String!
                let addrAddr1:String = (address[i] as! NSDictionary) ["address1"] as! String!
                let addrAddr2:String = (address[i] as! NSDictionary)["address2"] as! String!
                let addrCity:String = (address[i] as! NSDictionary)["city"] as! String!
                let addrState:String = (address[i] as! NSDictionary)["state"] as! String!
                let addrZipcode:Int = (address[i] as! NSDictionary)["zipcode"] as! Int!
            }

        } catch {
            print(error)
        }
    }
    task.resume()
}

I am passing this data to the contacts view controller with the following:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
   if let ContactsViewController = segue.destination as? ContactsViewController {
   ContactsViewController.myAddress = teamJSON
}

All is good so far.  Now in the contacts view controller I am performing a lookup of the contacts with the following:

override func viewDidLoad() {
   super.viewDidLoad()
   myLabel = ""
   // Do any additional setup after loading the view, typically from a nib.
   contactsLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
   //created NSURL
    let requestURL = NSURL(string: URL_GET_TEAMS)
    //creating NSMutableURLRequest
    let request = NSMutableURLRequest(url: requestURL! as URL)
    //setting the method to post
    request.httpMethod = "POST"
    //creating a task to send the post request
    let task = URLSession.shared.dataTask(with: request as URLRequest){
        data, response, error in
        //exiting if there is some error
        if error != nil{
            print("error is \(error)")
            return;
        }
        //parsing the response
        do {
            //converting resonse to NSDictionary
            var teamJSON: NSDictionary!
            teamJSON =  try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
            //getting the JSON array teams from the response
            let teams: NSArray = teamJSON["contacts"] as! NSArray
            //looping through all the json objects in the array teams
            for i in 0 ..< teams.count{
                //getting the data at each index
                let teamId:String = (teams[i] as! NSDictionary)["title"] as! String!
                let teamName:String = (teams[i] as! NSDictionary) ["name"] as! String!
                //displaying the data
                //print("id -> ", teamId)
                //print("name -> ", teamName)
                //print("===================")
                //print("")
                self.myLabel = self.myLabel + "" + teamId + ": " + "" + teamName + "

"
            }
        } catch {
            print(error)
        }
        DispatchQueue.main.async {
            let attrStr = try! NSAttributedString(data: self.myLabel.data(using: String.Encoding.unicode,allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
            self.contactsLabel.attributedText = attrStr
            self.contactsLabel.sizeToFit()
        }
    }
    //executing the task
    task.resume()

    let attrStr = try! NSAttributedString(data: myLabel.data(using: String.Encoding.unicode,allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
    contactsLabel.attributedText = attrStr
    contactsLabel.sizeToFit()
    getAddress()
}

The getAddress function call here takes the data that was passed in and adds it to the label:

func getAddress() {
    //getting the JSON array teams from the response
    let address: NSArray = myAddress["mailing"] as! NSArray
    //looping through all the json objects in the array teams
    for i in 0 ..< address.count{

        //getting the data at each index
        let addrName:String = (address[i] as! NSDictionary)["name"] as! String!
        let addrAddr1:String = (address[i] as! NSDictionary) ["address1"] as! String!
        let addrAddr2:String = (address[i] as! NSDictionary)["address2"] as! String!
        let addrCity:String = (address[i] as! NSDictionary)["city"] as! String!
        let addrState:String = (address[i] as! NSDictionary)["state"] as! String!
        let addrZipcode:Int = (address[i] as! NSDictionary)["zipcode"] as! Int!

        let myCityStateZip : String = addrCity + ", " + addrState + " " + String(addrZipcode)

        let myName : String = addrName + "
" + addrAddr1 + "
" + addrAddr2

        let myDescription : String = "*All Correspondence for the Board / Assoc.
 should be directed to the following address:

"

        self.myLabel = self.myLabel + "" + myDescription + ""
        self.myLabel = self.myLabel + "" + myName + ""
        self.myLabel = self.myLabel + "" + myCityStateZip + ""
        self.myLabel = self.myLabel + "

"

        let attrStr = try! NSAttributedString(data: myLabel.data(using: String.Encoding.unicode,allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
        contactsLabel.attributedText = attrStr
        contactsLabel.sizeToFit()
    }
}

Here is the problem, first time through it works perfectly displays the data correctly and in the correct order.  If you go back out and then back into the contacts page, the address ends up at the top of the label with the contacts following.  I can't seem to figure out why this is happening.  Any ideas?


问:
AWS Elastic Beanstalk using PHP with Private Composer Repositories
How do I utilize private composer repositories when deploying with Amazon AWS Elastic Beanstalk in a PHP environment? Specifically using GitHub (Q & A style, answer following)</p>

答:
I struggled with this. I've got repos in AWS CodeCommit and was looking for the path of least resistance to solve it. I tried ~/.composer/auth.json but it appears that composer is run before I could get the file in place etc. etc.

I went for an approach which includes the vendor directory in my repo (get rid of .git folders within so that it doesn't treate them as submodules) and the whole thing then gets published to Elastic Beanstalk via zip file including that folder.