问:
Employee Evaluation Scoring Form
I have an Employee Evaluation Program (C# WinForm) in which managers should see their employees and score them based on some criteria. A simplified database diagram showed in Figure1.

 enter image description here

Tables Definitions:

Prs: Personnel (Employees)

Job: Job of personnel

Post: A Joining table for Prs and Job (since they have many-to-many relationship)

SubCrt: Criteria for evaluating employees

Scoring: Table in which employees’ scores should be saved

Necessary Descriptions:

-   Evaluation takes place every 3 months (called a Season)

-   Criteria for every job is different from others

-   Every employee may have more than one post in a season (because of job change). So we have to handle its results

And WinForm showed in Figure 2.

Scenario:

-   Manager selects a job

-   DataGridView will be filled based on selected job of ComboBox like showed in Figure 3.

Now manager can type every employees’ scores related to every criteria

My major problem is how to implement such a table in DataGridView that can be used for data entry (inserting, updating, deleting scores)?

Your extra ideas and suggestions about DB, it’s relationships, C# Form and … will be kindly appreciated.

Regards

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Scoring_Form
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        DataClasses1DataContext db = new DataClasses1DataContext();
        public int rows(int JobId)
        {
            var row = from crt in db.SubCrts
                      join job in db.Jobs
                      on crt.JobId equals job.JobId
                      where job.JobId == JobId
                      select crt.JobId;
            return row.Count();

        }
        public int columns(int JobId)
        {
            var Col = from prs in db.Prs
                      join post in db.Posts
                      on prs.PrsId equals post.PrsId
                      join job in db.Jobs
                      on post.JobId equals job.JobId
                      where job.JobId == JobId
                      select prs.PrsId;
            return Col.Count();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.DataSource = db.Jobs.ToList();
            comboBox1.DisplayMember = "JobTitle";
            comboBox1.ValueMember = "JobId";

            //===================================================
            string[] PrsID = new string[columns(Convert.ToInt32(comboBox1.SelectedValue)) - 1];
            string[] PrsName = new string[columns(Convert.ToInt32(comboBox1.SelectedValue)) - 1];
            string[] CrtID = new string[rows(Convert.ToInt32(comboBox1.SelectedValue)) - 1];
            string[] CrtName = new string[rows(Convert.ToInt32(comboBox1.SelectedValue)) - 1];
            string[,] tbl = new string[rows(Convert.ToInt32(comboBox1.SelectedValue))+2,
                                       columns(Convert.ToInt32(comboBox1.SelectedValue))+2];

            for (int i = 0; i < columns(Convert.ToInt32(comboBox1.SelectedValue)) - 1; i++)
            {
                var a = from prs in db.Prs
                        join post in db.Posts
                        on prs.PrsId equals post.PrsId
                        join job in db.Jobs
                        on post.JobId equals job.JobId
                        select prs.PrsId;
                PrsID[i] = a.ElementAt(i).ToString();
                var b = from prs in db.Prs
                        select (prs.FName + ' ' + prs.LName).ToString();
                PrsName[i] = b.ElementAt(i);
            }
            for (int j = 0; j < rows(Convert.ToInt32(comboBox1.SelectedValue)) - 1; j++)
            {
                var c = from crt in db.SubCrts
                        join job in db.Jobs
                        on crt.JobId equals job.JobId
                        select crt.SubCId;
                CrtID[j] = c.ElementAt(j).ToString();
                var d = from crt in db.SubCrts
                        select crt.Title;
                CrtName[j] = d.ElementAt(j);
            }
            tbl[0, 0] = ""; tbl[0, 1] = ""; tbl[1, 0] = ""; tbl[1, 1] = "";
            for (int l = 2; l < columns(Convert.ToInt32(comboBox1.SelectedValue)) + 1; l++)
            {
                for (int m = 2; m < rows(Convert.ToInt32(comboBox1.SelectedValue)) + 1; m++)
                {
                    tbl[0, l] = PrsID.ElementAt(l - 2);
                    tbl[1, l] = PrsName.ElementAt(l - 2);
                    tbl[m, 0] = CrtID.ElementAt(m - 2);
                    tbl[m, 1] = CrtName.ElementAt(m - 2);

                    var h = from sss in db.Scorings
                            where sss.PrsId == Convert.ToInt32(tbl[0, l])
                            where sss.SubCId == Convert.ToInt32(tbl[m, 0])
                            select sss.Score;
                    tbl[l, m] = h.ElementAt(0).ToString();

                }
            }
            dataGridView1.DataSource = tbl;
        }
    }
}
</code>```

After doing some search, I found a peace of code from Rob Sedgwick to convert a 1D array to a datatable

```<code>        public DataTable ConvertArrayToDatatable(MarketUnit[] arrList)
{
    DataTable dt = new DataTable();
    try
    {
        if (arrList.Count() > 0)
        {
            Type arrype = arrList[0].GetType();
            dt = new DataTable(arrype.Name);

            foreach (PropertyInfo propInfo in arrype.GetProperties())
            {
                dt.Columns.Add(new DataColumn(propInfo.Name));
            }

            foreach (object obj in arrList)
            {
                DataRow dr = dt.NewRow();

                foreach (DataColumn dc in dt.Columns)
                {
                    dr[dc.ColumnName] = obj.GetType().GetProperty(dc.ColumnName).GetValue(obj, null);
                }
                dt.Rows.Add(dr);

            }
        }

        return dt;
    }
    catch (Exception ex)
    {
        return dt;
    }

}
</code>```

Would it be possible to change it to be used for my 2D array(Tbl)?

答:
As stated in my comments… your question is very broad in scope. There are many ways to achieve the goal of creating this “Employee Evaluation” form. So I hope this answer may help at least in the construction and managing a DataTable used as a DataSource to a DataGridView. My answer demonstrates how to filter a DataTable so the DataGridView  will display only the items that meet the filtered criteria or filtered on multiple criteria… i.e.. Filter a Manager’s selections to job types. Be aware this is about as basic as it gets and uses the RowFilter property of the DataTable to achieve this filtering. This RowFilter is somewhat limited and if the data is de-coupled from the original database the CRUD functions may become your problem. So use this as an example only.

The code you posted appears to be making this much more difficult than it has to be. The DataSource for ALL the DataGridViews and ComboBoxes in the example below are DATATABLES!. The posted codes insistence to convert the data source to a string array is unnecessary.

I used a different approach than what the database pictures shows. There are four (4) DataTables: employeesDT, is used as data source to the DataGridView dgvEmployees; jobsCBDT data table is used as a data source to the ComboBox cbJobs; managersCBDT is used as a data source to the ComboBox cbManagers;  and evaluationsDT is used as a data source to the DataGridView dgvEvaluations.

My approach broke this down to three main “Object”s: an “Employee” object, which may be a manager. This “Employee” object has an extra Boolean property to indicate if the employee is a manager; a “Job” object that defines the different “Job” types; finally the “Evaluation” object. This “Evaluation” class would have the following properties. You can do this without using classes but I would recommend you consider how useful they can be. The DataTable is necessary though.

```<code>public class Evaluation {
  public int ID { get; set; }
  public Employee EmployeeEvaluated { get; set; }
  public Employee EvaluatingManager { get; set; }
  public Job JobEvaluated { get; set; }
  public DateTime StartDate { get; set; }
  public DateTime EndDate { get; set; }
  public double PersonalScore { get; set; }
  public double ImpactScore { get; set; }
  public double CommunicationScore { get; set; }
  public double DecisionMakingScore { get; set; }
  public double KnowledgeSkillsScore { get; set; }
  public double CareerDevelopmentScore { get; set; }
  public double InterpersonalScore { get; set; }
  public Evaluation() { }
}
</code>```

Below is a DataTable definition for this Evaluation class.

```<code>public static DataTable GetEvaluationsDTStructure() {
  DataTable dt = new DataTable("Evaluations");
  dt.Columns.Add("ID", typeof(int));
  dt.Columns.Add("Employee Evaluated", typeof(string));
  dt.Columns.Add("Evaluating Manager", typeof(string));
  dt.Columns.Add("Job Title", typeof(string));
  dt.Columns.Add("Start Date", typeof(DateTime));
  dt.Columns.Add("End Date", typeof(DateTime));
  dt.Columns.Add("Personal Score", typeof(double));
  dt.Columns.Add("Impact Score", typeof(double));
  dt.Columns.Add("Communication Score", typeof(double));
  dt.Columns.Add("Decision Making Score", typeof(double));
  dt.Columns.Add("Knowledge Skills Score", typeof(double));
  dt.Columns.Add("Career Development Score", typeof(double));
  dt.Columns.Add("Interpersonal Score", typeof(double));
  return dt;
}
</code>```

This “Evaluation” structure appears to be missing from the post. This is an evaluation and an employee could have more than one evaluation. Figure 3 in the posted picture appears to be backwards. I am guessing here… I would think that there would be many evaluations and some evaluations from the same employee. The picture has this set up as columns. The rows on the other hand appear to be static. Using this strategy, there would be a column for every evaluation and there could be many. I switched this such that the columns are the scores for each area and the rows are the employee “evaluations”. I hope I am not missing something here like there are different scoring criteria depending on the selected job type.

Above is the form from the code below. You may have to adjust the tables to fit your needs. The top DataGridView dgvEmployees shows all the employees.  The buttons on the right will filter this list to “Managers Only”, “All Employees” and a button to “Save” this data to a file. Here you would update your database if needed.

Below that is the DataGridView dgvEvaluations that holds all the current evaluations. If there are many evaluations, you may want to filter the rows or search for a particular employee, manager or job. This is what the combo boxes do below the datagridview. There is an extra blank item added in the combo boxes to clear any filter or the user can click the “Clear Filter” button. Here you can filter the evaluations by a selected employee and by evaluating manager and job.

You can make changes to the current items and add new evaluations. Lastly, a button is on the right to save any changes. Again, I am simply writing the data table to a file. You would update your database.

NOTE Adding New Evaluations.

When users are allowed to input data, it is imperative that you check for valid data. Example, the DataTable columns for the scores are set as a type of double. If the user types in characters, the code will crash unless you address this issue. The same would apply to the date columns. To address this in a simple way (not the best) , the DataError event is wired up to capture when this happens, then simply display a message to the user that the input is invalid and cancel any changes in the grid. This prevents bad input from the users when typing in scores or dates.

The other user input problem is when the user types in the employee names for a new evaluation. If the user does not type the name exactly, then there will be problems later. If there is a new employee then that employee needs to be added to the employee’s database first. Same thing would apply to the “Job Title”, if the user types something that in not an existing job, then you will have errors later. Since these are employees and jobs… perhaps, a ComboBox cell here may make this easier for the user to simply select the employee and also the evaluating manager and job. This way, you can avoid the user typing incorrect info. You can look up DataGridViewComboBoxColumn for these “employee” columns. There is commented code at the end of this post for this combo box cell. For cells with dates there is a good article on how to make a DateTimePicker column that works well, is user friendly and almost guarantees the user enters a valid date. How to: Host Controls in Windows Forms DataGridView Cells

With that said, there are many problems with the code below, example, if you add a new employee into the top grid and then save the data… the combo boxes below will NOT be updated. This is something you will have to address. Another consideration is what to do if the user wants to add a new evaluation. Using the DataGridView to allow the user to do this is fine and doable, however you must implement several events and checks THROUGH the DataGridView. IMHO it may be easier to simply add a button to “add” a new evaluation and use this button to open an Evaluation form where the user could add the scores, change the employee etc… then save the evaluation. This may make things easier and would be user friendly.

I hope this helps, if I am totally missing something… please let me know and I will remove the answer. Good Luck

DataTable Definitions – evaluationsDT defined above

jobsCBDT

```<code>private static DataTable GetJobsDTStruc() {
  DataTable dt = new DataTable();
  dt.Columns.Add("ID", typeof(int));
  dt.Columns.Add("Job Title", typeof(string));
  dt.Columns.Add("Job Description", typeof(string));
  return dt;
}
</code>```

employeeDT managers dataTable is the same structure

```<code>private static DataTable GetEmplyeeDTSructure() {
  DataTable dt = new DataTable();
  DataColumn dc = new DataColumn("ID", typeof(int));
  dt.Columns.Add(dc);
  dc = new DataColumn("Manager", typeof(bool));
  dt.Columns.Add(dc);
  dc = new DataColumn("First Name", typeof(string));
  dt.Columns.Add(dc);
  dc = new DataColumn("Last Name", typeof(string));
  dt.Columns.Add(dc);
  dt.Columns.Add("Job Title", typeof(string));
  dt.Columns.Add("Full Name", typeof(string));
  return dt;
}
</code>```

Main form methods

```<code>public partial class Form1 : Form {

  DataTable employeesDT;
  DataTable evaluationsDT;
  DataTable managersCBDT;
  DataTable jobsCBDT;
  DataTable employeesCBDT;

  public Form1() {
    InitializeComponent();
  }

  private void Form1_Load(object sender, EventArgs e) {
    DisableComboEvents();                        // <-- turn off events while loading
    SetDataTables();                             // <-- get all the data tables
    dgvEmployees.DataSource = employeesDT;
    dgvEvaluations.DataSource = evaluationsDT;
    employeesCBDT = employeesDT.Copy();          // <-- copy of data - you could use the same source though
    SetEmployeeDGVColumns();                     // <-- Style the columns for the employee datagridview
    SetEvaluationsDGVColumns();                  // <-- Style the columns for the evaluations datagridview
    SetEmployeeComboBox();                       // <-- set up the employee combo box for filtering
    SetManagerComboBox();                        // <-- set up the managers combo box for filtering
    SetJobsComboBox();                           // <-- set up the jobs combo box for filtering
    labelEmployeeList.Text = "All Employees";
    EnableComboEvents();                         // <-- turn events back on

  }

  private void DisableComboEvents() {
    this.cbManagers.SelectedIndexChanged -= new System.EventHandler(this.cbManagers_SelectedIndexChanged);
    this.cbJobs.SelectedIndexChanged -= new System.EventHandler(this.cbJobs_SelectedIndexChanged);
    this.cbEmployees.SelectedIndexChanged -= new System.EventHandler(this.cbEmployees_SelectedIndexChanged);
  }
  private void EnableComboEvents() {
    this.cbManagers.SelectedIndexChanged += new System.EventHandler(this.cbManagers_SelectedIndexChanged);
    this.cbJobs.SelectedIndexChanged += new System.EventHandler(this.cbJobs_SelectedIndexChanged);
    this.cbEmployees.SelectedIndexChanged += new System.EventHandler(this.cbEmployees_SelectedIndexChanged);
  }

  // you will need to adjust the code below to your requirements
  private void SetDataTables() {
    employeesDT = Utilities.GetEmployeesDataTable(); // <-- table of employees
    evaluationsDT = Utilities.GetEvaluationsDT();    // <-- table of evaluations
    managersCBDT = Utilities.GetManagersDT();        // <-- table of managers (subset of employees)
    jobsCBDT = Utilities.GetJobsDT();                // <-- table of job types
  }

  private void SetEvaluationsDGVColumns() {
    dgvEvaluations.RowHeadersWidth = 20;
    dgvEvaluations.Columns["ID"].Width = 40;
    dgvEvaluations.Columns["Employee Evaluated"].Width = 140;
    dgvEvaluations.Columns["Evaluating Manager"].Width = 160;
    dgvEvaluations.Columns["Start Date"].Width = 65;
    dgvEvaluations.Columns["End Date"].Width = 65;
    SetScoreColumn("Personal Score", 60);
    SetScoreColumn("Impact Score", 60);
    SetScoreColumn("Communication Score", 85);
    SetScoreColumn("Decision Making Score", 60);
    SetScoreColumn("Knowledge Skills Score", 70);
    SetScoreColumn("Career Development Score", 80);
    SetScoreColumn("Interpersonal Score", 80);
  }

  private void SetScoreColumn(string colName, int colWidth) {
    dgvEvaluations.Columns[colName].Width = colWidth;
    dgvEvaluations.Columns[colName].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
    dgvEvaluations.Columns[colName].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
  }

  private void SetEmployeeDGVColumns() {
    dgvEmployees.Columns["ID"].Width = 40;
    dgvEmployees.Columns["ID"].ReadOnly = true;
    dgvEmployees.Columns["Manager"].Width = 60;
    dgvEmployees.Columns["First Name"].Width = 80;
    dgvEmployees.Columns["Last Name"].Width = 150;
    dgvEmployees.Columns["Full Name"].Width = 150;
    dgvEmployees.Columns["Full Name"].ReadOnly = true;
    dgvEmployees.Columns["Job Title"].Width = 120;
  }

  private void SetEmployeeComboBox() {
    DataRow dr = employeesCBDT.NewRow();
    employeesCBDT.Rows.InsertAt(dr, 0);
    cbEmployees.DataSource = employeesCBDT;
    cbEmployees.DisplayMember = "Full Name";
    cbEmployees.SelectedIndex = -1;
  }
  private void SetManagerComboBox() {
    DataRow dr = managersCBDT.NewRow();
    managersCBDT.Rows.InsertAt(dr, 0);
    cbManagers.DataSource = managersCBDT;
    cbManagers.DisplayMember = "Full Name";
    cbManagers.SelectedIndex = -1;
  }
  private void SetJobsComboBox() {
    DataRow dr = jobsCBDT.NewRow();
    jobsCBDT.Rows.InsertAt(dr, 0);
    cbJobs.DataSource = jobsCBDT;
    cbJobs.DisplayMember = "Job Title";
    cbJobs.SelectedIndex = -1;
  }

  private void dgvEvaluations_DataError(object sender, DataGridViewDataErrorEventArgs e) {
    if (e.ColumnIndex > 5 && e.ColumnIndex < 13) {
      MessageBox.Show("Invalid input for score!");
    } else {
      if (e.ColumnIndex > 3 && e.ColumnIndex < 6) {
        MessageBox.Show("Invalid intput for date!");
      }
    }
    dgvEvaluations.CancelEdit();
  }

  private void cbEmployees_SelectedIndexChanged(object sender, EventArgs e) {
    evaluationsDT.DefaultView.RowFilter = GetFilterString();
  }

  private void cbManagers_SelectedIndexChanged(object sender, EventArgs e) {
    evaluationsDT.DefaultView.RowFilter = GetFilterString();
  }

  private void cbJobs_SelectedIndexChanged(object sender, EventArgs e) {
    evaluationsDT.DefaultView.RowFilter = GetFilterString();
  }

  private string GetFilterString() {
    string targetManager = cbManagers.Text.Trim();
    string targetJob = cbJobs.Text.Trim();
    string targetEmployee = cbEmployees.Text.Trim();

    if (targetManager != "") {
      if (targetEmployee != "") {
        if (targetJob != "") {
          return string.Format("[Evaluating Manager] = '{0}' AND [Employee Evaluated] = '{1}' AND [Job Title] = '{2}'", targetManager, targetEmployee, targetJob);
        } else {
          return string.Format("[Evaluating Manager] = '{0}' AND [Employee Evaluated] = '{1}'", targetManager, targetEmployee);
        }
      } else {
        if (targetJob != "") {
          return string.Format("[Evaluating Manager] = '{0}' AND [Job Title] = '{1}'", targetManager, targetJob);
        } else {
          return string.Format("[Evaluating Manager] = '{0}'", targetManager);
        }
      }
    } else {
      // manager is blank
      if (targetEmployee != "") {
        if (targetJob != "") {
          return string.Format("[Employee Evaluated] = '{0}' AND [Job Title] = '{1}'", targetEmployee, targetJob);
        } else {
          return string.Format("[Employee Evaluated] = '{0}'", targetEmployee);
        }
      } else {
        if (targetJob != "") {
          return string.Format("[Job Title] = '{0}'", targetJob);
        } else {
          return "";
        }
      }
    }
  }

  private void btManagers_Click(object sender, EventArgs e) {
    employeesDT.DefaultView.RowFilter = string.Format("Manager = '{0}'", "True");
    labelEmployeeList.Text = "Managers Only";
  }

  private void btAllEmployees_Click(object sender, EventArgs e) {
    employeesDT.DefaultView.RowFilter = null;
    labelEmployeeList.Text = "All Employees";
  }

  private void btSaveEmployees_Click(object sender, EventArgs e) {
    Utilities.WriteEmployessToFile(employeesDT);    // <-- update your database
  }

  private void btSaveEvals_Click(object sender, EventArgs e) {
    Utilities.WriteEvaluationsToFile(evaluationsDT);    // <-- update your database
  }

  private void btClearEvalFilter_Click(object sender, EventArgs e) {
    cbManagers.SelectedIndex = -1;
    cbJobs.SelectedIndex = -1;
    cbEmployees.SelectedIndex = -1;
    evaluationsDT.DefaultView.RowFilter = null;
  }

  // Code to make a combo box column in the datagridView
  ////-------------------------------------------
  //public static DataGridViewComboBoxColumn GetEmployeeComboBoxColumn(DataTable employeeDT) {
  //  return GetComboBoxColumn(employeeDT, "Full Name", "Employee Evaluated");
  //}
  ////-------------------------------------------
  //public static DataGridViewComboBoxColumn GetManagerComboBoxColumn(DataTable managerDT) {
  //  return GetComboBoxColumn(managerDT, "Full Name", "Evaluating Manager");
  //}
  ////-------------------------------------------
  //public static DataGridViewComboBoxColumn GetComboBoxColumn(DataTable comboDT, string displayMember, string headerText) {
  //  DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
  //  comboCol.DataPropertyName = headerText;
  //  comboCol.HeaderText = headerText;
  //  DataTable comboData = comboDT.Copy();
  //  DataRow dr = comboData.NewRow();
  //  comboData.Rows.InsertAt(dr, 0);
  //  comboCol.DataSource = comboData;
  //  comboCol.DisplayMember = displayMember;
  //  comboCol.ValueMember = displayMember;
  //  comboCol.FlatStyle = FlatStyle.Flat;
  //  return comboCol;
  //}
}
</code>```

Hope this helps!

Title: Employee Evaluation Scoring Form

Body:
I have an Employee Evaluation Program (C# WinForm) in which managers should see their employees and score them based on some criteria. A simplified database diagram showed in Figure1.

 enter image description here

Tables Definitions:

Prs: Personnel (Employees)

Job: Job of personnel

Post: A Joining table for Prs and Job (since they have many-to-many relationship)

SubCrt: Criteria for evaluating employees

Scoring: Table in which employees’ scores should be saved

Necessary Descriptions:

-   Evaluation takes place every 3 months (called a Season)

-   Criteria for every job is different from others

-   Every employee may have more than one post in a season (because of job change). So we have to handle its results

And WinForm showed in Figure 2.

Scenario:

-   Manager selects a job

-   DataGridView will be filled based on selected job of ComboBox like showed in Figure 3.

Now manager can type every employees’ scores related to every criteria

My major problem is how to implement such a table in DataGridView that can be used for data entry (inserting, updating, deleting scores)?

Your extra ideas and suggestions about DB, it’s relationships, C# Form and … will be kindly appreciated.

Regards

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Scoring_Form
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        DataClasses1DataContext db = new DataClasses1DataContext();
        public int rows(int JobId)
        {
            var row = from crt in db.SubCrts
                      join job in db.Jobs
                      on crt.JobId equals job.JobId
                      where job.JobId == JobId
                      select crt.JobId;
            return row.Count();

        }
        public int columns(int JobId)
        {
            var Col = from prs in db.Prs
                      join post in db.Posts
                      on prs.PrsId equals post.PrsId
                      join job in db.Jobs
                      on post.JobId equals job.JobId
                      where job.JobId == JobId
                      select prs.PrsId;
            return Col.Count();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.DataSource = db.Jobs.ToList();
            comboBox1.DisplayMember = "JobTitle";
            comboBox1.ValueMember = "JobId";

            //===================================================
            string[] PrsID = new string[columns(Convert.ToInt32(comboBox1.SelectedValue)) - 1];
            string[] PrsName = new string[columns(Convert.ToInt32(comboBox1.SelectedValue)) - 1];
            string[] CrtID = new string[rows(Convert.ToInt32(comboBox1.SelectedValue)) - 1];
            string[] CrtName = new string[rows(Convert.ToInt32(comboBox1.SelectedValue)) - 1];
            string[,] tbl = new string[rows(Convert.ToInt32(comboBox1.SelectedValue))+2,
                                       columns(Convert.ToInt32(comboBox1.SelectedValue))+2];

            for (int i = 0; i < columns(Convert.ToInt32(comboBox1.SelectedValue)) - 1; i++)
            {
                var a = from prs in db.Prs
                        join post in db.Posts
                        on prs.PrsId equals post.PrsId
                        join job in db.Jobs
                        on post.JobId equals job.JobId
                        select prs.PrsId;
                PrsID[i] = a.ElementAt(i).ToString();
                var b = from prs in db.Prs
                        select (prs.FName + ' ' + prs.LName).ToString();
                PrsName[i] = b.ElementAt(i);
            }
            for (int j = 0; j < rows(Convert.ToInt32(comboBox1.SelectedValue)) - 1; j++)
            {
                var c = from crt in db.SubCrts
                        join job in db.Jobs
                        on crt.JobId equals job.JobId
                        select crt.SubCId;
                CrtID[j] = c.ElementAt(j).ToString();
                var d = from crt in db.SubCrts
                        select crt.Title;
                CrtName[j] = d.ElementAt(j);
            }
            tbl[0, 0] = ""; tbl[0, 1] = ""; tbl[1, 0] = ""; tbl[1, 1] = "";
            for (int l = 2; l < columns(Convert.ToInt32(comboBox1.SelectedValue)) + 1; l++)
            {
                for (int m = 2; m < rows(Convert.ToInt32(comboBox1.SelectedValue)) + 1; m++)
                {
                    tbl[0, l] = PrsID.ElementAt(l - 2);
                    tbl[1, l] = PrsName.ElementAt(l - 2);
                    tbl[m, 0] = CrtID.ElementAt(m - 2);
                    tbl[m, 1] = CrtName.ElementAt(m - 2);

                    var h = from sss in db.Scorings
                            where sss.PrsId == Convert.ToInt32(tbl[0, l])
                            where sss.SubCId == Convert.ToInt32(tbl[m, 0])
                            select sss.Score;
                    tbl[l, m] = h.ElementAt(0).ToString();

                }
            }
            dataGridView1.DataSource = tbl;
        }
    }
}

After doing some search, I found a peace of code from Rob Sedgwick to convert a 1D array to a datatable

        public DataTable ConvertArrayToDatatable(MarketUnit[] arrList)
{
    DataTable dt = new DataTable();
    try
    {
        if (arrList.Count() > 0)
        {
            Type arrype = arrList[0].GetType();
            dt = new DataTable(arrype.Name);

            foreach (PropertyInfo propInfo in arrype.GetProperties())
            {
                dt.Columns.Add(new DataColumn(propInfo.Name));
            }

            foreach (object obj in arrList)
            {
                DataRow dr = dt.NewRow();

                foreach (DataColumn dc in dt.Columns)
                {
                    dr[dc.ColumnName] = obj.GetType().GetProperty(dc.ColumnName).GetValue(obj, null);
                }
                dt.Rows.Add(dr);

            }
        }

        return dt;
    }
    catch (Exception ex)
    {
        return dt;
    }

}

Would it be possible to change it to be used for my 2D array(Tbl)?

Body:
As stated in my comments… your question is very broad in scope. There are many ways to achieve the goal of creating this “Employee Evaluation” form. So I hope this answer may help at least in the construction and managing a DataTable used as a DataSource to a DataGridView. My answer demonstrates how to filter a DataTable so the DataGridView  will display only the items that meet the filtered criteria or filtered on multiple criteria… i.e.. Filter a Manager’s selections to job types. Be aware this is about as basic as it gets and uses the RowFilter property of the DataTable to achieve this filtering. This RowFilter is somewhat limited and if the data is de-coupled from the original database the CRUD functions may become your problem. So use this as an example only.

The code you posted appears to be making this much more difficult than it has to be. The DataSource for ALL the DataGridViews and ComboBoxes in the example below are DATATABLES!. The posted codes insistence to convert the data source to a string array is unnecessary.

I used a different approach than what the database pictures shows. There are four (4) DataTables: employeesDT, is used as data source to the DataGridView dgvEmployees; jobsCBDT data table is used as a data source to the ComboBox cbJobs; managersCBDT is used as a data source to the ComboBox cbManagers;  and evaluationsDT is used as a data source to the DataGridView dgvEvaluations.

My approach broke this down to three main “Object”s: an “Employee” object, which may be a manager. This “Employee” object has an extra Boolean property to indicate if the employee is a manager; a “Job” object that defines the different “Job” types; finally the “Evaluation” object. This “Evaluation” class would have the following properties. You can do this without using classes but I would recommend you consider how useful they can be. The DataTable is necessary though.

public class Evaluation {
  public int ID { get; set; }
  public Employee EmployeeEvaluated { get; set; }
  public Employee EvaluatingManager { get; set; }
  public Job JobEvaluated { get; set; }
  public DateTime StartDate { get; set; }
  public DateTime EndDate { get; set; }
  public double PersonalScore { get; set; }
  public double ImpactScore { get; set; }
  public double CommunicationScore { get; set; }
  public double DecisionMakingScore { get; set; }
  public double KnowledgeSkillsScore { get; set; }
  public double CareerDevelopmentScore { get; set; }
  public double InterpersonalScore { get; set; }
  public Evaluation() { }
}

Below is a DataTable definition for this Evaluation class.

public static DataTable GetEvaluationsDTStructure() {
  DataTable dt = new DataTable("Evaluations");
  dt.Columns.Add("ID", typeof(int));
  dt.Columns.Add("Employee Evaluated", typeof(string));
  dt.Columns.Add("Evaluating Manager", typeof(string));
  dt.Columns.Add("Job Title", typeof(string));
  dt.Columns.Add("Start Date", typeof(DateTime));
  dt.Columns.Add("End Date", typeof(DateTime));
  dt.Columns.Add("Personal Score", typeof(double));
  dt.Columns.Add("Impact Score", typeof(double));
  dt.Columns.Add("Communication Score", typeof(double));
  dt.Columns.Add("Decision Making Score", typeof(double));
  dt.Columns.Add("Knowledge Skills Score", typeof(double));
  dt.Columns.Add("Career Development Score", typeof(double));
  dt.Columns.Add("Interpersonal Score", typeof(double));
  return dt;
}

This “Evaluation” structure appears to be missing from the post. This is an evaluation and an employee could have more than one evaluation. Figure 3 in the posted picture appears to be backwards. I am guessing here… I would think that there would be many evaluations and some evaluations from the same employee. The picture has this set up as columns. The rows on the other hand appear to be static. Using this strategy, there would be a column for every evaluation and there could be many. I switched this such that the columns are the scores for each area and the rows are the employee “evaluations”. I hope I am not missing something here like there are different scoring criteria depending on the selected job type.

Above is the form from the code below. You may have to adjust the tables to fit your needs. The top DataGridView dgvEmployees shows all the employees.  The buttons on the right will filter this list to “Managers Only”, “All Employees” and a button to “Save” this data to a file. Here you would update your database if needed.

Below that is the DataGridView dgvEvaluations that holds all the current evaluations. If there are many evaluations, you may want to filter the rows or search for a particular employee, manager or job. This is what the combo boxes do below the datagridview. There is an extra blank item added in the combo boxes to clear any filter or the user can click the “Clear Filter” button. Here you can filter the evaluations by a selected employee and by evaluating manager and job.

You can make changes to the current items and add new evaluations. Lastly, a button is on the right to save any changes. Again, I am simply writing the data table to a file. You would update your database.

NOTE Adding New Evaluations.

When users are allowed to input data, it is imperative that you check for valid data. Example, the DataTable columns for the scores are set as a type of double. If the user types in characters, the code will crash unless you address this issue. The same would apply to the date columns. To address this in a simple way (not the best) , the DataError event is wired up to capture when this happens, then simply display a message to the user that the input is invalid and cancel any changes in the grid. This prevents bad input from the users when typing in scores or dates.

The other user input problem is when the user types in the employee names for a new evaluation. If the user does not type the name exactly, then there will be problems later. If there is a new employee then that employee needs to be added to the employee’s database first. Same thing would apply to the “Job Title”, if the user types something that in not an existing job, then you will have errors later. Since these are employees and jobs… perhaps, a ComboBox cell here may make this easier for the user to simply select the employee and also the evaluating manager and job. This way, you can avoid the user typing incorrect info. You can look up DataGridViewComboBoxColumn for these “employee” columns. There is commented code at the end of this post for this combo box cell. For cells with dates there is a good article on how to make a DateTimePicker column that works well, is user friendly and almost guarantees the user enters a valid date. How to: Host Controls in Windows Forms DataGridView Cells

With that said, there are many problems with the code below, example, if you add a new employee into the top grid and then save the data… the combo boxes below will NOT be updated. This is something you will have to address. Another consideration is what to do if the user wants to add a new evaluation. Using the DataGridView to allow the user to do this is fine and doable, however you must implement several events and checks THROUGH the DataGridView. IMHO it may be easier to simply add a button to “add” a new evaluation and use this button to open an Evaluation form where the user could add the scores, change the employee etc… then save the evaluation. This may make things easier and would be user friendly.

I hope this helps, if I am totally missing something… please let me know and I will remove the answer. Good Luck

DataTable Definitions – evaluationsDT defined above

jobsCBDT

private static DataTable GetJobsDTStruc() {
  DataTable dt = new DataTable();
  dt.Columns.Add("ID", typeof(int));
  dt.Columns.Add("Job Title", typeof(string));
  dt.Columns.Add("Job Description", typeof(string));
  return dt;
}

employeeDT managers dataTable is the same structure

private static DataTable GetEmplyeeDTSructure() {
  DataTable dt = new DataTable();
  DataColumn dc = new DataColumn("ID", typeof(int));
  dt.Columns.Add(dc);
  dc = new DataColumn("Manager", typeof(bool));
  dt.Columns.Add(dc);
  dc = new DataColumn("First Name", typeof(string));
  dt.Columns.Add(dc);
  dc = new DataColumn("Last Name", typeof(string));
  dt.Columns.Add(dc);
  dt.Columns.Add("Job Title", typeof(string));
  dt.Columns.Add("Full Name", typeof(string));
  return dt;
}

Main form methods

public partial class Form1 : Form {

  DataTable employeesDT;
  DataTable evaluationsDT;
  DataTable managersCBDT;
  DataTable jobsCBDT;
  DataTable employeesCBDT;

  public Form1() {
    InitializeComponent();
  }

  private void Form1_Load(object sender, EventArgs e) {
    DisableComboEvents();                        // <-- turn off events while loading
    SetDataTables();                             // <-- get all the data tables
    dgvEmployees.DataSource = employeesDT;
    dgvEvaluations.DataSource = evaluationsDT;
    employeesCBDT = employeesDT.Copy();          // <-- copy of data - you could use the same source though
    SetEmployeeDGVColumns();                     // <-- Style the columns for the employee datagridview
    SetEvaluationsDGVColumns();                  // <-- Style the columns for the evaluations datagridview
    SetEmployeeComboBox();                       // <-- set up the employee combo box for filtering
    SetManagerComboBox();                        // <-- set up the managers combo box for filtering
    SetJobsComboBox();                           // <-- set up the jobs combo box for filtering
    labelEmployeeList.Text = "All Employees";
    EnableComboEvents();                         // <-- turn events back on

  }

  private void DisableComboEvents() {
    this.cbManagers.SelectedIndexChanged -= new System.EventHandler(this.cbManagers_SelectedIndexChanged);
    this.cbJobs.SelectedIndexChanged -= new System.EventHandler(this.cbJobs_SelectedIndexChanged);
    this.cbEmployees.SelectedIndexChanged -= new System.EventHandler(this.cbEmployees_SelectedIndexChanged);
  }
  private void EnableComboEvents() {
    this.cbManagers.SelectedIndexChanged += new System.EventHandler(this.cbManagers_SelectedIndexChanged);
    this.cbJobs.SelectedIndexChanged += new System.EventHandler(this.cbJobs_SelectedIndexChanged);
    this.cbEmployees.SelectedIndexChanged += new System.EventHandler(this.cbEmployees_SelectedIndexChanged);
  }

  // you will need to adjust the code below to your requirements
  private void SetDataTables() {
    employeesDT = Utilities.GetEmployeesDataTable(); // <-- table of employees
    evaluationsDT = Utilities.GetEvaluationsDT();    // <-- table of evaluations
    managersCBDT = Utilities.GetManagersDT();        // <-- table of managers (subset of employees)
    jobsCBDT = Utilities.GetJobsDT();                // <-- table of job types
  }

  private void SetEvaluationsDGVColumns() {
    dgvEvaluations.RowHeadersWidth = 20;
    dgvEvaluations.Columns["ID"].Width = 40;
    dgvEvaluations.Columns["Employee Evaluated"].Width = 140;
    dgvEvaluations.Columns["Evaluating Manager"].Width = 160;
    dgvEvaluations.Columns["Start Date"].Width = 65;
    dgvEvaluations.Columns["End Date"].Width = 65;
    SetScoreColumn("Personal Score", 60);
    SetScoreColumn("Impact Score", 60);
    SetScoreColumn("Communication Score", 85);
    SetScoreColumn("Decision Making Score", 60);
    SetScoreColumn("Knowledge Skills Score", 70);
    SetScoreColumn("Career Development Score", 80);
    SetScoreColumn("Interpersonal Score", 80);
  }

  private void SetScoreColumn(string colName, int colWidth) {
    dgvEvaluations.Columns[colName].Width = colWidth;
    dgvEvaluations.Columns[colName].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
    dgvEvaluations.Columns[colName].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
  }

  private void SetEmployeeDGVColumns() {
    dgvEmployees.Columns["ID"].Width = 40;
    dgvEmployees.Columns["ID"].ReadOnly = true;
    dgvEmployees.Columns["Manager"].Width = 60;
    dgvEmployees.Columns["First Name"].Width = 80;
    dgvEmployees.Columns["Last Name"].Width = 150;
    dgvEmployees.Columns["Full Name"].Width = 150;
    dgvEmployees.Columns["Full Name"].ReadOnly = true;
    dgvEmployees.Columns["Job Title"].Width = 120;
  }

  private void SetEmployeeComboBox() {
    DataRow dr = employeesCBDT.NewRow();
    employeesCBDT.Rows.InsertAt(dr, 0);
    cbEmployees.DataSource = employeesCBDT;
    cbEmployees.DisplayMember = "Full Name";
    cbEmployees.SelectedIndex = -1;
  }
  private void SetManagerComboBox() {
    DataRow dr = managersCBDT.NewRow();
    managersCBDT.Rows.InsertAt(dr, 0);
    cbManagers.DataSource = managersCBDT;
    cbManagers.DisplayMember = "Full Name";
    cbManagers.SelectedIndex = -1;
  }
  private void SetJobsComboBox() {
    DataRow dr = jobsCBDT.NewRow();
    jobsCBDT.Rows.InsertAt(dr, 0);
    cbJobs.DataSource = jobsCBDT;
    cbJobs.DisplayMember = "Job Title";
    cbJobs.SelectedIndex = -1;
  }

  private void dgvEvaluations_DataError(object sender, DataGridViewDataErrorEventArgs e) {
    if (e.ColumnIndex > 5 && e.ColumnIndex < 13) {
      MessageBox.Show("Invalid input for score!");
    } else {
      if (e.ColumnIndex > 3 && e.ColumnIndex < 6) {
        MessageBox.Show("Invalid intput for date!");
      }
    }
    dgvEvaluations.CancelEdit();
  }

  private void cbEmployees_SelectedIndexChanged(object sender, EventArgs e) {
    evaluationsDT.DefaultView.RowFilter = GetFilterString();
  }

  private void cbManagers_SelectedIndexChanged(object sender, EventArgs e) {
    evaluationsDT.DefaultView.RowFilter = GetFilterString();
  }

  private void cbJobs_SelectedIndexChanged(object sender, EventArgs e) {
    evaluationsDT.DefaultView.RowFilter = GetFilterString();
  }

  private string GetFilterString() {
    string targetManager = cbManagers.Text.Trim();
    string targetJob = cbJobs.Text.Trim();
    string targetEmployee = cbEmployees.Text.Trim();

    if (targetManager != "") {
      if (targetEmployee != "") {
        if (targetJob != "") {
          return string.Format("[Evaluating Manager] = '{0}' AND [Employee Evaluated] = '{1}' AND [Job Title] = '{2}'", targetManager, targetEmployee, targetJob);
        } else {
          return string.Format("[Evaluating Manager] = '{0}' AND [Employee Evaluated] = '{1}'", targetManager, targetEmployee);
        }
      } else {
        if (targetJob != "") {
          return string.Format("[Evaluating Manager] = '{0}' AND [Job Title] = '{1}'", targetManager, targetJob);
        } else {
          return string.Format("[Evaluating Manager] = '{0}'", targetManager);
        }
      }
    } else {
      // manager is blank
      if (targetEmployee != "") {
        if (targetJob != "") {
          return string.Format("[Employee Evaluated] = '{0}' AND [Job Title] = '{1}'", targetEmployee, targetJob);
        } else {
          return string.Format("[Employee Evaluated] = '{0}'", targetEmployee);
        }
      } else {
        if (targetJob != "") {
          return string.Format("[Job Title] = '{0}'", targetJob);
        } else {
          return "";
        }
      }
    }
  }

  private void btManagers_Click(object sender, EventArgs e) {
    employeesDT.DefaultView.RowFilter = string.Format("Manager = '{0}'", "True");
    labelEmployeeList.Text = "Managers Only";
  }

  private void btAllEmployees_Click(object sender, EventArgs e) {
    employeesDT.DefaultView.RowFilter = null;
    labelEmployeeList.Text = "All Employees";
  }

  private void btSaveEmployees_Click(object sender, EventArgs e) {
    Utilities.WriteEmployessToFile(employeesDT);    // <-- update your database
  }

  private void btSaveEvals_Click(object sender, EventArgs e) {
    Utilities.WriteEvaluationsToFile(evaluationsDT);    // <-- update your database
  }

  private void btClearEvalFilter_Click(object sender, EventArgs e) {
    cbManagers.SelectedIndex = -1;
    cbJobs.SelectedIndex = -1;
    cbEmployees.SelectedIndex = -1;
    evaluationsDT.DefaultView.RowFilter = null;
  }

  // Code to make a combo box column in the datagridView
  ////-------------------------------------------
  //public static DataGridViewComboBoxColumn GetEmployeeComboBoxColumn(DataTable employeeDT) {
  //  return GetComboBoxColumn(employeeDT, "Full Name", "Employee Evaluated");
  //}
  ////-------------------------------------------
  //public static DataGridViewComboBoxColumn GetManagerComboBoxColumn(DataTable managerDT) {
  //  return GetComboBoxColumn(managerDT, "Full Name", "Evaluating Manager");
  //}
  ////-------------------------------------------
  //public static DataGridViewComboBoxColumn GetComboBoxColumn(DataTable comboDT, string displayMember, string headerText) {
  //  DataGridViewComboBoxColumn comboCol = new DataGridViewComboBoxColumn();
  //  comboCol.DataPropertyName = headerText;
  //  comboCol.HeaderText = headerText;
  //  DataTable comboData = comboDT.Copy();
  //  DataRow dr = comboData.NewRow();
  //  comboData.Rows.InsertAt(dr, 0);
  //  comboCol.DataSource = comboData;
  //  comboCol.DisplayMember = displayMember;
  //  comboCol.ValueMember = displayMember;
  //  comboCol.FlatStyle = FlatStyle.Flat;
  //  return comboCol;
  //}
}

Hope this helps!


来源: stackexchange

问:
Ionic Live Reload not working
Live Reload has stopped working.

When I save code changes, the browser automatically refreshes, but code changes are not reflected. I need to stop my CLI and run ionic serve again in order to have any code changes reflected in the browser.

```<code>Your system information:

Cordova CLI: 6.4.0
Ionic Framework Version: 2.3.0
Ionic CLI Version: 2.1.18
Ionic App Lib Version: 2.1.9
Ionic App Scripts Version: 1.1.4
ios-deploy version: Not installed
ios-sim version: Not installed
OS: macOS Sierra
Node Version: v6.9.4
Xcode version: Xcode 8.2.1 Build version 8C1002
</code>```

答:
I think your problem is with your current project.So please create a new project like below.

```<code>ionic start myfirstapp blank --v2
</code>```

After that see whether live reload is working or not.It should work now.

```<code>ionic serve
</code>```

Note: If above one is working then you can copy/ paste your previous project's custom items where you have created to this project.Hope that solution will be much quicker than try to find a solution with the old project.That is my idea.

ContentLicense: CC BY-SA 3.0

Title: Ionic Live Reload not working

Body:
Live Reload has stopped working.

When I save code changes, the browser automatically refreshes, but code changes are not reflected. I need to stop my CLI and run ionic serve again in order to have any code changes reflected in the browser.

Your system information:

Cordova CLI: 6.4.0
Ionic Framework Version: 2.3.0
Ionic CLI Version: 2.1.18
Ionic App Lib Version: 2.1.9
Ionic App Scripts Version: 1.1.4
ios-deploy version: Not installed
ios-sim version: Not installed
OS: macOS Sierra
Node Version: v6.9.4
Xcode version: Xcode 8.2.1 Build version 8C1002

Body:
I think your problem is with your current project.So please create a new project like below.

ionic start myfirstapp blank --v2

After that see whether live reload is working or not.It should work now.

ionic serve

Note: If above one is working then you can copy/ paste your previous project's custom items where you have created to this project.Hope that solution will be much quicker than try to find a solution with the old project.That is my idea.


问:
Plot of time series with gray areas in intervals that go beyond the mean
I would like to plot a time series with shaded gray areas in the intervals that go above the mean. Any ideas on how to do so? or where to start looking?

Thanks

答:
Without information, it is hard to answer, but here is a potential outcome using ggplot:

```<code>data = data.frame(x = seq(as.POSIXct("2017-03-31"), as.POSIXct("2017-04-01"), by = "1 hour"),
              y = rnorm(25, 10, 3))

mean.y = mean(data$y)

ggplot(data, aes(x, y)) +
  theme_minimal() +
  geom_rect(data = subset(data, y > mean.y), aes(ymin = -Inf, ymax = Inf, xmin = x - 30*60, xmax = x + 30*60), fill = "grey") +
  geom_line() +
  geom_hline(yintercept = mean.y, color = "red")
</code>```

Body:
Without information, it is hard to answer, but here is a potential outcome using ggplot:

data = data.frame(x = seq(as.POSIXct("2017-03-31"), as.POSIXct("2017-04-01"), by = "1 hour"),
              y = rnorm(25, 10, 3))

mean.y = mean(data$y)

ggplot(data, aes(x, y)) +
  theme_minimal() +
  geom_rect(data = subset(data, y > mean.y), aes(ymin = -Inf, ymax = Inf, xmin = x - 30*60, xmax = x + 30*60), fill = "grey") +
  geom_line() +
  geom_hline(yintercept = mean.y, color = "red")


问:
Typescript error when importing a single 3rd party javascript file in an Ionic 2 project
I am migrating a html site into a Ionic app.

The html site uses a legacy javascript animation runtime file called "Swiffy":http://www.gstatic.com/swiffy/v5.4/runtime.js

Generally this is how it was used in the old site:

1) Including the runtime and declare a swiffyObject with a bunch of generated code.

```<code><script type="text/javascript" src="...path/to/swiffy.js"></script>
<script>swiffyobject = {"internedStrings":["::::50g2s..... a bunch of really long code...</script>
</code>```

2) Start the Swiffy object when document is ready

```<code>$(document).ready(function(){

var stage = new swiffy.Stage(document.getElementById('swiffycontainer'),swiffyobject);
stage.setBackground(null);
stage.start();

....
</code>```

I tried to do the same in a brand new Ionic 2 project:

1) Including the script in src/index.html

```<code><script type="text/javascript" src="...path/to/swiffy.js"></script>
<script>swiffyobject = {"internedStrings":["::::50g2s..... a bunch of really long code...</script>
</code>```

2) Insert the script in Homepage ionViewDidLoad:

```<code>ionViewDidLoad() {

var stage = new swiffy.Stage(document.getElementById('swiffycontainer'),swiffyobject);
stage.setBackground(null);
stage.start();
}
</code>```

Unfortunately, it doesnt work. When running ionic serve, two errors happen:

```<code>Cannot find name 'swiffy'.
Cannot find name 'swiffyobject'.
</code>```

I am a newbie in Angular 2, I am quite sure the homepage typescript file is not aware of the global variables swifft and swiffyobject declared in the index.html

I tried this:

```<code>var stage = new window["swiffy"].Stage(document.getElementById('swiffycontainer'),window["swiffyobject");
stage.setBackground(null);
stage.start();
}
</code>```

No Typescript compilation but it doesnt work too, complaining Cannot read property 'Stage' of undefined

How can I get the variables declared in index.html?

答:
declare those variable in your AppModule file

```<code>declare let swiffy : any;
declare let swiffyobject: any;

@NgModule({
   //...
})
export class AppModule{}
</code>```

Body:
I am migrating a html site into a Ionic app.

The html site uses a legacy javascript animation runtime file called "Swiffy":http://www.gstatic.com/swiffy/v5.4/runtime.js

Generally this is how it was used in the old site:

1) Including the runtime and declare a swiffyObject with a bunch of generated code.

2) Start the Swiffy object when document is ready

$(document).ready(function(){

var stage = new swiffy.Stage(document.getElementById('swiffycontainer'),swiffyobject);
stage.setBackground(null);
stage.start();

....

I tried to do the same in a brand new Ionic 2 project:

1) Including the script in src/index.html

2) Insert the script in Homepage ionViewDidLoad:

ionViewDidLoad() {

var stage = new swiffy.Stage(document.getElementById('swiffycontainer'),swiffyobject);
stage.setBackground(null);
stage.start();
}

Unfortunately, it doesnt work. When running ionic serve, two errors happen:

Cannot find name 'swiffy'.
Cannot find name 'swiffyobject'.

I am a newbie in Angular 2, I am quite sure the homepage typescript file is not aware of the global variables swifft and swiffyobject declared in the index.html

I tried this:

var stage = new window["swiffy"].Stage(document.getElementById('swiffycontainer'),window["swiffyobject");
stage.setBackground(null);
stage.start();
}

No Typescript compilation but it doesnt work too, complaining Cannot read property 'Stage' of undefined

How can I get the variables declared in index.html?

Body:
declare those variable in your AppModule file

declare let swiffy : any;
declare let swiffyobject: any;

@NgModule({
   //...
})
export class AppModule{}


问:
C# Multiple Indexers
Is it possible to have something like the following:

```<code>class C
{
    public Foo Foos[int i]
    {
        ...
    }

    public Bar Bars[int i]
    {
        ...
    }
}
</code>```

If not, then are what are some of the ways I can achieve this? I know I could make functions called getFoo(int i) and getBar(int i) but I was hoping to do this with properties.

答: C# doesn't have return type overloading. You can define multiple indexers if their input parameters are different.</p>

ContentLicense: CC BY-SA 2.5

Title: C# Multiple Indexers

Body:
Is it possible to have something like the following:

class C
{
    public Foo Foos[int i]
    {
        ...
    }

    public Bar Bars[int i]
    {
        ...
    }
}

If not, then are what are some of the ways I can achieve this? I know I could make functions called getFoo(int i) and getBar(int i) but I was hoping to do this with properties.

OwnerDisplayName: Josh


问:
Debugging stored procedures in SQL Server Management Studio
Is there a way to step into the stored procedure code in SQL Server Management Studio? I know this is possible with Visual Studio, but I am looking for a dependable debugging solution from within Management Studio</p>

答:
I have written a pretty detailed blog post about it here:

http://www.diaryofaninja.com/blog/2010/11/23/debugging-sql-queries-function-amp-stored-procedures-with-sql-management-studio

Basically the gist of it is that you enter your sql query to execute your stored procedure, and instead of pressing F5 or hitting the exclamation, you hit the play button and use F10 and F11 to step through and step into your stored procs.

This is very handy but no one seems to use it.

ContentLicense: CC BY-SA 4.0


问:
Image stretched when I capture image and save to SD card in Android
```<code>BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
bitmap = Bitmap.createScaledBitmap(bitmap, 150, 50, false);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = 150;
int newHeight = 50;

// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;

// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(-90);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
        width, height, matrix, true);
//      HomePage.image.setImageBitmap(resizedBitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Intent in1 = new Intent(CameraView.this, ImageDisplay.class);
in1.putExtra("picture",byteArray);
startActivity(in1);
</code>```

This is my code. I am unable to set image because image becomes stretched. It's not coming clear image full screen. Where am I doing wrong?

My image come like this we have fix it it should not stretched.

答:
```<code>>       public int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight){
>             final int height = options.outHeight;
>             final int width = options.outWidth;
>             int inSampleSize = 1;
>             if (height > reqHeight || width > reqWidth) {final int heightRatio = Math.round((float) height / (float) reqHeight);
>                 final int widthRatio = Math.round((float) width / (float) reqWidth);
>                 inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;}
>             final float totalPixels = width * height;
>             final float totalReqPixelsCap = reqWidth * reqHeight * 2;
>             while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {inSampleSize++;}
>             return inSampleSize;}
>
>     > `Blockquote`
</code>```

Body:
BitmapFactory.Options opts = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
bitmap = Bitmap.createScaledBitmap(bitmap, 150, 50, false);
int width = bitmap.getWidth();
int height = bitmap.getHeight();
int newWidth = 150;
int newHeight = 50;

// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;

// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(-90);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
        width, height, matrix, true);
//      HomePage.image.setImageBitmap(resizedBitmap);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();

Intent in1 = new Intent(CameraView.this, ImageDisplay.class);
in1.putExtra("picture",byteArray);
startActivity(in1);

This is my code. I am unable to set image because image becomes stretched. It's not coming clear image full screen. Where am I doing wrong?

My image come like this we have fix it it should not stretched.


问:
KnockoutJS Click binding on a dynamically created DOM token
By "token", I mean one of these things:

I'd like to bind a click event to the white cross icon that appears next to each Role. A Role is simply an entity (JS object) with a Name property.

To get from a Role, to a token, I have the following function:

```<code>var closeIcon = ' <i class="fa fa-times-circle" aria-hidden="true" data-bind="click: removeRoleForSelectedUser(role)" id="remove-role-btn"></i>';
self.createRoleToken = function(roleName) {
  return roleName + ' ' + closeIcon;
};
</code>```

The looping is happening here:

```<code><div class="roles-wrapper" data-bind="foreach: $root.selectedUser().roles()">
  <div class="role-token" data-bind="html: $root.createRoleToken(name())"></div>
</div>
</code>```

Even though I have the data-bind="click: removeRoleForSelectedUser(role)" on my HTML markup, it still doesn't trigger the event, so I'm guessing it isn't bound.

I went to Google for answers, and saw this. so I tried to do that binding on my role token (targeting the id property). I did the binding on user selection as seen here:

```<code>self.setCurrentUser = function (user) {
  const newRolesArray = self.roles().filter(function (role) {
    return !contains(user.roles(), role);
  });
  self.userAvailableRoles(newRolesArray);
  self.selectedUser(user);
  ko.applyBindings(self, document.getElementById("remove-role-btn"));
}
</code>```

That didn't work. It threw the following error:

What am I missing?

答:
Rather than having a complex function that returns markup with extra bindings in, you should instead make the close icon part of the general template:

```<code><div class="roles-wrapper" data-bind="foreach: $root.selectedUser().roles()">
  <div class="role-token">
    <span data-bind="text: name"></span>
    <i class="fa fa-times-circle" aria-hidden="true" data-bind="click: $root.removeRoleForSelectedUser"></i>
  </div>
</div>
</code>```

There should also be no need to repeatedly call applyBindings, so you should also at least remove that part.  Without seeing more of the code surrounding your question, it's hard to say if the above is exactly right, but it should get you on the way.

Body:
By "token", I mean one of these things:

I'd like to bind a click event to the white cross icon that appears next to each Role. A Role is simply an entity (JS object) with a Name property.

To get from a Role, to a token, I have the following function:

var closeIcon = ' ';
self.createRoleToken = function(roleName) {
  return roleName + ' ' + closeIcon;
};

The looping is happening here:

Even though I have the data-bind="click: removeRoleForSelectedUser(role)" on my HTML markup, it still doesn't trigger the event, so I'm guessing it isn't bound.

I went to Google for answers, and saw this. so I tried to do that binding on my role token (targeting the id property). I did the binding on user selection as seen here:

self.setCurrentUser = function (user) {
  const newRolesArray = self.roles().filter(function (role) {
    return !contains(user.roles(), role);
  });
  self.userAvailableRoles(newRolesArray);
  self.selectedUser(user);
  ko.applyBindings(self, document.getElementById("remove-role-btn"));
}

That didn't work. It threw the following error:

What am I missing?

Body:
Rather than having a complex function that returns markup with extra bindings in, you should instead make the close icon part of the general template:

<div class="roles-wrapper" data-bind="foreach: $root.selectedUser().roles()">
  <div class="role-token">
    <span data-bind="text: name"></span>
    <i class="fa fa-times-circle" aria-hidden="true" data-bind="click: $root.removeRoleForSelectedUser"></i>
  </div>
</div>

There should also be no need to repeatedly call applyBindings, so you should also at least remove that part.  Without seeing more of the code surrounding your question, it's hard to say if the above is exactly right, but it should get you on the way.


答:
Cannot find name 'swiffy'.

Cannot find name 'swiffyobject'.

In order to avoid these errors (since it's just typescript complaining about knowing nothing about these types) you could declare them in the same component file where you want to use them, like this:

```<code>declare var swiffy: any;
declare var swiffyobject: any;

@Component({...})
...
</code>```

That's enough to make Typescript happy.

But, in the other hand, now we should inspect in the console if these two properties are being created and set by the script you're importing. If they are not being set, please check if the path to the js library is ok, and take a look at that code to see if the properties are being created as global objects.

The second line of the scripts you're importing seems to create the swiffyobject, but I woudln't know if the swiffy one is also being created properly.

Title: Typescript error when importing a single 3rd party javascript file in an Ionic 2 project

Body:
Cannot find name 'swiffy'.

Cannot find name 'swiffyobject'.

In order to avoid these errors (since it's just typescript complaining about knowing nothing about these types) you could declare them in the same component file where you want to use them, like this:

declare var swiffy: any;
declare var swiffyobject: any;

@Component({...})
...

That's enough to make Typescript happy.

But, in the other hand, now we should inspect in the console if these two properties are being created and set by the script you're importing. If they are not being set, please check if the path to the js library is ok, and take a look at that code to see if the properties are being created as global objects.

The second line of the scripts you're importing seems to create the swiffyobject, but I woudln't know if the swiffy one is also being created properly.


问:
Firefox browser is not opening in Selenium webdriver in eclipse
I'm using Firefox 45.8.0 version and I tried below code to open Firefox browser but i'm getting error that: "The path to the driver executable must be set by the webdriver.gecko.driver system property".
Please sagest me how to set the path.
Note:gecko driver will work for above firefox version 48.  </p>

```<code>package First;

    import org.openqa.selenium.firefox.FirefoxDriver;
    public class City {

        public static void main(String[] args) {
            // TODO Auto-generated method stub

            FirefoxDriver c1=new FirefoxDriver();
            c1.get("http://google.com");

        }

    }
</code>```

答:
Try this below code.

In your code you were not provide gecko driver path. You can download gecko driver from this link

```<code>public class City {

    public static void main(String[] args) {

        System.setProperty("webdriver.gecko.driver", "C:\\Drivers\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
        driver.get("http://google.com");
    }
}
</code>```

Body:
I'm using Firefox 45.8.0 version and I tried below code to open Firefox browser but i'm getting error that: "The path to the driver executable must be set by the webdriver.gecko.driver system property".
Please sagest me how to set the path.
Note:gecko driver will work for above firefox version 48.

package First;

    import org.openqa.selenium.firefox.FirefoxDriver;
    public class City {

        public static void main(String[] args) {
            // TODO Auto-generated method stub

            FirefoxDriver c1=new FirefoxDriver();
            c1.get("http://google.com");

        }

    }

Body:
Try this below code.

In your code you were not provide gecko driver path. You can download gecko driver from this link

public class City {

    public static void main(String[] args) {

        System.setProperty("webdriver.gecko.driver", "C:\\Drivers\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(25, TimeUnit.SECONDS);
        driver.get("http://google.com");
    }
}


问:
Track system activity
Is there a neat/easy way in objective-c/cocoa to track if a user is at their computer, ie I assume by detecting key presses and mouse movement?

(ie I want to fill out my timesheet automatically by detecting when I am at work and not at work)

答:
Much more on Event Taps and handling global activity in Mac OS X 10.6 is here:
Mouse tracking daemon</p>

Title: Track system activity


问:
informatica min and max value dynamically fetch from database
I have a requirement to fetch records from a table in oracle database with the id in search condition .I need to take min and max value of the id and need to compare against another table and store the missing id .This need to be done on a daily basis and the current run max value will become the min value of next day run.

Kindly let me know how to achieve the get the min and max value as parameter in Informatica and assign on  daily basis

Thanks

答:
There are two basic options:
- store those in a file
- use mapping/workflow variable combination. Use persistent WF variables, do a Pre-session var assignment, set new values in the mapping, do a post-session var assignment to store values in workflow variables.
Let me know if you'd have any issues.</p>


问:
Should I include getters & setters in class diagram?
I am required to draw a class diagram for my JSF application for a project documentation. So I have lots of classes as managed beans, with many attributes therefore many getters and setters.

When I draw the class diagram should I also include the getters & setters in the diagram or can I simply leave them?

答: It may be useful to make the getter/setter convention explicit for the properties concerned by creating your own «get/set» and «get» stereotypes to be used for categorizing these private properties. See my answer to Shortcut for denoting or implying getters and setters in UML class diagrams.</p>


问:
Max characters in textarea with jquery
I have the following code, and I'm kind of stuck on what to do next. The idea is when you enter text into a text area a counter tells you how many characters you have left. Once you get to the max characters I want to stop allowing characters to be entered, or delete all the characters that were entered so there are only 10 characters in the text area. I know I have to put the code where it says alert("LONG"); but I'm not quite sure what.

```<code>var maxLen = 10;
        console.log("Start");
        $('#send-txt').keyup(function(){
            var Length = $("#send-txt").val().length;
            var AmountLeft = maxLen - Length;
            $('#txt-length-left').html(AmountLeft);
            if(Length >= maxLen){
                alert("LONG");
            }

        });
</code>```

答:
I find this works perfectly, and doesn't even flash the excess characters in the textarea before removing them, as a few other solutions do.</p>

```<code><h1>Add a comment:</h1>
<form>
    <textarea name="commentText" id="commentText"></textarea>
</form>
<br><span id="commentChars">1000</span> characters remaining

<script type="text/javascript">

    function checkChars(){
        var numChars = $('#commentText').val().length;
        var maxChars = 1000;
        var remChars = maxChars - numChars;
        if (remChars < 0) {
            $('#commentText').val($('#commentText').val().substring(0, maxChars));
                remChars = 0;
            }
        $('#commentChars').text(remChars);
    }

    $('#commentText').bind('input propertychange', function(){
        checkChars();
    });

    checkChars();

</script>
</code>```

Title: Max characters in textarea with jquery

Body:
I have the following code, and I'm kind of stuck on what to do next. The idea is when you enter text into a text area a counter tells you how many characters you have left. Once you get to the max characters I want to stop allowing characters to be entered, or delete all the characters that were entered so there are only 10 characters in the text area. I know I have to put the code where it says alert("LONG"); but I'm not quite sure what.

var maxLen = 10;
        console.log("Start");
        $('#send-txt').keyup(function(){
            var Length = $("#send-txt").val().length;
            var AmountLeft = maxLen - Length;
            $('#txt-length-left').html(AmountLeft);
            if(Length >= maxLen){
                alert("LONG");
            }

        });

Body:
I find this works perfectly, and doesn't even flash the excess characters in the textarea before removing them, as a few other solutions do.

<h1>Add a comment:</h1>
<form>
    <textarea name="commentText" id="commentText"></textarea>
</form>
<br><span id="commentChars">1000</span> characters remaining

<script type="text/javascript">

    function checkChars(){
        var numChars = $('#commentText').val().length;
        var maxChars = 1000;
        var remChars = maxChars - numChars;
        if (remChars < 0) {
            $('#commentText').val($('#commentText').val().substring(0, maxChars));
                remChars = 0;
            }
        $('#commentChars').text(remChars);
    }

    $('#commentText').bind('input propertychange', function(){
        checkChars();
    });

    checkChars();

</script>


问:
Uncaught SyntaxError: Unexpected token < Underscore and parse issues
I know there are a bunch of these issues already logged and most seem to be missing %> tags. I'm probably just being blind and missing them

javascript triggered on loading view

```<code>var positionQuery = new Parse.Query(Position);
            positionQuery.equalTo("user", user);
            positionQuery.find({
                success: function(userPositions){
                this.$el.html(_.template($('#no-position-view').html(), {pos : userPositions}));
                },
                error: function(error){
                    //need an error message here
                    console.log("no positons retrieved");
                }
</code>```

which should be calling the following template

```<code>    <script type="text/html" id="no-position-view">

    <% if (pos.length > 0){ %>
        <table>
        <thead><th> Company Name </th><th>admin</th><th>date added</th></thead>
        <tbody>
            <% for (var i = 0, i < pos.length, i++){ %>
                <tr class="tableRow"  id='<%= pos[i].objectId %>' >
                    <td><%= pos[i].posCompany %></td>
                    <td><%= pos[i].posAdmin %></td>
                    <td><%= pos[i].createdAt %></td>
                    </tr>

            <% }; %>
        </tbody></table>

    <% } else {%>
        <p> You have no positions setup </p>
    <% } %>
 </script>
</code>```

Any ideas

答:
Change type of script to type="text/template"

```<code><script id = "myScript" type="text/template">
    <% _.each(data, function(res){}); %>
</script>
</code>```

Body:
I know there are a bunch of these issues already logged and most seem to be missing %> tags. I'm probably just being blind and missing them

javascript triggered on loading view

var positionQuery = new Parse.Query(Position);
            positionQuery.equalTo("user", user);
            positionQuery.find({
                success: function(userPositions){
                this.$el.html(_.template($('#no-position-view').html(), {pos : userPositions}));
                },
                error: function(error){
                    //need an error message here
                    console.log("no positons retrieved");
                }

which should be calling the following template

Any ideas

Body:
Change type of script to type="text/template"

<script id = "myScript" type="text/template">
    <% _.each(data, function(res){}); %>
</script>


问:
Javascript regex between string delimiters
I have the following string:

```<code>%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%
</code>```

PROBLEM: I am trying to match all occurrences between %||....||% and process those substring matches

MY REGEX: /%([\s\S]*?)(?=%)/g

MY CODE

```<code>var a = "%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%";

var pattern = /%([\s\S]*?)(?=%)/g;

a.replace( pattern, function replacer(match){
    return match.doSomething();
} );
</code>```

Now the patterns seems to be selecting the everything between the first and last occurrence of %||  .... %||

MY
FIDDLE

WHAT I NEED:

I want to iterate over the matches

%||1234567890||Joe||%

AND

%||1234567890||Robert||%

and do something

答:
You need to use a callback inside a String#replace and modify the pattern to only match what is inside %|| and ||% like this:

var a = "%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%";
var pattern = /%\|\|([\s\S]*?)\|\|%/g;
a = a.replace( pattern, function (match, group1){
    var chunks = group1.split('||');
    return "{1}" + chunks.join("-") + "{/1}";
} );
console.log(a);```

The /%\|\|([\s\S]*?)\|\|%/g pattern will match:

%\|\| - a %|| substring

([\s\S]*?) - Capturing group 1 matching any 0+ chars as few as possible up to the first...

\|\|% - a ||% substring

/g - multiple times.

Body:
I have the following string:

%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%

PROBLEM: I am trying to match all occurrences between %||....||% and process those substring matches

MY REGEX: /%([\s\S]*?)(?=%)/g

MY CODE

var a = "%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%";

var pattern = /%([\s\S]*?)(?=%)/g;

a.replace( pattern, function replacer(match){
    return match.doSomething();
} );

Now the patterns seems to be selecting the everything between the first and last occurrence of %||  .... %||

MY
FIDDLE

WHAT I NEED:

I want to iterate over the matches

%||1234567890||Joe||%

AND

%||1234567890||Robert||%

and do something

Body:
You need to use a callback inside a String#replace and modify the pattern to only match what is inside %|| and ||% like this:

var a = "%||1234567890||Joe||% some text winter is coming %||1234567890||Robert||%";
var pattern = /%\|\|([\s\S]*?)\|\|%/g;
a = a.replace( pattern, function (match, group1){
    var chunks = group1.split('||');
    return "{1}" + chunks.join("-") + "{/1}";
} );
console.log(a);

The /%\|\|([\s\S]*?)\|\|%/g pattern will match:

%\|\| - a %|| substring

([\s\S]*?) - Capturing group 1 matching any 0+ chars as few as possible up to the first...

\|\|% - a ||% substring

/g - multiple times.


问:
MYSQL Show each date in case when
I would like to show each date in a case when query such as

```<code>SELECT pp.user_id, p.payment_profile_id,
       Max(case when p.transaction_type='New Order' THEN date(p.created_at) end ) as 'new_order_date',
       (case when p.transaction_type='Renewal Order' THEN date(p.created_at) end) as 'renew_date'
from payments p
    join payment_profiles pp on pp.id = p.payment_profile_id
</code>```

If I didn't add Max but it shows blank in the last two columns.

```<code>user.id payment_profile_id new_order_date  renew_date
    1         aaa                  (NULL)    (NULL)
</code>```

If I add Max but it shows blank in the last column.

```<code>user.id payment_profile_id new_order_date  renew_date
    1         aaa                  1/1/2013     (NULL)
</code>```

And if I remove group by, it will show up multiple rows but not

```<code>user.id payment_profile_id new_order_date  renew_date
    1         aaa                  1/1/2013     (NULL)
    1         aaa                  (NULL)       (NULL)
    1         aaa                  (NULL)       3/1/2013
    1         aaa                  (NULL)       4/1/2013
</code>```

I would like to get the result like--

```<code>user.id payment_profile_id new_order_date  renew_date
1         aaa                  1/1/2013     3/1/2013
1         aaa                  1/1/2013     4/1/2013
</code>```

The new order date only needs the latest one but one new order date may have many renew dates.

However, If I use this query, the renew date doesn't show the result..

答:
Please try the below:

```<code>SELECT p.payment_profile_id,p.created_at as Renewal_Date, a.max_new_order_date as Order_Date FROM p left join
(select id,payment_profile_id, transaction_type, max(created_at) as max_new_order_date from p where  transaction_type='New Order' group by payment_profile_id) a on p.payment_profile_id=a.payment_profile_id where p.transaction_type="Renewal Order";
</code>```

The above is to list out max order date that is group by payment_profile_id then later join with the original table so that could list out all individual order date.

Title: MYSQL Show each date in case when

Body:
I would like to show each date in a case when query such as

SELECT pp.user_id, p.payment_profile_id,
       Max(case when p.transaction_type='New Order' THEN date(p.created_at) end ) as 'new_order_date',
       (case when p.transaction_type='Renewal Order' THEN date(p.created_at) end) as 'renew_date'
from payments p
    join payment_profiles pp on pp.id = p.payment_profile_id

If I didn't add Max but it shows blank in the last two columns.

user.id payment_profile_id new_order_date  renew_date
    1         aaa                  (NULL)    (NULL)

If I add Max but it shows blank in the last column.

user.id payment_profile_id new_order_date  renew_date
    1         aaa                  1/1/2013     (NULL)

And if I remove group by, it will show up multiple rows but not

user.id payment_profile_id new_order_date  renew_date
    1         aaa                  1/1/2013     (NULL)
    1         aaa                  (NULL)       (NULL)
    1         aaa                  (NULL)       3/1/2013
    1         aaa                  (NULL)       4/1/2013

I would like to get the result like--

user.id payment_profile_id new_order_date  renew_date
1         aaa                  1/1/2013     3/1/2013
1         aaa                  1/1/2013     4/1/2013

The new order date only needs the latest one but one new order date may have many renew dates.

However, If I use this query, the renew date doesn't show the result..

Body:
Please try the below:

SELECT p.payment_profile_id,p.created_at as Renewal_Date, a.max_new_order_date as Order_Date FROM p left join
(select id,payment_profile_id, transaction_type, max(created_at) as max_new_order_date from p where  transaction_type='New Order' group by payment_profile_id) a on p.payment_profile_id=a.payment_profile_id where p.transaction_type="Renewal Order";

The above is to list out max order date that is group by payment_profile_id then later join with the original table so that could list out all individual order date.


问:
Div placement at proper position
I have a div which is visible in some scenarios. Below that div i have a next button. when that div is not visible the next button seems at the end. How can i tackle this situation? i want the next button to come at the place of the hidden div.</p>

```<code><div ng-show="(currentQuoteQto.requestType===constants.ssoQuote || currentQuoteQto.bu === constants.frNsQuote) && currentQuoteQto.status === constants.ssoPendingApproval
                      && (!currentCustomers[quoteRequest.contractingPartyIc01].onlineApproval ||
                      (currentQuoteQto.additionalDocuments && currentQuoteQto.additionalDocuments.length>0))" style="text-align: left; margin-left: 70px; margin-top: 25px" >
            <span translate>qrDetail.uploadDocuments</span><br>
          <span ng-repeat="additionalDocument in currentQuoteQto.additionalDocuments">
                {{$index + 1}}.{{additionalDocument.documentName}}<br>
            </span>
            <span ng-show="!currentCustomers[quoteRequest.contractingPartyIc01].onlineApproval">{{currentQuoteQto.additionalDocuments.length+1}}.<span translate>qrDetail.signedOrderForm</span></span>
            <div style="float: right" attachments show-Button=true attachments-data="quoteRequest" is-quote=true></div>
        </div>
    </div>
  <div style="text-align: right;margin-bottom: 40px;float: right">
<table>
  <tr>
    <td> <button class="bouton_action"
                 ng-click="showBundleAdditionalInformation()"
                 ng-disabled="!visibilityOfNextButtonForBundle()"
                 translate>button.next
    </button> </td>
    <td> <button class="bouton_action"

                 ng-show="visibilityOfSubmitButtonForBundle()  "
                 ng-click="setBundleOption();manageOrderRejection(false);manageQuoteRejection();"
                 ng-class="{bouton_action_l_pushed:inProgress.submit}"
                 translate>button.submitQuote
    </button> </td>
  </tr>
</table>
  </div>
</code>```

答:
You have a redundant closing
 tag right before the following element

```<code><div style="text-align: right;margin-bottom: 40px;float: right">
</code>```

Remove the redundant tag and see how it goes.

Title: Div placement at proper position

Body:
I have a div which is visible in some scenarios. Below that div i have a next button. when that div is not visible the next button seems at the end. How can i tackle this situation? i want the next button to come at the place of the hidden div.

0))" style="text-align: left; margin-left: 70px; margin-top: 25px" >
            qrDetail.uploadDocuments

                {{$index + 1}}.{{additionalDocument.documentName}}

            {{currentQuoteQto.additionalDocuments.length+1}}.qrDetail.signedOrderForm

     <button class="bouton_action"
                 ng-click="showBundleAdditionalInformation()"
                 ng-disabled="!visibilityOfNextButtonForBundle()"
                 translate>button.next
    </button>
     <button class="bouton_action"

                 ng-show="visibilityOfSubmitButtonForBundle()  "
                 ng-click="setBundleOption();manageOrderRejection(false);manageQuoteRejection();"
                 ng-class="{bouton_action_l_pushed:inProgress.submit}"
                 translate>button.submitQuote
    </button>

Body:
You have a redundant closing </div> tag right before the following element

<div style="text-align: right;margin-bottom: 40px;float: right">

Remove the redundant tag and see how it goes.


问:
Float random with value from "1.3000 to 1.4000" is possible?
Its possible to make float random from range 1.3000 to 1.4000? That give me numbers like 13405, 13855 etc.
I know double is more flexible with range floating point, but i cant use it.

So i create something like:

```<code>  float highmax = 0.6500f;
        float highlow = 0.7000f;
        float generatedFloatHigh = highmax + new Random().nextFloat() * (highlow - highmax);
</code>```

But this not work what i want.

Any suggestion? Or maybe i should look for other libraly?

答:
```<code>Random generator = new Random(System.currentTimeMillis());
int n = generator.nextInt(1000);
float generatedFloatHigh = 1.3000 + n/1000;
</code>```

Body:
Its possible to make float random from range 1.3000 to 1.4000? That give me numbers like 13405, 13855 etc.
I know double is more flexible with range floating point, but i cant use it.

So i create something like:

  float highmax = 0.6500f;
        float highlow = 0.7000f;
        float generatedFloatHigh = highmax + new Random().nextFloat() * (highlow - highmax);

But this not work what i want.

Any suggestion? Or maybe i should look for other libraly?


问:
Get dimension or CGRect of UIImage after AspectFit
I am just finding the way to get the image size whenever it aspect fit to imageview. but didn't get any proper way to get the image dimension.  I just want to calculate the difference between the imageview and the actual image in the imageview. Please advice.

答:
You can use this

```<code> CGSize imageViewSize = imageView.bounds.size;
 CGSize imageSize = image.size;
 CGFloat minFactor = imageViewSize.width / imageSize.width;
 if (imageViewSize.height / imageSize.height < minFactor)
 {
     minFactor = imageViewSize.height / imageSize.height;
 }

 CGSize resultSize = CGSizeMake(minFactor * imageSize.width, minFactor * imageSize.height);
</code>```

Hope it help.

Body:
You can use this

 CGSize imageViewSize = imageView.bounds.size;
 CGSize imageSize = image.size;
 CGFloat minFactor = imageViewSize.width / imageSize.width;
 if (imageViewSize.height / imageSize.height < minFactor)
 {
     minFactor = imageViewSize.height / imageSize.height;
 }

 CGSize resultSize = CGSizeMake(minFactor * imageSize.width, minFactor * imageSize.height);

Hope it help.


问:
How to color x and y coordinates in php grid table
I have a grid table. For now, my table x and y coordinates are showing the first letter of a key. I want to change this with the same color for all those coordinates.

```<code>for ( $i = 0; $i < $size; $i++ ) {
        # Create a temporary holder for our coordinates
        $curr = array( 'x' => $x, 'y' => $y );
        # Add current grid position to the direction we're going
        $curr[ $axis ] += $i;
        # Add the first letter of the key name to the grid
        $grid[ $curr['x'] ][ $curr['y'] ] =  substr( $name, 0, 1 );
    }
</code>```

My output looks like:

```<code>__________
|r |  |  |
|__|__|__|
|r |r |  |
|__|__|__|
</code>```

What is best way to change this $grid[ $curr['x'] ][ $curr['y'] ] =  substr( $name, 0, 1 ); with color? Should I use css or can I do it with PHP?

答:
If I'm understanding you correctly, you want the same colour for the same letter; so all 'A's would be red?

You could add a list of colours into an array...

```<code>$color = ['A'=>'FF0000','B'=>'00FF00',...,...]
</code>```

...and get your code to output...

```<code>"style='background-color: #".$color[$letter]."'"
</code>```

You could even change the hex values for class names and have a nice sass solution, if you're worried about inline styling.

See http://thesassway.com/intermediate/if-for-each-while for more information on that

Body:
I have a grid table. For now, my table x and y coordinates are showing the first letter of a key. I want to change this with the same color for all those coordinates.

for ( $i = 0; $i < $size; $i++ ) {
        # Create a temporary holder for our coordinates
        $curr = array( 'x' => $x, 'y' => $y );
        # Add current grid position to the direction we're going
        $curr[ $axis ] += $i;
        # Add the first letter of the key name to the grid
        $grid[ $curr['x'] ][ $curr['y'] ] =  substr( $name, 0, 1 );
    }

My output looks like:

__________
|r |  |  |
|__|__|__|
|r |r |  |
|__|__|__|

What is best way to change this $grid[ $curr['x'] ][ $curr['y'] ] =  substr( $name, 0, 1 ); with color? Should I use css or can I do it with PHP?

Body:
If I'm understanding you correctly, you want the same colour for the same letter; so all 'A's would be red?

You could add a list of colours into an array...

$color = ['A'=>'FF0000','B'=>'00FF00',...,...]

...and get your code to output...

"style='background-color: #".$color[$letter]."'"

You could even change the hex values for class names and have a nice sass solution, if you're worried about inline styling.

See http://thesassway.com/intermediate/if-for-each-while for more information on that


问:
Android Studio: keyboard shortcut to show the error on the current line?
The only way I have found to show the error of an underlined piece of code is to hover it with the mouse.

What is the keyboard shortcut to achieve this? (when the cursor is on the line in error)

答:
You should try using Alt+Enter key. This will recommend you the available solution for your error.

Also try using Ctrl+F1 it will give you a detailed information for your error.

P.S. these shortcuts are for Windows.


问:
Ip address DNS and Domains
I'm a little confused about IP addresses.

I know that every web domain has an ip address.
Does the IP address represent the physical machine / host the website files are stored on?

Therefore when DNS lookup is performed, the domain's IP address is returned to the client. The client then uses this ip to contact the server that the web files reside on.

Is my understanding correct?

Many thanks

答:
You are correct.

It is kind of like how some companies may say Dial PIZZAHUT instead of saying, Dial 74992488. PIZZAHUT is easier to remember, but you actually are dialling the number.

Title: Ip address DNS and Domains


问:
asp.net Core 1 RenderPartial ViewDataDictionary
I am re-writing a website in VS 2017 that was originally written in VS 2010. The command I used originally to display my visitor count in the footer was:-
@Html.RenderPartial( "/Counter/Counter.ascx", new ViewDataDictionary {{ "digits", 6 }, { "id", "Count" }}). This displayed the number in Count.txt as 6 digits using digits.gif as the pattern. When I try and use the same code in VS 2017, I get the following error message: 'ViewDataDictionary' does not contain a constructor that takes 0 arguments. I have spent a lot of time looking at similar questions in this forum and on other sites and have been unable to find an answer. Any help you can give me will be most appreciated.

答:
Another way to use this is to pass the ViewData of the current view into the constructor. That way the new ViewDataDictionary gets extended with the items you put in using the collection initializer.

```<code>@Html.Partial("MyPartial", new ViewDataDictionary(ViewData) { { "digits", 6 } })
</code>```

Body:
Another way to use this is to pass the ViewData of the current view into the constructor. That way the new ViewDataDictionary gets extended with the items you put in using the collection initializer.

@Html.Partial("MyPartial", new ViewDataDictionary(ViewData) { { "digits", 6 } })


问:
Java generic parameter method to avoid code duplication
I have a function that parse an object. But this function is required in two services and the parameter have same class name, but different package name. What i need is to avoid duplicated code.

Suppose the function is:

```<code>    private HashMap<String, Integer> getPagination(PagingRequestType pagingRequestType) {
        int pageSize = 200;
        int pageNumber = 1;
        if(pagingRequestType != null) {
            if (pagingRequestType.getNumberOfRecordsPerPage() != 0) {
                pageSize = pagingRequestType.getNumberOfRecordsPerPage();
            }
            if (pagingRequestType.getStartAtRecordNumber() != 0) {
                pageNumber = pagingRequestType.getStartAtRecordNumber();
            }
        }
        HashMap<String, Integer> result = new HashMap<>();
        result.put("pageNumber", pageNumber);
        result.put("pageSize", pageSize);
        return result;
    }
</code>```

Possible function calls:

```<code>- getPagination(new Abc.PagingRequestType());
- getPagination(new Xyz.PagingRequestType());
</code>```

PagingRequestType is an auto-generated class in two different    packages. The function needs to be implemented once and used in both    services.

Thanks.

答:
If the option to make those two PagingRequestTypes to implement a common interface is impossiable, you could do it the reverse way, define a proxy type to wrap those two types:

```<code>public final class PagingRequestTypeProxy {
    private a.b.c.PagingRequestType abcPagingRequestType;

    private a.b.d.PagingRequestType abdPagingRequestType;

    public PagingRequestTypeProxy(PagingRequestType abcPagingRequestType) {
        this.abcPagingRequestType = abcPagingRequestType;
    }

    public PagingRequestTypeProxy(a.b.d.PagingRequestType abdPagingRequestType) {
        this.abdPagingRequestType = abdPagingRequestType;
    }

    public int getNumberOfRecordsPerPage() {
        return abcPagingRequestType != null ? abcPagingRequestType.getNumberOfRecordsPerPage() : abdPagingRequestType.getNumberOfRecordsPerPage();
    }

    public int getStartAtRecordNumber() {
        return abcPagingRequestType != null ? abcPagingRequestType.getStartAtRecordNumber() : abdPagingRequestType.getStartAtRecordNumber();
    }
}
</code>```

And change the parameter type of getPagination to:

```<code>private HashMap<String, Integer> getPagination(PagingRequestTypeProxy pagingRequestType) {...}
</code>```

Then you could use it like:

```<code>getPagination(new PagingRequestTypeProxy(abcPagingReqType));
getPagination(new PagingRequestTypeProxy(abdPagingReqType));
</code>```

The cons is that there're extra codes to define PagingRequestTypeProxy, the pros is that logic of PagingRequestTypeProxy is very simple and easy to maintain, and you can put your biz code getPagination in one place.

Body:
I have a function that parse an object. But this function is required in two services and the parameter have same class name, but different package name. What i need is to avoid duplicated code.

Suppose the function is:

    private HashMap<String, Integer> getPagination(PagingRequestType pagingRequestType) {
        int pageSize = 200;
        int pageNumber = 1;
        if(pagingRequestType != null) {
            if (pagingRequestType.getNumberOfRecordsPerPage() != 0) {
                pageSize = pagingRequestType.getNumberOfRecordsPerPage();
            }
            if (pagingRequestType.getStartAtRecordNumber() != 0) {
                pageNumber = pagingRequestType.getStartAtRecordNumber();
            }
        }
        HashMap<String, Integer> result = new HashMap<>();
        result.put("pageNumber", pageNumber);
        result.put("pageSize", pageSize);
        return result;
    }

Possible function calls:

- getPagination(new Abc.PagingRequestType());
- getPagination(new Xyz.PagingRequestType());

PagingRequestType is an auto-generated class in two different    packages. The function needs to be implemented once and used in both    services.

Thanks.

Body:
If the option to make those two PagingRequestTypes to implement a common interface is impossiable, you could do it the reverse way, define a proxy type to wrap those two types:

public final class PagingRequestTypeProxy {
    private a.b.c.PagingRequestType abcPagingRequestType;

    private a.b.d.PagingRequestType abdPagingRequestType;

    public PagingRequestTypeProxy(PagingRequestType abcPagingRequestType) {
        this.abcPagingRequestType = abcPagingRequestType;
    }

    public PagingRequestTypeProxy(a.b.d.PagingRequestType abdPagingRequestType) {
        this.abdPagingRequestType = abdPagingRequestType;
    }

    public int getNumberOfRecordsPerPage() {
        return abcPagingRequestType != null ? abcPagingRequestType.getNumberOfRecordsPerPage() : abdPagingRequestType.getNumberOfRecordsPerPage();
    }

    public int getStartAtRecordNumber() {
        return abcPagingRequestType != null ? abcPagingRequestType.getStartAtRecordNumber() : abdPagingRequestType.getStartAtRecordNumber();
    }
}

And change the parameter type of getPagination to:

private HashMap<String, Integer> getPagination(PagingRequestTypeProxy pagingRequestType) {...}

Then you could use it like:

getPagination(new PagingRequestTypeProxy(abcPagingReqType));
getPagination(new PagingRequestTypeProxy(abdPagingReqType));

The cons is that there're extra codes to define PagingRequestTypeProxy, the pros is that logic of PagingRequestTypeProxy is very simple and easy to maintain, and you can put your biz code getPagination in one place.