问:
Pass Complex Model in Post Method of Asp.net MVC
In my Razor View, I have candidate details along with other Degrees etc. I have to append row of Candidate's degree. I have taken Degree View as a partial view. Which will be added by candidate according to the number of degree he has. I need to pass detail of degree along with other details of Candidate to controller. I have attached my UI and details here:-

Here is my Model

```<code> public class Candidate:BaseEntity
{
    public Candidate()
    {

        CandidateDegreeMap = new HashSet<CandidateDegreeMap>();
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNo { get; set; }
    public string Email { get; set; }
    public string Status { get; set; }
    public string Gender { get; set; }
    public DateTime Dob { get; set; }
    public DateTime DateCreated { get; set; }
    public int CreatedBy { get; set; }
    public DateTime? DateModified { get; set; }
    public int? ModifiedBy { get; set; }
    public bool IsDeleted { get; set; }

    public ICollection<CandidateDegreeMap> CandidateDegreeMap { get; set; }

}
</code>```

I need to pass candidate details with their multiple Education.
Here I am Adding my controller

```<code>[HttpPost]
    public async Task<IActionResult> AddEdit([FromBody]CandidateModel model,
string returnUrl = null)
    {
        return await Task.Run(()=>View("AddCandidate",model));
    }
</code>```

My View is below

```<code>/*Dashboard Page Ends*/
</code>```

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AddCandidate - CVManagement</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href=/css/select2.min.css />
    <link rel="stylesheet" href=/css/style.css />
    <link rel="stylesheet" href=/css/responsive.css />

                         <mp>John Doe</mp> arrow_drop_down

                     Dashboard

                     Candidates

    Dashboard
    Openings
    Add Candidate

Candidate Details

<form method="post" class="col s12 m12 l12 xl12" action="/Candidate/AddEdit">

Personal

                <input id="first_name" type="text" name="FirstName" value="">
                First Name

                <input id="last_name" type="text" name="LastName" value="">
                Last Name

                <input id="Dob" class="cv-date-picker" type="text" data-val="true" data-val-required="The Dob field is required." name="Dob" value="">
                Date of Birth

                <input id="Gender" type="text" disabled="disabled" name="Gender" value="">
                Gender

                <input id="phone_number" type="text" name="PhoneNo" value="">
                Phone Number

                <input id="email" type="email" name="Email" value="">
                Email

Education

        <input type="text" id="DegreeName" name="DegreeName" value="">
        Degree

        <input type="text" id="InstituteName" name="InstituteName" value="">
        Institute

        <input class="cv-date-picker" type="text" id="YearOfPassing" name="YearOfPassing" value="">
        Year Of Passing

            + Add more

Proffessional

                <input id="tot_exp" type="text">
                Total Experience

                <input id="rel_exp" type="text">
                Relevant Experience

             Add Wrok Experience

                    <input type="checkbox" class="filled-in" id="currentJob_1" />
                    Current Job

                    <input id="employer_1" type="text">
                    Employer

                    <input id="job_role_1" type="text">
                    Job Role

                    <select id="it_skills_1" class="material-select">
                        <option value="1">Option 1</option>
                        <option value="2">Option 2</option>
                        <option value="3">Option 3</option>
                    </select>
                    IT Skills

                        <input type="text" placeholder="Start" class="cv-date-picker">

                        <input type="text" placeholder="End" class="cv-date-picker">

                    Date Range

                    <input id="current_ctc_1" type="text">
                    Current CTC

                    <input id="expected_ctc_1" type="text">
                    Expected CTC

            clear

                    <input type="checkbox" class="filled-in" id="currentJob_2" />
                    Current Job

                    <input id="employer_2" type="text">
                    Employer

                    <input id="job_role_2" type="text">
                    Job Role

                    <select id="it_skills_2" class="material-select">
                        <option value="1">Option 1</option>
                        <option value="2">Option 2</option>
                        <option value="3">Option 3</option>
                    </select>
                    IT Skills

                        <input type="text" placeholder="Start" class="cv-date-picker">

                        <input type="text" placeholder="End" class="cv-date-picker">

                    Date Range

                    <input id="current_ctc_2" type="text">
                    Current CTC

                    <input id="expected_ctc_2" type="text">
                    Expected CTC

            clear

                <select id="capability" class="material-select">
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                </select>
                Capability

Recruiter Comment

                Good
                Bad Communication

                <textarea id="textarea1" class="materialize-textarea"></textarea>
                Comment

Hiring Manager Comment

                Good
                Bad Communication

                <textarea id="textarea1" class="materialize-textarea"></textarea>
                Comment

                <select class="material-select">
                    <option value="" disabled selected>Choose your option</option>
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                </select>
                Capability

                <select class="material-select">
                    <option value="" disabled selected>Choose your option</option>
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                </select>
                Opening

                <button class="btn btn-cre-opn waves-effect active">Save</button>
                <button class="btn btn-cre-opn waves-effect">Cancel</button>

<input name="__RequestVerificationToken" type="hidden" value="CfDJ8K7NtNmNf5lJsh806e0aRPmUONXIh2RLjJ1oH6KtOEdcIrE95C_Obn7dzp3LNYv2Eof0VGrWukRpqxXnYDAJGverd0YJjhOSXeUEJZFmHpAnjwlJMAoTnrYn2ILawiFAHDDU6_ujcJ-blB1IsoYXRzk" /></form>

© 2017 - Azilen Technology Pvt. Ltd

```

Moreover Please find Image also

答:
According to your initial question before edits , this basic setup should work:

Model:

Use List instead of Collection in your Model because Collections cannot be Indexed check this.

```<code>public class Canditate
{

    public Canditate()
    {

        CandidateCompanyMap = new List<CandidateCompanyMap>();
        CandidateDegreeMap = new List<CandidateDegreeMap>();
        CandidateDocumentMap = new List<CandidateDocumentMap>();
        CandidateTagsMap = new List<CandidateTagsMap>();
        EducationDetails = new List<EducationDetails>();

    }

    public string FirstName { get; set; }
    public string Email { get; set; }

    public List<CandidateCompanyMap> CandidateCompanyMap { get; set; }
    public List<CandidateDegreeMap> CandidateDegreeMap { get; set; }
    public List<CandidateDocumentMap> CandidateDocumentMap { get; set; }
    public List<CandidateTagsMap> CandidateTagsMap { get; set; }
    public List<EducationDetails> EducationDetails { get; set; }
}
</code>```

Candidate Get Action Method:

```<code>public ActionResult Index()
{
  // Populating some dummy data

  //TODO populate canditate list from your data repository
  Canditate canditate = new Canditate();
  canditate.FirstName = "Example Name";
  canditate.Email = "example@example.org";

  List<CandidateCompanyMap> candidateCompanyList = new List<CandidateCompanyMap>();
  List<CandidateDegreeMap> candidateeDegreeList = new List<CandidateDegreeMap>();
  List<CandidateDocumentMap> candidateDocumentList = new List<CandidateDocumentMap>();
  List<CandidateTagsMap> candidateTagsList = new List<CandidateTagsMap>();

  CandidateCompanyMap candidateCompany = new CandidateCompanyMap();
  candidateCompany.CompanyName = "Example Company";
  candidateCompanyList.Add(candidateCompany);

  CandidateDegreeMap candidateDegree = new CandidateDegreeMap();
  candidateDegree.DegreeName = "Example Degree";
  candidateeDegreeList.Add(candidateDegree);

  CandidateDocumentMap candidateDocument = new CandidateDocumentMap();
  candidateDocument.DocumentName = "Example Document";
  candidateDocumentList.Add(candidateDocument);

  CandidateTagsMap candidateTags = new CandidateTagsMap();
  candidateTags.TagsName = "Example Tags";
  candidateTagsList.Add(candidateTags);

  CandidateTagsMap candidateTags2 = new CandidateTagsMap();
  candidateTags2.TagsName = "Example Tags 2";
  candidateTagsList.Add(candidateTags2);

  canditate.CandidateCompanyMap = candidateCompanyList;
  canditate.CandidateDegreeMap = candidateeDegreeList;
  canditate.CandidateDocumentMap = candidateDocumentList;
  canditate.CandidateTagsMap = candidateTagsList;

  return View(canditate);
  }
</code>```

Index View:

```<code>@model Demo.Models.Canditate

@using (Html.BeginForm("Candidate", "Home", FormMethod.Post))
{

<label>Candidate First Name</label>
@Html.TextBoxFor(m => m.FirstName);

<br />

<label>Candidate Email</label>
@Html.TextBoxFor(m => m.Email);

<br />

<label>Education Details</label>

<div id="educationDetails">

    @foreach (var education in Model.EducationDetails)
    {
        @Html.Partial("_EducationalDetailsPartials", education)
    }

    <button type="button" id="addEducation">Add</button>
</div>

<label>Candidate Company</label>

for (int i = 0; i < Model.CandidateCompanyMap.Count; i++)
{

    @Html.TextBoxFor(m => m.CandidateCompanyMap[i].CompanyName);
}

<br />

<label>Candidate Degree</label>

for (int i = 0; i < Model.CandidateDegreeMap.Count; i++)
{

    @Html.TextBoxFor(m => m.CandidateDegreeMap[i].DegreeName);
}

<br />

<label>Candidate Document</label>

for (int i = 0; i < Model.CandidateDocumentMap.Count; i++)
{

    @Html.TextBoxFor(m => m.CandidateDocumentMap[i].DocumentName);
}

<br />

<label>Candidate Tags</label>

for (int i = 0; i < Model.CandidateTagsMap.Count; i++)
{

    @Html.TextBoxFor(m => m.CandidateTagsMap[i].TagsName);

    <br />
}

<input type="submit" value="Submit" />
</code>```

}

Candidate Post Action Method:

```<code>    [HttpPost]
    public ActionResult Candidate(Canditate data)
    {
       // TODO Save data

        return View(data);
    }
</code>```

Add Eduction GET Action Method:

```<code>    public PartialViewResult AddEduction(Canditate data)
    {

        return PartialView("_EducationalDetailsPartials", new EducationDetails());
    }
</code>```

Add Eduction Partial View:

Note: Install BeginCollectionItem HtmlHelper from here to have unique name attributes in form to bind to your model properties.

```<code> @model Demo.Models.EducationDetails
 @using HtmlHelpers.BeginCollectionItem

 @using (Html.BeginCollectionItem("educationDetails"))
 {

 @Html.LabelFor(model => model.Degree)

 @Html.EditorFor(model => model.Degree)
 @Html.ValidationMessageFor(model => model.Degree)

 @Html.LabelFor(model => model.Institute)

 @Html.EditorFor(model => model.Institute)
 @Html.ValidationMessageFor(model => model.Institute)

 <button type="button" value="Delete" class="btn btn-default">Delete</button>

<br />

}
</code>```

Script to Add New Education:

```<code><script>

$(document).ready(function () {

var url = '@Url.Action("AddEduction","Home")';

var educationDetails = $('#educationDetails');
$('#addEducation').click(function () {
   $.get(url, function (response) {
      educationDetails.append(response);

    });
  });
</code>```

})

```<code></script>
</code>```

Body:
In my Razor View, I have candidate details along with other Degrees etc. I have to append row of Candidate's degree. I have taken Degree View as a partial view. Which will be added by candidate according to the number of degree he has. I need to pass detail of degree along with other details of Candidate to controller. I have attached my UI and details here:-

Here is my Model

 public class Candidate:BaseEntity
{
    public Candidate()
    {

        CandidateDegreeMap = new HashSet<CandidateDegreeMap>();
    }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNo { get; set; }
    public string Email { get; set; }
    public string Status { get; set; }
    public string Gender { get; set; }
    public DateTime Dob { get; set; }
    public DateTime DateCreated { get; set; }
    public int CreatedBy { get; set; }
    public DateTime? DateModified { get; set; }
    public int? ModifiedBy { get; set; }
    public bool IsDeleted { get; set; }

    public ICollection<CandidateDegreeMap> CandidateDegreeMap { get; set; }

}

I need to pass candidate details with their multiple Education.
Here I am Adding my controller

[HttpPost]
    public async Task<IActionResult> AddEdit([FromBody]CandidateModel model,
string returnUrl = null)
    {
        return await Task.Run(()=>View("AddCandidate",model));
    }

My View is below

/*Dashboard Page Ends*/

<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>AddCandidate - CVManagement</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" />
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Nunito">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href=/css/select2.min.css />
    <link rel="stylesheet" href=/css/style.css />
    <link rel="stylesheet" href=/css/responsive.css />

                         <mp>John Doe</mp> arrow_drop_down

                     Dashboard

                     Candidates

    Dashboard
    Openings
    Add Candidate

Candidate Details

<form method="post" class="col s12 m12 l12 xl12" action="/Candidate/AddEdit">

Personal

                <input id="first_name" type="text" name="FirstName" value="">
                First Name

                <input id="last_name" type="text" name="LastName" value="">
                Last Name

                <input id="Dob" class="cv-date-picker" type="text" data-val="true" data-val-required="The Dob field is required." name="Dob" value="">
                Date of Birth

                <input id="Gender" type="text" disabled="disabled" name="Gender" value="">
                Gender

                <input id="phone_number" type="text" name="PhoneNo" value="">
                Phone Number

                <input id="email" type="email" name="Email" value="">
                Email

Education

        <input type="text" id="DegreeName" name="DegreeName" value="">
        Degree

        <input type="text" id="InstituteName" name="InstituteName" value="">
        Institute

        <input class="cv-date-picker" type="text" id="YearOfPassing" name="YearOfPassing" value="">
        Year Of Passing

            + Add more

Proffessional

                <input id="tot_exp" type="text">
                Total Experience

                <input id="rel_exp" type="text">
                Relevant Experience

             Add Wrok Experience

                    <input type="checkbox" class="filled-in" id="currentJob_1" />
                    Current Job

                    <input id="employer_1" type="text">
                    Employer

                    <input id="job_role_1" type="text">
                    Job Role

                    <select id="it_skills_1" class="material-select">
                        <option value="1">Option 1</option>
                        <option value="2">Option 2</option>
                        <option value="3">Option 3</option>
                    </select>
                    IT Skills

                        <input type="text" placeholder="Start" class="cv-date-picker">

                        <input type="text" placeholder="End" class="cv-date-picker">

                    Date Range

                    <input id="current_ctc_1" type="text">
                    Current CTC

                    <input id="expected_ctc_1" type="text">
                    Expected CTC

            clear

                    <input type="checkbox" class="filled-in" id="currentJob_2" />
                    Current Job

                    <input id="employer_2" type="text">
                    Employer

                    <input id="job_role_2" type="text">
                    Job Role

                    <select id="it_skills_2" class="material-select">
                        <option value="1">Option 1</option>
                        <option value="2">Option 2</option>
                        <option value="3">Option 3</option>
                    </select>
                    IT Skills

                        <input type="text" placeholder="Start" class="cv-date-picker">

                        <input type="text" placeholder="End" class="cv-date-picker">

                    Date Range

                    <input id="current_ctc_2" type="text">
                    Current CTC

                    <input id="expected_ctc_2" type="text">
                    Expected CTC

            clear

                <select id="capability" class="material-select">
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                </select>
                Capability

Recruiter Comment

                Good
                Bad Communication

                <textarea id="textarea1" class="materialize-textarea"></textarea>
                Comment

Hiring Manager Comment

                Good
                Bad Communication

                <textarea id="textarea1" class="materialize-textarea"></textarea>
                Comment

                <select class="material-select">
                    <option value="" disabled selected>Choose your option</option>
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                </select>
                Capability

                <select class="material-select">
                    <option value="" disabled selected>Choose your option</option>
                    <option value="1">Option 1</option>
                    <option value="2">Option 2</option>
                    <option value="3">Option 3</option>
                </select>
                Opening

                <button class="btn btn-cre-opn waves-effect active">Save</button>
                <button class="btn btn-cre-opn waves-effect">Cancel</button>

<input name="__RequestVerificationToken" type="hidden" value="CfDJ8K7NtNmNf5lJsh806e0aRPmUONXIh2RLjJ1oH6KtOEdcIrE95C_Obn7dzp3LNYv2Eof0VGrWukRpqxXnYDAJGverd0YJjhOSXeUEJZFmHpAnjwlJMAoTnrYn2ILawiFAHDDU6_ujcJ-blB1IsoYXRzk" /></form>

© 2017 - Azilen Technology Pvt. Ltd

Moreover Please find Image also

Body:
According to your initial question before edits , this basic setup should work:

Model:

Use List instead of Collection in your Model because Collections cannot be Indexed check this.

public class Canditate
{

    public Canditate()
    {

        CandidateCompanyMap = new List<CandidateCompanyMap>();
        CandidateDegreeMap = new List<CandidateDegreeMap>();
        CandidateDocumentMap = new List<CandidateDocumentMap>();
        CandidateTagsMap = new List<CandidateTagsMap>();
        EducationDetails = new List<EducationDetails>();

    }

    public string FirstName { get; set; }
    public string Email { get; set; }

    public List<CandidateCompanyMap> CandidateCompanyMap { get; set; }
    public List<CandidateDegreeMap> CandidateDegreeMap { get; set; }
    public List<CandidateDocumentMap> CandidateDocumentMap { get; set; }
    public List<CandidateTagsMap> CandidateTagsMap { get; set; }
    public List<EducationDetails> EducationDetails { get; set; }
}

Candidate Get Action Method:

public ActionResult Index()
{
  // Populating some dummy data

  //TODO populate canditate list from your data repository
  Canditate canditate = new Canditate();
  canditate.FirstName = "Example Name";
  canditate.Email = "example@example.org";

  List<CandidateCompanyMap> candidateCompanyList = new List<CandidateCompanyMap>();
  List<CandidateDegreeMap> candidateeDegreeList = new List<CandidateDegreeMap>();
  List<CandidateDocumentMap> candidateDocumentList = new List<CandidateDocumentMap>();
  List<CandidateTagsMap> candidateTagsList = new List<CandidateTagsMap>();

  CandidateCompanyMap candidateCompany = new CandidateCompanyMap();
  candidateCompany.CompanyName = "Example Company";
  candidateCompanyList.Add(candidateCompany);

  CandidateDegreeMap candidateDegree = new CandidateDegreeMap();
  candidateDegree.DegreeName = "Example Degree";
  candidateeDegreeList.Add(candidateDegree);

  CandidateDocumentMap candidateDocument = new CandidateDocumentMap();
  candidateDocument.DocumentName = "Example Document";
  candidateDocumentList.Add(candidateDocument);

  CandidateTagsMap candidateTags = new CandidateTagsMap();
  candidateTags.TagsName = "Example Tags";
  candidateTagsList.Add(candidateTags);

  CandidateTagsMap candidateTags2 = new CandidateTagsMap();
  candidateTags2.TagsName = "Example Tags 2";
  candidateTagsList.Add(candidateTags2);

  canditate.CandidateCompanyMap = candidateCompanyList;
  canditate.CandidateDegreeMap = candidateeDegreeList;
  canditate.CandidateDocumentMap = candidateDocumentList;
  canditate.CandidateTagsMap = candidateTagsList;

  return View(canditate);
  }

Index View:

@model Demo.Models.Canditate

@using (Html.BeginForm("Candidate", "Home", FormMethod.Post))
{

<label>Candidate First Name</label>
@Html.TextBoxFor(m => m.FirstName);

<br />

<label>Candidate Email</label>
@Html.TextBoxFor(m => m.Email);

<br />

<label>Education Details</label>

<div id="educationDetails">

    @foreach (var education in Model.EducationDetails)
    {
        @Html.Partial("_EducationalDetailsPartials", education)
    }

    <button type="button" id="addEducation">Add</button>
</div>

<label>Candidate Company</label>

for (int i = 0; i < Model.CandidateCompanyMap.Count; i++)
{

    @Html.TextBoxFor(m => m.CandidateCompanyMap[i].CompanyName);
}

<br />

<label>Candidate Degree</label>

for (int i = 0; i < Model.CandidateDegreeMap.Count; i++)
{

    @Html.TextBoxFor(m => m.CandidateDegreeMap[i].DegreeName);
}

<br />

<label>Candidate Document</label>

for (int i = 0; i < Model.CandidateDocumentMap.Count; i++)
{

    @Html.TextBoxFor(m => m.CandidateDocumentMap[i].DocumentName);
}

<br />

<label>Candidate Tags</label>

for (int i = 0; i < Model.CandidateTagsMap.Count; i++)
{

    @Html.TextBoxFor(m => m.CandidateTagsMap[i].TagsName);

    <br />
}

<input type="submit" value="Submit" />

}

Candidate Post Action Method:

    [HttpPost]
    public ActionResult Candidate(Canditate data)
    {
       // TODO Save data

        return View(data);
    }

Add Eduction GET Action Method:

    public PartialViewResult AddEduction(Canditate data)
    {

        return PartialView("_EducationalDetailsPartials", new EducationDetails());
    }

Add Eduction Partial View:

Note: Install BeginCollectionItem HtmlHelper from here to have unique name attributes in form to bind to your model properties.

 @model Demo.Models.EducationDetails
 @using HtmlHelpers.BeginCollectionItem

 @using (Html.BeginCollectionItem("educationDetails"))
 {

 @Html.LabelFor(model => model.Degree)

 @Html.EditorFor(model => model.Degree)
 @Html.ValidationMessageFor(model => model.Degree)

 @Html.LabelFor(model => model.Institute)

 @Html.EditorFor(model => model.Institute)
 @Html.ValidationMessageFor(model => model.Institute)

 <button type="button" value="Delete" class="btn btn-default">Delete</button>

<br />

}

Script to Add New Education:

<script>

$(document).ready(function () {

var url = '@Url.Action("AddEduction","Home")';

var educationDetails = $('#educationDetails');
$('#addEducation').click(function () {
   $.get(url, function (response) {
      educationDetails.append(response);

    });
  });

})

</script>


来源: stackexchange

问:
Javafx Desktop Application Deployment
I am trying to deploy a javafx desktop application. What are the executable files I need to create to cover as much as possible OS(windows/linux/Mac etc.) and how to create it? I want to package the JVM in the executable file so that the end user need not have to download any extra software.I am using netbeans 8.2 on windows 8.1 operating system.  Thanks.</p>

答:
For Mac OS you can check out this link Bundle Java program for Mac users with maven from GNU/Linux

And for Windows you can look into Inno setup for building a .exe

ContentLicense: CC BY-SA 3.0

Title: Javafx Desktop Application Deployment


问:
Sql Server - FULL JOIN splitting up the result rather than returning a joined dataset
Suppose I have the following (very simplified) schema / data set up in SQL Server:

```<code>CREATE TABLE #Ids1 (Id1 VARCHAR(1));
CREATE TABLE #Vals1 (Id1 VARCHAR(1), Id2 VARCHAR(1));

CREATE TABLE #Ids2 (Id1 VARCHAR(1));
CREATE TABLE #Vals2 (Id1 VARCHAR(1), Id2 VARCHAR(1));

INSERT INTO #Ids1 (Id1) VALUES ('a'), ('b'), ('c'), ('d');
INSERT INTO #Vals1 (Id1, Id2) VALUES ('a', '1'), ('b', '2'), ('c', '3'), ('d', '4');

INSERT INTO #Ids2 (Id1) VALUES ('a'), ('b'), ('c'), ('e'), ('f'), ('g');
INSERT INTO #Vals2 (Id1, Id2) VALUES ('a', '1'), ('b', '2'), ('c', '3'), ('e', '5'), ('f', '6'), ('g', '7');
</code>```

Basically, I have 2 similar datasets - One ending with a 1 suffix, the other ending with a 2 suffix and there is a chance either of the datasets may have data that is not in the other set.

What I would like to do is create a query that returns a single joined dataset that would look as follows:

```<code>#Ids1.Id1   #vals1.Id1  #vals1.Id2  #Ids2.Id1   #Vals2.Id1  #Vals2.Id2
a           a           1           a           a           1
b           b           2           b           b           2
c           c           3           c           c           3
d           d           4           NULL        NULL        NULL
NULL        NULL        NULL        e           e           5
NULL        NULL        NULL        f           f           6
NULL        NULL        NULL        g           g           7
</code>```

I figured the following SQL would accomplish this:

```<code>SELECT
     *
FROM
    #Ids1
    FULL JOIN #Vals1
    ON #Vals1.Id1 = #Ids1.Id1
    FULL JOIN #Ids2
    ON #Ids2.Id1 = #Ids1.Id1
    FULL JOIN #Vals2
    ON #Vals2.Id1 = #Ids2.Id1
    AND #Vals2.Id2 = #Vals1.Id2
</code>```

but it is separating out the last tables rather than joining them, so it ends up looking as follows:

```<code>#Ids1.Id1   #vals1.Id1  #vals1.Id2  #Ids2.Id1   #Vals2.Id1  #Vals2.Id2
a           a           1           a           a           1
b           b           2           b           b           2
c           c           3           c           c           3
d           d           4           NULL        NULL        NULL
NULL        NULL        NULL        e           NULL        NULL
NULL        NULL        NULL        f           NULL        NULL
NULL        NULL        NULL        g           NULL        NULL
NULL        NULL        NULL        NULL        e           5
NULL        NULL        NULL        NULL        f           6
NULL        NULL        NULL        NULL        g           7
</code>```

I've created a link to the prepared Schema and the SQL at the following URL:
http://rextester.com/SAX53638

I'm guessing / hoping I'm just missing something simple, but I just can't seem to get it to work. What's the best way to return the data I want?

答:
Join the tables internally and then join again

Try using the below the query

SELECT

     *

FROM

    (SELECT

    Ids1.Id1 AS Id11,

     vals1.Id1 AS Idv11,

     vals1.Id2 AS Idv12

     FROM

    Ids1

    FULL JOIN Vals1

    ON Vals1.Id1 = Ids1.Id1) Ivs1

    FULL JOIN

    (SELECT

     Ids2.Id1 AS Id21,

     vals2.Id1 AS Idv21,

     vals2.Id2 AS Idv22

    FROM

    Ids2

    FULL JOIN Vals2

    ON Vals2.Id1 = Ids2.Id1) Ivs2

    ON Ivs1.Id11 = Ivs2.Id21;

Body:
Suppose I have the following (very simplified) schema / data set up in SQL Server:

CREATE TABLE #Ids1 (Id1 VARCHAR(1));
CREATE TABLE #Vals1 (Id1 VARCHAR(1), Id2 VARCHAR(1));

CREATE TABLE #Ids2 (Id1 VARCHAR(1));
CREATE TABLE #Vals2 (Id1 VARCHAR(1), Id2 VARCHAR(1));

INSERT INTO #Ids1 (Id1) VALUES ('a'), ('b'), ('c'), ('d');
INSERT INTO #Vals1 (Id1, Id2) VALUES ('a', '1'), ('b', '2'), ('c', '3'), ('d', '4');

INSERT INTO #Ids2 (Id1) VALUES ('a'), ('b'), ('c'), ('e'), ('f'), ('g');
INSERT INTO #Vals2 (Id1, Id2) VALUES ('a', '1'), ('b', '2'), ('c', '3'), ('e', '5'), ('f', '6'), ('g', '7');

Basically, I have 2 similar datasets - One ending with a 1 suffix, the other ending with a 2 suffix and there is a chance either of the datasets may have data that is not in the other set.

What I would like to do is create a query that returns a single joined dataset that would look as follows:

#Ids1.Id1   #vals1.Id1  #vals1.Id2  #Ids2.Id1   #Vals2.Id1  #Vals2.Id2
a           a           1           a           a           1
b           b           2           b           b           2
c           c           3           c           c           3
d           d           4           NULL        NULL        NULL
NULL        NULL        NULL        e           e           5
NULL        NULL        NULL        f           f           6
NULL        NULL        NULL        g           g           7

I figured the following SQL would accomplish this:

SELECT
     *
FROM
    #Ids1
    FULL JOIN #Vals1
    ON #Vals1.Id1 = #Ids1.Id1
    FULL JOIN #Ids2
    ON #Ids2.Id1 = #Ids1.Id1
    FULL JOIN #Vals2
    ON #Vals2.Id1 = #Ids2.Id1
    AND #Vals2.Id2 = #Vals1.Id2

but it is separating out the last tables rather than joining them, so it ends up looking as follows:

#Ids1.Id1   #vals1.Id1  #vals1.Id2  #Ids2.Id1   #Vals2.Id1  #Vals2.Id2
a           a           1           a           a           1
b           b           2           b           b           2
c           c           3           c           c           3
d           d           4           NULL        NULL        NULL
NULL        NULL        NULL        e           NULL        NULL
NULL        NULL        NULL        f           NULL        NULL
NULL        NULL        NULL        g           NULL        NULL
NULL        NULL        NULL        NULL        e           5
NULL        NULL        NULL        NULL        f           6
NULL        NULL        NULL        NULL        g           7

I've created a link to the prepared Schema and the SQL at the following URL:
http://rextester.com/SAX53638

I'm guessing / hoping I'm just missing something simple, but I just can't seem to get it to work. What's the best way to return the data I want?


问:
loopback number precision
I'm using postgresql with loopback. I have a field in a model called amount being used as a Number. Now midway through the project, a new requirement came to hold amount value with precision. But I won't be able to store amount for example. as 1.50, as it is converted and stored as 1.5, which happens with javascript number type values.

Other approach for holding precision is to converting the property from number to string. But this change will be a major code change throughout all the modules.

Also there is a property called precision and scale for PostgreSQL connector. Is there any way in the model declaration (.json file) itself to hold precision with type number? Just wanted to be sure if there is any other approach before going through this change. Any help will be highly appreciated.

答:
You can these fields to the model.json. I have not tested the code but i think this will work </p>

```<code>"amount": {
  "type": "Number",
  "required": true,
  "postgresql": {
      "dataType": "numeric",
      "dataPrecision": 20,
      "dataScale": 0
    }
}
</code>```

Title: loopback number precision

Body:
You can these fields to the model.json. I have not tested the code but i think this will work

"amount": {
  "type": "Number",
  "required": true,
  "postgresql": {
      "dataType": "numeric",
      "dataPrecision": 20,
      "dataScale": 0
    }
}


问:
How to get response from another site in laravel controller
I want to create API in laravel which gives data return.
I want to get data from this link
into my laravel controller.</p>

答:
This can be done by pulling in guzzle.  Try: https://github.com/guzzle/guzzle

```<code>$client = new Client();
$body = $client->get('mtaapi.herokuapp.com/stations')->getBody();
$obj = json_decode($body);
</code>```

Hope this helps you!!

Body:
This can be done by pulling in guzzle.  Try: https://github.com/guzzle/guzzle

$client = new Client();
$body = $client->get('mtaapi.herokuapp.com/stations')->getBody();
$obj = json_decode($body);

Hope this helps you!!


问:
Change color of span upon click
https://codepen.io/SmileySteven/pen/pdBYdv?editors=1111

```<code>function test(){
  var span = document.querySelectorAll('span');
  for(var i = 0 ; i <= span.length ;i++){
    span.addEventListener('click', function(){
    this.style.backgroundColor === '#ffffff'? this.style.backgroundColor = 'yellow'
         : this.style.backgroundColor="#000000";
   })
 }
}
test();
</code>```

Hello guys, I am trying to change the background color of my spans upon click but it does not seem to work - care to guide me as to what I am doing wrong?  I have set all span to background color of #ffffff

答:
function test(){
  var span = document.querySelectorAll('span');

  span.forEach((item)=>{
    item.addEventListener('click',()=>{
      let styles = getComputedStyle(item);
      styles.backgroundColor == 'rgb(255, 255, 255)' ? item.style.backgroundColor = 'yellow' : item.style.backgroundColor = 'black';
    });
  });
}
test();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.def.def2{
  background-color:orange
}

div#ya{
  background-color:purple
}

span{

  background-color:#ffffff
}</code>```

<input type="text" id="i1">   </input>
<input type="text" id="i2">   </input>
<input type="number" id="i3">   </input>
<button id="btn">  sad </button>

 Div1

 div2

 div2

 sad

 test  test  test ```

I recommend to use forEach with querySelectorAll().

And, if you want to get the value of background-color, you should better use getComputedStyle().

But, getComputedStyle().backgroundColor always return rgb(), so you have to use rgb().

Title: Change color of span upon click

Body:
https://codepen.io/SmileySteven/pen/pdBYdv?editors=1111

function test(){
  var span = document.querySelectorAll('span');
  for(var i = 0 ; i <= span.length ;i++){
    span.addEventListener('click', function(){
    this.style.backgroundColor === '#ffffff'? this.style.backgroundColor = 'yellow'
         : this.style.backgroundColor="#000000";
   })
 }
}
test();

Hello guys, I am trying to change the background color of my spans upon click but it does not seem to work - care to guide me as to what I am doing wrong?  I have set all span to background color of #ffffff

Body:
function test(){
  var span = document.querySelectorAll('span');

  span.forEach((item)=>{
    item.addEventListener('click',()=>{
      let styles = getComputedStyle(item);
      styles.backgroundColor == 'rgb(255, 255, 255)' ? item.style.backgroundColor = 'yellow' : item.style.backgroundColor = 'black';
    });
  });
}
test();

.def.def2{
  background-color:orange
}

div#ya{
  background-color:purple
}

span{

  background-color:#ffffff
}

<input type="text" id="i1">   </input>
<input type="text" id="i2">   </input>
<input type="number" id="i3">   </input>
<button id="btn">  sad </button>
<div> Div1  </div>

<div class="def def2"> div2 </div>
<div id="ya" class="def def2 def3 omg"> div2 </div>
<p> sad </p>

<span > test </span><span> test </span><span> test </span>

I recommend to use forEach with querySelectorAll().

And, if you want to get the value of background-color, you should better use getComputedStyle().

But, getComputedStyle().backgroundColor always return rgb(), so you have to use rgb().


问:
Tuple vs Class in Java
Are there any advantages of using Tuples instead of creating a new class in Java?
I've seen something like this a few times
return Pair.of (username, password);. And I've always wondered what kind of advantages it has in relation to something like this return new Credentials (username, password).

答:
Java doesn't have a (first class) notion of tuples. Some projects and libraries introduce types like Pair or Tuple2/Tuple3/Tuple4/... to make up for it, but this is often considered poor style in Java.

By contrast returning a clearly-defined type like Credentials that provides not just structure but also type safety and meaningful getters for your data you make your code clearer, safer, and easier to work with. The Auto/Value project in particular makes it quick and painless to create value-types, making tuple-esque types all but unnecessary.

Title: Tuple vs Class in Java


问:
Why is my array outputting one row
My $aExtensionObjects print_r fine shows all of the things in the array but $aExtensionName only seems to output one why?

```<code>$aExtensionObjects Array:

Array ( [0] => Extension Object ( [iID:private] => [sExtensionName:private] => 2147483647 [db:private] => MySQLiPluggin Object ( [sqliConnection:private] => mysqli Object ( ) [Query:private] => [getResult:private] => ) [bExisting] => 1 ) [1] => Extension Object ( [iID:private] => [sExtensionName:private] => 876378990 [db:private] => MySQLiPluggin Object ( [sqliConnection:private] => mysqli Object ( ) [Query:private] => [getResult:private] => ) [bExisting] => 1 )) ) Etc..

$aExtensionName Array:

Array ( [] => 989898 )
</code>```

The code [ed: maybe?]

```<code>    $manExtensionManager  = new extensionManager();

    $aExtensionObjects   = $manExtensionManager->getallExtensions();

    $aExtensionName      = array();

for($iCount=0; $iCount<count($aExtensionObjects);$iCount++){
    $Extension = $aExtensionObjects[$iCount];
    $aExtensionName[$Extension->getExtensionID()] = $Extension->getExtensionName();
}
</code>```

答:
You're missing a dash --

```<code>$aExtensionName[$Extension->getExtensionID()] = $Extension>getExtensionName();
</code>```

should be

```<code>$aExtensionName[$Extension->getExtensionID()] = $Extension->getExtensionName();
</code>```

ContentLicense: CC BY-SA 2.5

Title: Why is my array outputting one row

Body:
My $aExtensionObjects print_r fine shows all of the things in the array but $aExtensionName only seems to output one why?

$aExtensionObjects Array:

Array ( [0] => Extension Object ( [iID:private] => [sExtensionName:private] => 2147483647 [db:private] => MySQLiPluggin Object ( [sqliConnection:private] => mysqli Object ( ) [Query:private] => [getResult:private] => ) [bExisting] => 1 ) [1] => Extension Object ( [iID:private] => [sExtensionName:private] => 876378990 [db:private] => MySQLiPluggin Object ( [sqliConnection:private] => mysqli Object ( ) [Query:private] => [getResult:private] => ) [bExisting] => 1 )) ) Etc..

$aExtensionName Array:

Array ( [] => 989898 )

The code [ed: maybe?]

    $manExtensionManager  = new extensionManager();

    $aExtensionObjects   = $manExtensionManager->getallExtensions();

    $aExtensionName      = array();

for($iCount=0; $iCount<count($aExtensionObjects);$iCount++){
    $Extension = $aExtensionObjects[$iCount];
    $aExtensionName[$Extension->getExtensionID()] = $Extension->getExtensionName();
}

Body:
You're missing a dash --

$aExtensionName[$Extension->getExtensionID()] = $Extension>getExtensionName();

should be

$aExtensionName[$Extension->getExtensionID()] = $Extension->getExtensionName();


问:
How to parse json array using retrofit?
My response is like this..

```<code>{
    "IsSuccess": true,
    "ResponseObject": ["one", "two", "three", "four", "five"]
}}
</code>```

i tried to do by creating POJO. Kindly help me with the solution.

答:
Your POJO class should be like this.

```<code>public class TempParams {
    /**
     * IsSuccess : true
     * ResponseObject : ["one","two","three","four","five"]
     */

    private boolean IsSuccess;
    private List<String> ResponseObject;

    public boolean isIsSuccess() {
        return IsSuccess;
    }

    public void setIsSuccess(boolean IsSuccess) {
        this.IsSuccess = IsSuccess;
    }

    public List<String> getResponseObject() {
        return ResponseObject;
    }

    public void setResponseObject(List<String> ResponseObject) {
        this.ResponseObject = ResponseObject;
    }

}
</code>```

After successfully getting response object you have to convert it like this.

```<code>Gson gson = new Gson();
TempParams model = gson.fromJson(mObject.toString(), TempParams.class);
</code>```

Now you can get value from POJO class.

Title: How to parse json array using retrofit?

Body:
My response is like this..

{
    "IsSuccess": true,
    "ResponseObject": ["one", "two", "three", "four", "five"]
}}

i tried to do by creating POJO. Kindly help me with the solution.

Body:
Your POJO class should be like this.

public class TempParams {
    /**
     * IsSuccess : true
     * ResponseObject : ["one","two","three","four","five"]
     */

    private boolean IsSuccess;
    private List<String> ResponseObject;

    public boolean isIsSuccess() {
        return IsSuccess;
    }

    public void setIsSuccess(boolean IsSuccess) {
        this.IsSuccess = IsSuccess;
    }

    public List<String> getResponseObject() {
        return ResponseObject;
    }

    public void setResponseObject(List<String> ResponseObject) {
        this.ResponseObject = ResponseObject;
    }

}

After successfully getting response object you have to convert it like this.

Gson gson = new Gson();
TempParams model = gson.fromJson(mObject.toString(), TempParams.class);

Now you can get value from POJO class.


问:
Template parameter deduction for constructors from initializer list
At the Kona meeting, template parameter deduction for constructors (P0091R0) has been approved. It simplifies some variable definitions:

```<code>std::pair   p  {1,2};     // o.k., constructor pair<int,int>(1,2)
std::vector v1 (10, 0);   // o.k., 10 zeroes, constructor vector<int>(size_t n, T initvalue)
std::vector v2 {10, 0};   // o.k., 2 values: 10, 0, apparently initializer list?
std::vector v3 = {10, 0}; // o.k., same as v2?
</code>```

However, the following lines do not compile in gcc 7 HEAD 201611 version (live example):

```<code>std::vector v4 = {3};     // error: no matching function for call to 'std::vector(int)'
std::vector v5 {1, 2, 3}; // error: 'int' is not a class
std::set    s  {1, 2, 3}; // error: no matching function for call to 'std::set(int,int,int)'
</code>```

Are these just "a bridge too far", since they involve initializer lists?
Are they covered by template type parameter deduction?
Will they be allowed, when compilers conform to C++1z?

答:
Because you want to call the foo::foo(const initializer_list &) constructor, you need to tell the compiler that there's exactly one argument, so you need an extra pair of parentheses or braces:

```<code>std::vector v5 ({1, 2, 3});
std::set    s  ({1, 2, 3});
               ^         ^
</code>```

In this way, the compiler knows that you're calling a function with only one argument as const initializer_list &, instead of a function with three ints.

Body:
At the Kona meeting, template parameter deduction for constructors (P0091R0) has been approved. It simplifies some variable definitions:

std::pair   p  {1,2};     // o.k., constructor pair<int,int>(1,2)
std::vector v1 (10, 0);   // o.k., 10 zeroes, constructor vector<int>(size_t n, T initvalue)
std::vector v2 {10, 0};   // o.k., 2 values: 10, 0, apparently initializer list?
std::vector v3 = {10, 0}; // o.k., same as v2?

However, the following lines do not compile in gcc 7 HEAD 201611 version (live example):

std::vector v4 = {3};     // error: no matching function for call to 'std::vector(int)'
std::vector v5 {1, 2, 3}; // error: 'int' is not a class
std::set    s  {1, 2, 3}; // error: no matching function for call to 'std::set(int,int,int)'

Are these just "a bridge too far", since they involve initializer lists?
Are they covered by template type parameter deduction?
Will they be allowed, when compilers conform to C++1z?

Body:
Because you want to call the foo::foo(const initializer_list &) constructor, you need to tell the compiler that there's exactly one argument, so you need an extra pair of parentheses or braces:

std::vector v5 ({1, 2, 3});
std::set    s  ({1, 2, 3});
               ^         ^

In this way, the compiler knows that you're calling a function with only one argument as const initializer_list &, instead of a function with three ints.

ContentLicense: CC BY-SA 4.0


问:
SQLite: full outer join with four tables with 30+ columns
This question is an extension to this post

 I want to join four different tables with SQLite which have just two columns in common. However, assume that there are 30+ columns, i.e more than just columns a - h. Please take a look at following example

Table1:

```<code>a   b   lon lat
---------------
22  33  11  22
</code>```

Table2:

```<code>c   d   lon lat
---------------
1   2   44  45
</code>```

Table3

```<code>e       f       lon lat
-----------------------
NULL    NULL    100 101
</code>```

Table4

```<code>g       h       lon lat
-----------------------
NULL    NULL    200 201
</code>```

The current solution is the following

```<code>SELECT a,b,NULL AS c, NULL AS d,NULL AS e, NULL AS f, NULL AS g, NULL AS h,
lon,lat
FROM table1
UNION ALL
SELECT NULL, NULL,c,d,NULL AS e, NULL AS f, NULL AS g, NULL AS h, lon,lat
FROM table2
UNION ALL
SELECT NULL, NULL,NULL,NULL,e,f, NULL AS g, NULL AS h, lon,lat
FROM table3
UNION ALL
SELECT NULL, NULL,NULL,NULL,NULL,NULL,g,h, lon,lat
from table4
</code>```

Result:

```<code>+------+------+------+------+------+------+------+------+-----+-----+
|  a   |  b   |  c   |  d   |  e   |  f   |  g   |  h   | lon | lat |
+------+------+------+------+------+------+------+------+-----+-----+
| 22   | 33   | NULL | NULL | NULL | NULL | NULL | NULL |  11 |  22 |
| NULL | NULL | 1    | 2    | NULL | NULL | NULL | NULL |  44 |  45 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 100 | 101 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 200 | 201 |
+------+------+------+------+------+------+------+------+-----+-----+
</code>```

DEMO

 Problem: What if I have not just the columns a until h, but a until z, i.e many many columns in table1, table2, table3, and table4 -> It would be very time-consuming and the structure wouldn't be clear if I had to write everywhere NULL as [letter] in my sql statement

 @zarruq was a huge help and he suggested that In that case I can just use `UNION ALL` and then `PIVOT` to convert columns to rows

 However, I am not sure how to do that. And, I do not know 100% what he means by that.

 EDIT: SQLite does not support pivot: Any other suggestions?

答:
One way to derive the result using pivot()(if your dbms supports that) could be as below.

```<code>select a,b,c,d,e,f,g,h,lon,lat
from (
select 'a' as columnName1, a as val1,'b' as ColumnName2, b as val2, lon,lat
from table1
union all
select 'c',c,'d', d, lon,lat
from table2
union all
select 'e',e,'f', f, lon,lat
from table3
union all
select 'g',g,'h', h, lon,lat
from table4
) t1
PIVOT (MAX(val1)
      FOR columnName1 IN (a,c,e,g)) as Pivot1
PIVOT (MAX(val2)
      FOR columnName2 IN (b,d,f,h)) AS Pivot2;
</code>```

Result:

```<code>+------+------+------+------+------+------+------+------+-----+-----+
|  a   |  b   |  c   |  d   |  e   |  f   |  g   |  h   | lon | lat |
+------+------+------+------+------+------+------+------+-----+-----+
| 22   | 33   | NULL | NULL | NULL | NULL | NULL | NULL |  11 |  22 |
| NULL | NULL | 1    | 2    | NULL | NULL | NULL | NULL |  44 |  45 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 100 | 101 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 200 | 201 |
+------+------+------+------+------+------+------+------+-----+-----+
</code>```

DEMO

P.S. Kindly note that the above query is for sql-Server, so you probably need to tweek it for your dbms.

Body:
This question is an extension to this post

 I want to join four different tables with SQLite which have just two columns in common. However, assume that there are 30+ columns, i.e more than just columns a - h. Please take a look at following example

Table1:

a   b   lon lat
---------------
22  33  11  22

Table2:

c   d   lon lat
---------------
1   2   44  45

Table3

e       f       lon lat
-----------------------
NULL    NULL    100 101

Table4

g       h       lon lat
-----------------------
NULL    NULL    200 201

The current solution is the following

SELECT a,b,NULL AS c, NULL AS d,NULL AS e, NULL AS f, NULL AS g, NULL AS h,
lon,lat
FROM table1
UNION ALL
SELECT NULL, NULL,c,d,NULL AS e, NULL AS f, NULL AS g, NULL AS h, lon,lat
FROM table2
UNION ALL
SELECT NULL, NULL,NULL,NULL,e,f, NULL AS g, NULL AS h, lon,lat
FROM table3
UNION ALL
SELECT NULL, NULL,NULL,NULL,NULL,NULL,g,h, lon,lat
from table4

Result:

+------+------+------+------+------+------+------+------+-----+-----+
|  a   |  b   |  c   |  d   |  e   |  f   |  g   |  h   | lon | lat |
+------+------+------+------+------+------+------+------+-----+-----+
| 22   | 33   | NULL | NULL | NULL | NULL | NULL | NULL |  11 |  22 |
| NULL | NULL | 1    | 2    | NULL | NULL | NULL | NULL |  44 |  45 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 100 | 101 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 200 | 201 |
+------+------+------+------+------+------+------+------+-----+-----+

DEMO

 Problem: What if I have not just the columns a until h, but a until z, i.e many many columns in table1, table2, table3, and table4 -> It would be very time-consuming and the structure wouldn't be clear if I had to write everywhere NULL as [letter] in my sql statement

 @zarruq was a huge help and he suggested that In that case I can just use `UNION ALL` and then `PIVOT` to convert columns to rows

 However, I am not sure how to do that. And, I do not know 100% what he means by that.

 EDIT: SQLite does not support pivot: Any other suggestions?

Body:
One way to derive the result using pivot()(if your dbms supports that) could be as below.

select a,b,c,d,e,f,g,h,lon,lat
from (
select 'a' as columnName1, a as val1,'b' as ColumnName2, b as val2, lon,lat
from table1
union all
select 'c',c,'d', d, lon,lat
from table2
union all
select 'e',e,'f', f, lon,lat
from table3
union all
select 'g',g,'h', h, lon,lat
from table4
) t1
PIVOT (MAX(val1)
      FOR columnName1 IN (a,c,e,g)) as Pivot1
PIVOT (MAX(val2)
      FOR columnName2 IN (b,d,f,h)) AS Pivot2;

Result:

+------+------+------+------+------+------+------+------+-----+-----+
|  a   |  b   |  c   |  d   |  e   |  f   |  g   |  h   | lon | lat |
+------+------+------+------+------+------+------+------+-----+-----+
| 22   | 33   | NULL | NULL | NULL | NULL | NULL | NULL |  11 |  22 |
| NULL | NULL | 1    | 2    | NULL | NULL | NULL | NULL |  44 |  45 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 100 | 101 |
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | 200 | 201 |
+------+------+------+------+------+------+------+------+-----+-----+

DEMO

P.S. Kindly note that the above query is for sql-Server, so you probably need to tweek it for your dbms.


问:
Compare date times in java in DAY hh:mm-hh:mm
How do we comapare dates and get the remainig available slots in java?

```<code>Sun 10:00-11:00
Sun 12:00-14:00
Sun 15:00-16:00
</code>```

So how can we get alll the availble time for a day in other than these three slots? how do we compare these dates in java? Can anyone please suggest?

答:
Design a class for an occupied slot. It sounds like you need a DayOfWeek field and two LocalTime fields. Parse the date-times into such objects: split at the hyphen and use a couple of DateTimeFormatters. Sort your objects. For each pair of adjacent objects, determine if there is a vacant slot between them (also report an error if there’s an overlap). You will also need to decide whether to consider a vacant slot before the first date-time (Sunday from 00:00 to 10:00?) and after the last one.

I am on purpose mentioning classes and an enum from java.time, the modern Java date and time API. It’s nice to work with, I recommend it without hesitation.

EDIT: You’ve now had five days for coding your class, so it may be time to share my version for you to compare and for future readers.

```<code>public class Slot {

    private static Pattern textPattern = Pattern.compile("(\\w+) ([0-9:]+)-([0-9:]+)");
    private static DateTimeFormatter dayFormatter = DateTimeFormatter.ofPattern("EEE");

    public static Slot parse(String text) {
        Matcher textMatcher = textPattern.matcher(text);
        if (textMatcher.matches()) {
            DayOfWeek day = DayOfWeek.from(dayFormatter.parse(textMatcher.group(1)));
            LocalTime startTime = LocalTime.parse(textMatcher.group(2));
            LocalTime endTime = LocalTime.parse(textMatcher.group(3));
            return new Slot(day, startTime, endTime);
        } else {
            throw new IllegalArgumentException("Unparsable slot " + text + ", expected format Sun 12:00-14:00");
        }
    }

    private final DayOfWeek day;
    private final LocalTime startTime;
    private final LocalTime endTime;

    Slot(DayOfWeek day, LocalTime startTime, LocalTime endTime) {
        if (! endTime.isAfter(startTime)) {
            throw new IllegalArgumentException("End time must be after start time");
        }
        this.day = Objects.requireNonNull(day);
        this.startTime = startTime;
        this.endTime = endTime;
    }

    public DayOfWeek getDay() {
        return day;
    }

    public LocalTime getStartTime() {
        return startTime;
    }

    public LocalTime getEndTime() {
        return endTime;
    }

    /**
     * @param nextSlot
     * @return A new Slot object representing the vacant Slot between this Slot and nextSlot,
     *      or an empty Optional if no gap
     */
    public Optional<Slot> slotBetween(Slot nextSlot) {
        if (! nextSlot.getDay().equals(day)) {
            throw new IllegalArgumentException("Cannot compare slots on different days of week");
        }
        if (nextSlot.getStartTime().isBefore(endTime)) {
            throw new IllegalArgumentException("Error: overlap between slots " + this + " and " + nextSlot);
        }
        if (nextSlot.getStartTime().isAfter(endTime)) { // there is a gap
            return Optional.of(new Slot(day, endTime, nextSlot.getStartTime()));
        } else {
            return Optional.empty();
        }
    }

    @Override
    public String toString() {
        return dayFormatter.format(day) + ' ' + startTime + '-' + endTime;
    }

}
</code>```

Body:
How do we comapare dates and get the remainig available slots in java?

Sun 10:00-11:00
Sun 12:00-14:00
Sun 15:00-16:00

So how can we get alll the availble time for a day in other than these three slots? how do we compare these dates in java? Can anyone please suggest?

Body:
Design a class for an occupied slot. It sounds like you need a DayOfWeek field and two LocalTime fields. Parse the date-times into such objects: split at the hyphen and use a couple of DateTimeFormatters. Sort your objects. For each pair of adjacent objects, determine if there is a vacant slot between them (also report an error if there’s an overlap). You will also need to decide whether to consider a vacant slot before the first date-time (Sunday from 00:00 to 10:00?) and after the last one.

I am on purpose mentioning classes and an enum from java.time, the modern Java date and time API. It’s nice to work with, I recommend it without hesitation.

EDIT: You’ve now had five days for coding your class, so it may be time to share my version for you to compare and for future readers.

public class Slot {

    private static Pattern textPattern = Pattern.compile("(\\w+) ([0-9:]+)-([0-9:]+)");
    private static DateTimeFormatter dayFormatter = DateTimeFormatter.ofPattern("EEE");

    public static Slot parse(String text) {
        Matcher textMatcher = textPattern.matcher(text);
        if (textMatcher.matches()) {
            DayOfWeek day = DayOfWeek.from(dayFormatter.parse(textMatcher.group(1)));
            LocalTime startTime = LocalTime.parse(textMatcher.group(2));
            LocalTime endTime = LocalTime.parse(textMatcher.group(3));
            return new Slot(day, startTime, endTime);
        } else {
            throw new IllegalArgumentException("Unparsable slot " + text + ", expected format Sun 12:00-14:00");
        }
    }

    private final DayOfWeek day;
    private final LocalTime startTime;
    private final LocalTime endTime;

    Slot(DayOfWeek day, LocalTime startTime, LocalTime endTime) {
        if (! endTime.isAfter(startTime)) {
            throw new IllegalArgumentException("End time must be after start time");
        }
        this.day = Objects.requireNonNull(day);
        this.startTime = startTime;
        this.endTime = endTime;
    }

    public DayOfWeek getDay() {
        return day;
    }

    public LocalTime getStartTime() {
        return startTime;
    }

    public LocalTime getEndTime() {
        return endTime;
    }

    /**
     * @param nextSlot
     * @return A new Slot object representing the vacant Slot between this Slot and nextSlot,
     *      or an empty Optional if no gap
     */
    public Optional<Slot> slotBetween(Slot nextSlot) {
        if (! nextSlot.getDay().equals(day)) {
            throw new IllegalArgumentException("Cannot compare slots on different days of week");
        }
        if (nextSlot.getStartTime().isBefore(endTime)) {
            throw new IllegalArgumentException("Error: overlap between slots " + this + " and " + nextSlot);
        }
        if (nextSlot.getStartTime().isAfter(endTime)) { // there is a gap
            return Optional.of(new Slot(day, endTime, nextSlot.getStartTime()));
        } else {
            return Optional.empty();
        }
    }

    @Override
    public String toString() {
        return dayFormatter.format(day) + ' ' + startTime + '-' + endTime;
    }

}


问:
get the count of columns contains a string in pandas
I have two dataframes df1 and df2.

df1:

```<code>PartNumber
0000D3447E
0000D3447E
0000D3447E12
0000D3447E
0000D3447E
0000D3447E
0000D3447E2345
0000F2892E
0000F2892E
0000F2892E
0000F2892E34
0000F2892E
0000F2892E
0000F2892E12
</code>```

df2:

```<code>PartNumber
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S2245
0000F2892EDI1
0000F2892EDI1
0000F2892EDI1
0000F2892EDI124
0000F2892EDI1
0000F2892EDI1
0000F2892EDI1
0000D1617EAD6
0000D1617EAD6
0000D1617EAD6137
0000D1617EAD6
0000D1617EAD6
0000D1617EAD612
0000D1617EAD6
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
</code>```

i need to take '0000D3447E' from df1 and get the column count of df2 which contains this string and update the count in df1 by creating a new column.

the given answer    df1['count_of_colors'] = df1['PartNumber'].map(df2['PartNumber'].str[:10].value_counts())

 may solve the problem but the string is not constant with 10 characters.So, i'm getting the wrong count of the strings because the string is restricted is str[:10] characters.

Thanks.

答:
My code is here. It works for me.. I could not copy all the data that u gave, but a sample is here</p>

```<code>import pandas as pd
df1= pd.DataFrame(["0000D3447E","0000F2892E"])
df1.columns=['data']
df2=pd.DataFrame(["0000D3447E","0000D3447E","0000D3447E","0000D3447E","0000F2892E"])
df2.columns=['data']

df1['count']= df1['data'].map(df2['data'].value_counts())

df1
</code>```

Body:
I have two dataframes df1 and df2.

df1:

PartNumber
0000D3447E
0000D3447E
0000D3447E12
0000D3447E
0000D3447E
0000D3447E
0000D3447E2345
0000F2892E
0000F2892E
0000F2892E
0000F2892E34
0000F2892E
0000F2892E
0000F2892E12

df2:

PartNumber
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S
0000D3447E39S2245
0000F2892EDI1
0000F2892EDI1
0000F2892EDI1
0000F2892EDI124
0000F2892EDI1
0000F2892EDI1
0000F2892EDI1
0000D1617EAD6
0000D1617EAD6
0000D1617EAD6137
0000D1617EAD6
0000D1617EAD6
0000D1617EAD612
0000D1617EAD6
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1
0000D3447EYG1

i need to take '0000D3447E' from df1 and get the column count of df2 which contains this string and update the count in df1 by creating a new column.

the given answer    df1['count_of_colors'] = df1['PartNumber'].map(df2['PartNumber'].str[:10].value_counts())

 may solve the problem but the string is not constant with 10 characters.So, i'm getting the wrong count of the strings because the string is restricted is str[:10] characters.

Thanks.

Body:
My code is here. It works for me.. I could not copy all the data that u gave, but a sample is here

import pandas as pd
df1= pd.DataFrame(["0000D3447E","0000F2892E"])
df1.columns=['data']
df2=pd.DataFrame(["0000D3447E","0000D3447E","0000D3447E","0000D3447E","0000F2892E"])
df2.columns=['data']

df1['count']= df1['data'].map(df2['data'].value_counts())

df1


问:
jquery : show/hide div, timing
I have a pretty standard problem here.

I have an error div that,

when a button is pressed is populated with an error message,
the div is then faded in, after (500*n)ms (where n = number of letters) the div is faded out.

my issue occurs when the user presses the button again before the div has faded out.

while the div is still visible the divs contents are updated with the new error message,

after the initial (500*n)ms the div is faded out, then immediately gets faded back in and is visible for another (500*n)ms.

What I want is.

user clicks button

div contents are updated

div is faded in

user clicks button again

div immediately fades out

content is updated

div is faded in.

How can I achieve this?

My current code is below

```<code>function login_error(message){
        $('form').effect('shake', { times: 1 }, 50);
        $('#error').html(message).fadeIn('fast').delay(500*message.length).fadeOut('fast');
}
</code>```

答:
Perhaps if you stop the animation and reset the div</p>

```<code>  $('#error').stop().hide().html(message).fadeIn('fast').delay(500*message.length).fadeOut('fast');
</code>```

Title: jquery : show/hide div, timing

Body:
I have a pretty standard problem here.

I have an error div that,

when a button is pressed is populated with an error message,
the div is then faded in, after (500*n)ms (where n = number of letters) the div is faded out.

my issue occurs when the user presses the button again before the div has faded out.

while the div is still visible the divs contents are updated with the new error message,

after the initial (500*n)ms the div is faded out, then immediately gets faded back in and is visible for another (500*n)ms.

What I want is.

user clicks button

div contents are updated

div is faded in

user clicks button again

div immediately fades out

content is updated

div is faded in.

How can I achieve this?

My current code is below

function login_error(message){
        $('form').effect('shake', { times: 1 }, 50);
        $('#error').html(message).fadeIn('fast').delay(500*message.length).fadeOut('fast');
}

Body:
Perhaps if you stop the animation and reset the div

  $('#error').stop().hide().html(message).fadeIn('fast').delay(500*message.length).fadeOut('fast');


问:
AndroidJUnit4 Espresso crash because of same id used in other fragments
Espresso crashing because of duplicate id used in application is there any solution working with duplicate id names.

```<code>onView(withId(R.id.linearMenu)).perform(click());
</code>```

Crash

android.support.test.espresso.NoMatchingViewException: No views in
  hierarchy found matching: with id:
  com.Example.activities:id/linearMenu

答:
From here count child elements with same id

```<code>public static Matcher<View> withChildViewCount(final int count, final Matcher<View> childMatcher) {
return new BoundedMatcher<View, ViewGroup>(ViewGroup.class) {
    @Override
    protected boolean matchesSafely(ViewGroup viewGroup) {
        int matchCount = 0;
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            if (childMatcher.matches(viewGroup.getChildAt(i))) {
                matchCount++;
            }
        }

        return matchCount == count;
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("ViewGroup with child-count=" + count + " and");
        childMatcher.describeTo(description);
    }
};
</code>```

}

Then just call

```<code>  onView(withId(R.id.view_group)).check(matches(withChildViewCount(2, withId(R.id.image_view))));
</code>```

Body:
Espresso crashing because of duplicate id used in application is there any solution working with duplicate id names.

onView(withId(R.id.linearMenu)).perform(click());

Crash

android.support.test.espresso.NoMatchingViewException: No views in
  hierarchy found matching: with id:
  com.Example.activities:id/linearMenu

Body:
From here count child elements with same id

public static Matcher<View> withChildViewCount(final int count, final Matcher<View> childMatcher) {
return new BoundedMatcher<View, ViewGroup>(ViewGroup.class) {
    @Override
    protected boolean matchesSafely(ViewGroup viewGroup) {
        int matchCount = 0;
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            if (childMatcher.matches(viewGroup.getChildAt(i))) {
                matchCount++;
            }
        }

        return matchCount == count;
    }

    @Override
    public void describeTo(Description description) {
        description.appendText("ViewGroup with child-count=" + count + " and");
        childMatcher.describeTo(description);
    }
};

}

Then just call

  onView(withId(R.id.view_group)).check(matches(withChildViewCount(2, withId(R.id.image_view))));


问:
Why set Xmx value only then java API get heap init value is 0?

When I set Xmx value,I found heap init value is 0 through Java API,
I set Xms and Xmx values ,I found heap init value is not 0 through Java API,
I not set Xms and Xmx values ,I found heap init value is not 0 through Java API.

-Xmx512M

-Xms256M -Xmx512M

not set

I found that JDK1.5 would have this problem.
    MemoryUsage heapMemoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
    heapMemoryUsage.getInit();

I want to know the principle

答:
Trying my best to interpret: -Xms lets you set the minimum heap size. This is what the JVM starts with. As your process requires more memory, it requests memory from the OS. -Xmx lets you set the max heap size; if your process exceeds the value you set for -Xmx, it throws a java.lang.OutOfMemoryError.

Perhaps, this is what you need: How's the default java heap size determined?


问:
Modify arguments after calling exec.Cmd() in Go
I am trying to run command with exec.Cmd(command, flags...) and want to have the flexibility to modify the arguments before calling the cmd.Run() function.

for example:

```<code>cmd := exec.Command("echo", "hello world")
cmd.Env = []string{"env1=1"}
cmd.Args = []string{"echo2", "oh wait I changed my mind"}
cmd.Run()
</code>```

The above code seems to be always running echo hello world but not echo2 oh wait I changed my mind

Am I correct to expect echo2 to be run instead of echo?

答:
When changing the command to execute, you must also set cmd.Path as in  exec.Command. </p>

```<code>cmd := exec.Command("echo", "hello world")
cmd.Env = []string{"env1=1"}
cmd.Args = []string{"echo2", "oh wait I changed my mind"}

lp, err := exec.LookPath("echo2")
if err != nil {
    // handle error
}

cmd.Path = lp
if err := cmd.Run(); err != nil {
    // handle error
}
</code>```

Body:
I am trying to run command with exec.Cmd(command, flags...) and want to have the flexibility to modify the arguments before calling the cmd.Run() function.

for example:

cmd := exec.Command("echo", "hello world")
cmd.Env = []string{"env1=1"}
cmd.Args = []string{"echo2", "oh wait I changed my mind"}
cmd.Run()

The above code seems to be always running echo hello world but not echo2 oh wait I changed my mind

Am I correct to expect echo2 to be run instead of echo?

Body:
When changing the command to execute, you must also set cmd.Path as in  exec.Command.

cmd := exec.Command("echo", "hello world")
cmd.Env = []string{"env1=1"}
cmd.Args = []string{"echo2", "oh wait I changed my mind"}

lp, err := exec.LookPath("echo2")
if err != nil {
    // handle error
}

cmd.Path = lp
if err := cmd.Run(); err != nil {
    // handle error
}


问:
Class selector works even after removing class
I have a live class selector (on) which should work on elements with numberonly class and removes non-numeric values from field. It does not stop working even when I remove the numberonly class from element:

$(document).ready(function(){
  $(".numberonly").on("input propertychange paste",function(){
    $(this).val($(this).val().replace(/[^\d.-]/g, ''));
  });
});

$(document).ready(function(){
  $("#myfield").removeClass("numberonly");
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input {width:300px;max-width:100%}</code>```

This input should accept non-numeric values
because I removed class "numberonly":

<input id="myfield" class="numberonly">```

答:
That is because events are attached on DOM element and not on selectors. You should rather add if condition in click event to check whether element have class in it or not:

```<code>$(document).ready(function(){
  $(".numberonly").on("input propertychange paste",function(){
    if($(this).hasClass('numberonly'))
       $(this).val($(this).val().replace(/[^\d.-]/g, ''));
  });
});
</code>```

$(document).ready(function(){
   $(".numberonly").on("input propertychange paste",function(){
  if($(this).hasClass('numberonly'))
     $(this).val($(this).val().replace(/[^\d.-]/g, ''));
});
});

$(document).ready(function(){
  $("#myfield").removeClass("numberonly");
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input {width:300px;max-width:100%}</code>```

This input should accept non-numeric values
because I removed class "numberonly":

<input id="myfield" class="numberonly">```

Body:
I have a live class selector (on) which should work on elements with numberonly class and removes non-numeric values from field. It does not stop working even when I remove the numberonly class from element:

$(document).ready(function(){
  $(".numberonly").on("input propertychange paste",function(){
    $(this).val($(this).val().replace(/[^\d.-]/g, ''));
  });
});

$(document).ready(function(){
  $("#myfield").removeClass("numberonly");
})

input {width:300px;max-width:100%}

This input should accept non-numeric values
because I removed class "numberonly":

<input id="myfield" class="numberonly">

Body:
That is because events are attached on DOM element and not on selectors. You should rather add if condition in click event to check whether element have class in it or not:

$(document).ready(function(){
  $(".numberonly").on("input propertychange paste",function(){
    if($(this).hasClass('numberonly'))
       $(this).val($(this).val().replace(/[^\d.-]/g, ''));
  });
});

$(document).ready(function(){
   $(".numberonly").on("input propertychange paste",function(){
  if($(this).hasClass('numberonly'))
     $(this).val($(this).val().replace(/[^\d.-]/g, ''));
});
});

$(document).ready(function(){
  $("#myfield").removeClass("numberonly");
})

input {width:300px;max-width:100%}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This input should accept non-numeric values<br>because I removed class "numberonly":<br><br>
<input id="myfield" class="numberonly">


问:
My Magento Extension Install Script Will Not Run
I am trying to create an install script for my extension and for some reason it will not the install script. The extension will show up in the core_resource table, but the attributes I am trying to create will not create.

I am pretty sure that the script is not even being called because I put an exit() at the beginning and the site ran just fine.

Here is what I have in my config XML file. This is placed inside global -> resources path:

```<code><nie_setup>
    <setup>
        <module>Nie_Nie</module>
    </setup>
    <connection>
        <use>core_setup</use>
    </connection>
</nie_setup>
</code>```

My install script is as follows:

```<code>$installer = $this;
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();

$setup->addAttribute('customer', 'nie_admin', array(
    'input'                 => 'text',
    'type'                  => 'text',
    'backend'               => '',
    'visible'               => 0,
    'required'          => 0,
    'user_defined'  => 1,
));

$installer->endSetup();
</code>```

Is there something obvious I am missing here that would be the reason the script will not run?

答:
Work your way through this article to make sure you don't have any misunderstanding of what the setup resources do, how they work, and how you can troubleshoot them.

Once you've done that, from everything you've said on this question thread it sounds like you're getting your resource "installed", but that your install script never runs. My guess is that the version number you used in

```<code>//0.0.1 is your version number
mysql4-install-0.0.1.php
</code>```

didn't match up with the version of your module

```<code><modules>
    <Nie_Nie>
        <version>?.?.?</version>
    </Nie_Nie>
</modules>
</code>```

Those should match for the script to run.  I think Magento is smart enough to run previous versions if it finds them, but the code in the setup resources is the kind that's hard to follow, so I always make sure they match.

Regardless, here's how you can see which file(s) magento is trying to run when it runs your setup resource.  Delete any entries from core_resource related to your module.  Clear your cache.  Then find the following locations in the setup class

app/code/core/Mage/Core/Model/Resource/Setup.php:

```<code>protected function _modifyResourceDb($actionType, $fromVersion, $toVersion)
{
    ...

    $sqlFilesDir = Mage::getModuleDir('sql', $modName).DS.$this->_resourceName;

    if (!is_dir($sqlFilesDir) || !is_readable($sqlFilesDir)) {
        return false;
    }

    ...

    $sqlDir->close();

    if (empty($arrAvailableFiles)) {
        return false;
    }

    ...

    $arrModifyFiles = $this->_getModifySqlFiles($actionType, $fromVersion, $toVersion, $arrAvailableFiles);
    if (empty($arrModifyFiles)) {
        return false;
    }
</code>```

and then modify them to add some temporary debugging exceptions

```<code>    if (!is_dir($sqlFilesDir) || !is_readable($sqlFilesDir)) {
        throw new Exception("$sqlFilesDir not found");
        return false;
    }

    ...

    if (empty($arrAvailableFiles)) {
        throw new Exception("No files found to run");
        return false;
    }

    ...

    $arrModifyFiles = $this->_getModifySqlFiles($actionType, $fromVersion, $toVersion, $arrAvailableFiles);
    if (empty($arrModifyFiles)) {
        throw new Exception("No valid upgrade files found to run for ");
        return false;
    }

    throw new Exception("If you're getting here, we have a file.  Remove your exceptions here and place one in your installer to make sure it's the one you think it is.");
</code>```

Reload the page and you'll get exception text complaining about whatever Magento can't find.  That should be enough to help you track down which installer script Magento is trying to run, but failing to find. Just remember to delete your module's row in core_resource and to clear your cache. (Magento caches which modules need to check for an install/upgrade)

If that doesn't work, start digging into the logic of applyAllDataUpdates and figure out why the class isn't including  your installer file.

Body:
I am trying to create an install script for my extension and for some reason it will not the install script. The extension will show up in the core_resource table, but the attributes I am trying to create will not create.

I am pretty sure that the script is not even being called because I put an exit() at the beginning and the site ran just fine.

Here is what I have in my config XML file. This is placed inside global -> resources path:

<nie_setup>
    <setup>
        <module>Nie_Nie</module>
    </setup>
    <connection>
        <use>core_setup</use>
    </connection>
</nie_setup>

My install script is as follows:

$installer = $this;
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();

$setup->addAttribute('customer', 'nie_admin', array(
    'input'                 => 'text',
    'type'                  => 'text',
    'backend'               => '',
    'visible'               => 0,
    'required'          => 0,
    'user_defined'  => 1,
));

$installer->endSetup();

Is there something obvious I am missing here that would be the reason the script will not run?

Body:
Work your way through this article to make sure you don't have any misunderstanding of what the setup resources do, how they work, and how you can troubleshoot them.

Once you've done that, from everything you've said on this question thread it sounds like you're getting your resource "installed", but that your install script never runs. My guess is that the version number you used in

//0.0.1 is your version number
mysql4-install-0.0.1.php

didn't match up with the version of your module

<modules>
    <Nie_Nie>
        <version>?.?.?</version>
    </Nie_Nie>
</modules>

Those should match for the script to run.  I think Magento is smart enough to run previous versions if it finds them, but the code in the setup resources is the kind that's hard to follow, so I always make sure they match.

Regardless, here's how you can see which file(s) magento is trying to run when it runs your setup resource.  Delete any entries from core_resource related to your module.  Clear your cache.  Then find the following locations in the setup class

app/code/core/Mage/Core/Model/Resource/Setup.php:

protected function _modifyResourceDb($actionType, $fromVersion, $toVersion)
{
    ...

    $sqlFilesDir = Mage::getModuleDir('sql', $modName).DS.$this->_resourceName;

    if (!is_dir($sqlFilesDir) || !is_readable($sqlFilesDir)) {
        return false;
    }

    ...

    $sqlDir->close();

    if (empty($arrAvailableFiles)) {
        return false;
    }

    ...

    $arrModifyFiles = $this->_getModifySqlFiles($actionType, $fromVersion, $toVersion, $arrAvailableFiles);
    if (empty($arrModifyFiles)) {
        return false;
    }

and then modify them to add some temporary debugging exceptions

    if (!is_dir($sqlFilesDir) || !is_readable($sqlFilesDir)) {
        throw new Exception("$sqlFilesDir not found");
        return false;
    }

    ...

    if (empty($arrAvailableFiles)) {
        throw new Exception("No files found to run");
        return false;
    }

    ...

    $arrModifyFiles = $this->_getModifySqlFiles($actionType, $fromVersion, $toVersion, $arrAvailableFiles);
    if (empty($arrModifyFiles)) {
        throw new Exception("No valid upgrade files found to run for ");
        return false;
    }

    throw new Exception("If you're getting here, we have a file.  Remove your exceptions here and place one in your installer to make sure it's the one you think it is.");

Reload the page and you'll get exception text complaining about whatever Magento can't find.  That should be enough to help you track down which installer script Magento is trying to run, but failing to find. Just remember to delete your module's row in core_resource and to clear your cache. (Magento caches which modules need to check for an install/upgrade)

If that doesn't work, start digging into the logic of applyAllDataUpdates and figure out why the class isn't including  your installer file.