问:
Doesn't appear the actual error through command line in Node.js
I am trying to create an HTTP server with GET and POST, using Node.js, the user will upload images and archives. But the problem is that while trying to run the server, the command line from Node.js don't show to me the actual error, and point out to some line that doesn't exist.

Server.js

```<code>var url = require("url");
var http = require("http");
var formidable = require("formidable");

function start(route ,handle) {
function onRequest(request, response) {
    var postData = "";
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");

    request.setEncoding("utf8");

    request.addListener("data", function(postDataChunk) {
        postData += postDataChunk;
        console.log("Received POST data chunk ' " +
            postDataChunk + " ' .");
    });

request.addListener("data", function(chunk) {
    //called when a new chunk of data was received
});

request.addListener("end", function() {
    //called when all chunks of data been received
});

    request.addListener("end", function() {
    route(handle, pathname, response, postData);
    });
}

    var formidable = require('formidable'),
    http = require('http'),
    sys = require('sys');

    http.createServer(function(req,res) {
        if(req.url == '/upload' && req.method.toLowerCase() == 'POST') {
            //parse a file upload
            var form = new formidable.IncomingForm();
            form.parse(req,function(err,fields,files) {
                res.writeHead(200, {'content-type' : 'text/plain'});
                res.write('received upload \n\n');
                res.end(sys.inspect({fields : fields, files : files}));
            });
            return;
        }

        //show a file upload form
        res.writeHead(200, {'content-type' : 'text/html'});
        res.end(
        '<form action = "/upload" enctype="multipart/form-data" ' +
        'method ="post">' +
        '<input type="text" name= "title" ><br>' +
        '<input type ="file" name = "upload" multiple="multiple"<br>' +
        '<input typw="submit" value="upload"' +
        '</form>');
}).listen(8888);

exports.start = start;
</code>```

The only thing for sure is that I know that is happening in Server.js because is pointed out to there.

server.js:69 - Unexpected token )

How can I get to know where this error is ? And maybe can be a lot of other sintax errors.

答:
You're missing the closing } for the start function. Try adding that in and see if the error goes away. This is how your code should look (with correct indents to make it easier to spot errors):

```<code>var url = require("url");
var http = require("http");
var formidable = require("formidable");

function start(route ,handle) {
    function onRequest(request, response) {
        var postData = "";
        var pathname = url.parse(request.url).pathname;
        console.log("Request for " + pathname + " received.");

        request.setEncoding("utf8");

        request.addListener("data", function(postDataChunk) {
            postData += postDataChunk;
            console.log("Received POST data chunk ' " +
                postDataChunk + " ' .");
        });

        request.addListener("data", function(chunk) {
            //called when a new chunk of data was received
        });

        request.addListener("end", function() {
            //called when all chunks of data been received
        });

        request.addListener("end", function() {
        route(handle, pathname, response, postData);
        });
    }

    var formidable = require('formidable'),
    http = require('http'),
    sys = require('sys');

    http.createServer(function(req,res) {
        if(req.url == '/upload' && req.method.toLowerCase() == 'POST') {
            //parse a file upload
            var form = new formidable.IncomingForm();
            form.parse(req,function(err,fields,files) {
                res.writeHead(200, {'content-type' : 'text/plain'});
                res.write('received upload \n\n');
                res.end(sys.inspect({fields : fields, files : files}));
            });
            return;
        }

        //show a file upload form
        res.writeHead(200, {'content-type' : 'text/html'});
        res.end(
        '<form action = "/upload" enctype="multipart/form-data" ' +
        'method ="post">' +
        '<input type="text" name= "title" ><br>' +
        '<input type ="file" name = "upload" multiple="multiple"<br>' +
        '<input typw="submit" value="upload"' +
        '</form>');
    }).listen(8888);
}

exports.start = start;
</code>```

Body:
I am trying to create an HTTP server with GET and POST, using Node.js, the user will upload images and archives. But the problem is that while trying to run the server, the command line from Node.js don't show to me the actual error, and point out to some line that doesn't exist.

Server.js

var url = require("url");
var http = require("http");
var formidable = require("formidable");

function start(route ,handle) {
function onRequest(request, response) {
    var postData = "";
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");

    request.setEncoding("utf8");

    request.addListener("data", function(postDataChunk) {
        postData += postDataChunk;
        console.log("Received POST data chunk ' " +
            postDataChunk + " ' .");
    });

request.addListener("data", function(chunk) {
    //called when a new chunk of data was received
});

request.addListener("end", function() {
    //called when all chunks of data been received
});

    request.addListener("end", function() {
    route(handle, pathname, response, postData);
    });
}

    var formidable = require('formidable'),
    http = require('http'),
    sys = require('sys');

    http.createServer(function(req,res) {
        if(req.url == '/upload' && req.method.toLowerCase() == 'POST') {
            //parse a file upload
            var form = new formidable.IncomingForm();
            form.parse(req,function(err,fields,files) {
                res.writeHead(200, {'content-type' : 'text/plain'});
                res.write('received upload \n\n');
                res.end(sys.inspect({fields : fields, files : files}));
            });
            return;
        }

        //show a file upload form
        res.writeHead(200, {'content-type' : 'text/html'});
        res.end(
        '<form action = "/upload" enctype="multipart/form-data" ' +
        'method ="post">' +
        '<input type="text" name= "title" >
' +
        '<input type ="file" name = "upload" multiple="multiple"
' +
        '<input typw="submit" value="upload"' +
        '</form>');
}).listen(8888);

exports.start = start;

The only thing for sure is that I know that is happening in Server.js because is pointed out to there.

server.js:69 - Unexpected token )

How can I get to know where this error is ? And maybe can be a lot of other sintax errors.

Body:
You're missing the closing } for the start function. Try adding that in and see if the error goes away. This is how your code should look (with correct indents to make it easier to spot errors):

var url = require("url");
var http = require("http");
var formidable = require("formidable");

function start(route ,handle) {
    function onRequest(request, response) {
        var postData = "";
        var pathname = url.parse(request.url).pathname;
        console.log("Request for " + pathname + " received.");

        request.setEncoding("utf8");

        request.addListener("data", function(postDataChunk) {
            postData += postDataChunk;
            console.log("Received POST data chunk ' " +
                postDataChunk + " ' .");
        });

        request.addListener("data", function(chunk) {
            //called when a new chunk of data was received
        });

        request.addListener("end", function() {
            //called when all chunks of data been received
        });

        request.addListener("end", function() {
        route(handle, pathname, response, postData);
        });
    }

    var formidable = require('formidable'),
    http = require('http'),
    sys = require('sys');

    http.createServer(function(req,res) {
        if(req.url == '/upload' && req.method.toLowerCase() == 'POST') {
            //parse a file upload
            var form = new formidable.IncomingForm();
            form.parse(req,function(err,fields,files) {
                res.writeHead(200, {'content-type' : 'text/plain'});
                res.write('received upload \n\n');
                res.end(sys.inspect({fields : fields, files : files}));
            });
            return;
        }

        //show a file upload form
        res.writeHead(200, {'content-type' : 'text/html'});
        res.end(
        '<form action = "/upload" enctype="multipart/form-data" ' +
        'method ="post">' +
        '<input type="text" name= "title" ><br>' +
        '<input type ="file" name = "upload" multiple="multiple"<br>' +
        '<input typw="submit" value="upload"' +
        '</form>');
    }).listen(8888);
}

exports.start = start;


来源: stackexchange

问:
Prioritizing case in mysql
I want to prioritize the status part. Everything which is not repported should appear first. Regardless date. But now, It orders eveything after date. How can I prioritize the first case 'not repported part'? The rest of the list should appear after date.

```<code>SELECT * FROM list
        ORDER BY date DESC,
CASE
        WHEN `bookings`.`status` = 'Not repported'  THEN 1
        WHEN day= 'Monday' THEN 2
        WHEN day= 'Tuesday' THEN 3
        WHEN day= 'Wednesday' THEN 4
        WHEN day= 'Thursdau' THEN 5
        WHEN day= 'Friday' THEN 6
        WHEN day= 'Saturday' THEN 7 WHEN
        day= 'Sunday' THEN 8 END ASC
        limit 1,20 ";
</code>```

I want something like this.

```<code>------------------------------
DATE----DAY-------STATUS------
2011---Monday-----Not reported
2015---Sunday-----Not reported
2010---Wednedday--Not reported
2016---Monday---------Reported
2015---Monday---------Reported
2014---Tuesday--------Reported
2013---Sunday---------Reported
------------------------------
</code>```

答:
Change the order by
Something like this

```<code>SELECT * FROM list
        ORDER BY
CASE
        WHEN `bookings`.`status` = 'Not repported'  THEN 1  ELSE 2
END,

CASE
        WHEN day= 'Monday' THEN 2
        WHEN day= 'Tuesday' THEN 3
        WHEN day= 'Wednesday' THEN 4
        WHEN day= 'Thursdau' THEN 5
        WHEN day= 'Friday' THEN 6
        WHEN day= 'Saturday' THEN 7 WHEN
        day= 'Sunday' THEN 8 END ASC,

date DESC
        limit 1,20 ";
</code>```

This will give you this result

'Not repported' , 1/1/2017

'Not repported' , 3/7/2017

'Not repported' , 15/8/2017

Monday          , 6/2/2017

Monday          , 11/11/2017

ContentLicense: CC BY-SA 3.0

Title: Prioritizing case in mysql

Body:
I want to prioritize the status part. Everything which is not repported should appear first. Regardless date. But now, It orders eveything after date. How can I prioritize the first case 'not repported part'? The rest of the list should appear after date.

SELECT * FROM list
        ORDER BY date DESC,
CASE
        WHEN `bookings`.`status` = 'Not repported'  THEN 1
        WHEN day= 'Monday' THEN 2
        WHEN day= 'Tuesday' THEN 3
        WHEN day= 'Wednesday' THEN 4
        WHEN day= 'Thursdau' THEN 5
        WHEN day= 'Friday' THEN 6
        WHEN day= 'Saturday' THEN 7 WHEN
        day= 'Sunday' THEN 8 END ASC
        limit 1,20 ";

I want something like this.

------------------------------
DATE----DAY-------STATUS------
2011---Monday-----Not reported
2015---Sunday-----Not reported
2010---Wednedday--Not reported
2016---Monday---------Reported
2015---Monday---------Reported
2014---Tuesday--------Reported
2013---Sunday---------Reported
------------------------------

Body:
Change the order by
Something like this

SELECT * FROM list
        ORDER BY
CASE
        WHEN `bookings`.`status` = 'Not repported'  THEN 1  ELSE 2
END,

CASE
        WHEN day= 'Monday' THEN 2
        WHEN day= 'Tuesday' THEN 3
        WHEN day= 'Wednesday' THEN 4
        WHEN day= 'Thursdau' THEN 5
        WHEN day= 'Friday' THEN 6
        WHEN day= 'Saturday' THEN 7 WHEN
        day= 'Sunday' THEN 8 END ASC,

date DESC
        limit 1,20 ";

This will give you this result

'Not repported' , 1/1/2017

'Not repported' , 3/7/2017

'Not repported' , 15/8/2017

Monday          , 6/2/2017

Monday          , 11/11/2017


问:
Directing a Car to head for a signal by measuring signal strength
I Have a Car Robot kit, (Sunfounder Smart Video Car Kit)

and as I learn, I want to make it drive to a Beacon.

I know how to measure the signal strength,

I now want to make up an algorithm to direct the car at the beacon.

I came up with several ideas, but i don't think they are the optimal:

define t - time part - time span for quanta.

define Q - Quanta - the distance driven by the car in time 't'.

define P - Power - the signal strength

Idea 1:

Assume car is @ (0,0)

Assume Car heading @ (0,1)

Drive forward 1Q

Record A0 = P[T] - P[T-t]

Drive backward 1Q

Turn Wheels to (alpha = (constant)) degrees (cause pre-computed/measured angle)

Drive forward 1Q

Record A1 = P[T] - P[T-t]

Axis0 = b0 = (0,1)

Axis2 = b1 = (cos(alpha), sin(alpha))

D = A0*b0 + A1*b1

now i need to drive heading to D!

but this feels very slow method.

Idea2

Drive forward

if (dP < 0) drive Backward

When 'dP ~= 0' // i know i am driving perpendicular to the becon

turn 90deg right

if(dP < 0) drive backward

this is a bit better but still aint optimal, as i could make the adjustment long before i got to dP = 0

Additionally, i Can't really make sure i am doing a good 90deg turn,

my car have a turn radius (unlike a Tank bot)

Third Idea

My third idea aims being close to optimal but i didn't get it right:

Let P - Power of signal
Let D - Distance from beacon

My idea, which involves correcting my angle as i go,

Is that "when heading at the beacon, dP will descent at P(D)' rate,
so i try get there.

just to reduce the computations, i will use D instead of P and try to get D=0

CMD = FORWARD

if dD decrease (d2D < 0) => beacon is in front of me, but not directly.

so CMD = LAST RIGHT/LEFT CMD

if d2D ~= 0 CMD = FORWARD

now i am missing something if CMD=LEFT/RIGHT && it's getting worse CMD = OPPOSITE(CMD)

Go To Step 2

I tried simulating that idea, but it got me really nowhere.

can you help me formulate the algorithm please?

I created an Excel sheet to simulate,
Enter the degree of turn in the CMD column and look at the results.

答:
Can you calculate the ratio by which the signal intensity change per unit of distance ?!

Like, how much does the intensity change when I move 5cm closer to the beacon.

If you have that, you could "correct angle as you go" when the dP ratio is higher or lower to that given dPRatio.

Because that dPRatio would mean that your are going straight to the beacon !!


问:
Access to the path is denied (An exception of type 'System.UnauthorizedAccessException' occurred) after deploying to azure websites
I am downloading content from blob and storing it in the local folder of the user browsing my application. Everything is working fine without any issues locally but after deploying to App Service Web Application, I am getting access denied issue. I have tried the following options,

Option 1:

```<code>string pathString = @"D:\Test";
System.IO.Directory.CreateDirectory(pathString);
</code>```

I get access denied issue when trying to create the directory after deploying to app service web app.

Option 2:

```<code>Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
</code>```

When executing locally, it gives me the the path F:\Users\xxxx\Desktop\TestEncrypt - Copy.txt where as after deploying it does not retrieve any path.

Option 3:

```<code>System.IO.Path.GetTempPath()
</code>```

When executing locally, it gives me the following path F:\Users\xxxxx\AppData\Local\Temp\TestEncrypt.txt whereas after deploying to app service web app it give me the following path D:\local\Temp\TestEncrypt.txt
I tried creating a directory using GetTempPath but it does not create any folder

Request your valuable inputs in resolving this issue

答:
Option 1: string pathString = @"D:\Test";

The reason is that application code uses this identity for basic read-only access to the operating system drive (the D:\ drive).

Reference : Operating system functionality on Azure App Service

Option 2: Environment.GetFolderPath(Environment.SpecialFolder.Desktop)

The desktop folder format is '%systemdrive%\users\%username%\Desktop'.  According to Kudu Environment page, we can find that the systemdrive variable value is 'D:'. The username variable value is 'RD0003FF2AE3CC$'. Since Azure Web App runs in a secure environment called a sandbox, the user 'RD0003FF2AE3CC$' is a virtual user which doesn't not exist.  To prove it, we can find all the user names from Kudu Debug Console Window. Here are the users I found in Kudu.

```<code>D:\Users>dir

Directory of D:\Users

04/01/2017  11:36 PM    <DIR>          .NET v2.0
04/01/2017  11:36 PM    <DIR>          .NET v2.0 Classic
04/01/2017  11:36 PM    <DIR>          Classic .NET AppPool
06/01/2017  07:32 AM    <DIR>          OnStartAdmin
06/01/2017  07:27 AM    <DIR>          Public
06/01/2017  07:48 AM    <DIR>          SiteStorageAdmin
</code>```

Option 3: System.IO.Path.GetTempPath()

Every Azure Web App has a local directory(D:\local) which is temporary. The content in this folder will be deleted when the run is no longer running on the VM. This directory is a place to store temporary data for the application. It is not recommended to use this folder by your web application.

Reference : Azure Web App sandbox

We suggest you create a temp folder at the root of your web application folder(D:\home\site\wwwroot) and use it to store the temp data.

```<code>string tempFolder = Server.MapPath("~/TEMP");
if (!Directory.Exists(tempFolder))
{
    Directory.CreateDirectory(tempFolder);
}
</code>```

my requirement is to download the blob content into the users machine

There are 2 ways to implement your requirement.

First, you could get blob content and save it to a memory stream. After that, you could transfer this data to client using following code.

```<code>public ActionResult Download()
{
    string blobName = "abc.png";
    string containerName = "mycontainer";
    string connectionString = "";
    // Retrieve storage account from connection string.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

    // Create the blob client.
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve reference to a previously created container.
    CloudBlobContainer container = blobClient.GetContainerReference(containerName);

    // Retrieve reference to a blob named "photo1.jpg".
    CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);

    MemoryStream ms = new MemoryStream();
    // Save blob contents to a file.
    blockBlob.DownloadToStream(ms);
    ms.Position = 0;

    return File(ms, "application/octet-stream", blobName);
}
</code>```

If the blob size is very large, you could generate a URL with SAS and redirect to the URL. The client will download the file directly from the blob server.

```<code>public ActionResult Download()
{
    string blobName = "abc.png";
    string containerName = "mycontainer";
    string connectionString = "";

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
    var sasConstraints = new SharedAccessBlobPolicy();
    sasConstraints.SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5);
    sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(10);
    sasConstraints.Permissions = SharedAccessBlobPermissions.Read;

    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference(containerName);
    CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);

    var sasBlobToken = blockBlob.GetSharedAccessSignature(sasConstraints);

    var sasUrl = blockBlob.Uri + sasBlobToken;

    return Redirect(sasUrl);
}
</code>```

Body:
I am downloading content from blob and storing it in the local folder of the user browsing my application. Everything is working fine without any issues locally but after deploying to App Service Web Application, I am getting access denied issue. I have tried the following options,

Option 1:

string pathString = @"D:\Test";
System.IO.Directory.CreateDirectory(pathString);

I get access denied issue when trying to create the directory after deploying to app service web app.

Option 2:

Environment.GetFolderPath(Environment.SpecialFolder.Desktop)

When executing locally, it gives me the the path F:\Users\xxxx\Desktop\TestEncrypt - Copy.txt where as after deploying it does not retrieve any path.

Option 3:

System.IO.Path.GetTempPath()

When executing locally, it gives me the following path F:\Users\xxxxx\AppData\Local\Temp\TestEncrypt.txt whereas after deploying to app service web app it give me the following path D:\local\Temp\TestEncrypt.txt
I tried creating a directory using GetTempPath but it does not create any folder

Request your valuable inputs in resolving this issue

Body:
Option 1: string pathString = @"D:\Test";

The reason is that application code uses this identity for basic read-only access to the operating system drive (the D:\ drive).

Reference : Operating system functionality on Azure App Service

Option 2: Environment.GetFolderPath(Environment.SpecialFolder.Desktop)

The desktop folder format is '%systemdrive%\users\%username%\Desktop'.  According to Kudu Environment page, we can find that the systemdrive variable value is 'D:'. The username variable value is 'RD0003FF2AE3CC$'. Since Azure Web App runs in a secure environment called a sandbox, the user 'RD0003FF2AE3CC$' is a virtual user which doesn't not exist.  To prove it, we can find all the user names from Kudu Debug Console Window. Here are the users I found in Kudu.

D:\Users>dir

Directory of D:\Users

04/01/2017  11:36 PM    <DIR>          .NET v2.0
04/01/2017  11:36 PM    <DIR>          .NET v2.0 Classic
04/01/2017  11:36 PM    <DIR>          Classic .NET AppPool
06/01/2017  07:32 AM    <DIR>          OnStartAdmin
06/01/2017  07:27 AM    <DIR>          Public
06/01/2017  07:48 AM    <DIR>          SiteStorageAdmin

Option 3: System.IO.Path.GetTempPath()

Every Azure Web App has a local directory(D:\local) which is temporary. The content in this folder will be deleted when the run is no longer running on the VM. This directory is a place to store temporary data for the application. It is not recommended to use this folder by your web application.

Reference : Azure Web App sandbox

We suggest you create a temp folder at the root of your web application folder(D:\home\site\wwwroot) and use it to store the temp data.

string tempFolder = Server.MapPath("~/TEMP");
if (!Directory.Exists(tempFolder))
{
    Directory.CreateDirectory(tempFolder);
}

my requirement is to download the blob content into the users machine

There are 2 ways to implement your requirement.

First, you could get blob content and save it to a memory stream. After that, you could transfer this data to client using following code.

public ActionResult Download()
{
    string blobName = "abc.png";
    string containerName = "mycontainer";
    string connectionString = "";
    // Retrieve storage account from connection string.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);

    // Create the blob client.
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve reference to a previously created container.
    CloudBlobContainer container = blobClient.GetContainerReference(containerName);

    // Retrieve reference to a blob named "photo1.jpg".
    CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);

    MemoryStream ms = new MemoryStream();
    // Save blob contents to a file.
    blockBlob.DownloadToStream(ms);
    ms.Position = 0;

    return File(ms, "application/octet-stream", blobName);
}

If the blob size is very large, you could generate a URL with SAS and redirect to the URL. The client will download the file directly from the blob server.

public ActionResult Download()
{
    string blobName = "abc.png";
    string containerName = "mycontainer";
    string connectionString = "";

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString);
    var sasConstraints = new SharedAccessBlobPolicy();
    sasConstraints.SharedAccessStartTime = DateTime.UtcNow.AddMinutes(-5);
    sasConstraints.SharedAccessExpiryTime = DateTime.UtcNow.AddMinutes(10);
    sasConstraints.Permissions = SharedAccessBlobPermissions.Read;

    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    CloudBlobContainer container = blobClient.GetContainerReference(containerName);
    CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobName);

    var sasBlobToken = blockBlob.GetSharedAccessSignature(sasConstraints);

    var sasUrl = blockBlob.Uri + sasBlobToken;

    return Redirect(sasUrl);
}


问:
How do I find out which tables have no indexes in MySQL
I am dealing with a database that has about 300 tables and I am looking for a way to find all tables that have NO indexes (excluding PRIMARY). Ideally I would like to get back a result set that gives me a count of the number of indexes per table. I have tried this using a query like this:

```<code>SELECT
  table_name, column_name, index_name, count(table_name) as index_count
FROM
  information_schema.statistics
WHERE
  index_name != 'primary'
AND
  table_schema = 'your_database'
GROUP BY
  table_name
</code>```

but it does not return accurate results. any help would be appreciated

答:
bpgergo, is on to something here.

And I believe this is what you are looking for

```<code>-- ============================================================================
-- TABLES WITHOUT INDICES BUT HAVE A PRIMARY KEY
-- ============================================================================
SELECT *
FROM INFORMATION_SCHEMA.TABLES AS MAIN_TABLE
WHERE
    TABLE_SCHEMA = 'your_database'
    -- ============================================================================
    -- FIND TABLES WITH A PRIMARY KEY
    -- ============================================================================
    AND TABLE_NAME IN (
                SELECT TABLE_NAME
                FROM (
                        SELECT TABLE_NAME, INDEX_NAME, COUNT(INDEX_NAME) AS TEST
        FROM INFORMATION_SCHEMA.STATISTICS
        WHERE TABLE_SCHEMA = 'your_database'
                AND INDEX_NAME = 'PRIMARY'
        GROUP BY TABLE_NAME , INDEX_NAME) AS TAB_IND_COLS
    GROUP BY TABLE_NAME)
    -- ============================================================================
    -- FIND TABLES WITH OUT ANY INDICES
    -- ============================================================================
AND TABLE_NAME NOT IN (
        SELECT TABLE_NAME
        FROM (
                SELECT TABLE_NAME, INDEX_NAME, COUNT(INDEX_NAME) AS TEST
        FROM INFORMATION_SCHEMA.STATISTICS
        WHERE TABLE_SCHEMA = 'your_database'
                AND INDEX_NAME <> 'PRIMARY'
        GROUP BY TABLE_NAME , INDEX_NAME) AS TAB_IND_COLS
    GROUP BY TABLE_NAME
    )
;
</code>```

You will ONLY need to change your_database to get this to work.

Body:
I am dealing with a database that has about 300 tables and I am looking for a way to find all tables that have NO indexes (excluding PRIMARY). Ideally I would like to get back a result set that gives me a count of the number of indexes per table. I have tried this using a query like this:

SELECT
  table_name, column_name, index_name, count(table_name) as index_count
FROM
  information_schema.statistics
WHERE
  index_name != 'primary'
AND
  table_schema = 'your_database'
GROUP BY
  table_name

but it does not return accurate results. any help would be appreciated

Body:
bpgergo, is on to something here.

And I believe this is what you are looking for

-- ============================================================================
-- TABLES WITHOUT INDICES BUT HAVE A PRIMARY KEY
-- ============================================================================
SELECT *
FROM INFORMATION_SCHEMA.TABLES AS MAIN_TABLE
WHERE
    TABLE_SCHEMA = 'your_database'
    -- ============================================================================
    -- FIND TABLES WITH A PRIMARY KEY
    -- ============================================================================
    AND TABLE_NAME IN (
                SELECT TABLE_NAME
                FROM (
                        SELECT TABLE_NAME, INDEX_NAME, COUNT(INDEX_NAME) AS TEST
        FROM INFORMATION_SCHEMA.STATISTICS
        WHERE TABLE_SCHEMA = 'your_database'
                AND INDEX_NAME = 'PRIMARY'
        GROUP BY TABLE_NAME , INDEX_NAME) AS TAB_IND_COLS
    GROUP BY TABLE_NAME)
    -- ============================================================================
    -- FIND TABLES WITH OUT ANY INDICES
    -- ============================================================================
AND TABLE_NAME NOT IN (
        SELECT TABLE_NAME
        FROM (
                SELECT TABLE_NAME, INDEX_NAME, COUNT(INDEX_NAME) AS TEST
        FROM INFORMATION_SCHEMA.STATISTICS
        WHERE TABLE_SCHEMA = 'your_database'
                AND INDEX_NAME <> 'PRIMARY'
        GROUP BY TABLE_NAME , INDEX_NAME) AS TAB_IND_COLS
    GROUP BY TABLE_NAME
    )
;

You will ONLY need to change your_database to get this to work.


问:
sql in oracle to find ratio with grouping by a column
Can anyone please help me to find the following by using a sql in oracle

```<code>Input in oracle TableX --

ColumnA |ColumnB
1      |20
1      |10
1      |30
2      |10
2      |30
3      |20

-- Desired result

ColumnA |ColumnB  |Ratio
1    |20    |0.333333333
1    |10    |0.166666667
1    |30    |0.5
2    |10    |0.25
2    |30    |0.75
3    |20    |1

SELECT
    ColumnA,
    ColumnB,
    ColumnA/sum(ColumnB) group ColumnA by as Ratio
FROM
    TableX
GROUP BY
    ColumnA
ORDER BY
    ColumnA
</code>```

I can't figure out how to calculate percentage within the GROUP BY

+++++++++

    Explanation:

    Trying to get the ratio by grouping ColumnA

    First row results is grouping 1 from ColumnA like 20/(20+10+30) = 0.333333333

    Grouping 2 from ColumnA 10/(10+30) = 0.25

    last row result grouping 3 from ColumnA is like 20/20 = 1

```<code>Hence the sum of 0.333333333+0.166666667+0.5 = 1
sum of 0.25  + 0.75  = 1
sum of 1+0 = 1
</code>```

答:
A window function is the cleanest and gets my vote. For another perspective though, you can also use a subquery to figure out what the total value is for each COLUMNA group. Then, join that back onto your original table and use the sum to calculate your ratio.</p>

```<code>WITH SUM_TABLE AS (SELECT COLUMNA, SUM(COLUMNB) AS COLSUM FROM TABLEX GROUP BY COLUMNA)
SELECT t1.COLUMNA, t1.COLUMNB, t1.COLUMNB/st.COLSUM AS RATIO
FROM TABLEX t1 LEFT JOIN SUM_TABLE st ON st.COLUMNA = t1.COLUMNA
</code>```

Body:
Can anyone please help me to find the following by using a sql in oracle

Input in oracle TableX --

ColumnA |ColumnB
1      |20
1      |10
1      |30
2      |10
2      |30
3      |20

-- Desired result

ColumnA |ColumnB  |Ratio
1    |20    |0.333333333
1    |10    |0.166666667
1    |30    |0.5
2    |10    |0.25
2    |30    |0.75
3    |20    |1

SELECT
    ColumnA,
    ColumnB,
    ColumnA/sum(ColumnB) group ColumnA by as Ratio
FROM
    TableX
GROUP BY
    ColumnA
ORDER BY
    ColumnA

I can't figure out how to calculate percentage within the GROUP BY

+++++++++

    Explanation:

    Trying to get the ratio by grouping ColumnA

    First row results is grouping 1 from ColumnA like 20/(20+10+30) = 0.333333333

    Grouping 2 from ColumnA 10/(10+30) = 0.25

    last row result grouping 3 from ColumnA is like 20/20 = 1

Hence the sum of 0.333333333+0.166666667+0.5 = 1
sum of 0.25  + 0.75  = 1
sum of 1+0 = 1

Body:
A window function is the cleanest and gets my vote. For another perspective though, you can also use a subquery to figure out what the total value is for each COLUMNA group. Then, join that back onto your original table and use the sum to calculate your ratio.

WITH SUM_TABLE AS (SELECT COLUMNA, SUM(COLUMNB) AS COLSUM FROM TABLEX GROUP BY COLUMNA)
SELECT t1.COLUMNA, t1.COLUMNB, t1.COLUMNB/st.COLSUM AS RATIO
FROM TABLEX t1 LEFT JOIN SUM_TABLE st ON st.COLUMNA = t1.COLUMNA


问:
Do I really need foreach loop for this?! (foreach probably overkilling)
I need to get GUID of an item. I know the SiteURL, List Name and Item Name. How do I get guid of this item insead to using splistitem li in list.items and loop through each item (if li.name==myitemname then assign strguid=li.uniqueid.tostring()

Is there a way not to use foreach loop since I know the name of the item? This will save time to loop throught items.

答:
Trying the following and it seems to be working.

```<code>query.ViewAttributes = "Scope=\"Recursive\"";
</code>```

or

```<code>query.ViewAttributes = "Scope='RecursiveAll'";
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Trying the following and it seems to be working.

query.ViewAttributes = "Scope=\"Recursive\"";

or

query.ViewAttributes = "Scope='RecursiveAll'";


问:
ios Knowing when a hls livestream has played the last chunk
I do not have a problem a stream, but I do not know when it is buffering or when the stream has ended. Is there anyway to determine this in Objective-C. I have found solutions for audio and I even tried the AVPlayerItemDidPlayToEndTimeNotification but it does not work. Any suggestions? </p>

```<code>    NSString *url = liveStream.stream[@"cdn"];

    dispatch_async(dispatch_get_main_queue(), ^{
        AVPlayerItem *playerItem = [[AVPlayerItem alloc]
                                    initWithURL:[NSURL URLWithString:url]];
         [_player replaceCurrentItemWithPlayerItem:playerItem];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];

        [_player play];
    });
}

-(void)itemDidFinishPlaying:(NSNotification *) notification {

}
</code>```

答:
In addition to the notification you're using, you should use KVO to observe the rate of the avPlayer, as well as the status of the avplayer's current AVPlayer item. From observing those properties, you can make a state machine of sorts where your player view controller knows what's going on, and can recover from various changes instate. There are various player states that you have to prepare for and recover from based on the properties that you observe.

Here's an answer on how to check for buffering

Here's an example of a complete AVPLayer

And of course, here's apple's documentation on AVPlayer

Here's the documentation on AVPlayerItem

Lastly, here's the link on KVOController. You'll thank me for this later.

Body:
I do not have a problem a stream, but I do not know when it is buffering or when the stream has ended. Is there anyway to determine this in Objective-C. I have found solutions for audio and I even tried the AVPlayerItemDidPlayToEndTimeNotification but it does not work. Any suggestions?

    NSString *url = liveStream.stream[@"cdn"];

    dispatch_async(dispatch_get_main_queue(), ^{
        AVPlayerItem *playerItem = [[AVPlayerItem alloc]
                                    initWithURL:[NSURL URLWithString:url]];
         [_player replaceCurrentItemWithPlayerItem:playerItem];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(itemDidFinishPlaying:) name:AVPlayerItemDidPlayToEndTimeNotification object:playerItem];

        [_player play];
    });
}

-(void)itemDidFinishPlaying:(NSNotification *) notification {

}


问:
Android handler vs service
I have got na application that have to check a website every minute even if app is closed too. I dont know what should I use do do that. Handler or Service?
Thanks! John</p>

答: A bit late, though Handlers can be useful in this type of use case.</p>

Title: Android handler vs service


问:
Remove ith item from a C++ std::vector
How do I remove the ith item from a std::vector?

I know I want to delete the ith element. I have int i; and std::vector<process> pList; where process is a struct. I want to do something equivalent to the following:

```<code>pList.remove(i);
</code>```

答:
```<code>vector.erase(iterator)
</code>```

Where iterator is the position. You can get the first element with vector.begin() and the last one with vector.end(). Just add to the iterator to get to the desired element.
e.g.:

```<code>pList.erase(pList.begin()+6);
</code>```

to erase the 6th item.

Title: Remove ith item from a C++ std::vector

Body:
How do I remove the ith item from a std::vector?

I know I want to delete the ith element. I have int i; and std::vector<process> pList; where process is a struct. I want to do something equivalent to the following:

pList.remove(i);

Body:
vector.erase(iterator)

Where iterator is the position. You can get the first element with vector.begin() and the last one with vector.end(). Just add to the iterator to get to the desired element.
e.g.:

pList.erase(pList.begin()+6);

to erase the 6th item.


问:
After changing PHP version, Joomla cannot connect to MySQL
I have Joomla 3.3.3 in a server where PHP 5.3.29 is installed.

I requested the hosting team (Hostgator) to install PHP 5.5.28 side by side.

When they told me the task was finished, I added these lines to the top of .htaccess file:

```<code># PHP 5.5
AddHandler application/x-httpd-php55 .php
<IfModule mod_suphp.c>
suPHP_ConfigPath /opt/php55/lib
</IfModule>
</code>```

After that, I tried to load the page and this error was shown, in both front end an in administration pages:

```<code>Error displaying the error page: Application Instantiation Error: Could not connect to MySQL.
</code>```

If I remove the added lines in .htaccess, site works again.

What may be hapenning here?

答:
It may be that they haven't installed the mysql extension, you can compare the versions of php using a simple phpinfo script:

```<code><?php
phpinfo();
</code>```

Run this in your browser using both PHP 5.3 and PHP 5.5 and scroll down the the 'mysql/mysqli/mysqlnd' section which will tell you whether it's been installed with the mysql extension or not, if it hasn't been contact your host and ask them to add it.

If you're running on a vps or similar you can also check apt/dnf/yum to check for package differences:

apt list --installed | grep php

dnf list --installed | grep php

yum list installed | grep php

If you see you have a lot of packages prefixed with php53- and only a few with php55- you could ask them to install the missing packages, for example (using brew on OSX), if I list with brew there is a clear difference between packages I have installed for php56 and php71:

```<code>user@comp ~ $ brew list | grep php
php56
php56-mcrypt
php56-memcache
php56-mongo
php56-xdebug
php71
php71-xdebug
</code>```

In this situation I would ask the host to install php71-mcrypt, php71-memcache and php71-mongo or equivalents.

Body:
I have Joomla 3.3.3 in a server where PHP 5.3.29 is installed.

I requested the hosting team (Hostgator) to install PHP 5.5.28 side by side.

When they told me the task was finished, I added these lines to the top of .htaccess file:

# PHP 5.5
AddHandler application/x-httpd-php55 .php
<IfModule mod_suphp.c>
suPHP_ConfigPath /opt/php55/lib
</IfModule>

After that, I tried to load the page and this error was shown, in both front end an in administration pages:

Error displaying the error page: Application Instantiation Error: Could not connect to MySQL.

If I remove the added lines in .htaccess, site works again.

What may be hapenning here?

Body:
It may be that they haven't installed the mysql extension, you can compare the versions of php using a simple phpinfo script:

<?php
phpinfo();

Run this in your browser using both PHP 5.3 and PHP 5.5 and scroll down the the 'mysql/mysqli/mysqlnd' section which will tell you whether it's been installed with the mysql extension or not, if it hasn't been contact your host and ask them to add it.

If you're running on a vps or similar you can also check apt/dnf/yum to check for package differences:

apt list --installed | grep php

dnf list --installed | grep php

yum list installed | grep php

If you see you have a lot of packages prefixed with php53- and only a few with php55- you could ask them to install the missing packages, for example (using brew on OSX), if I list with brew there is a clear difference between packages I have installed for php56 and php71:

user@comp ~ $ brew list | grep php
php56
php56-mcrypt
php56-memcache
php56-mongo
php56-xdebug
php71
php71-xdebug

In this situation I would ask the host to install php71-mcrypt, php71-memcache and php71-mongo or equivalents.


问:
Selecting multiple columns from .dat files in a bash loop and merging them horizontally
I am pretty much a beginner at this and am having trouble with processing .dat files. I have lots of .dat files (a_"number"_b.dat) containing 4 columns each and i would like to pull out columns 2 and 4 from each of them through a for loop and merge them horizontally in a new file i.e. pick out columns every loop and add them to the file side by side. I tried using both awk|paste statements and cut|paste statements but didn't get it working at all. In the awk case i end up with a file containing columns 2 and 4 only from the last file which was read in the loop and the cut|paste gives me a blank file. Here is the code i used:

```<code>for k in {1..9}
do
awk '{print $2,$4}' a_0"$k"_b.dat > atest.dat
paste atest.dat atestf.dat > atestf.dat
#cut -f2 a_0"$k"_b.dat | paste atest.dat
#cut -f4 a_0"$k"_b.dat | paste atest.dat
done
</code>```

Example of input and output:

```<code>file 1:
1 10 100 1000
2 20 200 2000
3 30 300 3000
4 40 400 4000
file2:
5 50 500 5000
6 60 600 6000
7 70 700 7000
8 80 800 8000

output expected:
10 1000 50 5000
20 2000 60 6000
30 3000 70 7000
40 4000 80 8000
</code>```

EDIT: i forgot to mention that some files have missing rows at the bottom and i would have to leave them as blank spaces when placing columns side by side.

答:
Solution

Input

```<code>  a_1_b.dat        a_2_b.dat
      |                |
      V                V

1 10 100 1000    5 50 500 5000
2 20 200 2000    6 60 600 6000
3 30 300 3000    7 70 700 7000
4 40 400 4000    8 80 800 8000
</code>```

Script

```<code># script.sh
dat_files=( $(find -E . -type f -maxdepth 1 -regex '^.*\/a_[0-9]+_b\.dat$') )

for line_number in $(seq 1 $(wc -l < ${dat_files[0]}))
do
  for file in ${dat_files[@]}
  do
    awk -v l=$line_number 'BEGIN {ORS=" "} NR==l {print $2, $4}' "$file"
  done
  echo
done
</code>```

Script explanation

The dat_files=... line stores all matching files into an array. All the files in the array match following conditions…

Regular file (-type f)

File name matches the regex pattern ^.*\/a_[0-9]+_b\.dat$

(^.*\/a_) - Starts with a_

([0-9]+) - Followed by one or more digits

(_b) - Followed by _b

(\.dat) - Ends with .dat

The outer for loop iterates from 1 to the number of lines (wc -l) in the first matching file (${dat_files[0]}). This assumes all files have the same number of lines. So if the files have 20 lines, the outer loop iterates from 1 to 20.

The inner for loop iterates all matching files and outputs fields/columns 2 and 4, adding a space at the end of each line instead of a newline character (OFS=' ') for each iteration. This is so that fields 2 and 4 of the next file (next iteration) are to the right of the previous fields instead of below them.

That's all there is to it!

Command

```<code>./script.sh > result.txt
</code>```

Output

```<code>10 1000 50 5000
20 2000 60 6000
30 3000 70 7000
40 4000 80 8000
</code>```

Body:
I am pretty much a beginner at this and am having trouble with processing .dat files. I have lots of .dat files (a_"number"_b.dat) containing 4 columns each and i would like to pull out columns 2 and 4 from each of them through a for loop and merge them horizontally in a new file i.e. pick out columns every loop and add them to the file side by side. I tried using both awk|paste statements and cut|paste statements but didn't get it working at all. In the awk case i end up with a file containing columns 2 and 4 only from the last file which was read in the loop and the cut|paste gives me a blank file. Here is the code i used:

for k in {1..9}
do
awk '{print $2,$4}' a_0"$k"_b.dat > atest.dat
paste atest.dat atestf.dat > atestf.dat
#cut -f2 a_0"$k"_b.dat | paste atest.dat
#cut -f4 a_0"$k"_b.dat | paste atest.dat
done

Example of input and output:

file 1:
1 10 100 1000
2 20 200 2000
3 30 300 3000
4 40 400 4000
file2:
5 50 500 5000
6 60 600 6000
7 70 700 7000
8 80 800 8000

output expected:
10 1000 50 5000
20 2000 60 6000
30 3000 70 7000
40 4000 80 8000

EDIT: i forgot to mention that some files have missing rows at the bottom and i would have to leave them as blank spaces when placing columns side by side.

Body:
Solution

Input

  a_1_b.dat        a_2_b.dat
      |                |
      V                V

1 10 100 1000    5 50 500 5000
2 20 200 2000    6 60 600 6000
3 30 300 3000    7 70 700 7000
4 40 400 4000    8 80 800 8000

Script

# script.sh
dat_files=( $(find -E . -type f -maxdepth 1 -regex '^.*\/a_[0-9]+_b\.dat$') )

for line_number in $(seq 1 $(wc -l < ${dat_files[0]}))
do
  for file in ${dat_files[@]}
  do
    awk -v l=$line_number 'BEGIN {ORS=" "} NR==l {print $2, $4}' "$file"
  done
  echo
done

Script explanation

The dat_files=... line stores all matching files into an array. All the files in the array match following conditions…

Regular file (-type f)

File name matches the regex pattern ^.*\/a_[0-9]+_b\.dat$

(^.*\/a_) - Starts with a_

([0-9]+) - Followed by one or more digits

(_b) - Followed by _b

(\.dat) - Ends with .dat

The outer for loop iterates from 1 to the number of lines (wc -l) in the first matching file (${dat_files[0]}). This assumes all files have the same number of lines. So if the files have 20 lines, the outer loop iterates from 1 to 20.

The inner for loop iterates all matching files and outputs fields/columns 2 and 4, adding a space at the end of each line instead of a newline character (OFS=' ') for each iteration. This is so that fields 2 and 4 of the next file (next iteration) are to the right of the previous fields instead of below them.

That's all there is to it!

Command

./script.sh > result.txt

Output

10 1000 50 5000
20 2000 60 6000
30 3000 70 7000
40 4000 80 8000


问:
How to obfuscate files without using any external libraries?
I am currently trying to obscure the contents of files or simply txt files without using any libraries. I know that this won't be very secure at all but what I basically want is a program that asks you what the password to "encrypt" it with is, then it asks what the files name is and then it finds that file and "encrypts" it. Then another program is used to "decrypt" it so it asks for the password and filename and then "decrypts" it. I don't care about actual security so if it can be easily opened it's fine I just need it so it doesn't just open if you click the file.

On top of that I don't want it to use ANY libraries so no pycrypto or anything like that.

I am on 64 bit windows.

I also am a complete beginner in tthe world of code and only know basic things such as how to get user input, print stuff, if loops and while loops.

Thanks in advance!

答:
You can use XTEA (xTended Tiny Encryption Algorithm) by copying the python code (xTended Tiny Encryption Algorithm) code into your project, it is only 28 lines of python. It has been subjected to cryptanalysis and shown to be reasonably secure.

```<code>import struct

def crypt(key,data,iv='\00\00\00\00\00\00\00\00',n=32):
    def keygen(key,iv,n):
        while True:
            iv = xtea_encrypt(key,iv,n)
            for k in iv:
                yield ord(k)
    xor = [ chr(x^y) for (x,y) in zip(map(ord,data),keygen(key,iv,n)) ]
    return "".join(xor)

def xtea_encrypt(key,block,n=32,endian="!"):
    v0,v1 = struct.unpack(endian+"2L",block)
    k = struct.unpack(endian+"4L",key)
    sum,delta,mask = 0L,0x9e3779b9L,0xffffffffL
    for round in range(n):
        v0 = (v0 + (((v1<<4 ^ v1>>5) + v1) ^ (sum + k[sum & 3]))) & mask
        sum = (sum + delta) & mask
        v1 = (v1 + (((v0<<4 ^ v0>>5) + v0) ^ (sum + k[sum>>11 & 3]))) & mask
    return struct.pack(endian+"2L",v0,v1)

def xtea_decrypt(key,block,n=32,endian="!"):
    v0,v1 = struct.unpack(endian+"2L",block)
    k = struct.unpack(endian+"4L",key)
    delta,mask = 0x9e3779b9L,0xffffffffL
    sum = (delta * n) & mask
    for round in range(n):
        v1 = (v1 - (((v0<<4 ^ v0>>5) + v0) ^ (sum + k[sum>>11 & 3]))) & mask
        sum = (sum - delta) & mask
        v0 = (v0 - (((v1<<4 ^ v1>>5) + v1) ^ (sum + k[sum & 3]))) & mask
    return struct.pack(endian+"2L",v0,v1)
</code>```

Attribution, code from: ActiveState Code » Recipes

Body:
You can use XTEA (xTended Tiny Encryption Algorithm) by copying the python code (xTended Tiny Encryption Algorithm) code into your project, it is only 28 lines of python. It has been subjected to cryptanalysis and shown to be reasonably secure.

import struct

def crypt(key,data,iv='\00\00\00\00\00\00\00\00',n=32):
    def keygen(key,iv,n):
        while True:
            iv = xtea_encrypt(key,iv,n)
            for k in iv:
                yield ord(k)
    xor = [ chr(x^y) for (x,y) in zip(map(ord,data),keygen(key,iv,n)) ]
    return "".join(xor)

def xtea_encrypt(key,block,n=32,endian="!"):
    v0,v1 = struct.unpack(endian+"2L",block)
    k = struct.unpack(endian+"4L",key)
    sum,delta,mask = 0L,0x9e3779b9L,0xffffffffL
    for round in range(n):
        v0 = (v0 + (((v1<<4 ^ v1>>5) + v1) ^ (sum + k[sum & 3]))) & mask
        sum = (sum + delta) & mask
        v1 = (v1 + (((v0<<4 ^ v0>>5) + v0) ^ (sum + k[sum>>11 & 3]))) & mask
    return struct.pack(endian+"2L",v0,v1)

def xtea_decrypt(key,block,n=32,endian="!"):
    v0,v1 = struct.unpack(endian+"2L",block)
    k = struct.unpack(endian+"4L",key)
    delta,mask = 0x9e3779b9L,0xffffffffL
    sum = (delta * n) & mask
    for round in range(n):
        v1 = (v1 - (((v0<<4 ^ v0>>5) + v0) ^ (sum + k[sum>>11 & 3]))) & mask
        sum = (sum - delta) & mask
        v0 = (v0 - (((v1<<4 ^ v1>>5) + v1) ^ (sum + k[sum & 3]))) & mask
    return struct.pack(endian+"2L",v0,v1)

Attribution, code from: ActiveState Code » Recipes


问:
find multiple files that contains a specific word in unix and linux
Say i have list of files contain the word 'contain' in the same directory  and i want to find those files at one command . I have tried with grep command to find out like

```<code>   grep 'contain' file name
</code>```

I tried  following command also.

```<code>    locate  'contain'
    find 'contain'
    grep 'contain' file name
</code>```

Currently i am not able to find any thing . Kindly help as its very important to find the files in a one command . Currently i am not able to find any thing . Kindly help as its very important to find the files in a one command . Currently i am not able to find any thing . Kindly help as its very important to find the files in a one command .

答:
Answer is within the question.

```<code>cd to the directory.
grep –l  ‘contain’ *
</code>```

Hope it helps .

Body:
Say i have list of files contain the word 'contain' in the same directory  and i want to find those files at one command . I have tried with grep command to find out like

   grep 'contain' file name

I tried  following command also.

    locate  'contain'
    find 'contain'
    grep 'contain' file name

Currently i am not able to find any thing . Kindly help as its very important to find the files in a one command . Currently i am not able to find any thing . Kindly help as its very important to find the files in a one command . Currently i am not able to find any thing . Kindly help as its very important to find the files in a one command .

Body:
Answer is within the question.

cd to the directory.
grep –l  ‘contain’ *

Hope it helps .


问:
Maximal flow graph algorithm
Does someone know which algorithm should be used to find the maximal flow in the unoriented graph?

As far as I understand, the unoriented network here basically turns the graph into a multigraph with vertices connected by two "ordinary" ribs and two "fake" ribs, which are, for example used in the Ford-Fulkerson algorithm.

But how should I handle the case of a multigraph?

答:
If you have unoriented edge

```<code>     5
* ------ *
</code>```

then you can turn it into two oriented edges:

```<code>     5
  ------>
*         *
  <------
     5
</code>```

Ford-Fulkerson method works on such graphs perfectly.

Title: Maximal flow graph algorithm

Body:
If you have unoriented edge

     5
* ------ *

then you can turn it into two oriented edges:

     5
  ------>
*         *
  <------
     5

Ford-Fulkerson method works on such graphs perfectly.


问:
How to pause and resume animation in onPause() and onResume() in android?
I have an activity which has 16 animated buttons .Initially they are invisible.
After that I am using a for loop each button is undergoing a fade animation . The R.anim.fade xml file is present at @anim/fade.

The problem is I cant pause and resume them. I like to pause and resume them in onPause() and onResume() method of an activity.

Also is there a method to check if all animations are complete??. That is how to know that b16 button which is the last button has completed its animation??

Here is my java code.

```<code>package com.ash432.itguesses;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;

 public class hints extends AppCompatActivity
 {

private int button_arr[] = {R.id.b1, R.id.b2, R.id.b3, R.id.b4, R.id.b5,
R.id.b6, R.id.b7, R.id.b8, R.id.b9,
R.id.b10, R.id.b11, R.id.b12, R.id.b13, R.id.b14, R.id.b15, R.id.b16};

Animation anim;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hints);
    int i;
    for (i = 0; i < 16; i++)
        invisible(button_arr[i]);

   for(i=0;i<16;i++)
            anim_button(button_arr[i], 200 * (i + 1));

    }

private void invisible(int id)
{
    Button b = (Button) findViewById(id);
    b.setVisibility(View.INVISIBLE);
}

private void anim_button(int id, long duration)
{
    Button b = (Button) findViewById(id);
    anim = AnimationUtils.loadAnimation(this, R.anim.fade);
    anim.setStartOffset(duration);
    b.startAnimation(anim);
    b.setVisibility(View.VISIBLE);
}

@Override
protected void onResume()
{
   super.onResume();
}

@Override
protected void onPause()
{
    super.onPause();
}
}
</code>```

Here is my xml file

```<code>  <?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#040404"
            android:clickable="false"
            android:orientation="vertical"
            android:id="@+id/rel">

    <Button
    android:id="@+id/b1"

    android:textColor="#000000"
    android:textSize="35sp"

    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#252323"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_marginTop="19dp"
    android:gravity="center"
    android:layout_marginLeft="24dp"
    android:layout_marginStart="24dp"
    android:focusable="false"
    android:focusableInTouchMode="false"

    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:id="@+id/b2"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_marginLeft="17dp"
    android:layout_marginStart="16dp"
    android:layout_alignTop="@+id/b1"
    android:layout_toRightOf="@+id/b1"
    android:layout_toEndOf="@+id/b1"
    android:gravity="center" />

<Button
    android:id="@+id/b3"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_marginLeft="17dp"
    android:layout_marginStart="15dp"
    android:layout_alignTop="@+id/b2"
    android:layout_toRightOf="@+id/b2"
    android:layout_toEndOf="@+id/b2"
    android:gravity="center" />

<Button
    android:id="@+id/b4"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_marginLeft="17dp"
    android:layout_marginStart="17dp"
    android:layout_alignTop="@+id/b3"
    android:layout_toRightOf="@+id/b3"
    android:layout_toEndOf="@+id/b3"
    android:gravity="center" />

<Button
    android:id="@+id/b5"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_marginTop="12dp"
    android:layout_below="@+id/b1"
    android:layout_alignLeft="@+id/b1"
    android:layout_alignStart="@+id/b1"
    android:gravity="center" />

<Button
    android:id="@+id/b6"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b5"
    android:layout_alignLeft="@+id/b2"
    android:layout_alignStart="@+id/b2"
    android:gravity="center" />

<Button
    android:id="@+id/b7"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b6"
    android:layout_alignLeft="@+id/b3"
    android:layout_alignStart="@+id/b3"
    android:gravity="center" />

<Button
    android:id="@+id/b8"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b7"
    android:layout_alignLeft="@+id/b4"
    android:layout_alignStart="@+id/b4"
    android:gravity="center" />

<Button
    android:id="@+id/b9"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_marginTop="12dp"
    android:layout_below="@+id/b5"
    android:layout_alignLeft="@+id/b5"
    android:layout_alignStart="@+id/b5"
    android:gravity="center" />

<Button
    android:id="@+id/b10"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b9"
    android:layout_alignLeft="@+id/b6"
    android:layout_alignStart="@+id/b6"
    android:gravity="center" />

<Button
    android:id="@+id/b11"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b10"
    android:layout_alignLeft="@+id/b7"
    android:layout_alignStart="@+id/b7"
    android:gravity="center" />

<Button
    android:id="@+id/b12"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b11"
    android:layout_alignLeft="@+id/b8"
    android:layout_alignStart="@+id/b8"
    android:gravity="center" />

<Button
    android:id="@+id/b13"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_marginTop="12dp"
    android:layout_below="@+id/b9"
    android:layout_alignLeft="@+id/b9"
    android:layout_alignStart="@+id/b9"
    android:gravity="center" />

<Button
    android:id="@+id/b14"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b13"
    android:layout_alignLeft="@+id/b10"
    android:layout_alignStart="@+id/b10"
    android:gravity="center" />

<Button
    android:id="@+id/b15"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b14"
    android:layout_alignLeft="@+id/b11"
    android:layout_alignStart="@+id/b11"
    android:gravity="center"
    android:singleLine="false"
    android:longClickable="false" />

<Button
    android:id="@+id/b16"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b15"
    android:layout_alignLeft="@+id/b12"
    android:layout_alignStart="@+id/b12"
    android:gravity="center" />

   </RelativeLayout>
</code>```

EDIT

This is my R.anim.fade xml file . Actually I am trying to do blink animation.

```<code> <?xml version="1.0" encoding="utf-8"?>
 <set xmlns:android="http://schemas.android.com/apk/res/android"
 android:interpolator="@android:anim/accelerate_interpolator"
 >
 <alpha
    android:fromAlpha="0.0"
    android:toAlpha="1.0"
    android:duration="200"
/>
<alpha
    android:fromAlpha="1.0"
    android:toAlpha="0.0"
    android:duration="200"
/>
</set>
</code>```

答:
For easy pause/resume animation you should use Animator with minSdkVersion 19. you can see here to know how to load Animator

animator -> fade_out.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<objectAnimator
    android:propertyName="alpha"
    android:valueFrom="0"
    android:valueTo="1"
    xmlns:android="http://schemas.android.com/apk/res/android"/>
</code>```

Then for pause and resume all animations, you can do like

```<code>List<Animator> mAnimatorList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    anim_button(R.id.btn1, 4000);
    anim_button(R.id.btn2, 6000);
}

private void anim_button(int id, long duration)
{
    Button b = (Button) findViewById(id);
    Animator animator = AnimatorInflater.loadAnimator(this, R.animator.fade_out);
    animator.setTarget(b);
    animator.setDuration(duration);
    animator.start();

    mAnimatorList.add(animator);
}

@Override
protected void onPause() {
    super.onPause();
    for (Animator animator: mAnimatorList) {
        animator.pause();
    }
}

@Override
protected void onResume() {
    super.onResume();
    for (Animator animator: mAnimatorList) {
        animator.resume();
    }
}
</code>```

Body:
I have an activity which has 16 animated buttons .Initially they are invisible.
After that I am using a for loop each button is undergoing a fade animation . The R.anim.fade xml file is present at @anim/fade.

The problem is I cant pause and resume them. I like to pause and resume them in onPause() and onResume() method of an activity.

Also is there a method to check if all animations are complete??. That is how to know that b16 button which is the last button has completed its animation??

Here is my java code.

package com.ash432.itguesses;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;

 public class hints extends AppCompatActivity
 {

private int button_arr[] = {R.id.b1, R.id.b2, R.id.b3, R.id.b4, R.id.b5,
R.id.b6, R.id.b7, R.id.b8, R.id.b9,
R.id.b10, R.id.b11, R.id.b12, R.id.b13, R.id.b14, R.id.b15, R.id.b16};

Animation anim;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hints);
    int i;
    for (i = 0; i < 16; i++)
        invisible(button_arr[i]);

   for(i=0;i<16;i++)
            anim_button(button_arr[i], 200 * (i + 1));

    }

private void invisible(int id)
{
    Button b = (Button) findViewById(id);
    b.setVisibility(View.INVISIBLE);
}

private void anim_button(int id, long duration)
{
    Button b = (Button) findViewById(id);
    anim = AnimationUtils.loadAnimation(this, R.anim.fade);
    anim.setStartOffset(duration);
    b.startAnimation(anim);
    b.setVisibility(View.VISIBLE);
}

@Override
protected void onResume()
{
   super.onResume();
}

@Override
protected void onPause()
{
    super.onPause();
}
}

Here is my xml file

  <?xml version="1.0" encoding="utf-8"?>
  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:background="#040404"
            android:clickable="false"
            android:orientation="vertical"
            android:id="@+id/rel">

    <Button
    android:id="@+id/b1"

    android:textColor="#000000"
    android:textSize="35sp"

    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#252323"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_marginTop="19dp"
    android:gravity="center"
    android:layout_marginLeft="24dp"
    android:layout_marginStart="24dp"
    android:focusable="false"
    android:focusableInTouchMode="false"

    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true" />

<Button
    android:id="@+id/b2"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_marginLeft="17dp"
    android:layout_marginStart="16dp"
    android:layout_alignTop="@+id/b1"
    android:layout_toRightOf="@+id/b1"
    android:layout_toEndOf="@+id/b1"
    android:gravity="center" />

<Button
    android:id="@+id/b3"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_marginLeft="17dp"
    android:layout_marginStart="15dp"
    android:layout_alignTop="@+id/b2"
    android:layout_toRightOf="@+id/b2"
    android:layout_toEndOf="@+id/b2"
    android:gravity="center" />

<Button
    android:id="@+id/b4"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_marginLeft="17dp"
    android:layout_marginStart="17dp"
    android:layout_alignTop="@+id/b3"
    android:layout_toRightOf="@+id/b3"
    android:layout_toEndOf="@+id/b3"
    android:gravity="center" />

<Button
    android:id="@+id/b5"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_marginTop="12dp"
    android:layout_below="@+id/b1"
    android:layout_alignLeft="@+id/b1"
    android:layout_alignStart="@+id/b1"
    android:gravity="center" />

<Button
    android:id="@+id/b6"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b5"
    android:layout_alignLeft="@+id/b2"
    android:layout_alignStart="@+id/b2"
    android:gravity="center" />

<Button
    android:id="@+id/b7"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b6"
    android:layout_alignLeft="@+id/b3"
    android:layout_alignStart="@+id/b3"
    android:gravity="center" />

<Button
    android:id="@+id/b8"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b7"
    android:layout_alignLeft="@+id/b4"
    android:layout_alignStart="@+id/b4"
    android:gravity="center" />

<Button
    android:id="@+id/b9"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_marginTop="12dp"
    android:layout_below="@+id/b5"
    android:layout_alignLeft="@+id/b5"
    android:layout_alignStart="@+id/b5"
    android:gravity="center" />

<Button
    android:id="@+id/b10"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b9"
    android:layout_alignLeft="@+id/b6"
    android:layout_alignStart="@+id/b6"
    android:gravity="center" />

<Button
    android:id="@+id/b11"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b10"
    android:layout_alignLeft="@+id/b7"
    android:layout_alignStart="@+id/b7"
    android:gravity="center" />

<Button
    android:id="@+id/b12"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b11"
    android:layout_alignLeft="@+id/b8"
    android:layout_alignStart="@+id/b8"
    android:gravity="center" />

<Button
    android:id="@+id/b13"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_marginTop="12dp"
    android:layout_below="@+id/b9"
    android:layout_alignLeft="@+id/b9"
    android:layout_alignStart="@+id/b9"
    android:gravity="center" />

<Button
    android:id="@+id/b14"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b13"
    android:layout_alignLeft="@+id/b10"
    android:layout_alignStart="@+id/b10"
    android:gravity="center" />

<Button
    android:id="@+id/b15"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b14"
    android:layout_alignLeft="@+id/b11"
    android:layout_alignStart="@+id/b11"
    android:gravity="center"
    android:singleLine="false"
    android:longClickable="false" />

<Button
    android:id="@+id/b16"
    android:textColor="#000000"
    android:textSize="35sp"
    android:layout_width="55dp"
    android:layout_height="55dp"
    android:background="#FFFFFF"
    android:shadowColor="#A8A8A8"
    android:shadowDx="0"
    android:shadowDy="0"
    android:shadowRadius="5"
    android:layout_alignTop="@+id/b15"
    android:layout_alignLeft="@+id/b12"
    android:layout_alignStart="@+id/b12"
    android:gravity="center" />

   </RelativeLayout>

EDIT

This is my R.anim.fade xml file . Actually I am trying to do blink animation.

 <?xml version="1.0" encoding="utf-8"?>
 <set xmlns:android="http://schemas.android.com/apk/res/android"
 android:interpolator="@android:anim/accelerate_interpolator"
 >
 <alpha
    android:fromAlpha="0.0"
    android:toAlpha="1.0"
    android:duration="200"
/>
<alpha
    android:fromAlpha="1.0"
    android:toAlpha="0.0"
    android:duration="200"
/>
</set>

Body:
For easy pause/resume animation you should use Animator with minSdkVersion 19. you can see here to know how to load Animator

animator -> fade_out.xml

<?xml version="1.0" encoding="UTF-8"?>
<objectAnimator
    android:propertyName="alpha"
    android:valueFrom="0"
    android:valueTo="1"
    xmlns:android="http://schemas.android.com/apk/res/android"/>

Then for pause and resume all animations, you can do like

List<Animator> mAnimatorList = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    anim_button(R.id.btn1, 4000);
    anim_button(R.id.btn2, 6000);
}

private void anim_button(int id, long duration)
{
    Button b = (Button) findViewById(id);
    Animator animator = AnimatorInflater.loadAnimator(this, R.animator.fade_out);
    animator.setTarget(b);
    animator.setDuration(duration);
    animator.start();

    mAnimatorList.add(animator);
}

@Override
protected void onPause() {
    super.onPause();
    for (Animator animator: mAnimatorList) {
        animator.pause();
    }
}

@Override
protected void onResume() {
    super.onResume();
    for (Animator animator: mAnimatorList) {
        animator.resume();
    }
}


问:
Is there any python operator that equivalent to javascript triple equal?
I tried to do this but fail:

```<code>File "<input>", line 1
    1==='1'
       ^
SyntaxError: invalid syntax
</code>```

Is there any workaround?

答:
The ordinary == operator in Python already works much like the === operator in JavaScript, in that it won't do string conversions. However, it does not compare types.

```<code>>>> 1 == '1'
False
>>> 1 == 1.0
True
>>> 1 == True
True
</code>```

So we would say that Python doesn't have an exact equivalent to the JavaScript == or === operators.  The way Python uses ==, without a === operator, is the norm. JavaScript (and PHP) are a bit unusual.

This last bit about bool might be a bit surprising, but bool is a subclass of int in Python.

Body:
I tried to do this but fail:

File "<input>", line 1
    1==='1'
       ^
SyntaxError: invalid syntax

Is there any workaround?

Body:
The ordinary == operator in Python already works much like the === operator in JavaScript, in that it won't do string conversions. However, it does not compare types.

>>> 1 == '1'
False
>>> 1 == 1.0
True
>>> 1 == True
True

So we would say that Python doesn't have an exact equivalent to the JavaScript == or === operators.  The way Python uses ==, without a === operator, is the norm. JavaScript (and PHP) are a bit unusual.

This last bit about bool might be a bit surprising, but bool is a subclass of int in Python.

ContentLicense: CC BY-SA 4.0


问:
An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll Additional information: Input string was not in a correct format
```<code>        //Declaring of "Total Statements"
        double   NetSalary, PensionFundPercentage, grossSalary, TaxableAmount, MonthlySalary, Allowance, Paye, Uif, MedicalAid, totalDeduction;
        double PensionFund;

        double Other = 0;
        double.TryParse(txtOtherDeductions.Text, out Other);

        //Convert Statements
        Allowance = Convert.ToDouble(txtDeductions.Text);
        PensionFund = Convert.ToDouble(txtPenFund.Text);
        Paye = Convert.ToDouble(txtPayasUEarn.Text);
</code>```

 IM UNABLE TO CALCULTE THE SALARY AMOUNT TO AGAINST THE THE AMOUNT QUOTED

答:
Perhaps, try using NumberFormatInfo while calling Convert.ToDouble(...).
I assume NumberFormat (or lack of) it could be a reason.
For example,

```<code>txtPenFund.Text = "2.00,00"; // assuming a convenient example to get exception
double PensionFund;
PensionFund = Convert.ToDouble(txtPenFund.Text); // will throw format exception
</code>```

If I use NumberFormatInfo, I can convert the string to double as expected.

```<code>NumberFormatInfo numFormat = new NumberFormatInfo();
numFormat.NumberDecimalSeparator = ",";
numFormat.NumberGroupSeparator = ".";
// somewhere in the UI, txtPenFund is set
txtPenFund.Text = "2.00,00";

double PensionFund;
PensionFund = Convert.ToDouble(txtPenFund.Text, numFormat);
</code>```

Body:
        //Declaring of "Total Statements"
        double   NetSalary, PensionFundPercentage, grossSalary, TaxableAmount, MonthlySalary, Allowance, Paye, Uif, MedicalAid, totalDeduction;
        double PensionFund;

        double Other = 0;
        double.TryParse(txtOtherDeductions.Text, out Other);

        //Convert Statements
        Allowance = Convert.ToDouble(txtDeductions.Text);
        PensionFund = Convert.ToDouble(txtPenFund.Text);
        Paye = Convert.ToDouble(txtPayasUEarn.Text);

 IM UNABLE TO CALCULTE THE SALARY AMOUNT TO AGAINST THE THE AMOUNT QUOTED

Body:
Perhaps, try using NumberFormatInfo while calling Convert.ToDouble(...).
I assume NumberFormat (or lack of) it could be a reason.
For example,

txtPenFund.Text = "2.00,00"; // assuming a convenient example to get exception
double PensionFund;
PensionFund = Convert.ToDouble(txtPenFund.Text); // will throw format exception

If I use NumberFormatInfo, I can convert the string to double as expected.

NumberFormatInfo numFormat = new NumberFormatInfo();
numFormat.NumberDecimalSeparator = ",";
numFormat.NumberGroupSeparator = ".";
// somewhere in the UI, txtPenFund is set
txtPenFund.Text = "2.00,00";

double PensionFund;
PensionFund = Convert.ToDouble(txtPenFund.Text, numFormat);


问:
How to extract an argument of 'function' type from NSInvocation
I am writing a unit test for the function that receives a protocol as input argument.

This function that I am testing calls some method of that protocol inside.
I want to mock this protocol and that method.

To mock the protocol using OCMock I wrote the following:
id<MyProtocol> myProtocol = OCMProtocolMock(@protocol(MyProtocol));

Now to mock the function I am using OCMStub.
The interesting part is that the function doesn't return any value but rather gets the callback as input argument and invokes it.
Here is its signature:
- (void)myFunction:(void (^ _Nonnull)(NSDictionary<NSString *, NSString *> * _Nonnull))completion;

I am writing the following code to mock this function:

OCMStub([myProtocol myFunction:[OCMArg any]])._andDo(^(NSInvocation *invocation){
        void (^ _Nonnull)(NSDictionary<NSString *, NSString *> * _Nonnull) completion;
        [invocation getArgument:&completion atIndex:0];
        // Here I will invoke the completion callback with some dictionary and invoke the invocation
    });

However I am getting the following error: "Expected identifer or '('". The error points to the line that defines completion variable.

How can I define the function variable of signature void (^ _Nonnull)(NSDictionary<NSString *, NSString *> * _Nonnull)?

答:
That ain't a function.  It is a block!

Regardless, both functions and blocks can be treated as void * in declarations.  You'll need to cast them to the appropriate type after.

But that's probably the easiest way to deal with it;  extract from the invocation as a void*, cast to a block, call it.


问:
How to create a duplex connection using TcpListener and TcpClient?
I have a situation where I need to send and receive information parallelly.

My protocol can define a read port and a write port.

I currently have the following code:

```<code>public void Listen()
{
    ThreadPool.SetMinThreads(50, 50);
    listener.Start();

    while (true)
    {
        var context = new ListeningContext(listener.AcceptTcpClient(), WritePort);
    }
}
</code>```

How can I create another listener from the TcpClient I am passing?

答: TCP connection is a full-duplex pipe, take a look here. You don't need a separate port or anything else.

Body:
I have a situation where I need to send and receive information parallelly.

My protocol can define a read port and a write port.

I currently have the following code:

public void Listen()
{
    ThreadPool.SetMinThreads(50, 50);
    listener.Start();

    while (true)
    {
        var context = new ListeningContext(listener.AcceptTcpClient(), WritePort);
    }
}

How can I create another listener from the TcpClient I am passing?


问:
How to automatically update a property inside a js .map
I have a mapped array which renders some buttons. Then a back and next button (outside of the map). When I click next I want it to update the URL route.  It changes component and shows the next button on the screen but does not change the URL route. I am guessing that inside NavLink - I need the 'to' property to update when the next/back buttons are clicked. Any suggestions where to start with this?</p>

```<code>const debug = require("debug")("components:Letterindex")
const React = require("react")
const { connect } = require("react-redux")
const request = require("superagent")
const { Link, Redirect } = require("react-router")

const NavLink = require("./NavLink.js")

class Letterindex extends React.Component {

  constructor(){
    super()
    this.nextButton = this.nextButton.bind(this)
    this.previousButton = this.previousButton.bind(this)
  }

  handleClick(e) {
    e.preventDefault()
  }

  nextButton(letter,letters,dispatch){
    const id = letters.findIndex(item =>{
      return item.id ===letter.id
    })
    if(id === (letters.length -1)){
      dispatch({
        type: "RENDER_LETTER",
        payload: letters[0],
      })
    }
    else {
      return (
        dispatch({
          type: "RENDER_LETTER",
          payload: letters[id+1],
        })
      )
    }
  }

  previousButton(letter,letters,dispatch){
    const id = letters.findIndex(item =>{
      return item.id ===letter.id
    })
    if(id === 0){
      dispatch({
        type: "RENDER_LETTER",
        payload: letters[letters.length-1],
      })
    }
    else {
      return (
        dispatch({
          type: "RENDER_LETTER",
          payload: letters[id-1],
        })
       )
     }
   }

  render() {
debug(this.props)
const { dispatch, letters, letter } = this.props
return (
  <div className="row">
    <div className="col-sm-12">

      <img id="back" src="../../images/back.gif" alt="back button"
        onClick={()=>
        this.previousButton(letter, letters, dispatch)}
      />
    {
      letters.map((letter) => {

        return (
          <NavLink
            key={letter.id}
            to={`/letterindex/${letter.capital}`}
            activeClassName="active">
            <div
              className="btn-group btn-group-lg btn-group-center wiggle-me"
              role="group"
              aria-label="...">

              <button
                type="button"
                className="btn"
                onClick={() =>
                    dispatch({
                      type: "RENDER_LETTER",
                      payload: letter,
                    })
                }>
              {letter.capital}
              </button>
            </div>
          </NavLink>
        )
      })
    }

    <img id="next" src="../../images/next.gif" alt="next button"
      onClick={()=>
        this.nextButton(letter, letters, dispatch)}
    />
    {this.props.children}

    </div>
  </div>
    )
  }
}

module.exports = connect(state => state)(Letterindex)
</code>```

答:
Added a router push to the dispatch in each letter function:

```<code>  this.props.router.push(`/letterindex/${letters[0].capital}`)
</code>```

Full code for the button here:

```<code>  nextButton(letter,letters,dispatch){
const id = letters.findIndex(item =>{
  return item.id ===letter.id
})
if(id === (letters.length -1)){
  this.props.router.push(`/letterindex/${letters[0].capital}`)
  dispatch({
    type: "RENDER_LETTER",
    payload: letters[0],
  })
}
else {
  this.props.router.push(`/letterindex/${letters[id+1].capital}`)
    dispatch({
      type: "RENDER_LETTER",
      payload: letters[id+1],
    })
}
</code>```

}

Body:
I have a mapped array which renders some buttons. Then a back and next button (outside of the map). When I click next I want it to update the URL route.  It changes component and shows the next button on the screen but does not change the URL route. I am guessing that inside NavLink - I need the 'to' property to update when the next/back buttons are clicked. Any suggestions where to start with this?

const debug = require("debug")("components:Letterindex")
const React = require("react")
const { connect } = require("react-redux")
const request = require("superagent")
const { Link, Redirect } = require("react-router")

const NavLink = require("./NavLink.js")

class Letterindex extends React.Component {

  constructor(){
    super()
    this.nextButton = this.nextButton.bind(this)
    this.previousButton = this.previousButton.bind(this)
  }

  handleClick(e) {
    e.preventDefault()
  }

  nextButton(letter,letters,dispatch){
    const id = letters.findIndex(item =>{
      return item.id ===letter.id
    })
    if(id === (letters.length -1)){
      dispatch({
        type: "RENDER_LETTER",
        payload: letters[0],
      })
    }
    else {
      return (
        dispatch({
          type: "RENDER_LETTER",
          payload: letters[id+1],
        })
      )
    }
  }

  previousButton(letter,letters,dispatch){
    const id = letters.findIndex(item =>{
      return item.id ===letter.id
    })
    if(id === 0){
      dispatch({
        type: "RENDER_LETTER",
        payload: letters[letters.length-1],
      })
    }
    else {
      return (
        dispatch({
          type: "RENDER_LETTER",
          payload: letters[id-1],
        })
       )
     }
   }

  render() {
debug(this.props)
const { dispatch, letters, letter } = this.props
return (

        this.previousButton(letter, letters, dispatch)}
      />
    {
      letters.map((letter) => {

        return (
          <NavLink
            key={letter.id}
            to={`/letterindex/${letter.capital}`}
            activeClassName="active">

              <button
                type="button"
                className="btn"
                onClick={() =>
                    dispatch({
                      type: "RENDER_LETTER",
                      payload: letter,
                    })
                }>
              {letter.capital}
              </button>

          </NavLink>
        )
      })
    }

        this.nextButton(letter, letters, dispatch)}
    />
    {this.props.children}

    )
  }
}

module.exports = connect(state => state)(Letterindex)

Body:
Added a router push to the dispatch in each letter function:

  this.props.router.push(`/letterindex/${letters[0].capital}`)

Full code for the button here:

  nextButton(letter,letters,dispatch){
const id = letters.findIndex(item =>{
  return item.id ===letter.id
})
if(id === (letters.length -1)){
  this.props.router.push(`/letterindex/${letters[0].capital}`)
  dispatch({
    type: "RENDER_LETTER",
    payload: letters[0],
  })
}
else {
  this.props.router.push(`/letterindex/${letters[id+1].capital}`)
    dispatch({
      type: "RENDER_LETTER",
      payload: letters[id+1],
    })
}

}


问:
Python: printing strings from another file
I want to call a file, erase its data, write new lines and print it.
Below is my program and its output.

```<code>from sys import argv
string, filename = argv
text = open(filename, 'w+')
text.truncate()
line1 = "hey"
line2 = "I was doing just fine before I met you"
line3 = "I drink too much and that's an issue but I'm okay"
text.write('%s\n%s\n%s\n' %(line1, line2, line3))
new = text.read()
old = text.readlines()
print "%s" %(new)
print old
print text.readlines()
text.close()
</code>```

Output:

[]
[]

答:
So adding seek(0) will do the job here.
seek(0) set the pointer at the beginning.
Here's the working code:

```<code>    from sys import argv
    string, filename = argv

    text = open(filename, 'w+')
    text.truncate()

    line1 = "hey"
    line2 = "I was doing just fine before I met you"
    line3 = "I drink too much and that's an issue but I'm okay"

    text.write('%s\n%s\n%s\n' %(line1, line2, line3))
    text.seek(0)
    new = text.read()
    text.seek(0)
    old = text.readlines()
    print "%s" %(new)
    print old
    text.seek(0)
    print text.readlines()

    text.close()
</code>```

Output:

hey
I was doing just fine before I met you
I drink too much and that's an issue but I'm okay

['hey\n', 'I was doing just fine before I met you\n', "I drink too much and that's an issue but I'm okay\n"]
['hey\n', 'I was doing just fine before I met you\n', "I drink too much and that's an issue but I'm okay\n"]

Body:
I want to call a file, erase its data, write new lines and print it.
Below is my program and its output.

from sys import argv
string, filename = argv
text = open(filename, 'w+')
text.truncate()
line1 = "hey"
line2 = "I was doing just fine before I met you"
line3 = "I drink too much and that's an issue but I'm okay"
text.write('%s\n%s\n%s\n' %(line1, line2, line3))
new = text.read()
old = text.readlines()
print "%s" %(new)
print old
print text.readlines()
text.close()

Output:

[]
[]

Body:
So adding seek(0) will do the job here.
seek(0) set the pointer at the beginning.
Here's the working code:

    from sys import argv
    string, filename = argv

    text = open(filename, 'w+')
    text.truncate()

    line1 = "hey"
    line2 = "I was doing just fine before I met you"
    line3 = "I drink too much and that's an issue but I'm okay"

    text.write('%s\n%s\n%s\n' %(line1, line2, line3))
    text.seek(0)
    new = text.read()
    text.seek(0)
    old = text.readlines()
    print "%s" %(new)
    print old
    text.seek(0)
    print text.readlines()

    text.close()

Output:

hey
I was doing just fine before I met you
I drink too much and that's an issue but I'm okay

['hey\n', 'I was doing just fine before I met you\n', "I drink too much and that's an issue but I'm okay\n"]
['hey\n', 'I was doing just fine before I met you\n', "I drink too much and that's an issue but I'm okay\n"]


答: Closest would maybe be the is operator. It returns True only if both variables point to the same object.

Title: Is there any python operator that equivalent to javascript triple equal?