问:
How to set elasticsearch index.mapping.total_fields.limit to unlimited
I am dealing with a huge json blob so I need to open the seal. How can I set elasticsearch index.mapping.total_fields.limit to unlimited?

答:
I don't think that current implementation allow you to set this value to unlimited.

As you probably know the default value is already high(1000) as described in official docs.

And if you check the source code you can see that current implementation does not allow for unlimited(like setting to -1 for instance), as you can see in the following fragment of code taken from official elasticsearch source code:

private void checkTotalFieldsLimit(long totalMappers) {
    long allowedTotalFields = indexSettings.getValue(INDEX_MAPPING_TOTAL_FIELDS_LIMIT_SETTING);
    if (allowedTotalFields < totalMappers) {
        throw new IllegalArgumentException("Limit of total fields [" + allowedTotalFields + "] in index [" + index().getName() + "] has been exceeded");
    }
}
```

I believe your best option is to set it to a very high value when mapping your index and check if the overhead is acceptable for your use case.

Body:
I don't think that current implementation allow you to set this value to unlimited.

As you probably know the default value is already high(1000) as described in official docs.

And if you check the source code you can see that current implementation does not allow for unlimited(like setting to -1 for instance), as you can see in the following fragment of code taken from official elasticsearch source code:

private void checkTotalFieldsLimit(long totalMappers) {
    long allowedTotalFields = indexSettings.getValue(INDEX_MAPPING_TOTAL_FIELDS_LIMIT_SETTING);
    if (allowedTotalFields < totalMappers) {
        throw new IllegalArgumentException("Limit of total fields [" + allowedTotalFields + "] in index [" + index().getName() + "] has been exceeded");
    }
}

I believe your best option is to set it to a very high value when mapping your index and check if the overhead is acceptable for your use case.


来源: stackexchange

问:
How to use unicode in CodeIgniter?
I am using CI framework for my project. If I use like this

```<code>$title= "प्रदेश";      // प्रदेश is written in nepali langauge.

echo $title;        // It will display प्रदेश
</code>```

Now I want to use

```<code><a href = "<?php echo base_url("home/$title")?>">    //home is a controller
</code>```

Now In home controller if I tried to display$title it will not show प्रदेश.

It will display like this %E0%A4%AA%E0%A5%8D%E0%A4%B0%E0%A4%A6%E0%A5%87%E0%A4%B6

Please help me.

答:
The base_url calls urlencode on the string, which makes it into url entities.

A space becomes %20 and things like that.

The url that is displayed is actually correct and should be interpretted correctly by the server, even if it's gibberish according to humans.

If you really want the human readable characters for some reason you can do two approaches, urldecode the resulting url(not recommended):

```<code>echo urldecode(base_url("home/$title"));
</code>```

or

```<code>echo base_url("home/").$title
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to use unicode in CodeIgniter?

Body:
I am using CI framework for my project. If I use like this

$title= "प्रदेश";      // प्रदेश is written in nepali langauge.

echo $title;        // It will display प्रदेश

Now I want to use

<a href = "<?php echo base_url("home/$title")?>">    //home is a controller

Now In home controller if I tried to display$title it will not show प्रदेश.

It will display like this %E0%A4%AA%E0%A5%8D%E0%A4%B0%E0%A4%A6%E0%A5%87%E0%A4%B6

Please help me.

Body:
The base_url calls urlencode on the string, which makes it into url entities.

A space becomes %20 and things like that.

The url that is displayed is actually correct and should be interpretted correctly by the server, even if it's gibberish according to humans.

If you really want the human readable characters for some reason you can do two approaches, urldecode the resulting url(not recommended):

echo urldecode(base_url("home/$title"));

or

echo base_url("home/").$title


问:
How to change the primary key value in sql server?
I am using SQL server 2014.

In my table, I set primary key for the column.The primary key value starts from 1. I want to change it to start from 0. How can I achieve this?

答:
this creates a table where the autoinc fields starts with 0 in stead of 1

Also it is best to name your primary key

```<code>CREATE TABLE myTable
(
    id int IDENTITY(0,1),
    othercolumn int,
    and so on...

    constraint PK_myTableID primary key (id)
)
</code>```

If however you want to do this with an existing table than your best option is to use Element Zero's anwser

Body:
this creates a table where the autoinc fields starts with 0 in stead of 1

Also it is best to name your primary key

CREATE TABLE myTable
(
    id int IDENTITY(0,1),
    othercolumn int,
    and so on...

    constraint PK_myTableID primary key (id)
)

If however you want to do this with an existing table than your best option is to use Element Zero's anwser


问:
Can't figure out how to do this all in one function
I am creating a zoo simulation game in Unity 5.4.0f3 using C#. I am trying to spawn a bear prefab clone, do some math, wait for a period of time, do some more math, then destroy the clone object all in one function. Here is what I have right now. The math that I am trying to do in WaitForBearLife() does not happen. Thanks in advance!</p>

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

public class BuyBearButton : MonoBehaviour
{
    [SerializeField] GameManager gameManager;
    [SerializeField] GameObject bearPrefab;
    [SerializeField] Visitor visitor;

    GameObject bearClone;

    float xMin = -15;
    float xMax = 15;
    float yMin = 5;
    float yMax = 6;

    public void BuyBear()
    {
        Vector2 pos = new Vector2 (Random.Range (xMin, xMax), Random.Range (yMin, yMax));

        if (gameManager.myMoney >= gameManager.bearCost)
        {
            gameManager.numberOfBears++;
            gameManager.myMoney = gameManager.myMoney - gameManager.bearCost;
            visitor.spawnTime = visitor.spawnTime / visitor.bearAttraction;
            bearClone = (GameObject) Instantiate (bearPrefab, pos, transform.rotation);
            StartCoroutine (WaitForBearLife ());
            Destroy (bearClone, gameManager.bearLife);
        }
    }

    IEnumerator WaitForBearLife()
    {
        yield return new WaitForSeconds (gameManager.bearLife);
        visitor.spawnTime = visitor.spawnTime * visitor.bearAttraction;
    }
}
</code>```

答:
I've just copied your code in an empty project, and made placeholder classes for GameManager and Visitor, just with random values in the variables we need in this script. It works just fine... really.So, I'll make you some questions (as I don't have the reputation yet to comment in your post...)

First, there's a script in the bear prefab of any sorts?

This is because it maybe have something that could interrupt the coroutine. It seems unlikely, but you can't know for sure until you try.

Next, how is the declaration of Visitor and GameManager?

The very beginning, when you define the class name and such. In fact, I would like to know more about the variables you used, like gameManager.bearLife and such.

Now, let's see the values.

I've tried with:

```<code>public int myMoney = 50000;
public int bearCost = 50;
public int numberOfBears = 0;
public float bearLife = 2.0f;
</code>```

In GameManager. And:

```<code>public float spawnTime = 5;
public float bearAttraction = 2;
</code>```

In Visitor. It does some weird math, and the logic of this script itself is clearly in development right now, I suppose. But the point is, it works, and with this:

```<code>IEnumerator WaitForBearLife()
{
    yield return new WaitForSeconds (gameManager.bearLife);
    print (visitor.spawnTime);
    visitor.spawnTime = visitor.spawnTime * visitor.bearAttraction;
    print (visitor.spawnTime);
}
</code>```

I get 2.5 and 5 in the correspondant prints if I only click once. Some prints (As @Benjamin-lecomte stated) could help you to know if it's even executing that part.

For now, I can't help you without knowing much more. So I'll wait for your answer, then.

Body:
I am creating a zoo simulation game in Unity 5.4.0f3 using C#. I am trying to spawn a bear prefab clone, do some math, wait for a period of time, do some more math, then destroy the clone object all in one function. Here is what I have right now. The math that I am trying to do in WaitForBearLife() does not happen. Thanks in advance!

using UnityEngine;
using System.Collections;

public class BuyBearButton : MonoBehaviour
{
    [SerializeField] GameManager gameManager;
    [SerializeField] GameObject bearPrefab;
    [SerializeField] Visitor visitor;

    GameObject bearClone;

    float xMin = -15;
    float xMax = 15;
    float yMin = 5;
    float yMax = 6;

    public void BuyBear()
    {
        Vector2 pos = new Vector2 (Random.Range (xMin, xMax), Random.Range (yMin, yMax));

        if (gameManager.myMoney >= gameManager.bearCost)
        {
            gameManager.numberOfBears++;
            gameManager.myMoney = gameManager.myMoney - gameManager.bearCost;
            visitor.spawnTime = visitor.spawnTime / visitor.bearAttraction;
            bearClone = (GameObject) Instantiate (bearPrefab, pos, transform.rotation);
            StartCoroutine (WaitForBearLife ());
            Destroy (bearClone, gameManager.bearLife);
        }
    }

    IEnumerator WaitForBearLife()
    {
        yield return new WaitForSeconds (gameManager.bearLife);
        visitor.spawnTime = visitor.spawnTime * visitor.bearAttraction;
    }
}

Body:
I've just copied your code in an empty project, and made placeholder classes for GameManager and Visitor, just with random values in the variables we need in this script. It works just fine... really.So, I'll make you some questions (as I don't have the reputation yet to comment in your post...)

First, there's a script in the bear prefab of any sorts?

This is because it maybe have something that could interrupt the coroutine. It seems unlikely, but you can't know for sure until you try.

Next, how is the declaration of Visitor and GameManager?

The very beginning, when you define the class name and such. In fact, I would like to know more about the variables you used, like gameManager.bearLife and such.

Now, let's see the values.

I've tried with:

public int myMoney = 50000;
public int bearCost = 50;
public int numberOfBears = 0;
public float bearLife = 2.0f;

In GameManager. And:

public float spawnTime = 5;
public float bearAttraction = 2;

In Visitor. It does some weird math, and the logic of this script itself is clearly in development right now, I suppose. But the point is, it works, and with this:

IEnumerator WaitForBearLife()
{
    yield return new WaitForSeconds (gameManager.bearLife);
    print (visitor.spawnTime);
    visitor.spawnTime = visitor.spawnTime * visitor.bearAttraction;
    print (visitor.spawnTime);
}

I get 2.5 and 5 in the correspondant prints if I only click once. Some prints (As @Benjamin-lecomte stated) could help you to know if it's even executing that part.

For now, I can't help you without knowing much more. So I'll wait for your answer, then.


问:
Cannot convert value of type string to type url in coercion

I'm receiving the error Cannot convert value of type string
  to type url in coercion at this constant. Thanks for the help ahead of time :)

```<code>**let safariVC = SFSafariViewController(url: JobUrl as URL)**
</code>```

```<code>import UIKit
import SafariServices

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    //Indeed API Query as JSON
   final let urlString = "http://api.indeed.com/ads/apisearch?publisher=9727336427429597&as_phr=&as_any=&as_not=&as_ttl=&as_cmp=&jt=parttime&st=&salary=&radius=25&l=32304&fromage=any&limit=25&sort=&psf=advsrch=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2&format=json"

    @IBOutlet weak var tableView: UITableView!

    var jobTitleArray = [String]()
    var snippetArray = [String]()
    var companyArray = [String]()
    var cityArray = [String]()
    var jobUrlArray = [String]()

//    url = URL(string: epsDictionary["link"] as! String)

    override func viewDidLoad() {
        super.viewDidLoad()

        self.downloadJsonWithURL()

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        //dispose of any resources that can be recreated
    }

    //fetch Json
    func downloadJsonWithURL() {
        let url = NSURL(string: urlString)
        URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) ->
            Void in

            if let JsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                as? NSDictionary {
                print(JsonObj!.value(forKey: "results")!)

                if let resultsArray = JsonObj!.value(forKey: "results") as? NSArray {
                    for result in resultsArray {
                        if let resultDict = result as? NSDictionary {

                            if let jobTitle = resultDict.value(forKey: "jobtitle") {
                                self.jobTitleArray.append(jobTitle as! String)
                            }
                            if let snippet = resultDict.value(forKey: "snippet") {
                                self.snippetArray.append(snippet as! String)
                            }
                            if let company = resultDict.value(forKey: "company") {
                                self.companyArray.append(company as! String)
                            }
                            if let city = resultDict.value(forKey: "formattedRelativeTime") {
                                self.cityArray.append(city as! String)
                            }
                            if let jobUrl1 = resultDict.value(forKey: "url") {
                                self.jobUrlArray.append(jobUrl1 as! String)
                            }

                            OperationQueue.main.addOperation({
                                self.tableView.reloadData()
                            })
                        }

                    }
                }

            }

        }).resume()
    }

    func downloadJsonWithTask() {
        let url = NSURL(string: urlString)

        var downloadTask = URLRequest(url: (url as? URL)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)

        downloadTask.httpMethod = "Get"

        URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) ->
        Void in

        let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)

            print(jsonData!)

        }).resume()

    }

     var jobToUrl = URL(string: "http://www.indeed.com/viewjob?jk=5de353a4c580dce0&qd=8FiWEXDXvmdNb_GJC9BAOpLFMiNO7rztIOPtGp_-cISTa1VWcmBigetsBoobMSCXdNyr-z6ge7UiYg2Mx15EH6m1Aj3izkOw87NHJgxznYA&indpubnum=9727336427429597&atk=1bchrhjof5hgga1k")

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)

        print("USER SELECTED CELL")
        let JobUrl = jobUrlArray[indexPath.row]

        **let safariVC = SFSafariViewController(url: JobUrl as URL)**
        self.present(safariVC, animated: true, completion: nil)

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return jobTitleArray.count
    }

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
        cell.jobTitle.text = jobTitleArray[indexPath.row]
        cell.jobSummary.text = snippetArray[indexPath.row]
        cell.employerName.text = companyArray[indexPath.row]
        cell.cityName.text = cityArray[indexPath.row]
        cell.ApplyButton.text = jobUrlArray[indexPath.row]

//        let imageUrl = NSURL(string: imageUrlArray[indexPath.row])

//        if imageUrl != nil {
//            let data = NSData(contentsOf: (imageUrl as? URL)!)
//            cell.imageView?.image = UIImage (data: data as! Data)
//        }

        return cell

    }

}
</code>```

答:
You can't cast a string to a URL. Casting simply says "Ok, the thing in this box. It's not a string, it's an URL." If the object can't double as the other class, the cast fails.

You need to create a URL using a string as input:

```<code>let url = URL(string: myString)
</code>```

Body:
I'm receiving the error Cannot convert value of type string
  to type url in coercion at this constant. Thanks for the help ahead of time :)

**let safariVC = SFSafariViewController(url: JobUrl as URL)**

import UIKit
import SafariServices

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    //Indeed API Query as JSON
   final let urlString = "http://api.indeed.com/ads/apisearch?publisher=9727336427429597&as_phr=&as_any=&as_not=&as_ttl=&as_cmp=&jt=parttime&st=&salary=&radius=25&l=32304&fromage=any&limit=25&sort=&psf=advsrch=&userip=1.2.3.4&useragent=Mozilla/%2F4.0%28Firefox%29&v=2&format=json"

    @IBOutlet weak var tableView: UITableView!

    var jobTitleArray = [String]()
    var snippetArray = [String]()
    var companyArray = [String]()
    var cityArray = [String]()
    var jobUrlArray = [String]()

//    url = URL(string: epsDictionary["link"] as! String)

    override func viewDidLoad() {
        super.viewDidLoad()

        self.downloadJsonWithURL()

        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        //dispose of any resources that can be recreated
    }

    //fetch Json
    func downloadJsonWithURL() {
        let url = NSURL(string: urlString)
        URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) ->
            Void in

            if let JsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
                as? NSDictionary {
                print(JsonObj!.value(forKey: "results")!)

                if let resultsArray = JsonObj!.value(forKey: "results") as? NSArray {
                    for result in resultsArray {
                        if let resultDict = result as? NSDictionary {

                            if let jobTitle = resultDict.value(forKey: "jobtitle") {
                                self.jobTitleArray.append(jobTitle as! String)
                            }
                            if let snippet = resultDict.value(forKey: "snippet") {
                                self.snippetArray.append(snippet as! String)
                            }
                            if let company = resultDict.value(forKey: "company") {
                                self.companyArray.append(company as! String)
                            }
                            if let city = resultDict.value(forKey: "formattedRelativeTime") {
                                self.cityArray.append(city as! String)
                            }
                            if let jobUrl1 = resultDict.value(forKey: "url") {
                                self.jobUrlArray.append(jobUrl1 as! String)
                            }

                            OperationQueue.main.addOperation({
                                self.tableView.reloadData()
                            })
                        }

                    }
                }

            }

        }).resume()
    }

    func downloadJsonWithTask() {
        let url = NSURL(string: urlString)

        var downloadTask = URLRequest(url: (url as? URL)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)

        downloadTask.httpMethod = "Get"

        URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) ->
        Void in

        let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)

            print(jsonData!)

        }).resume()

    }

     var jobToUrl = URL(string: "http://www.indeed.com/viewjob?jk=5de353a4c580dce0&qd=8FiWEXDXvmdNb_GJC9BAOpLFMiNO7rztIOPtGp_-cISTa1VWcmBigetsBoobMSCXdNyr-z6ge7UiYg2Mx15EH6m1Aj3izkOw87NHJgxznYA&indpubnum=9727336427429597&atk=1bchrhjof5hgga1k")

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)

        print("USER SELECTED CELL")
        let JobUrl = jobUrlArray[indexPath.row]

        **let safariVC = SFSafariViewController(url: JobUrl as URL)**
        self.present(safariVC, animated: true, completion: nil)

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return jobTitleArray.count
    }

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
        cell.jobTitle.text = jobTitleArray[indexPath.row]
        cell.jobSummary.text = snippetArray[indexPath.row]
        cell.employerName.text = companyArray[indexPath.row]
        cell.cityName.text = cityArray[indexPath.row]
        cell.ApplyButton.text = jobUrlArray[indexPath.row]

//        let imageUrl = NSURL(string: imageUrlArray[indexPath.row])

//        if imageUrl != nil {
//            let data = NSData(contentsOf: (imageUrl as? URL)!)
//            cell.imageView?.image = UIImage (data: data as! Data)
//        }

        return cell

    }

}

Body:
You can't cast a string to a URL. Casting simply says "Ok, the thing in this box. It's not a string, it's an URL." If the object can't double as the other class, the cast fails.

You need to create a URL using a string as input:

let url = URL(string: myString)


问:
Displaying text during each loop iteration
This is hopefully a reasonably simple question. But, this is my first time posting a question into a forum so it's highly possible that I won't convey my question well. If so, sorry in advance.

So I want to print some text from inside a for loop and then have Julia wait for a response during each iteration.
    However, the code that I have using (which is below) asks for an input during each iteration and displays all text once the entire loop is finished.
    A factor which might be important to note is that I have been doing all of my coding on the Juliabox website.

This is what I have been using:

```<code>A = [1,2,3,4,5,6];
answer = "n";
for k = 1:length(A)
    prompt = "Is this a 3? (enter y/n)";
    println(prompt)
    answer = chomp(readline())
    if answer == "y"
        #do something
    elseif answer == "n"
        #do something else
    end
end
</code>```

This is the result I obtain:

```<code>STDIN> n
STDIN> n
Is this a 3? (enter y/n)
Is this a 3? (enter y/n)
</code>```

答: I think this must be an artefact of the JuliaBox IDE, your code runs correctly at: https://www.tutorialspoint.com/execute_julia_online.php</p>

ContentLicense: CC BY-SA 4.0

Body:
This is hopefully a reasonably simple question. But, this is my first time posting a question into a forum so it's highly possible that I won't convey my question well. If so, sorry in advance.

So I want to print some text from inside a for loop and then have Julia wait for a response during each iteration.
    However, the code that I have using (which is below) asks for an input during each iteration and displays all text once the entire loop is finished.
    A factor which might be important to note is that I have been doing all of my coding on the Juliabox website.

This is what I have been using:

A = [1,2,3,4,5,6];
answer = "n";
for k = 1:length(A)
    prompt = "Is this a 3? (enter y/n)";
    println(prompt)
    answer = chomp(readline())
    if answer == "y"
        #do something
    elseif answer == "n"
        #do something else
    end
end

This is the result I obtain:

STDIN> n
STDIN> n
Is this a 3? (enter y/n)
Is this a 3? (enter y/n)


问:
parsing a cv file
I want to write a code either in Java or PHP (Codeigniter) to extract information such as email and phone number of a user uploading hbis resume or cv to the site. Basically I want to build a cv parser.

Need help for this.

thanks

EDIT
The cv format will be in doc.

答:
As @Corbin said, there is no standard CV format. It will be quite difficult to parse with 100% accuracy.

Though, you can try Apache Tika - A Content Analysis Toolkit to parse resume doc/docx format. Apache also support many document format including pdf, txt, xml, odf etc.

Btw, extracting email and phone number from resume can be achieved with few lines of code with the help of regex after getting whole contents from cv using Apache Tika.

Let me know if you get stuck.

Hope this helps!

Note- (I am working on resume summarizer).

ContentLicense: CC BY-SA 2.5

Title: parsing a cv file


问:
Xcode 8 A valid provisioning profile for this executable was not found
I know there are other questions asked like this here but I've followed all their solutions yet still end up with this error message.

I have a valid Apple Developer account with program active.

I have tried using managed and unmanaged provisioning with new/fresh bundle ID's (which get recreated provisioning profiles).

I have tried this: A valid provisioning profile for this executable was not found for debug mode

I have tried this: XCode :7 App installation failed :A valid provisioning profile for this executable was not found

I have deleted any old versions of the app from my phone.

I have confirmed my device ID on the developer portal is the same as in Xcode (was also useful for manual provisioning profile management to confirm)

I even tried another developer ID I have out of sheer desperation and yet the same error appears.

I even get this error when building for release scheme with my valid distribution certificate.

I've spent a ton of time trying to figure this out now I'm hoping someone else has felt my pain and actually solved this.

UPDATE: Adding screenshots for usefulness

UPDATE 2: I gave up trying to solve this problem, I created a new project and copied source files into the new project and I now have it working. Clearly something in the project configuration/settings files got corrupted somehow in the previous project which no obvious fix available. Will leave this question open, perhaps someone has a solution eventually. I have my old 'non-working' project so will continue to try those just for curiousities sake.

Before this error message, Build Succeeded is shown.

答: I'm on 8.2.1 and just had this same error.  Deleting the original project folder and recreating it worked seamlessly.  I verified that all of the signing and provisioning certificates were exactly the same as the last project.  I'm not sure where the issue lies, but I believe your assumption of corrupted files is accurate.</p>


问:
How to add triangle to input[type='text']
I want to add a small triangle to the upper-right corner of an input type='text' HTML element, like Excel uses to indicate a comment.

The accepted answer to this question:

How to add triangle in table cell

shows how to do it for a table cell.  I naively applied the "note" css class to my input element but it didn't work.  Any suggestions for how to achieve this?

答:
Pseudo elements can't be used on input's. You can use the same CSS as described in the linked post (here) but you would have to apply the class to an ancestor.

.note {
    position: relative;
    display: inline-block;
}
.note:after {
    content: "";
    position: absolute;
    top: 0;
    right: 0;
    width: 0;
    height: 0;
    display: block;
    border-left: 20px solid transparent;
    border-bottom: 20px solid transparent;
    border-top: 20px solid #f00;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="note">
  <input type="text">
</div></code>```

Body:
Pseudo elements can't be used on input's. You can use the same CSS as described in the linked post (here) but you would have to apply the class to an ancestor.

.note {
    position: relative;
    display: inline-block;
}
.note:after {
    content: "";
    position: absolute;
    top: 0;
    right: 0;
    width: 0;
    height: 0;
    display: block;
    border-left: 20px solid transparent;
    border-bottom: 20px solid transparent;
    border-top: 20px solid #f00;
}

<div class="note">
  <input type="text">
</div>


答:
String and URL are not related therefore cannot be casted to each other. You have to create the URL from a string (like in another line in the code).

```<code>let safariVC = SFSafariViewController(url: URL(string: JobUrl)!)
</code>```

Don't use NSURL in Swift 3 at all.

PS: Be aware that all optional bindings in downloadJsonWithURL are meaningless if you are using multiple arrays as data source. If one value does not pass the binding the app will crash at the latest in cellForRow due to an out-of-range exception.

Title: Cannot convert value of type string to type url in coercion

Body:
String and URL are not related therefore cannot be casted to each other. You have to create the URL from a string (like in another line in the code).

let safariVC = SFSafariViewController(url: URL(string: JobUrl)!)

Don't use NSURL in Swift 3 at all.

PS: Be aware that all optional bindings in downloadJsonWithURL are meaningless if you are using multiple arrays as data source. If one value does not pass the binding the app will crash at the latest in cellForRow due to an out-of-range exception.


问:
Compiling C++ program using H5Cpp.h header file
I'm need to create a HDF5 file. I'm using the H5Cpp.h header file.
I'm trying to compile the C++ code below on OSX 10.11 El Capitan.

```<code>#include "include/hdf5-1.10.0-patch1/c++/src/H5Cpp.h"
using namespace H5;

const int NX = 5;
const int NY = 5;
const H5std_string  FILE_NAME( "SDS.h5" );
const H5std_string  DATASET_NAME( "IntArray" );

int main(){
  int i, j;
  int data[NX][NY];          // buffer for data to write
  for (j = 0; j < NX; j++){
    for (i = 0; i < NY; i++)
      data[j][i] = i + j;
  }
  H5File file(FILE_NAME, H5F_ACC_TRUNC);
  hsize_t dimsf[2] = {NX, NY};
  DataSpace dataspace(2, dimsf);
  DataSet dataset = file.createDataSet(DATASET_NAME, PredType::NATIVE_INT,
                       dataspace);
  // Attempt to write data to HDF5 file
  dataset.write(data, PredType::NATIVE_DOUBLE);
  return 0;
}
</code>```

I keep getting this error,

```<code>ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [all] Error 1
</code>```

Here's the verbose output - https://gist.github.com/gkarthik/e21d2f83baffc2d2eb1b883696c44df8

Thanks!

答:
A few tips:

I think that you have to compile the HDF5 library yourself if you haven't the pre-built binaries. At the HDF5 website there are no pre-built binaries for Mac (as far as I can see).

In windows, to compile a C++ application to use the HDF5 library you have to indicate to the linker the following dependencies (in this order), maybe in mac is also imperative:
szip.lib zlib.lib hdf5.lib hdf5_cpp.lib

If you download some pre-built binaries, there is a file that will indicate the steps to compile your C++ program. In windows it is called: "USING_HDF5_CMake.txt" and "USING_HDF5_VS.txt". You can find these files for example here.

Body:
I'm need to create a HDF5 file. I'm using the H5Cpp.h header file.
I'm trying to compile the C++ code below on OSX 10.11 El Capitan.

#include "include/hdf5-1.10.0-patch1/c++/src/H5Cpp.h"
using namespace H5;

const int NX = 5;
const int NY = 5;
const H5std_string  FILE_NAME( "SDS.h5" );
const H5std_string  DATASET_NAME( "IntArray" );

int main(){
  int i, j;
  int data[NX][NY];          // buffer for data to write
  for (j = 0; j < NX; j++){
    for (i = 0; i < NY; i++)
      data[j][i] = i + j;
  }
  H5File file(FILE_NAME, H5F_ACC_TRUNC);
  hsize_t dimsf[2] = {NX, NY};
  DataSpace dataspace(2, dimsf);
  DataSet dataset = file.createDataSet(DATASET_NAME, PredType::NATIVE_INT,
                       dataspace);
  // Attempt to write data to HDF5 file
  dataset.write(data, PredType::NATIVE_DOUBLE);
  return 0;
}

I keep getting this error,

ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [all] Error 1

Here's the verbose output - https://gist.github.com/gkarthik/e21d2f83baffc2d2eb1b883696c44df8

Thanks!


问:
How to insert newlines on argparse help text?
I'm using argparse in Python 2.7 for parsing input options. One of my options is a multiple choice. I want to make a list in its help text, e.g.

```<code>from argparse import ArgumentParser

parser = ArgumentParser(description='test')

parser.add_argument('-g', choices=['a', 'b', 'g', 'd', 'e'], default='a',
    help="Some option, where\n"
         " a = alpha\n"
         " b = beta\n"
         " g = gamma\n"
         " d = delta\n"
         " e = epsilon")

parser.parse_args()
</code>```

However, argparse strips all newlines and consecutive spaces. The result looks like

```
~/Downloads:52$ python2.7 x.py -h
usage: x.py [-h] [-g {a,b,g,d,e}]

test

optional arguments:
  -h, --help      show this help message and exit
  -g {a,b,g,d,e}  Some option, where a = alpha b = beta g = gamma d = delta e
                  = epsilon
```

How to insert newlines in the help text?

答:
I wanted to have both manual line breaks in the description text, and auto wrapping of it; but none of the suggestions here worked for me - so I ended up modifying the SmartFormatter class given in the answers here; the issues with the argparse method names not being a public API notwithstanding, here is what I have (as a file called test.py):

```<code>import argparse
from argparse import RawDescriptionHelpFormatter

# call with: python test.py -h

class SmartDescriptionFormatter(argparse.RawDescriptionHelpFormatter):
  #def _split_lines(self, text, width): # RawTextHelpFormatter, although function name might change depending on Python
  def _fill_text(self, text, width, indent): # RawDescriptionHelpFormatter, although function name might change depending on Python
    #print("splot",text)
    if text.startswith('R|'):
      paragraphs = text[2:].splitlines()
      rebroken = [argparse._textwrap.wrap(tpar, width) for tpar in paragraphs]
      #print(rebroken)
      rebrokenstr = []
      for tlinearr in rebroken:
        if (len(tlinearr) == 0):
          rebrokenstr.append("")
        else:
          for tlinepiece in tlinearr:
            rebrokenstr.append(tlinepiece)
      #print(rebrokenstr)
      return '\n'.join(rebrokenstr) #(argparse._textwrap.wrap(text[2:], width))
    # this is the RawTextHelpFormatter._split_lines
    #return argparse.HelpFormatter._split_lines(self, text, width)
    return argparse.RawDescriptionHelpFormatter._fill_text(self, text, width, indent)

parser = argparse.ArgumentParser(formatter_class=SmartDescriptionFormatter, description="""R|Blahbla bla blah blahh/blahbla (bla blah-blabla) a blahblah bl a blaha-blah .blah blah

Blah blah bla blahblah, bla blahblah blah blah bl blblah bl blahb; blah bl blah bl bl a blah, bla blahb bl:

  blah blahblah blah bl blah blahblah""")

options = parser.parse_args()
</code>```

This is how it works in 2.7 and 3.4:

$ python test.py -h
usage: test.py [-h]

Blahbla bla blah blahh/blahbla (bla blah-blabla) a blahblah bl a blaha-blah
.blah blah

Blah blah bla blahblah, bla blahblah blah blah bl blblah bl blahb; blah bl
blah bl bl a blah, bla blahb bl:

  blah blahblah blah bl blah blahblah

optional arguments:
  -h, --help  show this help message and exit
```

Body:
I'm using argparse in Python 2.7 for parsing input options. One of my options is a multiple choice. I want to make a list in its help text, e.g.

from argparse import ArgumentParser

parser = ArgumentParser(description='test')

parser.add_argument('-g', choices=['a', 'b', 'g', 'd', 'e'], default='a',
    help="Some option, where\n"
         " a = alpha\n"
         " b = beta\n"
         " g = gamma\n"
         " d = delta\n"
         " e = epsilon")

parser.parse_args()

However, argparse strips all newlines and consecutive spaces. The result looks like

~/Downloads:52$ python2.7 x.py -h
usage: x.py [-h] [-g {a,b,g,d,e}]

test

optional arguments:
  -h, --help      show this help message and exit
  -g {a,b,g,d,e}  Some option, where a = alpha b = beta g = gamma d = delta e
                  = epsilon

How to insert newlines in the help text?

Body:
I wanted to have both manual line breaks in the description text, and auto wrapping of it; but none of the suggestions here worked for me - so I ended up modifying the SmartFormatter class given in the answers here; the issues with the argparse method names not being a public API notwithstanding, here is what I have (as a file called test.py):

import argparse
from argparse import RawDescriptionHelpFormatter

# call with: python test.py -h

class SmartDescriptionFormatter(argparse.RawDescriptionHelpFormatter):
  #def _split_lines(self, text, width): # RawTextHelpFormatter, although function name might change depending on Python
  def _fill_text(self, text, width, indent): # RawDescriptionHelpFormatter, although function name might change depending on Python
    #print("splot",text)
    if text.startswith('R|'):
      paragraphs = text[2:].splitlines()
      rebroken = [argparse._textwrap.wrap(tpar, width) for tpar in paragraphs]
      #print(rebroken)
      rebrokenstr = []
      for tlinearr in rebroken:
        if (len(tlinearr) == 0):
          rebrokenstr.append("")
        else:
          for tlinepiece in tlinearr:
            rebrokenstr.append(tlinepiece)
      #print(rebrokenstr)
      return '\n'.join(rebrokenstr) #(argparse._textwrap.wrap(text[2:], width))
    # this is the RawTextHelpFormatter._split_lines
    #return argparse.HelpFormatter._split_lines(self, text, width)
    return argparse.RawDescriptionHelpFormatter._fill_text(self, text, width, indent)

parser = argparse.ArgumentParser(formatter_class=SmartDescriptionFormatter, description="""R|Blahbla bla blah blahh/blahbla (bla blah-blabla) a blahblah bl a blaha-blah .blah blah

Blah blah bla blahblah, bla blahblah blah blah bl blblah bl blahb; blah bl blah bl bl a blah, bla blahb bl:

  blah blahblah blah bl blah blahblah""")

options = parser.parse_args()

This is how it works in 2.7 and 3.4:

$ python test.py -h
usage: test.py [-h]

Blahbla bla blah blahh/blahbla (bla blah-blabla) a blahblah bl a blaha-blah
.blah blah

Blah blah bla blahblah, bla blahblah blah blah bl blblah bl blahb; blah bl
blah bl bl a blah, bla blahb bl:

  blah blahblah blah bl blah blahblah

optional arguments:
  -h, --help  show this help message and exit


问:
Connect 4 winning method
I've created this method to check for horizontal matches (then I will expand in vertical and diagonally) but the problem is that my method "triggers" only when there are 5 tiles on the same column, and I want to trigger when I have 4. This is the method I created. I'm using an 1 dimensional array. I can give you the whole code if you need it.

```<code>  public partial class Form1 : Form
 {
     Button[] gameButtons = new Button[42]; //array of buttons for  markers(red and blue)
    bool blue = true;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Text = "Connect 4";
        this.BackColor = Color.BlanchedAlmond;
        this.Width = 500;
        this.Height = 500;

        for (int i = 0; i < gameButtons.Length; i++)
        {
            int index = i;
            this.gameButtons[i] = new Button();
            int x = 50 + (i % 7) * 50;
            int y = 50 + (i / 7) * 50;

            this.gameButtons[i].Location = new System.Drawing.Point(x, y);
            this.gameButtons[i].Name = "btn" + (index + 1);
            this.gameButtons[i].Size = new System.Drawing.Size(50, 50);
            this.gameButtons[i].TabIndex = i;
            //this.gameButtons[i].Text = Convert.ToString(index);
            this.gameButtons[i].UseVisualStyleBackColor = true;
            this.gameButtons[i].Visible = true;

            gameButtons[i].Click += (sender1, ex) => this.buttonHasBeenPressed(sender1, index);
            this.Controls.Add(gameButtons[i]);
        }
    }
    {
        var pressedButton = (Button)sender;
        //getLocation(sender);

        if (pressedButton.BackColor == Color.BlanchedAlmond)
        {
            var newBackColor = blue ? Color.Blue : Color.Red;

            var buttonToChangeIndex = index;

            while (buttonToChangeIndex + 7 < gameButtons.Count() && gameButtons[buttonToChangeIndex + 7].BackColor == Color.BlanchedAlmond)
            {
                buttonToChangeIndex += 7;  // Set to the index to point to this button.
            }

            gameButtons[buttonToChangeIndex].BackColor = newBackColor;

            blue = !blue;

            winCon(sender,index);
        }

private void winCon(object sender, int index)
    {
        int xLocation = index % Width;
        int yLocation = index / Width;
        int j = xLocation + Width * yLocation;
        bool end = false;

        for (int k = 50; k < 150; k = k + 50)
        {
            if (j + k != j)
            {
                end = false;
            }
        }
        end = true;

        if (end == true)
        {
            if (gameButtons[j].BackColor == Color.Blue)
            {
                MessageBox.Show("There is a blue match");

            }
            if (gameButtons[j].BackColor == Color.Red)
            {
                MessageBox.Show("There is a red match");
            }
        }
}
</code>```

Edit: Added the whole code.
Edit 2: I just realised. My code isn't even working as it should even with 5 tiles. Where ever I click with my mouse I get the message " There is a blue/red match". I was just testing it wrong.

答:
I didn't quite understand what you want to do but j + k != j is always going to be true maybe you mean gameButtons[j + k] != gameButtons[j] and it doesn't matter anyway because the whole loop doesn't do anything end = true; is always going to be executed and the condition on the next if statement is going to be met maybe you mean to do this :

```<code>private void winCon(object sender, int index)
{
    int xLocation = index % Width;
    int yLocation = index / Width;
    int j = xLocation + Width * yLocation;
    bool end = true;

    for (int k = 50; k < 150; k = k + 50)
    {
        if (gameButtons[j + k] != gameButtons[j])
        {
            end = false;
        }
    }
    if (end == true)
    {
        if (gameButtons[j].BackColor == Color.Blue)
        {
            MessageBox.Show("There is a blue match");

        }
        if (gameButtons[j].BackColor == Color.Red)
        {
            MessageBox.Show("There is a red match");
        }
    }
}
</code>```

also the code inside your loop is only going to be executed twice, for k=50 and for k=100, for k=150 the condition is not met.

good luck

Title: Connect 4 winning method

Body:
I've created this method to check for horizontal matches (then I will expand in vertical and diagonally) but the problem is that my method "triggers" only when there are 5 tiles on the same column, and I want to trigger when I have 4. This is the method I created. I'm using an 1 dimensional array. I can give you the whole code if you need it.

  public partial class Form1 : Form
 {
     Button[] gameButtons = new Button[42]; //array of buttons for  markers(red and blue)
    bool blue = true;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        this.Text = "Connect 4";
        this.BackColor = Color.BlanchedAlmond;
        this.Width = 500;
        this.Height = 500;

        for (int i = 0; i < gameButtons.Length; i++)
        {
            int index = i;
            this.gameButtons[i] = new Button();
            int x = 50 + (i % 7) * 50;
            int y = 50 + (i / 7) * 50;

            this.gameButtons[i].Location = new System.Drawing.Point(x, y);
            this.gameButtons[i].Name = "btn" + (index + 1);
            this.gameButtons[i].Size = new System.Drawing.Size(50, 50);
            this.gameButtons[i].TabIndex = i;
            //this.gameButtons[i].Text = Convert.ToString(index);
            this.gameButtons[i].UseVisualStyleBackColor = true;
            this.gameButtons[i].Visible = true;

            gameButtons[i].Click += (sender1, ex) => this.buttonHasBeenPressed(sender1, index);
            this.Controls.Add(gameButtons[i]);
        }
    }
    {
        var pressedButton = (Button)sender;
        //getLocation(sender);

        if (pressedButton.BackColor == Color.BlanchedAlmond)
        {
            var newBackColor = blue ? Color.Blue : Color.Red;

            var buttonToChangeIndex = index;

            while (buttonToChangeIndex + 7 < gameButtons.Count() && gameButtons[buttonToChangeIndex + 7].BackColor == Color.BlanchedAlmond)
            {
                buttonToChangeIndex += 7;  // Set to the index to point to this button.
            }

            gameButtons[buttonToChangeIndex].BackColor = newBackColor;

            blue = !blue;

            winCon(sender,index);
        }

private void winCon(object sender, int index)
    {
        int xLocation = index % Width;
        int yLocation = index / Width;
        int j = xLocation + Width * yLocation;
        bool end = false;

        for (int k = 50; k < 150; k = k + 50)
        {
            if (j + k != j)
            {
                end = false;
            }
        }
        end = true;

        if (end == true)
        {
            if (gameButtons[j].BackColor == Color.Blue)
            {
                MessageBox.Show("There is a blue match");

            }
            if (gameButtons[j].BackColor == Color.Red)
            {
                MessageBox.Show("There is a red match");
            }
        }
}

Edit: Added the whole code.
Edit 2: I just realised. My code isn't even working as it should even with 5 tiles. Where ever I click with my mouse I get the message " There is a blue/red match". I was just testing it wrong.

Body:
I didn't quite understand what you want to do but j + k != j is always going to be true maybe you mean gameButtons[j + k] != gameButtons[j] and it doesn't matter anyway because the whole loop doesn't do anything end = true; is always going to be executed and the condition on the next if statement is going to be met maybe you mean to do this :

private void winCon(object sender, int index)
{
    int xLocation = index % Width;
    int yLocation = index / Width;
    int j = xLocation + Width * yLocation;
    bool end = true;

    for (int k = 50; k < 150; k = k + 50)
    {
        if (gameButtons[j + k] != gameButtons[j])
        {
            end = false;
        }
    }
    if (end == true)
    {
        if (gameButtons[j].BackColor == Color.Blue)
        {
            MessageBox.Show("There is a blue match");

        }
        if (gameButtons[j].BackColor == Color.Red)
        {
            MessageBox.Show("There is a red match");
        }
    }
}

also the code inside your loop is only going to be executed twice, for k=50 and for k=100, for k=150 the condition is not met.

good luck


问:
Android Studio: Package name not set to a valid package name

I want to create an activity in the "layout" package so I right-clicked it and selected new activity and it's giving me this error. How do I resolve it?

答: go to AndroidManifest.xml in your project, copy package name(3rd line) from there and past it here in the last field. </p>


问:
.NET Random Class picking always 0 when range is 0 or 1
I am writing a random question generator. I would like to pick one question from each section.

Random class with DateTime.Now.Milliseconds as seed value generates random numbers, if the range is greater than 2(0,2/2+). But, If I give a min of 0 and a max of 1 in the range, it always returns me 0.

Am I using it wrongly.

Please suggest if there are any other alternatives.

Thanks,
Mahesh

答:
You're calling Random.Next, which returns a random integer more than or equal to the first parameter and less than, but not equal to, the second.

Specifically, you're asking for an integer in the range [0, 1), which can only be zero.

If you're looking for an integer that is either 0 or 1, you need to call Random.Next(0, 2).

If you're looking for a real number between 0 and 1, you need to call Random.NextDouble.


问:
unable to integrate Neo4j 3 with Gephi 0.9
I tried all possible ways to connect Neo4j 3.1.1 database with Gephi 0.9.1 but it is not connecting

Environment :
OS: Windows 7 professional
JDK: 1.8
Neo4j: 3.1.1
Gephi: 0.9.1

答:
I have it running using Apoc plugin and it works as expected on windows.
What you need to do is install Gephi graph streaming plugin, which can be found Tools --> Plugins --> Available Plugins

Once you have graph streaming running we utilize apoc.gephi.add as in example:

```<code>match path = (:Person)-[:ACTED_IN]->(:Movie)
WITH path LIMIT 1000
with collect(path) as paths
call apoc.gephi.add(null,'workspace0', paths) yield nodes, relationships, time
return nodes, relationships, time
</code>```

For more info check documentation.

Body:
I have it running using Apoc plugin and it works as expected on windows.
What you need to do is install Gephi graph streaming plugin, which can be found Tools --> Plugins --> Available Plugins

Once you have graph streaming running we utilize apoc.gephi.add as in example:

match path = (:Person)-[:ACTED_IN]->(:Movie)
WITH path LIMIT 1000
with collect(path) as paths
call apoc.gephi.add(null,'workspace0', paths) yield nodes, relationships, time
return nodes, relationships, time

For more info check documentation.


问:
How do I import CSV file into a MySQL table?
I have an unnormalized events-diary CSV from a client that I'm trying to load into a MySQL table so that I can refactor into a sane format. I created a table called 'CSVImport' that has one field for every column of the CSV file. The CSV contains 99 columns , so this was a hard enough task in itself:

```<code>CREATE TABLE 'CSVImport' (id INT);
ALTER TABLE CSVImport ADD COLUMN Title VARCHAR(256);
ALTER TABLE CSVImport ADD COLUMN Company VARCHAR(256);
ALTER TABLE CSVImport ADD COLUMN NumTickets VARCHAR(256);
...
ALTER TABLE CSVImport Date49 ADD COLUMN Date49 VARCHAR(256);
ALTER TABLE CSVImport Date50 ADD COLUMN Date50 VARCHAR(256);
</code>```

No constraints are on the table, and all the fields hold VARCHAR(256) values, except the columns which contain counts (represented by INT), yes/no (represented by BIT), prices (represented by DECIMAL), and text blurbs (represented by TEXT).

I tried to load data into the file:

```<code>LOAD DATA INFILE '/home/paul/clientdata.csv' INTO TABLE CSVImport;
Query OK, 2023 rows affected, 65535 warnings (0.08 sec)
Records: 2023  Deleted: 0  Skipped: 0  Warnings: 198256
SELECT * FROM CSVImport;
| NULL             | NULL        | NULL           | NULL | NULL               |
...
</code>```

The whole table is filled with NULL.

I think the problem is that the text blurbs contain more than one line, and MySQL is parsing the file as if each new line would correspond to one databazse row. I can load the file into OpenOffice without a problem.

The clientdata.csv file contains 2593 lines, and 570 records. The first line contains column names. I think it is comma delimited, and text is apparently delimited with doublequote.

UPDATE:

When in doubt, read the manual: http://dev.mysql.com/doc/refman/5.0/en/load-data.html

I added some information to the LOAD DATA statement that OpenOffice was smart enough to infer, and now it loads the correct number of records:

```<code>LOAD DATA INFILE "/home/paul/clientdata.csv"
INTO TABLE CSVImport
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;
</code>```

But still there are lots of completely NULL records, and none of the data that got loaded seems to be in the right place.

答:
Here is sample excel file screen shot:

Save as  and choose .csv.

And you will have as shown below .csv data screen shot if you open using notepad++ or any other notepad.

Make sure you remove header and have column alignment in .csv as in mysql Table.
Replace folder_name by your folder name

LOAD DATA LOCAL INFILE

'D:/folder_name/myfilename.csv'
INTO TABLE mail
FIELDS TERMINATED BY ','
(fname,lname ,email, phone);

If big data, you can take coffee and have it load!.

Thats all you need.

Body:
I have an unnormalized events-diary CSV from a client that I'm trying to load into a MySQL table so that I can refactor into a sane format. I created a table called 'CSVImport' that has one field for every column of the CSV file. The CSV contains 99 columns , so this was a hard enough task in itself:

CREATE TABLE 'CSVImport' (id INT);
ALTER TABLE CSVImport ADD COLUMN Title VARCHAR(256);
ALTER TABLE CSVImport ADD COLUMN Company VARCHAR(256);
ALTER TABLE CSVImport ADD COLUMN NumTickets VARCHAR(256);
...
ALTER TABLE CSVImport Date49 ADD COLUMN Date49 VARCHAR(256);
ALTER TABLE CSVImport Date50 ADD COLUMN Date50 VARCHAR(256);

No constraints are on the table, and all the fields hold VARCHAR(256) values, except the columns which contain counts (represented by INT), yes/no (represented by BIT), prices (represented by DECIMAL), and text blurbs (represented by TEXT).

I tried to load data into the file:

LOAD DATA INFILE '/home/paul/clientdata.csv' INTO TABLE CSVImport;
Query OK, 2023 rows affected, 65535 warnings (0.08 sec)
Records: 2023  Deleted: 0  Skipped: 0  Warnings: 198256
SELECT * FROM CSVImport;
| NULL             | NULL        | NULL           | NULL | NULL               |
...

The whole table is filled with NULL.

I think the problem is that the text blurbs contain more than one line, and MySQL is parsing the file as if each new line would correspond to one databazse row. I can load the file into OpenOffice without a problem.

The clientdata.csv file contains 2593 lines, and 570 records. The first line contains column names. I think it is comma delimited, and text is apparently delimited with doublequote.

UPDATE:

When in doubt, read the manual: http://dev.mysql.com/doc/refman/5.0/en/load-data.html

I added some information to the LOAD DATA statement that OpenOffice was smart enough to infer, and now it loads the correct number of records:

LOAD DATA INFILE "/home/paul/clientdata.csv"
INTO TABLE CSVImport
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

But still there are lots of completely NULL records, and none of the data that got loaded seems to be in the right place.


问:
Lua unicode, using string.sub() with two-byted chars
As example: I want remove the first 2 letters from the string "ПРИВЕТ" and "HELLO." one of these are containing only two-byted unicode symbols.

Trying to use string.sub("ПРИВЕТ") and string.sub("HELLO.")

Got "РИВЕТ" and "LLO.".

string.sub() removed 2 BYTES(not chars) from these strings. So i want to know how to get the removing of the chars

Something, like utf8.sub()

答:
The key standard function for this task is utf8.offset(s,n), which gives the position in bytes of the start of the n-th character of s.

So try this:

```<code>print(string.sub(s,utf8.offset(s,3),-1))
</code>```

You can define utf8.sub as follows:

```<code>function utf8.sub(s,i,j)
    i=utf8.offset(s,i)
    j=utf8.offset(s,j+1)-1
    return string.sub(s,i,j)
end
</code>```

(This code only works for positive j. See http://lua-users.org/lists/lua-l/2014-04/msg00590.html for the general case.)

Body:
The key standard function for this task is utf8.offset(s,n), which gives the position in bytes of the start of the n-th character of s.

So try this:

print(string.sub(s,utf8.offset(s,3),-1))

You can define utf8.sub as follows:

function utf8.sub(s,i,j)
    i=utf8.offset(s,i)
    j=utf8.offset(s,j+1)-1
    return string.sub(s,i,j)
end

(This code only works for positive j. See http://lua-users.org/lists/lua-l/2014-04/msg00590.html for the general case.)


问:
Check that specific sequence exists or not in hibernate
I want to run a query like this -

```<code>"SELECT nextval('sequenceName')"
</code>```

but before this I want to check that sequenceName exists or not in Hibernate.

答:
The answer here gives me an idea Check if sequence exists in Postgres (plpgsql),
I don't know if this is a perfect solution or not but you can use :

```<code>SELECT COUNT(*)
FROM information_schema.sequences
WHERE sequence_schema='sch_name' AND sequence_name='sequence_name'
</code>```

This will give you 0 (if not exist) or 1 (if exist).

So to solve your problem, you have to execute your query in two shots, one to check if your sequence exist, and the second is to select your sequence, so your code should look like this :

```<code>String sch_name = "sch_test";
String sequence_name = "sequence_name";

//Check if your sequence exist or not
Query q = createNativeQuery("SELECT COUNT(*) FROM
                             information_schema.sequences
                             WHERE sequence_schema='" + sch_name + "'
                             AND sequence_name='" + sequence_name + "'");

int i = (Integer) q.getSingleResult();
int sequence = 0;

//if the sequence exit it will return 1
if(i == 1){
  //increment your sequence and return the result
  q = createNativeQuery("SELECT nextval('" + sequence_name + "')");
  sequence = (Integer) q.getSingleResult();
}else{
   //sequence not exist
}
</code>```

Body:
I want to run a query like this -

"SELECT nextval('sequenceName')"

but before this I want to check that sequenceName exists or not in Hibernate.

Body:
The answer here gives me an idea Check if sequence exists in Postgres (plpgsql),
I don't know if this is a perfect solution or not but you can use :

SELECT COUNT(*)
FROM information_schema.sequences
WHERE sequence_schema='sch_name' AND sequence_name='sequence_name'

This will give you 0 (if not exist) or 1 (if exist).

So to solve your problem, you have to execute your query in two shots, one to check if your sequence exist, and the second is to select your sequence, so your code should look like this :

String sch_name = "sch_test";
String sequence_name = "sequence_name";

//Check if your sequence exist or not
Query q = createNativeQuery("SELECT COUNT(*) FROM
                             information_schema.sequences
                             WHERE sequence_schema='" + sch_name + "'
                             AND sequence_name='" + sequence_name + "'");

int i = (Integer) q.getSingleResult();
int sequence = 0;

//if the sequence exit it will return 1
if(i == 1){
  //increment your sequence and return the result
  q = createNativeQuery("SELECT nextval('" + sequence_name + "')");
  sequence = (Integer) q.getSingleResult();
}else{
   //sequence not exist
}


问:
Pointer does not increment, if incremented in other function
```<code>#include <stdio.h>

increment(char *c)
{
    c++;
    c++;
    printf("works 'n' %c \n", *c);
}

int main()
{

    char *p;
    char mon[10] = "Monday";
    p = mon;
    increment(p);
    printf("expecting 'n' %c \n", *p);

    return 0;
}
</code>```

If character buffer pointer incremented in other function it will not reflect after coming out of the function.

答:
In increment(char *c) you create a new pointer c which is pointing to the same object p does, but they are not the same, they are just pointing to the same thing. If you increment one, the other one stays the same.

If you want to increment the pointer p you need a pointer to this pointer, pass it to your function and change p instead of a local copy.

Body:
#include <stdio.h>

increment(char *c)
{
    c++;
    c++;
    printf("works 'n' %c \n", *c);
}

int main()
{

    char *p;
    char mon[10] = "Monday";
    p = mon;
    increment(p);
    printf("expecting 'n' %c \n", *p);

    return 0;
}

If character buffer pointer incremented in other function it will not reflect after coming out of the function.


问:
How do you compile the Hello World program for Java?
I am at step 6 in the process of installing JDK onto windows using instructions from  this website .

When I attempt to “Set the Current Drive to the drive where you saved your source file Hello.java” by typing “c:”, nothing happens (the instructions indicate that something like C:\xxx> should appear).

I have saved the hello world file in the C: directory as indicated in the previous step (step 5).

I am trying to start learning Java and any help would be appreciated.

答:
You need to enter the following command:

```<code>C:\Users>cd\
</code>```

It will navigate you to the C: drive then apply the command to navigate  to the folder where you saved your source file C:\xxx

```<code>C:\ >cd xxx
</code>```

then you will get..

```<code>C:\xxx>
</code>```

Body:
You need to enter the following command:

C:\Users>cd\

It will navigate you to the C: drive then apply the command to navigate  to the folder where you saved your source file C:\xxx

C:\ >cd xxx

then you will get..

C:\xxx>


问:
Sending build context to Docker daemon (it doesn't stop)
(UBUNTU) I create my dockerfile with touch dockerfile and I do sudo vim dockerfile. the code inside is:

```<code>FROM ubuntu:12.00
CMD echo Hello World!!
</code>```

So I do sudo docker build . . The shell prints me

```<code>Sending build context to Docker daemon TOT kB
</code>```

TOT is the number of GB that the shell download and Now I have 10.40 GB. IS it possible or I wrong something?

答:
mv your Dockerfile to an empty folder, and build it.
When build a docker image, docker will "use" all files in current folder as its "context".
You can also create a .dockerignore file to exclude files or directories like .gitignore.

Body:
(UBUNTU) I create my dockerfile with touch dockerfile and I do sudo vim dockerfile. the code inside is:

FROM ubuntu:12.00
CMD echo Hello World!!

So I do sudo docker build . . The shell prints me

Sending build context to Docker daemon TOT kB

TOT is the number of GB that the shell download and Now I have 10.40 GB. IS it possible or I wrong something?


问:
Is PHP used for quick and easy website where other languages are used in more complex websites?
I just put this question in serverfault.com and I know that this question may be rejected in Stackoverflow.

But I thought programmers know better.

This stat shows that PHP is used by 75.2% of all the websites whose server-side programming language.

http://w3techs.com/technologies/overview/programming_language/all

And this page shows that PHP is the least used server-side language in ranked by usage on top websites

http://w3techs.com/technologies/topsite/programming_language

Q1. Does this mean PHP is used for quick and easy website where other languages are used in more complex websites?

Q2. Why PHP is ranked at the bottom? Or why big company tend to use other language than PHP?

Update: I know that facebook and other biggies uses PHP. But it does not tell why there are more other languages are used in top websites.

答: Not neccessarily there are lots of very complicated websites made with PHP a good example of this is Facebook</p>


问:
how to set add button at right side of after recently added image in android?
I want to add button right side of image( which is recently added image).

I am using below code to add a button on click button images are adding one by one right side of previous image .

But i want to add button should always appear right side of previously added image and click then image should appear in place of button and button should just appear right side of image again and again.

as per below sample image

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Button"
        />

    <neeraj.com.images.PredicateLayout
        android:id="@+id/image_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp">
    </neeraj.com.images.PredicateLayout>

</LinearLayout>

public class MainActivity extends AppCompatActivity {
    PredicateLayout predicate;
    Button button1;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_main);
        //linearLayout1 = (GridLayout) findViewById(R.id.linearLayout1);
        predicate = (PredicateLayout) findViewById(R.id.image_container);
        button1 = (Button) findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageView image = new ImageView(MainActivity.this);
                image.setBackgroundResource(R.mipmap.ic_launcher);
                predicate.addView(image);

            }
        });

    }

}
</code>```

PredicateLayout

```<code>public class PredicateLayout extends ViewGroup {

    private int line_height;

    public PredicateLayout(Context context) {
        super(context);
    }

    public PredicateLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        assert (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED);

        final int width = MeasureSpec.getSize(widthMeasureSpec);

        // The next line is WRONG!!! Doesn't take into account requested MeasureSpec mode!
        int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom();
        final int count = getChildCount();
        int line_height = 0;

        int xpos = getPaddingLeft();
        int ypos = getPaddingTop();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final LayoutParams lp = child.getLayoutParams();
                child.measure(
                        MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
                        MeasureSpec.makeMeasureSpec(height, MeasureSpec.UNSPECIFIED));

                final int childw = child.getMeasuredWidth();
                line_height = Math.max(line_height, child.getMeasuredHeight() + lp.height);

                if (xpos + childw > width) {
                    xpos = getPaddingLeft();
                    ypos += line_height;
                }

                xpos += childw + lp.width + 8;
            }
        }
        this.line_height = line_height;

        if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) {
            height = ypos + line_height;

        } else if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) {
            if (ypos + line_height < height) {
                height = ypos + line_height;
            }
        }
        setMeasuredDimension(width, height + 20);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(2, 2); // default of 1px spacing
    }

    @Override
    protected boolean checkLayoutParams(LayoutParams p) {
        return (p instanceof LayoutParams);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = getChildCount();
        final int width = r - l;
        int xpos = getPaddingLeft();
        int ypos = getPaddingTop();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final int childw = child.getMeasuredWidth();
                final int childh = child.getMeasuredHeight();
                final LayoutParams lp =  child.getLayoutParams();
                if (xpos + childw > width) {
                    xpos = getPaddingLeft();
                    ypos += line_height;
                }
                child.layout(xpos, ypos, xpos + childw, ypos + childh);
                xpos += childw + lp.width + 8;
            }
        }
    }
}
</code>```

答: you can use horizontal  recycler view and imageview and use static arraylist after click image if possition is last add +1 in arralist and notify adapter you will get exactly what u want.</p>

Body:
I want to add button right side of image( which is recently added image).

I am using below code to add a button on click button images are adding one by one right side of previous image .

But i want to add button should always appear right side of previously added image and click then image should appear in place of button and button should just appear right side of image again and again.

as per below sample image

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClick"
        android:text="Button"
        />

    <neeraj.com.images.PredicateLayout
        android:id="@+id/image_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp">
    </neeraj.com.images.PredicateLayout>

</LinearLayout>

public class MainActivity extends AppCompatActivity {
    PredicateLayout predicate;
    Button button1;

    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.activity_main);
        //linearLayout1 = (GridLayout) findViewById(R.id.linearLayout1);
        predicate = (PredicateLayout) findViewById(R.id.image_container);
        button1 = (Button) findViewById(R.id.button1);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ImageView image = new ImageView(MainActivity.this);
                image.setBackgroundResource(R.mipmap.ic_launcher);
                predicate.addView(image);

            }
        });

    }

}

PredicateLayout

public class PredicateLayout extends ViewGroup {

    private int line_height;

    public PredicateLayout(Context context) {
        super(context);
    }

    public PredicateLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        assert (MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.UNSPECIFIED);

        final int width = MeasureSpec.getSize(widthMeasureSpec);

        // The next line is WRONG!!! Doesn't take into account requested MeasureSpec mode!
        int height = MeasureSpec.getSize(heightMeasureSpec) - getPaddingTop() - getPaddingBottom();
        final int count = getChildCount();
        int line_height = 0;

        int xpos = getPaddingLeft();
        int ypos = getPaddingTop();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final LayoutParams lp = child.getLayoutParams();
                child.measure(
                        MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
                        MeasureSpec.makeMeasureSpec(height, MeasureSpec.UNSPECIFIED));

                final int childw = child.getMeasuredWidth();
                line_height = Math.max(line_height, child.getMeasuredHeight() + lp.height);

                if (xpos + childw > width) {
                    xpos = getPaddingLeft();
                    ypos += line_height;
                }

                xpos += childw + lp.width + 8;
            }
        }
        this.line_height = line_height;

        if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.UNSPECIFIED) {
            height = ypos + line_height;

        } else if (MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.AT_MOST) {
            if (ypos + line_height < height) {
                height = ypos + line_height;
            }
        }
        setMeasuredDimension(width, height + 20);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new LayoutParams(2, 2); // default of 1px spacing
    }

    @Override
    protected boolean checkLayoutParams(LayoutParams p) {
        return (p instanceof LayoutParams);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = getChildCount();
        final int width = r - l;
        int xpos = getPaddingLeft();
        int ypos = getPaddingTop();

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                final int childw = child.getMeasuredWidth();
                final int childh = child.getMeasuredHeight();
                final LayoutParams lp =  child.getLayoutParams();
                if (xpos + childw > width) {
                    xpos = getPaddingLeft();
                    ypos += line_height;
                }
                child.layout(xpos, ypos, xpos + childw, ypos + childh);
                xpos += childw + lp.width + 8;
            }
        }
    }
}


问:
How To validate php post variables?
Here I Am going to insert the user details and my insert_search.php contains form fields and insert_dummy.php contains insert code for entering userdetails. My problem is how to validate php post variables and where i need to insert validate code eigther insert_search.php or insert_dummy.php?
As i am new to php.Thank you in Advance.
insert_search.php

```<code><?php
include('header/page_header.php');
$user="root";
$server="localhost";
$password="";
$db="coedsproddb1";
$dbconn= mysql_connect($server,$user,$password);
mysql_select_db($db,$dbconn);

?>
<html>
<head><title>Insert</title>
<link rel="stylesheet" href="css/bookstyles.css">
<link rel="stylesheet" href="css/jquery-ui.css">
<script src="js/jquery-1.12.4.js"></script>
  <script src="js/jquery-ui.js"></script>
</head>
<body>
<div class="container">

<style>
#display {
color:red;
font-size:12px;
text-align:center;
}
.logo {
padding:5px;
float:right;
}
header {
background-color:#074e7c;
height:60px;
width:100%;
text-align:center;
color:white;
font-size:40px;

}
#wrap {
text-align:center;
}
table ,tr,td {
border-collapse:collapse;
}
</style>
<?php
$end_date1 = date('Y-m-d', strtotime("+3 months"));
 $end_date2 = date('Y-m-d', strtotime("+6 months"));
 $end_date3 = date('Y-m-d', strtotime("+9 months"));
 if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["userName"])) {
        $userNameErr = "Missing";
    }
    else {
        $userName = $_POST["userName"];
    }

    if (empty($_POST["userEmail"])) {
        $userEmailErr = "Missing";
    }
    else {
        $userEmail = $_POST["userEmail"];
    }

    if (empty($_POST["userPassword"]))  {
        $userPasswordErr = "Missing";
    }
    else {
        $userPassword = $_POST["userPassword"];
    }

}
 ?>
<form name="useradd" id="useradd" action="insert_dummy.php" method="post">
<input type="hidden" name="end_date" >
<input type="hidden" name="userId" id="userId" value="<?php $userid;?>" >
<table align='center' border='1'>

    <tr>

           <td> <label for="userName">UserName</label></td>
            <td ><input id="userName" name="userName"  type="text" /></td>

        </tr>
        <tr>
        <td> <label for="userEmail">Email</label></td>
        <td ><input id="userEmail" name="userEmail" type="text"/></td>
        </tr>
        <tr>
        <td>
            <label for="userPassword">password</label></td>
            <td ><input id="userPassword" name="userPassword" type="password" /></td>

        </tr>
        <tr>
        <td>
            <label for="expiry_date">Application_expiry_date</label></td>
            <td ><input id="expiry_date" name="expiry_date" type="text" /></td>

        </tr>
        <br/>
        <br/>

    <td> <label for="end_date">EndDate</label></td>
        <td >  <select name="end_date" id="end_date">
             <option value=<?php echo $end_date1; ?>><?php echo $end_date1; ?></option>
             <option value=<?php echo $end_date2; ?>><?php echo $end_date2; ?> </option>
             <option value=<?php echo $end_date3;?>><?php echo $end_date3;?> </option>

        </select>
</td>
</tr>

        </table>

<br>

<div id="wrap">
<input type="submit" name="add" value="add" id="add">

</form>
<div id="display">
</div>

</div>

                <script type="text/javascript">
$('document').ready(function() {

    $(".tooltip").click(function(e) {
     $('[data-toggle="tooltip"]').tooltip();
     e.preventDefault();
     });
     });
     </script>-->
     <script type="text/javascript" >
    $(document).ready(function() {
    $( "#expiry_date" ).datepicker();
    $("#menuwrapper").hide();
    $("#unicode").click(function() {
        $("#menuwrapper").slideToggle(500);
    });
    });
</script>

</body>
</html>
</code>```

insert_dummy.php

```<code><html>
<head><title>Insertion</title>

</head>
<body>
<style>

#colour {
text-decoration:none;
}
</style>
<div id="display">
<?php
include('header/page_header.php');
include('db.php');

$userName=mysql_real_escape_string($_POST['userName']);
$userEmail=mysql_real_escape_string($_POST['userEmail']);
$userPassword=mysql_real_escape_string($_POST['userPassword']);
$expiry_date1=mysql_real_escape_string($_POST['expiry_date']);
$expiry_date=date("Y-m-d" ,strtotime($expiry_date1));
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));

 $regDate = date("Y-m-d");

function generateCode($characters)
{
    $possible = '23456789abcdefghjkmnpqrstuvwxyz!@#$%^&*';
    $code = '';
    $i = 0;
    while ($i < $characters) {
        $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
        $i++;
    }
    return $code;
}

$registration_key=generateCode(10);

$str="insert into coeds_user(userName,userEmail,userPassword,regDate,expiry_date,registration_key) values('$userName','$userEmail','$userPassword','$regDate','$expiry_date','$registration_key')";

$query=mysql_query($str);
$userid=mysql_insert_id();
if($query)
{
$display="Success";
}
/*$string="select chapter_no from chapter_details ";
echo $string;
$query7=mysql_query($string);

$count=mysql_num_rows($query7);
for($i=0;$i<$count;$i++)
{
$chap_lic=generateCode(50);
$chapter_no=mysql_result($query7,$i,'chapter_no');
$start_date=date('Y-m-d');
$expiry_date=mysql_real_escape_string($_POST['end_date']);
$end_date=mysql_real_escape_string($_POST['end_date']);

$s="insert into chapter_subscriptions (userId,chapter_no,start_date,end_date) values($userid,$chapter_no,'$start_date','$end_date')";

$query8=mysql_query($s);
}
}*/
else
{
$display= "Failed";
}
/*$str="select * from chapter_subscriptions where userId=$userid";
$query7=mysql_query($str);
$display.="<table border='1' align='center'>";
$display.="<tr><th>ChapterNumber</th><th>StartDate</th><th>EndDate</th><th>ChapterLicense</th><th colspan='2'>Action</th></tr>";
while($result=mysql_fetch_array($query7))
{
$display.="<tr>";
$display.="<td>".$result['chapter_no']."</td>";
$display.="<td>".$result['start_date']."</td>";

$display.="<td>".$result['end_date']."</td>";
$display.="<td>".$result['chap_lic']."</td>";

$display.="<td><a id='colour' class='tooltip' title='Edit' href='chapter_subscription_update.php?user_Id=".$result['userId']."'><img id='image' src='./images/small.gif'/></a></td>";
$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='Delete' href='chapter_subscription_delete.php?user_Id=".$result['userId']." '><img id='image' src='./images/trash.png'/></a></td>";

$display.="</tr>";
}
$display.="</table>";*/

$string="select * from coeds_user where userId=$userid";
$query2=mysql_query($string);
$display.="<table border='1' align='center'>";
$display.="<tr><th>UserName</th><th>UserEmail</th><th>UserPassword</th><th>RegDate</th><th>ExpiryDate</th><th>RegistrationKey</th><th colspan='3'>Action</th></tr>";
while($result=mysql_fetch_array($query2))
{
$display.="<tr>";

$display.="<td>".$result['userName']."</td>";
$display.="<td>".$result['userEmail']."</td>";
$display.="<td>".$result['userPassword']."</td>";
$display.="<td>".$result['regDate']."</td>";
$display.="<td>".$result['expiry_date']."</td>";
$display.="<td>".$result['registration_key']."</td>";
$display.="<td><a id='colour' class='tooltip' title='Edit' href='user_update.php?user_Id=".$result['userId']."'><img id='image' src='./images/small.gif'/></a></td>";
$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='Delete' href='user_delete.php?user_Id=".$result['userId']." '><img id='image' src='./images/trash.png'/></a></td>";

$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='insert' href='chapter_subscription_search.php?user_Id=".$result['userId']." '>i</a></td>";
$display.="</tr>";

$display.="</table>";

 $end_date1 = date('Y-m-d', strtotime("+3 months"));
 $end_date2 = date('Y-m-d', strtotime("+6 months"));
 $end_date3 = date('Y-m-d', strtotime("+9 months"));
 $page="";

 ?>

<table align='center' border='1'>

    <tr>

           <td> <label for="userId">UserId</label></td>
            <td ><input id="userId" name="userId"  type="text" value="<?php echo $userid;?>"/></td>

        </tr>
        <tr>
        <td> <label for="userName">UserName</label></td>
        <td ><input id="userName" name="userName" type="text" value="<?php echo $result['userName'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="userEmail">UserEmail</label></td>
        <td ><input id="userEmail" name="userEmail" type="text" value="<?php echo $result['userEmail'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="userPassword">UserPassword</label></td>
        <td ><input id="userPassword" name="userPassword" type="password" value="<?php echo $result['userPassword'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="expiry_date">ExpiryDate</label></td>
        <td ><input id="expiry_date" name="expiry_date" type="text" value="<?php echo $result['expiry_date'];?>"/></td>
        </tr>
        <tr>
        <td> <label for="end_date">EndDate</label></td>
        <td >  <select name="end_date" id="end_date">
             <option value=<?php echo $end_date1; ?>><?php echo $end_date1; ?></option>
             <option value=<?php echo $end_date2; ?>><?php echo $end_date2; ?> </option>
             <option value=<?php echo $end_date3;?>><?php echo $end_date3;?> </option>

        </select>
</td>
        </tr>

        </table>

<?php
}
$str="select chapter_no from chapter_details ";

$query7=mysql_query($str);

$count=mysql_num_rows($query7);
for($i=0;$i<$count;$i++)
{
$chap_lic=generateCode(50);
$chapter_no=mysql_result($query7,$i,'chapter_no');
$start_date=date('Y-m-d');
$expiry_date=mysql_real_escape_string($_POST['end_date']);
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));
$s="insert into chapter_subscriptions (userId,chapter_no,start_date,end_date) values($userid,$chapter_no,'$start_date','$end_date')";

$query8=mysql_query($s);
}
$strings="select * from chapter_subscriptions where userId=$userid";
$query9=mysql_query($strings);
$display.="<table border='1' align='center'>";
$display.="<tr><th>ChapterNumber</th><th>StartDate</th><th>EndDate</th><th colspan='2'>Action</th></tr>";
while($result=mysql_fetch_array($query9))
{
$display.="<tr>";
$display.="<td>".$result['chapter_no']."</td>";
$display.="<td>".$result['start_date']."</td>";

$display.="<td>".$result['end_date']."</td>";

$display.="<td><a id='colour' class='tooltip' title='Edit' href='chapter_subscription_update.php?user_Id=".$result['userId']."'><img id='image' src='./images/small.gif'/></a></td>";
$display.="<td><a id='colour' class='tooltip' data-toggle='tooltip' title='Delete' href='chapter_subscription_delete.php?user_Id=".$result['userId']." '><img id='image' src='./images/trash.png'/></a></td>";

$display.="</tr>";
}
$display.="</table>";

echo $display;

?>
</div>
 <script type="text/javascript">
    $(document).ready(function() {
    $( "#expiry_date" ).datepicker();
    $("#menuwrapper").hide();
    $("#unicode").click(function() {
        $("#menuwrapper").slideToggle(500);
    });
    });

</script>

</body>
</html>
</code>```

答:
You always validate in the PHP-file that accepts user input (GET, POST or whatever you use), ie. in insert_dummy.php.

Anything before that can be circumvented most of the time by passing parameters in URL or programmatically generating the form data.

Form validation in the actual form is for user convenience only so they don't have to send the form and get a "error, bad form fields" error from the PHP file that does the actual information saving (unless you implement something needlessly complicated like hashing the form data, but then you'd need to validate that and you'd have the hashing code exposed as Javascript anyway).

As for how - only you know what kind of data you accept (username / password length, complexity, etc), so you will have to write a custom function to do it and run it before passing anything to the database part.

Title: How To validate php post variables?

Body:
Here I Am going to insert the user details and my insert_search.php contains form fields and insert_dummy.php contains insert code for entering userdetails. My problem is how to validate php post variables and where i need to insert validate code eigther insert_search.php or insert_dummy.php?
As i am new to php.Thank you in Advance.
insert_search.php

<?php
include('header/page_header.php');
$user="root";
$server="localhost";
$password="";
$db="coedsproddb1";
$dbconn= mysql_connect($server,$user,$password);
mysql_select_db($db,$dbconn);

?>

<title>Insert</title>
<link rel="stylesheet" href="css/bookstyles.css">
<link rel="stylesheet" href="css/jquery-ui.css">

<?php
$end_date1 = date('Y-m-d', strtotime("+3 months"));
 $end_date2 = date('Y-m-d', strtotime("+6 months"));
 $end_date3 = date('Y-m-d', strtotime("+9 months"));
 if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["userName"])) {
        $userNameErr = "Missing";
    }
    else {
        $userName = $_POST["userName"];
    }

    if (empty($_POST["userEmail"])) {
        $userEmailErr = "Missing";
    }
    else {
        $userEmail = $_POST["userEmail"];
    }

    if (empty($_POST["userPassword"]))  {
        $userPasswordErr = "Missing";
    }
    else {
        $userPassword = $_POST["userPassword"];
    }

}
 ?>
<form name="useradd" id="useradd" action="insert_dummy.php" method="post">
<input type="hidden" name="end_date" >
<input type="hidden" name="userId" id="userId" value="<?php $userid;?>" >

            UserName
            <input id="userName" name="userName"  type="text" />

         Email
        <input id="userEmail" name="userEmail" type="text"/>

            password
            <input id="userPassword" name="userPassword" type="password" />

            Application_expiry_date
            <input id="expiry_date" name="expiry_date" type="text" />

     EndDate
          <select name="end_date" id="end_date">
             <option value=<?php echo $end_date1; ?>><?php echo $end_date1; ?></option>
             <option value=<?php echo $end_date2; ?>><?php echo $end_date2; ?> </option>
             <option value=<?php echo $end_date3;?>><?php echo $end_date3;?> </option>

        </select>

<input type="submit" name="add" value="add" id="add">

</form>

                -->

insert_dummy.php

<title>Insertion</title>

<?php
include('header/page_header.php');
include('db.php');

$userName=mysql_real_escape_string($_POST['userName']);
$userEmail=mysql_real_escape_string($_POST['userEmail']);
$userPassword=mysql_real_escape_string($_POST['userPassword']);
$expiry_date1=mysql_real_escape_string($_POST['expiry_date']);
$expiry_date=date("Y-m-d" ,strtotime($expiry_date1));
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));

 $regDate = date("Y-m-d");

function generateCode($characters)
{
    $possible = '23456789abcdefghjkmnpqrstuvwxyz!@#$%^&*';
    $code = '';
    $i = 0;
    while ($i < $characters) {
        $code .= substr($possible, mt_rand(0, strlen($possible)-1), 1);
        $i++;
    }
    return $code;
}

$registration_key=generateCode(10);

$str="insert into coeds_user(userName,userEmail,userPassword,regDate,expiry_date,registration_key) values('$userName','$userEmail','$userPassword','$regDate','$expiry_date','$registration_key')";

$query=mysql_query($str);
$userid=mysql_insert_id();
if($query)
{
$display="Success";
}
/*$string="select chapter_no from chapter_details ";
echo $string;
$query7=mysql_query($string);

$count=mysql_num_rows($query7);
for($i=0;$i<$count;$i++)
{
$chap_lic=generateCode(50);
$chapter_no=mysql_result($query7,$i,'chapter_no');
$start_date=date('Y-m-d');
$expiry_date=mysql_real_escape_string($_POST['end_date']);
$end_date=mysql_real_escape_string($_POST['end_date']);

$s="insert into chapter_subscriptions (userId,chapter_no,start_date,end_date) values($userid,$chapter_no,'$start_date','$end_date')";

$query8=mysql_query($s);
}
}*/
else
{
$display= "Failed";
}
/*$str="select * from chapter_subscriptions where userId=$userid";
$query7=mysql_query($str);
$display.="
";
$display.="
ChapterNumber	StartDate	EndDate	ChapterLicense	Action
";
while($result=mysql_fetch_array($query7))
{
$display.="
";
$display.="".$result['chapter_no']."	";
$display.="".$result['start_date']."	";

$display.="".$result['end_date']."	";
$display.="".$result['chap_lic']."	";

$display.="	";
$display.="	";

$display.="
";
}
$display.="
";*/

$string="select * from coeds_user where userId=$userid";
$query2=mysql_query($string);
$display.="
";
$display.="
UserName	UserEmail	UserPassword	RegDate	ExpiryDate	RegistrationKey	Action
";
while($result=mysql_fetch_array($query2))
{
$display.="
";

$display.="".$result['userName']."	";
$display.="".$result['userEmail']."	";
$display.="".$result['userPassword']."	";
$display.="".$result['regDate']."	";
$display.="".$result['expiry_date']."	";
$display.="".$result['registration_key']."	";
$display.="	";
$display.="	";

$display.="i	";
$display.="
";

$display.="
";

 $end_date1 = date('Y-m-d', strtotime("+3 months"));
 $end_date2 = date('Y-m-d', strtotime("+6 months"));
 $end_date3 = date('Y-m-d', strtotime("+9 months"));
 $page="";

 ?>

            UserId
            <input id="userId" name="userId"  type="text" value="<?php echo $userid;?>"/>

         UserName
        <input id="userName" name="userName" type="text" value="<?php echo $result['userName'];?>"/>

         UserEmail
        <input id="userEmail" name="userEmail" type="text" value="<?php echo $result['userEmail'];?>"/>

         UserPassword
        <input id="userPassword" name="userPassword" type="password" value="<?php echo $result['userPassword'];?>"/>

         ExpiryDate
        <input id="expiry_date" name="expiry_date" type="text" value="<?php echo $result['expiry_date'];?>"/>

         EndDate
          <select name="end_date" id="end_date">
             <option value=<?php echo $end_date1; ?>><?php echo $end_date1; ?></option>
             <option value=<?php echo $end_date2; ?>><?php echo $end_date2; ?> </option>
             <option value=<?php echo $end_date3;?>><?php echo $end_date3;?> </option>

        </select>

<?php
}
$str="select chapter_no from chapter_details ";

$query7=mysql_query($str);

$count=mysql_num_rows($query7);
for($i=0;$i<$count;$i++)
{
$chap_lic=generateCode(50);
$chapter_no=mysql_result($query7,$i,'chapter_no');
$start_date=date('Y-m-d');
$expiry_date=mysql_real_escape_string($_POST['end_date']);
$end_date1=mysql_real_escape_string($_POST['end_date']);
$end_date=date("Y-m-d",strtotime($end_date1));
$s="insert into chapter_subscriptions (userId,chapter_no,start_date,end_date) values($userid,$chapter_no,'$start_date','$end_date')";

$query8=mysql_query($s);
}
$strings="select * from chapter_subscriptions where userId=$userid";
$query9=mysql_query($strings);
$display.="
";
$display.="
ChapterNumber	StartDate	EndDate	Action
";
while($result=mysql_fetch_array($query9))
{
$display.="
";
$display.="".$result['chapter_no']."	";
$display.="".$result['start_date']."	";

$display.="".$result['end_date']."	";

$display.="	";
$display.="	";

$display.="
";
}
$display.="
";

echo $display;

?>


问:
Yii Framework 2.0 -findModel returns an empty object
I am trying to show the form values which I have stored in the database.But it's not happening and also returning the empty values.I have added whatever I did.

Controller

```<code>protected function findModel($id)
    {
        if (($model = UserRegistration::find($id)->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
</code>```

Model

this is my model.I have declared all variables as public.Is that a problem? If I remove im getting error also.

```<code>class UserRegistration extends ActiveRecord
{
    public $username;
    public $firstname;
    public $lastname;
    public $email;
    public $Country;
    public $State;
    public $City;
    public $phone_number;
    public $about_me;
    public $password;
    public $verify_password;
    public $photo;

    public static function tableName()
    {
        return 'user';
    }

    public function rules()
    {
        return [
            [['username','password', 'email'], 'required'],
            [['status', 'created_at', 'updated_at', 'teespring_id'], 'integer'],
            [['username','lastname','firstname', 'password_hash', 'password_reset_token', 'email','about_me'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['role'], 'string', 'max' => 10],
            [['email','username'],'email'],
            [['email','username','password_reset_token'], 'unique'],
            ['phone_number','string','length'=>10],
            [['Country','State','City'],'string'],
            ['verify_password','compare','compareAttribute'=>'password'],
            [['photo'],'file', 'extensions' => 'png, jpg']
        ];
    }
}
</code>```

Update: I have tried $model = UserRegistration::findOne($id) also.no luck
Please help me.

答:
This is wrong.

```<code>$model = UserRegistration::find($id)->one()
</code>```

It should be:

```<code>$model = UserRegistration::findOne($id);
</code>```

or

```<code>$model = UserRegistration::find()->where(['id' => $id])->one();
</code>```

if $id is referred to 'id' field

Body:
I am trying to show the form values which I have stored in the database.But it's not happening and also returning the empty values.I have added whatever I did.

Controller

protected function findModel($id)
    {
        if (($model = UserRegistration::find($id)->one()) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

Model

this is my model.I have declared all variables as public.Is that a problem? If I remove im getting error also.

class UserRegistration extends ActiveRecord
{
    public $username;
    public $firstname;
    public $lastname;
    public $email;
    public $Country;
    public $State;
    public $City;
    public $phone_number;
    public $about_me;
    public $password;
    public $verify_password;
    public $photo;

    public static function tableName()
    {
        return 'user';
    }

    public function rules()
    {
        return [
            [['username','password', 'email'], 'required'],
            [['status', 'created_at', 'updated_at', 'teespring_id'], 'integer'],
            [['username','lastname','firstname', 'password_hash', 'password_reset_token', 'email','about_me'], 'string', 'max' => 255],
            [['auth_key'], 'string', 'max' => 32],
            [['role'], 'string', 'max' => 10],
            [['email','username'],'email'],
            [['email','username','password_reset_token'], 'unique'],
            ['phone_number','string','length'=>10],
            [['Country','State','City'],'string'],
            ['verify_password','compare','compareAttribute'=>'password'],
            [['photo'],'file', 'extensions' => 'png, jpg']
        ];
    }
}

Update: I have tried $model = UserRegistration::findOne($id) also.no luck
Please help me.

Body:
This is wrong.

$model = UserRegistration::find($id)->one()

It should be:

$model = UserRegistration::findOne($id);

or

$model = UserRegistration::find()->where(['id' => $id])->one();

if $id is referred to 'id' field