问:
I keep getting null values after adding new element to my object
I have an array object with some similar values. I'm excluding their duplicate values using a loop, and then I add the values to my other object(objectProperties) it's working fine however I get a NULL values inside category

   // data which im extracting
var data = [
   {
      "label":"May 14",
      "value":56714.4,
      "proID":"ISB"
   },
   {
      "label":"May 14",
      "value":15902.5,
      "proID":"LI8"
   },
   {
      "label":"May 14",
      "value":419.6,
      "proID":"TR2"
   },
   {
      "label":"May 15",
      "value":2754.8,
      "proID":"DAC"
   },
   {
      "label":"May 15",
      "value":50845.7,
      "proID":"ISB"
   },
   {
      "label":"May 15",
      "value":19760.3,
      "proID":"LI8"
   },
   {
      "label":"May 15",
      "value":1704.1,
      "proID":"TR2"
   },
   {
      "label":"May 16",
      "value":2145.6,
      "proID":"DAC"
   },
   {
      "label":"May 16",
      "value":55666.4,
      "proID":"ISB"
   },
   {
      "label":"May 16",
      "value":15044.4,
      "proID":"LI8"
   },
   {
      "label":"May 16",
      "value":2413.5,
      "proID":"TR2"
   },
   {
      "label":"May 17",
      "value":6564.4,
      "proID":"DAC"
   },
   {
      "label":"May 17",
      "value":71379,
      "proID":"ISB"
   },
   {
      "label":"May 17",
      "value":21774.2,
      "proID":"LI8"
   },
   {
      "label":"May 17",
      "value":2191.4,
      "proID":"TR2"
   },
   {
      "label":"May 18",
      "value":63338.9,
      "proID":"ISB"
   },
   {
      "label":"May 18",
      "value":24451,
      "proID":"LI8"
   },
   {
      "label":"May 18",
      "value":2616.5,
      "proID":"TR2"
   }
];

var propertiesObject = {    // my object
    type: 'mscolumn2d',
     renderAt: 'chart-container',
     width: '1000',
     height: '500',
     dataFormat: 'json',
     dataSource: {
        chart: {
            caption: "Kilos per Date Comparison"

            },
    categories: [
            {
                category: []
            }
        ]

    }
 };

    var propCount = Object.keys(data).length; // getting object length
    var checkSameLabel = data[0].label;    // for reference reference inside the loop
    var firstIndex = {"label":data[0].label}; // im taking first index of object and add manually
    propertiesObject.dataSource.categories[0].category[0] = firstIndex; // adding the first index to my object
    var currentProject = data[0].proID, counterCurrentProject = 0;
    for(let i = 0; i < propCount; i++) {
        if(checkSameLabel !== data[i].label) { // check if current value of label is not equal then add new data to my object

            const value = data[i].label;
            var obj = {
                "label": value
            };
            propertiesObject.dataSource.categories[0].category[i] = value; // adding new data
        }
        checkSameLabel = data[i].label; // for the next check
    }
    console.log(JSON.stringify(propertiesObject));
    document.getElementById("result").innerHTML = JSON.stringify(propertiesObject);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="result"></div></code>```

I'm expecting the output to be like this inside "category"

```<code>{ "label": "May 14" },
{ "label": "May 15" },
{ "label": "May 16" },
{ "label": "May 17" }
</code>```

I don't know if it's because of my loop or im doing something wrong.

答:
Instead of assigning to indicies of the array, use push instead, else you'll have empty values:

// data which im extracting
var data = [{
    "label": "May 14",
    "value": 56714.4,
    "proID": "ISB"
  },
  {
    "label": "May 14",
    "value": 15902.5,
    "proID": "LI8"
  },
  {
    "label": "May 14",
    "value": 419.6,
    "proID": "TR2"
  },
  {
    "label": "May 15",
    "value": 2754.8,
    "proID": "DAC"
  },
  {
    "label": "May 15",
    "value": 50845.7,
    "proID": "ISB"
  },
  {
    "label": "May 15",
    "value": 19760.3,
    "proID": "LI8"
  },
  {
    "label": "May 15",
    "value": 1704.1,
    "proID": "TR2"
  },
  {
    "label": "May 16",
    "value": 2145.6,
    "proID": "DAC"
  },
  {
    "label": "May 16",
    "value": 55666.4,
    "proID": "ISB"
  },
  {
    "label": "May 16",
    "value": 15044.4,
    "proID": "LI8"
  },
  {
    "label": "May 16",
    "value": 2413.5,
    "proID": "TR2"
  },
  {
    "label": "May 17",
    "value": 6564.4,
    "proID": "DAC"
  },
  {
    "label": "May 17",
    "value": 71379,
    "proID": "ISB"
  },
  {
    "label": "May 17",
    "value": 21774.2,
    "proID": "LI8"
  },
  {
    "label": "May 17",
    "value": 2191.4,
    "proID": "TR2"
  },
  {
    "label": "May 18",
    "value": 63338.9,
    "proID": "ISB"
  },
  {
    "label": "May 18",
    "value": 24451,
    "proID": "LI8"
  },
  {
    "label": "May 18",
    "value": 2616.5,
    "proID": "TR2"
  }
];

var propertiesObject = { // my object
  type: 'mscolumn2d',
  renderAt: 'chart-container',
  width: '1000',
  height: '500',
  dataFormat: 'json',
  dataSource: {
    chart: {
      caption: "Kilos per Date Comparison"

    },
    categories: [{
      category: []
    }]

  }
};

var propCount = Object.keys(data).length; // getting object length
var checkSameLabel = data[0].label; // for reference reference inside the loop
var firstIndex = {
  "label": data[0].label
}; // im taking first index of object and add manually
propertiesObject.dataSource.categories[0].category[0] = firstIndex; // adding the first index to my object
var currentProject = data[0].proID,
  counterCurrentProject = 0;
for (let i = 0; i < propCount; i++) {
  if (checkSameLabel !== data[i].label) { // check if current value of label is not equal then add new data to my object

    const value = data[i].label;
    var obj = {
      "label": value
    };
    propertiesObject.dataSource.categories[0].category.push(obj);
  }
  checkSameLabel = data[i].label; // for the next check
}
console.log(propertiesObject);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="result"></div></code>```

You could also simplify things by using a Set to keep track of labels added so far and forEaching over the data:

// data which im extracting
var data = [{
    "label": "May 14",
    "value": 56714.4,
    "proID": "ISB"
  },
  {
    "label": "May 14",
    "value": 15902.5,
    "proID": "LI8"
  },
  {
    "label": "May 14",
    "value": 419.6,
    "proID": "TR2"
  },
  {
    "label": "May 15",
    "value": 2754.8,
    "proID": "DAC"
  },
  {
    "label": "May 15",
    "value": 50845.7,
    "proID": "ISB"
  },
  {
    "label": "May 15",
    "value": 19760.3,
    "proID": "LI8"
  },
  {
    "label": "May 15",
    "value": 1704.1,
    "proID": "TR2"
  },
  {
    "label": "May 16",
    "value": 2145.6,
    "proID": "DAC"
  },
  {
    "label": "May 16",
    "value": 55666.4,
    "proID": "ISB"
  },
  {
    "label": "May 16",
    "value": 15044.4,
    "proID": "LI8"
  },
  {
    "label": "May 16",
    "value": 2413.5,
    "proID": "TR2"
  },
  {
    "label": "May 17",
    "value": 6564.4,
    "proID": "DAC"
  },
  {
    "label": "May 17",
    "value": 71379,
    "proID": "ISB"
  },
  {
    "label": "May 17",
    "value": 21774.2,
    "proID": "LI8"
  },
  {
    "label": "May 17",
    "value": 2191.4,
    "proID": "TR2"
  },
  {
    "label": "May 18",
    "value": 63338.9,
    "proID": "ISB"
  },
  {
    "label": "May 18",
    "value": 24451,
    "proID": "LI8"
  },
  {
    "label": "May 18",
    "value": 2616.5,
    "proID": "TR2"
  }
];

var propertiesObject = { // my object
  type: 'mscolumn2d',
  renderAt: 'chart-container',
  width: '1000',
  height: '500',
  dataFormat: 'json',
  dataSource: {
    chart: {
      caption: "Kilos per Date Comparison"

    },
    categories: [{
      category: []
    }]
  }
};

const labelsAdded = new Set();
data.forEach(({ label }) => {
  if (labelsAdded.has(label)) {
    return;
  }
  labelsAdded.add(label);
  propertiesObject.dataSource.categories[0].category.push({ label });
});
console.log(propertiesObject);```
</div>
</div>
</p>

<p>Or, by creating a Set of the label strings, and then using <code>.map</code>:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// data which im extracting
var data = [{
    "label": "May 14",
    "value": 56714.4,
    "proID": "ISB"
  },
  {
    "label": "May 14",
    "value": 15902.5,
    "proID": "LI8"
  },
  {
    "label": "May 14",
    "value": 419.6,
    "proID": "TR2"
  },
  {
    "label": "May 15",
    "value": 2754.8,
    "proID": "DAC"
  },
  {
    "label": "May 15",
    "value": 50845.7,
    "proID": "ISB"
  },
  {
    "label": "May 15",
    "value": 19760.3,
    "proID": "LI8"
  },
  {
    "label": "May 15",
    "value": 1704.1,
    "proID": "TR2"
  },
  {
    "label": "May 16",
    "value": 2145.6,
    "proID": "DAC"
  },
  {
    "label": "May 16",
    "value": 55666.4,
    "proID": "ISB"
  },
  {
    "label": "May 16",
    "value": 15044.4,
    "proID": "LI8"
  },
  {
    "label": "May 16",
    "value": 2413.5,
    "proID": "TR2"
  },
  {
    "label": "May 17",
    "value": 6564.4,
    "proID": "DAC"
  },
  {
    "label": "May 17",
    "value": 71379,
    "proID": "ISB"
  },
  {
    "label": "May 17",
    "value": 21774.2,
    "proID": "LI8"
  },
  {
    "label": "May 17",
    "value": 2191.4,
    "proID": "TR2"
  },
  {
    "label": "May 18",
    "value": 63338.9,
    "proID": "ISB"
  },
  {
    "label": "May 18",
    "value": 24451,
    "proID": "LI8"
  },
  {
    "label": "May 18",
    "value": 2616.5,
    "proID": "TR2"
  }
];

var propertiesObject = { // my object
  type: 'mscolumn2d',
  renderAt: 'chart-container',
  width: '1000',
  height: '500',
  dataFormat: 'json',
  dataSource: {
    chart: {
      caption: "Kilos per Date Comparison"

    },
    categories: [{
      category: [...new Set(data.map(({ label }) => label))].map(label => ({ label }))
    }]
  }
};
console.log(propertiesObject);</code>```

Body:
I have an array object with some similar values. I'm excluding their duplicate values using a loop, and then I add the values to my other object(objectProperties) it's working fine however I get a NULL values inside category

   // data which im extracting
var data = [
   {
      "label":"May 14",
      "value":56714.4,
      "proID":"ISB"
   },
   {
      "label":"May 14",
      "value":15902.5,
      "proID":"LI8"
   },
   {
      "label":"May 14",
      "value":419.6,
      "proID":"TR2"
   },
   {
      "label":"May 15",
      "value":2754.8,
      "proID":"DAC"
   },
   {
      "label":"May 15",
      "value":50845.7,
      "proID":"ISB"
   },
   {
      "label":"May 15",
      "value":19760.3,
      "proID":"LI8"
   },
   {
      "label":"May 15",
      "value":1704.1,
      "proID":"TR2"
   },
   {
      "label":"May 16",
      "value":2145.6,
      "proID":"DAC"
   },
   {
      "label":"May 16",
      "value":55666.4,
      "proID":"ISB"
   },
   {
      "label":"May 16",
      "value":15044.4,
      "proID":"LI8"
   },
   {
      "label":"May 16",
      "value":2413.5,
      "proID":"TR2"
   },
   {
      "label":"May 17",
      "value":6564.4,
      "proID":"DAC"
   },
   {
      "label":"May 17",
      "value":71379,
      "proID":"ISB"
   },
   {
      "label":"May 17",
      "value":21774.2,
      "proID":"LI8"
   },
   {
      "label":"May 17",
      "value":2191.4,
      "proID":"TR2"
   },
   {
      "label":"May 18",
      "value":63338.9,
      "proID":"ISB"
   },
   {
      "label":"May 18",
      "value":24451,
      "proID":"LI8"
   },
   {
      "label":"May 18",
      "value":2616.5,
      "proID":"TR2"
   }
];

var propertiesObject = {    // my object
    type: 'mscolumn2d',
     renderAt: 'chart-container',
     width: '1000',
     height: '500',
     dataFormat: 'json',
     dataSource: {
        chart: {
            caption: "Kilos per Date Comparison"

            },
    categories: [
            {
                category: []
            }
        ]

    }
 };

    var propCount = Object.keys(data).length; // getting object length
    var checkSameLabel = data[0].label;    // for reference reference inside the loop
    var firstIndex = {"label":data[0].label}; // im taking first index of object and add manually
    propertiesObject.dataSource.categories[0].category[0] = firstIndex; // adding the first index to my object
    var currentProject = data[0].proID, counterCurrentProject = 0;
    for(let i = 0; i < propCount; i++) {
        if(checkSameLabel !== data[i].label) { // check if current value of label is not equal then add new data to my object

            const value = data[i].label;
            var obj = {
                "label": value
            };
            propertiesObject.dataSource.categories[0].category[i] = value; // adding new data
        }
        checkSameLabel = data[i].label; // for the next check
    }
    console.log(JSON.stringify(propertiesObject));
    document.getElementById("result").innerHTML = JSON.stringify(propertiesObject);

I'm expecting the output to be like this inside "category"

{ "label": "May 14" },
{ "label": "May 15" },
{ "label": "May 16" },
{ "label": "May 17" }

I don't know if it's because of my loop or im doing something wrong.

Body:
Instead of assigning to indicies of the array, use push instead, else you'll have empty values:

// data which im extracting
var data = [{
    "label": "May 14",
    "value": 56714.4,
    "proID": "ISB"
  },
  {
    "label": "May 14",
    "value": 15902.5,
    "proID": "LI8"
  },
  {
    "label": "May 14",
    "value": 419.6,
    "proID": "TR2"
  },
  {
    "label": "May 15",
    "value": 2754.8,
    "proID": "DAC"
  },
  {
    "label": "May 15",
    "value": 50845.7,
    "proID": "ISB"
  },
  {
    "label": "May 15",
    "value": 19760.3,
    "proID": "LI8"
  },
  {
    "label": "May 15",
    "value": 1704.1,
    "proID": "TR2"
  },
  {
    "label": "May 16",
    "value": 2145.6,
    "proID": "DAC"
  },
  {
    "label": "May 16",
    "value": 55666.4,
    "proID": "ISB"
  },
  {
    "label": "May 16",
    "value": 15044.4,
    "proID": "LI8"
  },
  {
    "label": "May 16",
    "value": 2413.5,
    "proID": "TR2"
  },
  {
    "label": "May 17",
    "value": 6564.4,
    "proID": "DAC"
  },
  {
    "label": "May 17",
    "value": 71379,
    "proID": "ISB"
  },
  {
    "label": "May 17",
    "value": 21774.2,
    "proID": "LI8"
  },
  {
    "label": "May 17",
    "value": 2191.4,
    "proID": "TR2"
  },
  {
    "label": "May 18",
    "value": 63338.9,
    "proID": "ISB"
  },
  {
    "label": "May 18",
    "value": 24451,
    "proID": "LI8"
  },
  {
    "label": "May 18",
    "value": 2616.5,
    "proID": "TR2"
  }
];

var propertiesObject = { // my object
  type: 'mscolumn2d',
  renderAt: 'chart-container',
  width: '1000',
  height: '500',
  dataFormat: 'json',
  dataSource: {
    chart: {
      caption: "Kilos per Date Comparison"

    },
    categories: [{
      category: []
    }]

  }
};

var propCount = Object.keys(data).length; // getting object length
var checkSameLabel = data[0].label; // for reference reference inside the loop
var firstIndex = {
  "label": data[0].label
}; // im taking first index of object and add manually
propertiesObject.dataSource.categories[0].category[0] = firstIndex; // adding the first index to my object
var currentProject = data[0].proID,
  counterCurrentProject = 0;
for (let i = 0; i < propCount; i++) {
  if (checkSameLabel !== data[i].label) { // check if current value of label is not equal then add new data to my object

    const value = data[i].label;
    var obj = {
      "label": value
    };
    propertiesObject.dataSource.categories[0].category.push(obj);
  }
  checkSameLabel = data[i].label; // for the next check
}
console.log(propertiesObject);

<div id="result"></div>

You could also simplify things by using a Set to keep track of labels added so far and forEaching over the data:

// data which im extracting
var data = [{
    "label": "May 14",
    "value": 56714.4,
    "proID": "ISB"
  },
  {
    "label": "May 14",
    "value": 15902.5,
    "proID": "LI8"
  },
  {
    "label": "May 14",
    "value": 419.6,
    "proID": "TR2"
  },
  {
    "label": "May 15",
    "value": 2754.8,
    "proID": "DAC"
  },
  {
    "label": "May 15",
    "value": 50845.7,
    "proID": "ISB"
  },
  {
    "label": "May 15",
    "value": 19760.3,
    "proID": "LI8"
  },
  {
    "label": "May 15",
    "value": 1704.1,
    "proID": "TR2"
  },
  {
    "label": "May 16",
    "value": 2145.6,
    "proID": "DAC"
  },
  {
    "label": "May 16",
    "value": 55666.4,
    "proID": "ISB"
  },
  {
    "label": "May 16",
    "value": 15044.4,
    "proID": "LI8"
  },
  {
    "label": "May 16",
    "value": 2413.5,
    "proID": "TR2"
  },
  {
    "label": "May 17",
    "value": 6564.4,
    "proID": "DAC"
  },
  {
    "label": "May 17",
    "value": 71379,
    "proID": "ISB"
  },
  {
    "label": "May 17",
    "value": 21774.2,
    "proID": "LI8"
  },
  {
    "label": "May 17",
    "value": 2191.4,
    "proID": "TR2"
  },
  {
    "label": "May 18",
    "value": 63338.9,
    "proID": "ISB"
  },
  {
    "label": "May 18",
    "value": 24451,
    "proID": "LI8"
  },
  {
    "label": "May 18",
    "value": 2616.5,
    "proID": "TR2"
  }
];

var propertiesObject = { // my object
  type: 'mscolumn2d',
  renderAt: 'chart-container',
  width: '1000',
  height: '500',
  dataFormat: 'json',
  dataSource: {
    chart: {
      caption: "Kilos per Date Comparison"

    },
    categories: [{
      category: []
    }]
  }
};

const labelsAdded = new Set();
data.forEach(({ label }) => {
  if (labelsAdded.has(label)) {
    return;
  }
  labelsAdded.add(label);
  propertiesObject.dataSource.categories[0].category.push({ label });
});
console.log(propertiesObject);

Or, by creating a Set of the label strings, and then using .map:

// data which im extracting
var data = [{
    "label": "May 14",
    "value": 56714.4,
    "proID": "ISB"
  },
  {
    "label": "May 14",
    "value": 15902.5,
    "proID": "LI8"
  },
  {
    "label": "May 14",
    "value": 419.6,
    "proID": "TR2"
  },
  {
    "label": "May 15",
    "value": 2754.8,
    "proID": "DAC"
  },
  {
    "label": "May 15",
    "value": 50845.7,
    "proID": "ISB"
  },
  {
    "label": "May 15",
    "value": 19760.3,
    "proID": "LI8"
  },
  {
    "label": "May 15",
    "value": 1704.1,
    "proID": "TR2"
  },
  {
    "label": "May 16",
    "value": 2145.6,
    "proID": "DAC"
  },
  {
    "label": "May 16",
    "value": 55666.4,
    "proID": "ISB"
  },
  {
    "label": "May 16",
    "value": 15044.4,
    "proID": "LI8"
  },
  {
    "label": "May 16",
    "value": 2413.5,
    "proID": "TR2"
  },
  {
    "label": "May 17",
    "value": 6564.4,
    "proID": "DAC"
  },
  {
    "label": "May 17",
    "value": 71379,
    "proID": "ISB"
  },
  {
    "label": "May 17",
    "value": 21774.2,
    "proID": "LI8"
  },
  {
    "label": "May 17",
    "value": 2191.4,
    "proID": "TR2"
  },
  {
    "label": "May 18",
    "value": 63338.9,
    "proID": "ISB"
  },
  {
    "label": "May 18",
    "value": 24451,
    "proID": "LI8"
  },
  {
    "label": "May 18",
    "value": 2616.5,
    "proID": "TR2"
  }
];

var propertiesObject = { // my object
  type: 'mscolumn2d',
  renderAt: 'chart-container',
  width: '1000',
  height: '500',
  dataFormat: 'json',
  dataSource: {
    chart: {
      caption: "Kilos per Date Comparison"

    },
    categories: [{
      category: [...new Set(data.map(({ label }) => label))].map(label => ({ label }))
    }]
  }
};
console.log(propertiesObject);


来源: stackexchange

问:
A help in concept and a database query question (Django/Python)
I am trying to build a kind of news website for learning purposes.

```<code>class NewsCategory(models.Model):
    category = models.CharField(max_length=50)
</code>```

Note: A category can be Soccer, Tennis, business ... User can register to different news category. This choice will be saved in their preferences.

```<code>class Profile(models.Model):
    user = models.ForeignKey(User, unique=True)
    gender = models.CharField(max_length=1,blank=True)
    preference = models.ManyToManyField(NewsCategory)
</code>```

I am currently stuck on how to update the preference list of each user (the list that specifies in which categories he is interested in.)

View:

```<code>category = [(item.category) for item in NewsCategory.objects.all()]
</code>```

and then I am sending the category to the template below

template:

```<code><div id="c_b">
    {% for c in category %}
        <input type="checkbox" name="category[]" value="{{c}}">
        <label for="{{c}}">{{c}}</label>
    {% endfor %}
</div>
</code>```

Questions:

What is the best way to add the checked tag next to the checkboxes that are already saved in the user's preference when I display the template.

I though of getting all the preferences users are registered for: saved_preference = user.preference.all() and then checking for each item in category if it is in saved_preference

I am also blanking out on the way to actually write that into code, and whether this should be done in the view or the template.

What is a good way to update the user preference list?

I was planning on running user.preference.clear() and then going through every item in the submitted form and running user.preference.add(the_new_preference)

答:
You'll need to pass the complete list of categories and also an index of user-selected categories to your template. You don't need to convert the NewsCategory queryset into a list in your view, by the way:

View

```<code>categories = NewsCategory.objects.all()
user_preferences = [item.id for item in Profile.preference.all()]
</code>```

The user_preferences variable will act as a lookup index for our template.

Then you loop through all the categories in the template, and check to see if it exists in the list of user preferences:

Template

```<code><div id="c_b">
{% for c in categories %}
    <input type="checkbox" name="category[]" id="id_{{ c.category }}" value="{{ c.id }}" {% if c.id in user_preferences %}checked="checked"{% endif %} />
    <label for="id_{{ c.id }}">{{ c.category }}</label>
{% endfor %}
</div>
</code>```

Update - saving user preferences

There is no hard and fast rule here. The main consideration, as far as I am concerned, would be minimising database hits. You can just clear the user preferences, like you say, and add the new ones - in fact, this is how Django's admin handles it. Just make use of Django's transaction management:

```<code>from django.db import transaction

@transaction.commit_manually
def add_preferences(user, preferences):
  user.preference.clear()
  for pref in preferences:
    user.preference.add(pref)
  transaction.commit()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to build a kind of news website for learning purposes.

class NewsCategory(models.Model):
    category = models.CharField(max_length=50)

Note: A category can be Soccer, Tennis, business ... User can register to different news category. This choice will be saved in their preferences.

class Profile(models.Model):
    user = models.ForeignKey(User, unique=True)
    gender = models.CharField(max_length=1,blank=True)
    preference = models.ManyToManyField(NewsCategory)

I am currently stuck on how to update the preference list of each user (the list that specifies in which categories he is interested in.)

View:

category = [(item.category) for item in NewsCategory.objects.all()]

and then I am sending the category to the template below

template:

    {% for c in category %}
        <input type="checkbox" name="category[]" value="{{c}}">
        {{c}}
    {% endfor %}

Questions:

What is the best way to add the checked tag next to the checkboxes that are already saved in the user's preference when I display the template.

I though of getting all the preferences users are registered for: saved_preference = user.preference.all() and then checking for each item in category if it is in saved_preference

I am also blanking out on the way to actually write that into code, and whether this should be done in the view or the template.

What is a good way to update the user preference list?

I was planning on running user.preference.clear() and then going through every item in the submitted form and running user.preference.add(the_new_preference)

Body:
You'll need to pass the complete list of categories and also an index of user-selected categories to your template. You don't need to convert the NewsCategory queryset into a list in your view, by the way:

View

categories = NewsCategory.objects.all()
user_preferences = [item.id for item in Profile.preference.all()]

The user_preferences variable will act as a lookup index for our template.

Then you loop through all the categories in the template, and check to see if it exists in the list of user preferences:

Template

<div id="c_b">
{% for c in categories %}
    <input type="checkbox" name="category[]" id="id_{{ c.category }}" value="{{ c.id }}" {% if c.id in user_preferences %}checked="checked"{% endif %} />
    <label for="id_{{ c.id }}">{{ c.category }}</label>
{% endfor %}
</div>

Update - saving user preferences

There is no hard and fast rule here. The main consideration, as far as I am concerned, would be minimising database hits. You can just clear the user preferences, like you say, and add the new ones - in fact, this is how Django's admin handles it. Just make use of Django's transaction management:

from django.db import transaction

@transaction.commit_manually
def add_preferences(user, preferences):
  user.preference.clear()
  for pref in preferences:
    user.preference.add(pref)
  transaction.commit()


问:
How to create and save file to Files application (iOS platform)
I need to create PDF-file (done) and save it to Files application, so user can access it anytime outside of my app. I tried rn-fetch-blob and react-native-fs packages and they worked fine for Android, but for iOS they can only create files to internal app storage (so files are not created in external storage, i.e. not in iOS Files application).
What options do I have to save my created files to Files application? I know that it is possible, i.g. Slack app allows saving files to Files app.

答:
You have to either add the UISupportsDocumentBrowser key and set to true, or both the UIFileSharingEnabled and LSSupportsOpeningDocumentsInPlace keys in your Info.plist file

When the user will open a document from your app's Documents directory, through Files app, they would be editing the document in place. The changes are saved to your app's Documents directory.

Refer this for more.

ContentLicense: CC BY-SA 4.0


问:
CSS Scroll Snap with Animation Effect
Precondition

I am trying to make a number list picker that user can scroll on it.
The selected number was supposed to snap to the center of the container.
Once a number was selected, it should be enlarged and changed the color.

Problems

How can I snap the first or latest items to the center of the
container?

Is there a CSS or JavaScript way to detect a number is
snapping to the center then assign selected class on it?

Do not rely on any plugins.

* {
  box-sizing: border-box;
  font-family: Roboto, sans-serif;
}

.container {
  display: flex;
  flex-direction: row;
  width: 10rem;
  height: 22rem;
  border-radius: 3rem;
  border: solid 0.2rem #b2b2c2;
  background-color: #000000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.scrollport {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  width: 9.4rem;
  height: 22rem;
  overflow: auto;
  scroll-snap-type: y mandatory;
}

.cell {
  display: block;
  scroll-snap-align: center;
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: 33.3%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #e9e9f2;
  font-size: 2.4rem;
}

.selected {
  font-size: 3rem;
  font-weight: bold;
  color: #0073e6;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="scrollport">
    <div class="cell">09</div>
    <div class="cell selected">10</div>
    <div class="cell">11</div>
    <div class="cell">12</div>
    <div class="cell">13</div>
    <div class="cell">14</div>
    <div class="cell">15</div>
    <div class="cell">16</div>
  </div>
</div></code>```

Expect Result

答:
You can try this code here:

in this answer used jquery malihu-custom-scrollbar-plugin link and update some code here

(function($){
    $(window).on("load",function(){
        $(".scrollport").mCustomScrollbar({autoHideScrollbar:true});
    });
})(jQuery);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  box-sizing: border-box;
  font-family: Roboto, sans-serif;
}

.container {
  display: flex;
  flex-direction: row;
  width: 10rem;
  height: 22rem;
  border-radius: 3rem;
  border: solid 0.2rem #b2b2c2;
  background-color: #000000;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.scrollport {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  width: 9.4rem;
  height: 22rem;
  overflow: auto;
}

.cell {
  flex-basis: 120px;
  height: 120px;
  color: #e9e9f2;
  font-size: 2.4rem;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-left: 20px;
}

.selected {
  font-size: 3rem;
  font-weight: bold;
  color: #0073e6;
}</code>```

<link href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.css" rel="stylesheet" />

09

10

11

12

13

14

15

16

```

Title: CSS Scroll Snap with Animation Effect

Body:
Precondition

I am trying to make a number list picker that user can scroll on it.
The selected number was supposed to snap to the center of the container.
Once a number was selected, it should be enlarged and changed the color.

Problems

How can I snap the first or latest items to the center of the
container?

Is there a CSS or JavaScript way to detect a number is
snapping to the center then assign selected class on it?

Do not rely on any plugins.

* {
  box-sizing: border-box;
  font-family: Roboto, sans-serif;
}

.container {
  display: flex;
  flex-direction: row;
  width: 10rem;
  height: 22rem;
  border-radius: 3rem;
  border: solid 0.2rem #b2b2c2;
  background-color: #000000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.scrollport {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  width: 9.4rem;
  height: 22rem;
  overflow: auto;
  scroll-snap-type: y mandatory;
}

.cell {
  display: block;
  scroll-snap-align: center;
  flex-grow: 1;
  flex-shrink: 0;
  flex-basis: 33.3%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #e9e9f2;
  font-size: 2.4rem;
}

.selected {
  font-size: 3rem;
  font-weight: bold;
  color: #0073e6;
}

09

10

11

12

13

14

15

16

Expect Result

Body:
You can try this code here:

in this answer used jquery malihu-custom-scrollbar-plugin link and update some code here

(function($){
    $(window).on("load",function(){
        $(".scrollport").mCustomScrollbar({autoHideScrollbar:true});
    });
})(jQuery);

* {
  box-sizing: border-box;
  font-family: Roboto, sans-serif;
}

.container {
  display: flex;
  flex-direction: row;
  width: 10rem;
  height: 22rem;
  border-radius: 3rem;
  border: solid 0.2rem #b2b2c2;
  background-color: #000000;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.scrollport {
  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  width: 9.4rem;
  height: 22rem;
  overflow: auto;
}

.cell {
  flex-basis: 120px;
  height: 120px;
  color: #e9e9f2;
  font-size: 2.4rem;
  display: flex;
  align-items: center;
  justify-content: center;
  padding-left: 20px;
}

.selected {
  font-size: 3rem;
  font-weight: bold;
  color: #0073e6;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.css" rel="stylesheet" />

<div class="container">
  <div class="scrollport">
    <div class="cell">09</div>
    <div class="cell selected">10</div>
    <div class="cell">11</div>
    <div class="cell">12</div>
    <div class="cell">13</div>
    <div class="cell">14</div>
    <div class="cell">15</div>
    <div class="cell">16</div>
  </div>
</div>


问:
Based on input selected redirect to new html page on button click
I am new to javascripts. Based on the input selected from the drop downlist I need to redirect to new html page once i click the next button.</p>

```<code>...
<p>Application Type&nbsp
<select id = "aList" name="selection">
<option value = "">---Select Value---</option>
<option value = "New_req_p2_web.html">External Web Application</option>
<option value = "New_req_p2_web.html">Internal Web Application</option>
<option value = "New_req_p2_mob.html">Mobile Application</option>
<option value = "New_req_p2_net.html">Network</option>
</select>
</p>
<button type="submit" id="next" onclick="WinOpen()">Next</button>
....
<script type="text/javascript">
function WinOpen() {
var url=document.redirect.selection.value
document.location.href=url
}
</script>
...
</code>```

答:
You can do something like this:

You will need to make sure the path/value is correct for your htmlpage based on the current page your on, so the values may need to change to something like: ./New_req_p2_web.html

```<code><p>Application Type</p>
<select id="aList" name="selection">
<option value="">---Select Value---</option>
<option value="New_req_p2_web.html">External Web Application</option>
<option value="New_req_p2_web.html">Internal Web Application</option>
<option value="New_req_p2_mob.html">Mobile Application</option>
<option value="New_req_p2_net.html">Network</option>
</select>
<button type="submit" id="next" onclick="WinOpen()">Next</button>

<script type="text/javascript">
//THIS WILL OPEN IN A NEW WINDOW/TAB
function WinOpen() {
    var url = $('#aList').val();
    window.open(url);
}
//THIS WILL OPEN ON ITS SELF - if you use this remove the onclick for the button.
$('#next').click(function () {
     var url = $('#aList').val();
     window.open(url, "_self");
});

</script>
</code>```

Your path will need to be correct for the value, what i mean by this is if this file is in your desktop folder then your 'New_req_p2_web.html' will have to be in the same folder unless you change the pathing of your value.

Body:
I am new to javascripts. Based on the input selected from the drop downlist I need to redirect to new html page once i click the next button.

...

Application Type&nbsp
<select id = "aList" name="selection">
<option value = "">---Select Value---</option>
<option value = "New_req_p2_web.html">External Web Application</option>
<option value = "New_req_p2_web.html">Internal Web Application</option>
<option value = "New_req_p2_mob.html">Mobile Application</option>
<option value = "New_req_p2_net.html">Network</option>
</select>

<button type="submit" id="next" onclick="WinOpen()">Next</button>
....

...

Body:
You can do something like this:

You will need to make sure the path/value is correct for your htmlpage based on the current page your on, so the values may need to change to something like: ./New_req_p2_web.html

<p>Application Type</p>
<select id="aList" name="selection">
<option value="">---Select Value---</option>
<option value="New_req_p2_web.html">External Web Application</option>
<option value="New_req_p2_web.html">Internal Web Application</option>
<option value="New_req_p2_mob.html">Mobile Application</option>
<option value="New_req_p2_net.html">Network</option>
</select>
<button type="submit" id="next" onclick="WinOpen()">Next</button>

<script type="text/javascript">
//THIS WILL OPEN IN A NEW WINDOW/TAB
function WinOpen() {
    var url = $('#aList').val();
    window.open(url);
}
//THIS WILL OPEN ON ITS SELF - if you use this remove the onclick for the button.
$('#next').click(function () {
     var url = $('#aList').val();
     window.open(url, "_self");
});

</script>

Your path will need to be correct for the value, what i mean by this is if this file is in your desktop folder then your 'New_req_p2_web.html' will have to be in the same folder unless you change the pathing of your value.


问:
Nuget packages are not updated even running Update-Package -reinstall
I would like to remove-add updated nuget packages and executed the ff:

```<code>Update-Package
Update-Package -reinstall
Update-Package -reinstall -Project <ProjectName>
Update-Package -Project <ProjectName>
</code>```

None of which satisfied. Yes, they were executed but none of my packages were updated. I have to manually remove them. I don't know if it's Microsoft's scope but these are NOT WORKING..

I'm using VS2017.

答:
Right click on 'ProjectSolution' in Solution Explorer and click on 'Restore Nuget Package'

After restore, you can Update Packages

Body:
I would like to remove-add updated nuget packages and executed the ff:

Update-Package
Update-Package -reinstall
Update-Package -reinstall -Project <ProjectName>
Update-Package -Project <ProjectName>

None of which satisfied. Yes, they were executed but none of my packages were updated. I have to manually remove them. I don't know if it's Microsoft's scope but these are NOT WORKING..

I'm using VS2017.


问:
Saving a blob using FileSaver.js
I use FileSaver.js to save a blob containing some binary data. I construct the blob from ArrayBuffer like this:

```<code>saveAs(new Blob([arr], {type: "application/octet-stream"}), '_test.data');
</code>```

Now the problem is that the resulting file is all zeroes. When I print the content of the ArrayBuffer, the bytes are just OK, it's not an "all-zero" array. Clearly the construction of the blob must be wrong in some way. But according to the documentation, this should be the way to do it. That is, it should be able to accept ArrayBuffer, which should be packed within another array (hence the square brackets) and octet-stream type should stand for binary data. So what am I missing?

Thanks

答:
I dont know how you are creating your binary array because it is working here. You can compare with following code Or provide your code so that we can check

<!DOCTYPE html>

<title>Web Page Design</title>

```

Title: Saving a blob using FileSaver.js

Body:
I use FileSaver.js to save a blob containing some binary data. I construct the blob from ArrayBuffer like this:

saveAs(new Blob([arr], {type: "application/octet-stream"}), '_test.data');

Now the problem is that the resulting file is all zeroes. When I print the content of the ArrayBuffer, the bytes are just OK, it's not an "all-zero" array. Clearly the construction of the blob must be wrong in some way. But according to the documentation, this should be the way to do it. That is, it should be able to accept ArrayBuffer, which should be packed within another array (hence the square brackets) and octet-stream type should stand for binary data. So what am I missing?

Thanks

Body:
I dont know how you are creating your binary array because it is working here. You can compare with following code Or provide your code so that we can check

<!DOCTYPE html>
<html>
<title>Web Page Design</title>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js">
  </script>
  <script>
    document.write("Hello, Coding Ground!");
    var str = "Hello";
    var bytes = []; // char codes
    for (var i = 0; i < str.length; ++i) {
      var code = str.charCodeAt(i);
      bytes = bytes.concat([code]);

    }
    var blob = new Blob(bytes, {
      type: "application/octet-stream"
    });
    saveAs(blob, "_data.data");
  </script>
</head>

<body>
</body>

</html>


问:
I want to change alias about python but I don't khow how
I want to be able to start python3.7.0 if I enter python at the terminal, but I do not know how. If you enter Python as terminal now, python 2.7.6 will be launched.

I think I could solve the problem by changing the alias setting, but I did not know how to change it.

The contents of the corresponding file were [PATH="/usr/local/sbin:/usr/local/bin:usr/sbin:usr/bin:/sbin:/bin"]. How do I change this?

答:
You have to replace your Python 2 with your Python 3 executable on your environment variables. If on Windows, click the search button on your task bar and type environment variables and replace all the Python 2 paths with Python 3 ones.
In Linux Mint, try the below:
Open /etc/environment as root with a text editor:

sudo gedit /etc/environment

Change the desired variable (the one with Python 2) in the text file separated by colon, save, logout, login - and it is permanently and globally changed.


问:
ASP.Net MVC how does back-end know if user signed in
I created a ASP.Net C# MVC app with "Individual User Account" for Authentication + localDB. I started the app in visual studio with IIS express on localhost, signed up an user and logged in with that user.

I am trying to understand how back-end know a user has logged in in the following scenario:

start the iis express & app in visual studio

log in

stop the iis express & app in visual studio

start again the iis express & app in visual studio

user still logged in (WHY???)

I checked the user tables in db, and could not find any fields indicate a logged in user. I am thinking stop & restart iis express should clear everything in the back-end as well.

So how does the back-end know there was an user logged in in the step 5 above??

I found the following cookie in the http request

Cookie: _ga=GA1.1.1546797954.1551225891; __RequestVerificationToken=PSFeb9iP4aZr3wxxb8nJNKtki_1XPTzGO1Hzaf0W3iDsSCnV_qCfMsC9TY980X51c2rANZA-zureu6UHKEssAHza58AdmQUdZVL98VGYlRc1; .AspNet.ApplicationCookie=VUPznoprBRK2z13u03ArrC9HLHeGGUyTSvu9rYpSnZju_Rz4X2V5n9faw0EhnmuFjVN1AIva7HZSAhUBeSZ5jQHSej6XaAExy0hkwF_9vC190LfWBPP-oH3Zp0jj0ZmZ7L3sLlLqux4HV5CZSA-jqhDF4IXAFKyisFFV136PlxrJTmb9OXRrmo9rigCiIy0z_oixDlg1eHVI3T6ptVgn1Qhohtr1mTqoBJsF7gi7CHymSBlyFJ5MgYxfPcWNhJnj3H-WWK1ijkfzxsm0R13m2_6IbIiK1y5uzQBkklb8oMuz0mD27GlwMzteQBP3VLOXn77BreOPefJ8_2AekYjFGjgBIGGpngxLVzDneT4rC-BDiVKdWO_FRuail4ivVAN2ZJtdjK0uEPqnln5rmOlT0MLAhYzHMkk-HTvtW-Xo-Kexinlh58uxz0E7bncY5I6troc19E0fBLMnfXThtaL7ur6CN4pqUyq4yALJCTHszG3RPLQoJja0u1g34i-mKunZ

答:
Following is how authentication works in ASP.NET MVC

Enter Username and password in login form and click on "Login" button

On click of Login button Server side code checks whether entered Username and Password exists in database

If entered Username and Password exists in database then server side code creates cookie and stores them in the browser(not in the database)

On every page request IIS checks whether authentication cookie exists or not.

If cookie exists then user is logged In and if cookie doesn't exist the user is not logged in

Since authentication cookie is stored in browser and not in IIS. Stopping and Starting IIS has no effect on User log in status.

To answer your specific question: So how does the back-end know there was an user logged in in the step 5 above??
Ans: On ever page request from IIS. Along with other information, authentication cookie  stored in browser is sent to back-end/IIS. back-end/IIS then checks whether or not authentication cookie is valid. If cookie is valid back-end/IIS knows user is logged in. If cookie is invalid back-end/IIS knows user is not logged in.

To understand this process further. I would recommend reading about cookies first and then read about authentication in ASP.NET.

Hope this helps!


问:
How can I sort a collection based in the given order in other array
I have a array of ibject with another object inside each element like

```<code>data = [
  {
    name: "A",
    type: "AA",
    children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
    other: "NA"
  },
  {
    name: "B",
    type: "BB",
    children: [ { id: 2, name: "Child-B" }],
    other: "NA"
  },
  {
    name: "C",
    type: "CC",
    children: [ { id: 3, name: "Child-C" }],
    other: "NA"
  }

]
</code>```

I want to order the whole collection by the children.id value but based on the order given by another array

```<code>orderArray = [3, 1, 2]
</code>```

So the output would be

```<code>data =[
    {
        name: "C",
        type: "CC",
        children: [ { id: 3, name: "Child-C" }],
        other: "NA"
    },
    {
        name: "A",
        type: "AA",
        children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
        other: "NA"
    },
    {
        name: "B",
        type: "BB",
        children: [ { id: 2, name: "Child-B" }],
        other: "NA"
    }
]
</code>```

答:
Try this:</p>

```<code>var newdataArray = []

orderArray.forEach(index => {
    newdataArray.push(data[index - 1])
});

data = newdataArray
</code>```

Body:
I have a array of ibject with another object inside each element like

data = [
  {
    name: "A",
    type: "AA",
    children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
    other: "NA"
  },
  {
    name: "B",
    type: "BB",
    children: [ { id: 2, name: "Child-B" }],
    other: "NA"
  },
  {
    name: "C",
    type: "CC",
    children: [ { id: 3, name: "Child-C" }],
    other: "NA"
  }

]

I want to order the whole collection by the children.id value but based on the order given by another array

orderArray = [3, 1, 2]

So the output would be

data =[
    {
        name: "C",
        type: "CC",
        children: [ { id: 3, name: "Child-C" }],
        other: "NA"
    },
    {
        name: "A",
        type: "AA",
        children: [ { id: 1, name: "Child-A", admin: ["Y"] }],
        other: "NA"
    },
    {
        name: "B",
        type: "BB",
        children: [ { id: 2, name: "Child-B" }],
        other: "NA"
    }
]

Body:
Try this:

var newdataArray = []

orderArray.forEach(index => {
    newdataArray.push(data[index - 1])
});

data = newdataArray


问:
Knockout binding for radio button not working initially
I currently have the following HTML...

<input type="radio" style="height: 12px; width: 20px;" name="physTabPregRadio" value="true" data-bind="checked: pregnant.radioBool" />Y
<input type="radio" style="height: 12px; width: 20px;" name="physTabPregRadio" value="false" data-bind="checked: pregnant.radioBool" />N

```

<p>...and the <code>radioBool</code> function is an extension of ko, as defined here...</p>

```ko.observable.radioBool = function () {
    var observable = ko.observable();
    observable.radioBool = ko.computed({
        read: function () {
            if (observable() === true) return 'true';
            else if (observable() === false) return 'false';
            else return 'unknown';
        },
        write: function (v) {
            if (v.toLowerCase() === 'true') observable(true);
            else if (v.toLowerCase() === 'false') observable(false);
            else observable(undefined);
        }
    });
    return observable;
};
```

<p>...and is initialized in the model like this...</p>

```self.pregnant = ko.observable.radioBool();
self.pregnant(false);
```

Upon loading the page, neither radio button is checked, but the span's text is "false". Is there any potential reasons why the Radio Button would not be checked, even though its value is equal to one of the radio button's values?

答:
I ran into a similar issue. Solved it by initializing the observable with a string value instead of a boolean or number.</p>

```<code>self.pregnant('false');
</code>```

Body:
I currently have the following HTML...

<input type="radio" style="height: 12px; width: 20px;" name="physTabPregRadio" value="true" data-bind="checked: pregnant.radioBool" />Y
<input type="radio" style="height: 12px; width: 20px;" name="physTabPregRadio" value="false" data-bind="checked: pregnant.radioBool" />N

...and the radioBool function is an extension of ko, as defined here...

ko.observable.radioBool = function () {
    var observable = ko.observable();
    observable.radioBool = ko.computed({
        read: function () {
            if (observable() === true) return 'true';
            else if (observable() === false) return 'false';
            else return 'unknown';
        },
        write: function (v) {
            if (v.toLowerCase() === 'true') observable(true);
            else if (v.toLowerCase() === 'false') observable(false);
            else observable(undefined);
        }
    });
    return observable;
};

...and is initialized in the model like this...

self.pregnant = ko.observable.radioBool();
self.pregnant(false);

Upon loading the page, neither radio button is checked, but the span's text is "false". Is there any potential reasons why the Radio Button would not be checked, even though its value is equal to one of the radio button's values?

Body:
I ran into a similar issue. Solved it by initializing the observable with a string value instead of a boolean or number.

self.pregnant('false');


问:
How to have a User Account for different entities in Spring JPA?
I'm making a system (using Spring + JPA with MySQL) that shows the best applicants for a certain job offer. The company and the applicants have their respective user account, and with that, they can fill in their personal/company information and their job profile/job offer conditions. With that, the system should match the job conditions (like 3+ years of experience in C) with the applicant's job profile.

My problem is that the User Account is created first, and should be independent, but these two different entities (Applicant and Company), with different attributes, are using it. So if I do something like create an applicant and company in the User Account, one of them will be always null.

How can I solve this? I guess the problem would be something like: how to implement a user account that can hold data from different entities that have different attributes (therefore, can't be grouped)? (In fact, I need one more entity, but I tried to simplify it to illustrate the problem more clearly).

答:
I think, you should make marker interface, like public interface UserAccountable or smth. Implement this interface in your Applicant and Company classes. Then you can make a field in UserAccount class, like private UserAccountable someUser; and throught setters and getters you can assign and get this variable to Applicant or Company.
Hope this helps!


问:
Get the product object from sku and update the price in WooCommerce
How can I update a product by product_id in my functions file?

I tried using the below code but to no success:

```<code>$_pf = new WC_Product_Factory();
$product_id = wc_get_product_id_by_sku( $sku );
$_product = $_pf->get_product($product_id);
$_product->set_price('225');
</code>```

答:
Since WooCommerce 3, new WC_Product_Factory() with get_product() method is deprecated and replaced simply by the function wc_get_product().

To update price, you have to update the price and the regular price (or the price and the sale price)...

Also the save() method is necessary to grab the data at the end.

So to get the WC_Product Object from an existing product SKU and to use on it any available method, do the following:

```<code>$new_price   = '225'; // New price
$_product_id = wc_get_product_id_by_sku( $sku );

if ( $_product_id > 0 ) {
    // Get an instance of the WC_Product Object
    $_product = wc_get_product( $_product_id );

    $_product->set_regular_price($new_price); // Set the regular price
    $_product->set_price($new_price); // Set the price
    $_product->save(); // Save to database and sync
} else {
    // Display an error (invalid Sku
    printf('Invalid sku "%s"… Can not update price.', $sku);
}
</code>```

Tested and works.

Body:
How can I update a product by product_id in my functions file?

I tried using the below code but to no success:

$_pf = new WC_Product_Factory();
$product_id = wc_get_product_id_by_sku( $sku );
$_product = $_pf->get_product($product_id);
$_product->set_price('225');

Body:
Since WooCommerce 3, new WC_Product_Factory() with get_product() method is deprecated and replaced simply by the function wc_get_product().

To update price, you have to update the price and the regular price (or the price and the sale price)...

Also the save() method is necessary to grab the data at the end.

So to get the WC_Product Object from an existing product SKU and to use on it any available method, do the following:

$new_price   = '225'; // New price
$_product_id = wc_get_product_id_by_sku( $sku );

if ( $_product_id > 0 ) {
    // Get an instance of the WC_Product Object
    $_product = wc_get_product( $_product_id );

    $_product->set_regular_price($new_price); // Set the regular price
    $_product->set_price($new_price); // Set the price
    $_product->save(); // Save to database and sync
} else {
    // Display an error (invalid Sku
    printf('Invalid sku "%s"… Can not update price.', $sku);
}

Tested and works.


问:
Codeigniter. How to pass parameters $ _GET in the route.php?
This code $route['basketball'] = "controller/product/?id=7" does not work.

```<code>function product()
{
    echo $_GET['id']  // no output
}
</code>```

How to describe the rules in the route?

答:
Because you are in PHP , you can basically set $_GET and $_REQUEST parameters which are super global variables that can be accessed anywhere in the code.
So you can do a callback and set them there.

For example:

```<code>$route['basketball'] = function(){
  $_GET['id']=$_REQUEST['id'] = 7;
  return "controller/product/";

};
</code>```

Then in your code you can access $_GET['id'] or whatever.

Body:
This code $route['basketball'] = "controller/product/?id=7" does not work.

function product()
{
    echo $_GET['id']  // no output
}

How to describe the rules in the route?

Body:
Because you are in PHP , you can basically set $_GET and $_REQUEST parameters which are super global variables that can be accessed anywhere in the code.
So you can do a callback and set them there.

For example:

$route['basketball'] = function(){
  $_GET['id']=$_REQUEST['id'] = 7;
  return "controller/product/";

};

Then in your code you can access $_GET['id'] or whatever.


问:
Trouble clicking on different links using puppeteer
I've written tiny scripts in node using puppeteer to perform clicks cyclically on the link of different posts from it's landing page of a website.

The site link used within my scripts is a placeholder. Moreover, they are not dynamic. So, puppeteer might be overkill. However, My intention is to learn the logic of clicking.

When I execute my first script, It clicks once and throws the following error as it goes out of the source.

```<code>const puppeteer = require("puppeteer");

(async () => {
    const browser = await puppeteer.launch({headless:false});
    const [page] = await browser.pages();
    await page.goto("https://stackoverflow.com/questions/tagged/web-scraping",{waitUntil:'networkidle2'});
    await page.waitFor(".summary");
    const sections = await page.$$(".summary");

    for (const section of sections) {
        await section.$eval(".question-hyperlink", el => el.click())
    }

    await browser.close();
})();
</code>```

The error the above script encounters:

```<code>(node:9944) UnhandledPromiseRejectionWarning: Error: Execution context was destroyed, most likely because of a navigation.
</code>```

When I execute the following, the script pretends to click once (in reality it is not) and encounters the same error as earlier.

```<code>const puppeteer = require("puppeteer");

(async () => {
    const browser = await puppeteer.launch({headless:false});
    const [page] = await browser.pages();
    await page.goto("https://stackoverflow.com/questions/tagged/web-scraping");

    await page.waitFor(".summary .question-hyperlink");
    const sections = await page.$$(".summary .question-hyperlink");

    for (let i=0, lngth = sections.length; i < lngth; i++) {
        await sections[i].click();
    }

    await browser.close();
})();
</code>```

The error the above one throws:

```<code>(node:10128) UnhandledPromiseRejectionWarning: Error: Execution context was destroyed, most likely because of a navigation.
</code>```

How can I let my script perform clicks cyclically?

答:
Instead of clicking all the links cyclically, I find it better to parse all the links and then navigate to each of them reusing the same browser. Give it a shot:</p>

```<code>const puppeteer = require("puppeteer");

(async () => {
    const browser = await puppeteer.launch({headless:false});
    const [page] = await browser.pages();
    const base = "https://stackoverflow.com"
    await page.goto("https://stackoverflow.com/questions/tagged/web-scraping");
    let links = [];
    await page.waitFor(".summary .question-hyperlink");
    const sections = await page.$$(".summary .question-hyperlink");

    for (const section of sections) {
        const clink = await page.evaluate(el=>el.getAttribute("href"), section);
        links.push(`${base}${clink}`);
    }

    for (const link of links) {
        await page.goto(link);
        await page.waitFor('h1 > a');
    }
    await browser.close();
})();
</code>```

Body:
I've written tiny scripts in node using puppeteer to perform clicks cyclically on the link of different posts from it's landing page of a website.

The site link used within my scripts is a placeholder. Moreover, they are not dynamic. So, puppeteer might be overkill. However, My intention is to learn the logic of clicking.

When I execute my first script, It clicks once and throws the following error as it goes out of the source.

const puppeteer = require("puppeteer");

(async () => {
    const browser = await puppeteer.launch({headless:false});
    const [page] = await browser.pages();
    await page.goto("https://stackoverflow.com/questions/tagged/web-scraping",{waitUntil:'networkidle2'});
    await page.waitFor(".summary");
    const sections = await page.$$(".summary");

    for (const section of sections) {
        await section.$eval(".question-hyperlink", el => el.click())
    }

    await browser.close();
})();

The error the above script encounters:

(node:9944) UnhandledPromiseRejectionWarning: Error: Execution context was destroyed, most likely because of a navigation.

When I execute the following, the script pretends to click once (in reality it is not) and encounters the same error as earlier.

const puppeteer = require("puppeteer");

(async () => {
    const browser = await puppeteer.launch({headless:false});
    const [page] = await browser.pages();
    await page.goto("https://stackoverflow.com/questions/tagged/web-scraping");

    await page.waitFor(".summary .question-hyperlink");
    const sections = await page.$$(".summary .question-hyperlink");

    for (let i=0, lngth = sections.length; i < lngth; i++) {
        await sections[i].click();
    }

    await browser.close();
})();

The error the above one throws:

(node:10128) UnhandledPromiseRejectionWarning: Error: Execution context was destroyed, most likely because of a navigation.

How can I let my script perform clicks cyclically?

Body:
Instead of clicking all the links cyclically, I find it better to parse all the links and then navigate to each of them reusing the same browser. Give it a shot:

const puppeteer = require("puppeteer");

(async () => {
    const browser = await puppeteer.launch({headless:false});
    const [page] = await browser.pages();
    const base = "https://stackoverflow.com"
    await page.goto("https://stackoverflow.com/questions/tagged/web-scraping");
    let links = [];
    await page.waitFor(".summary .question-hyperlink");
    const sections = await page.$$(".summary .question-hyperlink");

    for (const section of sections) {
        const clink = await page.evaluate(el=>el.getAttribute("href"), section);
        links.push(`${base}${clink}`);
    }

    for (const link of links) {
        await page.goto(link);
        await page.waitFor('h1 > a');
    }
    await browser.close();
})();


问:
Preact router: Multiple path names for a same component
Related to this but pertains to Preact Router- Is it possible to use the same component for multiple different routes?

Like <ServiceType path=["/cleaning", "/printing", "/accounting"] />

So that my URL would look like
example.com/cleaning
example.com/printing
example.com/accounting

And they are all handled in the same component <ServiceType />.

Is this possible?

答:
according to this it's not possible because it doesn't work with path ranking.
the recommendation if you really need Regex Match in path is to switch to enroute or React Router.

Also, Note that this is an open defect from 2017,  i wouldn't get much hope its gonna be fixed any time soon..

if you're not into switching lib you will need to do this like so:

```<code><ServiceType path="/cleaning" />
<ServiceType path="/printing" />
<ServiceType path="/accounting" />
</code>```

Body:
according to this it's not possible because it doesn't work with path ranking.
the recommendation if you really need Regex Match in path is to switch to enroute or React Router.

Also, Note that this is an open defect from 2017,  i wouldn't get much hope its gonna be fixed any time soon..

if you're not into switching lib you will need to do this like so:

<ServiceType path="/cleaning" />
<ServiceType path="/printing" />
<ServiceType path="/accounting" />


问:
pagespeed_no_transform attribute not taken in account
I'm using the Nginx PageSpeed module, and got an issue when it comes to images managed with jquery.matchHeight.js. I decided to disable optimization on these specific images, to I added the pagespeed_no_transform attribute (I also tried data-pagespeed-no-transform without success):

```<code><img src="https://example.com/image-icon_300.png" alt="Alt title" pagespeed_no_transform />
</code>```

Unfortunately, PageSpeed does not seem to take this attribute in account. Worse, it purely remove it and do the optimization. Below is the rendered code:

```<code><img src="https://example.com/image-icon_300.png.pagespeed.ce.gkz42_jTc5@2x.png" alt="Alt title" data-pagespeed-url-hash="627608977" onload="pagespeed.CriticalImages.checkImageForCriticality(this);" width="240" height="200">
</code>```

In cas this would be related to my PageSpeed version/configuration, here is my Nginx conf:

```<code># Header X-Page-Speed: 1.13.35.2-0
server {
  # Ansible managed
  pagespeed on;
  pagespeed FileCachePath /var/ngx_pagespeed_cache;

  location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" {
    add_header "" "";
  }
  location ~ "^/pagespeed_static/" { }
  location ~ "^/ngx_pagespeed_beacon$" { }
}
</code>```

答:
For people who are facing the same issue, it appears it's perfectly working!

PageSpeed to several optimisations on images, mainly:

Conversion (to PNG, JPEG or WebP)

Recompression

Resizing

Inlining

Caching

When using the data-pagespeed-no-transform attribute, you're telling PageSpeed to not "transform" your image, but this not mean it won't be cached, and this is why you still see the https://example.com/image-icon_300.png.pagespeed.ce.gkz42_jTc5@2x.png URL.

To know if your image has been transformed, you need to check its URL:

Caching only: image-icon_300.png.pagespeed.ce.gkz42_jTc5@2x.png

Resizing + Caching: 150x150ximage-icon_300.png.pagespeed.ce.gkz42_jTc5@2x.png

Conversion + Resizing + Caching: ximage-icon_300.png.pagespeed.ic.gkz42_jTc5@2x.webp

Inlining: data:image/jpeg;base64,…

Body:
I'm using the Nginx PageSpeed module, and got an issue when it comes to images managed with jquery.matchHeight.js. I decided to disable optimization on these specific images, to I added the pagespeed_no_transform attribute (I also tried data-pagespeed-no-transform without success):

Unfortunately, PageSpeed does not seem to take this attribute in account. Worse, it purely remove it and do the optimization. Below is the rendered code:

In cas this would be related to my PageSpeed version/configuration, here is my Nginx conf:

# Header X-Page-Speed: 1.13.35.2-0
server {
  # Ansible managed
  pagespeed on;
  pagespeed FileCachePath /var/ngx_pagespeed_cache;

  location ~ "\.pagespeed\.([a-z]\.)?[a-z]{2}\.[^.]{10}\.[^.]+" {
    add_header "" "";
  }
  location ~ "^/pagespeed_static/" { }
  location ~ "^/ngx_pagespeed_beacon$" { }
}


问:
mongodb: unrecognized service in Docker
I created my own Docker container that includes the latest version of ubuntu, python3.7 and mongodb.

Dockerfile

```<code>FROM       ubuntu:latest
MAINTAINER Docker

# Update apt-get sources AND install MongoDB
RUN apt-get update && apt-get upgrade -y
RUN apt-get install -y software-properties-common
RUN apt install -y gnupg2
RUN gpg2 --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys F3B1AA8B

# Installation:
RUN add-apt-repository ppa:deadsnakes/ppa

RUN apt-get install -y python3.7

#Mongodb
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6
RUN apt-add-repository 'deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse'

RUN apt-get update

RUN apt-get install -y mongodb-org

# Create the MongoDB data directory
RUN mkdir -p /data/db

# Create the MongoDB data directory
RUN mkdir -p /data/code
RUN mongod --version

RUN mongod --dbpath /data/db --fork --logpath /data/db/log

# COPY some Code to Container
COPY dev /data/code

# Installing pip for python modules
RUN apt-get install -y python3-pip

# Install modules
WORKDIR /data/code/
RUN pip3 install -r requirements.txt

RUN service mongodb start

RUN python3 main.py
RUN python3 server.py

EXPOSE 80

# Set /bin/bash as the dockerized entry-point application
ENTRYPOINT ["/bin/bash"]
</code>```

when I run the build command:
    docker build -t myContainer --no-cache .

it runs successfully till to the point where mongodb should start as a service

```<code>.
.
.
Removing intermediate container 3d43e1d1cd96
 ---> 62f10ce67e07
Step 21/25 : RUN service mongodb start
 ---> Running in 42e08e7d7638
mongodb: unrecognized service
</code>```

How do I start the service? I'm trying to start the service with the command: service mongodb start. Isn't that correct? And what does the line:

```<code>Removing intermediate container 3d43e1d1cd96
</code>```

means?

答:
Firstly, it should be service mongod start i guess. But this is not going to solve your problem.

While using Docker, your process has to be a foreground process service mongod start will go into background & your container will exit immediately.

You should use mongod foreground process as below -

```<code>CMD ["mongod"]
</code>```

Put the above CMD at the end of Dockerfile to make sure your container runs mongod.

Official Dockerfile -

https://github.com/docker-library/mongo/blob/40056ae591c1caca88ffbec2a426e4da07e02d57/3.4/Dockerfile

If you want to run multiple processes, use docker ENTRYPOINT in conjunction with supervisord or use a wrapper script.

Ref - https://docs.docker.com/config/containers/multi-service_container/

Title: mongodb: unrecognized service in Docker

Body:
I created my own Docker container that includes the latest version of ubuntu, python3.7 and mongodb.

Dockerfile

FROM       ubuntu:latest
MAINTAINER Docker

# Update apt-get sources AND install MongoDB
RUN apt-get update && apt-get upgrade -y
RUN apt-get install -y software-properties-common
RUN apt install -y gnupg2
RUN gpg2 --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys F3B1AA8B

# Installation:
RUN add-apt-repository ppa:deadsnakes/ppa

RUN apt-get install -y python3.7

#Mongodb
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6
RUN apt-add-repository 'deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse'

RUN apt-get update

RUN apt-get install -y mongodb-org

# Create the MongoDB data directory
RUN mkdir -p /data/db

# Create the MongoDB data directory
RUN mkdir -p /data/code
RUN mongod --version

RUN mongod --dbpath /data/db --fork --logpath /data/db/log

# COPY some Code to Container
COPY dev /data/code

# Installing pip for python modules
RUN apt-get install -y python3-pip

# Install modules
WORKDIR /data/code/
RUN pip3 install -r requirements.txt

RUN service mongodb start

RUN python3 main.py
RUN python3 server.py

EXPOSE 80

# Set /bin/bash as the dockerized entry-point application
ENTRYPOINT ["/bin/bash"]

when I run the build command:
    docker build -t myContainer --no-cache .

it runs successfully till to the point where mongodb should start as a service

.
.
.
Removing intermediate container 3d43e1d1cd96
 ---> 62f10ce67e07
Step 21/25 : RUN service mongodb start
 ---> Running in 42e08e7d7638
mongodb: unrecognized service

How do I start the service? I'm trying to start the service with the command: service mongodb start. Isn't that correct? And what does the line:

Removing intermediate container 3d43e1d1cd96

means?

Body:
Firstly, it should be service mongod start i guess. But this is not going to solve your problem.

While using Docker, your process has to be a foreground process service mongod start will go into background & your container will exit immediately.

You should use mongod foreground process as below -

CMD ["mongod"]

Put the above CMD at the end of Dockerfile to make sure your container runs mongod.

Official Dockerfile -

https://github.com/docker-library/mongo/blob/40056ae591c1caca88ffbec2a426e4da07e02d57/3.4/Dockerfile

If you want to run multiple processes, use docker ENTRYPOINT in conjunction with supervisord or use a wrapper script.

Ref - https://docs.docker.com/config/containers/multi-service_container/


问:
Check if any of the files within a folder contain a pattern then return filename
I'm writing a script that aim to automate the fulfill of some variables and I'm looking for help to achieve this:

I have a nginx sites-enabled folder which contain some reverses proxied sites.
I need to:

check if a pattern $var1 is found in any of the files in "/volume1/nginx/sites-enabled/"

return the name of the file containing $var1 as $var2

Many thanks for your attention and help!

I have found some lines but none try any files in a folder

```<code>if grep -q $var1 "/volume1/nginx/sites-enabled/testfile"; then
  echo "found"
fi
</code>```

答:
Assuming you have GNU Grep, this will store all files containing the contents of $var1 in an array $var2.

```<code>for file in /volume1/nginx/sites-enabled/*
do
    if grep --fixed-strings --quiet "$var1" "$file"
    then
        var2+=("$file")
    fi
done
</code>```

This will loop through NUL-separated paths:

```<code>while IFS= read -d'' -r -u9 path
do
    …something with "$path"
done 9< <(grep --fixed-strings --files-without-match --recursive "$var1" /volume1/nginx/sites-enabled)
</code>```

Body:
I'm writing a script that aim to automate the fulfill of some variables and I'm looking for help to achieve this:

I have a nginx sites-enabled folder which contain some reverses proxied sites.
I need to:

check if a pattern $var1 is found in any of the files in "/volume1/nginx/sites-enabled/"

return the name of the file containing $var1 as $var2

Many thanks for your attention and help!

I have found some lines but none try any files in a folder

if grep -q $var1 "/volume1/nginx/sites-enabled/testfile"; then
  echo "found"
fi

Body:
Assuming you have GNU Grep, this will store all files containing the contents of $var1 in an array $var2.

for file in /volume1/nginx/sites-enabled/*
do
    if grep --fixed-strings --quiet "$var1" "$file"
    then
        var2+=("$file")
    fi
done

This will loop through NUL-separated paths:

while IFS= read -d'' -r -u9 path
do
    …something with "$path"
done 9< <(grep --fixed-strings --files-without-match --recursive "$var1" /volume1/nginx/sites-enabled)


问:
Why List<Map<? extends Number,? extends Number>> is not working for List<Map<Integer,Double>>
I am iterating through a map whose keys are charts and values are data sets which will be displayed on charts. Data sets are lists of maps because I have multiple XYSeries displayed on each of my Charts (one series - one map with x and y values). In some charts x-axis/y-axis values are Doubles, and in others Integers. Thus, my data sets are type < ? extends Number>. What am I doing wrong?

```<code>for (Map.Entry<Chart, List<Map<? extends Number, ? extends Number>>> entry : tcInstance.getMapChartDataset().entrySet()) {
        switch (entry.getKey().getTitle()) {
            case something:
                entry.setValue(listOfMaps1);
                break;
            case something else:
                entry.setValue(listOfMaps2);
                break;
           // other case options
         }
}
</code>```

These are the declarations of lists of maps:

```<code>static List<Map<Integer, Double>> listOfMaps1 = new ArrayList<>();
static List<Map<Double, Double>> listOfMaps2 = new ArrayList<>();
</code>```

I expected values to be set, but instead I got these errors which tell that the method setValue is not applicable for the arguments (List>) (and the same error for the arguments (List>).

答:
A List<Map<Integer,Double>> is not a List<Map<? extends Number,? extends Number>>.

If it were, I could do this:

```<code>List<Map<Integer,Double>> list = new ArrayList<>();
List<Map<? extends Number,? extends Number>> listX = list;  // Doesn't work, pretend it does.

Map<Double,Integer> map = new HashMap<>();
map.put(0.0, 0);

listX.add(map);

for (Map<Integer, Double> e : list) {
  Integer i = e.keySet().iterator().next();  // ClassCastException!
}
</code>```

You would get a ClassCastException because e has a Double key, not Integer as expected.

Ideone demo

If you add an extra upper bound to the wildcarded list:

```<code>List<? extends Map<? extends Number,? extends Number>>
     ^-------^ here
</code>```

then you wouldn't have been able to add map to listX, so it would be safe.

Body:
I am iterating through a map whose keys are charts and values are data sets which will be displayed on charts. Data sets are lists of maps because I have multiple XYSeries displayed on each of my Charts (one series - one map with x and y values). In some charts x-axis/y-axis values are Doubles, and in others Integers. Thus, my data sets are type < ? extends Number>. What am I doing wrong?

for (Map.Entry<Chart, List<Map<? extends Number, ? extends Number>>> entry : tcInstance.getMapChartDataset().entrySet()) {
        switch (entry.getKey().getTitle()) {
            case something:
                entry.setValue(listOfMaps1);
                break;
            case something else:
                entry.setValue(listOfMaps2);
                break;
           // other case options
         }
}

These are the declarations of lists of maps:

static List<Map<Integer, Double>> listOfMaps1 = new ArrayList<>();
static List<Map<Double, Double>> listOfMaps2 = new ArrayList<>();

I expected values to be set, but instead I got these errors which tell that the method setValue is not applicable for the arguments (List>) (and the same error for the arguments (List>).

Body:
A List<Map<Integer,Double>> is not a List<Map<? extends Number,? extends Number>>.

If it were, I could do this:

List<Map<Integer,Double>> list = new ArrayList<>();
List<Map<? extends Number,? extends Number>> listX = list;  // Doesn't work, pretend it does.

Map<Double,Integer> map = new HashMap<>();
map.put(0.0, 0);

listX.add(map);

for (Map<Integer, Double> e : list) {
  Integer i = e.keySet().iterator().next();  // ClassCastException!
}

You would get a ClassCastException because e has a Double key, not Integer as expected.

Ideone demo

If you add an extra upper bound to the wildcarded list:

List<? extends Map<? extends Number,? extends Number>>
     ^-------^ here

then you wouldn't have been able to add map to listX, so it would be safe.


问:
EF - Save Changes - How to fix VIOLATION OF PRIMARY KEY constraint
I am using Entity Framework to add data into a table in sql.
I have the below class and method to add the new records.
But I am getting the below error.

SqlException: Violation of PRIMARY KEY constraint
  'PK__Users__3214EC27E90BFE7E'. Cannot insert duplicate key in object
  'dbo.Users'. The duplicate key value is (0). The statement has been
  terminated.

```<code>public partial class User
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string Name { get; set; }

    public string Surname { get; set; }

}

    public void InsertUser(MyEvent e)
    {
        using (var db = CreateInstance())
        {
            var users = db.Set<User>();
            users.Add(new User
            {
                Name= e.Name,
                Surname= e.Surname
            });
            db.SaveChanges();
         }
      }
</code>```

How can EF auto-increment the ID in the table?

答:
Remove the DB and just define as:

```<code>public int Id { get; set; }
</code>```

without any Data Annotations

Body:
I am using Entity Framework to add data into a table in sql.
I have the below class and method to add the new records.
But I am getting the below error.

SqlException: Violation of PRIMARY KEY constraint
  'PK__Users__3214EC27E90BFE7E'. Cannot insert duplicate key in object
  'dbo.Users'. The duplicate key value is (0). The statement has been
  terminated.

public partial class User
{
    [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }
    public string Name { get; set; }

    public string Surname { get; set; }

}

    public void InsertUser(MyEvent e)
    {
        using (var db = CreateInstance())
        {
            var users = db.Set<User>();
            users.Add(new User
            {
                Name= e.Name,
                Surname= e.Surname
            });
            db.SaveChanges();
         }
      }

How can EF auto-increment the ID in the table?

Body:
Remove the DB and just define as:

public int Id { get; set; }

without any Data Annotations


问:
How to create a polygon using svg?
I want to create a polygon like in the picture below.

I came across the following polygon but I'm not sure how to make it like in the picture.

html,
body,
svg {
  height: 100%;
  background-color: #000;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="none">
    <polygon fill="white" points="0,100 200,0 300,100"/>
</svg></code>```

But the problem is, I want to top line run parallel to the bottom line. i.e

Also please explain how does the points work like

```<code>points = 'x1 y1, x1 y2, x3 y3, x3,y4'
</code>```

Image:

答:
From MDN:

For <polygon>, points defines a list of points, each representing a vertex of the shape to be drawn. Each point is define by a X and Y coordinate in the user coordinate system

So, you need points="x1,y1 x2,y2 x3,y3 x4,y4" but you have x2 == x1 and x4 == x3, so it's actually points="x1,y1 x1,y2 x3,y3 x3,y4"

Your svg also misses stroke="black" to draw the black border on your white polygon and viewBox could have better coordinates.

Working example below:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" preserveAspectRatio="none">
    <polygon fill="white" stroke="black" points="0,0 0,100 100,150 100,50"/>
</svg>```

Title: How to create a polygon using svg?

Body:
I want to create a polygon like in the picture below.

I came across the following polygon but I'm not sure how to make it like in the picture.

html,
body,
svg {
  height: 100%;
  background-color: #000;
}

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="none">
    <polygon fill="white" points="0,100 200,0 300,100"/>
</svg>

But the problem is, I want to top line run parallel to the bottom line. i.e

Also please explain how does the points work like

points = 'x1 y1, x1 y2, x3 y3, x3,y4'

Image:


问:
How to remove first chracter from the string and store the same into new column in Pandas?
I have a column name called Student name and each row has four or five student names -- like this John mills, Tim Harry, Alex win, Kate marry... I want to take the first two student names and store into a new column called Student 1 and Student 2. Names have been separated from comma.

I created a function and i can able to extract first student name . result storing into my dataframe called student_0

```<code>def find_student(df2):
for i in range(2):
df2[f"student name_{i}"] = [x.split(',')[i] for x in df2["student name"]]
return df2
</code>```

```<code>new_df = find_student(df2)
</code>```

df2 is my dataframe name

I AM NOT GETTING SECOND STUDENT NAME. PLEASE ADVISE

答:
Use Series.str.split with select first 2 columns by positions by DataFrame.iloc if need name and surnames:

```<code>print (df2)
                                   student name
0   John mills, Tim Harry, Alex win, Kate marry
1  Brando XI, James Caan, Richard S. Castellano
2   Heath Ledger, Aaron Eckhart, Michael Caine

N = 2
df3 = df2["student name"].str.split(', ', expand=True).iloc[:, :N]
#rename columns names
df3.columns = [f"student name_{i+1}" for i in range(len(df3.columns))]
print (df3)
  student name_1 student name_2
0     John mills      Tim Harry
1      Brando XI     James Caan
2   Heath Ledger  Aaron Eckhart
</code>```

Or use list comprehension:

```<code>N = 2
L = [x.split(',')[:2] for x in df2["student name"]]
df3 = pd.DataFrame(L, columns=[f"student name_{i+1}" for i in range(N)])
print (df3)
  student name_1  student name_2
0     John mills       Tim Harry
1      Brando XI      James Caan
2   Heath Ledger   Aaron Eckhart
</code>```

If need only names:

```<code>N = 2
L = [[y.split()[0] for y in x.split(',')[:2]] for x in df2["student name"]]
df3 = pd.DataFrame(L, columns=[f"student name_{i+1}" for i in range(N)])
print (df3)
  student name_1 student name_2
0           John            Tim
1         Brando          James
2          Heath          Aaron
</code>```

```<code>#join to original if necessary
df2 = df2.join(df3)
</code>```

Body:
I have a column name called Student name and each row has four or five student names -- like this John mills, Tim Harry, Alex win, Kate marry... I want to take the first two student names and store into a new column called Student 1 and Student 2. Names have been separated from comma.

I created a function and i can able to extract first student name . result storing into my dataframe called student_0

def find_student(df2):
for i in range(2):
df2[f"student name_{i}"] = [x.split(',')[i] for x in df2["student name"]]
return df2

new_df = find_student(df2)

df2 is my dataframe name

I AM NOT GETTING SECOND STUDENT NAME. PLEASE ADVISE

Body:
Use Series.str.split with select first 2 columns by positions by DataFrame.iloc if need name and surnames:

print (df2)
                                   student name
0   John mills, Tim Harry, Alex win, Kate marry
1  Brando XI, James Caan, Richard S. Castellano
2   Heath Ledger, Aaron Eckhart, Michael Caine

N = 2
df3 = df2["student name"].str.split(', ', expand=True).iloc[:, :N]
#rename columns names
df3.columns = [f"student name_{i+1}" for i in range(len(df3.columns))]
print (df3)
  student name_1 student name_2
0     John mills      Tim Harry
1      Brando XI     James Caan
2   Heath Ledger  Aaron Eckhart

Or use list comprehension:

N = 2
L = [x.split(',')[:2] for x in df2["student name"]]
df3 = pd.DataFrame(L, columns=[f"student name_{i+1}" for i in range(N)])
print (df3)
  student name_1  student name_2
0     John mills       Tim Harry
1      Brando XI      James Caan
2   Heath Ledger   Aaron Eckhart

If need only names:

N = 2
L = [[y.split()[0] for y in x.split(',')[:2]] for x in df2["student name"]]
df3 = pd.DataFrame(L, columns=[f"student name_{i+1}" for i in range(N)])
print (df3)
  student name_1 student name_2
0           John            Tim
1         Brando          James
2          Heath          Aaron

#join to original if necessary
df2 = df2.join(df3)


问:
Regex to extract hashtags with two dot-separated parts
I'm trying to create a regular expression in order to extract some text from strings. I want to extract text from urls or normal text messages e.g.:

```<code>endpoint/?userId=#someuser.id
</code>```

OR

```<code>Hi #someuser.name, how are you?
</code>```

And from both I want to extract exactly #someuser.name from message and #someuser.id from url. There might be be many of those string to extract from the url and messages.

My regular expression currently looks like this:

```<code>(#[^\.]+?\.)([^\W]\w+\b)
</code>```

It works fine, except one for one case and I don't know how to do it - e.g.:

Those strings SHOULD NOT be matched: # .id, #.id. There must be at least one character between # and .. One or more spaces between those characters should not be matched.

How can I do it using my current regex?

答:
You can try the following regex:

```<code>#(\w+)\.(\w+)
</code>```

demo

Notes:

remove the parenthesis if you do not want to capture any group.

in your java regex string you need to escape every \

this gives #(\\w+)\\.(\\w+)

if the id is only made of numbers you can change the second \w by [0-9]

if the username include other characters than alphabet, numbers and underscore you have to change \w into a character class with all the authorised characters defined explicitly.

Code sample:

```<code>String input = "endpoint/?userId=#someuser.id Hi #someuser.name, how are you? # .id, #.id.";
Matcher m = Pattern.compile("#(\\w+)\\.(\\w+)").matcher(input);
while (m.find()) {
    System.out.println(m.group());
}
</code>```

output:

```<code>#someuser.id
#someuser.name
</code>```

Body:
I'm trying to create a regular expression in order to extract some text from strings. I want to extract text from urls or normal text messages e.g.:

endpoint/?userId=#someuser.id

OR

Hi #someuser.name, how are you?

And from both I want to extract exactly #someuser.name from message and #someuser.id from url. There might be be many of those string to extract from the url and messages.

My regular expression currently looks like this:

(#[^\.]+?\.)([^\W]\w+\b)

It works fine, except one for one case and I don't know how to do it - e.g.:

Those strings SHOULD NOT be matched: # .id, #.id. There must be at least one character between # and .. One or more spaces between those characters should not be matched.

How can I do it using my current regex?

Body:
You can try the following regex:

#(\w+)\.(\w+)

demo

Notes:

remove the parenthesis if you do not want to capture any group.

in your java regex string you need to escape every \

this gives #(\\w+)\\.(\\w+)

if the id is only made of numbers you can change the second \w by [0-9]

if the username include other characters than alphabet, numbers and underscore you have to change \w into a character class with all the authorised characters defined explicitly.

Code sample:

String input = "endpoint/?userId=#someuser.id Hi #someuser.name, how are you? # .id, #.id.";
Matcher m = Pattern.compile("#(\\w+)\\.(\\w+)").matcher(input);
while (m.find()) {
    System.out.println(m.group());
}

output:

#someuser.id
#someuser.name


问:
Filter array based property value
I have a JSON file containing 13k objects. I need to get only the objects which have the events { name: "Submitted"} property from it. events is an array of objects which contain multiple name properties. Here is a screenshot of how it looks:

{
  "_id": "03c319a5-86d4-4ce6-ba19-1a50584cecb4",
  "_rev": "21-7cb67ebb46c485ff443995fc27bdd950",
  "doctype": "application",
  "events": [{
      "name": "change",
      "time": 1532547503182
    },
    {
      "name": "change",
      "time": 1532547503182
    },
    {
      "name": "submitted",
      "time": 1532547503182
    },
    {
      "name": "edited",
      "time": 1532547503182
    }
  ]
}
```

<p>This is how I get all the object inside the json file:</p>

```$.getJSON("export.json", function(data) {
  var data = [];
  var arrays = data;

  var i;
  for (i = 0; i < arrays.length; i++) {
    console.log(arrays[i]);
  }
});
```

Now I need to push all the objects which have events[name:submitted] I get in arrays[i] into the doc[]. How can I filter the results?

答:
You can filter your array of the object by filter method.

```<code>$.getJSON("export.json", function(data) {
  var data = [];
  var arrays = data;

  var newArray = arrays.filter(function (el) {
    return el.name == 'Submitted';
  });

  console.log(newArray);
});
</code>```

You can also do in one line using ES6 arrow function

```<code>var newArray  = arrays.filter(el => el.name === 'Submitted')
</code>```

Title: Filter array based property value

Body:
I have a JSON file containing 13k objects. I need to get only the objects which have the events { name: "Submitted"} property from it. events is an array of objects which contain multiple name properties. Here is a screenshot of how it looks:

{
  "_id": "03c319a5-86d4-4ce6-ba19-1a50584cecb4",
  "_rev": "21-7cb67ebb46c485ff443995fc27bdd950",
  "doctype": "application",
  "events": [{
      "name": "change",
      "time": 1532547503182
    },
    {
      "name": "change",
      "time": 1532547503182
    },
    {
      "name": "submitted",
      "time": 1532547503182
    },
    {
      "name": "edited",
      "time": 1532547503182
    }
  ]
}

This is how I get all the object inside the json file:

$.getJSON("export.json", function(data) {
  var data = [];
  var arrays = data;

  var i;
  for (i = 0; i < arrays.length; i++) {
    console.log(arrays[i]);
  }
});

Now I need to push all the objects which have events[name:submitted] I get in arrays[i] into the doc[]. How can I filter the results?

Body:
You can filter your array of the object by filter method.

$.getJSON("export.json", function(data) {
  var data = [];
  var arrays = data;

  var newArray = arrays.filter(function (el) {
    return el.name == 'Submitted';
  });

  console.log(newArray);
});

You can also do in one line using ES6 arrow function

var newArray  = arrays.filter(el => el.name === 'Submitted')


问:
SQL Server remote connection using SQL Server Management Studio
I want to connect my SQL Server Management Studio to a remote database.

My question is: what is the right format for server name?

```<code>122.XXX.XXX.XXX\instance,port
</code>```

Any idea?

答: This 122.XXX.XXX.XXX\instance,port format the you have entered is correct, First you enter the server name or IP address, then server instance entered aftre "\"  then port entered and separated by ","</p>

Body:
I want to connect my SQL Server Management Studio to a remote database.

My question is: what is the right format for server name?

122.XXX.XXX.XXX\instance,port

Any idea?


问:
How to know when text is copied from a specific textfield in Objective-C?
I have some textFields which are editable. when user selects its text copy and paste menu items are shown.

I want to know when user taps on the copy. because I want to change the copied text.

Is it possible?

More details:
I want to change the copy of 3 textfields. I want to concatenate all these 3 textfields texts into clipboard when one of the textfields are copied. There are other textfields in this page too but I don't want to do anything for them.

答:
You can get copied string from Clipboard and update to clipboard before paste.</p>

```<code>NotificationCenter.default.addObserver(self, selector: #selector(clipboardChanged),
                                               name: UIPasteboard.changedNotification , object: nil)

@objc func clipboardChanged() {
    if let clipboardString = UIPasteboard.general.string as? String {
        // Update string as per your requirement
        let myString = textfield1.text! + " " + textfield2.text! + " " + textfield3.text! + " Append String"
        textfield1.text = myString
        textfield2.text = myString
        textfield3.text = myString
        print(myString)
    }
}
</code>```

Body:
You can get copied string from Clipboard and update to clipboard before paste.

NotificationCenter.default.addObserver(self, selector: #selector(clipboardChanged),
                                               name: UIPasteboard.changedNotification , object: nil)

@objc func clipboardChanged() {
    if let clipboardString = UIPasteboard.general.string as? String {
        // Update string as per your requirement
        let myString = textfield1.text! + " " + textfield2.text! + " " + textfield3.text! + " Append String"
        textfield1.text = myString
        textfield2.text = myString
        textfield3.text = myString
        print(myString)
    }
}


问:
Is it good practice to use "using" on a new empty DataTable?
I've been rewriting some old code so that the using statement is used for my DataTables, instead of remembering to Dispose each time:

```<code>using (DataTable dt = BLL.GetDataTable()) {
   foreach(DataRow dr in dt.Rows) {
     // iteration logic
   }
}
</code>```

However in one particular case, the DataTable content differs based on a variable, so I create the initial DataTable and then assign the value afterwards:

```<code>DataTable dt = new DataTable();
switch(foo) {
  case bar:
     dt = BLL.GetDataTable(bar);
     break;
  default:
     dt = BLL.GetDataTable();
     break;
}
// iteration logic here
dt.Dispose();
</code>```

Changing this to use using, I have:

```<code>using (DataTable dt = new DataTable()) {
    switch(foo) {
      case bar:
         dt = BLL.GetDataTable(bar);
         break;
      default:
         dt = BLL.GetDataTable();
         break;
    }
    // iteration logic here
}
</code>```

Is that good practice (i.e. creating the empty DataTable with a using statement)?  I don't know why but it doesn't feel quite right.

答:
In your last example, you are only disposing the first DataTable object and not the other that gets assigned.

The using statement is just syntactic sugar for try/finally. You can instead write your last example like:

```<code>DataTable dt;
try
{
    switch (foo)
    {
        case bar:
            dt = BLL.GetDataTable(bar);
            break;
        default:
            dt = BLL.GetDataTable();
            break;
    }
}
finally
{
    dt?.Dispose();
}
</code>```

This will ensure your IDisposable object is always disposed. It is a bit of a weird example in this case though since I don't see why you'd assign a DataTable in the switch and then immediately dispose it.

Body:
I've been rewriting some old code so that the using statement is used for my DataTables, instead of remembering to Dispose each time:

using (DataTable dt = BLL.GetDataTable()) {
   foreach(DataRow dr in dt.Rows) {
     // iteration logic
   }
}

However in one particular case, the DataTable content differs based on a variable, so I create the initial DataTable and then assign the value afterwards:

DataTable dt = new DataTable();
switch(foo) {
  case bar:
     dt = BLL.GetDataTable(bar);
     break;
  default:
     dt = BLL.GetDataTable();
     break;
}
// iteration logic here
dt.Dispose();

Changing this to use using, I have:

using (DataTable dt = new DataTable()) {
    switch(foo) {
      case bar:
         dt = BLL.GetDataTable(bar);
         break;
      default:
         dt = BLL.GetDataTable();
         break;
    }
    // iteration logic here
}

Is that good practice (i.e. creating the empty DataTable with a using statement)?  I don't know why but it doesn't feel quite right.

Body:
In your last example, you are only disposing the first DataTable object and not the other that gets assigned.

The using statement is just syntactic sugar for try/finally. You can instead write your last example like:

DataTable dt;
try
{
    switch (foo)
    {
        case bar:
            dt = BLL.GetDataTable(bar);
            break;
        default:
            dt = BLL.GetDataTable();
            break;
    }
}
finally
{
    dt?.Dispose();
}

This will ensure your IDisposable object is always disposed. It is a bit of a weird example in this case though since I don't see why you'd assign a DataTable in the switch and then immediately dispose it.


答:
You can use filter(), checking each element in the events array to see if the name is equal to submitted:

const object = {
  "_id": "03c319a5-86d4-4ce6-ba19-1a50584cecb4",
  "_rev": "21-7cb67ebb46c485ff443995fc27bdd950",
  "doctype": "application",
  "events": [{
      "name": "change",
      "time": 1532547503182
    },
    {
      "name": "change",
      "time": 1532547503182
    },
    {
      "name": "submitted",
      "time": 1532547503182
    },
    {
      "name": "edited",
      "time": 1532547503182
    }
  ]
}

const filtered  = object.events.filter(obj => obj.name === 'submitted')
console.log(filtered)```

Title: Filter array based property value