问:
Selenium code to open facebook messenger and send a message
I'm just starting to learn a little bit of Selenium scripting (in Java). Currently I'm trying to open a chat box in Facebook and send a message.

I have gotten up to being able to open the chat box through selenium, however I can't figure out how to actually type things into the text box.

Currently here is my code:

```<code>import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

public class practice {
    public static void main(String[] args) throws InterruptedException {
      System.setProperty("webdriver.chrome.driver", "C:/max/chromedriver.exe");

      WebDriver driver = new ChromeDriver();
      driver.get("http://facebook.com/login/");
      driver.manage().window().maximize();
      driver.findElement(By.name("email")).sendKeys("myemail@yahoo.com");
      driver.findElement(By.name("pass")).sendKeys("myPassword");
      driver.findElement(By.id("loginbutton")).click();
      driver.findElement(By.name("mercurymessages")).click();
      driver.findElement(By.cssSelector("a[href*='https://www.facebook.com/messages/conversation-8148306']")).click();
     // This has worked randomly. Sometimes the driver will work and open the chat box. Sometimes it will say element not found. I didn't include the full link of the conversation because apparently you don't have to. And it has worked like this in the past.
}
}
</code>```

My current issue I'd like resolved is: why does this only work sometimes, and how do i find the text box area on the chat box? I did an Inspect Element and the chat box is very odd. It doesn't have anything like an id or a name, so i can't do By.id, or By.name. I can't figure out how to do it with By.cssSelector. This is what the inspect element for the text box looks like:

```<code>textarea class="uiTextareaAutogrow _552m" data-ft=".... more stuff here" onkeydown=" more stuff here" style= "more stuff here."
</code>```

答:
How to send message to your friend on Facebook:: Using Selenium WebDriver</p>

```<code>// Find Username and Enter
        driver.findElement(By.id("email")).sendKeys("Email");
        System.out.println("Email");

        // Find Password and Enter
        driver.findElement(By.id("pass")).sendKeys("Password");
        System.out.println("Password");

        // Click Login
        driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
        driver.findElement(By.xpath(".//*[@id='u_0_q']")).click();
        System.out.println("LogIn Successfull");
        Thread.sleep(2000);

        // Message
        driver.findElement(By.xpath(".//*[@id='u_0_f']/a/div")).click();
        driver.findElement(By
                .xpath(".//*[@id='u_0_f']/div/div[3]/div/div[1]/div/div/ul/li[2]/a/div/div[2]/div/div[2]/div/div[1]/strong/span"))
                .click();

        Thread.sleep(2000);

        driver.findElement(By.xpath("//*[@class='_1mf _1mj']//following :: div[11]")).click();
        Thread.sleep(2000);
        WebElement sendmsg = driver
                .findElement(By.xpath("//div[@class='_1ia']/descendant::div[@class='_5rpu' and @role='combobox']"));
        sendmsg.sendKeys("Just testing: using selenium webdriver" + Keys.ENTER);
</code>```

Body:
I'm just starting to learn a little bit of Selenium scripting (in Java). Currently I'm trying to open a chat box in Facebook and send a message.

I have gotten up to being able to open the chat box through selenium, however I can't figure out how to actually type things into the text box.

Currently here is my code:

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

public class practice {
    public static void main(String[] args) throws InterruptedException {
      System.setProperty("webdriver.chrome.driver", "C:/max/chromedriver.exe");

      WebDriver driver = new ChromeDriver();
      driver.get("http://facebook.com/login/");
      driver.manage().window().maximize();
      driver.findElement(By.name("email")).sendKeys("myemail@yahoo.com");
      driver.findElement(By.name("pass")).sendKeys("myPassword");
      driver.findElement(By.id("loginbutton")).click();
      driver.findElement(By.name("mercurymessages")).click();
      driver.findElement(By.cssSelector("a[href*='https://www.facebook.com/messages/conversation-8148306']")).click();
     // This has worked randomly. Sometimes the driver will work and open the chat box. Sometimes it will say element not found. I didn't include the full link of the conversation because apparently you don't have to. And it has worked like this in the past.
}
}

My current issue I'd like resolved is: why does this only work sometimes, and how do i find the text box area on the chat box? I did an Inspect Element and the chat box is very odd. It doesn't have anything like an id or a name, so i can't do By.id, or By.name. I can't figure out how to do it with By.cssSelector. This is what the inspect element for the text box looks like:

textarea class="uiTextareaAutogrow _552m" data-ft=".... more stuff here" onkeydown=" more stuff here" style= "more stuff here."

Body:
How to send message to your friend on Facebook:: Using Selenium WebDriver

// Find Username and Enter
        driver.findElement(By.id("email")).sendKeys("Email");
        System.out.println("Email");

        // Find Password and Enter
        driver.findElement(By.id("pass")).sendKeys("Password");
        System.out.println("Password");

        // Click Login
        driver.manage().timeouts().implicitlyWait(2, TimeUnit.SECONDS);
        driver.findElement(By.xpath(".//*[@id='u_0_q']")).click();
        System.out.println("LogIn Successfull");
        Thread.sleep(2000);

        // Message
        driver.findElement(By.xpath(".//*[@id='u_0_f']/a/div")).click();
        driver.findElement(By
                .xpath(".//*[@id='u_0_f']/div/div[3]/div/div[1]/div/div/ul/li[2]/a/div/div[2]/div/div[2]/div/div[1]/strong/span"))
                .click();

        Thread.sleep(2000);

        driver.findElement(By.xpath("//*[@class='_1mf _1mj']//following :: div[11]")).click();
        Thread.sleep(2000);
        WebElement sendmsg = driver
                .findElement(By.xpath("//div[@class='_1ia']/descendant::div[@class='_5rpu' and @role='combobox']"));
        sendmsg.sendKeys("Just testing: using selenium webdriver" + Keys.ENTER);


来源: stackexchange

问:
URL rewriting not working in Express 4.14.1
I've found in quite a few SO posts that in order to rewrite a URL in Express 4 I would do something like the following:

```<code>router.use('/one/:someId', (req, res, next) => {
    req.url = `/two/${req.params.someId}`;
    next();
});

router.get('/one/:someId', (req, res) => {
    res.send("reached /one/:someId");
});

router.get('/two/:someId', (req, res) => {
    res.send("reached /two/:someId");
});
</code>```

But when I try this, not only does the URL does not change to my expected "/two/some integer" and stays being "/one/some integer" but it gets to the 404 - Not Found page I have set up in my app file.

This routes are in a router file and I have also tried setting the URL to:

```<code>req.url = `/routerPath/two/${req.params.someId}`;
</code>```

but the result is exactly the same.

So what could I be missing?

Thank you.

答:
You have to distinguish two kinds of redirects:

Internal redirects work on the server, without the client noticing. They are a convenience for your server programming and never necessary - you could always introduce a helper method that gets called by all endpoints.

HTTP redirects advise the client (e.g. a web browser) to go to a different URL. Since you expect the URL to change, that's the one you want.

Simply call res.redirect, making sure to encode special characters:

```<code>router.get('/one/:someId', (req, res) => {
    res.redirect(`/two/${encodeURIComponent(req.params.someId)}`);
});

router.get('/two/:someId', (req, res) => {
    res.render("reached /two/:someId");
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've found in quite a few SO posts that in order to rewrite a URL in Express 4 I would do something like the following:

router.use('/one/:someId', (req, res, next) => {
    req.url = `/two/${req.params.someId}`;
    next();
});

router.get('/one/:someId', (req, res) => {
    res.send("reached /one/:someId");
});

router.get('/two/:someId', (req, res) => {
    res.send("reached /two/:someId");
});

But when I try this, not only does the URL does not change to my expected "/two/some integer" and stays being "/one/some integer" but it gets to the 404 - Not Found page I have set up in my app file.

This routes are in a router file and I have also tried setting the URL to:

req.url = `/routerPath/two/${req.params.someId}`;

but the result is exactly the same.

So what could I be missing?

Thank you.

Body:
You have to distinguish two kinds of redirects:

Internal redirects work on the server, without the client noticing. They are a convenience for your server programming and never necessary - you could always introduce a helper method that gets called by all endpoints.

HTTP redirects advise the client (e.g. a web browser) to go to a different URL. Since you expect the URL to change, that's the one you want.

Simply call res.redirect, making sure to encode special characters:

router.get('/one/:someId', (req, res) => {
    res.redirect(`/two/${encodeURIComponent(req.params.someId)}`);
});

router.get('/two/:someId', (req, res) => {
    res.render("reached /two/:someId");
});


问:
Querying a SQL table column that contains JSON and updating a value in that JSON based on a condition
This table has about 1.5 million rows. A particular column contains JSON. What I need to do is query that column for that JSON and then query for a particular boolean key/pair "FLAG" in that JSON. If that "FLAG" is True, I'll need to update another key/pair in that JSON to a Null value rather than the string that it currently is.

The tricksy part of this for me is that I have to query the JSON itself and run the check. But it's not like I can index the JSON like in other languages, it's effectively a string that I'm going to need to query via sql-regex. I'm also a bit confused as to how I will surgically update the second key/pair to a null.

```<code> Json Start:
 {
    "flag": true,
    "anotherKvP": "some string"
 }
 How I need the Json to be updated to:
 {
    "flag": true
    "anotherKvP": null
 }
</code>```

答:
So I ended up coming across a function called STUFF ( character_expression , start , length , replaceWith_expression ) which allowed me to jam together a string within a string. That's the second part.

The first part, in my FROM clause, I selected the value's index I needed to split on using PATINDEX ( '%pattern%' , expression ) to gather the starting index of the patterned position.

Lastly, the WHERE and LIKE was used to pattern match the query for the  "flag": true.

Body:
This table has about 1.5 million rows. A particular column contains JSON. What I need to do is query that column for that JSON and then query for a particular boolean key/pair "FLAG" in that JSON. If that "FLAG" is True, I'll need to update another key/pair in that JSON to a Null value rather than the string that it currently is.

The tricksy part of this for me is that I have to query the JSON itself and run the check. But it's not like I can index the JSON like in other languages, it's effectively a string that I'm going to need to query via sql-regex. I'm also a bit confused as to how I will surgically update the second key/pair to a null.

 Json Start:
 {
    "flag": true,
    "anotherKvP": "some string"
 }
 How I need the Json to be updated to:
 {
    "flag": true
    "anotherKvP": null
 }


问:
Extract specific text out of bash variable containing TSV string
I have the following TSV and newlines string assigned to a variable in bash:

```<code>TAGS    Product3    qwerty  text    Desc3
TAGS    Product1    qwerty  text    Desc1
TAGS    Product2    qwerty  text    Desc2
</code>```

I would like to extract the last column to a new string, and it has to be product ordered by my product input, for example:

Product1,Product2,Product3 will have to output: Desc1,Desc2,Desc3

What would be the best approach to accomplish this?

答:
Here's a function that I suppose should do it:

```<code>get_descriptions() {
    local tsvstring="$1"
    local prodnames="$2"
    local result=()
    # read tsv line by line, splitting into variables
    while IFS=$'\t' read -r tags prodname val1 val2 desc || [[ -n ${prodname} && -n ${desc} ]]; do
        # check if the line matches the query, and if, append to array
        if grep -iq "${prodname}" <<< "${prodnames}"; then
            result+=("${desc}")
        fi
    done <<< "${tsvstring}"
    # echo the result-array with field separator set to comma
    echo $(IFS=,; echo "${result[*]}")
}
</code>```

Then you can just use it like:

```<code>get_descriptions "${tsv_string_var}" "product1,product2"
</code>```

Body:
I have the following TSV and newlines string assigned to a variable in bash:

TAGS    Product3    qwerty  text    Desc3
TAGS    Product1    qwerty  text    Desc1
TAGS    Product2    qwerty  text    Desc2

I would like to extract the last column to a new string, and it has to be product ordered by my product input, for example:

Product1,Product2,Product3 will have to output: Desc1,Desc2,Desc3

What would be the best approach to accomplish this?

Body:
Here's a function that I suppose should do it:

get_descriptions() {
    local tsvstring="$1"
    local prodnames="$2"
    local result=()
    # read tsv line by line, splitting into variables
    while IFS=$'\t' read -r tags prodname val1 val2 desc || [[ -n ${prodname} && -n ${desc} ]]; do
        # check if the line matches the query, and if, append to array
        if grep -iq "${prodname}" <<< "${prodnames}"; then
            result+=("${desc}")
        fi
    done <<< "${tsvstring}"
    # echo the result-array with field separator set to comma
    echo $(IFS=,; echo "${result[*]}")
}

Then you can just use it like:

get_descriptions "${tsv_string_var}" "product1,product2"


问:
Can we deploy a C# 7 web app to Azure using Kudu?
Since Visual Studio 2017 is released and we can use the new C# 7 features I expected this will work when deploying on Azure Web apps.

Unfortunately we're seeing compile errors when using continuous deployment (kudu git deploy) so it seems Azure doesn't support the new toolchain yet.

Is there anything we can do to get this to work now (besides publishing the assemblies directly)?

答:
since we don't yet have msbuild15 in Azure.
if you want to use c#7 features with continuous integration, you may need some workaround

for dotnet core web solution, you can build it in Azure out of the box. (it uses its own dotnet msbuild.dll) [repository sample]

for asp.net web solution, you need to add Microsoft.Net.Compilers 2.0+ nuget package to the project where the new language feature is applied. For example, if a class library in the solution is using the new syntax, you need to add nuget package to that lib project. (the new c# compiler is thus imported if you refer this nuget package) [repository sample]

finally for mixed solution (dotnet core web app + .NET framework class lib), you need to run nuget restore for the .NET framework lib project independently since dotnet restore is not backwards compatible, it cannot retore project from the old build system. I did this by hacking my deploy.cmd [repository sample]

these workarounds either try to

imitate msbuild15 (case1: dotnet msbuild.dll, case2: compiler as a nuget package)

or imitate nuget4.0 (case 3: run both dotnet restore and nuget3.5 restore)

we are in the process of building these tools for Azure, they should be out soon. you can stay updated on github


问:
all group members but the current row
I've got a grouped data frame, like so:

```<code>df <- data.frame(group = rep(1:4, each=3),
                 lets = rep(LETTERS[1:4], times=3))
</code>```

For each row I would now like to identify all lets within the same group other than the lets of the row itself. Using dplyr I can get all lets thus:

```<code>df %>%
  group_by(group) %>%
  mutate(all_lets_in_group = paste(lets, collapse=','))
</code>```

But how do I exclude the lets of the current row from what I feed into paste()?

答:
The purpose of this task is not very clear, so the code clarity thus suffers as well, but still:

```<code>library(tidyverse)

df %>%
  group_by(group) %>%
  mutate(
    all_lets_in_group = lets %>%
      map(function(l) setdiff(., l)) %>%
      map_chr(function(x) paste(x, collapse=',')))
</code>```

Uses set operation setdiff to subtract current letter provided by purrr::map from the group's set, then reformats the list of vectors with paste and returns as character vector.

Title: all group members but the current row

Body:
I've got a grouped data frame, like so:

df <- data.frame(group = rep(1:4, each=3),
                 lets = rep(LETTERS[1:4], times=3))

For each row I would now like to identify all lets within the same group other than the lets of the row itself. Using dplyr I can get all lets thus:

df %>%
  group_by(group) %>%
  mutate(all_lets_in_group = paste(lets, collapse=','))

But how do I exclude the lets of the current row from what I feed into paste()?

Body:
The purpose of this task is not very clear, so the code clarity thus suffers as well, but still:

library(tidyverse)

df %>%
  group_by(group) %>%
  mutate(
    all_lets_in_group = lets %>%
      map(function(l) setdiff(., l)) %>%
      map_chr(function(x) paste(x, collapse=',')))

Uses set operation setdiff to subtract current letter provided by purrr::map from the group's set, then reformats the list of vectors with paste and returns as character vector.


问:
php/mysqli - combined selecting/filtering database of two nested json objects
I'm sending json via $.ajax to php/mysqli. The json has two objects (data & terms) where terms has always one nested object and data: none, one or multiple ... like this:

Searching for value01 sends back this json:

```<code>{"data":{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]},"terms":{"term":"value04"}}
</code>```

...

How can I now filter my database by the values given in the objects considering the above situation and especially that $arr['data']['tags'][0]['tag'] can also be empty?

答:
```<code>$data=file_get_contents("php://input");
//$data='{"data":{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"},{"tag":"value04"}]},"terms":{"term":"value05"}}';

$arr=json_decode($data,true);
$mysqli=new mysqli(...);  // do this appropriately
$query="SELECT * FROM accounts WHERE name LIKE '%".$mysqli->real_escape_string($arr['terms']['term'])."%'";
foreach($arr['data']['tags'] as $array){
    $tag=$array['tag'];
    $query.=" AND `name` LIKE '%".$mysqli->real_escape_string($tag)."%'";
}
$query.=" ORDER BY name;";
</code>```

Body:
I'm sending json via $.ajax to php/mysqli. The json has two objects (data & terms) where terms has always one nested object and data: none, one or multiple ... like this:

Searching for value01 sends back this json:

{"data":{"tags":[{"tag":"value01"},{"tag":"value02"},{"tag":"value03"}]},"terms":{"term":"value04"}}

...

How can I now filter my database by the values given in the objects considering the above situation and especially that $arr['data']['tags'][0]['tag'] can also be empty?


问:
Swift TableView ProgressView indicator on multiple rows on single select
I have a tableview list that has a select action tied to it.  When the user selects the row, it gives them a prompt and begins to download a file and displays progress using a progressive indicator.  For some reason, the indicator is being displayed every 12 records from the selection.  Why is this happening... am I selecting the cell incorrectly?

Here is my code:

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = self.tableView.cellForRow(at: indexPath) as! downloadCell
    let cellName = CurrentFiles[indexPath.row].labelName
    let internalName = CurrentFiles[indexPath.row].internalName
    let fileLocation = CurrentFiles[indexPath.row].fileName
    let safeURL = fileLocation.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
    let fileExtension = CurrentFiles[indexPath.row].fileExtension
    let fileDate = CurrentFiles[indexPath.row].lastUpdate
    if (cell.progressView.isHidden) && (cell.fileStatus == "Installed") && (cell.fileIcon.image ==  nil) {
        let fileLoc = getSharedFilePath(appGroup:applicationGroup,sharedFilename:"\(internalName).\(fileExtension)")
        let defaults = UserDefaults.standard
        defaults.set(fileLoc, forKey: "loadmap")
        defaults.set(cellName, forKey: "loadmapName")
        performSegue(withIdentifier: "gotoMap", sender: self)
    } else if (cell.progressView.isHidden) {
        alertControllerMsg(msgStyle: UIAlertControllerStyle.alert,msgTitle: "Download File", msgBody: "Are you sure you want to download \(cellName)?", cancelLbl: "Cancel", actionLbl: "Download", complete: {
            cell.fileStatus = "Installed"      //prevent double download
            //download file
            let destination: (URL, HTTPURLResponse) -> (URL, DownloadRequest.DownloadOptions) = {
                (temporaryURL, response) in
                if let directoryURL = FileManager().containerURL(forSecurityApplicationGroupIdentifier: applicationGroup), let suggestedFilename = response.suggestedFilename {
                    let filePath = directoryURL.appendingPathComponent("\(suggestedFilename)")
                    return (filePath, [.removePreviousFile, .createIntermediateDirectories])
                }
                return (temporaryURL, [.removePreviousFile, .createIntermediateDirectories])
            }
            if self.reachability.isReachableViaWiFi {
                cell.progressView.isHidden = false
                //BackendAPI is used to allow for downloads in background
                BackendAPIManager.sharedInstance.alamoFireManager.download(safeURL!, to: destination)
                    .downloadProgress { progress in
                        cell.fileIcon.image =  nil
                        cell.progressView.setProgress(Float(progress.fractionCompleted), animated: true)
                        cell.pctLabel.text = "\(String(format:"%g",round(progress.fractionCompleted*100)))%"
                    }.response { response in
                        cell.pctLabel.text = nil
                        cell.progressView.isHidden = true
                        cell.additionalLbl.text = nil
                        UserDefaults(suiteName: applicationGroup)!.set(fileDate, forKey: internalName)
                        cell.fileStatus = "Installed"
                        self.getAvailSpace()
                }
            } else {
                self.alertControllerMsg(msgStyle: UIAlertControllerStyle.alert,msgTitle: "Insufficient Network", msgBody: "Please connect to a Wifi network to download this file.", cancelLbl: "Cancel", actionLbl: "Retry", complete: {
                    self.downloadAndSort()
                })
            }
        })
    }
}
</code>```

EDIT:

CellforRowAt code

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "downloadCell", for: indexPath) as? downloadCell {
        let currentFile = CurrentFiles[indexPath.row]
        cell.configureCell(currentFile: currentFile)
        return cell
    } else {
        return downloadCell()
    }
}
</code>```

EDIT 2:

```<code>class downloadCell: UITableViewCell {

@IBOutlet weak var fileLbl: UILabel!
@IBOutlet weak var fileIcon: UIImageView!
@IBOutlet weak var pctLabel: UILabel!
@IBOutlet weak var additionalLbl: UILabel!
@IBOutlet weak var fileSize: UILabel!
@IBOutlet weak var progressView: UIProgressView!

var fileStatus = "NotInstalled"
func configureCell(currentFile: currentFiles) {

    fileLbl.text = currentFile.labelName
    fileSize.text = currentFile.fileSize
    let internalName = currentFile.internalName
    fileIcon.image = UIImage(named: "download")
    additionalLbl.text = "Updated: \(convertDateFormatter(date: currentFile.lastUpdate))"

    let fileExists = (readFromSharedFile(sharedFilename: internalName, fileExtension: currentFile.fileExtension))
    if fileExists == "Success" {
        //file has been downloaded on device
        let lastUpdateDate = UserDefaults(suiteName: applicationGroup)!.string(forKey: internalName)

        if lastUpdateDate != currentFile.lastUpdate {
                fileIcon.image =  UIImage(named: "download")
                fileStatus = "NeedsUpdate"
            } else {
                fileIcon.image = nil
                fileStatus = "Installed"
                additionalLbl.text = nil
            }
    } else {
        // not on device
        fileStatus = "NotInstalled"

    }
}
}
</code>```

答: We really need your code for cellForRowAtindex as well and a better description of the issue. How many cells fit the screen (is it around 12)? Is just progress view shown for every 12-th cell or does actual progress run in every 12th cell? If the progress view is just shown but is not updated, then the most obvious reason that comes to mind is that you forgot to hide progressView  in cellForRowAtindex when the cell is being re-used after dequeueReusableCell(withIdentifier:).

Body:
I have a tableview list that has a select action tied to it.  When the user selects the row, it gives them a prompt and begins to download a file and displays progress using a progressive indicator.  For some reason, the indicator is being displayed every 12 records from the selection.  Why is this happening... am I selecting the cell incorrectly?

Here is my code:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = self.tableView.cellForRow(at: indexPath) as! downloadCell
    let cellName = CurrentFiles[indexPath.row].labelName
    let internalName = CurrentFiles[indexPath.row].internalName
    let fileLocation = CurrentFiles[indexPath.row].fileName
    let safeURL = fileLocation.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
    let fileExtension = CurrentFiles[indexPath.row].fileExtension
    let fileDate = CurrentFiles[indexPath.row].lastUpdate
    if (cell.progressView.isHidden) && (cell.fileStatus == "Installed") && (cell.fileIcon.image ==  nil) {
        let fileLoc = getSharedFilePath(appGroup:applicationGroup,sharedFilename:"\(internalName).\(fileExtension)")
        let defaults = UserDefaults.standard
        defaults.set(fileLoc, forKey: "loadmap")
        defaults.set(cellName, forKey: "loadmapName")
        performSegue(withIdentifier: "gotoMap", sender: self)
    } else if (cell.progressView.isHidden) {
        alertControllerMsg(msgStyle: UIAlertControllerStyle.alert,msgTitle: "Download File", msgBody: "Are you sure you want to download \(cellName)?", cancelLbl: "Cancel", actionLbl: "Download", complete: {
            cell.fileStatus = "Installed"      //prevent double download
            //download file
            let destination: (URL, HTTPURLResponse) -> (URL, DownloadRequest.DownloadOptions) = {
                (temporaryURL, response) in
                if let directoryURL = FileManager().containerURL(forSecurityApplicationGroupIdentifier: applicationGroup), let suggestedFilename = response.suggestedFilename {
                    let filePath = directoryURL.appendingPathComponent("\(suggestedFilename)")
                    return (filePath, [.removePreviousFile, .createIntermediateDirectories])
                }
                return (temporaryURL, [.removePreviousFile, .createIntermediateDirectories])
            }
            if self.reachability.isReachableViaWiFi {
                cell.progressView.isHidden = false
                //BackendAPI is used to allow for downloads in background
                BackendAPIManager.sharedInstance.alamoFireManager.download(safeURL!, to: destination)
                    .downloadProgress { progress in
                        cell.fileIcon.image =  nil
                        cell.progressView.setProgress(Float(progress.fractionCompleted), animated: true)
                        cell.pctLabel.text = "\(String(format:"%g",round(progress.fractionCompleted*100)))%"
                    }.response { response in
                        cell.pctLabel.text = nil
                        cell.progressView.isHidden = true
                        cell.additionalLbl.text = nil
                        UserDefaults(suiteName: applicationGroup)!.set(fileDate, forKey: internalName)
                        cell.fileStatus = "Installed"
                        self.getAvailSpace()
                }
            } else {
                self.alertControllerMsg(msgStyle: UIAlertControllerStyle.alert,msgTitle: "Insufficient Network", msgBody: "Please connect to a Wifi network to download this file.", cancelLbl: "Cancel", actionLbl: "Retry", complete: {
                    self.downloadAndSort()
                })
            }
        })
    }
}

EDIT:

CellforRowAt code

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "downloadCell", for: indexPath) as? downloadCell {
        let currentFile = CurrentFiles[indexPath.row]
        cell.configureCell(currentFile: currentFile)
        return cell
    } else {
        return downloadCell()
    }
}

EDIT 2:

class downloadCell: UITableViewCell {

@IBOutlet weak var fileLbl: UILabel!
@IBOutlet weak var fileIcon: UIImageView!
@IBOutlet weak var pctLabel: UILabel!
@IBOutlet weak var additionalLbl: UILabel!
@IBOutlet weak var fileSize: UILabel!
@IBOutlet weak var progressView: UIProgressView!

var fileStatus = "NotInstalled"
func configureCell(currentFile: currentFiles) {

    fileLbl.text = currentFile.labelName
    fileSize.text = currentFile.fileSize
    let internalName = currentFile.internalName
    fileIcon.image = UIImage(named: "download")
    additionalLbl.text = "Updated: \(convertDateFormatter(date: currentFile.lastUpdate))"

    let fileExists = (readFromSharedFile(sharedFilename: internalName, fileExtension: currentFile.fileExtension))
    if fileExists == "Success" {
        //file has been downloaded on device
        let lastUpdateDate = UserDefaults(suiteName: applicationGroup)!.string(forKey: internalName)

        if lastUpdateDate != currentFile.lastUpdate {
                fileIcon.image =  UIImage(named: "download")
                fileStatus = "NeedsUpdate"
            } else {
                fileIcon.image = nil
                fileStatus = "Installed"
                additionalLbl.text = nil
            }
    } else {
        // not on device
        fileStatus = "NotInstalled"

    }
}
}


问:
Tensorflow: does feeding a value to a variable override its value permanently?
I have a NN model with some weights, and I need to be able to make inference (and learning) using sometiems a set of weights A and sometimes a set of weights B.
I know I can feed values to Variables and not only to placeholders, but if I do so I permanently override the variable value or is it temporary, within the execution window of the op nodes requested?

For example,
Let's assume I built the graph and learnt a model using weight set A.
If I want to make inference using another weight set, set B, I can do:

```<code>sess.run(output, feed_dict={input:input, weights:weightsB}) #inference
</code>```

My question is: If I feed the values weightsB, will they permanently override the values of the network? If next time I will run

```<code>sess.run(output, feed_dict={input:input}) #inference
</code>```

will it use weightsA or weightsB?

答:
In TensorFlow, feeding a value for a variable in one step does not affect the value stored in that variable. In subsequent steps, if you use the variable, it will continue to have its previous value.

Note that if you want a feed to change the value of a variable in future steps, you should explicitly assign that value to the variable, using a construction like:

```<code>v = tf.Variable(...)
v_update_placeholder = tf.placeholder(v.dtype, shape=v.shape)
v_update_op = v.assign(v_update_placeholder).op

# ...

sess.run(v_update_op, feed_dict={v_update_placeholder: ...})
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a NN model with some weights, and I need to be able to make inference (and learning) using sometiems a set of weights A and sometimes a set of weights B.
I know I can feed values to Variables and not only to placeholders, but if I do so I permanently override the variable value or is it temporary, within the execution window of the op nodes requested?

For example,
Let's assume I built the graph and learnt a model using weight set A.
If I want to make inference using another weight set, set B, I can do:

sess.run(output, feed_dict={input:input, weights:weightsB}) #inference

My question is: If I feed the values weightsB, will they permanently override the values of the network? If next time I will run

sess.run(output, feed_dict={input:input}) #inference

will it use weightsA or weightsB?

Body:
In TensorFlow, feeding a value for a variable in one step does not affect the value stored in that variable. In subsequent steps, if you use the variable, it will continue to have its previous value.

Note that if you want a feed to change the value of a variable in future steps, you should explicitly assign that value to the variable, using a construction like:

v = tf.Variable(...)
v_update_placeholder = tf.placeholder(v.dtype, shape=v.shape)
v_update_op = v.assign(v_update_placeholder).op

# ...

sess.run(v_update_op, feed_dict={v_update_placeholder: ...})


问:
MYSQL SELECT ... FOR UPDATE Not working?
I am having issues with MySQL's SELECT .. FOR UPDATE, here is the query I am trying to run:

```<code>SQL = "SELECT * " +
      "FROM " + TableName + " " +
      "WHERE out_status IN ("+outSStatus+") AND queued <= NOW() " +
      "ORDER BY out_status, id_queue ASC "+ limitSql+
      "FOR UPDATE";
</code>```

After this, the thread will do an UPDATE and change the out_status to 99, which is then it should unlock the row.

I am running a multi-threaded java application, so 3 threads are running this SQL statement, but when thread 1 runs this, it doesn't lock (hide) its results from thread 2 & 3. Therefore threads 2 & 3 are getting the same results.

Also each thread is on its own mysql connection.

Can anybody please help me with this? OR perhaps have a better solution?

Much Appreciated.

答: You can use transactions</p>

ContentLicense: CC BY-SA 2.5

Body:
I am having issues with MySQL's SELECT .. FOR UPDATE, here is the query I am trying to run:

SQL = "SELECT * " +
      "FROM " + TableName + " " +
      "WHERE out_status IN ("+outSStatus+") AND queued <= NOW() " +
      "ORDER BY out_status, id_queue ASC "+ limitSql+
      "FOR UPDATE";

After this, the thread will do an UPDATE and change the out_status to 99, which is then it should unlock the row.

I am running a multi-threaded java application, so 3 threads are running this SQL statement, but when thread 1 runs this, it doesn't lock (hide) its results from thread 2 & 3. Therefore threads 2 & 3 are getting the same results.

Also each thread is on its own mysql connection.

Can anybody please help me with this? OR perhaps have a better solution?

Much Appreciated.

Body: You can use transactions


问:
Checking if a metatype is an Array with an Element type of kind MyProtocol
I need do different things for different classes. For example I've created the protocols

```<code>protocol ResponseProtocol {
    associatedtype ResponseType: Any
}

protocol MappableProtocol {
    init(map: String)
}
</code>```

and I'm adding my data class MyDto

```<code>class MyDto: MappableProtocol {
    required init(map: String) { }
}
</code>```

and 3 different response classes

```<code>class A1: ResponseProtocol {
    typealias ResponseType = String
}

class A2: ResponseProtocol {
    typealias ResponseType = MyDto
}

class A3: ResponseProtocol {
    typealias ResponseType = [MyDto]
}
</code>```

now I need do different things depending on ResponseType.

I tried this code, but I'm running into problems with Arrays

```<code>class API {

    func test<T: ResponseProtocol>(a: T) -> String {

        if T.ResponseType.self is String.Type {
            return "String"
        }
        if T.ResponseType.self is MappableProtocol.Type {
            return "MappableProtocol"
        }

        if T.ResponseType.self is [Any].Type {
            return "Array<Any>" // Why is this false?
        }
        if T.ResponseType.self is [MappableProtocol].Type {
            return "Array<MappableProtocol>" //Why is this false?
        }
        if T.ResponseType.self is [MyDto].Type {
            return "Array<MyDto>" // Why is only this true?
        }
        return "notFound"
    }

}
let api = API()
let t1 = api.test(a: A1())
let t2 = api.test(a: A2())
let t3 = api.test(a: A3())
</code>```

In my playground console, for array A3, I see Array<MyDto>, but I expected the first return for array like Array<Any>.

How can I check for an Array where the Element is of kind MappableProtocol?

答:
The problem is that while instances of [MyDto] can be freely converted to [MappableProtocol] and [Any], these are really just magical conversions that the compiler does behind the scenes (see this Q&A for more information).

The same conversions don't exist for metatype values, which is why Swift says that a [MyDto].Type is not a [MappableProtocol].Type nor a [Any].Type – they are unrelated metatype types.

Likely the simplest solution in your case would just be to forget working with metatypes, and instead just declare different overloads of test(a:) to handle different ResponseType types.

```<code>// 'default' overload of test(a:)
func test<T : ResponseProtocol>(a: T) -> String {
    return "notFound"
}

func test<T : ResponseProtocol>(a: T) -> String where T.ResponseType == String {
    return "String"
}

func test<T : ResponseProtocol>(a: T) -> String where T.ResponseType : MappableProtocol {
    return "MappableProtocol"
}

func test<T : ResponseProtocol>(a: T) -> String where T.ResponseType == [MyDto] {
    return "Array<MDto>"
}

// overload of test(a:) that accepts a type that conforms to ResponseProtocol, where the
// ResponseType is an Array with arbitrary Element type.
func test<T : ResponseProtocol, ResponseTypeElement : MappableProtocol>(a: T) -> String
    where T.ResponseType == [ResponseTypeElement]
{
    return "Array<MappableProtocol>"
}

print(test(a: A1())) // String
print(test(a: A2())) // MappableProtocol
print(test(a: A3())) // Array<MyDto>

// A MappableProtocol with a ResponseType that conforms to MappableProtocol,
// but isn't MyDto.
class Foo : MappableProtocol { required init(map: String) { } }
class A4  : ResponseProtocol { typealias ResponseType = [Foo] }

print(test(a: A4())) // Array<MappableProtocol>
</code>```

(I removed your API class just to simplify things)

The compiler will simply resolve which overload to call at compile time, rather than having the runtime jump through lots of type-casting hoops.

If you insist on working with metatype values, one possible solution is to define a dummy protocol for Array to conform to (see for example this similar Q&A), which we can then cast the metatype values to. We can then declare an elementType static requirement in order to extract the Array's Element.self metatype value, which we can then inspect the type of in order to determine what the array is convertible to.

For example, if we define and conform Array to _ArrayProtocol:

```<code>protocol _ArrayProtocol {
    static var elementType: Any.Type { get }
}

extension Array : _ArrayProtocol {
    static var elementType: Any.Type {
        return Element.self
    }
}
</code>```

We can now use test(a:) like so:

```<code>func test<T : ResponseProtocol>(a: T) -> String {

    if T.ResponseType.self is String.Type {
        return "String"
    }

    if T.ResponseType.self is MappableProtocol.Type {
        return "MappableProtocol"
    }

    // attempt to cast the T.ResponseType.self metatype value to the existential metatype
    // type _ArrayProtocol.Type (i.e a type that conforms to _ArrayProtocol),
    // in this case, that's only ever Array.
    if let responseType = T.ResponseType.self as? _ArrayProtocol.Type {

        // switch on the element type, attempting to cast to different metatype types.
        switch responseType.elementType {
        case is MyDto.Type:
            return "Array<MyDto>"
        case is MappableProtocol.Type:
            return "Array<MappableProtocol>"
        default:
            return "Array<Any>"
        }
    }

    return "notFound"
}

print(test(a: A1())) // String
print(test(a: A2())) // MappableProtocol
print(test(a: A3())) // Array<MyDto>
print(test(a: A4())) // Array<MappableProtocol>
</code>```

Body:
I need do different things for different classes. For example I've created the protocols

protocol ResponseProtocol {
    associatedtype ResponseType: Any
}

protocol MappableProtocol {
    init(map: String)
}

and I'm adding my data class MyDto

class MyDto: MappableProtocol {
    required init(map: String) { }
}

and 3 different response classes

class A1: ResponseProtocol {
    typealias ResponseType = String
}

class A2: ResponseProtocol {
    typealias ResponseType = MyDto
}

class A3: ResponseProtocol {
    typealias ResponseType = [MyDto]
}

now I need do different things depending on ResponseType.

I tried this code, but I'm running into problems with Arrays

class API {

    func test<T: ResponseProtocol>(a: T) -> String {

        if T.ResponseType.self is String.Type {
            return "String"
        }
        if T.ResponseType.self is MappableProtocol.Type {
            return "MappableProtocol"
        }

        if T.ResponseType.self is [Any].Type {
            return "Array<Any>" // Why is this false?
        }
        if T.ResponseType.self is [MappableProtocol].Type {
            return "Array<MappableProtocol>" //Why is this false?
        }
        if T.ResponseType.self is [MyDto].Type {
            return "Array<MyDto>" // Why is only this true?
        }
        return "notFound"
    }

}
let api = API()
let t1 = api.test(a: A1())
let t2 = api.test(a: A2())
let t3 = api.test(a: A3())

In my playground console, for array A3, I see Array<MyDto>, but I expected the first return for array like Array<Any>.

How can I check for an Array where the Element is of kind MappableProtocol?

Body:
The problem is that while instances of [MyDto] can be freely converted to [MappableProtocol] and [Any], these are really just magical conversions that the compiler does behind the scenes (see this Q&A for more information).

The same conversions don't exist for metatype values, which is why Swift says that a [MyDto].Type is not a [MappableProtocol].Type nor a [Any].Type – they are unrelated metatype types.

Likely the simplest solution in your case would just be to forget working with metatypes, and instead just declare different overloads of test(a:) to handle different ResponseType types.

// 'default' overload of test(a:)
func test<T : ResponseProtocol>(a: T) -> String {
    return "notFound"
}

func test<T : ResponseProtocol>(a: T) -> String where T.ResponseType == String {
    return "String"
}

func test<T : ResponseProtocol>(a: T) -> String where T.ResponseType : MappableProtocol {
    return "MappableProtocol"
}

func test<T : ResponseProtocol>(a: T) -> String where T.ResponseType == [MyDto] {
    return "Array<MDto>"
}

// overload of test(a:) that accepts a type that conforms to ResponseProtocol, where the
// ResponseType is an Array with arbitrary Element type.
func test<T : ResponseProtocol, ResponseTypeElement : MappableProtocol>(a: T) -> String
    where T.ResponseType == [ResponseTypeElement]
{
    return "Array<MappableProtocol>"
}

print(test(a: A1())) // String
print(test(a: A2())) // MappableProtocol
print(test(a: A3())) // Array<MyDto>

// A MappableProtocol with a ResponseType that conforms to MappableProtocol,
// but isn't MyDto.
class Foo : MappableProtocol { required init(map: String) { } }
class A4  : ResponseProtocol { typealias ResponseType = [Foo] }

print(test(a: A4())) // Array<MappableProtocol>

(I removed your API class just to simplify things)

The compiler will simply resolve which overload to call at compile time, rather than having the runtime jump through lots of type-casting hoops.

If you insist on working with metatype values, one possible solution is to define a dummy protocol for Array to conform to (see for example this similar Q&A), which we can then cast the metatype values to. We can then declare an elementType static requirement in order to extract the Array's Element.self metatype value, which we can then inspect the type of in order to determine what the array is convertible to.

For example, if we define and conform Array to _ArrayProtocol:

protocol _ArrayProtocol {
    static var elementType: Any.Type { get }
}

extension Array : _ArrayProtocol {
    static var elementType: Any.Type {
        return Element.self
    }
}

We can now use test(a:) like so:

func test<T : ResponseProtocol>(a: T) -> String {

    if T.ResponseType.self is String.Type {
        return "String"
    }

    if T.ResponseType.self is MappableProtocol.Type {
        return "MappableProtocol"
    }

    // attempt to cast the T.ResponseType.self metatype value to the existential metatype
    // type _ArrayProtocol.Type (i.e a type that conforms to _ArrayProtocol),
    // in this case, that's only ever Array.
    if let responseType = T.ResponseType.self as? _ArrayProtocol.Type {

        // switch on the element type, attempting to cast to different metatype types.
        switch responseType.elementType {
        case is MyDto.Type:
            return "Array<MyDto>"
        case is MappableProtocol.Type:
            return "Array<MappableProtocol>"
        default:
            return "Array<Any>"
        }
    }

    return "notFound"
}

print(test(a: A1())) // String
print(test(a: A2())) // MappableProtocol
print(test(a: A3())) // Array<MyDto>
print(test(a: A4())) // Array<MappableProtocol>


问:
Codeigniter - 403 Forbidden Access when sending array with 3000 entries via Ajax
I have a Controller which consumes Ajax requests and responds with the result of the database operation. The Ajax call is formed with a set of IDs (an array of ints) and a message.

When the set of IDs have a normal ammount of IDs (I tested with 20 IDs), the Ajax call returns normally. When trying to send 3000 IDs, I get an almost instant response with a 403 Forbidden Access error.

This is probably a Codeigniter or Apache server error. I looked for it, but didn't find any answer.

Thanks in advance.

答:
On your AJAX code, are you sending it via GET?, if so, change it to POST</p>

```<code>$.ajax({
        type: "POST",
        url: 'url',
        data: data,
        dataType: "json",
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            //some code
        }
    });
</code>```

Body:
On your AJAX code, are you sending it via GET?, if so, change it to POST

$.ajax({
        type: "POST",
        url: 'url',
        data: data,
        dataType: "json",
        cache: false,
        contentType: false,
        processData: false,
        success: function (data) {
            //some code
        }
    });


问:
Why does open() create my file with the wrong permissions?
I am trying to read some text from a file and write it to another using open(), read() and write().

This is my open() for the file-to-write-to (I want to create a new file and write into it):

```<code>fOut = open ("test-1", O_RDWR | O_CREAT | O_SYNC);
</code>```

This is setting file-permissions to something I don't understand at all. This is the output of ls -l:

```<code>---------T 1 chaitanya chaitanya 0 2010-02-11 09:38 test-1
</code>```

Even the read permission is locked. I tried searching for this, but could not find ANYTHING.
Strangely, write() still successfully writes data to the file.

Also, if I do a 'chmod 777 test-1', things start working properly again.

Could someone please let me know where I am going wrong in my open call?

Thanks!

For your reference, I have pasted the complete program below:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main () {

    char buffer[512], ch;

    int fIn, fOut, i;
    ssize_t bytes;
    FILE *fp = NULL;

    //open a file
    fIn = open ("test", O_RDONLY);
    if (fIn == -1) {
        printf("\nfailed to open file.");
        return 1;
    }

    //read from file
    bytes =  read (fIn, buffer, sizeof(buffer));
    //and close it
    close (fIn);

    printf("\nSuccessfully read %d bytes.\n", bytes);

    //Create a new file
    fOut = open ("test-1", O_RDWR | O_CREAT | O_SYNC);

    printf("\nThese are the permissions for test-1\n");
    fflush(stdout);
    system("ls -l test-1");

    //write to it and close it.
    write (fOut, buffer, bytes);
    close (fOut);

    //write is somehow locking even the read permission to the file. Change it.
    system("chmod 777 test-1");

    fp = fopen ("test-1", "r");
    if (fp == NULL) {
        printf("\nCan't open test-1");
        return 1;
    }

    while (1)
    {
        ch = fgetc(fp);
        if (ch == EOF)
            break;
        printf("\n%c", ch);
    }

    fclose (fp);

    return 0;
}
</code>```

答:
Not strictly relevant to the question, but the accepted answer could use this clarifying point:

There is a relationship between rwx and its numerical representation that can be seen by treating the presence of a letter as a binary 1, and its absence as a binary 0.

e.g.

```<code>rwx  <-->  111 (binary) <-->  7 (octal)

r--  <-->  100 (binary) <-->  4 (octal)

-wx  <-->  011 (binary) <-->  3 (octal)
</code>```

As a further addendum, you may now consider the chmod command:

chmod 777 filename.extension -->  rwxrwxrwx  permissions

```<code>777 <--> 111 111 111 <--> rwx rwx rwx
</code>```

or: chmod 654 filename.extension --> rw-r-x-r--

```<code>654 <--> 110 101 100 <--> rw- r-x r--
</code>```

Hope this is informative!

Body:
I am trying to read some text from a file and write it to another using open(), read() and write().

This is my open() for the file-to-write-to (I want to create a new file and write into it):

fOut = open ("test-1", O_RDWR | O_CREAT | O_SYNC);

This is setting file-permissions to something I don't understand at all. This is the output of ls -l:

---------T 1 chaitanya chaitanya 0 2010-02-11 09:38 test-1

Even the read permission is locked. I tried searching for this, but could not find ANYTHING.
Strangely, write() still successfully writes data to the file.

Also, if I do a 'chmod 777 test-1', things start working properly again.

Could someone please let me know where I am going wrong in my open call?

Thanks!

For your reference, I have pasted the complete program below:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main () {

    char buffer[512], ch;

    int fIn, fOut, i;
    ssize_t bytes;
    FILE *fp = NULL;

    //open a file
    fIn = open ("test", O_RDONLY);
    if (fIn == -1) {
        printf("\nfailed to open file.");
        return 1;
    }

    //read from file
    bytes =  read (fIn, buffer, sizeof(buffer));
    //and close it
    close (fIn);

    printf("\nSuccessfully read %d bytes.\n", bytes);

    //Create a new file
    fOut = open ("test-1", O_RDWR | O_CREAT | O_SYNC);

    printf("\nThese are the permissions for test-1\n");
    fflush(stdout);
    system("ls -l test-1");

    //write to it and close it.
    write (fOut, buffer, bytes);
    close (fOut);

    //write is somehow locking even the read permission to the file. Change it.
    system("chmod 777 test-1");

    fp = fopen ("test-1", "r");
    if (fp == NULL) {
        printf("\nCan't open test-1");
        return 1;
    }

    while (1)
    {
        ch = fgetc(fp);
        if (ch == EOF)
            break;
        printf("\n%c", ch);
    }

    fclose (fp);

    return 0;
}

Body:
Not strictly relevant to the question, but the accepted answer could use this clarifying point:

There is a relationship between rwx and its numerical representation that can be seen by treating the presence of a letter as a binary 1, and its absence as a binary 0.

e.g.

rwx  <-->  111 (binary) <-->  7 (octal)

r--  <-->  100 (binary) <-->  4 (octal)

-wx  <-->  011 (binary) <-->  3 (octal)

As a further addendum, you may now consider the chmod command:

chmod 777 filename.extension -->  rwxrwxrwx  permissions

777 <--> 111 111 111 <--> rwx rwx rwx

or: chmod 654 filename.extension --> rw-r-x-r--

654 <--> 110 101 100 <--> rw- r-x r--

Hope this is informative!


答:
echo "$tsv_data" | awk '{print $2 " " $5}' | sort | awk '{print $2}' | paste -sd ',' -

This does the following steps in order:

Print the second and 5th argument (Product and Description) with a space between them.

Sort the input with sort (use gnu-sort if it can contain numbers)

Print only the description (in each line)

Join the lines together with paste

which will produce the following output:

```<code>Desc1,Desc2,Desc3
</code>```

Title: Extract specific text out of bash variable containing TSV string

Body:
echo "$tsv_data" | awk '{print $2 " " $5}' | sort | awk '{print $2}' | paste -sd ',' -

This does the following steps in order:

Print the second and 5th argument (Product and Description) with a space between them.

Sort the input with sort (use gnu-sort if it can contain numbers)

Print only the description (in each line)

Join the lines together with paste

which will produce the following output:

Desc1,Desc2,Desc3


问:
Checking array of editText is empty
I made this code to check if any of the edit texts are empty. I place them all in an array and then check each one to see if it was empty. If there's an empty one, a toast shows. If all are not empty, the app continues. The problem is, my method is queuing all the edit text and its freezing the toast on the app. How can I fix this problem?

My array inside a button onCreate:

```<code>            final EditText[] editTextArray = new EditText[] {
                    (EditText) findViewById(R.id.num1),
                    (EditText) findViewById(R.id.num2),
                    (EditText) findViewById(R.id.num3),
                    (EditText) findViewById(R.id.num4),
                    (EditText) findViewById(R.id.num5),
                    (EditText) findViewById(R.id.num6),
                    (EditText) findViewById(R.id.num7),
                    (EditText) findViewById(R.id.num8),
                    (EditText) findViewById(R.id.num9),
                    (EditText) findViewById(R.id.num10),
                    (EditText) findViewById(R.id.num11),
                    (EditText) findViewById(R.id.num12),
                    (EditText) findViewById(R.id.num13),
                    (EditText) findViewById(R.id.num14),
                    (EditText) findViewById(R.id.num15),
                    (EditText) findViewById(R.id.num16),
            };
</code>```

loop:

```<code>for (EditText anEditTextArray : editTextArray) {
                checkTextInput(anEditTextArray);
            }
</code>```

the method:

```<code>private boolean checkTextInput(EditText input) {

    String inputNum = input.getText().toString();

    if (inputNum.isEmpty()){

        // Toast message
        Toast.makeText(MainActivity.this, "The board is missing numbers.", Toast.LENGTH_SHORT).show();
        return true;

    } else {

        Log.i(TAG, "working");
        return false;
    }

} // end checkTextInput
</code>```

答:
You can modify your for loop like this</p>

```<code>for(EditText anEditTextArray : editTextArray) {
    if(checkTextInput(anEditTextArray)) {
        // an edit text is empty, so we need to stop the for loop to prevent lots of toast being shown on screen if there are more empty edit texts
        break;  // or use return based on the logic of your code
    }
}
</code>```

Title: Checking array of editText is empty

Body:
I made this code to check if any of the edit texts are empty. I place them all in an array and then check each one to see if it was empty. If there's an empty one, a toast shows. If all are not empty, the app continues. The problem is, my method is queuing all the edit text and its freezing the toast on the app. How can I fix this problem?

My array inside a button onCreate:

            final EditText[] editTextArray = new EditText[] {
                    (EditText) findViewById(R.id.num1),
                    (EditText) findViewById(R.id.num2),
                    (EditText) findViewById(R.id.num3),
                    (EditText) findViewById(R.id.num4),
                    (EditText) findViewById(R.id.num5),
                    (EditText) findViewById(R.id.num6),
                    (EditText) findViewById(R.id.num7),
                    (EditText) findViewById(R.id.num8),
                    (EditText) findViewById(R.id.num9),
                    (EditText) findViewById(R.id.num10),
                    (EditText) findViewById(R.id.num11),
                    (EditText) findViewById(R.id.num12),
                    (EditText) findViewById(R.id.num13),
                    (EditText) findViewById(R.id.num14),
                    (EditText) findViewById(R.id.num15),
                    (EditText) findViewById(R.id.num16),
            };

loop:

for (EditText anEditTextArray : editTextArray) {
                checkTextInput(anEditTextArray);
            }

the method:

private boolean checkTextInput(EditText input) {

    String inputNum = input.getText().toString();

    if (inputNum.isEmpty()){

        // Toast message
        Toast.makeText(MainActivity.this, "The board is missing numbers.", Toast.LENGTH_SHORT).show();
        return true;

    } else {

        Log.i(TAG, "working");
        return false;
    }

} // end checkTextInput

Body:
You can modify your for loop like this

for(EditText anEditTextArray : editTextArray) {
    if(checkTextInput(anEditTextArray)) {
        // an edit text is empty, so we need to stop the for loop to prevent lots of toast being shown on screen if there are more empty edit texts
        break;  // or use return based on the logic of your code
    }
}


问:
How to retrieve an int value from SQL database and compare it with an int value..
i created a login page, and in its database i crated a column (role) which contains an int value ( 0 or 1 ) to determine the role of the user if it is admin or normal user..
so, i want to write a query that retrieve the int value (role) of the login user and compare it with 1 or 0 to redirect the user to its specific page..

this is my code :

```<code>    using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class LogInPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(TextBox1.Text))
        { Label4.Text = "**Required**"; }
        else
        { Label4.Text = ""; }
        if (string.IsNullOrWhiteSpace(TextBox2.Text))
        { Label6.Text = "**Required**"; }
        else
        { Label6.Text = ""; }

        if (TextBox1.Text.Count() > 0 && TextBox2.Text.Count() > 0)
        {

            SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Azooz_2\Documents\Visual Studio 2013\WebSites\Gulf_K\App_Data\DatabaseGulf.mdf;Integrated Security=True;");
            SqlDataAdapter sda = new SqlDataAdapter("Select count(*) From Users Where UserName ='" + TextBox1.Text + "' and Password ='" + TextBox2.Text + "'", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);

            if (dt.Rows[0][0].ToString() == "1")
            {
                if (){
                  Response.Redirect("TheArrivalTime.aspx");
                }
               else{Response.Redirect("TheArrival.aspx")}

            }
            else
            {
                Label5.Text = "Wrong UserName or Password !!";
                Label6.Text = " ";
                Label4.Text = " ";
                TextBox1.Text = " ";
                TextBox2.Text = " ";
            }

        }

    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Label4.Text = " ";
        Label5.Text = " ";
        Label6.Text = " ";
        TextBox1.Text = " ";
        TextBox2.Text = " ";
    }
    protected void TextBox2_TextChanged(object sender, EventArgs e)
    {this.resetLbls();}
    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {this.resetLbls();}

    protected void resetLbls()
    {
        Label4.Text = " ";
        Label5.Text = " ";
        Label6.Text = " ";
    }
    }
</code>```

and i want to put the query in this if statement :

```<code> if (){
          Response.Redirect("TheArrivalTime.aspx");
        }
       else{ Response.Redirect("TheArrival.aspx");}
</code>```

so, can anyone help me please ??

答:
why don't select user_type from users where username = variable and
  password
  = variable and then put [user type field] in the condition if there is a match

... count will only give you  a number

Body:
i created a login page, and in its database i crated a column (role) which contains an int value ( 0 or 1 ) to determine the role of the user if it is admin or normal user..
so, i want to write a query that retrieve the int value (role) of the login user and compare it with 1 or 0 to redirect the user to its specific page..

this is my code :

    using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class LogInPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrWhiteSpace(TextBox1.Text))
        { Label4.Text = "**Required**"; }
        else
        { Label4.Text = ""; }
        if (string.IsNullOrWhiteSpace(TextBox2.Text))
        { Label6.Text = "**Required**"; }
        else
        { Label6.Text = ""; }

        if (TextBox1.Text.Count() > 0 && TextBox2.Text.Count() > 0)
        {

            SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Azooz_2\Documents\Visual Studio 2013\WebSites\Gulf_K\App_Data\DatabaseGulf.mdf;Integrated Security=True;");
            SqlDataAdapter sda = new SqlDataAdapter("Select count(*) From Users Where UserName ='" + TextBox1.Text + "' and Password ='" + TextBox2.Text + "'", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);

            if (dt.Rows[0][0].ToString() == "1")
            {
                if (){
                  Response.Redirect("TheArrivalTime.aspx");
                }
               else{Response.Redirect("TheArrival.aspx")}

            }
            else
            {
                Label5.Text = "Wrong UserName or Password !!";
                Label6.Text = " ";
                Label4.Text = " ";
                TextBox1.Text = " ";
                TextBox2.Text = " ";
            }

        }

    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        Label4.Text = " ";
        Label5.Text = " ";
        Label6.Text = " ";
        TextBox1.Text = " ";
        TextBox2.Text = " ";
    }
    protected void TextBox2_TextChanged(object sender, EventArgs e)
    {this.resetLbls();}
    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {this.resetLbls();}

    protected void resetLbls()
    {
        Label4.Text = " ";
        Label5.Text = " ";
        Label6.Text = " ";
    }
    }

and i want to put the query in this if statement :

 if (){
          Response.Redirect("TheArrivalTime.aspx");
        }
       else{ Response.Redirect("TheArrival.aspx");}

so, can anyone help me please ??


问:
ajax progress loading does not work properly
I am now in javascript, I am trying to display a indictor icon when ajax  starts and hide it when it finishes, below is my code:

```<code>CSS:
 div.ajax-progress {
      //some setting and url
}
<body>
   <div class="ajax-progress"></div>
</body>
Javascript:

$('#fileToUpload').on('change', function(e) {

            var file = e.target.files[0];
            var formData = new FormData($('form')[0]);
            imageId = cornerstoneWADOImageLoader.fileManager.add(file);

            $.ajax({
            url: 'loadfile.php',
            type: 'POST',
            data: formData,
            async: false,
            dataType: 'json',
            timeout : 60000,
            beforeSend :function(){
                $(".ajax-progress").show();
            }，
            success: function (html) {}
           $(".ajax-progress").hide();
             //doing something}
        });
    });
</code>```

but nothing happens, any idea? appreciated.

答: Maybe if you put  $(".ajax-progress").show(); before the call of ajax $.ajax({}); and them hide it in the succes.

Body:
I am now in javascript, I am trying to display a indictor icon when ajax  starts and hide it when it finishes, below is my code:

CSS:
 div.ajax-progress {
      //some setting and url
}

Javascript:

$('#fileToUpload').on('change', function(e) {

            var file = e.target.files[0];
            var formData = new FormData($('form')[0]);
            imageId = cornerstoneWADOImageLoader.fileManager.add(file);

            $.ajax({
            url: 'loadfile.php',
            type: 'POST',
            data: formData,
            async: false,
            dataType: 'json',
            timeout : 60000,
            beforeSend :function(){
                $(".ajax-progress").show();
            }，
            success: function (html) {}
           $(".ajax-progress").hide();
             //doing something}
        });
    });

but nothing happens, any idea? appreciated.


问:
Android Building Your First App 4: Build Error: Cannot find symbol variable EXTRA_MESSAGE
I am posting this as a new question, although I have managed to find the solution to the problem myself, and despite the fact that the question has been asked before, either directly or indirectly. I mention the following posts at StackOverflow as examples:

stackoverflow.com/questions/39872779/extra-message-and-putextra

stackoverflow.com/questions/38938297/android-studio-cannot-find-symbol-variable

The reason for doing this post, is that the issue seems to be a recurring pitfall among beginners (myself included) who follow the guide "Building Your First App" by Android Developers. It seems difficult to find the answer explaining specifically why the problem arises. I spent several hours plundring in Android Studio and searching online, until I found the answer.

Description of the problem:

While having followed the step "Start Another Activity", thus attempting to run the application, you may experience Build error, with the following message:

"error: cannot find symbol variable EXTRA_MESSAGE"

In addition, instances of EXTRA_MESSAGE are colored red in the programming code in Android Studio.

It can be hard to understand why this error occurs when you have followed the description in the guide to the best of ability. A brief answer that have been given a number of times is that you have not declared the EXTRA_MESSAGE variable as public static in the MainActivity. But this provides no explanation of how the declaration should have been performed (syntax), or how you have managed to avoid the declaration in the first place.

答:
A long answer:

In MainActivity.java, the following phrase is missing:

public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";

The phrase declares a symbol variable called EXTRA_MESSAGE, of string-type. The symbol variable is public constant, hence it’s available in all methods in the application, not only MainActivity. The phrase actually appears in the guide, but it is easy to overlook, as a result of the way the guide is designed:

At step 1 under "Respond to the send button", you are prompted to add the method sendMessage(), shown as follows:

(Screenshot) Respond to the send button

Currently, the method performs nothing, as only a comment is inserted where the program code should be. Later, under "Build an Intent", you are prompted to add the EXTRA_MESSAGE constant and sendMessage() code, shown as follows:

(Screenshot) Build an Intent

At this point, you’ll mess up if you simply copy the program code under the method sendMessage(), while ignoring that you also need to add the new phrase above the sentence "@Override."

However, the guide provides poor explanation of the terms of the sentence:
"Public", "final", "static" and "String", and the difference between EXTRA_MESSAGE and com.example.myfirstapp.MESSAGE. This could have been improved, I think.

I hope this post will be of help to other beginners who are stuck with the same issue.


问:
The requested operation cannot be performed on a file with a user-mapped section open
Whenever I tried to copy 4 files into my bin folder, after stopping the main service, I am getting an error with one file (TexteDll). The error is:

```<code>Cannot copy TexteDll: The requested operation cannot be performed on a file
with a user-mapped section open
</code>```

It may be due to some system locking. Or perhaps another process is using this DLL. When I googled, I found that rebooting the system may resolve this.

Can anybody suggest a cause or solution for this? I inspected the properties of TexteDll (general, version, security, etc). Everything appears normal.

答:
None of the solutions posted here worked for me. It was devenv.exe (Visual Studio) locking the file, but if I restarted it, it would re-lock it.

Bizarrely, Windows wouldn't let me Delete the files (to Recycle Bin), but Shift+Delete (permanent delete) worked.

Body:
Whenever I tried to copy 4 files into my bin folder, after stopping the main service, I am getting an error with one file (TexteDll). The error is:

Cannot copy TexteDll: The requested operation cannot be performed on a file
with a user-mapped section open

It may be due to some system locking. Or perhaps another process is using this DLL. When I googled, I found that rebooting the system may resolve this.

Can anybody suggest a cause or solution for this? I inspected the properties of TexteDll (general, version, security, etc). Everything appears normal.


问:
Laravel logging out on user deleting
I am using Laravel 5.3.

I have an User model extending Authenticatable.

I also have an users panel where the super user can update and delete other users.

However, every time the super user deletes another user, he gets disconnected (logged out) from the system. How can I workaround this?

I am deleting on a custom controller "UserController":

```<code>public function delete (User $user)
    {
        $deleted = $user->delete();
        return compact('deleted');
    }
</code>```

答:
Without seeing any of your error logs, I'm not aware of Laravel's ability to return a variable from its controllers directly.  So unless this feature exists, the issue may (at its core), be occurring due to the line:

```<code>return compact('deleted');
</code>```

Try to return a view with the variable attached, (e.g. - if your view resides in resources/views/users/index.blade.php), replace the aforementioned line with the following:

```<code>return view('users.index', compact('deleted'));
</code>```

Title: Laravel logging out on user deleting

Body:
I am using Laravel 5.3.

I have an User model extending Authenticatable.

I also have an users panel where the super user can update and delete other users.

However, every time the super user deletes another user, he gets disconnected (logged out) from the system. How can I workaround this?

I am deleting on a custom controller "UserController":

public function delete (User $user)
    {
        $deleted = $user->delete();
        return compact('deleted');
    }

Body:
Without seeing any of your error logs, I'm not aware of Laravel's ability to return a variable from its controllers directly.  So unless this feature exists, the issue may (at its core), be occurring due to the line:

return compact('deleted');

Try to return a view with the variable attached, (e.g. - if your view resides in resources/views/users/index.blade.php), replace the aforementioned line with the following:

return view('users.index', compact('deleted'));


问:
Parse Json data
```<code>a=  [{
    "data" : {
        "check": true,
    },
    "AMI": {
        "status": 1,
        "firewall":{
            "status": enable
        },
        "d_suffix": "x.y.com",
        "id": 4
    },
    "tags": [  #Sometime tags could be like "tags":  ["default","auto"]
        "default"
    ],
    "hostname": "abc.com",
}
]
</code>```

How to get a hostname on the basis of tags?I am trying to implement it using

```<code>for i in a:
  if i['tags'] == 'default':
     output = i['hostname']
</code>```

but it's failing because 'tags' is a list which is not mapping to hostname key.Is there any way i can get hostname on the basis of 'tags'?

答:
To get all hostnames tagged as default, use a list comprehension:

```<code>def_hostnames = [i['hostname'] for i in a if 'default' in i['tags']]
print('Default hostnames: %s' % ','.join(def_hostnames))
</code>```

If you only want the first hit, either use def_hostnames[0] or the equivalent generator expression:

```<code>print('first: %s' % next(i['hostname'] for i in a if 'default' in i['tags']))
</code>```

Your current code fails because it uses default, which is a variable named default. You want to look for a string default.

Title: Parse Json data

Body:
a=  [{
    "data" : {
        "check": true,
    },
    "AMI": {
        "status": 1,
        "firewall":{
            "status": enable
        },
        "d_suffix": "x.y.com",
        "id": 4
    },
    "tags": [  #Sometime tags could be like "tags":  ["default","auto"]
        "default"
    ],
    "hostname": "abc.com",
}
]

How to get a hostname on the basis of tags?I am trying to implement it using

for i in a:
  if i['tags'] == 'default':
     output = i['hostname']

but it's failing because 'tags' is a list which is not mapping to hostname key.Is there any way i can get hostname on the basis of 'tags'?

Body:
To get all hostnames tagged as default, use a list comprehension:

def_hostnames = [i['hostname'] for i in a if 'default' in i['tags']]
print('Default hostnames: %s' % ','.join(def_hostnames))

If you only want the first hit, either use def_hostnames[0] or the equivalent generator expression:

print('first: %s' % next(i['hostname'] for i in a if 'default' in i['tags']))

Your current code fails because it uses default, which is a variable named default. You want to look for a string default.


答:
Initialize Toast outside checkTextInput and cancel it before show. So it will stop previous one and show the new one.</p>

```<code>Toast t = Toast.makeText(MainActivity.this, "The board is missing numbers.", Toast.LENGTH_SHORT);

    private boolean checkTextInput(EditText input) {

        String inputNum = input.getText().toString();

        if (inputNum.isEmpty()){

            // Toast message
            t.cancel();
            t.show();
            return true;

        } else {

            Log.i(TAG, "working");
            return false;
        }

    } // end checkTextInput
</code>```

Title: Checking array of editText is empty

Body:
Initialize Toast outside checkTextInput and cancel it before show. So it will stop previous one and show the new one.

Toast t = Toast.makeText(MainActivity.this, "The board is missing numbers.", Toast.LENGTH_SHORT);

    private boolean checkTextInput(EditText input) {

        String inputNum = input.getText().toString();

        if (inputNum.isEmpty()){

            // Toast message
            t.cancel();
            t.show();
            return true;

        } else {

            Log.i(TAG, "working");
            return false;
        }

    } // end checkTextInput


问:
Generate a unique ObjectId for a collection
I would like to generate a unique ObjectId for a resource to give back clients with the nodejs mongodb driver.

IE:

```<code>var ObjectID = require('mongodb').ObjectID;
var objectId = new ObjectID();
</code>```

Reading about an ObjectId it seems that there are some cases in which this id may not be unique.  Even though this is extremely rare I still cannot take a chance on having a duplicate id.

Question #1, Using this driver is it possible (even though unlikely) to get a duplicate id doing this:

```<code>var objectId = new ObjectID();
</code>```

Question #2 (if above is not 100% guarantee to give a unique id):

Does this driver guarantee that for a certain collection the ObjectId that is automatically created when a new document is inserted is unique?  If yes, how?  If yes, can I somehow duplicate that behavior when calling new ObjectID() myself without a collection?

If the driver or the mongo server ensures (100% of the time) that for a collection every new doc gets a unique id, I could always have a collection of just ids, then when generating a new, empty doc for that collection I would ensure I get a unique ObjectId.  However seems like overkill to have another collection just to store ids.

That being said some might ask why not just generate the ObjectId in a collection and update that doc later with data.  The answer is that in my case data may not ever come later and I don't want to implement logic to check for empty docs that only contain an id.

答:
It's very unlikely that the same ObjectID will generate as mongo guarantees unique ID. objectID is created with a combination of two same values and two different values (unix epoch time, and a random value). However, in any case of a duplicate, you won't be allowed to insert a document as objectID acts as a primary key and insert function will return duplicate key error to your callback. Read more here. The same error is returned if mongo node native library creates a duplicate ObjectID.

UPDATE: again after reading the code base, if "hypothetically" the objectID that was generated by the library isn't unique, the answer is no. We are not ensured by the library that the id is unique, but we are ensured of a duplicate error doesn't matter who or what sent the id.

Here's the process:
 1. generates ID
 2. Sends straight to server.
 3. Returns results.

Mongo isn't looping in nodeJS with existing ids because the library isn't storing it in cache. Read the code base for the library.

Body:
I would like to generate a unique ObjectId for a resource to give back clients with the nodejs mongodb driver.

IE:

var ObjectID = require('mongodb').ObjectID;
var objectId = new ObjectID();

Reading about an ObjectId it seems that there are some cases in which this id may not be unique.  Even though this is extremely rare I still cannot take a chance on having a duplicate id.

Question #1, Using this driver is it possible (even though unlikely) to get a duplicate id doing this:

var objectId = new ObjectID();

Question #2 (if above is not 100% guarantee to give a unique id):

Does this driver guarantee that for a certain collection the ObjectId that is automatically created when a new document is inserted is unique?  If yes, how?  If yes, can I somehow duplicate that behavior when calling new ObjectID() myself without a collection?

If the driver or the mongo server ensures (100% of the time) that for a collection every new doc gets a unique id, I could always have a collection of just ids, then when generating a new, empty doc for that collection I would ensure I get a unique ObjectId.  However seems like overkill to have another collection just to store ids.

That being said some might ask why not just generate the ObjectId in a collection and update that doc later with data.  The answer is that in my case data may not ever come later and I don't want to implement logic to check for empty docs that only contain an id.


问:
How to Add a String inside of another string without erasing the rest of it

I'm having bad times trying to add a string inside of another string in a especific position. Every time I use this code, the rest of the string become blank.

```<code>double temperature = 22.1;
unsigned char pacote[16] = "#0123456789ABCDEF";
unsigned char temp_local[3];
dtostrf(temperatura, 3, 1, temp_local);
sprintf(pacote+3,"%s", temp_local);
</code>```

or

```<code>sprintf(pacote+3,temp_local);
</code>```

got the same printf:

```<code>#0122.1
</code>```

istead of:

```<code>#0122.16789ABCDEF
</code>```

Why is it erasing all the rest of the string and not just replace the next 4 positions after [3] and leaving the rest alone.
I'm using arduino but I think that's generic C question.

Thank you very much!!!

答:
You should move the string data into the designated position (instead of copying the string, which includes a terminating '\0'):

```<code>memcpy(pacote+3, temp_local, strlen(temp_local));
</code>```

Body:
I'm having bad times trying to add a string inside of another string in a especific position. Every time I use this code, the rest of the string become blank.

double temperature = 22.1;
unsigned char pacote[16] = "#0123456789ABCDEF";
unsigned char temp_local[3];
dtostrf(temperatura, 3, 1, temp_local);
sprintf(pacote+3,"%s", temp_local);

or

sprintf(pacote+3,temp_local);

got the same printf:

#0122.1

istead of:

#0122.16789ABCDEF

Why is it erasing all the rest of the string and not just replace the next 4 positions after [3] and leaving the rest alone.
I'm using arduino but I think that's generic C question.

Thank you very much!!!

Body:
You should move the string data into the designated position (instead of copying the string, which includes a terminating '\0'):

memcpy(pacote+3, temp_local, strlen(temp_local));


问:
pymssql problem - INSERT does not work with parameters
I'm using pymssql to do database programming with Python on Linux.

I'm having problems with passing parameters to queries. This problem only seems to exist with INSERT queries.

This works:

```<code>query = "SELECT col1, col2 FROM table WHERE col3=%s"
cur.execute(query, (value,))
</code>```

But this doesn't:

```<code>query = "INSERT INTO table (col1, col2) VALUES (%s, %s)"
cur.execute(query, (value1, value2,))
</code>```

Any idea why the INSERT query won't work?

Here is the traceback:

```<code>Traceback (most recent call last):
  File "test.py", line 46, in ?
    cur.execute(query, (value1, value2,))
  File "/usr/lib/python2.4/site-packages/pymssql.py", line 126, in execute
    self.executemany(operation, (params,))
  File "/usr/lib/python2.4/site-packages/pymssql.py", line 152, in executemany
    raise DatabaseError, "internal error: %s" % self.__source.errmsg()
pymssql.DatabaseError: internal error: None
</code>```

答: Turns out one of the values I was trying to insert was of type unicode. When I converted it to string, using str(value1), the query worked.

Body:
I'm using pymssql to do database programming with Python on Linux.

I'm having problems with passing parameters to queries. This problem only seems to exist with INSERT queries.

This works:

query = "SELECT col1, col2 FROM table WHERE col3=%s"
cur.execute(query, (value,))

But this doesn't:

query = "INSERT INTO table (col1, col2) VALUES (%s, %s)"
cur.execute(query, (value1, value2,))

Any idea why the INSERT query won't work?

Here is the traceback:

Traceback (most recent call last):
  File "test.py", line 46, in ?
    cur.execute(query, (value1, value2,))
  File "/usr/lib/python2.4/site-packages/pymssql.py", line 126, in execute
    self.executemany(operation, (params,))
  File "/usr/lib/python2.4/site-packages/pymssql.py", line 152, in executemany
    raise DatabaseError, "internal error: %s" % self.__source.errmsg()
pymssql.DatabaseError: internal error: None


问:
Apache RewriteEngine - Rewrite anything that not exists to index.php
I'm really struggling now.
First of all, i searched on Google and here, and none of the solutions found worked for me. I don't really have much time right now to completely dig into Apache docs for solid understanding of the RewriteEngine(will do later for sure).

WHAT I NEED

I need to handle special requests from our Google Adwords campaign, which look like this: http://website.com/something/%first_param%/%second_param%/%third_param%
In my document root directory, i have index.php where i parse the query string using regex and acquire these parameters, like this:

$request_URI = $_SERVER['REQUEST_URI'];
preg_match('/\/[^\/]+\/([^\/]+)\/([^\/]+)\/([^\/]+)/', $request_URI, $matches);

THE PROBLEM

Apache successfully redirects everything, but it also includes all additional requests for all the resources, so instead of fetching resources it just gets me the same index.php.

Currently i have this .htaccess file in my document root:

        RewriteEngine on

        RewriteCond %{REQUEST_FILENAME} !-d

        RewriteCond %{REQUEST_FILENAME} !-f

        RewriteRule .* index.php?url=$0 [QSA,L]

Please note, that i am using Virtual Host for this project:

<VirtualHost *:80>

    ServerName masuma.hyperauto.local

    DocumentRoot "c:/wamp64/www/projects/masuma landing"

</VirtualHost>

I have my index.php in this root directory above.

I have also enabled RewriteEngine logs and found interesting things here, but i still can't solve this:

```<code>add path info postfix: C:/wamp64/www/projects/masuma landing/test -> C:/wamp64/www/projects/masuma landing/test/test/firm/css/bootstrap.min.css, referer: host_here/test/test/firm/toyota
strip per-dir prefix: C:/wamp64/www/projects/masuma landing/test/test/firm/css/bootstrap.min.css -> test/test/firm/css/bootstrap.min.css, referer: host_here/test/test/firm/toyota
applying pattern '.*' to uri 'test/test/firm/css/bootstrap.min.css', referer: host_here/test/test/firm/toyota
rewrite 'test/test/firm/css/bootstrap.min.css' -> 'index.php?url=test/test/firm/css/bootstrap.min.css', referer: host_here/test/test/firm/toyota
split uri=index.php?url=test/test/firm/css/bootstrap.min.css -> uri=index.php, args=url=test/test/firm/css/bootstrap.min.css, referer: host_here/test/test/firm/toyota <br><br>
</code>```

I can see here, that it prepends the path in query string to the resource filename, like test/test/firm/css/bootstrap.min.css, but the resources are in the document root!

UPD: SOLUTION

The flag [DPI] in my RewriteRule solved the problem.

Now the rule looks like RewriteRule .* index.php?url=$0 [QSA,L,DPI]

And, what is important, i am still able to get the original query path in $_SERVER['REQUEST_URI']

答: Do you just need the [DPI] flag on your RewriteRule to get rid of the calculated PATH_INFO?

Body:
I'm really struggling now.
First of all, i searched on Google and here, and none of the solutions found worked for me. I don't really have much time right now to completely dig into Apache docs for solid understanding of the RewriteEngine(will do later for sure).

WHAT I NEED

I need to handle special requests from our Google Adwords campaign, which look like this: http://website.com/something/%first_param%/%second_param%/%third_param%
In my document root directory, i have index.php where i parse the query string using regex and acquire these parameters, like this:

$request_URI = $_SERVER['REQUEST_URI'];
preg_match('/\/[^\/]+\/([^\/]+)\/([^\/]+)\/([^\/]+)/', $request_URI, $matches);

THE PROBLEM

Apache successfully redirects everything, but it also includes all additional requests for all the resources, so instead of fetching resources it just gets me the same index.php.

Currently i have this .htaccess file in my document root:

        RewriteEngine on

        RewriteCond %{REQUEST_FILENAME} !-d

        RewriteCond %{REQUEST_FILENAME} !-f

        RewriteRule .* index.php?url=$0 [QSA,L]

Please note, that i am using Virtual Host for this project:

<VirtualHost *:80>

    ServerName masuma.hyperauto.local

    DocumentRoot "c:/wamp64/www/projects/masuma landing"

</VirtualHost>

I have my index.php in this root directory above.

I have also enabled RewriteEngine logs and found interesting things here, but i still can't solve this:

add path info postfix: C:/wamp64/www/projects/masuma landing/test -> C:/wamp64/www/projects/masuma landing/test/test/firm/css/bootstrap.min.css, referer: host_here/test/test/firm/toyota
strip per-dir prefix: C:/wamp64/www/projects/masuma landing/test/test/firm/css/bootstrap.min.css -> test/test/firm/css/bootstrap.min.css, referer: host_here/test/test/firm/toyota
applying pattern '.*' to uri 'test/test/firm/css/bootstrap.min.css', referer: host_here/test/test/firm/toyota
rewrite 'test/test/firm/css/bootstrap.min.css' -> 'index.php?url=test/test/firm/css/bootstrap.min.css', referer: host_here/test/test/firm/toyota
split uri=index.php?url=test/test/firm/css/bootstrap.min.css -> uri=index.php, args=url=test/test/firm/css/bootstrap.min.css, referer: host_here/test/test/firm/toyota

I can see here, that it prepends the path in query string to the resource filename, like test/test/firm/css/bootstrap.min.css, but the resources are in the document root!

UPD: SOLUTION

The flag [DPI] in my RewriteRule solved the problem.

Now the rule looks like RewriteRule .* index.php?url=$0 [QSA,L,DPI]

And, what is important, i am still able to get the original query path in $_SERVER['REQUEST_URI']


问:
PHP: Need to convert imagemagick command to php script
I use this command to batch modify images for a site. They need to be this size to suit the theme.

Now I also want to use these images in Facebook Ads, but they have to be resized. The command I use (which works fine) is:

```<code>for i in `ls -1 *.jpg`; do convert $i -fuzz 10% -trim +repage -resize 980x1200 -background white -gravity center -extent 980x1200 $i; done
</code>```

Now I need to make a PHP script that does the same, but also returns the image as response.

I came up with the following:

```<code><?php

/* Create the object and read the image in */
$im = new Imagick("image.jpg");

/* Trim the image with 10% fuzz */
$im->trimImage(10);

/* Repage */
$im->setImagePage(0, 0, 0, 0);

/* Resize */
$im->resizeImage(1200,628,Imagick::FILTER_LANCZOS,0);

/* Add Borders*/
$im->setImageBackgroundColor('White');
$im->setGravity('Centre');
$im->setImageExtent(1200,628);

/* Output the image */
header("Content-Type: image/" . $im->getImageFormat());
echo $im;
?>
</code>```

Unfortunately it doesn't seem to work. All it does is return a black rectangle (which looks like the right dimensions as used in the script).

答:
First error I get when running this code:

PHP Warning:  Imagick::setgravity() expects parameter 1 to be integer, string given in resize.php on line 18

Try using imagick::GRAVITY_CENTER instead.

Next issue, Imagick::resizeImage() and Imagick::setImageExtent() expect parameters in width, height order.

Finally, try setting a non-zero value like 1 for blur on Imagick::resizeImage() to resolve the black image issue.

I'm not sure how you are trying to get a border, but you may want to look at Imagick::borderImage().

I don't know if that will solve all your problems, but it should get you a lot closer!

```<code><?php

/* Create the object and read the image in */
$im = new Imagick("image.jpg");

/* Trim the image with 10% fuzz */
$im->trimImage(10);

/* Repage */
$im->setImagePage(0, 0, 0, 0);

/* Resize */
$im->resizeImage(628, 1200, Imagick::FILTER_LANCZOS, 1);

/* Add Borders*/
$im->setImageBackgroundColor('White');
$im->setGravity(Imagick::GRAVITY_CENTER);
$im->setImageExtent(628, 1200);

/* Output the image */
header("Content-Type: image/" . $im->getImageFormat());
echo $im;
?>
</code>```

Body:
I use this command to batch modify images for a site. They need to be this size to suit the theme.

Now I also want to use these images in Facebook Ads, but they have to be resized. The command I use (which works fine) is:

for i in `ls -1 *.jpg`; do convert $i -fuzz 10% -trim +repage -resize 980x1200 -background white -gravity center -extent 980x1200 $i; done

Now I need to make a PHP script that does the same, but also returns the image as response.

I came up with the following:

<?php

/* Create the object and read the image in */
$im = new Imagick("image.jpg");

/* Trim the image with 10% fuzz */
$im->trimImage(10);

/* Repage */
$im->setImagePage(0, 0, 0, 0);

/* Resize */
$im->resizeImage(1200,628,Imagick::FILTER_LANCZOS,0);

/* Add Borders*/
$im->setImageBackgroundColor('White');
$im->setGravity('Centre');
$im->setImageExtent(1200,628);

/* Output the image */
header("Content-Type: image/" . $im->getImageFormat());
echo $im;
?>

Unfortunately it doesn't seem to work. All it does is return a black rectangle (which looks like the right dimensions as used in the script).

Body:
First error I get when running this code:

PHP Warning:  Imagick::setgravity() expects parameter 1 to be integer, string given in resize.php on line 18

Try using imagick::GRAVITY_CENTER instead.

Next issue, Imagick::resizeImage() and Imagick::setImageExtent() expect parameters in width, height order.

Finally, try setting a non-zero value like 1 for blur on Imagick::resizeImage() to resolve the black image issue.

I'm not sure how you are trying to get a border, but you may want to look at Imagick::borderImage().

I don't know if that will solve all your problems, but it should get you a lot closer!

<?php

/* Create the object and read the image in */
$im = new Imagick("image.jpg");

/* Trim the image with 10% fuzz */
$im->trimImage(10);

/* Repage */
$im->setImagePage(0, 0, 0, 0);

/* Resize */
$im->resizeImage(628, 1200, Imagick::FILTER_LANCZOS, 1);

/* Add Borders*/
$im->setImageBackgroundColor('White');
$im->setGravity(Imagick::GRAVITY_CENTER);
$im->setImageExtent(628, 1200);

/* Output the image */
header("Content-Type: image/" . $im->getImageFormat());
echo $im;
?>


答:
Use in to test if something is in a list. You also need to put default in quotes to make it a string.

```<code>for i in a:
    if 'default' in i['tags']:
        output = i['hostname']
        break
</code>```

If you only need to find one match, you should break out of the loop once you find it.

If you need to find multiple matches, use @phihag's answer with the list comprehension.

Title: Parse Json data

Body:
Use in to test if something is in a list. You also need to put default in quotes to make it a string.

for i in a:
    if 'default' in i['tags']:
        output = i['hostname']
        break

If you only need to find one match, you should break out of the loop once you find it.

If you need to find multiple matches, use @phihag's answer with the list comprehension.


问:
elements of list in row
i have few polygons and distance of some points from those polygons. i tried to write in a csv by pandas where distance between each point and polygon will come in separate rows. i got this:

```<code>poly total inside outside dist
1000   2     0      2     [16015,5678]
1100   1     0      1     [5267]
</code>```

I wanted to get like:

```<code>poly total inside outside dist
1000   2    0       2     16015
1000   2    0       2     5678
1100   1    0       1     5267
</code>```

I tried the following after looking at this previous q [How to write nth value of list into csv file

```<code>distance =[]
for row in arcpy.da.SearchCursor(outSide, ["SHAPE@XY"]):
            px, py = row[0]
            zipPoint=point(px,py)
            Distance.append(int(zipPoint.calDist(PolyCenter)))
for i in distance:
    df.loc[polygon,"distance"]=distance
    df.loc[zipCode,"Total"]=count
    df.loc[zipCode,"Inside"]=insideNum
    df.loc[zipCode,"Outside"]=outsideNum
</code>```

But its giving me the same result in csv. any help is appreciated.

答:
i got a solution..

df2=df.fillna(0)
s=df2.apply(lambda x:pd.Series(x['Distances']),axis=1).stack().reset_index(level=1, drop=True)
s.name="Distance"
df3=df2.drop("Distances",axis=1).join(s)

it looked like:
    enter code here

```<code>32811   253  221  32  20
32811  253  221  32  3015
32811   253  221  32  2010
</code>```

Thanks you for your help..still i would appreciate if you can give me a solution for error: 'ValueError: invalid literal for long() with base 10: '[16015, 5678]''.

Title: elements of list in row

Body:
i have few polygons and distance of some points from those polygons. i tried to write in a csv by pandas where distance between each point and polygon will come in separate rows. i got this:

poly total inside outside dist
1000   2     0      2     [16015,5678]
1100   1     0      1     [5267]

I wanted to get like:

poly total inside outside dist
1000   2    0       2     16015
1000   2    0       2     5678
1100   1    0       1     5267

I tried the following after looking at this previous q [How to write nth value of list into csv file

distance =[]
for row in arcpy.da.SearchCursor(outSide, ["SHAPE@XY"]):
            px, py = row[0]
            zipPoint=point(px,py)
            Distance.append(int(zipPoint.calDist(PolyCenter)))
for i in distance:
    df.loc[polygon,"distance"]=distance
    df.loc[zipCode,"Total"]=count
    df.loc[zipCode,"Inside"]=insideNum
    df.loc[zipCode,"Outside"]=outsideNum

But its giving me the same result in csv. any help is appreciated.

Body:
i got a solution..

df2=df.fillna(0)
s=df2.apply(lambda x:pd.Series(x['Distances']),axis=1).stack().reset_index(level=1, drop=True)
s.name="Distance"
df3=df2.drop("Distances",axis=1).join(s)

it looked like:
    enter code here

32811   253  221  32  20
32811  253  221  32  3015
32811   253  221  32  2010

Thanks you for your help..still i would appreciate if you can give me a solution for error: 'ValueError: invalid literal for long() with base 10: '[16015, 5678]''.