问:
show next custom error message if user enter only first input in any row
iam working on form validation, my requirement is show erro message if user did not fill all field in a row. in my page there are two rows every row contains two input fields. when i click submit button when all fields are empty it should show error. page first two inputs working. when user enter first field the next field also mandatory. no need of second row, if user filled first row and also filed second row first field, the second row second field mandatory.
    in this manner is my requirement i have written some code.
    Thanks in advance.

HTML

function crtNewRelease() {
  var versionIpa = document.getElementById("versionIpa");
  var version1Error = document.getElementById("version1Error");
  var selectDevice1 = document.getElementById("selectDevice1");
  var selectDevice1Error = document.getElementById("selectDevice1Error");
  var versionApk = document.getElementById("versionApk");
  var version2Error = document.getElementById("version2Error");
  var selectDevice2 = document.getElementById("selectDevice2");
  var selectDevice2Error = document.getElementById("selectDevice2Error");
  if (sltProject.value == "") {
    sltProject.style.border = "solid 1px red";
    firstNError.textContent = "Select Project";
    firstNError.style.color = "red";
    firstNError.style.marginTop = "10px"
    sltProject.focus();
    return false;
  }
  if (releaseName.value == "") {
    releaseName.style.border = "solid 1px red";
    lastNError.textContent = "Enter Release Name";
    lastNError.style.color = "red";
    lastNError.style.marginTop = "10px"
    releaseName.focus();
    return false;
  }
  var sameCls = document.getElementsByClassName("newformInputs");
  var inputArray = [];
  var result;
  var i = 1
  for (i = 1; i < sameCls.length; i++) {
    result += sameCls[i]
    if (result == 1) {
      version1Error.textContent = "Enter version";
      return false;
    } else {
      version1Error.style.display = "none";
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="createNewRelease" onsubmit="return crtNewRelease();">
  <select class="form-control" id="sltProject">
        <option value="">Select Project</option>
        <option value="one">one</option>
        <option value="two">two</option>
        <option value="three">Domino’s Makeline App</option>
      </select>
  <div id="firstNError" class="firstN"></div>
  <input class="form-control " placeholder="Release Name" type="text" id="releaseName">
  <div id="lastNError" class="firstN"></div>
  <div class="selectPlatform">
    <h6>Select platforms (you can select both)</h6>
    <div class="row">
      <div class="col-md-5">
        <input class="form-control newformInputs" placeholder="Version number" type="text" id="versionIpa" />
        <div id="version1Error" class="firstN"></div>
      </div>
      <div class="col-md-5 ">
        <select class="form-control newformInputs" id="selectDevice1">
              <option value="">Select device</option>
              <option>iPhone</option>
              <option>iPad</option>
            </select>
        <div id="selectDevice1Error" class="selectDevice1Cls"></div>
      </div>
      <div class="col-md-1"> <span> </span></div>
    </div>
    <div class="row">
      <div class="col-md-5 ">
        <input class="form-control newformInputs" placeholder="Version number" type="text" id="versionApk">
        <div id="version2Error" class="firstN"></div>
      </div>
      <div class="col-md-5 ">
        <select class="form-control newformInputs" id="selectDevice2">
              <option value="">Select device</option>
              <option>iPhone</option>
              <option>iPad</option>
            </select>
        <div id="selectDevice2Error" class="selectDevice2Cls"></div>
      </div>
      <div class="col-md-1"> <span></span></div>
    </div>
  </div>
  <div class="btnsRow">
    <button class="btn" type="submit">Create Release</button>
    Cancel
  </div>
</form></code>```

答:
OK i add it to this code.check it!.

```<code><form name="createNewRelease" onsubmit="return crtNewRelease();">
  <select class="form-control" id="sltProject">
        <option value="">Select Project</option>
        <option value="one">one</option>
        <option value="two">two</option>
        <option value="three">Domino’s Makeline App</option>
      </select>
  <div id="firstNError" class="firstN"></div>
  <input class="form-control " placeholder="Release Name" type="text" id="releaseName">
  <div id="lastNError" class="firstN"></div>
  <div class="selectPlatform">
    <h6>Select platforms (you can select both)</h6>
    <div class="row">
      <div class="col-md-5">
        <input class="form-control newformInputs" placeholder="Version number" type="text" id="versionIpa" />
        <div class="error"></div>
      </div>
      <div class="col-md-5 ">
        <select class="form-control newformInputs" id="selectDevice1">
              <option value="">Select device</option>
              <option>iPhone</option>
              <option>iPad</option>
            </select>
        <div class="error"></div>
      </div>
      <div class="col-md-1"> <span> </span></div>
    </div>
    <div class="row">
      <div class="col-md-5 ">
        <input class="form-control newformInputs" placeholder="Version number" type="text" id="versionApk">
        <div class="error"></div>
      </div>
      <div class="col-md-5 ">
        <select class="form-control newformInputs" id="selectDevice2">
              <option value="">Select device</option>
              <option>iPhone</option>
              <option>iPad</option>
            </select>
        <div class="error"></div>
      </div>
      <div class="col-md-1"> <span></span></div>
    </div>
  </div>
  <div class="btnsRow">
    <button class="btn" type="submit">Create Release</button>
    <a href="javascript:void(0)" class="btn btn-primary">Cancel</a>
  </div>
</form>
</code>```

JS :

```<code>function crtNewRelease() {
  var versionIpa = document.getElementById("versionIpa");
  var version1Error = document.getElementById("version1Error");
  var selectDevice1 = document.getElementById("selectDevice1");
  var selectDevice1Error = document.getElementById("selectDevice1Error");
  var versionApk = document.getElementById("versionApk");
  var version2Error = document.getElementById("version2Error");
  var selectDevice2 = document.getElementById("selectDevice2");
  var selectDevice2Error = document.getElementById("selectDevice2Error");
  if (sltProject.value == "") {
    sltProject.style.border = "solid 1px red";
    firstNError.textContent = "Select Project";
    firstNError.style.color = "red";
    firstNError.style.marginTop = "10px"
    sltProject.focus();
    return false;
  }
  if (releaseName.value == "") {
    releaseName.style.border = "solid 1px red";
    lastNError.textContent = "Enter Release Name";
    lastNError.style.color = "red";
    lastNError.style.marginTop = "10px"
    releaseName.focus();
    return false;
  }
  var sameCls = document.getElementsByClassName("newformInputs");
  var inputArray = [];
  var errorPos = [];
  var result;
  var i = 0;
  for (i = 0; i < sameCls.length; i++) {
    result = sameCls[i];
    if (result.value == "" ) {
            errorPos.push(i);
    } else {
      //version1Error.style.display = "none";
    }
  }
  //reset error class
  var listerror = document.getElementsByClassName("error");
  for(var t5 = 0 ; t5 < listerror.length ; t5++ ){
    listerror[t5].textContent = "";
  }
  console.log(errorPos);
  var flag = false;
  if(errorPos.length > 0){
    for (i = 0; i < sameCls.length; i=i+2 ) {

        if(i % 2 == 0){
        console.log(errorPos.indexOf(i));
            if(errorPos.indexOf(i)==-1){
            if(errorPos.indexOf(i+1)==-1){
                flag = true;
            }
            else{
                flag = false;
            }

          }

        }
    }
    if(!flag){
        for(var t2= 0 ; t2 < errorPos.length ; t2++){
      console.log(sameCls[errorPos[t2]]);
        for(var t3 = 0 ; t3 < sameCls[errorPos[t2]].parentNode.childNodes.length; t3++ ){
           if(sameCls[errorPos[t2]].parentNode.childNodes[t3].className == "error"){
              sameCls[errorPos[t2]].parentNode.childNodes[t3].textContent = "Erorr!!";
              sameCls[errorPos[t2]].parentNode.childNodes[t3].style.display = "block";
              return false;
            }
        }
      }

    }
   }
   return false;
}
</code>```

Check It!

Body:
iam working on form validation, my requirement is show erro message if user did not fill all field in a row. in my page there are two rows every row contains two input fields. when i click submit button when all fields are empty it should show error. page first two inputs working. when user enter first field the next field also mandatory. no need of second row, if user filled first row and also filed second row first field, the second row second field mandatory.
    in this manner is my requirement i have written some code.
    Thanks in advance.

HTML

function crtNewRelease() {
  var versionIpa = document.getElementById("versionIpa");
  var version1Error = document.getElementById("version1Error");
  var selectDevice1 = document.getElementById("selectDevice1");
  var selectDevice1Error = document.getElementById("selectDevice1Error");
  var versionApk = document.getElementById("versionApk");
  var version2Error = document.getElementById("version2Error");
  var selectDevice2 = document.getElementById("selectDevice2");
  var selectDevice2Error = document.getElementById("selectDevice2Error");
  if (sltProject.value == "") {
    sltProject.style.border = "solid 1px red";
    firstNError.textContent = "Select Project";
    firstNError.style.color = "red";
    firstNError.style.marginTop = "10px"
    sltProject.focus();
    return false;
  }
  if (releaseName.value == "") {
    releaseName.style.border = "solid 1px red";
    lastNError.textContent = "Enter Release Name";
    lastNError.style.color = "red";
    lastNError.style.marginTop = "10px"
    releaseName.focus();
    return false;
  }
  var sameCls = document.getElementsByClassName("newformInputs");
  var inputArray = [];
  var result;
  var i = 1
  for (i = 1; i < sameCls.length; i++) {
    result += sameCls[i]
    if (result == 1) {
      version1Error.textContent = "Enter version";
      return false;
    } else {
      version1Error.style.display = "none";
    }
  }
}

<form name="createNewRelease" onsubmit="return crtNewRelease();">
  <select class="form-control" id="sltProject">
        <option value="">Select Project</option>
        <option value="one">one</option>
        <option value="two">two</option>
        <option value="three">Domino’s Makeline App</option>
      </select>

  <input class="form-control " placeholder="Release Name" type="text" id="releaseName">

Select platforms (you can select both)

        <input class="form-control newformInputs" placeholder="Version number" type="text" id="versionIpa" />

        <select class="form-control newformInputs" id="selectDevice1">
              <option value="">Select device</option>
              <option>iPhone</option>
              <option>iPad</option>
            </select>

        <input class="form-control newformInputs" placeholder="Version number" type="text" id="versionApk">

        <select class="form-control newformInputs" id="selectDevice2">
              <option value="">Select device</option>
              <option>iPhone</option>
              <option>iPad</option>
            </select>

    <button class="btn" type="submit">Create Release</button>
    Cancel

</form>

Body:
OK i add it to this code.check it!.

<form name="createNewRelease" onsubmit="return crtNewRelease();">
  <select class="form-control" id="sltProject">
        <option value="">Select Project</option>
        <option value="one">one</option>
        <option value="two">two</option>
        <option value="three">Domino’s Makeline App</option>
      </select>
  <div id="firstNError" class="firstN"></div>
  <input class="form-control " placeholder="Release Name" type="text" id="releaseName">
  <div id="lastNError" class="firstN"></div>
  <div class="selectPlatform">
    <h6>Select platforms (you can select both)</h6>
    <div class="row">
      <div class="col-md-5">
        <input class="form-control newformInputs" placeholder="Version number" type="text" id="versionIpa" />
        <div class="error"></div>
      </div>
      <div class="col-md-5 ">
        <select class="form-control newformInputs" id="selectDevice1">
              <option value="">Select device</option>
              <option>iPhone</option>
              <option>iPad</option>
            </select>
        <div class="error"></div>
      </div>
      <div class="col-md-1"> <span> </span></div>
    </div>
    <div class="row">
      <div class="col-md-5 ">
        <input class="form-control newformInputs" placeholder="Version number" type="text" id="versionApk">
        <div class="error"></div>
      </div>
      <div class="col-md-5 ">
        <select class="form-control newformInputs" id="selectDevice2">
              <option value="">Select device</option>
              <option>iPhone</option>
              <option>iPad</option>
            </select>
        <div class="error"></div>
      </div>
      <div class="col-md-1"> <span></span></div>
    </div>
  </div>
  <div class="btnsRow">
    <button class="btn" type="submit">Create Release</button>
    <a href="javascript:void(0)" class="btn btn-primary">Cancel</a>
  </div>
</form>

JS :

function crtNewRelease() {
  var versionIpa = document.getElementById("versionIpa");
  var version1Error = document.getElementById("version1Error");
  var selectDevice1 = document.getElementById("selectDevice1");
  var selectDevice1Error = document.getElementById("selectDevice1Error");
  var versionApk = document.getElementById("versionApk");
  var version2Error = document.getElementById("version2Error");
  var selectDevice2 = document.getElementById("selectDevice2");
  var selectDevice2Error = document.getElementById("selectDevice2Error");
  if (sltProject.value == "") {
    sltProject.style.border = "solid 1px red";
    firstNError.textContent = "Select Project";
    firstNError.style.color = "red";
    firstNError.style.marginTop = "10px"
    sltProject.focus();
    return false;
  }
  if (releaseName.value == "") {
    releaseName.style.border = "solid 1px red";
    lastNError.textContent = "Enter Release Name";
    lastNError.style.color = "red";
    lastNError.style.marginTop = "10px"
    releaseName.focus();
    return false;
  }
  var sameCls = document.getElementsByClassName("newformInputs");
  var inputArray = [];
  var errorPos = [];
  var result;
  var i = 0;
  for (i = 0; i < sameCls.length; i++) {
    result = sameCls[i];
    if (result.value == "" ) {
            errorPos.push(i);
    } else {
      //version1Error.style.display = "none";
    }
  }
  //reset error class
  var listerror = document.getElementsByClassName("error");
  for(var t5 = 0 ; t5 < listerror.length ; t5++ ){
    listerror[t5].textContent = "";
  }
  console.log(errorPos);
  var flag = false;
  if(errorPos.length > 0){
    for (i = 0; i < sameCls.length; i=i+2 ) {

        if(i % 2 == 0){
        console.log(errorPos.indexOf(i));
            if(errorPos.indexOf(i)==-1){
            if(errorPos.indexOf(i+1)==-1){
                flag = true;
            }
            else{
                flag = false;
            }

          }

        }
    }
    if(!flag){
        for(var t2= 0 ; t2 < errorPos.length ; t2++){
      console.log(sameCls[errorPos[t2]]);
        for(var t3 = 0 ; t3 < sameCls[errorPos[t2]].parentNode.childNodes.length; t3++ ){
           if(sameCls[errorPos[t2]].parentNode.childNodes[t3].className == "error"){
              sameCls[errorPos[t2]].parentNode.childNodes[t3].textContent = "Erorr!!";
              sameCls[errorPos[t2]].parentNode.childNodes[t3].style.display = "block";
              return false;
            }
        }
      }

    }
   }
   return false;
}

Check It!


来源: stackexchange

问:
Problems with GULP Watch task. After compiling index.html from PUG, Gulp watch task don't refresh browser
i need help with my gulp tasks.

After compiling index.html from PUG, Gulp watch task don't refresh browser.

This is my watch.js

```<code>var gulp = require('gulp'),
    watch = require('gulp-watch'),
    browserSync = require('browser-sync').create();

gulp.task('watch', function(){
    browserSync.init({
        notify: false,
        server: {
            baseDir: "app"
        }
    });

    watch('./app/index.html', function(){
        browserSync.reload();
    });

    watch('./app/assets/pug/*.pug', function(){
        gulp.start('htmlRefresh');
    });
});

gulp.task('htmlRefresh', ['pug'] ,function(){
    browserSync.reload();
});
</code>```

this is my pug.js

```<code>var gulp = require('gulp'),
    pug =  require('gulp-pug'),
    notify = require('gulp-notify');

gulp.task('pug',function(){
   return gulp.src('./app/assets/pug/*.pug')
   .pipe(pug({ pretty: true }))
   .on('error', notify.onError(function (error) {
    return {
        title: 'Pug',
        message: error.message
    }
}))
   .pipe(gulp.dest('./app'));
});
</code>```

On the output I get compiled HTML code in folder './app/index.html'. Watch task must reload browser:

```<code>watch('./app/index.html', function(){
    browserSync.reload();
});
</code>```

But nothing changes.
Where is the mistake?

答: "browser-sync" only works there is tag "body". When I test this Gulp tasks, I experimented with single html tag, without .</p>

ContentLicense: CC BY-SA 3.0

Body:
i need help with my gulp tasks.

After compiling index.html from PUG, Gulp watch task don't refresh browser.

This is my watch.js

var gulp = require('gulp'),
    watch = require('gulp-watch'),
    browserSync = require('browser-sync').create();

gulp.task('watch', function(){
    browserSync.init({
        notify: false,
        server: {
            baseDir: "app"
        }
    });

    watch('./app/index.html', function(){
        browserSync.reload();
    });

    watch('./app/assets/pug/*.pug', function(){
        gulp.start('htmlRefresh');
    });
});

gulp.task('htmlRefresh', ['pug'] ,function(){
    browserSync.reload();
});

this is my pug.js

var gulp = require('gulp'),
    pug =  require('gulp-pug'),
    notify = require('gulp-notify');

gulp.task('pug',function(){
   return gulp.src('./app/assets/pug/*.pug')
   .pipe(pug({ pretty: true }))
   .on('error', notify.onError(function (error) {
    return {
        title: 'Pug',
        message: error.message
    }
}))
   .pipe(gulp.dest('./app'));
});

On the output I get compiled HTML code in folder './app/index.html'. Watch task must reload browser:

watch('./app/index.html', function(){
    browserSync.reload();
});

But nothing changes.
Where is the mistake?


问:
Java: Printing trailing spaces
I'm a beginner in Java and working on a code that first requires user to enter total number of integers and next the integers themselves. Example input is:

```<code>4
1 4 3 2
</code>```

The code will need to reverse the second input to the following:

```<code>2 3 4 1
</code>```

My solution is as follow:

```<code>public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int arr[] = new int[n];
    for(int arr_i=0; arr_i < n; arr_i++){
        arr[arr_i] = in.nextInt();
    }
    for(int reverse_i=n-1; reverse_i>=0; reverse_i--){
        System.out.print(arr[reverse_i]);
            if(reverse_i != 0){System.out.print(" ");}
    }
}
</code>```

My question is related to the code to add a blank space " " in between the printed numbers. I wonder what other way I can use to get this done? Any suggestion is appreciated, thank you.

答:
First reverse the array and then print it with a for loop. </p>

```<code>import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int arr[] = new int[n];
        for(int arr_i=0; arr_i < n; arr_i++)
        {
            arr[arr_i] = in.nextInt();
        }
        for(int i = 0; i < arr.length / 2; i++)
        {
            int temp = arr[i];
            arr[i] = arr[arr.length - i - 1];
            arr[arr.length - i - 1] = temp;
        }
        for(int i = 0; i < arr.length; i++)
        {
            System.out.print(arr[i]+" ");
        }
    }
}
</code>```

Title: Java: Printing trailing spaces

Body:
I'm a beginner in Java and working on a code that first requires user to enter total number of integers and next the integers themselves. Example input is:

4
1 4 3 2

The code will need to reverse the second input to the following:

2 3 4 1

My solution is as follow:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int arr[] = new int[n];
    for(int arr_i=0; arr_i < n; arr_i++){
        arr[arr_i] = in.nextInt();
    }
    for(int reverse_i=n-1; reverse_i>=0; reverse_i--){
        System.out.print(arr[reverse_i]);
            if(reverse_i != 0){System.out.print(" ");}
    }
}

My question is related to the code to add a blank space " " in between the printed numbers. I wonder what other way I can use to get this done? Any suggestion is appreciated, thank you.

Body:
First reverse the array and then print it with a for loop.

import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int arr[] = new int[n];
        for(int arr_i=0; arr_i < n; arr_i++)
        {
            arr[arr_i] = in.nextInt();
        }
        for(int i = 0; i < arr.length / 2; i++)
        {
            int temp = arr[i];
            arr[i] = arr[arr.length - i - 1];
            arr[arr.length - i - 1] = temp;
        }
        for(int i = 0; i < arr.length; i++)
        {
            System.out.print(arr[i]+" ");
        }
    }
}


问:
Given a set of positive integers <=k and its n subsets , find union of which pairs of subsets give the original set
I have a set A which consists of first p positive integers (1 to p), and I am given n subsets of this set. How can I find how many pair of subsets on union would give the original set A?

Of course this can be done naively by checking the size of the union of each pair and if it is equal to p , the union must make up the set A, but is there a more elegant way of doing this, which reduces the time complexity?

The set_union in c++ has a time complexity of 2*(size(set 1) + size(set 2)) - 1 which is not good for nC2 pairs.

答:
If we need to cope with a worst-case scenario then some ideas about this problem:

I suppose that using of std::bitset without any optimizations would be sufficient for this task because of the much faster union operation. But if not, don't use variable size vectors, use simple p-length 0-1 arrays/vectors or unordered_sets. I don't think variable size vectors without O(1) find operation would be better in worst-case scenarios.

Use heuristics to minimize subsets unions. The simplest heuristic is checking the sizes of subsets. We need only those pairs (A, B) of subsets where size(A) + size(B) >= p.

In addition to heuristics, we can count (in O(n^2)) the frequencies of appearing of every number in subsets. After that, we can check the presence of the numbers in some subset(s) in frequence-increasing order. Also, we can exclude those numbers that appear in every subset.

If you'll fix some subset A (in the outer loop for example) and will find unions with other subsets, you can check only those numbers that do not appear in set A. If the subset A is large enough this can dramatically reduce the number of operations needed.


问:
Generating a recursive sitemap with relative href links
I'm using Flask to expose a local directory of HTML files on a web page.

I am also using a jinja2 to generate the sitemap in the lefthand div of my main endpoint.

I am unable to correctly specify the URL to the endpoint of my subfolders.

As mentioned in the code below, how would I dynamically build a relative link from /docs (i.e. /docs/folder1/subfolder1/SubFolder1Page.html)?
The way I am currently setting the value for href obviously does not work.

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Docs Demo</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
    <div id="container">
        <div class="left_frame">
            <h1>{{ tree.name }}</h1>
            <ul>
            {%- for item in tree.children recursive %}
                <!-- How would I build a relative link from /docs/ i.e. /docs/folder1/subfolder1/SubFolder1Page.html -->
                <li><a href="docs/{{ item.name }}" target="iframe1">{{ item.name }}
                {%- if item.children -%}
                    <ul>{{ loop(item.children) }}</ul>
                {%- endif %}</a></li>
            {%- endfor %}
            </ul>
        </div>
        <div class="right_frame">
            <iframe name="iframe1"></iframe>
        </div>
    </div>
</body>
</html>
</code>```

Folder structure example:

How it looks overall displaying the contents of file1.html:

答:
To add onto the solution of @HEADLESS_0NE:

He added a few more if statements in the for loop, like so:

```<code>       {%- for item in tree.children recursive %}
    ->        {% if '.html' in item.name %}
                <li><a href="docs/{{ item.name }}" target="iframe1">
    ->            {{ item.name.split('/')[-1:][0] }}
                {%- if item.children -%}
                    <ul>{{ loop(item.children) }}</ul>
                {%- endif %}</a></li>
    ->        {% else %}
    ->            <li>{{ item.name }}
    ->            {%- if item.children -%}
    ->                <ul>{{ loop(item.children) }}</ul>
    ->            {%- endif %}</li>
    ->        {% endif %}
        {%- endfor %}
</code>```

Everything with an -> has been changed in the html, I couldn't find what he added in his python or css, but in short:

An if to check if there's a .html in the item.name.

A split on the item.name, so the / gets removed.

An else statement if there's no .html in the item.name.

This basically adds the ul's and the li's in the correct format.

For a more detailed explanation I hope HEADLESS_0NE could provide us of more information what he might've changed in the python script.

Body:
I'm using Flask to expose a local directory of HTML files on a web page.

I am also using a jinja2 to generate the sitemap in the lefthand div of my main endpoint.

I am unable to correctly specify the URL to the endpoint of my subfolders.

As mentioned in the code below, how would I dynamically build a relative link from /docs (i.e. /docs/folder1/subfolder1/SubFolder1Page.html)?
The way I am currently setting the value for href obviously does not work.

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Docs Demo</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">

{{ tree.name }}

            {%- for item in tree.children recursive %}

{{ item.name }}
                {%- if item.children -%}

{{ loop(item.children) }}

                {%- endif %}

            {%- endfor %}

Folder structure example:

How it looks overall displaying the contents of file1.html:

Body:
To add onto the solution of @HEADLESS_0NE:

He added a few more if statements in the for loop, like so:

       {%- for item in tree.children recursive %}
    ->        {% if '.html' in item.name %}
                <li><a href="docs/{{ item.name }}" target="iframe1">
    ->            {{ item.name.split('/')[-1:][0] }}
                {%- if item.children -%}
                    <ul>{{ loop(item.children) }}</ul>
                {%- endif %}</a></li>
    ->        {% else %}
    ->            <li>{{ item.name }}
    ->            {%- if item.children -%}
    ->                <ul>{{ loop(item.children) }}</ul>
    ->            {%- endif %}</li>
    ->        {% endif %}
        {%- endfor %}

Everything with an -> has been changed in the html, I couldn't find what he added in his python or css, but in short:

An if to check if there's a .html in the item.name.

A split on the item.name, so the / gets removed.

An else statement if there's no .html in the item.name.

This basically adds the ul's and the li's in the correct format.

For a more detailed explanation I hope HEADLESS_0NE could provide us of more information what he might've changed in the python script.


问:
C# Split Date and Time format into Datatable
I have a CSV with a server log. I need to split the date/time format as attached image into my datatable.

Sample of CSV txt file

10.115.10.74 - - [20/Mar/2016:03:38:14 +0800] "GET /portal/images/banners/iot.jpg HTTP/1.1" 404 918 "http://www.utem.edu.my/portal/" "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0"

172.16.75.219 - - [20/Mar/2016:03:38:17 +0800] "GET / HTTP/1.1" 200 98 "http://192.168.0.1:8090/httpclient.html" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36"

Is there any way I can do to achieve something like this?

What I have tried so far

```<code>string[] raw_text = System.IO.File.ReadAllLines("C:\\log4.csv");

string[] data_col = null;

int x = 0;
foreach (string text_line in raw_text)
{
    //MessageBox.Show(text_line);
    data_col = text_line.Split(' ', '<', '>', '[', ']', '-', '"', ';', '(', ')', '+', ':');

    if (x == 1)
    {
        for (int i = 0; i <= data_col.Count() - 1; i++)
        {
            my_datatable.Columns.Add(data_col[i]);
        }

        x++;
    }
    else
    {

        my_datatable.Rows.Add(data_col);
    }
</code>```

答:
You can do it this way; This is a skeleton. You will need to loop through, (or use linq) to convert dates. Make below code a function and pass the date as a parameter.</p>

```<code>    var parts = ("20/Mar/2016:03:38:17 +800").Split(':').ToList();
    var datePart = parts[0];
    var timePart = parts.Except(new[]{datePart});
    var timeString = string.Join(":", timePart);
    var time = timeString.Split('+')[0];
    var gmt = "+" + timeString.Split('+')[1];
    Console.WriteLine(datePart);
    Console.WriteLine(time);
    Console.WriteLine(gmt);
</code>```

Body:
I have a CSV with a server log. I need to split the date/time format as attached image into my datatable.

Sample of CSV txt file

10.115.10.74 - - [20/Mar/2016:03:38:14 +0800] "GET /portal/images/banners/iot.jpg HTTP/1.1" 404 918 "http://www.utem.edu.my/portal/" "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0"

172.16.75.219 - - [20/Mar/2016:03:38:17 +0800] "GET / HTTP/1.1" 200 98 "http://192.168.0.1:8090/httpclient.html" "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36"

Is there any way I can do to achieve something like this?

What I have tried so far

string[] raw_text = System.IO.File.ReadAllLines("C:\\log4.csv");

string[] data_col = null;

int x = 0;
foreach (string text_line in raw_text)
{
    //MessageBox.Show(text_line);
    data_col = text_line.Split(' ', '<', '>', '[', ']', '-', '"', ';', '(', ')', '+', ':');

    if (x == 1)
    {
        for (int i = 0; i <= data_col.Count() - 1; i++)
        {
            my_datatable.Columns.Add(data_col[i]);
        }

        x++;
    }
    else
    {

        my_datatable.Rows.Add(data_col);
    }

Body:
You can do it this way; This is a skeleton. You will need to loop through, (or use linq) to convert dates. Make below code a function and pass the date as a parameter.

    var parts = ("20/Mar/2016:03:38:17 +800").Split(':').ToList();
    var datePart = parts[0];
    var timePart = parts.Except(new[]{datePart});
    var timeString = string.Join(":", timePart);
    var time = timeString.Split('+')[0];
    var gmt = "+" + timeString.Split('+')[1];
    Console.WriteLine(datePart);
    Console.WriteLine(time);
    Console.WriteLine(gmt);


问:
Can c declare two function with the same name, return type but different parameters
Why the following code can be compiled by gcc

```<code>#include <stdio.h>
int func();
int func(int a) { return 1; }
int main() {
   func(10);
   return 0;
}
</code>```

But if i add char func();, gcc say conflicting types for ‘func’

答:
Your first declaration is K&R declaration, while the next declaration (with definition) is ANSI prototype.

It is possible to make any combination between KR decl and ANSI prototypes, if they are compatible .

The C type checker will combine both and will keep the ANSI prototype.  This is called the composite type.

Here is how the composite type is computed for the combination between ANSI and K&R decl:

6.2.7 Compatible type and composite type

3 ... If only one type is a function type with a parameter type list (a
  function prototype), the composite type is a function prototype with
  the parameter type list.

To check whether 2 function declarations are compatible one must apply the rules from 6.7.6.3 Function declarators

15 For two function types to be compatible, both shall specify
  compatible return types.146) Moreover, the parameter type lists, if
  both are present, shall agree in the number of parameters and in use
  of the ellipsis terminator; corresponding parameters shall have
  compatible types.

This is why your prototype can be combined with K&R decl, as they are considered compatibles.

Body:
Why the following code can be compiled by gcc

#include <stdio.h>
int func();
int func(int a) { return 1; }
int main() {
   func(10);
   return 0;
}

But if i add char func();, gcc say conflicting types for ‘func’


问:
String length changes suddenly
Here in this code, the character length is changing suddenly. Before introducing char file the strlen(str) was correct. As I introduced the new char file the strlen value of variable str changes.

```<code>#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

int main(){

    char buf[BUFSIZ];

    if(!getcwd(buf,BUFSIZ)){
            perror("ERROR!");
    }

    cout << buf << endl;

    char *str;
    str = new char[strlen(buf)];
    strcpy(str,buf);
    strcat(str,"/");
    strcat(str,"input/abcdefghijklmnop");
    cout << str << endl;
    cout << strlen(str) << endl;

    char *file;
    file = new char[strlen(str)];
    cout << strlen(file) << endl;
    strcpy(file,str);
    cout << file << endl;
}
</code>```

答:
Your code has undefined behavior because of buffer overflow. You should be scared.

You should consider using std::string.

```<code>  std::string sbuf;
  {
      char cwdbuf[BUFSIZ];
      if (getcwd(cwdbuf, sizeof(cwdbuf))
        sbuf = cwdbuf;
      else {
        perror("getcwd");
        exit(EXIT_FAILURE);
      }
 }
 sbuf += "/input/abcdefghijklmnop";
</code>```

You should compile with all warnings & debug info (e.g. g++ -Wall -Wextra -g) then use the debugger gdb. Don't forget that strings are zero-byte terminated. Your str is much too short. If you insist on avoiding std::string (which IMHO you should not), you need to allocate more space (and remember the extra zero byte).

```<code>str = new char[strlen(buf)+sizeof("/input/abcdefghijklmnop")];
strcpy(str, buf);
strcat(str, "/input/abcdefghijklmnop");
</code>```

Remember that the sizeof some literal string is one byte more than its length (as measured by strlen). For instance sizeof("abc") is 4.

Likewise your file variable is one byte too short (missing space for the terminating zero byte).

```<code>file = new char[strlen(str)+1];
</code>```

BTW on GNU systems (such as Linux) you could use asprintf(3) or strdup(3) (and use free not delete to release the memory) and consider using valgrind.

Title: String length changes suddenly

Body:
Here in this code, the character length is changing suddenly. Before introducing char file the strlen(str) was correct. As I introduced the new char file the strlen value of variable str changes.

#include <unistd.h>
#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;

int main(){

    char buf[BUFSIZ];

    if(!getcwd(buf,BUFSIZ)){
            perror("ERROR!");
    }

    cout << buf << endl;

    char *str;
    str = new char[strlen(buf)];
    strcpy(str,buf);
    strcat(str,"/");
    strcat(str,"input/abcdefghijklmnop");
    cout << str << endl;
    cout << strlen(str) << endl;

    char *file;
    file = new char[strlen(str)];
    cout << strlen(file) << endl;
    strcpy(file,str);
    cout << file << endl;
}

Body:
Your code has undefined behavior because of buffer overflow. You should be scared.

You should consider using std::string.

  std::string sbuf;
  {
      char cwdbuf[BUFSIZ];
      if (getcwd(cwdbuf, sizeof(cwdbuf))
        sbuf = cwdbuf;
      else {
        perror("getcwd");
        exit(EXIT_FAILURE);
      }
 }
 sbuf += "/input/abcdefghijklmnop";

You should compile with all warnings & debug info (e.g. g++ -Wall -Wextra -g) then use the debugger gdb. Don't forget that strings are zero-byte terminated. Your str is much too short. If you insist on avoiding std::string (which IMHO you should not), you need to allocate more space (and remember the extra zero byte).

str = new char[strlen(buf)+sizeof("/input/abcdefghijklmnop")];
strcpy(str, buf);
strcat(str, "/input/abcdefghijklmnop");

Remember that the sizeof some literal string is one byte more than its length (as measured by strlen). For instance sizeof("abc") is 4.

Likewise your file variable is one byte too short (missing space for the terminating zero byte).

file = new char[strlen(str)+1];

BTW on GNU systems (such as Linux) you could use asprintf(3) or strdup(3) (and use free not delete to release the memory) and consider using valgrind.


问:
How to use declared variable for SQL statement by using "IN" condition
I am trying to write some code but it doesn't work. It only those TypeT description. How can I display the TypeT and TypeS condition for below case?

```<code>DECLARE @PaymentType VARCHAR(20) = '';

SELECT @PaymentType = LISTID
FROM LIST
WHERE LISTCONFIG IN ('TypeT', 'TypeS')

SELECT *
FROM LIST
WHERE LISTID IN  (@PaymentType)
</code>```

答:
Try:

```<code>SELECT *
FROM LIST
WHERE
    LISTID IN  (SELECT LISTID FROM LIST WHERE LISTCONFIG IN ('TypeT','TypeS'))
</code>```

However, I think that this is still too complex. Have you tried:

```<code>SELECT *
FROM LIST WHERE LISTCONFIG IN ('TypeT','TypeS')
</code>```

Body:
I am trying to write some code but it doesn't work. It only those TypeT description. How can I display the TypeT and TypeS condition for below case?

DECLARE @PaymentType VARCHAR(20) = '';

SELECT @PaymentType = LISTID
FROM LIST
WHERE LISTCONFIG IN ('TypeT', 'TypeS')

SELECT *
FROM LIST
WHERE LISTID IN  (@PaymentType)

Body:
Try:

SELECT *
FROM LIST
WHERE
    LISTID IN  (SELECT LISTID FROM LIST WHERE LISTCONFIG IN ('TypeT','TypeS'))

However, I think that this is still too complex. Have you tried:

SELECT *
FROM LIST WHERE LISTCONFIG IN ('TypeT','TypeS')


问:
Periodic timeouts when using HttpWebRequest
I have some code that send a simple xml web request. It is called from a windows service. Sometimes the service starts throwing exceptions (System.Net.WebException: The operation has timed out) and a restart of the service fixes the issue. Here is the code:

```<code>    public bool PerformXmlRequest(string xml)
    {
        var httpRequest = (HttpWebRequest)WebRequest.Create(_url);

        httpRequest.Method = "POST";

        httpRequest.ContentType = "text/xml";

        using (var xmlWriter = new StreamWriter(httpRequest.GetRequestStream(), Encoding.UTF8))
        {
            xmlWriter.WriteLine(xml);
        }

        using (var httpResponse = (HttpWebResponse)httpRequest.GetResponse())
        {
            return httpResponse.StatusDescription == "OK";
        }
    }
</code>```

Is there anything obviously wrong with it that might be causing this issue?

答:
There is nothing I can find is wrong with the calling code.

Is the error generated by client side code or does it come from the service?

If it is from the service it's the service that needs to be fixed, idéaly the service should never timeout no matter what you send it, it should fail in a more controlled maner giving a beter error message.

ContentLicense: CC BY-SA 2.5

Body:
I have some code that send a simple xml web request. It is called from a windows service. Sometimes the service starts throwing exceptions (System.Net.WebException: The operation has timed out) and a restart of the service fixes the issue. Here is the code:

    public bool PerformXmlRequest(string xml)
    {
        var httpRequest = (HttpWebRequest)WebRequest.Create(_url);

        httpRequest.Method = "POST";

        httpRequest.ContentType = "text/xml";

        using (var xmlWriter = new StreamWriter(httpRequest.GetRequestStream(), Encoding.UTF8))
        {
            xmlWriter.WriteLine(xml);
        }

        using (var httpResponse = (HttpWebResponse)httpRequest.GetResponse())
        {
            return httpResponse.StatusDescription == "OK";
        }
    }

Is there anything obviously wrong with it that might be causing this issue?


问:
Why can't I get separate documents in my xpages repeat control?
I've done this before for other projects, but can't seem to get this to work this time.

I have a repeat control that returns a list of several unids.  A panel within the repeat is bound to a NotesDocument which opens the document based on each unid.  ignoreRequestParams=true on the panel.  Simple enough.  Except, it doesn't work.

```<code><xp:panel id="panelDetail">
    <xp:this.data>
        <xp:dominoDocument var="detdoc"
            formName="QuoteDetail" documentId="#{javascript:detdata}"
            ignoreRequestParams="true" action="openDocument">
        </xp:dominoDocument>
    </xp:this.data>
</code>```

where detdata is the var from the parent repeat control (the unid).

One of my links within the panel checks to see if my document (detdoc) is editable, however, this is the error I get.

```<code>Error calling method 'isEditable()' on an object of type 'lotus.domino.local.Document [Static Java Interface Wrapper, lotus.domino.local.Document: lotus.domino.Document]'
</code>```

what gives?

I have several edit boxes in the panel that are bound to fields in the detdoc and they appear to show correctly - each row shows different values, but my computed fields that use detdoc.getItemValueString("fieldname") all show the value from the first document.  ???

pic of my repeat

I've checked the properties and compared it to a previous working project and just can't put my finger on my problem here.  Can someone point me in the right direction?

答:
Your isEditable() check appears to be being performed against the backend document (lotus.domino.local.Document), not the dominoDocument datasource. Please check the relevant component.

If your logging doesn't identify that, use XPages OpenLog Logger from OpenNTF, which will output the error and the relevant component to an OpenLog database (download OpenLog database itself from the separate OpenLog project on OpenNTF - XPages OpenLog Logger is just the XPages extension library to perform the logging).

Body:
I've done this before for other projects, but can't seem to get this to work this time.

I have a repeat control that returns a list of several unids.  A panel within the repeat is bound to a NotesDocument which opens the document based on each unid.  ignoreRequestParams=true on the panel.  Simple enough.  Except, it doesn't work.

<xp:panel id="panelDetail">
    <xp:this.data>
        <xp:dominoDocument var="detdoc"
            formName="QuoteDetail" documentId="#{javascript:detdata}"
            ignoreRequestParams="true" action="openDocument">
        </xp:dominoDocument>
    </xp:this.data>

where detdata is the var from the parent repeat control (the unid).

One of my links within the panel checks to see if my document (detdoc) is editable, however, this is the error I get.

Error calling method 'isEditable()' on an object of type 'lotus.domino.local.Document [Static Java Interface Wrapper, lotus.domino.local.Document: lotus.domino.Document]'

what gives?

I have several edit boxes in the panel that are bound to fields in the detdoc and they appear to show correctly - each row shows different values, but my computed fields that use detdoc.getItemValueString("fieldname") all show the value from the first document.  ???

pic of my repeat

I've checked the properties and compared it to a previous working project and just can't put my finger on my problem here.  Can someone point me in the right direction?


问:
unable to insert users registration details into the database
i cannot insert users into database after registration, i have done all i can but was not successful, i really neddd help here, please i want to know and what am doing wrong in my script.

this is my registration html script:

```<code><span class='details' ><h1><bold>ENTER YOUR DETAILS HERE</bold></h1></span>

  <form action="trotle.php"  method="POST">

              <div class="form-group" style="margin-left:50px;color:#000099; font-family:times;">
              <input type="hidden" class="form-control" name="id" placeholder="enter your id" required />
                </div><br>

               <div class="form-group" style="margin-left:50px;color:#000099; font-family:times;">

              <label>fullname</label>

                  <input type="text" class="form-control" name="fullname" placeholder="Enter your fullname" required />
                </div><br>

                <div class="form-group" style="margin-left:50px;color:#000099; font-family:times;">

              <label>username</label>

                  <input type="username" class="form-control" name="username" placeholder="Enter your username" required />
                </div><br>

                <div class="form-group" >
                   <label>password</label>

                 <input type="password" class="form-control" name="password"  placeholder="type in your password" required />
                </div>

              <br>
              <div class="form-group" style="margin-left:50px;color:#000099; font-family:times;" />
                <label>email</label>

                  <input type="email" class="form-control" name="email"  placeholder="Enter your email" required />
                </div><br>

                <div class="form-group" style="margin-left:50px;color:#000099; font-family:times;">
                <label>country</label>

                  <input type="text" class="form-control" name="country"  placeholder="Enter your country" required />
                </div><br>

                <div class="form-group" style="margin-left:50px;color:#000099; font-family:times;">
                <label>phone number</label>

                  <input type="number" class="form-control" name="phonenumber"  placeholder="Enter your phonenumber" required />
                </div><br>

                <div class="form-group" style="margin-left:50px;color:#000099; font-family:times;">
                <label>Alternative phone number</label>

                  <input type="number" class="form-control" name="alternativephonenumber"  placeholder="Enter your alternative phonenumber" required />
                </div><br>

              <div class="form-group"  style="margin-left:50px;color:#000099; font-family:times;">
                <label>referrer</label>
                  <input type="text" class="form-control" name="referrer" placeholder="type in who referred you here" required />
                </div><br>

              <div class="form-group"  style="margin-left:50px;color:#000099; font-family:times;"">
                <label>paymentmode</label>

                  <select name="paymentmode" class="form-control" required />
<option value="">Select your paymentmode</option>
<option value="bitcoin">bitcoin</option>
<option value="perfectmoney">perfectmoney</option>
<option value="naira">naira</option>

                  </select>

                </div>
                <br>

           <div class="form-group" style='text-align: center;padding-top: 30px;'>

              <input type="checkbox" style=" vertical-align: sub; margin-left: 120px;margin-bottom: -15px; " required><a href="homepage.php">  I agree with </a><a href='../terms' target="_blank">Terms and conditions</a><br>
              <input type="submit" class="btn btn-success" name="submit_signup" value='REGISTER' style="margin-left:145px;border:none; margin-bottom: -10px; background-color: green; font-weight: bold;border-style: dotted;">
              <a href="trotle.php"><input type="post" class="btn btn-success" value='LOGIN' style="margin-left:140px;background-color: green; font-weight: bold;border-style: dotted; border-color:black ;padding: 5px; size:20px; margin-bottom:-10px;"></a>
              </div>
              <br>
              <?php

              ?>
              </form>
</code>```

my php script for inserting users into database is below;

```<code><?php
$id=$fullname=$username=$password=$email=$country= $phonenumber=$alternativephonenumber=$referrer=$paymentmode="";
if(isset($_POST) && array_key_exists('submit_signup',$_POST))
{
$id= $_POST['id'];
if(isset($_POST['id'])){
$id= $_POST['id'];

}
$fullname=$_POST['fullname'];
if(isset($_POST['fullname'])){
$fullname= $_POST['fullname'];
}
else{
    echo 'please enter your fullname';
}
$username= $_POST['username'];
if(isset($_POST['username'])){
$username= $_POST['username'];
}
else{
    echo 'enter your username';
}
$password= $_POST['password'];
if(isset($_POST['password'])){
$password= $_POST['password'];
}
else{
    echo 'enter your password';
}
$email= $_POST['email'];
if(isset($_POST['email'])){
$email= $_POST['email'];
}
else{
    echo 'enter your email';
}
$country= $_POST['country'];
if(isset($_POST['country'])){
$country= $_POST['country'];
}
else{
    echo 'enter your country';
}
$phonenumber= $_POST['phonenumber'];
if(isset($_POST['phonenumber'])){
$phonenumber= $_POST['phonenumber'];
}
else{
    echo 'enter your phonenumber';
}
$alternativephonenumber= $_POST['alternativephonenumber'];
if(isset($_POST['alternativephonenumber'])){
$alternativephonenumber= $_POST['alternativephonenumber'];
}
else{
    echo 'enter your alternativephonenumber';
}
$referrer= $_POST['referrer'];
if(isset($_POST['referrer'])){
$referrer= $_POST['referrer'];
}
else{
    echo 'enter your referrer';
}
$paymentmode= $_POST['paymentmode'];
if(isset($_POST['paymentmode'])){
$paymentmode= $_POST['paymentmode'];
}
else{var_dump($_POST['id']);
    echo 'enter your paymentmode';
}
}
    else {
        echo 'nah';

    }

    $serverhost='localhost';
$serverdb='charles';
$serveruser='root';
$serverpassword='';

try{
    $connect= new PDO("mysql:host=$serverhost;dbname=charles;" , $serveruser, $serverpassword);
 $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     }
      catch( PDOException $e)
        {
            echo $e->getmessage();
        }

     if($connect){
        echo 'database successful!';
     }

$sql="INSERT INTO users(id, fullname, username, password, email, country, phonenumber, alternativephonenumber, referrer, paymentmode)VALUES(:id, :fullname, :username, :password, :email, :country, :phonenumber, :alternativephonenumber, :referrer, :paymentmode)";

$query=$connect->prepare($sql);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->bindParam(':fullname', $fullname, PDO::PARAM_STR);
$query->bindParam(':username', $username, PDO::PARAM_STR);
$query->bindParam(':password', $password, PDO::PARAM_STR);
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':country', $country, PDO::PARAM_STR);
$query->bindParam(':phonenumber', $phonenumber, PDO::PARAM_INT);
$query->bindParam(':alternativephonenumber', $alternativephonenumber, PDO::PARAM_INT);
$query->bindParam(':referrer', $referrer, PDO::PARAM_STR);
$query->bindParam(':paymentmode', $paymentmode, PDO::PARAM_STR);
$query->execute();

?>
</code>```

答:
Change you PHP script like this and try, if you not getting the error it might be your validation is wrong

```<code>$id=$fullname=$username=$password=$email=$country= $phonenumber=$alternativephonenumber=$referrer=$paymentmode="";
if(isset($_POST['submit_signup']))  //simplified validation
{

if(isset($_POST['id'])){
$id= $_POST['id'];

}

if(isset($_POST['fullname'])){
$fullname= $_POST['fullname'];
}
else{
    echo 'please enter your fullname';
}

if(isset($_POST['username'])){
$username= $_POST['username'];
}
else{
    echo 'enter your username';
}

if(isset($_POST['password'])){
$password= $_POST['password'];
}
else{
    echo 'enter your password';
}

if(isset($_POST['email'])){
$email= $_POST['email'];
}
else{
    echo 'enter your email';
}

if(isset($_POST['country'])){
$country= $_POST['country'];
}
else{
    echo 'enter your country';
}

if(isset($_POST['phonenumber'])){
$phonenumber= $_POST['phonenumber'];
}
else{
    echo 'enter your phonenumber';
}

if(isset($_POST['alternativephonenumber'])){
$alternativephonenumber= $_POST['alternativephonenumber'];
}
else{
    echo 'enter your alternativephonenumber';
}

if(isset($_POST['referrer'])){
$referrer= $_POST['referrer'];
}
else{
    echo 'enter your referrer';
}

if(isset($_POST['paymentmode'])){
$paymentmode= $_POST['paymentmode'];
}
else{var_dump($_POST['id']);
    echo 'enter your paymentmode';
}
}
    else {
        echo 'nah';

    }

    $serverhost='localhost';
$serverdb='charles';
$serveruser='root';
$serverpassword='';

try{
    $connect= new PDO("mysql:host=$serverhost;dbname=$serverdb;" , $serveruser, $serverpassword);
 $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     }
      catch( PDOException $e)
        {
            echo $e->getmessage();
        }

     if($connect){
        echo 'database successful!';
     }

$sql="INSERT INTO users(id, fullname, username, password, email, country, phonenumber, alternativephonenumber, referrer, paymentmode)VALUES(:id, :fullname, :username, :password, :email, :country, :phonenumber, :alternativephonenumber, :referrer, :paymentmode)";

$query=$connect->prepare($sql);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->bindParam(':fullname', $fullname, PDO::PARAM_STR);
$query->bindParam(':username', $username, PDO::PARAM_STR);
$query->bindParam(':password', $password, PDO::PARAM_STR);
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':country', $country, PDO::PARAM_STR);
$query->bindParam(':phonenumber', $phonenumber, PDO::PARAM_INT);
$query->bindParam(':alternativephonenumber', $alternativephonenumber, PDO::PARAM_INT);
$query->bindParam(':referrer', $referrer, PDO::PARAM_STR);
$query->bindParam(':paymentmode', $paymentmode, PDO::PARAM_STR);
$query->execute();
</code>```

Changes made:

Simplified the validation

Removed unnecessary assignment of variables, if you are using isset then don't assign it out side the isset

Update your db name with variable for the db name

Last advise, if you are echo the validation error for testing it's fine, otherwise hold in a variable and echo it in the proper place. And take your insert query code block inside the validation.

Body:
i cannot insert users into database after registration, i have done all i can but was not successful, i really neddd help here, please i want to know and what am doing wrong in my script.

this is my registration html script:

<bold>ENTER YOUR DETAILS HERE</bold>

  <form action="trotle.php"  method="POST">

              <input type="hidden" class="form-control" name="id" placeholder="enter your id" required />

              fullname

                  <input type="text" class="form-control" name="fullname" placeholder="Enter your fullname" required />

              username

                  <input type="username" class="form-control" name="username" placeholder="Enter your username" required />

                   password

                 <input type="password" class="form-control" name="password"  placeholder="type in your password" required />

                email

                  <input type="email" class="form-control" name="email"  placeholder="Enter your email" required />

                country

                  <input type="text" class="form-control" name="country"  placeholder="Enter your country" required />

                phone number

                  <input type="number" class="form-control" name="phonenumber"  placeholder="Enter your phonenumber" required />

                Alternative phone number

                  <input type="number" class="form-control" name="alternativephonenumber"  placeholder="Enter your alternative phonenumber" required />

                referrer
                  <input type="text" class="form-control" name="referrer" placeholder="type in who referred you here" required />

                paymentmode

                  <select name="paymentmode" class="form-control" required />
<option value="">Select your paymentmode</option>
<option value="bitcoin">bitcoin</option>
<option value="perfectmoney">perfectmoney</option>
<option value="naira">naira</option>

                  </select>

              <input type="checkbox" style=" vertical-align: sub; margin-left: 120px;margin-bottom: -15px; " required>  I agree with Terms and conditions

              <input type="submit" class="btn btn-success" name="submit_signup" value='REGISTER' style="margin-left:145px;border:none; margin-bottom: -10px; background-color: green; font-weight: bold;border-style: dotted;">
              <input type="post" class="btn btn-success" value='LOGIN' style="margin-left:140px;background-color: green; font-weight: bold;border-style: dotted; border-color:black ;padding: 5px; size:20px; margin-bottom:-10px;">

              <?php

              ?>
              </form>

my php script for inserting users into database is below;

<?php
$id=$fullname=$username=$password=$email=$country= $phonenumber=$alternativephonenumber=$referrer=$paymentmode="";
if(isset($_POST) && array_key_exists('submit_signup',$_POST))
{
$id= $_POST['id'];
if(isset($_POST['id'])){
$id= $_POST['id'];

}
$fullname=$_POST['fullname'];
if(isset($_POST['fullname'])){
$fullname= $_POST['fullname'];
}
else{
    echo 'please enter your fullname';
}
$username= $_POST['username'];
if(isset($_POST['username'])){
$username= $_POST['username'];
}
else{
    echo 'enter your username';
}
$password= $_POST['password'];
if(isset($_POST['password'])){
$password= $_POST['password'];
}
else{
    echo 'enter your password';
}
$email= $_POST['email'];
if(isset($_POST['email'])){
$email= $_POST['email'];
}
else{
    echo 'enter your email';
}
$country= $_POST['country'];
if(isset($_POST['country'])){
$country= $_POST['country'];
}
else{
    echo 'enter your country';
}
$phonenumber= $_POST['phonenumber'];
if(isset($_POST['phonenumber'])){
$phonenumber= $_POST['phonenumber'];
}
else{
    echo 'enter your phonenumber';
}
$alternativephonenumber= $_POST['alternativephonenumber'];
if(isset($_POST['alternativephonenumber'])){
$alternativephonenumber= $_POST['alternativephonenumber'];
}
else{
    echo 'enter your alternativephonenumber';
}
$referrer= $_POST['referrer'];
if(isset($_POST['referrer'])){
$referrer= $_POST['referrer'];
}
else{
    echo 'enter your referrer';
}
$paymentmode= $_POST['paymentmode'];
if(isset($_POST['paymentmode'])){
$paymentmode= $_POST['paymentmode'];
}
else{var_dump($_POST['id']);
    echo 'enter your paymentmode';
}
}
    else {
        echo 'nah';

    }

    $serverhost='localhost';
$serverdb='charles';
$serveruser='root';
$serverpassword='';

try{
    $connect= new PDO("mysql:host=$serverhost;dbname=charles;" , $serveruser, $serverpassword);
 $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     }
      catch( PDOException $e)
        {
            echo $e->getmessage();
        }

     if($connect){
        echo 'database successful!';
     }

$sql="INSERT INTO users(id, fullname, username, password, email, country, phonenumber, alternativephonenumber, referrer, paymentmode)VALUES(:id, :fullname, :username, :password, :email, :country, :phonenumber, :alternativephonenumber, :referrer, :paymentmode)";

$query=$connect->prepare($sql);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->bindParam(':fullname', $fullname, PDO::PARAM_STR);
$query->bindParam(':username', $username, PDO::PARAM_STR);
$query->bindParam(':password', $password, PDO::PARAM_STR);
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':country', $country, PDO::PARAM_STR);
$query->bindParam(':phonenumber', $phonenumber, PDO::PARAM_INT);
$query->bindParam(':alternativephonenumber', $alternativephonenumber, PDO::PARAM_INT);
$query->bindParam(':referrer', $referrer, PDO::PARAM_STR);
$query->bindParam(':paymentmode', $paymentmode, PDO::PARAM_STR);
$query->execute();

?>

Body:
Change you PHP script like this and try, if you not getting the error it might be your validation is wrong

$id=$fullname=$username=$password=$email=$country= $phonenumber=$alternativephonenumber=$referrer=$paymentmode="";
if(isset($_POST['submit_signup']))  //simplified validation
{

if(isset($_POST['id'])){
$id= $_POST['id'];

}

if(isset($_POST['fullname'])){
$fullname= $_POST['fullname'];
}
else{
    echo 'please enter your fullname';
}

if(isset($_POST['username'])){
$username= $_POST['username'];
}
else{
    echo 'enter your username';
}

if(isset($_POST['password'])){
$password= $_POST['password'];
}
else{
    echo 'enter your password';
}

if(isset($_POST['email'])){
$email= $_POST['email'];
}
else{
    echo 'enter your email';
}

if(isset($_POST['country'])){
$country= $_POST['country'];
}
else{
    echo 'enter your country';
}

if(isset($_POST['phonenumber'])){
$phonenumber= $_POST['phonenumber'];
}
else{
    echo 'enter your phonenumber';
}

if(isset($_POST['alternativephonenumber'])){
$alternativephonenumber= $_POST['alternativephonenumber'];
}
else{
    echo 'enter your alternativephonenumber';
}

if(isset($_POST['referrer'])){
$referrer= $_POST['referrer'];
}
else{
    echo 'enter your referrer';
}

if(isset($_POST['paymentmode'])){
$paymentmode= $_POST['paymentmode'];
}
else{var_dump($_POST['id']);
    echo 'enter your paymentmode';
}
}
    else {
        echo 'nah';

    }

    $serverhost='localhost';
$serverdb='charles';
$serveruser='root';
$serverpassword='';

try{
    $connect= new PDO("mysql:host=$serverhost;dbname=$serverdb;" , $serveruser, $serverpassword);
 $connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     }
      catch( PDOException $e)
        {
            echo $e->getmessage();
        }

     if($connect){
        echo 'database successful!';
     }

$sql="INSERT INTO users(id, fullname, username, password, email, country, phonenumber, alternativephonenumber, referrer, paymentmode)VALUES(:id, :fullname, :username, :password, :email, :country, :phonenumber, :alternativephonenumber, :referrer, :paymentmode)";

$query=$connect->prepare($sql);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->bindParam(':fullname', $fullname, PDO::PARAM_STR);
$query->bindParam(':username', $username, PDO::PARAM_STR);
$query->bindParam(':password', $password, PDO::PARAM_STR);
$query->bindParam(':email', $email, PDO::PARAM_STR);
$query->bindParam(':country', $country, PDO::PARAM_STR);
$query->bindParam(':phonenumber', $phonenumber, PDO::PARAM_INT);
$query->bindParam(':alternativephonenumber', $alternativephonenumber, PDO::PARAM_INT);
$query->bindParam(':referrer', $referrer, PDO::PARAM_STR);
$query->bindParam(':paymentmode', $paymentmode, PDO::PARAM_STR);
$query->execute();

Changes made:

Simplified the validation

Removed unnecessary assignment of variables, if you are using isset then don't assign it out side the isset

Update your db name with variable for the db name

Last advise, if you are echo the validation error for testing it's fine, otherwise hold in a variable and echo it in the proper place. And take your insert query code block inside the validation.


问:
Render ImageData from canvas context.getImageData in React
In a React component how can I render an image created using canvas?</p>

```<code>componentWillMount () {
  const canvas = document.createElement('canvas')
  const context = canvas.getContext('2d')
  canvas.width = 256
  canvas.height = 256
  // omitted canvas painting code
  const image = context.getImageData(0, 0, canvas.width, canvas.height)
  this.setState({image})
}

render() {
  return ?
}
</code>```

答:
Please convert your canvas content to data URI using canvas.toDataURL, then you can render the image with an img tag passing the data URI as src attribute:

```<code><img src={this.state.dataURI} />
</code>```

class Example extends React.Component {
  state = {}

  componentWillMount () {
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    canvas.width = 256
    canvas.height = 256

    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const radius = 70;

    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    context.fillStyle = 'green';
    context.fill();
    context.lineWidth = 5;
    context.strokeStyle = '#003300';
    context.stroke();

    const dataURI = canvas.toDataURL()
    this.setState({dataURI})
  }

  render() {
    return
  }
}

ReactDOM.render(<Example />, document.body)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script></code>```

Body:
In a React component how can I render an image created using canvas?

componentWillMount () {
  const canvas = document.createElement('canvas')
  const context = canvas.getContext('2d')
  canvas.width = 256
  canvas.height = 256
  // omitted canvas painting code
  const image = context.getImageData(0, 0, canvas.width, canvas.height)
  this.setState({image})
}

render() {
  return ?
}

Body:
Please convert your canvas content to data URI using canvas.toDataURL, then you can render the image with an img tag passing the data URI as src attribute:

<img src={this.state.dataURI} />

class Example extends React.Component {
  state = {}

  componentWillMount () {
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    canvas.width = 256
    canvas.height = 256

    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const radius = 70;

    context.beginPath();
    context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
    context.fillStyle = 'green';
    context.fill();
    context.lineWidth = 5;
    context.strokeStyle = '#003300';
    context.stroke();

    const dataURI = canvas.toDataURL()
    this.setState({dataURI})
  }

  render() {
    return <img src={this.state.dataURI} />
  }
}

ReactDOM.render(<Example />, document.body)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


问:
jQuery plus minus toggle
I am trying to implement plus/minus icons in a the datagrid using jQuery. On expand, minus icon is coming but on collapse the plus icon is not coming back.

Here is the implementation: http://jsfiddle.net/pixelfx/3fwyf/10/

Can anyone please look into the code.

答:
As Sandeepan Nath's answer, but in one line.

Replace

```<code>$('.minus').show();
$('.add').hide();
</code>```

With

```<code>$('.minus, .add').toggle();
</code>```

Title: jQuery plus minus toggle

Body:
As Sandeepan Nath's answer, but in one line.

Replace

$('.minus').show();
$('.add').hide();

With

$('.minus, .add').toggle();


问:
How yield identify that its iteration done once.?
I have read about yield at What does the "yield" keyword do in Python? keyword in python but i have one question that how system identity that yield iterated once.

```<code>def test_yield():
    name = 'Hello World!'
    for i in name:
        yield i

y= test_yield()

print "first yield",y
for c in y:
    print c

print "second yield",y
for c in y:
    print c
</code>```

Output

```<code>first yield <generator object test_yield at 0x7f4c2bc10be0>
H
e
l
l
o

W
o
r
l
d
!
second yield <generator object test_yield at 0x7f4c2bc10be0>
</code>```

In output second time yield object printed but not iterate.so how program identity that its executed once?

答: Looping through an iterator "uses it up". So your first yield loop iterates through it and reaches the end. Just as if you opened a file and read all of the lines until EOF. After that, no matter how many times you call read(), you won't get more data, only EOF. Similarly, once your iterator has reached its last element, calling .next on it just raises StopIteration.

Body:
I have read about yield at What does the "yield" keyword do in Python? keyword in python but i have one question that how system identity that yield iterated once.

def test_yield():
    name = 'Hello World!'
    for i in name:
        yield i

y= test_yield()

print "first yield",y
for c in y:
    print c

print "second yield",y
for c in y:
    print c

Output

first yield <generator object test_yield at 0x7f4c2bc10be0>
H
e
l
l
o

W
o
r
l
d
!
second yield <generator object test_yield at 0x7f4c2bc10be0>

In output second time yield object printed but not iterate.so how program identity that its executed once?


问:
Validate Command in CQRS that related to other domain
I am learning to develop microservices using DDD, CQRS, and ES. It is HTTP RESTful service. The microservices is about online shop. There are several domains like products, orders, suppliers, customers, and so on. The domains built in separate services. How to do the validation if the command payload relates to other domains?

For example, here is the addOrderItemCommand payload in the order service (command-side).

```<code>{
"customerId": "CUST111",
"productId": "SKU222",
"orderId":"SO333"
}
</code>```

How to validate the command above? How to know that the customer is really exists in database (query-side customer service) and still active? How to know that the product is exists in database and the status of the product is published? How to know whether the customer eligible to get the promo price from the related product?

Is it ok to call API directly (like point-to-point / ajax / request promise) to validate this payload in order command-side service? But I think, the performance will get worse if the API called directly just for validation. Because, we have developed an event processor outside the command-service that listen from the event and apply the event to the materalized view.

Thank you.

答:
As there are more than one bounded contexts that need to be queried for the validation to pass you need to consider eventual consistency. That being said, there is always a chance that the process as a whole can be in an invalid state for a "small" amount of time. For example, the user could be deactivated after the command is accepted and before the order is shipped. An online shop is a complex system and exceptions could appear in any of its subsystems. However, being implemented as an event-driven system helps; every time the ordering process enters an invalid state you can take compensatory actions/commands. For example, if the user is deactivated in the meantime you can cancel all its standing orders, release the reserved products, announce the potential customers that have those products in the wishlist that they are not available and so on.

There are many kinds of validation in DDD but I follow the general rule that the validation should be done as early as possible but without compromising data consistency. So, in order to be early you could query the readmodel to reject the commands that couldn't possible be valid and in order for the system to be consistent you need to make another check just before the order is shipped.

Now let's talk about your specific questions:

How to know that the customer is really exists in database (query-side customer service) and still active?

You can query the readmodel to verify that the user exists and it is still active. You should do this as a command that comes from an invalid user is a strong indication of some kind of attack and you don't want those kind of commands passing through your system. However, even if a command passes this check, it does not necessarily mean that the order will be shipped as other exceptions could be raised in between.

How to know that the product is exists in database and the status of the product is published?

Again, you can query the readmodel in order to notify the user that the product is not available at the moment. Or, depending on your business, you could allow the command to pass if you know that those products will be available in less than 24 hours based on some previous statistics (for example you know that TV sets arrive daily in your stock). Or you could let the customer choose whether it waits or not. In this case, if the products are not in stock at the final phase of the ordering (the shipping) you notify the customer that the products are not in stock anymore.

How to know whether the customer eligible to get the promo price from the related product?

You will probably have to query another bounded context like Promotions BC to check this. This depends on how promotions are validated/used.

Is it ok to call API directly (like point-to-point / ajax / request promise) to validate this payload in order command-side service? But I think, the performance will get worse if the API called directly just for validation.

This depends on how resilient you want your system to be and how fast you want to reject invalid commands.

Synchronous call are simpler to implement but they lead to a less resilient system (you should be aware of cascade failures and use technics like circuit breaker to stop them).

Asynchronous (i.e. using events) calls are harder to implement but make you system more resilient. In order to have async calls, the ordering system can subscribe to other systems for events and maintain a private state that can be queried for validation purposes as the commands arrive. In this way, the ordering system continues to work even of the link to inventory or customer management systems are down.

In any case, it really depends on your business and none of us can tell you exaclty what to do.

Body:
I am learning to develop microservices using DDD, CQRS, and ES. It is HTTP RESTful service. The microservices is about online shop. There are several domains like products, orders, suppliers, customers, and so on. The domains built in separate services. How to do the validation if the command payload relates to other domains?

For example, here is the addOrderItemCommand payload in the order service (command-side).

{
"customerId": "CUST111",
"productId": "SKU222",
"orderId":"SO333"
}

How to validate the command above? How to know that the customer is really exists in database (query-side customer service) and still active? How to know that the product is exists in database and the status of the product is published? How to know whether the customer eligible to get the promo price from the related product?

Is it ok to call API directly (like point-to-point / ajax / request promise) to validate this payload in order command-side service? But I think, the performance will get worse if the API called directly just for validation. Because, we have developed an event processor outside the command-service that listen from the event and apply the event to the materalized view.

Thank you.


问:
How to NOT release keypress in autopy or pyautogui?
When we press a key (such as 'a') in a notebook, and don't release it, we will get aaaaaaaaaaaaaaaa......

I want to simulate the key-press in python. So I've coded as follows.

```<code>import pyautogui, autopy

pyautogui.keyDown('a')
# or
autopy.key.toggle('a')
</code>```

Then, I get just one 'a', even I didn't release the key-press.

How do I solve the problem?

答:
Performs a keyboard key press without the release. This will put that
  key in a held down state.

NOTE: For some reason, this does not seem to cause key repeats like
  would happen if a keyboard key was held down on a text field.

```<code>import pyautogui
while True:
    pyautogui.press('a')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
When we press a key (such as 'a') in a notebook, and don't release it, we will get aaaaaaaaaaaaaaaa......

I want to simulate the key-press in python. So I've coded as follows.

import pyautogui, autopy

pyautogui.keyDown('a')
# or
autopy.key.toggle('a')

Then, I get just one 'a', even I didn't release the key-press.

How do I solve the problem?

Body:
Performs a keyboard key press without the release. This will put that
  key in a held down state.

NOTE: For some reason, this does not seem to cause key repeats like
  would happen if a keyboard key was held down on a text field.

import pyautogui
while True:
    pyautogui.press('a')


问:
Android: Menù popup with long click?
I need to implement a menù that appears with a long click around a button, so the user can choose with option he wants to take simply sliding toward a certain direction. Is there any way to do that? I have just a setOnLongClickListener with a onLongClick method for now.</p>

```<code>btn01.setOnLongClickListener(new View.OnLongClickListener(){
            public boolean onLongClick (View view) {
                Toast.makeText(getApplicationContext(),"Button 01 long clicked", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
</code>```

答:
In your Activity :</p>

```<code>    btn01.setOnLongClickListener(new View.OnLongClickListener(){
        public boolean onLongClick (View view) {
            registerForContextMenu(btn01);
            openContextMenu(btn01);
            return true;
        }
    });

    @Override
    public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
        //Context menu
        menu.setHeaderTitle("My Context Menu");
        menu.add(Menu.NONE, CONTEXT_MENU_VIEW, Menu.NONE, "Add");
        menu.add(Menu.NONE, CONTEXT_MENU_EDIT, Menu.NONE, "Edit");
        menu.add(Menu.NONE, CONTEXT_MENU_ARCHIVE, Menu.NONE, "Delete");
    }

    @Override
    public boolean onContextItemSelected (MenuItem item){
        switch (item.getItemId()) {
            case CONTEXT_MENU_VIEW: {

            }
            break;
            case CONTEXT_MENU_EDIT: {
                // Edit Action

            }
    }
}
</code>```

Title: Android: Menù popup with long click?

Body:
I need to implement a menù that appears with a long click around a button, so the user can choose with option he wants to take simply sliding toward a certain direction. Is there any way to do that? I have just a setOnLongClickListener with a onLongClick method for now.

btn01.setOnLongClickListener(new View.OnLongClickListener(){
            public boolean onLongClick (View view) {
                Toast.makeText(getApplicationContext(),"Button 01 long clicked", Toast.LENGTH_SHORT).show();
                return true;
            }
        });

Body:
In your Activity :

    btn01.setOnLongClickListener(new View.OnLongClickListener(){
        public boolean onLongClick (View view) {
            registerForContextMenu(btn01);
            openContextMenu(btn01);
            return true;
        }
    });

    @Override
    public void onCreateContextMenu (ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
        //Context menu
        menu.setHeaderTitle("My Context Menu");
        menu.add(Menu.NONE, CONTEXT_MENU_VIEW, Menu.NONE, "Add");
        menu.add(Menu.NONE, CONTEXT_MENU_EDIT, Menu.NONE, "Edit");
        menu.add(Menu.NONE, CONTEXT_MENU_ARCHIVE, Menu.NONE, "Delete");
    }

    @Override
    public boolean onContextItemSelected (MenuItem item){
        switch (item.getItemId()) {
            case CONTEXT_MENU_VIEW: {

            }
            break;
            case CONTEXT_MENU_EDIT: {
                // Edit Action

            }
    }
}


问:
Convert a geometry to a path in wpf (with blend ?)
my question is simple.

how can I convert this code:

```<code><Path>
    <Path.Data>
        <EllipseGeometry Center="5,4" RadiusX="4" RadiusY="4"/>
    </Path.Data>
</Path>
</code>```

into something like

```<code><Path Data="M 0 5 L 3 10 10 0"/>
</code>```

(please note that the second one produces a checkmark, not an ellipse. It was just for illustration purposes, and my goal is just that: find what sequence gives an ellipse)

edit: I also read the doc about Bezier curves in xaml and am fully aware that I could simply produce the right code by calculating the exact points of the Bezier curve to get an ellipse, but I do not wish to go to the hassle of doing this calculation myself, so I was wondering if there is an easy way to do this (in Blend maybe)

答:
This shows how to do it from code. I'm not sure if that'll solve your problem or not - you say "with blend?" in the title, and I'm not aware of a way to do this in Blend. But I hope this may help.

The first step would be to convert the EllipseGeometry into a PathGeometry:

```<code>var geom = new EllipseGeometry(new Point(5, 4), 4, 4);
var pathGeometry = PathGeometry.CreateFromGeometry(geom);
</code>```

Once you've got a PathGeometry you can simply call ToString and it'll give you the string representation:

```<code>string pathText = pathGeometry.ToString();
</code>```

On my system, this produces the following rather verbose text:

"M9,4C9,6.20913899932317 7.20913899932317,8 5,8 2.79086100067683,8 1,6.20913899932317 1,4 1,1.79086100067683 2.79086100067683,0 5,0 7.20913899932317,0 9,1.79086100067683 9,4z"

Now if you want to end up with exactly what you would have got if you'd fed that string into Xaml, you need one more step, because Xaml of the form you've supplied:

```<code><Path Data="M 0 5 L 3 10 10 0"/>
</code>```

doesn't produce a PathGeometry. It produces a StreamGeometry, which is a slightly more efficient, but fixed representation of the path. (The main difference being that you can't get hold of individual objects representing the various figures and segements in a StreamGeometry, whereas you can with a PathGeometry. StreamGeometry is cheaper, as a result.)

You can get a StreamGeometry from the path text:

```<code>var streamGeometry = StreamGeometry.Parse(pathText);
</code>```

And then if you want that in a Path just build it:

```<code>var p = new Path { Data = streamGeometry };
</code>```

Depending on what your exact goal is, there may be more efficient ways to do this. (StreamGeometry is a more efficient representation because it ends up creating far fewer objects. But the route by which my code gets to that representation is not very efficient, so you might be better off just stopping with the PathGeometry that the very first code snippet produces. Alternatively, if your goal is really just to get the path text, then the PathGeometry is also sufficient for your needs.)

Body:
my question is simple.

how can I convert this code:

<Path>
    <Path.Data>
        <EllipseGeometry Center="5,4" RadiusX="4" RadiusY="4"/>
    </Path.Data>
</Path>

into something like

<Path Data="M 0 5 L 3 10 10 0"/>

(please note that the second one produces a checkmark, not an ellipse. It was just for illustration purposes, and my goal is just that: find what sequence gives an ellipse)

edit: I also read the doc about Bezier curves in xaml and am fully aware that I could simply produce the right code by calculating the exact points of the Bezier curve to get an ellipse, but I do not wish to go to the hassle of doing this calculation myself, so I was wondering if there is an easy way to do this (in Blend maybe)

Body:
This shows how to do it from code. I'm not sure if that'll solve your problem or not - you say "with blend?" in the title, and I'm not aware of a way to do this in Blend. But I hope this may help.

The first step would be to convert the EllipseGeometry into a PathGeometry:

var geom = new EllipseGeometry(new Point(5, 4), 4, 4);
var pathGeometry = PathGeometry.CreateFromGeometry(geom);

Once you've got a PathGeometry you can simply call ToString and it'll give you the string representation:

string pathText = pathGeometry.ToString();

On my system, this produces the following rather verbose text:

"M9,4C9,6.20913899932317 7.20913899932317,8 5,8 2.79086100067683,8 1,6.20913899932317 1,4 1,1.79086100067683 2.79086100067683,0 5,0 7.20913899932317,0 9,1.79086100067683 9,4z"

Now if you want to end up with exactly what you would have got if you'd fed that string into Xaml, you need one more step, because Xaml of the form you've supplied:

<Path Data="M 0 5 L 3 10 10 0"/>

doesn't produce a PathGeometry. It produces a StreamGeometry, which is a slightly more efficient, but fixed representation of the path. (The main difference being that you can't get hold of individual objects representing the various figures and segements in a StreamGeometry, whereas you can with a PathGeometry. StreamGeometry is cheaper, as a result.)

You can get a StreamGeometry from the path text:

var streamGeometry = StreamGeometry.Parse(pathText);

And then if you want that in a Path just build it:

var p = new Path { Data = streamGeometry };

Depending on what your exact goal is, there may be more efficient ways to do this. (StreamGeometry is a more efficient representation because it ends up creating far fewer objects. But the route by which my code gets to that representation is not very efficient, so you might be better off just stopping with the PathGeometry that the very first code snippet produces. Alternatively, if your goal is really just to get the path text, then the PathGeometry is also sufficient for your needs.)


问:
MongoDB define collection that has an array as document
I'm a newbie to mongodb and I'm trying to create my first database.

This is my scenario: A user can connect to a FTP Location and get/put some files. Each user can have more than one FTP Storage that he can access.

These are the fields required for the user document:

```<code>username: String
password: String
</code>```

And these are the fields required for the ftp document:

```<code>host: String
port: Number
user: String
pass: String
</code>```

And here comes my question...Can I have a single collection that contains both documents mentioned above?

More precisely, I need to know how I can get a record like this and how my database should look...

```<code>{
    "username": "User",
    "password": "test",
    [
      {
        "host": "first-host",
        "port": 21,
        "user": "defined-user",
        "pass": "defined-pass"
      },
      {
        "host": "second-host",
        "port": 21,
        "user": "defined-user",
        "pass": "defined-pass"
      }
    ]
}
</code>```

Not sure if my question is clearly enough, but please let me know if I need to specify additional information to get some answers

答:
Mongo uses json format, so you can have something like that :

```<code>  "username": "User",
  "password": "test",
  "storage": [
    {
      "host": "first-host",
      "port": 21,
      "user": "defined-user",
      "pass": "defined-pass"
    },
    {
      "host": "second-host",
      "port": 21,
      "user": "defined-user",
      "pass": "defined-pass"
    }
  ]
</code>```

And you shema should be defined like this :

```<code>username: String
password: String
storage : Array
</code>```

Body:
I'm a newbie to mongodb and I'm trying to create my first database.

This is my scenario: A user can connect to a FTP Location and get/put some files. Each user can have more than one FTP Storage that he can access.

These are the fields required for the user document:

username: String
password: String

And these are the fields required for the ftp document:

host: String
port: Number
user: String
pass: String

And here comes my question...Can I have a single collection that contains both documents mentioned above?

More precisely, I need to know how I can get a record like this and how my database should look...

{
    "username": "User",
    "password": "test",
    [
      {
        "host": "first-host",
        "port": 21,
        "user": "defined-user",
        "pass": "defined-pass"
      },
      {
        "host": "second-host",
        "port": 21,
        "user": "defined-user",
        "pass": "defined-pass"
      }
    ]
}

Not sure if my question is clearly enough, but please let me know if I need to specify additional information to get some answers

Body:
Mongo uses json format, so you can have something like that :

  "username": "User",
  "password": "test",
  "storage": [
    {
      "host": "first-host",
      "port": 21,
      "user": "defined-user",
      "pass": "defined-pass"
    },
    {
      "host": "second-host",
      "port": 21,
      "user": "defined-user",
      "pass": "defined-pass"
    }
  ]

And you shema should be defined like this :

username: String
password: String
storage : Array


问:
Alternative to getUserMedia() for reading live camera stream on iOS?
We are building a mobile barcode-scanner using QuaggaJS that reads barcodes directly from the device's camera stream. Works fine on desktop/Android, but doesn't work at all on iOS.

From initial research, I've found that iOS simply does not support WebRTC/getUserMedia through Safari or iOS Chrome (related links below), which is what QuaggaJS uses to read the camera stream.

I've also seen this question about capturing a still image on iOS, but the answer provided is only for capturing a still image, not for reading the stream real-time.

My question - is there any other way to grab the stream from an iOS camera? Perhaps an alternate library other than QuaggaJS that does not use getUserMedia? I am not well-versed in Javascript, so I am not sure if there even is a possible way to access the camera stream other than getUserMedia.

A "no" is an acceptable answer here; I'm simply looking for someone more experienced to provide guidance.

Appendix/related links:

navigator.getUserMedia alternative API for iOS safari mobile browser?

https://www.quora.com/Why-is-navigator-getUserMedia-not-supported-in-Safari

https://bloggeek.me/webrtc-apple-or-microsoft/

HTML5: getUserMedia iOS issue?

答:
2017 update: Apple just announced that getUserMedia will finally be supported in iOS11.

Aug 2019 update: ONLY works in Safari, not in a WebView of any kind. Thanks @Klathmon for the comment.


问:
How to change font family only numbers
On whole my website there are many places that use numbers. because my font doesn't good to numbers.I would like to change font them to what I wanted.

now similar questions asked before but I not find a good answer to do this.
some answers suggests to use jquery/javascript function. but I think using jquery/javascript function make lazy my webpages.

Is there any better solution?

答:
You could add a class to every occurence of numbers on your page, and simply change the font-family of said class.

HTML

```<code><p> .... <span class="number">42</span> ... </p>
</code>```

CSS

```<code>.number{
  font-family: 'myFont';
}
</code>```

Title: How to change font family only numbers

Body:
You could add a class to every occurence of numbers on your page, and simply change the font-family of said class.

HTML

<p> .... <span class="number">42</span> ... </p>

CSS

.number{
  font-family: 'myFont';
}


答:
The first time the for calls the generator object created from your function, it will run the code in your function from the beginning until it hits yield, then it’ll return the first value of the loop. Then, each other call will run the loop you have written in the function one more time, and return the next value, until there is no value to return. In your second for loop, there's no more value to retrieve because you already wasted them.

For more insight as to what's happening behind the scenes, the for loop can be rewritten to this:

```<code>iterator = some_func()
try:
    while 1:
        print iterator.next()
except StopIteration:
    pass
</code>```

Title: How yield identify that its iteration done once.?

Body:
The first time the for calls the generator object created from your function, it will run the code in your function from the beginning until it hits yield, then it’ll return the first value of the loop. Then, each other call will run the loop you have written in the function one more time, and return the next value, until there is no value to return. In your second for loop, there's no more value to retrieve because you already wasted them.

For more insight as to what's happening behind the scenes, the for loop can be rewritten to this:

iterator = some_func()
try:
    while 1:
        print iterator.next()
except StopIteration:
    pass


问:
Writing a file client side using Angularjs
Can we write an xlsx file on client side using angular js .If it is possible then please provide me the solution.</p>

答:
you can create your excel file.

install npm install excel4node

and then use the basic code

```<code>// Require library
var xl = require('excel4node');

// Create a new instance of a Workbook class
var wb = new xl.Workbook();

// Add Worksheets to the workbook
var ws = wb.addWorksheet('Sheet 1');
var ws2 = wb.addWorksheet('Sheet 2');

// Create a reusable style
var style = wb.createStyle({
    font: {
        color: '#FF0800',
        size: 12
    },
    numberFormat: '$#,##0.00; ($#,##0.00); -'
});

// Set value of cell A1 to 100 as a number type styled with paramaters of style
ws.cell(1,1).number(100).style(style);

// Set value of cell B1 to 300 as a number type styled with paramaters of style
ws.cell(1,2).number(200).style(style);

// Set value of cell C1 to a formula styled with paramaters of style
ws.cell(1,3).formula('A1 + B1').style(style);

// Set value of cell A2 to 'string' styled with paramaters of style
ws.cell(2,1).string('string').style(style);

// Set value of cell A3 to true as a boolean type styled with paramaters of style but with an adjustment to the font size.
ws.cell(3,1).bool(true).style(style).style({font: {size: 14}});

wb.write('Excel.xlsx');
</code>```

here i have added ref link :https://www.npmjs.com/package/excel4node

Body:
you can create your excel file.

install npm install excel4node

and then use the basic code

// Require library
var xl = require('excel4node');

// Create a new instance of a Workbook class
var wb = new xl.Workbook();

// Add Worksheets to the workbook
var ws = wb.addWorksheet('Sheet 1');
var ws2 = wb.addWorksheet('Sheet 2');

// Create a reusable style
var style = wb.createStyle({
    font: {
        color: '#FF0800',
        size: 12
    },
    numberFormat: '$#,##0.00; ($#,##0.00); -'
});

// Set value of cell A1 to 100 as a number type styled with paramaters of style
ws.cell(1,1).number(100).style(style);

// Set value of cell B1 to 300 as a number type styled with paramaters of style
ws.cell(1,2).number(200).style(style);

// Set value of cell C1 to a formula styled with paramaters of style
ws.cell(1,3).formula('A1 + B1').style(style);

// Set value of cell A2 to 'string' styled with paramaters of style
ws.cell(2,1).string('string').style(style);

// Set value of cell A3 to true as a boolean type styled with paramaters of style but with an adjustment to the font size.
ws.cell(3,1).bool(true).style(style).style({font: {size: 14}});

wb.write('Excel.xlsx');

here i have added ref link :https://www.npmjs.com/package/excel4node


问:
Jenkins - abort running build if new one is started
I use Jenkins and Multibranch Pipeline. I have a job for each active git branch.
New build is triggered by push in git repository. What I want is to abort running builds in current branch if new one appears in same branch.

For example: I commit and push to branch feature1. Then BUILD_1 started in Jenkins. I make another commit and push to branch feature1 while BUILD_1 is still running. I want BUILD_1 to be aborted and to start BUILD_2.

I tried to use stage concurrency=x option, and stage-lock-milestone feature, but didn't manage to solve my problem.

Also I've read this thread Stopping Jenkins job in case newer one is started, but there is no solution for my problem.

Do you know any solution to this?

答:
Got it to work by having the following script in the Global Shared Library :

```<code>import hudson.model.Result
import jenkins.model.CauseOfInterruption.UserInterruption

def killOldBuilds() {
  while(currentBuild.rawBuild.getPreviousBuildInProgress() != null) {
    currentBuild.rawBuild.getPreviousBuildInProgress().doKill()
  }
}
</code>```

And calling it in my pipeline :

```<code>@Library('librayName')
def pipeline = new killOldBuilds()
[...]
stage 'purge'
pipeline.killOldBuilds()
</code>```

Edit : Depending on how strongly you want to kill the oldBuild, you can use doStop(), doTerm() or doKill() !

Body:
Got it to work by having the following script in the Global Shared Library :

import hudson.model.Result
import jenkins.model.CauseOfInterruption.UserInterruption

def killOldBuilds() {
  while(currentBuild.rawBuild.getPreviousBuildInProgress() != null) {
    currentBuild.rawBuild.getPreviousBuildInProgress().doKill()
  }
}

And calling it in my pipeline :

@Library('librayName')
def pipeline = new killOldBuilds()
[...]
stage 'purge'
pipeline.killOldBuilds()

Edit : Depending on how strongly you want to kill the oldBuild, you can use doStop(), doTerm() or doKill() !


问:
How to create a multi language report?
I want to create a document, which prints in more than one language, based on the Locale.

I have created 2 resource bundles, one in English and one in Chinese, but I am not sure how to use them.

答:
Since the document generator may be part of your application, you should somewhere have a language selector menu-item, check-box or combo-box which is already preselected.

So, why don't you just add an if statement that reads the Locale, or the needed language before the report generation, and load the appropriate report accordingly to the locale.

This way you will need to keep one jrxml file for every language. It will be fairly easy to just translate the headers and labels manually.

Your data should be already translated in your database, where you have to keep the relevant attribute values multilingual anyway.

You will need to modify the SQL query for the appropriate language, but since the Query is part of your jrxml it will be executed automatically.

Title: How to create a multi language report?