问:
Disable form fields on input into a group of other fields
I have the below form and would like to use jQuery to do the following:

1/ Disable the fields 'filter_from' and 'filter_to' if any character is entered into any one or more of the fields 'filter_loan_id', 'filter_fname', 'filter_lname', 'filter_postcode'.

2/ Re-enable the fields 'filter_from' and 'filter_to' only if there is no input in any of the fields 'filter_loan_id', 'filter_fname', 'filter_lname', 'filter_postcode'. That is, all 4 of these fields are empty.

I have the below code which works for point 1 - It disables the 2 fields when any of the other fields have data entered.

It does not work as required for point 2 - It currently re-enables the 2 fields if any one of the other fields is cleared. It should only re-enable the 2 fields when all of the other fields are cleared.

The fields 'filter_com' and 'filter_employer' should be ignored. They are only mentioned here to explain that not all of the fields on the form are to be used to disable the other 2 fields, just selected fields.

```<code><form>
  <input name="filter_from" type="text" autocomplete="off">
  <input name="filter_to" type="text" autocomplete="off">
  <input name="filter_loan_id" type="text" autocomplete="off">
  <input name="filter_fname" type="text" autocomplete="off">
  <input name="filter_lname" type="text" autocomplete="off">
  <input name="filter_postcode" type="text" autocomplete="off">
  <input name="filter_com" type="text" autocomplete="off">
  <input name="filter_employer" type="text" autocomplete="off">
</form>

$(document).ready(function() {

    $('input[name=filter_fname], input[name=filter_lname], input[name=filter_loan_id], input[name=filter_postcode]').change(function() {
        if ($(this).val() != '') {
            $('input[name=filter_from]').prop('disabled', true);
            $('input[name=filter_to]').prop('disabled', true);
        } else {
            $('input[name=filter_from]').prop('disabled', false);
            $('input[name=filter_to]').prop('disabled', false);
        }
    });

});
</code>```

答:
Try concatenating the values of all the relevant inputs and use that for checking

$(document).ready(function() {

  var disableable = $('input[name=filter_from], input[name=filter_to]'),
      valuable = $('input[name=filter_fname], input[name=filter_lname], input[name=filter_loan_id], input[name=filter_postcode]').on('input change', function() {

      var combinedValue = valuable.get().map(function(element) {
        return element.value;
      }).join('');

      disableable.prop('disabled', combinedValue !== '');
    });
  valuable.trigger('change');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>input:disabled{background:#ccc;}</code>```

<form>
  filter_from<input name="filter_from" type="text" autocomplete="off">
 filter_to
  <input name="filter_to" type="text" autocomplete="off">
 filter_loan_id
  <input name="filter_loan_id" type="text" autocomplete="off">
 filter_fname
  <input name="filter_fname" type="text" autocomplete="off">
 filter_lname
  <input name="filter_lname" type="text" autocomplete="off">
 filter_postcode
  <input name="filter_postcode" type="text" autocomplete="off">
 filter_com
  <input name="filter_com" type="text" autocomplete="off">
 filter_employer
  <input name="filter_employer" type="text" autocomplete="off">
</form>```

Body:
I have the below form and would like to use jQuery to do the following:

1/ Disable the fields 'filter_from' and 'filter_to' if any character is entered into any one or more of the fields 'filter_loan_id', 'filter_fname', 'filter_lname', 'filter_postcode'.

2/ Re-enable the fields 'filter_from' and 'filter_to' only if there is no input in any of the fields 'filter_loan_id', 'filter_fname', 'filter_lname', 'filter_postcode'. That is, all 4 of these fields are empty.

I have the below code which works for point 1 - It disables the 2 fields when any of the other fields have data entered.

It does not work as required for point 2 - It currently re-enables the 2 fields if any one of the other fields is cleared. It should only re-enable the 2 fields when all of the other fields are cleared.

The fields 'filter_com' and 'filter_employer' should be ignored. They are only mentioned here to explain that not all of the fields on the form are to be used to disable the other 2 fields, just selected fields.

<form>
  <input name="filter_from" type="text" autocomplete="off">
  <input name="filter_to" type="text" autocomplete="off">
  <input name="filter_loan_id" type="text" autocomplete="off">
  <input name="filter_fname" type="text" autocomplete="off">
  <input name="filter_lname" type="text" autocomplete="off">
  <input name="filter_postcode" type="text" autocomplete="off">
  <input name="filter_com" type="text" autocomplete="off">
  <input name="filter_employer" type="text" autocomplete="off">
</form>

$(document).ready(function() {

    $('input[name=filter_fname], input[name=filter_lname], input[name=filter_loan_id], input[name=filter_postcode]').change(function() {
        if ($(this).val() != '') {
            $('input[name=filter_from]').prop('disabled', true);
            $('input[name=filter_to]').prop('disabled', true);
        } else {
            $('input[name=filter_from]').prop('disabled', false);
            $('input[name=filter_to]').prop('disabled', false);
        }
    });

});

Body:
Try concatenating the values of all the relevant inputs and use that for checking

$(document).ready(function() {

  var disableable = $('input[name=filter_from], input[name=filter_to]'),
      valuable = $('input[name=filter_fname], input[name=filter_lname], input[name=filter_loan_id], input[name=filter_postcode]').on('input change', function() {

      var combinedValue = valuable.get().map(function(element) {
        return element.value;
      }).join('');

      disableable.prop('disabled', combinedValue !== '');
    });
  valuable.trigger('change');
});

input:disabled{background:#ccc;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  filter_from<input name="filter_from" type="text" autocomplete="off"><br> filter_to
  <input name="filter_to" type="text" autocomplete="off"><br> filter_loan_id
  <input name="filter_loan_id" type="text" autocomplete="off"><br> filter_fname
  <input name="filter_fname" type="text" autocomplete="off"><br> filter_lname
  <input name="filter_lname" type="text" autocomplete="off"><br> filter_postcode
  <input name="filter_postcode" type="text" autocomplete="off"><br> filter_com
  <input name="filter_com" type="text" autocomplete="off"><br> filter_employer
  <input name="filter_employer" type="text" autocomplete="off">
</form>


来源: stackexchange

问:
Lazy loading using MEAN stack (AngularJS 1.x)
how to implement lazy loading/more data on scroll with MEAN stack. I want to load 10 posts at a time, when I scroll down, the next 10 elements should load.

The following code is showing all the list of users:

```<code>exports.findAllUsers = function (req, res) {
User.find(function (err, data) {
    if (err) {
        console.log("Users not Find.." + err);
        res.json({ success: false, "data": err });
    }
    else {
        console.log("Users Finds.. " + data);
        res.json({ success: true, "data": data });
    }
});
};
</code>```

I have tried the lazy loading using following code: but I am getting this error (Error: No default engine was specified and no extension was provided.)

```<code>var itemsPerPage = 6;

exports.findAllUsers = function (req, res, pageNum) {

User.find({skip: (itemsPerPage * (pageNum-1)), limit: itemsPerPage}, function (err, data) {
    if (err) {
        console.log("Users not Find.." + err);
        res.json({ success: false, "data": err });
    }
    else {
        console.log("Users Finds.. " + data);
        res.json({ success: true, "data": data });
    }
});
};
</code>```

Thanks in advance!

答:
The error you get is nothing to do with throws routes,ist says that you didn't choose and set a template engine to your application.

You need to set it like so:

```<code>app.set('view engine', 'jade');
</code>```

Or, if you want use a more easy to learn template engine, use ejs like so:

```<code>// set the view engine to ejs
app.set('view engine', 'ejs');
</code>```

ContentLicense: CC BY-SA 3.0

Body:
how to implement lazy loading/more data on scroll with MEAN stack. I want to load 10 posts at a time, when I scroll down, the next 10 elements should load.

The following code is showing all the list of users:

exports.findAllUsers = function (req, res) {
User.find(function (err, data) {
    if (err) {
        console.log("Users not Find.." + err);
        res.json({ success: false, "data": err });
    }
    else {
        console.log("Users Finds.. " + data);
        res.json({ success: true, "data": data });
    }
});
};

I have tried the lazy loading using following code: but I am getting this error (Error: No default engine was specified and no extension was provided.)

var itemsPerPage = 6;

exports.findAllUsers = function (req, res, pageNum) {

User.find({skip: (itemsPerPage * (pageNum-1)), limit: itemsPerPage}, function (err, data) {
    if (err) {
        console.log("Users not Find.." + err);
        res.json({ success: false, "data": err });
    }
    else {
        console.log("Users Finds.. " + data);
        res.json({ success: true, "data": data });
    }
});
};

Thanks in advance!

Body:
The error you get is nothing to do with throws routes,ist says that you didn't choose and set a template engine to your application.

You need to set it like so:

app.set('view engine', 'jade');

Or, if you want use a more easy to learn template engine, use ejs like so:

// set the view engine to ejs
app.set('view engine', 'ejs');


问:
Spring CORS 404
I'm using spring mvc without spring security.  I have this bean in my @Configuration class trying to allow requests from localhost:8080

```<code>@Bean
    @Profile("dev")
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:8080").allowedMethods("GET","POST","PUT","DELETE", "OPTIONS");
            }
        };
    }
</code>```

The active profile is dev in my application.yml.  My application is running on localhost:8090.  This request works
http://localhost:8090/assessment/api/questions/page?offset=0&limit=10
but this request returns a 404
http://localhost:8080/assessment/api/questions/page?offset=0&limit=10

Am I missing some extra configuration?

答:
You are confusing URL to which to send the request and URL from which the request was sent.

"My application is running on localhost:8090." appears to indicate that the only listener you have is on port 8090.

CORS is a means to allow requests that source from a different domain,
it is not a means to setup multiple listeners in your container.

Title: Spring CORS 404

Body:
I'm using spring mvc without spring security.  I have this bean in my @Configuration class trying to allow requests from localhost:8080

@Bean
    @Profile("dev")
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("http://localhost:8080").allowedMethods("GET","POST","PUT","DELETE", "OPTIONS");
            }
        };
    }

The active profile is dev in my application.yml.  My application is running on localhost:8090.  This request works
http://localhost:8090/assessment/api/questions/page?offset=0&limit=10
but this request returns a 404
http://localhost:8080/assessment/api/questions/page?offset=0&limit=10

Am I missing some extra configuration?


问:
Vertically aligning a div and an input
After trying to get it right for hours I've finally found a way to align two divs perfectly on one line, but now I'm trying to get a button and an input box aligned and they're just slightly off. Note: I'm using Bootstrap with this!

Here's my code:

html:

```<code><input id="col1" type="text" class="form-control" placeholder="Enter activity" /><button id="col2" class="btn btn-outline-success my-2 my-sm-0" type = "button">Add</button>
</code>```

css:

```<code>body {
    margin: 10px;
}

#col1 {
    display: inline-block;
    width: 70%;
    height: 100px;

}

#col2 {
    display: inline-block;
    width: 30%;
    height: 100px;

}

button, input {
  height: 100%;
  width: 100%;
  line-height: 0;
  border: 0;
}
</code>```

http://jsfiddle.net/x1hphsvb/335/

Any help is appreciated!

答:
You have a few more properties to zero out:

```<code>button, input {
  ...
  border: 0;
  line-height: 0;
  vertical-align: top; /* or 'middle'; for Bootstrap */
}
</code>```

Demo

Title: Vertically aligning a div and an input

Body:
After trying to get it right for hours I've finally found a way to align two divs perfectly on one line, but now I'm trying to get a button and an input box aligned and they're just slightly off. Note: I'm using Bootstrap with this!

Here's my code:

html:

<input id="col1" type="text" class="form-control" placeholder="Enter activity" /><button id="col2" class="btn btn-outline-success my-2 my-sm-0" type = "button">Add</button>

css:

body {
    margin: 10px;
}

#col1 {
    display: inline-block;
    width: 70%;
    height: 100px;

}

#col2 {
    display: inline-block;
    width: 30%;
    height: 100px;

}

button, input {
  height: 100%;
  width: 100%;
  line-height: 0;
  border: 0;
}

http://jsfiddle.net/x1hphsvb/335/

Any help is appreciated!

Body:
You have a few more properties to zero out:

button, input {
  ...
  border: 0;
  line-height: 0;
  vertical-align: top; /* or 'middle'; for Bootstrap */
}

Demo


问:
Model for UnderReview/Published User Content
I am building a user-generated website, but want to be able to moderate them. I also need the posts have a static id, because I want to use the facebook social plugins. I was initially thinking about having two distinct tables 'review' and 'published' and move the posts from one table to another. However, I didnt know how make them retain their id, as the incremental id of the table is used?

I could also use one table and have a published attribute, but I feel this solution is not really performant, but the only way to preserve the id?

btw, i am using rails

答: Why not have a state column in the posts table to show if a post is reviewed or published?  If you want to get fancy you can use something like the aasm gem.

ContentLicense: CC BY-SA 2.5


问:
c# serial port flushing for small data chunks
I'm writing a small byte array of two bytes using something like the following:

```<code>int bytes_to_write = 2;
port.Write(byte_buffer, buffer_offset, bytes_to_write);
</code>```

It appears as though the underlying libraries are waiting for more data to come through before writing it to the port. Is this the correct behaviour and can I force it to write the small chunk immediately? Some of the forums say using:

```<code>port.BaseStream.Flush();
</code>```

will cause the correct behaviour but others say this doesn't work. I've run a couple of tests and it doesn't seem to be working for me.

Cheers,
Richard

答:
I have a very similar situation. I try to write on a serial port from c# to an Arduino board.
I can write into the serial port but data are finally send only after close and open the port. I try several settings, may be that should help you. DtrEnable is certainly the most important one.  </p>

```<code>port.Handshake = Handshake.None;
port.Open();
port.DiscardInBuffer();
port.DiscardOutBuffer();
port.DtrEnable = true;
</code>```

Body:
I'm writing a small byte array of two bytes using something like the following:

int bytes_to_write = 2;
port.Write(byte_buffer, buffer_offset, bytes_to_write);

It appears as though the underlying libraries are waiting for more data to come through before writing it to the port. Is this the correct behaviour and can I force it to write the small chunk immediately? Some of the forums say using:

port.BaseStream.Flush();

will cause the correct behaviour but others say this doesn't work. I've run a couple of tests and it doesn't seem to be working for me.

Cheers,
Richard

Body:
I have a very similar situation. I try to write on a serial port from c# to an Arduino board.
I can write into the serial port but data are finally send only after close and open the port. I try several settings, may be that should help you. DtrEnable is certainly the most important one.

port.Handshake = Handshake.None;
port.Open();
port.DiscardInBuffer();
port.DiscardOutBuffer();
port.DtrEnable = true;


问:
Java regex for string pattern
I would want to write a regex for this string pattern:

```<code><Col name="SKU_UPC_NBR">85634546495</Col>
</code>```

I want to fetch the value between Col tag.

I tried the below pattern :

```<code>Pattern TAG_REGEX = Pattern.compile("<Col name='SKU_UPC_NBR'>(.+?)</col>");
Matcher matcher = TAG_REGEX.matcher(str);
</code>```

The above is not matching my string and returns empty.
Please help me on this problem.

答:
Try this please:

```<code>(?<=">)\d*(?=<\/)
</code>```

It will match 0 or more digits preceded by "> (quotation mark and greater than sign) and followed by (less than sign and forward slash)

You can test this here:

https://regex101.com/

Title: Java regex for string pattern

Body:
I would want to write a regex for this string pattern:

<Col name="SKU_UPC_NBR">85634546495</Col>

I want to fetch the value between Col tag.

I tried the below pattern :

Pattern TAG_REGEX = Pattern.compile("<Col name='SKU_UPC_NBR'>(.+?)</col>");
Matcher matcher = TAG_REGEX.matcher(str);

The above is not matching my string and returns empty.
Please help me on this problem.

Body:
Try this please:

(?<=">)\d*(?=<\/)

It will match 0 or more digits preceded by "> (quotation mark and greater than sign) and followed by (less than sign and forward slash)

You can test this here:

https://regex101.com/


问:
db.collection is not a function when using MongoClient v3.0
I have been trying W3schools tutorial on nodeJS with MongoDB.

When I try to implement this example in a nodeJS environment and invoke the function with an AJAX call, I got the error below:

```<code>TypeError: db.collection is not a function
    at c:\Users\user\Desktop\Web Project\WebService.JS:79:14
    at args.push (c:\Users\user\node_modules\mongodb\lib\utils.js:431:72)
    at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:254:5
    at connectCallback (c:\Users\user\node_modules\mongodb\lib\mongo_client.js:933:5)
    at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:794:11
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
</code>```

Please find below my implemented code:

```<code>var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mytestingdb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  db.collection("customers").findOne({}, function(err, result) {
    if (err) throw err;
    console.log(result.name);
    db.close();
  });
});
</code>```

Note that the error occurs whenever the execution hits:

```<code>db.collection("customers").findOne({}, function(err, result) {}
</code>```

Also, note (in case it matters) that I have installed the latest MongoDB package for node JS (npm install mongodb), and the MongoDB version is MongoDB Enterprise 3.4.4, with MongoDB Node.js driver v3.0.0-rc0.

答:
For people on version 3.0 of the MongoDB native NodeJS driver:

(This is applicable to people with "mongodb": "^3.0.0-rc0", or a later version in package.json, that want to keep using the latest version.)

In version 2.x of the MongoDB native NodeJS driver you would get the database object as an argument to the connect callback:

```<code>MongoClient.connect('mongodb://localhost:27017/mytestingdb', (err, db) => {
  // Database returned
});
</code>```

According to the changelog for 3.0 you now get a client object containing the database object instead:

```<code>MongoClient.connect('mongodb://localhost:27017', (err, client) => {
  // Client returned
  var db = client.db('mytestingdb');
});
</code>```

The close() method has also been moved to the client. The code in the question can therefore be translated to:

```<code>MongoClient.connect('mongodb://localhost', function (err, client) {
  if (err) throw err;

  var db = client.db('mytestingdb');

  db.collection('customers').findOne({}, function (findErr, result) {
    if (findErr) throw findErr;
    console.log(result.name);
    client.close();
  });
});
</code>```

Body:
I have been trying W3schools tutorial on nodeJS with MongoDB.

When I try to implement this example in a nodeJS environment and invoke the function with an AJAX call, I got the error below:

TypeError: db.collection is not a function
    at c:\Users\user\Desktop\Web Project\WebService.JS:79:14
    at args.push (c:\Users\user\node_modules\mongodb\lib\utils.js:431:72)
    at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:254:5
    at connectCallback (c:\Users\user\node_modules\mongodb\lib\mongo_client.js:933:5)
    at c:\Users\user\node_modules\mongodb\lib\mongo_client.js:794:11
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)

Please find below my implemented code:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mytestingdb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  db.collection("customers").findOne({}, function(err, result) {
    if (err) throw err;
    console.log(result.name);
    db.close();
  });
});

Note that the error occurs whenever the execution hits:

db.collection("customers").findOne({}, function(err, result) {}

Also, note (in case it matters) that I have installed the latest MongoDB package for node JS (npm install mongodb), and the MongoDB version is MongoDB Enterprise 3.4.4, with MongoDB Node.js driver v3.0.0-rc0.

Body:
For people on version 3.0 of the MongoDB native NodeJS driver:

(This is applicable to people with "mongodb": "^3.0.0-rc0", or a later version in package.json, that want to keep using the latest version.)

In version 2.x of the MongoDB native NodeJS driver you would get the database object as an argument to the connect callback:

MongoClient.connect('mongodb://localhost:27017/mytestingdb', (err, db) => {
  // Database returned
});

According to the changelog for 3.0 you now get a client object containing the database object instead:

MongoClient.connect('mongodb://localhost:27017', (err, client) => {
  // Client returned
  var db = client.db('mytestingdb');
});

The close() method has also been moved to the client. The code in the question can therefore be translated to:

MongoClient.connect('mongodb://localhost', function (err, client) {
  if (err) throw err;

  var db = client.db('mytestingdb');

  db.collection('customers').findOne({}, function (findErr, result) {
    if (findErr) throw findErr;
    console.log(result.name);
    client.close();
  });
});


问:
Ajax submit doesn't work (can't read $_POST in php)
I am trying to submit my form using Ajax. When the button is clicked the hit() function gets called and passes the contents of the textbox back to test.php

$_POST seems to be empty, since I get the alert from ajax (form was submitted) but I don't get to see the echo (echo $_POST['textbox'])

test.php

```<code><?php
    echo "test";
    if($_POST)
    {
        echo $_POST['textbox'];
    }
?>
<html>
    <body>
            <form action="index.php" method="post" align="center" id="form" name="form">

                <script type="text/javascript" src="test2.js"> </script>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>

                <input type="text" class="form-control" id="input" name="input" oninput="check();">
                <input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
            </form>
    </body>
    </div>
</html>
</code>```

test2.js

```<code>function hit() {
        var inputText = $("#input").val();
        var inputTextString = "textbox=" + inputText;
        $.ajax({
            type: 'post',
            url: 'test.php',
            data: inputTextString,
            success: function () {
              alert('form was submitted');
            }
        });

}
</code>```

答:
There're more of problems here

In test.php

how can you include your js file before you include jquery .. first is first ..
After Tested Yes you can use jquery $() inside a function without getting $ undefined error while you'll run the function after include jquery .. sorry my bad

Scripts should be on the  or before

while you using just button click why you're using <form>

your code should be something like that

```<code><?php
    echo "test";
    if($_POST)
    {
        echo $_POST['textbox'];
        return false;
    }
?>
<html>
    <head>
    </head>
    <body>
         <input type="text" class="form-control" id="input" name="input" oninput="check();">
          <input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">

      <script type="text/javascript" src="test2.js"> </script>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
    </body>
    </div>
</html>
</code>```

On test2.js

```<code>function hit() {
    var inputText = $("#input").val();
    var inputTextString = {textbox : inputText}; // use this
    $.ajax({
        type: 'post',
        url: 'test.php',
        data: inputTextString,
        success: function () {
           alert('form was submitted');
        }
    });
}
</code>```

Note: for me I prefer to use separated php file to use it with ajax .. it'll make it easier for outputs

If you need to use a form .. you can use your form code including my notes above and make your submit button type="submit" and remove onclick="hit()" from it then on your js file you can use

```<code>$(document).ready(function(){
     $('form').on('submit',function(e){
        e.preventDefault(); // to prevent form reload
        var inputText = $("#input").val();
        var inputTextString = {textbox : inputText}; // use this
        $.ajax({
           type: 'post',
           url: 'test.php',
           data: inputTextString,
           success: function () {
              alert('form was submitted');
           }
        });
     });
});
</code>```

Body:
I am trying to submit my form using Ajax. When the button is clicked the hit() function gets called and passes the contents of the textbox back to test.php

$_POST seems to be empty, since I get the alert from ajax (form was submitted) but I don't get to see the echo (echo $_POST['textbox'])

test.php

<?php
    echo "test";
    if($_POST)
    {
        echo $_POST['textbox'];
    }
?>

            <form action="index.php" method="post" align="center" id="form" name="form">

                <input type="text" class="form-control" id="input" name="input" oninput="check();">
                <input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
            </form>

test2.js

function hit() {
        var inputText = $("#input").val();
        var inputTextString = "textbox=" + inputText;
        $.ajax({
            type: 'post',
            url: 'test.php',
            data: inputTextString,
            success: function () {
              alert('form was submitted');
            }
        });

}

Body:
There're more of problems here

In test.php

how can you include your js file before you include jquery .. first is first ..
After Tested Yes you can use jquery $() inside a function without getting $ undefined error while you'll run the function after include jquery .. sorry my bad

Scripts should be on the <head></head> or before </body>

while you using just button click why you're using <form>

your code should be something like that

<?php
    echo "test";
    if($_POST)
    {
        echo $_POST['textbox'];
        return false;
    }
?>
<html>
    <head>
    </head>
    <body>
         <input type="text" class="form-control" id="input" name="input" oninput="check();">
          <input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">

      <script type="text/javascript" src="test2.js"> </script>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js" type="text/javascript"></script>
    </body>
    </div>
</html>

On test2.js

function hit() {
    var inputText = $("#input").val();
    var inputTextString = {textbox : inputText}; // use this
    $.ajax({
        type: 'post',
        url: 'test.php',
        data: inputTextString,
        success: function () {
           alert('form was submitted');
        }
    });
}

Note: for me I prefer to use separated php file to use it with ajax .. it'll make it easier for outputs

If you need to use a form .. you can use your form code including my notes above and make your submit button type="submit" and remove onclick="hit()" from it then on your js file you can use

$(document).ready(function(){
     $('form').on('submit',function(e){
        e.preventDefault(); // to prevent form reload
        var inputText = $("#input").val();
        var inputTextString = {textbox : inputText}; // use this
        $.ajax({
           type: 'post',
           url: 'test.php',
           data: inputTextString,
           success: function () {
              alert('form was submitted');
           }
        });
     });
});


问:
GStreamer freezes at first frame
I wish to split the GStreamer pipeline so the video is both displayed and recorded. I got this working with gst-launch using the following pipeline:

gst-launch-1.0 -v videotestsrc  ! video/x-raw,width=640,height=480 tee
  name="t" ! queue ! glupload ! glimagesink t. ! queue ! jpegenc ! avimux !
  filesink location=output.avi

I've tried to implement this in my C++ application, but ran in to a problem that doesn't make sense to me. Below is the entire pipeline setup, but only the last couple of lines are relevant/interesting.

```<code>gst_init (NULL, NULL);

GstElement *pipeline = gst_pipeline_new(NULL);
GstElement *sink = NULL;

GstElement *src = gst_element_factory_make("videotestsrc", NULL);
g_assert(src);

GstElement *filter = gst_element_factory_make("capsfilter", "filter");
g_assert(filter);

g_object_set(G_OBJECT (filter), "caps", gst_caps_new_simple("video/x-raw",
    "width", G_TYPE_INT, 640,
    "height", G_TYPE_INT, 480,
    NULL),
NULL);

GstElement *convert = gst_element_factory_make("videoconvert", NULL);
g_assert(convert);

// Tee
GstElement *tee = gst_element_factory_make("tee", "videotee");
g_assert(GstElement *tee);

// Display queue
GstElement *displayQueue = gst_element_factory_make("queue", "displayQueue");
g_assert(displayQueue);

GstElement *upload = gst_element_factory_make("glupload", NULL);
g_assert(upload);

sink = gst_element_factory_make("qmlglsink", NULL);
g_assert(sink);

// Record queue
GstElement *recordQueue = gst_element_factory_make("queue", "recordQueue");
g_assert(recordQueue);

GstElement *encode = gst_element_factory_make("jpegenc", NULL);
g_assert(encode);

GstElement *mux = gst_element_factory_make("avimux", NULL);
g_assert(mux);

GstElement *filesink = gst_element_factory_make("filesink", NULL);
g_assert(filesink);

g_object_set(G_OBJECT(filesink), "location", "output.avi", NULL);

// The above is not interesting, just included it for completeness

// Add elements to bin
gst_bin_add_many(GST_BIN (pipeline), src, filter, convert, tee, displayQueue, upload, sink, recordQueue, encode, mux, filesink, NULL);

// Link elements
gst_element_link_many(src, filter, convert, tee, NULL);
gst_element_link_many(tee, displayQueue, upload, sink, NULL);
//gst_element_link_many(tee, recordQueue, encode, mux, filesink, NULL);
</code>```

If I don't add filesink to the bin, then the test video is displayed as intended. If I add filesink to the bin, then the video displays the first frame and then freezes. I don't understand why this is, since I haven't linked the filesink to the pipeline yet (the line is commented out).

Does anyone know why this is?

(If I uncomment the line where the record queue is linked to the pipeline, then nothing is displayed. But this might be a question for later.)

UPDATE

I tried to run the pipeline using gst_parse_launch() and it shows the same behaviour.

```<code>GError *error = NULL;
GstPipeline *pipeline;
pipeline = GST_PIPELINE(gst_parse_launch("videotestsrc  ! video/x-raw,width=640,height=480 tee name='t' ! queue ! glupload ! glimagesink t. ! queue ! jpegenc ! avimux ! filesink location=output.avi", &error));
gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_PLAYING);
</code>```

The code above freezes at first frame and the output.avi file gets created but has a size of 0 bytes. If I remove the filesink queue, then the video displays fine.

Works:

videotestsrc ! video/x-raw,width=640,height=480 tee name="t" ! queue !
  glupload ! glimagesink

Doesn't work:

videotestsrc ! video/x-raw,width=640,height=480 tee name="t" ! queue !
  glupload ! glimagesink t. ! queue ! jpegenc ! avimux ! filesink
  location=output.avi

So I guess I have an issue with the filesink plugin. I've tried to use absolute path to file, but that didn't help. (It still works fine when I use gst-launch from terminal)

I've also tried to print some debug information with the environment variable GST_DEBUG="filesink:9", but it doesn't print any errors, only this info:

0:00:00.116304411  3331 0x7f92b4002f60 INFO                filesink
  gstfilesink.c:301:gst_file_sink_set_location: filename :
  /some/path/output.avi

0:00:00.116345776  3331
  0x7f92b4002f60 INFO                filesink
  gstfilesink.c:302:gst_file_sink_set_location: uri      :
  file:///some/path/output.avi

0:00:00.118291875  3331
  0x7f92b4002f60 DEBUG               filesink
  gstfilesink.c:523:gst_file_sink_do_seek: Seeking to offset
  0 using fseeko

0:00:00.118320893  3331 0x7f92b4002f60 DEBUG           filesink
  gstfilesink.c:423:gst_file_sink_open_file: opened
  file /some/path/output.avi, seekable 1

Does anyone know what could be causing this?

答:
You could first go with easy option that is use gst_parse_launch(), instead you creating elements and connecting the pads.

Coming to your issue where it freezes, the linking of elements is not correct
it needs to be following:

```<code> // Link elements
gst_element_link_many(src, filter, convert, tee, NULL);

/* Manually link the Tee, which has "Request" pads */
  GstPad *tee_display_pad = gst_element_get_request_pad (tee, "src_%u");
  GstPad *queue_display_pad = gst_element_get_static_pad (displayQueue, "sink");

  GstPad *tee_video_pad = gst_element_get_request_pad (tee, "src_%u");
  GstPad *queue_video_pad = gst_element_get_static_pad (recordQueue, "sink");

  if (gst_pad_link (tee_display_pad, queue_display_pad) != GST_PAD_LINK_OK ||
      gst_pad_link (tee_video_pad, queue_video_pad) != GST_PAD_LINK_OK)
    return -1;

  gst_object_unref (tee_display_pad);
  gst_object_unref (queue_display_pad);
  gst_object_unref (tee_video_pad);
  gst_object_unref (queue_video_pad);

  gst_element_link_many(displayQueue, upload, sink, NULL);

gst_element_link_many(recordQueue, encode, mux, filesink, NULL);
</code>```

Title: GStreamer freezes at first frame

Body:
I wish to split the GStreamer pipeline so the video is both displayed and recorded. I got this working with gst-launch using the following pipeline:

gst-launch-1.0 -v videotestsrc  ! video/x-raw,width=640,height=480 tee
  name="t" ! queue ! glupload ! glimagesink t. ! queue ! jpegenc ! avimux !
  filesink location=output.avi

I've tried to implement this in my C++ application, but ran in to a problem that doesn't make sense to me. Below is the entire pipeline setup, but only the last couple of lines are relevant/interesting.

gst_init (NULL, NULL);

GstElement *pipeline = gst_pipeline_new(NULL);
GstElement *sink = NULL;

GstElement *src = gst_element_factory_make("videotestsrc", NULL);
g_assert(src);

GstElement *filter = gst_element_factory_make("capsfilter", "filter");
g_assert(filter);

g_object_set(G_OBJECT (filter), "caps", gst_caps_new_simple("video/x-raw",
    "width", G_TYPE_INT, 640,
    "height", G_TYPE_INT, 480,
    NULL),
NULL);

GstElement *convert = gst_element_factory_make("videoconvert", NULL);
g_assert(convert);

// Tee
GstElement *tee = gst_element_factory_make("tee", "videotee");
g_assert(GstElement *tee);

// Display queue
GstElement *displayQueue = gst_element_factory_make("queue", "displayQueue");
g_assert(displayQueue);

GstElement *upload = gst_element_factory_make("glupload", NULL);
g_assert(upload);

sink = gst_element_factory_make("qmlglsink", NULL);
g_assert(sink);

// Record queue
GstElement *recordQueue = gst_element_factory_make("queue", "recordQueue");
g_assert(recordQueue);

GstElement *encode = gst_element_factory_make("jpegenc", NULL);
g_assert(encode);

GstElement *mux = gst_element_factory_make("avimux", NULL);
g_assert(mux);

GstElement *filesink = gst_element_factory_make("filesink", NULL);
g_assert(filesink);

g_object_set(G_OBJECT(filesink), "location", "output.avi", NULL);

// The above is not interesting, just included it for completeness

// Add elements to bin
gst_bin_add_many(GST_BIN (pipeline), src, filter, convert, tee, displayQueue, upload, sink, recordQueue, encode, mux, filesink, NULL);

// Link elements
gst_element_link_many(src, filter, convert, tee, NULL);
gst_element_link_many(tee, displayQueue, upload, sink, NULL);
//gst_element_link_many(tee, recordQueue, encode, mux, filesink, NULL);

If I don't add filesink to the bin, then the test video is displayed as intended. If I add filesink to the bin, then the video displays the first frame and then freezes. I don't understand why this is, since I haven't linked the filesink to the pipeline yet (the line is commented out).

Does anyone know why this is?

(If I uncomment the line where the record queue is linked to the pipeline, then nothing is displayed. But this might be a question for later.)

UPDATE

I tried to run the pipeline using gst_parse_launch() and it shows the same behaviour.

GError *error = NULL;
GstPipeline *pipeline;
pipeline = GST_PIPELINE(gst_parse_launch("videotestsrc  ! video/x-raw,width=640,height=480 tee name='t' ! queue ! glupload ! glimagesink t. ! queue ! jpegenc ! avimux ! filesink location=output.avi", &error));
gst_element_set_state (GST_ELEMENT (pipeline), GST_STATE_PLAYING);

The code above freezes at first frame and the output.avi file gets created but has a size of 0 bytes. If I remove the filesink queue, then the video displays fine.

Works:

videotestsrc ! video/x-raw,width=640,height=480 tee name="t" ! queue !
  glupload ! glimagesink

Doesn't work:

videotestsrc ! video/x-raw,width=640,height=480 tee name="t" ! queue !
  glupload ! glimagesink t. ! queue ! jpegenc ! avimux ! filesink
  location=output.avi

So I guess I have an issue with the filesink plugin. I've tried to use absolute path to file, but that didn't help. (It still works fine when I use gst-launch from terminal)

I've also tried to print some debug information with the environment variable GST_DEBUG="filesink:9", but it doesn't print any errors, only this info:

0:00:00.116304411  3331 0x7f92b4002f60 INFO                filesink
  gstfilesink.c:301:gst_file_sink_set_location: filename :
  /some/path/output.avi

0:00:00.116345776  3331
  0x7f92b4002f60 INFO                filesink
  gstfilesink.c:302:gst_file_sink_set_location: uri      :
  file:///some/path/output.avi

0:00:00.118291875  3331
  0x7f92b4002f60 DEBUG               filesink
  gstfilesink.c:523:gst_file_sink_do_seek: Seeking to offset
  0 using fseeko

0:00:00.118320893  3331 0x7f92b4002f60 DEBUG           filesink
  gstfilesink.c:423:gst_file_sink_open_file: opened
  file /some/path/output.avi, seekable 1

Does anyone know what could be causing this?

Body:
You could first go with easy option that is use gst_parse_launch(), instead you creating elements and connecting the pads.

Coming to your issue where it freezes, the linking of elements is not correct
it needs to be following:

 // Link elements
gst_element_link_many(src, filter, convert, tee, NULL);

/* Manually link the Tee, which has "Request" pads */
  GstPad *tee_display_pad = gst_element_get_request_pad (tee, "src_%u");
  GstPad *queue_display_pad = gst_element_get_static_pad (displayQueue, "sink");

  GstPad *tee_video_pad = gst_element_get_request_pad (tee, "src_%u");
  GstPad *queue_video_pad = gst_element_get_static_pad (recordQueue, "sink");

  if (gst_pad_link (tee_display_pad, queue_display_pad) != GST_PAD_LINK_OK ||
      gst_pad_link (tee_video_pad, queue_video_pad) != GST_PAD_LINK_OK)
    return -1;

  gst_object_unref (tee_display_pad);
  gst_object_unref (queue_display_pad);
  gst_object_unref (tee_video_pad);
  gst_object_unref (queue_video_pad);

  gst_element_link_many(displayQueue, upload, sink, NULL);

gst_element_link_many(recordQueue, encode, mux, filesink, NULL);


问:
Register new constraint validator for standard bean validation annotation
I'm wondering whether it's possible to register new constraint validator of some custom type to a annotation defined by Bean Validation specification.
For example, let's image I have a class that accumulates several int values

```<code>public class IntContainer
{
  private int value1;
  private int value2;

  public int getValue1()
  {
    return value1;
  }

  public void setValue1(final int value1)
  {
    this.value1 = value1;
  }

  public int getValue2()
  {
    return value2;
  }

  public void setValue2(final int value2)
  {
    this.value2 = value2;
  }
}
</code>```

I would like to register a custom constraint validator to support the @Positive annotation for this type (instead of created a custom annotation).

```<code>public class PositiveIntContainerValidator implements ConstraintValidator<Positive, IntContainer>
{
  @Override
  public boolean isValid(final IntContainer value, final ConstraintValidatorContext context)
  {
    //TODO: do some validation here based on IntContainer state
    return false;
  }
}
</code>```

So that later I can use this:

```<code>@Positive
private IntContainer valueContainer;
</code>```

答:
It is not possible to use the @Positive annotation on your IntContainer class, as the validator does not support this data type.

Supported types for the @Positive annotation are:

BigDecimal

BigInteger

byte, short, int, long, float, double and their respective wrappers

See Annotation Type Positive.

You have two options here, you could write your own custom validator for IntContainer, or you could get the IntContainer from an entity that has it has a member variable and then validate it. Such as:

Bean:
    public class IntContainer {

```<code>@Positive
private int value1;
@Positive
private int value2;

public IntContainer() {

}

public IntContainer(int value1, int value2) {
    this.value1 = value1;
    this.value2 = value2;
}

public int getValue1() {
    return value1;
}

public void setValue1(final int value1) {
    this.value1 = value1;
}

public int getValue2() {
    return value2;
}

public void setValue2(final int value2) {
    this.value2 = value2;
}

}
</code>```

Rest:

```<code>@POST
public Response postTest(TestRest testRest) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<IntContainer>> constraintViolations = validator.validate(testRest.getIntContainer());
    System.out.println(constraintViolations.size());

    return Response.status(Response.Status.OK).entity(constraintViolations.size()).build();
}
</code>```

Body:
I'm wondering whether it's possible to register new constraint validator of some custom type to a annotation defined by Bean Validation specification.
For example, let's image I have a class that accumulates several int values

public class IntContainer
{
  private int value1;
  private int value2;

  public int getValue1()
  {
    return value1;
  }

  public void setValue1(final int value1)
  {
    this.value1 = value1;
  }

  public int getValue2()
  {
    return value2;
  }

  public void setValue2(final int value2)
  {
    this.value2 = value2;
  }
}

I would like to register a custom constraint validator to support the @Positive annotation for this type (instead of created a custom annotation).

public class PositiveIntContainerValidator implements ConstraintValidator<Positive, IntContainer>
{
  @Override
  public boolean isValid(final IntContainer value, final ConstraintValidatorContext context)
  {
    //TODO: do some validation here based on IntContainer state
    return false;
  }
}

So that later I can use this:

@Positive
private IntContainer valueContainer;

Body:
It is not possible to use the @Positive annotation on your IntContainer class, as the validator does not support this data type.

Supported types for the @Positive annotation are:

BigDecimal

BigInteger

byte, short, int, long, float, double and their respective wrappers

See Annotation Type Positive.

You have two options here, you could write your own custom validator for IntContainer, or you could get the IntContainer from an entity that has it has a member variable and then validate it. Such as:

Bean:
    public class IntContainer {

@Positive
private int value1;
@Positive
private int value2;

public IntContainer() {

}

public IntContainer(int value1, int value2) {
    this.value1 = value1;
    this.value2 = value2;
}

public int getValue1() {
    return value1;
}

public void setValue1(final int value1) {
    this.value1 = value1;
}

public int getValue2() {
    return value2;
}

public void setValue2(final int value2) {
    this.value2 = value2;
}

}

Rest:

@POST
public Response postTest(TestRest testRest) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<IntContainer>> constraintViolations = validator.validate(testRest.getIntContainer());
    System.out.println(constraintViolations.size());

    return Response.status(Response.Status.OK).entity(constraintViolations.size()).build();
}


问:
Http Interceptor Angular 4
I'm getting an error in my Typescript file that uses the Angular 4 framework. intelliJ IDE is not able to recognize the any datatype for HttpRequest.

Here is the code:

```<code>import {Component, Injectable, OnInit} from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import {ActivatedRoute, Router} from "@angular/router";
import {
  HttpClient, HttpErrorResponse, HttpEvent, HttpHandler, HttpHeaders, HttpRequest,
  HttpResponse, HttpInterceptor, HttpEventType} from "@angular/common/http";
import * as $ from "jquery";

@Injectable()
export class Service {

public getNames() {

   intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
       if (request.responseType == 'json') {
       request = request.clone({ responseType: 'text' });

       return next.handle(req).map(response => {
         if (response instanceof HttpResponse) {
         response = response.clone<any>({ body: JSON.parse(response.body) });
      }

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

From the following GitHub website: https://github.com/angular/angular/issues/18396#issuecomment-349403045

I've checked that I'm importing '@angular/common/http' and that my Typescript version is up-to-date (I have version 2.6.2).

Does anyone know how to fix this?
Any suggestions would be greatly appreciated.

Thank you.

答:
The right way to use interceptors is this:

```<code>import {
  Injectable,
} from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import {
  Observable
} from 'rxjs/Observable';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  constructor() {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (request.responseType == 'json') {
      request = request.clone({ responseType: 'text' });
    }

    return next.handle(request).map(// your code here)
  }
}
</code>```

find the difference in your code.

Title: Http Interceptor Angular 4

Body:
I'm getting an error in my Typescript file that uses the Angular 4 framework. intelliJ IDE is not able to recognize the any datatype for HttpRequest.

Here is the code:

import {Component, Injectable, OnInit} from '@angular/core';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import {ActivatedRoute, Router} from "@angular/router";
import {
  HttpClient, HttpErrorResponse, HttpEvent, HttpHandler, HttpHeaders, HttpRequest,
  HttpResponse, HttpInterceptor, HttpEventType} from "@angular/common/http";
import * as $ from "jquery";

@Injectable()
export class Service {

public getNames() {

   intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
       if (request.responseType == 'json') {
       request = request.clone({ responseType: 'text' });

       return next.handle(req).map(response => {
         if (response instanceof HttpResponse) {
         response = response.clone<any>({ body: JSON.parse(response.body) });
      }

      return response;
    });
  }
}

From the following GitHub website: https://github.com/angular/angular/issues/18396#issuecomment-349403045

I've checked that I'm importing '@angular/common/http' and that my Typescript version is up-to-date (I have version 2.6.2).

Does anyone know how to fix this?
Any suggestions would be greatly appreciated.

Thank you.

Body:
The right way to use interceptors is this:

import {
  Injectable,
} from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import {
  Observable
} from 'rxjs/Observable';

@Injectable()
export class MyInterceptor implements HttpInterceptor {
  constructor() {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (request.responseType == 'json') {
      request = request.clone({ responseType: 'text' });
    }

    return next.handle(request).map(// your code here)
  }
}

find the difference in your code.


问:
Strong Validation in WPF
I have a databound TextBox in my application like so: (The type of Height is decimal?)

    <TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged,
                            ValidatesOnExceptions=True,
                            Converter={StaticResource NullConverter}}" />
```
<pre class="lang-cs prettyprint-override"><code>    public class NullableConverter : IValueConverter {
        public object Convert(object o, Type type, object parameter, CultureInfo culture) {
            return o;
        }

        public object ConvertBack(object o, Type type, object parameter, CultureInfo culture) {
            if (o as string == null || (o as string).Trim() == string.Empty)
                return null;
            return o;
        }
    }
</code>```

Configured this way, any non-empty strings which cannot be converted to decimal result in a validation error which will immediately highlight the textbox. However, the TextBox can still lose focus and remain in an invalid state. What I would like to do is either:

Not allow the TextBox to lose focus until it contains a valid value.

Revert the value in the TextBox to the last valid value.

What is the best way to do this?

Update:

I've found a way to do #2. I don't love it, but it works:

```<code>private void TextBox_LostKeyboardFocus(object sender, RoutedEventArgs e) {
    var box = sender as TextBox;
    var binding = box.GetBindingExpression(TextBox.TextProperty);
    if (binding.HasError)
        binding.UpdateTarget();
}
</code>```

Does anyone know how to do this better? (Or do #1.)

答:
You can force the keyboard focus to stay on the TextBox by handling the PreviewLostKeyBoardFocus event like this:

     <TextBox PreviewLostKeyboardFocus="TextBox_PreviewLostKeyboardFocus" />
```
<pre class="lang-cs prettyprint-override"><code>     private void TextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {
         e.Handled = true;
     }
</code>```

OwnerDisplayName: Joseph Sturtevant

ContentLicense: CC BY-SA 4.0

Title: Strong Validation in WPF

Body:
I have a databound TextBox in my application like so: (The type of Height is decimal?)

    <TextBox Text="{Binding Height, UpdateSourceTrigger=PropertyChanged,
                            ValidatesOnExceptions=True,
                            Converter={StaticResource NullConverter}}" />

    public class NullableConverter : IValueConverter {
        public object Convert(object o, Type type, object parameter, CultureInfo culture) {
            return o;
        }

        public object ConvertBack(object o, Type type, object parameter, CultureInfo culture) {
            if (o as string == null || (o as string).Trim() == string.Empty)
                return null;
            return o;
        }
    }

Configured this way, any non-empty strings which cannot be converted to decimal result in a validation error which will immediately highlight the textbox. However, the TextBox can still lose focus and remain in an invalid state. What I would like to do is either:

Not allow the TextBox to lose focus until it contains a valid value.

Revert the value in the TextBox to the last valid value.

What is the best way to do this?

Update:

I've found a way to do #2. I don't love it, but it works:

private void TextBox_LostKeyboardFocus(object sender, RoutedEventArgs e) {
    var box = sender as TextBox;
    var binding = box.GetBindingExpression(TextBox.TextProperty);
    if (binding.HasError)
        binding.UpdateTarget();
}

Does anyone know how to do this better? (Or do #1.)

LastEditorDisplayName: Joseph Sturtevant

Body:
You can force the keyboard focus to stay on the TextBox by handling the PreviewLostKeyBoardFocus event like this:

     <TextBox PreviewLostKeyboardFocus="TextBox_PreviewLostKeyboardFocus" />

     private void TextBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) {
         e.Handled = true;
     }

OwnerDisplayName: David Schmitt


问:
Delegating dynamic object resolution to other instances
I'm currently hosting IronPython in a .NET 2.0 application.

I want to create a class (in C#) whose instances can be "extended" by plugin instances. That means, each member access which is unresolvable on my instance should be forwarded to the appropriate plugin instance providing that member. My object will hold a private container with those plugin instances then.

AFAICS, the way to go there is via deriving from DynamicObject. The first step was easy so far that TryGetMember is called whenever python code uses "unknown" members of my instance. I also could return objects and delegates which could be used from the python code.

But, somehow, I got stuck when trying to use the DLR to perform the "subsearch" on the plugin instance and e. G. return a method or property of the plugin instance in the way IronPython expects it.

Any hints are welcome!

Thanks!

Edit: My original question was not formulated clear enough, sorry. Here some points:

The solution has to run with plain .NET 2.0, no .NET 3.5 or 4.0 allowed.

The plugin list are per instance (that means each instance can have a different - but immutable - list of plugin objects).

The plugin objects should be plain C# objects with all public members (or at least methods and properties) mapped.

Collision detection is not important.

Thanks again.

答:
What it sounds like you want to do is have your plugin instances typed to object or dynamic (versus having them typed to some interface where you effectively pass through the TryGetMember request) and then perform a dynamic binding against another object.  Luckily for you the DLR interop protocol allows for exactly this scenario! It'll require to drop down to the IDynamicMetaObjectProvider layer instead of using DynamicObject but it's actually pretty simple.  I'll show you a simple example using InvokeMember that works end-to-end w/ C# 4.0.  You'll need to go and do the rest of the operations - in particular IronPython will use GetMember instead of InvokeMember.  But that's a straight forward process.

First an explanation of how you do it.  At the IDMOP level the DLR deals with meta objects and languages request operations from meta objects and those meta objects return more meta objects. You can also ask the language to perform it's default binding and most importantly you can provide to it a suggestion of what to do when things go wrong.

Based upon that you can ask the language to try and bind to each one of your plugins and your own object.  Depending on whether you want plugins to have precedence, or your dynamic object, you can perform the binding to yourself last.  This sample demonstrates both techniques based upon the member names.

So without further delay, here it is:

```<code>using System;
using System.Dynamic;
using System.Linq.Expressions;

namespace ConsoleApplication10 {
    class Program {
        static void Main(string[] args) {
            dynamic dynamicObj = new MyDynamicObject(new TestPlugin());
            dynamicObj.Foo();
            dynamicObj.Bar();
            Console.ReadLine();
        }

    }

    public class TestPlugin {
        public void Foo() {
            Console.WriteLine("TestPlugin Foo");
        }

        public void Bar() {
            Console.WriteLine("TestPlugin Bar");
        }
    }

    class MyDynamicObject : IDynamicMetaObjectProvider {
        internal readonly object[] _plugins;

        public void Foo() {
            Console.WriteLine("MyDynamicObject Foo");
        }

        public void Bar() {
            Console.WriteLine("MyDynamicObject Bar");
        }

        public MyDynamicObject(params object[] plugins) {
            _plugins = plugins;
        }

        class Meta : DynamicMetaObject {
            public Meta(Expression parameter, BindingRestrictions restrictions, MyDynamicObject self)
                : base(parameter, restrictions, self) {
            }

            public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) {
                // get the default binding the language would return if we weren't involved
                // This will either access a property on MyDynamicObject or it will report
                // an error in a language appropriate manner.
                DynamicMetaObject errorSuggestion = binder.FallbackInvokeMember(this, args);

                // run through the plugins and replace our current rule.  Running through
                // the list forward means the last plugin has the highest precedence because
                // it may throw away the previous rules if it succeeds.
                for (int i = 0; i < Value._plugins.Length; i++) {
                    var pluginDo = DynamicMetaObject.Create(Value._plugins[i],
                        Expression.Call(
                            typeof(MyDynamicObjectOps).GetMethod("GetPlugin"),
                            Expression,
                            Expression.Constant(i)
                        )
                    );

                    errorSuggestion = binder.FallbackInvokeMember(pluginDo, args, errorSuggestion);
                }

                // Do we want DynamicMetaObject to have precedence?  If so then we can do
                // one more bind passing what we've produced so far as the rule.  Or if the
                // plugins have precedence we could just return the value.  We'll do that
                // here based upon the member name.

                if (binder.Name == "Foo") {
                    return binder.FallbackInvokeMember(this, args, errorSuggestion);
                }

                return errorSuggestion;
            }

            public new MyDynamicObject Value {
                get {
                    return (MyDynamicObject)base.Value;
                }
            }
        }

        #region IDynamicMetaObjectProvider Members

        public DynamicMetaObject GetMetaObject(System.Linq.Expressions.Expression parameter) {
            return new Meta(parameter, BindingRestrictions.Empty, this);
        }

        #endregion
    }

    public static class MyDynamicObjectOps {
        public static object GetPlugin(object myDo, int index) {
            return ((MyDynamicObject)myDo)._plugins[index];
        }
    }
}
</code>```

Running this prints:

MyDynamicObject Foo
TestPlugin Bar

Showing that for Foo members we prefer the binding on the actual object, and for Bar members we prefer Bar.  If you add access to a third Baz member it produces C#'s runtime binder exception.  If this was called from IronPython we'd produce an AttributeError to Python programs (a MissingMemberException in .NET) and a JavaScript implement should return undefined to their programs.

So you get not only your extensible plugin system you also easily get the correct behavior in any langauge which consumes your object.

Body:
What it sounds like you want to do is have your plugin instances typed to object or dynamic (versus having them typed to some interface where you effectively pass through the TryGetMember request) and then perform a dynamic binding against another object.  Luckily for you the DLR interop protocol allows for exactly this scenario! It'll require to drop down to the IDynamicMetaObjectProvider layer instead of using DynamicObject but it's actually pretty simple.  I'll show you a simple example using InvokeMember that works end-to-end w/ C# 4.0.  You'll need to go and do the rest of the operations - in particular IronPython will use GetMember instead of InvokeMember.  But that's a straight forward process.

First an explanation of how you do it.  At the IDMOP level the DLR deals with meta objects and languages request operations from meta objects and those meta objects return more meta objects. You can also ask the language to perform it's default binding and most importantly you can provide to it a suggestion of what to do when things go wrong.

Based upon that you can ask the language to try and bind to each one of your plugins and your own object.  Depending on whether you want plugins to have precedence, or your dynamic object, you can perform the binding to yourself last.  This sample demonstrates both techniques based upon the member names.

So without further delay, here it is:

using System;
using System.Dynamic;
using System.Linq.Expressions;

namespace ConsoleApplication10 {
    class Program {
        static void Main(string[] args) {
            dynamic dynamicObj = new MyDynamicObject(new TestPlugin());
            dynamicObj.Foo();
            dynamicObj.Bar();
            Console.ReadLine();
        }

    }

    public class TestPlugin {
        public void Foo() {
            Console.WriteLine("TestPlugin Foo");
        }

        public void Bar() {
            Console.WriteLine("TestPlugin Bar");
        }
    }

    class MyDynamicObject : IDynamicMetaObjectProvider {
        internal readonly object[] _plugins;

        public void Foo() {
            Console.WriteLine("MyDynamicObject Foo");
        }

        public void Bar() {
            Console.WriteLine("MyDynamicObject Bar");
        }

        public MyDynamicObject(params object[] plugins) {
            _plugins = plugins;
        }

        class Meta : DynamicMetaObject {
            public Meta(Expression parameter, BindingRestrictions restrictions, MyDynamicObject self)
                : base(parameter, restrictions, self) {
            }

            public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) {
                // get the default binding the language would return if we weren't involved
                // This will either access a property on MyDynamicObject or it will report
                // an error in a language appropriate manner.
                DynamicMetaObject errorSuggestion = binder.FallbackInvokeMember(this, args);

                // run through the plugins and replace our current rule.  Running through
                // the list forward means the last plugin has the highest precedence because
                // it may throw away the previous rules if it succeeds.
                for (int i = 0; i < Value._plugins.Length; i++) {
                    var pluginDo = DynamicMetaObject.Create(Value._plugins[i],
                        Expression.Call(
                            typeof(MyDynamicObjectOps).GetMethod("GetPlugin"),
                            Expression,
                            Expression.Constant(i)
                        )
                    );

                    errorSuggestion = binder.FallbackInvokeMember(pluginDo, args, errorSuggestion);
                }

                // Do we want DynamicMetaObject to have precedence?  If so then we can do
                // one more bind passing what we've produced so far as the rule.  Or if the
                // plugins have precedence we could just return the value.  We'll do that
                // here based upon the member name.

                if (binder.Name == "Foo") {
                    return binder.FallbackInvokeMember(this, args, errorSuggestion);
                }

                return errorSuggestion;
            }

            public new MyDynamicObject Value {
                get {
                    return (MyDynamicObject)base.Value;
                }
            }
        }

        #region IDynamicMetaObjectProvider Members

        public DynamicMetaObject GetMetaObject(System.Linq.Expressions.Expression parameter) {
            return new Meta(parameter, BindingRestrictions.Empty, this);
        }

        #endregion
    }

    public static class MyDynamicObjectOps {
        public static object GetPlugin(object myDo, int index) {
            return ((MyDynamicObject)myDo)._plugins[index];
        }
    }
}

Running this prints:

MyDynamicObject Foo
TestPlugin Bar

Showing that for Foo members we prefer the binding on the actual object, and for Bar members we prefer Bar.  If you add access to a third Baz member it produces C#'s runtime binder exception.  If this was called from IronPython we'd produce an AttributeError to Python programs (a MissingMemberException in .NET) and a JavaScript implement should return undefined to their programs.

So you get not only your extensible plugin system you also easily get the correct behavior in any langauge which consumes your object.


问:
PHP Script to convert .DBF files to .MYSQL
Just wondering if anyone can point me in the direction of some tips / a script that will help me create an mysql from an original dbf File, using PHP.

thanks before.

答:
UPDATED:
in the event that your did not compile PHP with dbase library you could get the following error:

```<code>Call to undefined function dbase_open()
</code>```

in which case (centos)

```<code>yum install php-dbase
</code>```

Here is the updated code for $mysqli

<?php

$mysqli = new mysqli("localhost", "DBusername", "DBpassword", "tableName");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$tbl = "yourTableName";
$db = 'YourDBName';

// Path to dbase file
$db_path = "/path/dbaseFileName.dbf";

// Open dbase file
$dbh = dbase_open($db_path, 0)
or die("Error! Could not open dbase database file '$db_path'.");

// Get column information
$column_info = dbase_get_header_info($dbh);

$line = array();

foreach($column_info as $col) {
 switch($col['type']){

  case 'character':
   $line[]= "`$col[name]` VARCHAR( $col[length] )";
   break;

  case 'number':
   $line[]= "`$col[name]` FLOAT";
   break;

  case 'boolean':
   $line[]= "`$col[name]` BOOL";
   break;

  case 'date':
   $line[]= "`$col[name]` DATE";
   break;

  case 'memo':
   $line[]= "`$col[name]` TEXT";
   break;
 }
}

$str = implode(",",$line);
$sql = "CREATE TABLE `$tbl` ( $str );";

//mysql_select_db($db,$conn);

//mysql_query($sql,$conn);
$mysqli->query($sql);
set_time_limit(0); // I added unlimited time limit here, because the records I imported were in the hundreds of thousands.

// This is part 2 of the code

import_dbf($db, $tbl, $db_path, $mysqli);

function import_dbf($db, $table, $dbf_file,$mysqli){
 //global $conn;
 global $mysqli;
 if (!$dbf = dbase_open ($dbf_file, 0)){ die("Could not open $dbf_file for import."); }
 $num_rec = dbase_numrecords($dbf);
 $num_fields = dbase_numfields($dbf);
 $fields = array();

 for ($i=1; $i<=$num_rec; $i++){
 $row = @dbase_get_record_with_names($dbf,$i);
 $q = "insert into $db.$table values (";
 foreach ($row as $key => $val){
 if ($key == 'deleted'){ continue; }
 $q .= "'" . addslashes(trim($val)) . "',"; // Code modified to trim out whitespaces
 }

 if (isset($extra_col_val)){ $q .= "'$extra_col_val',"; }
 $q = substr($q, 0, -1);
 $q .= ')';
 //if the query failed - go ahead and print a bunch of debug info
 // if (!$result = mysql_query($q, $conn)){
 if (!$result = $mysqli->query($q)){
  print (mysql_error() . " SQL: $q\n");
  print (substr_count($q, ',') + 1) . " Fields total.";

  $problem_q = explode(',', $q);
  $q1 = "desc $db.$table";
  //$result1 = mysql_query($q1, $conn);
  $result1 = $mysqli->query($q1);
  $columns = array();

  $i = 1;

  while ($row1 = $result1->fetch_assoc()){
   $columns[$i] = $row1['Field'];
   $i++;
  }

  $i = 1;
  foreach ($problem_q as $pq){
   print "$i column: {$columns[$i]} data: $pq\n";
   $i++;
  }
  die();
 }
}
}

$mysqli->close();

?>```

Body:
UPDATED:
in the event that your did not compile PHP with dbase library you could get the following error:

Call to undefined function dbase_open()

in which case (centos)

yum install php-dbase

Here is the updated code for $mysqli

<?php

$mysqli = new mysqli("localhost", "DBusername", "DBpassword", "tableName");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}

$tbl = "yourTableName";
$db = 'YourDBName';

// Path to dbase file
$db_path = "/path/dbaseFileName.dbf";

// Open dbase file
$dbh = dbase_open($db_path, 0)
or die("Error! Could not open dbase database file '$db_path'.");

// Get column information
$column_info = dbase_get_header_info($dbh);

$line = array();

foreach($column_info as $col) {
 switch($col['type']){

  case 'character':
   $line[]= "`$col[name]` VARCHAR( $col[length] )";
   break;

  case 'number':
   $line[]= "`$col[name]` FLOAT";
   break;

  case 'boolean':
   $line[]= "`$col[name]` BOOL";
   break;

  case 'date':
   $line[]= "`$col[name]` DATE";
   break;

  case 'memo':
   $line[]= "`$col[name]` TEXT";
   break;
 }
}

$str = implode(",",$line);
$sql = "CREATE TABLE `$tbl` ( $str );";

//mysql_select_db($db,$conn);

//mysql_query($sql,$conn);
$mysqli->query($sql);
set_time_limit(0); // I added unlimited time limit here, because the records I imported were in the hundreds of thousands.

// This is part 2 of the code

import_dbf($db, $tbl, $db_path, $mysqli);

function import_dbf($db, $table, $dbf_file,$mysqli){
 //global $conn;
 global $mysqli;
 if (!$dbf = dbase_open ($dbf_file, 0)){ die("Could not open $dbf_file for import."); }
 $num_rec = dbase_numrecords($dbf);
 $num_fields = dbase_numfields($dbf);
 $fields = array();

 for ($i=1; $i<=$num_rec; $i++){
 $row = @dbase_get_record_with_names($dbf,$i);
 $q = "insert into $db.$table values (";
 foreach ($row as $key => $val){
 if ($key == 'deleted'){ continue; }
 $q .= "'" . addslashes(trim($val)) . "',"; // Code modified to trim out whitespaces
 }

 if (isset($extra_col_val)){ $q .= "'$extra_col_val',"; }
 $q = substr($q, 0, -1);
 $q .= ')';
 //if the query failed - go ahead and print a bunch of debug info
 // if (!$result = mysql_query($q, $conn)){
 if (!$result = $mysqli->query($q)){
  print (mysql_error() . " SQL: $q\n");
  print (substr_count($q, ',') + 1) . " Fields total.";

  $problem_q = explode(',', $q);
  $q1 = "desc $db.$table";
  //$result1 = mysql_query($q1, $conn);
  $result1 = $mysqli->query($q1);
  $columns = array();

  $i = 1;

  while ($row1 = $result1->fetch_assoc()){
   $columns[$i] = $row1['Field'];
   $i++;
  }

  $i = 1;
  foreach ($problem_q as $pq){
   print "$i column: {$columns[$i]} data: $pq\n";
   $i++;
  }
  die();
 }
}
}

$mysqli->close();

?>


问:
not generic Error in Java HashMap
I am getting the below error for HashMap in the Java code.

Error - "The type HashMap is not generic; it cannot be parameterized with arguments <>"

```<code>package com.example.map;

import java.util.Map;
import java.util.HashMap;

public class HashMap {

    public static void main(String[] args) {
        // compilation error here                vvvvvvv
        Map<Integer, String> mapHttpErrors = new HashMap<>();

        mapHttpErrors.put(200, "OK");
        mapHttpErrors.put(303, "See Other");
        mapHttpErrors.put(404, "Not Found");
        mapHttpErrors.put(500, "Internal Server Error");

        System.out.println(mapHttpErrors);

    }

}
</code>```

答:
As the error is telling you, your HashMap class isn't generic, so your code makes no sense.

You should not make classes with the same names as built-in classes.

Title: not generic Error in Java HashMap

Body:
I am getting the below error for HashMap in the Java code.

Error - "The type HashMap is not generic; it cannot be parameterized with arguments <>"

package com.example.map;

import java.util.Map;
import java.util.HashMap;

public class HashMap {

    public static void main(String[] args) {
        // compilation error here                vvvvvvv
        Map<Integer, String> mapHttpErrors = new HashMap<>();

        mapHttpErrors.put(200, "OK");
        mapHttpErrors.put(303, "See Other");
        mapHttpErrors.put(404, "Not Found");
        mapHttpErrors.put(500, "Internal Server Error");

        System.out.println(mapHttpErrors);

    }

}


问:
calculate highest salary department in SQL

Question: sql query to get:

The names of the departments with the highest average salary of their employees.

答:
If you using t-sql (MS-SQL)</p>

```<code>SELECT AVG(salary) AS 'avgSalary' , dept
 FROM emp
GROUP BY dept
Order BY avgSalary DESC
</code>```

Body:
If you using t-sql (MS-SQL)

SELECT AVG(salary) AS 'avgSalary' , dept
 FROM emp
GROUP BY dept
Order BY avgSalary DESC


问:
Cloud Explorer fails with "Unable to retrieve child resources"
How to fix this bug?

Open Cloud Explorer (logged in)

Open "Files" folder for some Azure Web App (former Azure Website)

Result:

Cloud Explorer has encountered an unexpected error: Unable to retrieve
  child resources.

Details: 'Newtonsoft.Json.Linq.JObject' does not contain a definition
  for 'requestNamespace'

I'm using:

Microsoft Visual Studio Community 2015 Version 14.0.25431.01 Update 3

Azure App Service Tools v2.9.6   14.0.21111.0

Common Azure Tools   1.8

Microsoft Azure Tools for Microsoft Visual Studio 2015 - v2.9.41104.6

答:
I had this problem and it was a permissions issue, mine was with a Cosmos Document DB database node.

I had my DevOps guy add me as a contributor to the IAM Azure role and it started working for me.   So check all the permissions, and it is the cloud so sometimes you have to give it time to propagate the changes too.


问:
"No suitable driver found for jdbc:microsoft:sqlserver"
I am running Ubuntu 16.04 and using Oracle Java 9.

```<code>$ java --version
java 9.0.1
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)
</code>```

I have installed SQL Server jdbc driver (sqljdbc_6.2.2.0_enu.tar.gz in https://www.microsoft.com/en-us/download/details.aspx?id=55539)

```<code>$ ls /home/t/program_files/RDBMS/JDBC/mssqlserverjdbc_6.0/enu/jre*
/home/t/program_files/RDBMS/JDBC/mssqlserverjdbc_6.0/enu/jre7:
sqljdbc41.jar

/home/t/program_files/RDBMS/JDBC/mssqlserverjdbc_6.0/enu/jre8:
sqljdbc42.jar
</code>```

I wrote some simple   code to test using the driver :

```<code>// JDBC driver name and database URL
String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
// static final String DB_URL = "jdbc:mysql://localhost/"; // connect to a DBMS
String DB_URL = "jdbc:microsoft:sqlserver://localhost/STUDENTS"; // connect to a specific database in a DBMS
//  Database credentials
String USER = "SA";
String PASS = "password";

//Register JDBC driver
try{
    Class.forName(JDBC_DRIVER);
}catch(Exception e){ //Handle errors for Class.forName
    e.printStackTrace();
}

    //Open a connection
System.out.println("Connecting to database...");

try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); // connect to DBMS, not to a DB
    Statement st = conn.createStatement()){

}catch(SQLException se){ //Handle errors for JDBC
    se.printStackTrace();
}
</code>```

Compilation is fine:

```<code>$ javac BasicOperations.java
</code>```

Running isn't.

```<code>$ java -cp .:/home/t/program_files/RDBMS/JDBC/mssqlserverjdbc_6.0/enu/jre8/sqljdbc42.jar BasicOperations

Connecting to database...
java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver://localhost/STUDENTS
        at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:703)
        at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:229)
        at BasicOperations.main(BasicOperations.java:46)
</code>```

How shall I solve the problem?

Is it because I am using Java 9 and SQL Server jdbc driver has drivers for jre7 and jre8?

Thanks.

答:
Looks like format of database connection URL is incorrect.
Please check https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url

To be specific: microsoft: should be removed from URL. This is the format:

```<code>jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]
</code>```

Body:
I am running Ubuntu 16.04 and using Oracle Java 9.

$ java --version
java 9.0.1
Java(TM) SE Runtime Environment (build 9.0.1+11)
Java HotSpot(TM) 64-Bit Server VM (build 9.0.1+11, mixed mode)

I have installed SQL Server jdbc driver (sqljdbc_6.2.2.0_enu.tar.gz in https://www.microsoft.com/en-us/download/details.aspx?id=55539)

$ ls /home/t/program_files/RDBMS/JDBC/mssqlserverjdbc_6.0/enu/jre*
/home/t/program_files/RDBMS/JDBC/mssqlserverjdbc_6.0/enu/jre7:
sqljdbc41.jar

/home/t/program_files/RDBMS/JDBC/mssqlserverjdbc_6.0/enu/jre8:
sqljdbc42.jar

I wrote some simple   code to test using the driver :

// JDBC driver name and database URL
String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
// static final String DB_URL = "jdbc:mysql://localhost/"; // connect to a DBMS
String DB_URL = "jdbc:microsoft:sqlserver://localhost/STUDENTS"; // connect to a specific database in a DBMS
//  Database credentials
String USER = "SA";
String PASS = "password";

//Register JDBC driver
try{
    Class.forName(JDBC_DRIVER);
}catch(Exception e){ //Handle errors for Class.forName
    e.printStackTrace();
}

    //Open a connection
System.out.println("Connecting to database...");

try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); // connect to DBMS, not to a DB
    Statement st = conn.createStatement()){

}catch(SQLException se){ //Handle errors for JDBC
    se.printStackTrace();
}

Compilation is fine:

$ javac BasicOperations.java

Running isn't.

$ java -cp .:/home/t/program_files/RDBMS/JDBC/mssqlserverjdbc_6.0/enu/jre8/sqljdbc42.jar BasicOperations

Connecting to database...
java.sql.SQLException: No suitable driver found for jdbc:microsoft:sqlserver://localhost/STUDENTS
        at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:703)
        at java.sql/java.sql.DriverManager.getConnection(DriverManager.java:229)
        at BasicOperations.main(BasicOperations.java:46)

How shall I solve the problem?

Is it because I am using Java 9 and SQL Server jdbc driver has drivers for jre7 and jre8?

Thanks.

Body:
Looks like format of database connection URL is incorrect.
Please check https://learn.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url

To be specific: microsoft: should be removed from URL. This is the format:

jdbc:sqlserver://[serverName[\instanceName][:portNumber]][;property=value[;property=value]]


答:
In the following line HashMap refers to the public class you created:

```<code>Map<Integer, String> mapHttpErrors = new **HashMap**<>();
</code>```

Naming your class with exact the same name as classes from official Java API is often a very bad idea. But if you're sure that instead of that, you still want to keep the old name, here is the way you can use the HashMap from java.util package:

```<code>Map<Integer, String> mapHttpErrors = new java.util.HashMap<>();
</code>```

But again, remember that naming your classes as you did in your program is rather a bad idea.

Title: not generic Error in Java HashMap

Body:
In the following line HashMap refers to the public class you created:

Map<Integer, String> mapHttpErrors = new **HashMap**<>();

Naming your class with exact the same name as classes from official Java API is often a very bad idea. But if you're sure that instead of that, you still want to keep the old name, here is the way you can use the HashMap from java.util package:

Map<Integer, String> mapHttpErrors = new java.util.HashMap<>();

But again, remember that naming your classes as you did in your program is rather a bad idea.


问:
Make rotation stop realisticly in Swift
I have a square = SKSpriteNode() that turns that rotates 360° when you touch it. I want to stop the spinning when you touch it again.
Now I would make square rotate through the SKAction.rotate but how can I stop the spinning realisticly meaning that I want the sprite to spin slower and slower until it stands still.

答: Did you try and ease out curve for the timingMode?  If you don't like this effect you can provide your own custom timingFunction.  There are several websites where you can explore animation curves online.  I like this one.</p>

Title: Make rotation stop realisticly in Swift


答:
you never test if you see the reponse from echo - hence you don't alert the response from php at all.

To see what your php script returns you have to alert (or log, or do something usefull with) the passed in parameter to the success callback:

```<code>....
success: function (response) {
     alert(response);
     console.log(response);
},
....
</code>```

Anyway you should make sure to not send additional data (like unneeded html in your case) back to ajax, but only the value/json. So in your case an exit; after echo would help.

Also follow @Mohammed-Yousef's instructions for the other issues!!

Title: Ajax submit doesn't work (can't read $_POST in php)

Body:
I am trying to submit my form using Ajax. When the button is clicked the hit() function gets called and passes the contents of the textbox back to test.php

$_POST seems to be empty, since I get the alert from ajax (form was submitted) but I don't get to see the echo (echo $_POST['textbox'])

test.php

<?php
    echo "test";
    if($_POST)
    {
        echo $_POST['textbox'];
    }
?>

            <form action="index.php" method="post" align="center" id="form" name="form">

                <input type="text" class="form-control" id="input" name="input" oninput="check();">
                <input type="button" class="form-control" id="send" name="send" value="Send" onclick="hit();">
            </form>

test2.js

function hit() {
        var inputText = $("#input").val();
        var inputTextString = "textbox=" + inputText;
        $.ajax({
            type: 'post',
            url: 'test.php',
            data: inputTextString,
            success: function () {
              alert('form was submitted');
            }
        });

}

Body:
you never test if you see the reponse from echo - hence you don't alert the response from php at all.

To see what your php script returns you have to alert (or log, or do something usefull with) the passed in parameter to the success callback:

....
success: function (response) {
     alert(response);
     console.log(response);
},
....

Anyway you should make sure to not send additional data (like unneeded html in your case) back to ajax, but only the value/json. So in your case an exit; after echo would help.

Also follow @Mohammed-Yousef's instructions for the other issues!!


问:
create tutorial mode
I have a Qt application and want to show a little tutorial when the user access the application for the first time. Something like this:

How can I do something like this on Qt?

I'm using Qt 5.4 on Windows.

答:
To perform this task we must make the translucent background, we do it by activating the attribute Qt::WA_TranslucentBackground, then we use QPainterPath to draw the rectangle minus the transparent circle.

Then use eventFilter to know some events like when they are displayed, if you change the size or position.

Then a structure is created to store the data, in this case the center of the circle, the radius, the position of the text and the text itself.

Then the next and return buttons are added, and the logic of the page change is handled in the slot.

tutowidget.h

```<code>#ifndef TUTOWIDGET_H
#define TUTOWIDGET_H

#include <QWidget>
class QButtonGroup;

class TutoWidget : public QWidget
{
    Q_OBJECT
    struct Pages{
        QPoint center;
        int radius;
        QPoint  pText;
        QString text;
    };
public:
    TutoWidget(QWidget *parent);
    void addPage(const QPoint &center, int radius, const QPoint &pText, const QString & text);
    bool eventFilter(QObject *watched, QEvent *event);
protected:
    void paintEvent(QPaintEvent *);
private slots:
    void onClicked(int id);
private:
    QWidget *mParent;
    QButtonGroup *group;
    QVector<Pages> pages;
    int currentIndex = -1;
};

#endif // TUTOWIDGET_H
</code>```

tutowidget.cpp

```<code>#include "tutowidget.h"

#include <QVBoxLayout>
#include <QButtonGroup>
#include <QPushButton>
#include <QEvent>
#include <QTimer>
#include <QPainter>

TutoWidget::TutoWidget(QWidget *parent):QWidget(0)
{
    setWindowFlags(Qt::FramelessWindowHint|Qt::Popup);
    setAttribute(Qt::WA_TranslucentBackground, true);
    mParent = parent;
    mParent->installEventFilter(this);

    QVBoxLayout *vlay = new QVBoxLayout(this);
    vlay->addItem(new QSpacerItem(20, 243, QSizePolicy::Minimum, QSizePolicy::Expanding));
    QHBoxLayout *hlay = new QHBoxLayout;
    vlay->addLayout(hlay);
    group = new QButtonGroup(this);
    const QStringList nameBtns{"Return", "Next"};
    for(int i=0; i < nameBtns.length(); i++){
        QPushButton* btn = new QPushButton(nameBtns[i]);
        btn->setFlat(true);
        group->addButton(btn, i);
        hlay->addWidget(btn);
    }
    connect(group, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked),
            this, static_cast<void (TutoWidget::*)(int)>(&TutoWidget::onClicked));
    hlay->addItem(new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum));
    group->button(0)->hide();
}

void TutoWidget::addPage(const QPoint &center, int radius, const QPoint &pText, const QString &text)
{
    pages << Pages{center, radius, pText, text};
    if(currentIndex == -1){
        currentIndex = 0;
        update();
    }
}

bool TutoWidget::eventFilter(QObject *watched, QEvent *event){
    if(watched == mParent){

        switch (event->type()) {
        case QEvent::Show:
            QTimer::singleShot(10,  this, &QWidget::show);
            break;
        case QEvent::Close:
            close();
            break;
        case QEvent::Move:
            move(mParent->mapToGlobal(QPoint(0, 0)));
            break;
        case QEvent::Resize:
            resize(mParent->size());
            break;
        default:
            break;
        }
    }
    return QWidget::eventFilter(watched, event);
}

void TutoWidget::paintEvent(QPaintEvent *){
    QPainter painter(this);
    painter.setPen(Qt::NoPen);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(QColor(100, 100, 100, 200));
    QPainterPath path;
    if(currentIndex != -1){
        QPoint center = pages[currentIndex].center;
        int radius = pages[currentIndex].radius;
        QString text = pages[currentIndex].text;
        QPoint pText = pages[currentIndex].pText;
        path.moveTo(center + radius/2*QPoint(1, 0));
        path.arcTo(QRect(center-radius/2*QPoint(1, 1),radius*QSize(1, 1)), 0, 360);
        path.addText(pText, font(), text);
    }
    path.addRect(rect());
    painter.drawPath(path);
}

void TutoWidget::onClicked(int id)
{
    if(id == 0){
        if(currentIndex > 0)
            currentIndex--;
    }
    else if(id == 1){
        if(currentIndex < pages.count()-1)
            currentIndex++;
    }
    update();
    group->button(0)->setVisible(currentIndex!=0);
    group->button(1)->setVisible(currentIndex!=(pages.count()-1));
}
</code>```

Example:

```<code>tuto = new TutoWidget(this); // this is the widget
tuto->addPage(QPoint(200, 200), 40, QPoint(100, 100), "some text1");
tuto->addPage(QPoint(300, 300), 60, QPoint(200, 100), "some text2");
tuto->addPage(QPoint(100, 200), 100, QPoint(200, 50), "some text3");
tuto->addPage(QPoint(200, 100), 80, QPoint(100, 200), "some text4");
</code>```

The complete example is in the following link

Title: create tutorial mode

Body:
To perform this task we must make the translucent background, we do it by activating the attribute Qt::WA_TranslucentBackground, then we use QPainterPath to draw the rectangle minus the transparent circle.

Then use eventFilter to know some events like when they are displayed, if you change the size or position.

Then a structure is created to store the data, in this case the center of the circle, the radius, the position of the text and the text itself.

Then the next and return buttons are added, and the logic of the page change is handled in the slot.

tutowidget.h

#ifndef TUTOWIDGET_H
#define TUTOWIDGET_H

#include <QWidget>
class QButtonGroup;

class TutoWidget : public QWidget
{
    Q_OBJECT
    struct Pages{
        QPoint center;
        int radius;
        QPoint  pText;
        QString text;
    };
public:
    TutoWidget(QWidget *parent);
    void addPage(const QPoint &center, int radius, const QPoint &pText, const QString & text);
    bool eventFilter(QObject *watched, QEvent *event);
protected:
    void paintEvent(QPaintEvent *);
private slots:
    void onClicked(int id);
private:
    QWidget *mParent;
    QButtonGroup *group;
    QVector<Pages> pages;
    int currentIndex = -1;
};

#endif // TUTOWIDGET_H

tutowidget.cpp

#include "tutowidget.h"

#include <QVBoxLayout>
#include <QButtonGroup>
#include <QPushButton>
#include <QEvent>
#include <QTimer>
#include <QPainter>

TutoWidget::TutoWidget(QWidget *parent):QWidget(0)
{
    setWindowFlags(Qt::FramelessWindowHint|Qt::Popup);
    setAttribute(Qt::WA_TranslucentBackground, true);
    mParent = parent;
    mParent->installEventFilter(this);

    QVBoxLayout *vlay = new QVBoxLayout(this);
    vlay->addItem(new QSpacerItem(20, 243, QSizePolicy::Minimum, QSizePolicy::Expanding));
    QHBoxLayout *hlay = new QHBoxLayout;
    vlay->addLayout(hlay);
    group = new QButtonGroup(this);
    const QStringList nameBtns{"Return", "Next"};
    for(int i=0; i < nameBtns.length(); i++){
        QPushButton* btn = new QPushButton(nameBtns[i]);
        btn->setFlat(true);
        group->addButton(btn, i);
        hlay->addWidget(btn);
    }
    connect(group, static_cast<void (QButtonGroup::*)(int)>(&QButtonGroup::buttonClicked),
            this, static_cast<void (TutoWidget::*)(int)>(&TutoWidget::onClicked));
    hlay->addItem(new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum));
    group->button(0)->hide();
}

void TutoWidget::addPage(const QPoint &center, int radius, const QPoint &pText, const QString &text)
{
    pages << Pages{center, radius, pText, text};
    if(currentIndex == -1){
        currentIndex = 0;
        update();
    }
}

bool TutoWidget::eventFilter(QObject *watched, QEvent *event){
    if(watched == mParent){

        switch (event->type()) {
        case QEvent::Show:
            QTimer::singleShot(10,  this, &QWidget::show);
            break;
        case QEvent::Close:
            close();
            break;
        case QEvent::Move:
            move(mParent->mapToGlobal(QPoint(0, 0)));
            break;
        case QEvent::Resize:
            resize(mParent->size());
            break;
        default:
            break;
        }
    }
    return QWidget::eventFilter(watched, event);
}

void TutoWidget::paintEvent(QPaintEvent *){
    QPainter painter(this);
    painter.setPen(Qt::NoPen);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setBrush(QColor(100, 100, 100, 200));
    QPainterPath path;
    if(currentIndex != -1){
        QPoint center = pages[currentIndex].center;
        int radius = pages[currentIndex].radius;
        QString text = pages[currentIndex].text;
        QPoint pText = pages[currentIndex].pText;
        path.moveTo(center + radius/2*QPoint(1, 0));
        path.arcTo(QRect(center-radius/2*QPoint(1, 1),radius*QSize(1, 1)), 0, 360);
        path.addText(pText, font(), text);
    }
    path.addRect(rect());
    painter.drawPath(path);
}

void TutoWidget::onClicked(int id)
{
    if(id == 0){
        if(currentIndex > 0)
            currentIndex--;
    }
    else if(id == 1){
        if(currentIndex < pages.count()-1)
            currentIndex++;
    }
    update();
    group->button(0)->setVisible(currentIndex!=0);
    group->button(1)->setVisible(currentIndex!=(pages.count()-1));
}

Example:

tuto = new TutoWidget(this); // this is the widget
tuto->addPage(QPoint(200, 200), 40, QPoint(100, 100), "some text1");
tuto->addPage(QPoint(300, 300), 60, QPoint(200, 100), "some text2");
tuto->addPage(QPoint(100, 200), 100, QPoint(200, 50), "some text3");
tuto->addPage(QPoint(200, 100), 80, QPoint(100, 200), "some text4");

The complete example is in the following link